[wgpu-core] Ray tracing pipelines (#10144)

Co-authored-by: Connor Fitzgerald <connorwadefitzgerald@gmail.com>
This commit is contained in:
VecvecandConnor Fitzgerald authored and GitHub committed 2026-11-05 19:20:32 +00:00
1 parent 545f277225
commit 9e744954f7
57 files changed
+4106 -49

No files matched your search

@@ -292,6 +292,7 @@ impl crate::framework::Example for Example {
)),
0,
0xff,
0,
));
let mut encoder =
@@ -343,6 +343,7 @@ impl crate::framework::Example for Example {
)),
0,
0xff,
0,
));
}
}
@@ -307,7 +307,7 @@ impl crate::framework::Example for Example {
.try_into()
.unwrap();
*instance = Some(wgpu::TlasInstance::new(&self.blas, transform, 0, 0xff));
*instance = Some(wgpu::TlasInstance::new(&self.blas, transform, 0, 0xff, 0));
}
}
}
@@ -334,6 +334,7 @@ impl crate::framework::Example for Example {
)),
0,
0xff,
0,
));
}
}
+1
View File
@@ -487,6 +487,7 @@ impl crate::framework::Example for Example {
transform,
blas_index as u32,
0xff,
0,
));
}
}
+1
View File
@@ -223,6 +223,7 @@ impl crate::framework::Example for Example {
[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
0,
0xFF,
0,
));
let mut encoder =
@@ -165,6 +165,7 @@ impl crate::framework::Example for Example {
.unwrap(),
0,
0xff,
0,
));
tlas[1] = Some(TlasInstance::new(
@@ -180,6 +181,7 @@ impl crate::framework::Example for Example {
.unwrap(),
0,
0xff,
0,
));
tlas[2] = Some(TlasInstance::new(
@@ -195,6 +197,7 @@ impl crate::framework::Example for Example {
.unwrap(),
0,
0xff,
0,
));
let uniforms = {
@@ -191,6 +191,13 @@ impl DeviceInterface for CustomDevice {
wgpu::custom::DispatchComputePipeline::custom(CustomComputePipeline(module.0.clone()))
}
fn create_ray_tracing_pipeline(
&self,
_desc: &wgpu::RayTracingPipelineDescriptor<'_>,
) -> wgpu::custom::DispatchRayTracingPipeline {
unimplemented!()
}
unsafe fn create_pipeline_cache(
&self,
_desc: &wgpu::PipelineCacheDescriptor<'_>,
+8
View File
@@ -135,6 +135,11 @@ pub fn compact(module: &mut crate::Module, keep_unused: KeepUnused) {
if let Some(task_payload) = e.task_payload {
module_tracer.global_variables_used.insert(task_payload);
}
if let Some(incoming_ray_payload) = e.incoming_ray_payload {
module_tracer
.global_variables_used
.insert(incoming_ray_payload);
}
if let Some(ref mesh_info) = e.mesh_info {
module_tracer
.global_variables_used
@@ -381,6 +386,9 @@ pub fn compact(module: &mut crate::Module, keep_unused: KeepUnused) {
if let Some(ref mut task_payload) = entry.task_payload {
module_map.globals.adjust(task_payload);
}
if let Some(ref mut incoming_ray_payload) = entry.incoming_ray_payload {
module_map.globals.adjust(incoming_ray_payload);
}
if let Some(ref mut mesh_info) = entry.mesh_info {
module_map.globals.adjust(&mut mesh_info.output_variable);
module_map.types.adjust(&mut mesh_info.vertex_output_type);
+141
View File
@@ -54,6 +54,10 @@ pub struct Player {
wgc::id::PointerId<wgc::id::markers::ComputePipeline>,
Arc<wgc::pipeline::ComputePipeline>,
>,
ray_tracing_pipelines: HashMap<
wgc::id::PointerId<wgc::id::markers::RayTracingPipeline>,
Arc<wgc::ray_tracing_pipeline::RayTracingPipeline>,
>,
pipeline_caches: HashMap<
wgc::id::PointerId<wgc::id::markers::PipelineCache>,
Arc<wgc::pipeline::PipelineCache>,
@@ -83,6 +87,7 @@ impl Default for Player {
render_bundles: HashMap::new(),
render_pipelines: HashMap::new(),
compute_pipelines: HashMap::new(),
ray_tracing_pipelines: HashMap::new(),
pipeline_caches: HashMap::new(),
query_sets: HashMap::new(),
buffers: HashMap::new(),
@@ -207,6 +212,15 @@ impl Player {
let bgl = pipeline.get_bind_group_layout(index);
self.bind_group_layouts.insert(id, bgl);
}
Action::GetRayTracingPipelineBindGroupLayout {
id,
pipeline,
index,
} => {
let pipeline = self.resolve_ray_tracing_pipeline_id(pipeline);
let (bgl, _error) = pipeline.get_bind_group_layout(index);
self.bind_group_layouts.insert(id, bgl);
}
Action::DropBindGroupLayout(id) => {
self.bind_group_layouts
.remove(&id)
@@ -341,6 +355,16 @@ impl Player {
.remove(&id)
.expect("invalid render pipeline");
}
Action::CreateRayTracingPipeline { id, desc } => {
let descriptor = self.resolve_ray_tracing_pipeline_descriptor(desc);
let (rt_pipeline, _error) = device.create_ray_tracing_pipeline(descriptor);
self.ray_tracing_pipelines.insert(id, rt_pipeline);
}
Action::DropRayTracingPipeline(id) => {
self.ray_tracing_pipelines
.remove(&id)
.expect("invalid ray tracing pipeline");
}
Action::CreatePipelineCache { id, desc } => {
let (cache, _error) = unsafe { device.create_pipeline_cache(&desc) };
self.pipeline_caches.insert(id, cache);
@@ -573,6 +597,16 @@ impl Player {
.clone()
}
fn resolve_ray_tracing_pipeline_id(
&self,
id: wgc::id::PointerId<wgc::id::markers::RayTracingPipeline>,
) -> Arc<wgc::ray_tracing_pipeline::RayTracingPipeline> {
self.ray_tracing_pipelines
.get(&id)
.expect("invalid ray tracing pipeline")
.clone()
}
fn resolve_pipeline_cache_id(
&self,
id: wgc::id::PointerId<wgc::id::markers::PipelineCache>,
@@ -715,6 +749,61 @@ impl Player {
}
}
fn resolve_ray_tracing_pipeline_descriptor<'a>(
&self,
desc: wgc::device::trace::TraceRayTracingPipelineDescriptor<'a>,
) -> wgc::ray_tracing_pipeline::RayTracingPipelineDescriptor<'a> {
let layout = desc.layout.map(|id| self.resolve_pipeline_layout_id(id));
wgc::ray_tracing_pipeline::RayTracingPipelineDescriptor {
label: desc.label,
layout,
cache: desc.cache.map(|id| self.resolve_pipeline_cache_id(id)),
ray_generation: wgc::pipeline::ProgrammableStageDescriptor {
module: self.resolve_shader_module_id(desc.ray_generation.module),
entry_point: desc.ray_generation.entry_point,
constants: desc.ray_generation.constants,
zero_initialize_workgroup_memory: desc
.ray_generation
.zero_initialize_workgroup_memory,
},
miss: wgc::pipeline::ProgrammableStageDescriptor {
module: self.resolve_shader_module_id(desc.miss.module),
entry_point: desc.miss.entry_point,
constants: desc.miss.constants,
zero_initialize_workgroup_memory: desc.miss.zero_initialize_workgroup_memory,
},
intersections: desc
.intersections
.into_iter()
.map(|intersections| match intersections {
wgc::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit,
any_hit,
} => wgc::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit: wgc::pipeline::ProgrammableStageDescriptor {
module: self.resolve_shader_module_id(closest_hit.module),
entry_point: closest_hit.entry_point,
constants: closest_hit.constants,
zero_initialize_workgroup_memory: closest_hit
.zero_initialize_workgroup_memory,
},
any_hit: any_hit.map(|any_hit| {
wgc::pipeline::ProgrammableStageDescriptor {
module: self.resolve_shader_module_id(any_hit.module),
entry_point: any_hit.entry_point,
constants: any_hit.constants,
zero_initialize_workgroup_memory: any_hit
.zero_initialize_workgroup_memory,
}
}),
},
})
.collect(),
max_recursion_depth: desc.max_recursion_depth,
}
}
fn resolve_bind_group_descriptor<'a>(
&self,
desc: wgc::device::trace::TraceBindGroupDescriptor<'a>,
@@ -905,6 +994,9 @@ impl Player {
occlusion_query_set: occlusion_query_set.map(|qs| self.resolve_query_set_id(qs)),
multiview_mask,
},
Command::RunRayTracingPass { pass } => Command::RunRayTracingPass {
pass: self.resolve_ray_tracing_pass(pass),
},
Command::BuildAccelerationStructures { blas, tlas } => {
Command::BuildAccelerationStructures {
blas: blas
@@ -996,6 +1088,30 @@ impl Player {
}
}
fn resolve_ray_tracing_pass(
&self,
pass: BasePass<wgc::command::RayTracingCommand<PointerReferences>, Infallible>,
) -> BasePass<wgc::command::RayTracingCommand<ArcReferences>, Infallible> {
let BasePass {
label,
error,
commands,
dynamic_offsets,
string_data,
} = pass;
BasePass {
label,
error,
commands: commands
.into_iter()
.map(|cmd| self.resolve_ray_tracing_command(cmd))
.collect(),
dynamic_offsets,
string_data,
}
}
fn resolve_compute_command(
&self,
command: wgc::command::ComputeCommand<PointerReferences>,
@@ -1197,6 +1313,30 @@ impl Player {
}
}
fn resolve_ray_tracing_command(
&self,
command: wgc::command::RayTracingCommand<PointerReferences>,
) -> wgc::command::RayTracingCommand<ArcReferences> {
use wgc::command::RayTracingCommand as C;
match command {
C::SetBindGroup {
index,
num_dynamic_offsets,
bind_group,
} => C::SetBindGroup {
index,
num_dynamic_offsets,
bind_group: bind_group.map(|bg| self.resolve_bind_group_id(bg)),
},
C::SetPipeline(id) => C::SetPipeline(self.resolve_ray_tracing_pipeline_id(id)),
C::SetImmediate { offset, data } => C::SetImmediate { offset, data },
C::TraceRays(groups) => C::TraceRays(groups),
C::PushDebugGroup { color, len } => C::PushDebugGroup { color, len },
C::PopDebugGroup => C::PopDebugGroup,
C::InsertDebugMarker { color, len } => C::InsertDebugMarker { color, len },
}
}
fn resolve_pass_timestamp_writes(
&self,
writes: wgc::command::PassTimestampWrites<PointerId<wgc::id::markers::QuerySet>>,
@@ -1329,6 +1469,7 @@ impl Player {
transform: instance.transform,
custom_data: instance.custom_data,
mask: instance.mask,
intersection_index: instance.intersection_index,
}
}
@@ -131,12 +131,14 @@ async fn binding_array_tlas(ctx: TestingContext) {
[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,
0,
));
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,
0,
));
// Build BLAS and TLASes.
@@ -86,6 +86,7 @@ fn aabb_blas_build_and_trace(ctx: TestingContext) {
[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,
0,
));
let mut encoder = ctx
@@ -556,6 +556,7 @@ fn build_with_transform(ctx: TestingContext) {
[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,
0,
));
let mut encoder_build = ctx
@@ -64,6 +64,7 @@ fn acceleration_structure_use_after_free(ctx: TestingContext) {
[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,
0,
));
// Actually build the BLAS.
+3
View File
@@ -16,6 +16,7 @@ mod as_build;
mod as_create;
mod as_use_after_free;
mod limits;
mod pipelines;
mod scene;
mod shader;
@@ -27,6 +28,7 @@ pub fn all_tests(tests: &mut Vec<wgpu_test::GpuTestInitializer>) {
limits::all_tests(tests);
scene::all_tests(tests);
shader::all_tests(tests);
pipelines::all_tests(tests);
}
fn acceleration_structure_limits() -> wgpu::Limits {
@@ -84,6 +86,7 @@ impl AsBuildContext {
[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,
0,
));
Self {
File diff suppressed because it is too large. Load diff
@@ -76,6 +76,7 @@ fn acceleration_structure_build(ctx: &TestingContext, use_index_buffer: bool) {
)),
0,
0xff,
0,
));
}
+1
View File
@@ -212,6 +212,7 @@ ids! {
pub type ShaderModuleId ShaderModule;
pub type RenderPipelineId RenderPipeline;
pub type ComputePipelineId ComputePipeline;
pub type RayTracingPipelineId RayTracingPipeline;
pub type PipelineCacheId PipelineCache;
pub type CommandEncoderId CommandEncoder;
pub type CommandBufferId CommandBuffer;
+1
View File
@@ -15,6 +15,7 @@ impl wgpu_core::command::ReferenceType for IdReferences {
type RenderPipeline = RenderPipelineId;
type RenderBundle = RenderBundleId;
type ComputePipeline = ComputePipelineId;
type RayTracingPipeline = RayTracingPipelineId;
type Blas = BlasId;
type Tlas = TlasId;
}
+51 -1
View File
@@ -28,6 +28,7 @@ use crate::{
device::{bgl, Device, DeviceError, MissingDownlevelFlags, MissingFeatures},
init_tracker::{BufferInitTrackerAction, TextureInitTrackerAction},
pipeline::{ComputePipeline, RenderPipeline},
ray_tracing_pipeline::RayTracingPipeline,
resource::{
Buffer, DestroyedResourceError, ExternalTexture, InvalidOrDestroyedResourceError,
InvalidResourceError, Labeled, MissingBufferUsageError, MissingTextureUsageError,
@@ -407,6 +408,10 @@ pub(crate) struct PerStageBindingTypeCounter {
vertex: Saturating<u32>,
fragment: Saturating<u32>,
compute: Saturating<u32>,
ray_generation: Saturating<u32>,
miss: Saturating<u32>,
any_hit: Saturating<u32>,
closest_hit: Saturating<u32>,
}
impl PerStageBindingTypeCounter {
@@ -420,10 +425,29 @@ impl PerStageBindingTypeCounter {
if stage.contains(wgt::ShaderStages::COMPUTE) {
self.compute += count;
}
if stage.contains(wgt::ShaderStages::RAY_GENERATION) {
self.ray_generation += count;
}
if stage.contains(wgt::ShaderStages::MISS) {
self.miss += count;
}
if stage.contains(wgt::ShaderStages::ANY_HIT) {
self.any_hit += count;
}
if stage.contains(wgt::ShaderStages::CLOSEST_HIT) {
self.closest_hit += count;
}
}
pub(crate) fn max(&self) -> (BindingZone, u32) {
let max_value = self.vertex.max(self.fragment.max(self.compute));
let max_value = self.vertex.max(
self.fragment.max(
self.compute.max(
self.ray_generation
.max(self.miss.max(self.any_hit.max(self.closest_hit))),
),
),
);
let mut stage = wgt::ShaderStages::NONE;
if max_value == self.vertex {
stage |= wgt::ShaderStages::VERTEX
@@ -434,6 +458,18 @@ impl PerStageBindingTypeCounter {
if max_value == self.compute {
stage |= wgt::ShaderStages::COMPUTE
}
if max_value == self.ray_generation {
stage |= wgt::ShaderStages::RAY_GENERATION
}
if max_value == self.miss {
stage |= wgt::ShaderStages::MISS
}
if max_value == self.any_hit {
stage |= wgt::ShaderStages::ANY_HIT
}
if max_value == self.closest_hit {
stage |= wgt::ShaderStages::CLOSEST_HIT
}
(BindingZone::Stage(stage), max_value.0)
}
@@ -1163,6 +1199,7 @@ pub(crate) enum ExclusivePipeline {
None,
Render(Weak<RenderPipeline>),
Compute(Weak<ComputePipeline>),
RayTracing(Weak<RayTracingPipeline>),
}
impl From<&Arc<RenderPipeline>> for ExclusivePipeline {
@@ -1177,6 +1214,12 @@ impl From<&Arc<ComputePipeline>> for ExclusivePipeline {
}
}
impl From<&Arc<RayTracingPipeline>> for ExclusivePipeline {
fn from(pipeline: &Arc<RayTracingPipeline>) -> Self {
Self::RayTracing(Arc::downgrade(pipeline))
}
}
impl fmt::Display for ExclusivePipeline {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -1195,6 +1238,13 @@ impl fmt::Display for ExclusivePipeline {
f.write_str("ComputePipeline")
}
}
ExclusivePipeline::RayTracing(p) => {
if let Some(p) = p.upgrade() {
p.error_ident().fmt(f)
} else {
f.write_str("RayTracingPipeline")
}
}
}
}
}
+7
View File
@@ -21,6 +21,7 @@ pub trait ReferenceType {
type RenderPipeline: Clone + core::fmt::Debug;
type RenderBundle: Clone + core::fmt::Debug;
type ComputePipeline: Clone + core::fmt::Debug;
type RayTracingPipeline: Clone + core::fmt::Debug;
type Blas: Clone + core::fmt::Debug;
type Tlas: Clone + core::fmt::Debug;
}
@@ -51,6 +52,7 @@ impl ReferenceType for PointerReferences {
type RenderPipeline = crate::id::PointerId<crate::id::markers::RenderPipeline>;
type RenderBundle = crate::id::PointerId<crate::id::markers::RenderBundle>;
type ComputePipeline = crate::id::PointerId<crate::id::markers::ComputePipeline>;
type RayTracingPipeline = crate::id::PointerId<crate::id::markers::RayTracingPipeline>;
type Blas = crate::id::PointerId<crate::id::markers::Blas>;
type Tlas = crate::id::PointerId<crate::id::markers::Tlas>;
}
@@ -66,6 +68,7 @@ impl ReferenceType for ArcReferences {
type RenderPipeline = Arc<crate::pipeline::RenderPipeline>;
type RenderBundle = Arc<crate::command::RenderBundle>;
type ComputePipeline = Arc<crate::pipeline::ComputePipeline>;
type RayTracingPipeline = Arc<crate::ray_tracing_pipeline::RayTracingPipeline>;
type Blas = Arc<crate::resource::Blas>;
type Tlas = Arc<crate::resource::Tlas>;
}
@@ -85,6 +88,7 @@ attribute_alias! {
R::RenderPipeline: serde::Serialize + for<'d> serde::Deserialize<'d>,\
R::RenderBundle: serde::Serialize + for<'d> serde::Deserialize<'d>,\
R::ComputePipeline: serde::Serialize + for<'d> serde::Deserialize<'d>,\
R::RayTracingPipeline: serde::Serialize + for<'d> serde::Deserialize<'d>,\
R::Blas: serde::Serialize + for<'d> serde::Deserialize<'d>,\
R::Tlas: serde::Serialize + for<'d> serde::Deserialize<'d>,\
wgt::BufferTransition<R::Buffer>: serde::Serialize + for<'d> serde::Deserialize<'d>,\
@@ -144,6 +148,9 @@ pub enum Command<R: ReferenceType> {
pass: crate::command::BasePass<crate::command::ComputeCommand<R>, Infallible>,
timestamp_writes: Option<crate::command::PassTimestampWrites<R::QuerySet>>,
},
RunRayTracingPass {
pass: crate::command::BasePass<crate::command::RayTracingCommand<R>, Infallible>,
},
RunRenderPass {
pass: crate::command::BasePass<crate::command::RenderCommand<R>, Infallible>,
color_attachments: ColorAttachments<R::TextureView>,
+37 -2
View File
@@ -21,6 +21,8 @@ mod memory_init;
mod pass;
mod query;
mod ray_tracing;
mod ray_tracing_pass;
mod ray_tracing_pass_commands;
mod render;
mod render_command;
mod timestamp_writes;
@@ -55,6 +57,11 @@ pub use self::{
draw::{DrawError, Rect, RenderCommandError},
encoder_command::{ArcCommand, ArcReferences, Command, ReferenceType},
query::{QueryError, QueryUseError, ResolveError, SimplifiedQueryType},
ray_tracing_pass::{
RayTracingBasePass, RayTracingPass, RayTracingPassDescriptor, RayTracingPassError,
RayTracingPassErrorInner, TraceRayError,
},
ray_tracing_pass_commands::ArcRayTracingCommand,
render::{
AttachmentError, AttachmentErrorLocation, ColorAttachmentError, ColorAttachments, LoadOp,
PassChannel, RenderBasePass, RenderPass, RenderPassColorAttachment,
@@ -80,7 +87,10 @@ pub(crate) use self::{
pub(crate) use allocator::CommandAllocator;
/// cbindgen:ignore
pub use self::{compute_command::ComputeCommand, render_command::RenderCommand};
pub use self::{
compute_command::ComputeCommand, ray_tracing_pass_commands::RayTracingCommand,
render_command::RenderCommand,
};
pub use timestamp_writes::PassTimestampWrites;
@@ -1114,6 +1124,7 @@ impl CommandEncoder {
ArcCommand::RunRenderPass { .. }
| ArcCommand::RunComputePass { .. }
| ArcCommand::ResolveQuerySet { .. }
| ArcCommand::RunRayTracingPass { .. }
) {
// Compute passes and render passes can accept either an
// open or closed encoder. Resolving query sets needs to
@@ -1203,6 +1214,22 @@ impl CommandEncoder {
destination_offset,
)?;
}
ArcCommand::RunRayTracingPass { pass } => {
api_log!(
"Begin encoding ray tracing pass with '{}' label",
pass.label.as_deref().unwrap_or("")
);
let res = ray_tracing_pass::encode_ray_tracing_pass(&mut state, pass);
match res.as_ref() {
Err(err) => {
api_log!("Finished encoding ray tracing pass ({err:?})")
}
Ok(_) => {
api_log!("Finished encoding ray tracing pass (success)")
}
}
res?;
}
_ => unreachable!(),
}
} else {
@@ -1287,7 +1314,8 @@ impl CommandEncoder {
}
ArcCommand::RunComputePass { .. }
| ArcCommand::RunRenderPass { .. }
| ArcCommand::ResolveQuerySet { .. } => {
| ArcCommand::ResolveQuerySet { .. }
| ArcCommand::RunRayTracingPass { .. } => {
unreachable!()
}
}
@@ -1659,6 +1687,8 @@ pub enum CommandEncoderError {
ComputePass(#[from] ComputePassError),
#[error(transparent)]
RenderPass(#[from] RenderPassError),
#[error(transparent)]
RayTracingPass(#[from] RayTracingPassError),
}
impl From<InvalidOrDestroyedResourceError> for CommandEncoderError {
@@ -1713,6 +1743,7 @@ impl WebGpuError for CommandEncoderError {
Self::ResourceUsage(e) => e.webgpu_error_type(),
Self::ComputePass(e) => e.webgpu_error_type(),
Self::RenderPass(e) => e.webgpu_error_type(),
Self::RayTracingPass(e) => e.webgpu_error_type(),
}
}
}
@@ -2020,6 +2051,8 @@ pub enum PassErrorScope {
SetPipelineRender,
#[error("In a set_pipeline command")]
SetPipelineCompute,
#[error("In a set_pipeline command")]
SetPipelineRayTracing,
#[error("In a set_immediates command")]
SetImmediate,
#[error("In a set_vertex_buffer command")]
@@ -2061,6 +2094,8 @@ pub enum PassErrorScope {
PopDebugGroup,
#[error("In a insert_debug_marker command")]
InsertDebugMarker,
#[error("In a trace rays command")]
TraceRays,
}
/// Variant of `EncoderStateError` that includes the pass scope.
+1 -1
View File
@@ -236,7 +236,7 @@ pub(super) fn flush_bindings_helper(
.used
.acceleration_structures
.into_iter()
.map(|tlas| crate::ray_tracing::AsAction::UseTlas(tlas.clone()));
.map(|tlas| crate::ray_tracing::AsAction::BindTlas(tlas.clone()));
state.base.as_actions.extend(used_resource);
+115 -10
View File
@@ -62,7 +62,7 @@ impl super::CommandEncoder {
|cmd_buf_data| -> Result<(), BuildAccelerationStructureError> {
let device = &self.device;
device.check_is_valid()?;
device.require_features(Features::EXPERIMENTAL_RAY_QUERY)?;
device.require_acceleration_structures()?;
let mut build_command = AsBuild::with_capacity(blases.len(), tlases.len());
@@ -78,6 +78,8 @@ impl super::CommandEncoder {
build_command.tlas_s_built.push(TlasBuild {
tlas,
dependencies: Vec::new(),
max_intersection_idx: None,
required_intersection_types: Vec::new(),
});
}
@@ -198,9 +200,7 @@ pub(crate) fn build_acceleration_structures(
mut tlases: Vec<OwnedTlasPackage<ArcReferences>>,
) -> Result<(), BuildAccelerationStructureError> {
profiling::scope!("build_acceleration_structures");
state
.device
.require_features(Features::EXPERIMENTAL_RAY_QUERY)?;
state.device.require_acceleration_structures()?;
let mut build_command = AsBuild::with_capacity(blases.len(), tlases.len());
let mut input_barriers = Vec::<hal::BufferBarrier<dyn hal::DynBuffer>>::new();
@@ -237,13 +237,29 @@ pub(crate) fn build_acceleration_structures(
let mut dependencies = Vec::new();
let mut seen_dependencies = FastHashSet::<TrackerIndex>::default();
let mut required_intersection_types = Vec::new();
let mut seen_intersection_types =
FastHashSet::<crate::resource::TlasIntersectionType>::default();
let mut instance_count = 0;
for instance in mem::take(&mut package.instances).into_iter().flatten() {
let mut max_intersection_idx = None;
for (instance_idx, instance) in mem::take(&mut package.instances)
.into_iter()
.enumerate()
.flat_map(|(idx, instance)| instance.map(|inst| (idx, inst)))
{
if instance.custom_data >= (1u32 << 24u32) {
return Err(BuildAccelerationStructureError::TlasInvalidCustomIndex(
return Err(BuildAccelerationStructureError::TlasInvalidCustomData(
tlas.error_ident(),
instance_idx,
));
}
let max_intersection_idx = max_intersection_idx.get_or_insert(0);
*max_intersection_idx = (*max_intersection_idx).max(instance.intersection_index);
let blas = instance.blas;
let is_new_dependency = seen_dependencies.insert(blas.tracker_index());
@@ -251,13 +267,27 @@ pub(crate) fn build_acceleration_structures(
state.tracker.blas_s.insert_single(blas.clone());
}
if instance.intersection_index >= (1u32 << 24u32) {
return Err(
BuildAccelerationStructureError::TlasInvalidIntersectionIndex(
tlas.error_ident(),
instance_idx,
instance.intersection_index,
),
);
} else if instance.intersection_index != 0 {
state
.device
.require_features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)?;
}
state.device.raw().tlas_instance_to_bytes(
hal::TlasInstance {
transform: instance.transform,
custom_data: instance.custom_data,
mask: instance.mask,
blas_address: blas.handle,
pipeline_intersection_data_offset: 0,
pipeline_intersection_data_offset: instance.intersection_index,
},
&mut instance_buffer_staging_source,
);
@@ -279,6 +309,24 @@ pub(crate) fn build_acceleration_structures(
instance_count += 1;
let intersection_ty = crate::resource::TlasIntersectionType {
index: instance.intersection_index,
required_intersection_ty: match blas.sizes {
wgt::BlasGeometrySizeDescriptors::Triangles { .. } => {
crate::ray_tracing_pipeline::RayTracingIntersectionType::Triangle
}
wgt::BlasGeometrySizeDescriptors::AABBs { .. } => {
crate::ray_tracing_pipeline::RayTracingIntersectionType::AABB
}
},
};
let new_intersection_ty = seen_intersection_types.insert(intersection_ty);
if new_intersection_ty {
required_intersection_types.push(intersection_ty);
}
if is_new_dependency {
dependencies.push(blas);
}
@@ -287,6 +335,8 @@ pub(crate) fn build_acceleration_structures(
build_command.tlas_s_built.push(TlasBuild {
tlas: tlas.clone(),
dependencies,
max_intersection_idx,
required_intersection_types,
});
if instance_count > tlas.max_instance_count {
@@ -523,10 +573,14 @@ impl CommandBufferMutable {
.tlas
.dependencies
.write()
.clone_from(&tlas_build.dependencies)
.clone_from(&tlas_build.dependencies);
*tlas_build.tlas.max_intersection_index.write() =
tlas_build.max_intersection_idx;
*tlas_build.tlas.required_intersection_types.write() =
tlas_build.required_intersection_types.clone();
}
}
AsAction::UseTlas(tlas) => {
AsAction::BindTlas(tlas) => {
let tlas_build_index = tlas.built_index.read();
let dependencies = tlas.dependencies.read();
@@ -550,6 +604,55 @@ impl CommandBufferMutable {
blas.try_raw(snatch_guard)?;
}
}
AsAction::TraceTlas(tlas, intersection_types) => {
let current_max = tlas.max_intersection_index.read();
let max_intersection_len = u32::try_from(intersection_types.len())
.expect("should be smaller than a u32");
if let Some(current_max) = *current_max {
if current_max >= max_intersection_len {
return Err(ValidateAsActionsError::TlasIntersectionInvalid(
tlas.error_ident(),
current_max,
max_intersection_len,
));
}
}
drop(current_max);
let required_intersection_types = tlas.required_intersection_types.read();
for intersection_ty in required_intersection_types.iter() {
let Ok(index) = usize::try_from(intersection_ty.index) else {
return Err(
ValidateAsActionsError::TlasInstancesIntersectionIndicesDiffer(
tlas.error_ident(),
intersection_ty.required_intersection_ty,
intersection_ty.index,
None,
),
);
};
match intersection_types.get(index) {
Some(ty) => {
if *ty != intersection_ty.required_intersection_ty {
return Err(ValidateAsActionsError::TlasInstancesIntersectionIndicesDiffer(tlas.error_ident(), intersection_ty.required_intersection_ty, intersection_ty.index, Some(*ty)));
}
}
None => {
return Err(
ValidateAsActionsError::TlasInstancesIntersectionIndicesDiffer(
tlas.error_ident(),
intersection_ty.required_intersection_ty,
intersection_ty.index,
None,
),
);
}
}
}
}
}
}
Ok(())
@@ -563,9 +666,11 @@ impl CommandBufferMutable {
AsAction::Build(build) => {
dependencies.extend(build.blas_s_built.iter().map(Arc::clone));
}
AsAction::UseTlas(tlas) => {
AsAction::BindTlas(tlas) => {
dependencies.extend(tlas.dependencies.read().iter().map(Arc::clone));
}
// Any tlas traced against must also be bound.
AsAction::TraceTlas(..) => {}
}
}
+992
View File
@@ -0,0 +1,992 @@
use core::{convert::Infallible, fmt};
use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec};
use thiserror::Error;
use wgt::{
error::{ErrorType, WebGpuError},
BufferAddress, DynamicOffset,
};
use crate::{
api_log,
binding_model::{BindError, BindGroup, ImmediateUploadError, LateMinBufferBindingSizeMismatch},
command::{
bind::{Binder, BinderError},
memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState},
pass::{self, flush_bindings_helper, ImmediateState},
pass_base, pass_try,
ray_tracing_pass_commands::ArcRayTracingCommand,
ArcCommand, BasePass, BindGroupStateChange, CommandEncoder, CommandEncoderError,
DebugGroupError, EncoderStateError, EncodingState, InnerCommandEncoder, MapPassErr,
PassErrorScope, PassStateError, StateChange,
},
device::{Device, DeviceError, MissingDownlevelFlags, MissingFeatures},
hal_label, id, impl_resource_type,
ray_tracing::AsAction,
ray_tracing_pipeline::RayTracingPipeline,
resource::{
DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError, Labeled,
MissingBufferUsageError, ParentDevice,
},
track::{ResourceUsageCompatibilityError, Tracker},
Label,
};
pub type RayTracingBasePass = BasePass<ArcRayTracingCommand, RayTracingPassError>;
/// Very similar to [`super::compute::ComputePass`]
pub struct RayTracingPass {
/// All pass data & records is stored here.
base: RayTracingBasePass,
/// Parent command encoder that this pass records commands into.
///
/// Implications are the same as [`super::compute::ComputePass::parent`]
parent: Option<Arc<CommandEncoder>>,
device: Arc<Device>,
current_bind_groups: BindGroupStateChange,
current_pipeline: StateChange<Arc<RayTracingPipeline>>,
}
impl_resource_type!(RayTracingPass);
impl crate::storage::StorageItem for RayTracingPass {
type Marker = id::markers::RayTracingPassEncoder;
}
impl fmt::Debug for RayTracingPass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.parent {
Some(ref cmd_enc) => {
write!(f, "RayTracingPass {{ parent: {} }}", cmd_enc.error_ident())
}
None => write!(f, "RayTracingPass {{ parent: None }}"),
}
}
}
impl RayTracingPass {
/// If the parent command encoder is invalid, the returned pass will be invalid.
fn new(
parent: Arc<CommandEncoder>,
desc: RayTracingPassDescriptor,
) -> Result<Self, MissingFeatures> {
parent
.device
.require_features(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)?;
let RayTracingPassDescriptor { label } = desc;
Ok(Self {
base: BasePass::new(&label),
device: parent.device.clone(),
parent: Some(parent),
current_bind_groups: BindGroupStateChange::new(),
current_pipeline: StateChange::new(),
})
}
fn new_invalid(parent: Arc<CommandEncoder>, label: &Label, err: RayTracingPassError) -> Self {
Self {
base: BasePass::new_invalid(label, err),
device: parent.device.clone(),
parent: Some(parent),
current_bind_groups: BindGroupStateChange::new(),
current_pipeline: StateChange::new(),
}
}
#[inline]
pub fn label(&self) -> Option<&str> {
self.base.label.as_deref()
}
pub fn set_bind_group(
&mut self,
index: u32,
bind_group: Option<Arc<BindGroup>>,
offsets: &[DynamicOffset],
) {
if let Err(err) = self.set_bind_group_inner(index, bind_group, offsets) {
self.device
.handle_error(err, self.label(), "RayTracingPass::set_bind_group");
}
}
pub fn set_bind_group_inner(
&mut self,
index: u32,
bind_group: Option<Arc<BindGroup>>,
offsets: &[DynamicOffset],
) -> Result<(), PassStateError> {
let scope = PassErrorScope::SetBindGroup;
// This statement will return an error if the pass is ended. It's
// important the error check comes before the early-out for
// `set_and_check_redundant`.
let base = pass_base!(self, scope);
if self.current_bind_groups.set_and_check_redundant(
&bind_group,
index,
&mut base.dynamic_offsets,
offsets,
) {
return Ok(());
}
let bind_group = if let Some(bind_group) = bind_group {
pass_try!(base, scope, bind_group.check_is_valid());
Some(bind_group)
} else {
None
};
base.commands.push(ArcRayTracingCommand::SetBindGroup {
index,
num_dynamic_offsets: offsets.len(),
bind_group,
});
Ok(())
}
pub fn set_immediates_inner(&mut self, offset: u32, data: &[u8]) -> Result<(), PassStateError> {
let scope = PassErrorScope::SetImmediate;
let base = pass_base!(self, scope);
pass_try!(
base,
scope,
pass::validate_immediates_alignment(offset, data.len())
);
base.commands.push(ArcRayTracingCommand::SetImmediate {
offset,
data: data
.chunks_exact(size_of::<u32>())
.map(|ck| u32::from_le_bytes(ck.try_into().unwrap()))
.collect(),
});
Ok(())
}
pub fn set_immediates(&mut self, offset: u32, data: &[u8]) {
if let Err(err) = self.set_immediates_inner(offset, data) {
self.device
.handle_error(err, self.label(), "RayTracingPass::set_immediates");
}
}
}
#[derive(Clone, Debug, Default)]
pub struct RayTracingPassDescriptor<'a> {
pub label: Label<'a>,
}
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum TraceRayError {
#[error("Ray tracing pipeline must be set")]
MissingPipeline(pass::MissingPipeline),
#[error(transparent)]
IncompatibleBindGroup(#[from] Box<BinderError>),
#[error("Trace ray size ({current:?}) must be less or equal to {limit:?}")]
InvalidDimensionSize { current: [u32; 3], limit: [u32; 3] },
#[error("The total count of rays invocations ({current:?}) must be less or equal to {limit}")]
TooManyTotal { current: u32, limit: u32 },
#[error(transparent)]
BindingSizeTooSmall(#[from] LateMinBufferBindingSizeMismatch),
#[error("Not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: {missing})")]
MissingImmediateData {
missing: naga::valid::ImmediateSlots,
},
}
impl WebGpuError for TraceRayError {
fn webgpu_error_type(&self) -> ErrorType {
ErrorType::Validation
}
}
/// Error encountered when performing a ray tracing pass.
#[derive(Clone, Debug, Error)]
pub enum RayTracingPassErrorInner {
#[error(transparent)]
Device(#[from] DeviceError),
#[error(transparent)]
EncoderState(#[from] EncoderStateError),
#[error("Parent encoder is invalid")]
InvalidParentEncoder,
#[error(transparent)]
DebugGroupError(#[from] DebugGroupError),
#[error(transparent)]
BindGroupIndexOutOfRange(#[from] pass::BindGroupIndexOutOfRange),
#[error(transparent)]
DestroyedResource(#[from] DestroyedResourceError),
#[error("Indirect buffer offset {0:?} is not a multiple of 4")]
UnalignedIndirectBufferOffset(BufferAddress),
#[error("Indirect buffer uses bytes {offset}..{end_offset} which overruns indirect buffer of size {buffer_size}")]
IndirectBufferOverrun {
offset: u64,
end_offset: u64,
buffer_size: u64,
},
#[error(transparent)]
ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
#[error(transparent)]
MissingBufferUsage(#[from] MissingBufferUsageError),
#[error(transparent)]
TraceRay(#[from] TraceRayError),
#[error(transparent)]
Bind(#[from] BindError),
#[error(transparent)]
ImmediateData(#[from] ImmediateUploadError),
#[error("Immediate data offset must be aligned to 4 bytes")]
ImmediateOffsetAlignment,
#[error("Immediate data size must be aligned to 4 bytes")]
ImmediateDataizeAlignment,
#[error("Ran out of immediate data space. Don't set 4gb of immediates per RayTracingPass.")]
ImmediateOutOfMemory,
#[error(transparent)]
MissingFeatures(#[from] MissingFeatures),
#[error(transparent)]
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
#[error("The ray tracing pass has already been ended and no further commands can be recorded")]
PassEnded,
#[error(transparent)]
InvalidResource(#[from] InvalidResourceError),
}
impl From<InvalidOrDestroyedResourceError> for RayTracingPassErrorInner {
fn from(error: InvalidOrDestroyedResourceError) -> Self {
match error {
InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
}
}
}
/// Error encountered when performing a ray tracing pass, stored for later reporting
/// when encoding ends.
#[derive(Clone, Debug, Error)]
#[error("{scope}")]
pub struct RayTracingPassError {
pub scope: PassErrorScope,
#[source]
pub(super) inner: Box<RayTracingPassErrorInner>,
}
impl From<pass::MissingPipeline> for RayTracingPassErrorInner {
fn from(value: pass::MissingPipeline) -> Self {
Self::TraceRay(TraceRayError::MissingPipeline(value))
}
}
impl<E> MapPassErr<RayTracingPassError> for E
where
E: Into<RayTracingPassErrorInner>,
{
fn map_pass_err(self, scope: PassErrorScope) -> RayTracingPassError {
RayTracingPassError {
scope,
inner: Box::new(self.into()),
}
}
}
impl WebGpuError for RayTracingPassError {
fn webgpu_error_type(&self) -> ErrorType {
match self.inner.as_ref() {
RayTracingPassErrorInner::Device(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::EncoderState(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::DebugGroupError(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::DestroyedResource(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::ResourceUsageCompatibility(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::MissingBufferUsage(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::TraceRay(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::Bind(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::ImmediateData(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::MissingFeatures(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::InvalidResource(e) => e.webgpu_error_type(),
RayTracingPassErrorInner::InvalidParentEncoder
| RayTracingPassErrorInner::BindGroupIndexOutOfRange { .. }
| RayTracingPassErrorInner::UnalignedIndirectBufferOffset(_)
| RayTracingPassErrorInner::IndirectBufferOverrun { .. }
| RayTracingPassErrorInner::ImmediateOffsetAlignment
| RayTracingPassErrorInner::ImmediateDataizeAlignment
| RayTracingPassErrorInner::ImmediateOutOfMemory
| RayTracingPassErrorInner::PassEnded => ErrorType::Validation,
}
}
}
struct State<'scope, 'snatch_guard, 'cmd_enc> {
pipeline: Option<Arc<RayTracingPipeline>>,
pass: pass::PassState<'scope, 'snatch_guard, 'cmd_enc>,
intermediate_trackers: Tracker,
}
impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> {
fn is_ready(&self) -> Result<(), TraceRayError> {
if let Some(pipeline) = self.pipeline.as_ref() {
self.pass.binder.check_compatibility(pipeline.as_ref())?;
self.pass.binder.check_late_buffer_bindings()?;
if !self
.pass
.immediate_state
.immediate_slots_set
.contains(pipeline.immediate_slots_required)
{
return Err(TraceRayError::MissingImmediateData {
missing: pipeline
.immediate_slots_required
.difference(self.pass.immediate_state.immediate_slots_set),
});
}
Ok(())
} else {
Err(TraceRayError::MissingPipeline(pass::MissingPipeline))
}
}
fn flush_immediates(&mut self) {
let pipeline = self.pipeline.as_ref().unwrap();
let layout = pipeline.layout().unwrap();
self.pass
.immediate_state
.flush_immediates(layout, self.pass.base.raw_encoder);
}
/// Flush binding state in preparation for a trace rays call.
///
/// This behaves almost the same as a compute pass' equivalent
/// function, but also adds a `AsAction::TraceTlas` as trace ray
/// calls need a bit more validation.
///
/// This differs from a render pass, which the equivalent method
/// on compute pass' state discuss more.
fn flush_bindings(&mut self) -> Result<(), RayTracingPassErrorInner> {
for bind_group in self.pass.binder.list_active() {
unsafe { self.pass.scope.merge_bind_group(&bind_group.used)? };
}
// For ray tracing passes, usage scopes are associated with each trace
// ray (in the same way as compute passes) and not with the pass as a
// whole. However, because the cost of creating and dropping
// `UsageScope`s is significant (even with the pool), we add and then
// remove usage from a single usage scope.
let intersection_types = self.pipeline.as_ref().unwrap().intersection_types()?;
for bind_group in self.pass.binder.list_active() {
self.intermediate_trackers
.set_and_remove_from_usage_scope_sparse(&mut self.pass.scope, &bind_group.used);
for tlas in bind_group.used.acceleration_structures.into_iter() {
self.pass.base.as_actions.push(AsAction::TraceTlas(
tlas.clone(),
intersection_types.clone(),
));
}
}
flush_bindings_helper(&mut self.pass)?;
CommandEncoder::drain_barriers(
self.pass.base.raw_encoder,
&mut self.intermediate_trackers,
self.pass.base.snatch_guard,
);
Ok(())
}
}
// Ray tracing pass commands
impl RayTracingPass {
pub fn set_pipeline(&mut self, pipeline: Arc<RayTracingPipeline>) {
if let Err(err) = self.set_pipeline_inner(pipeline) {
self.device
.handle_error(err, self.label(), "RayTracingPass::set_pipeline");
}
}
pub fn set_pipeline_inner(
&mut self,
pipeline: Arc<RayTracingPipeline>,
) -> Result<(), PassStateError> {
let scope = PassErrorScope::SetPipelineRayTracing;
let redundant = self.current_pipeline.set_and_check_redundant(&pipeline);
// This statement will return an error if the pass is ended.
// Its important the error check comes before the early-out for `redundant`.
let base = pass_base!(self, scope);
if redundant {
return Ok(());
}
pass_try!(base, scope, pipeline.check_valid());
base.commands
.push(ArcRayTracingCommand::SetPipeline(pipeline));
Ok(())
}
pub fn end_inner(&mut self) -> Result<(), EncoderStateError> {
profiling::scope!(
"CommandEncoder::run_ray_tracing_pass {}",
self.base.label.as_deref().unwrap_or("")
);
let cmd_enc = self.parent.take().ok_or(EncoderStateError::Ended)?;
let mut cmd_buf_data = cmd_enc.data.lock();
cmd_buf_data.unlock_encoder()?;
let base = self.base.take();
if let Err(RayTracingPassError { inner, scope: _ }) = &base {
if let RayTracingPassErrorInner::EncoderState(
err @ (EncoderStateError::Locked | EncoderStateError::Ended),
) = inner.as_ref()
{
// Most encoding errors are detected and raised within `finish()`.
//
// However, we raise a validation error here if the pass was opened
// within another pass, or on a finished encoder. The latter is
// particularly important, because in that case reporting errors via
// `CommandEncoder::finish` is not possible.
return Err(err.clone());
}
}
cmd_buf_data.push_with(|| -> Result<_, RayTracingPassError> {
Ok(ArcCommand::RunRayTracingPass { pass: base? })
})
}
pub fn end(&mut self) {
if let Err(err) = self.end_inner() {
self.device
.handle_error(err, self.label(), "RayTracingPass::end");
}
}
pub fn push_debug_group_inner(
&mut self,
label: &str,
color: u32,
) -> Result<(), PassStateError> {
let base = pass_base!(self, PassErrorScope::PushDebugGroup);
let bytes = label.as_bytes();
base.string_data.extend_from_slice(bytes);
base.commands.push(ArcRayTracingCommand::PushDebugGroup {
color,
len: bytes.len(),
});
Ok(())
}
pub fn push_debug_group(&mut self, label: &str, color: u32) {
if let Err(err) = self.push_debug_group_inner(label, color) {
self.device
.handle_error(err, self.label(), "RayTracingPass::push_debug_group");
}
}
pub fn pop_debug_group_inner(&mut self) -> Result<(), PassStateError> {
let base = pass_base!(self, PassErrorScope::PopDebugGroup);
base.commands.push(ArcRayTracingCommand::PopDebugGroup);
Ok(())
}
pub fn pop_debug_group(&mut self) {
if let Err(err) = self.pop_debug_group_inner() {
self.device
.handle_error(err, self.label(), "RayTracingPass::pop_debug_group");
}
}
pub fn insert_debug_marker_inner(
&mut self,
label: &str,
color: u32,
) -> Result<(), PassStateError> {
let base = pass_base!(self, PassErrorScope::InsertDebugMarker);
let bytes = label.as_bytes();
base.string_data.extend_from_slice(bytes);
base.commands.push(ArcRayTracingCommand::InsertDebugMarker {
color,
len: bytes.len(),
});
Ok(())
}
pub fn insert_debug_marker(&mut self, label: &str, color: u32) {
if let Err(err) = self.insert_debug_marker_inner(label, color) {
self.device
.handle_error(err, self.label(), "RayTracingPass::insert_debug_marker");
}
}
pub fn trace_rays_inner(
&mut self,
count_x: u32,
count_y: u32,
count_z: u32,
) -> Result<(), PassStateError> {
let scope = PassErrorScope::TraceRays;
pass_base!(self, scope)
.commands
.push(ArcRayTracingCommand::TraceRays([count_x, count_y, count_z]));
Ok(())
}
pub fn trace_rays(&mut self, count_x: u32, count_y: u32, count_z: u32) {
if let Err(err) = self.trace_rays_inner(count_x, count_y, count_z) {
self.device
.handle_error(err, self.label(), "RayTracingPass::trace_rays");
}
}
}
impl CommandEncoder {
pub fn begin_ray_tracing_pass_inner(
self: &Arc<Self>,
desc: &RayTracingPassDescriptor<'_>,
) -> (RayTracingPass, Option<CommandEncoderError>) {
use EncoderStateError as SErr;
let label = desc.label.as_deref().map(Cow::Borrowed);
let scope = PassErrorScope::Pass;
let mut cmd_buf_data = self.data.lock();
match cmd_buf_data.lock_encoder() {
Ok(()) => {
drop(cmd_buf_data);
if let Err(err) = self.device.check_is_valid() {
return (
RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
None,
);
}
let pass = match RayTracingPass::new(
self.clone(),
RayTracingPassDescriptor {
label: label.clone(),
},
) {
Ok(pass) => pass,
Err(err) => {
return (
RayTracingPass::new_invalid(
self.clone(),
&label,
err.map_pass_err(scope),
),
None,
);
}
};
(pass, None)
}
Err(err @ SErr::Locked) => {
// Attempting to open a new pass while the encoder is locked
// invalidates the encoder, but does not generate a validation
// error.
cmd_buf_data.invalidate(err.clone());
drop(cmd_buf_data);
(
RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
None,
)
}
Err(err @ (SErr::Ended | SErr::Submitted)) => {
// Attempting to open a new pass after the encode has ended
// generates an immediate validation error.
drop(cmd_buf_data);
(
RayTracingPass::new_invalid(
self.clone(),
&label,
err.clone().map_pass_err(scope),
),
Some(err.into()),
)
}
Err(err @ SErr::Invalid) => {
// Passes can be opened even on an invalid encoder. Such passes
// are even valid, but since there's no visible side-effect of
// the pass being valid and there's no point in storing recorded
// commands that will ultimately be discarded, we open an
// invalid pass to save that work.
drop(cmd_buf_data);
(
RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
None,
)
}
Err(SErr::Unlocked) => {
unreachable!("lock_encoder cannot fail due to the encoder being unlocked")
}
}
}
pub fn begin_ray_tracing_pass(
self: &Arc<Self>,
desc: &RayTracingPassDescriptor<'_>,
) -> RayTracingPass {
let (pass, err) = self.begin_ray_tracing_pass_inner(desc);
if let Some(err) = err {
self.device
.handle_error(err, pass.label(), "CommandEncoder::begin_ray_tracing_pass");
}
pass
}
}
pub(super) fn encode_ray_tracing_pass(
parent_state: &mut EncodingState<InnerCommandEncoder>,
mut base: BasePass<ArcRayTracingCommand, Infallible>,
) -> Result<(), RayTracingPassError> {
let pass_scope = PassErrorScope::Pass;
let device = parent_state.device;
// We automatically keep extending command buffers over time, and because
// we want to insert a command buffer _before_ what we're about to record,
// we need to make sure to close the previous one.
parent_state
.raw_encoder
.close_if_open()
.map_pass_err(pass_scope)?;
let raw_encoder = parent_state
.raw_encoder
.open_pass(base.label.as_deref())
.map_pass_err(pass_scope)?;
let mut debug_scope_depth = 0;
let mut state = State {
pipeline: None,
pass: pass::PassState {
base: EncodingState {
device,
raw_encoder,
tracker: parent_state.tracker,
buffer_memory_init_actions: parent_state.buffer_memory_init_actions,
texture_memory_actions: parent_state.texture_memory_actions,
as_actions: parent_state.as_actions,
temp_resources: parent_state.temp_resources,
indirect_draw_validation_resources: parent_state.indirect_draw_validation_resources,
snatch_guard: parent_state.snatch_guard,
debug_scope_depth: &mut debug_scope_depth,
query_set_writes: parent_state.query_set_writes,
deferred_query_set_resolves: parent_state.deferred_query_set_resolves,
},
binder: Binder::new(),
temp_offsets: Vec::new(),
dynamic_offset_count: 0,
pending_discard_init_fixups: SurfacesInDiscardState::new(),
scope: device.new_usage_scope(),
string_offset: 0,
immediate_state: ImmediateState::default(),
},
intermediate_trackers: Tracker::new(
device.ordered_buffer_usages,
device.ordered_texture_usages,
),
};
let indices = &device.tracker_indices;
state
.pass
.base
.tracker
.buffers
.set_size(indices.buffers.size());
state
.pass
.base
.tracker
.textures
.set_size(indices.textures.size());
let hal_desc = hal::RayTracingPassDescriptor {
label: hal_label(base.label.as_deref(), device.instance_flags),
};
unsafe {
state
.pass
.base
.raw_encoder
.begin_ray_tracing_pass(&hal_desc);
}
for command in base.commands.drain(..) {
match command {
ArcRayTracingCommand::SetBindGroup {
index,
num_dynamic_offsets,
bind_group,
} => {
let scope = PassErrorScope::SetBindGroup;
pass::set_bind_group::<RayTracingPassErrorInner>(
&mut state.pass,
device,
&base.dynamic_offsets,
index,
num_dynamic_offsets,
bind_group,
false,
)
.map_pass_err(scope)?;
}
ArcRayTracingCommand::SetPipeline(pipeline) => {
let scope = PassErrorScope::SetPipelineRayTracing;
set_pipeline(&mut state, device, pipeline).map_pass_err(scope)?;
}
ArcRayTracingCommand::SetImmediate { offset, data } => {
let scope = PassErrorScope::SetImmediate;
state
.pass
.immediate_state
.set_immediates::<RayTracingPassErrorInner>(
&state.pass.base.device.limits,
offset,
&data,
)
.map_pass_err(scope)?;
}
ArcRayTracingCommand::PushDebugGroup { color: _, len } => {
pass::push_debug_group(&mut state.pass, &base.string_data, len);
}
ArcRayTracingCommand::PopDebugGroup => {
let scope = PassErrorScope::PopDebugGroup;
pass::pop_debug_group::<RayTracingPassErrorInner>(&mut state.pass)
.map_pass_err(scope)?;
}
ArcRayTracingCommand::InsertDebugMarker { color: _, len } => {
pass::insert_debug_marker(&mut state.pass, &base.string_data, len);
}
ArcRayTracingCommand::TraceRays(groups) => {
let scope = PassErrorScope::TraceRays;
trace_rays(&mut state, groups, device).map_pass_err(scope)?;
}
}
}
if *state.pass.base.debug_scope_depth > 0 {
Err(
RayTracingPassErrorInner::DebugGroupError(DebugGroupError::MissingPop)
.map_pass_err(pass_scope),
)?;
}
unsafe {
state.pass.base.raw_encoder.end_ray_tracing_pass();
}
let State {
pass: pass::PassState {
pending_discard_init_fixups,
..
},
intermediate_trackers,
..
} = state;
// Stop the current command encoder.
parent_state.raw_encoder.close().map_pass_err(pass_scope)?;
// Create a new command encoder, which we will insert _before_ the body of the ray tracing pass.
//
// Use that buffer to insert barriers and clear discarded images.
let transit = parent_state
.raw_encoder
.open_pass(hal_label(
Some("(wgpu internal) Pre Pass"),
device.instance_flags,
))
.map_pass_err(pass_scope)?;
// If the ray tracing pass reads any surfaces that were discarded by a previous
// render pass in the same command buffer, initialize them.
fixup_discarded_surfaces(
pending_discard_init_fixups.into_iter(),
transit,
&mut parent_state.tracker.textures,
device,
parent_state.snatch_guard,
);
CommandEncoder::insert_barriers_from_tracker(
transit,
parent_state.tracker,
&intermediate_trackers,
parent_state.snatch_guard,
);
// Close the command encoder, and swap it with the previous.
parent_state
.raw_encoder
.close_and_swap()
.map_pass_err(pass_scope)?;
Ok(())
}
fn set_pipeline(
state: &mut State,
device: &Arc<Device>,
pipeline: Arc<RayTracingPipeline>,
) -> Result<(), RayTracingPassErrorInner> {
pipeline.same_device(device)?;
state.pipeline = Some(pipeline.clone());
let pipeline = state
.pass
.base
.tracker
.ray_tracing_pipelines
.insert_single(pipeline)
.clone();
unsafe {
state
.pass
.base
.raw_encoder
.set_ray_tracing_pipeline(pipeline.raw()?);
}
// Rebind resources
let pipeline_layout = pipeline.layout()?;
pass::change_pipeline_layout::<RayTracingPassErrorInner>(
&mut state.pass,
pipeline_layout,
&pipeline.late_sized_buffer_groups,
)
}
fn trace_rays(
state: &mut State,
dims: [u32; 3],
device: &Device,
) -> Result<(), RayTracingPassErrorInner> {
api_log!("RayTracingPass::trace_rays {dims:?}");
state.is_ready()?;
state.flush_bindings()?;
state.flush_immediates();
let limits = &state.pass.base.device.limits;
// `saturating_mul` is fine here as it is the limit, so a lower limit if it would overflow is just a
// slightly greater restriction.
let dim_size_limit = [
limits
.max_compute_workgroup_size_x
.saturating_mul(limits.max_compute_workgroups_per_dimension),
limits
.max_compute_workgroup_size_y
.saturating_mul(limits.max_compute_workgroups_per_dimension),
limits
.max_compute_workgroup_size_z
.saturating_mul(limits.max_compute_workgroups_per_dimension),
];
if dims[0] > dim_size_limit[0] {
return Err(RayTracingPassErrorInner::TraceRay(
TraceRayError::InvalidDimensionSize {
current: dims,
limit: dim_size_limit,
},
));
}
if dims[1] > dim_size_limit[1] {
return Err(RayTracingPassErrorInner::TraceRay(
TraceRayError::InvalidDimensionSize {
current: dims,
limit: dim_size_limit,
},
));
}
if dims[2] > dim_size_limit[2] {
return Err(RayTracingPassErrorInner::TraceRay(
TraceRayError::InvalidDimensionSize {
current: dims,
limit: dim_size_limit,
},
));
}
let tot_rays = dims[0]
.checked_mul(dims[1])
.and_then(|tmp| tmp.checked_mul(dims[2]));
if tot_rays.is_none_or(|tot_rays| tot_rays > limits.max_ray_dispatch_count) {
return Err(RayTracingPassErrorInner::TraceRay(
TraceRayError::TooManyTotal {
current: tot_rays.unwrap_or(u32::MAX),
limit: limits.max_ray_dispatch_count,
},
));
}
let current_pipeline = state.pipeline.as_ref().unwrap();
let shader_binding_data = current_pipeline.shader_binding_data()?;
unsafe {
state.pass.base.raw_encoder.trace_rays(
dims,
hal::PipelineGroupData {
buffer: shader_binding_data.raw.as_ref(),
offset: 0,
stride: device.alignments.ray_tracing_pipeline_group_data_size as _,
count: 1,
},
hal::PipelineGroupData {
buffer: shader_binding_data.raw.as_ref(),
offset: shader_binding_data.miss_offset,
stride: device.alignments.ray_tracing_pipeline_group_data_size as _,
count: 1,
},
hal::PipelineGroupData {
buffer: shader_binding_data.raw.as_ref(),
offset: shader_binding_data.intersection_offset,
stride: device.alignments.ray_tracing_pipeline_group_data_size as _,
count: shader_binding_data.num_intersection_groups as _,
},
);
}
Ok(())
}
@@ -0,0 +1,47 @@
#[cfg(feature = "serde")]
use crate::command::serde_object_reference_struct;
use crate::command::{ArcReferences, ReferenceType};
use alloc::vec::Vec;
#[cfg(feature = "serde")]
use macro_rules_attribute::apply;
/// cbindgen:ignore
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))]
pub enum RayTracingCommand<R: ReferenceType> {
SetBindGroup {
index: u32,
num_dynamic_offsets: usize,
bind_group: Option<R::BindGroup>,
},
SetPipeline(R::RayTracingPipeline),
/// Set a range of immediates to values stored in `immediates_data`.
SetImmediate {
/// The byte offset within the immediate data storage to write to. This
/// must be a multiple of four.
offset: u32,
/// The immediate data to be written.
data: Vec<u32>,
},
TraceRays([u32; 3]),
PushDebugGroup {
color: u32,
len: usize,
},
PopDebugGroup,
InsertDebugMarker {
color: u32,
len: usize,
},
}
/// cbindgen:ignore
pub type ArcRayTracingCommand = RayTracingCommand<ArcReferences>;
+17 -2
View File
@@ -30,6 +30,7 @@ use crate::{
init_tracker::{has_copy_partial_init_tracker_coverage, TextureInitRange},
lock::{rank, Mutex, MutexGuard, RwLock, RwLockWriteGuard},
ray_tracing::{BlasCompactReadyPendingClosure, CompactBlasError},
ray_tracing_pipeline,
resource::{
Blas, BlasCompactState, BlasDescriptor, BlasState, Buffer, BufferAccessError,
BufferMapState, DestroyedBuffer, DestroyedQuerySet, DestroyedResourceError,
@@ -351,6 +352,9 @@ pub(crate) struct EncoderInFlight {
pub(crate) pending_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
/// These are the BLASes that have been tracked by `PendingWrites`.
pub(crate) pending_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
/// These are the shader binding data buffers that have been tracked by `PendingWrites`.
/// Only need to keep these live while the writes wait.
_pending_shader_binding_data: Vec<Arc<ray_tracing_pipeline::ShaderBindingData>>,
}
/// A private command encoder for writes made directly on the device
@@ -393,6 +397,9 @@ pub(crate) struct PendingWrites {
dst_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
dst_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
copied_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
/// Buffers of shader binding data that have been written to when creating their
/// ray tracing pipelines.
written_shader_binding_data: Vec<Arc<ray_tracing_pipeline::ShaderBindingData>>,
instance_flags: wgt::InstanceFlags,
/// Staging buffers that are the source of a copy recorded in
@@ -444,6 +451,7 @@ impl PendingWrites {
instance_flags,
hoisted_staging_buffers: Vec::new(),
hoisted_buffer_barriers: Vec::new(),
written_shader_binding_data: Vec::new(),
}
}
@@ -462,6 +470,10 @@ impl PendingWrites {
.insert(blas.tracker_index(), blas.clone());
}
pub fn use_shader_binding_data(&mut self, sbd: &Arc<ray_tracing_pipeline::ShaderBindingData>) {
self.written_shader_binding_data.push(sbd.clone())
}
pub fn contains_buffer(&self, buffer: &Arc<Buffer>) -> bool {
self.dst_buffers.contains_key(&buffer.tracker_index())
}
@@ -604,6 +616,7 @@ impl PendingWrites {
let pending_buffers = mem::take(&mut self.dst_buffers);
let pending_textures = mem::take(&mut self.dst_textures);
let pending_blas_s = mem::take(&mut self.copied_blas_s);
let pending_shader_binding_data = mem::take(&mut self.written_shader_binding_data);
let cmd_buf = unsafe { self.command_encoder.end_encoding() }
.map_err(|e| device.handle_hal_error(e))?;
@@ -630,6 +643,7 @@ impl PendingWrites {
pending_buffers,
pending_textures,
pending_blas_s,
_pending_shader_binding_data: pending_shader_binding_data,
};
let staging_buffers = self.record_hoisted_barriers(&mut encoder, snatch_guard)?;
@@ -642,6 +656,7 @@ impl PendingWrites {
self.dst_buffers.clear();
self.dst_textures.clear();
self.copied_blas_s.clear();
self.written_shader_binding_data.clear();
Ok(None)
}
}
@@ -1830,6 +1845,7 @@ impl Queue {
pending_buffers: FastHashMap::default(),
pending_textures: FastHashMap::default(),
pending_blas_s: FastHashMap::default(),
_pending_shader_binding_data: Vec::new(),
});
}
}
@@ -2148,8 +2164,7 @@ impl Queue {
self.device.check_is_valid()?;
self.device
.require_features(wgpu_types::Features::EXPERIMENTAL_RAY_QUERY)?;
self.device.require_acceleration_structures()?;
blas.check_is_valid()?;
self.same_device_as(blas.as_ref())?;
+273 -5
View File
@@ -1,10 +1,13 @@
use alloc::{sync::Arc, vec::Vec};
use alloc::{string::ToString, sync::Arc, vec::Vec};
use core::mem::{size_of, ManuallyDrop};
use crate::device::stage_compiler::StageCompiler;
#[cfg(feature = "trace")]
use crate::device::trace::{Action, IntoTrace};
use crate::device::DeviceError;
use crate::resource::ResourceState;
use crate::device::{DeviceError, ENTRYPOINT_FAILURE_ERROR};
use crate::pipeline::CreatePipelineError;
use crate::ray_tracing_pipeline;
use crate::resource::{ParentDevice, ResourceState};
use crate::{
api_log,
device::Device,
@@ -21,6 +24,12 @@ use hal::AccelerationStructureTriangleIndices;
use wgt::{Features, AABB_GEOMETRY_MIN_STRIDE};
impl Device {
/// Requires any feature that allows acceleration structures as they can be provided by multiple extensions.
pub fn require_acceleration_structures(&self) -> Result<(), crate::device::MissingFeatures> {
self.require_features(Features::EXPERIMENTAL_RAY_QUERY)
.or_else(|_| self.require_features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES))
}
pub fn create_blas(
self: &Arc<Self>,
blas_desc: &resource::BlasDescriptor,
@@ -52,7 +61,7 @@ impl Device {
sizes: wgt::BlasGeometrySizeDescriptors,
) -> Result<Arc<resource::Blas>, CreateBlasError> {
self.check_is_valid()?;
self.require_features(Features::EXPERIMENTAL_RAY_QUERY)?;
self.require_acceleration_structures()?;
if blas_desc
.flags
@@ -262,7 +271,7 @@ impl Device {
desc: &resource::TlasDescriptor,
) -> Result<Arc<resource::Tlas>, CreateTlasError> {
self.check_is_valid()?;
self.require_features(Features::EXPERIMENTAL_RAY_QUERY)?;
self.require_acceleration_structures()?;
if desc.max_instances > self.limits.max_tlas_instance_count {
return Err(CreateTlasError::TooManyInstances(
@@ -343,6 +352,265 @@ impl Device {
label: desc.label.to_string(),
max_instance_count: desc.max_instances,
tracking_data: TrackingData::new(self.tracker_indices.tlas_s.clone()),
max_intersection_index: RwLock::new(rank::TLAS_MAX_INTERSECTION_IDX, None),
required_intersection_types: RwLock::new(
rank::TLAS_REQUIRED_INTERSECTION_TYPES,
Vec::new(),
),
}))
}
pub fn create_ray_tracing_pipeline(
self: &Arc<Self>,
desc: ray_tracing_pipeline::RayTracingPipelineDescriptor,
) -> (
Arc<ray_tracing_pipeline::RayTracingPipeline>,
Option<CreatePipelineError>,
) {
let (ray_tracing_pipeline, error) =
match self.create_ray_tracing_pipeline_inner(desc.clone()) {
Ok(ray_tracing_pipeline) => (ray_tracing_pipeline, None),
Err(error) => (
ray_tracing_pipeline::RayTracingPipeline::invalid(
self.clone(),
desc.label.to_string(),
),
Some(error),
),
};
#[cfg(feature = "trace")]
if let Some(ref mut trace) = *self.trace.lock() {
use crate::device::trace::IntoTrace;
trace.add(Action::CreateRayTracingPipeline {
id: ray_tracing_pipeline.to_trace(),
desc: desc.to_trace(),
});
}
(ray_tracing_pipeline, error)
}
pub fn create_ray_tracing_pipeline_inner(
self: &Arc<Self>,
desc: ray_tracing_pipeline::RayTracingPipelineDescriptor,
) -> Result<Arc<ray_tracing_pipeline::RayTracingPipeline>, CreatePipelineError> {
use crate::validation;
self.check_is_valid()?;
self.require_features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)?;
let io = validation::StageIo::default();
let is_auto_layout = desc.layout.is_none();
// Get the pipeline layout from the desc if it is provided.
let pipeline_layout = match desc.layout {
Some(pipeline_layout) => {
pipeline_layout.same_device(self)?;
Some(pipeline_layout)
}
None => None,
};
let mut compiler = StageCompiler::new(self, pipeline_layout.clone(), io, None);
let ray_generation = {
let stage = validation::ShaderStageForValidation::RayGeneration;
compiler.compile(&desc.ray_generation, stage)?
};
let miss = {
let stage = validation::ShaderStageForValidation::Miss;
compiler.compile(&desc.miss, stage)?
};
if desc.intersections.len() > 1 << 24 {
return Err(
ray_tracing_pipeline::RayTracingPipelineError::TooManyIntersectionGroups(
desc.intersections.len(),
)
.into(),
);
}
if desc.max_recursion_depth > self.limits.max_ray_recursion_depth {
return Err(
ray_tracing_pipeline::RayTracingPipelineError::TooHighRayRecursionDepth(
desc.max_recursion_depth,
self.limits.max_ray_recursion_depth,
)
.into(),
);
}
let mut intersections = Vec::with_capacity(desc.intersections.len());
let mut compiled_intersections = Vec::with_capacity(desc.intersections.len());
for intersection in &desc.intersections {
match intersection {
ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit,
any_hit,
} => {
let closest_hit = {
let stage =
validation::ShaderStageForValidation::ClosestHit { triangle: true };
compiler.compile(closest_hit, stage)?
};
let any_hit = match any_hit {
Some(any_hit) => {
let stage =
validation::ShaderStageForValidation::AnyHit { triangle: true };
Some(compiler.compile(any_hit, stage)?)
}
None => None,
};
compiled_intersections.push((closest_hit, any_hit));
}
}
}
for (closest_hit, any_hit) in compiled_intersections.iter() {
intersections.push(hal::RayObjectIntersectionState {
closest_hit: closest_hit.to_hal(),
any_hit: any_hit.as_ref().map(|any| any.to_hal()),
});
}
let StageCompiler { resources, .. } = compiler;
let pipeline_layout = match resources.layout {
validation::BindingLayoutSource::Provided(layout) => layout,
validation::BindingLayoutSource::Derived(entries) => {
self.create_derived_pipeline_layout(entries, resources.immediates.size())?
}
};
let late_sized_buffer_groups = Device::make_late_sized_buffer_groups(
&resources.minimum_binding_sizes,
&pipeline_layout,
);
let cache = match desc.cache {
Some(cache) => {
cache.same_device(self)?;
Some(cache)
}
None => None,
};
let raw = {
let pipeline_desc = hal::RayTracingPipelineDescriptor {
label: desc.label.to_hal(self.instance_flags),
layout: pipeline_layout.raw()?,
ray_generation: ray_generation.to_hal(),
miss: miss.to_hal(),
intersection: &intersections,
max_recursion_depth: desc.max_recursion_depth,
cache: cache.as_ref().map(|it| it.raw()).transpose()?,
};
unsafe { self.raw().create_ray_tracing_pipeline(&pipeline_desc) }.map_err(|err| {
match err {
hal::PipelineError::Device(error) => {
CreatePipelineError::Device(self.handle_hal_error(error))
}
hal::PipelineError::Linkage(stage, message) => {
CreatePipelineError::Internal { stage, message }
}
hal::PipelineError::EntryPoint(stage) => CreatePipelineError::Internal {
stage: hal::auxil::map_naga_stage(stage),
message: ENTRYPOINT_FAILURE_ERROR.to_string(),
},
hal::PipelineError::PipelineConstants(stage, message) => {
CreatePipelineError::PipelineConstants { stage, message }
}
}
})?
};
let (shader_modules, intersection_types) = {
let mut shader_modules = Vec::new();
shader_modules.push(desc.ray_generation.module.clone());
shader_modules.push(desc.miss.module.clone());
shader_modules.reserve(desc.intersections.len());
let mut intersection_types = Vec::with_capacity(desc.intersections.len());
for intersection in &desc.intersections {
match intersection {
ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit,
any_hit,
} => {
shader_modules.push(closest_hit.module.clone());
if let Some(any) = any_hit {
shader_modules.push(any.module.clone());
}
intersection_types
.push(ray_tracing_pipeline::RayTracingIntersectionType::Triangle);
}
}
}
(
shader_modules,
Arc::from(intersection_types.into_boxed_slice()),
)
};
// Won't panic because the length of `desc.intersections` is required to be below 2^24
// (see `CreateRayTracingPipelineError::TooManyIntersectionGroups`)
let shader_binding_data = match ray_tracing_pipeline::ShaderBindingData::from_raw_pipeline(
self.clone(),
raw.as_ref(),
desc.intersections.len(),
) {
Ok(sbd) => sbd,
Err(e) => {
// We need to destroy the raw ray tracing pipeline first.
unsafe { self.raw().destroy_ray_tracing_pipeline(raw) };
return Err(e);
}
};
let naga::valid::ImmediateUsage::Valid {
slots: immediate_slots_required,
size: _,
} = resources.immediates
else {
unreachable!("Immediates exceeding maxImmediateSize should have been rejected");
};
let pipeline = ray_tracing_pipeline::RayTracingPipeline {
state: ResourceState::Valid(ray_tracing_pipeline::RayTracingPipelineState {
raw: ManuallyDrop::new(raw),
layout: pipeline_layout.clone(),
_shader_modules: shader_modules,
shader_binding_data,
intersection_types,
}),
device: self.clone(),
late_sized_buffer_groups,
immediate_slots_required,
label: desc.label.to_string(),
tracking_data: TrackingData::new(self.tracker_indices.ray_tracing_pipelines.clone()),
};
let pipeline = Arc::new(pipeline);
if is_auto_layout {
for bgl in pipeline_layout.bind_group_layouts.iter() {
let Some(bgl) = bgl else {
continue;
};
// `bind_group_layouts` might contain duplicate entries, so we need to ignore the result.
let _ = bgl.exclusive_pipeline.set((&pipeline).into());
}
}
Ok(pipeline)
}
}
+7 -6
View File
@@ -1249,7 +1249,7 @@ impl Device {
.usage
.intersects(wgt::BufferUsages::BLAS_INPUT | wgt::BufferUsages::TLAS_INPUT)
{
self.require_features(wgt::Features::EXPERIMENTAL_RAY_QUERY)?;
self.require_acceleration_structures()?;
}
if desc.usage.contains(wgt::BufferUsages::INDEX)
@@ -2944,7 +2944,7 @@ impl Device {
/// Generate information about late-validated buffer bindings for pipelines.
//TODO: should this be combined with `get_introspection_bind_group_layouts` in some way?
fn make_late_sized_buffer_groups(
pub(super) fn make_late_sized_buffer_groups(
shader_binding_sizes: &FastHashMap<naga::ResourceBinding, wgt::BufferSize>,
layout: &binding_model::PipelineLayout,
) -> ArrayVec<pipeline::LateSizedBufferGroup, { hal::MAX_BIND_GROUPS }> {
@@ -3205,11 +3205,12 @@ impl Device {
)
}
Bt::AccelerationStructure { vertex_return } => {
self.require_features(wgt::Features::EXPERIMENTAL_RAY_QUERY)
.map_err(|e| CreateBindGroupLayoutError::Entry {
self.require_acceleration_structures().map_err(|e| {
CreateBindGroupLayoutError::Entry {
binding: entry.binding,
error: e.into(),
})?;
}
})?;
if vertex_return {
self.require_features(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN)
.map_err(|e| CreateBindGroupLayoutError::Entry {
@@ -4407,7 +4408,7 @@ impl Device {
Ok(layout)
}
fn create_derived_pipeline_layout(
pub(super) fn create_derived_pipeline_layout(
self: &Arc<Self>,
mut derived_group_layouts: Box<ArrayVec<bgl::EntryMap, { hal::MAX_BIND_GROUPS }>>,
immediate_size: u32,
+22
View File
@@ -171,6 +171,11 @@ pub enum Action<'a, R: ReferenceType> {
pipeline: PointerId<markers::ComputePipeline>,
index: u32,
},
GetRayTracingPipelineBindGroupLayout {
id: PointerId<markers::BindGroupLayout>,
pipeline: PointerId<markers::RayTracingPipeline>,
index: u32,
},
DropBindGroupLayout(PointerId<markers::BindGroupLayout>),
CreatePipelineLayout(
PointerId<markers::PipelineLayout>,
@@ -202,6 +207,11 @@ pub enum Action<'a, R: ReferenceType> {
desc: TraceGeneralRenderPipelineDescriptor<'a>,
},
DropRenderPipeline(PointerId<markers::RenderPipeline>),
CreateRayTracingPipeline {
id: PointerId<markers::RayTracingPipeline>,
desc: TraceRayTracingPipelineDescriptor<'a>,
},
DropRayTracingPipeline(PointerId<markers::RayTracingPipeline>),
CreatePipelineCache {
id: PointerId<markers::PipelineCache>,
desc: crate::pipeline::PipelineCacheDescriptor<'a>,
@@ -286,3 +296,15 @@ pub type TraceComputePipelineDescriptor<'a> = crate::pipeline::ComputePipelineDe
PointerId<markers::ShaderModule>,
PointerId<markers::PipelineCache>,
>;
/// Not a public API. For use by `player` only.
///
/// cbindgen:ignore
#[doc(hidden)]
pub type TraceRayTracingPipelineDescriptor<'a> =
crate::ray_tracing_pipeline::RayTracingPipelineDescriptor<
'a,
PointerId<markers::PipelineLayout>,
PointerId<markers::ShaderModule>,
PointerId<markers::PipelineCache>,
>;
+95 -4
View File
@@ -4,11 +4,12 @@ use std::io::Write as _;
use crate::{
command::{
ArcCommand, ArcComputeCommand, ArcReferences, ArcRenderCommand, BasePass, ColorAttachments,
Command, ComputeCommand, PassTimestampWrites, PointerReferences, RenderCommand,
RenderPassColorAttachment, ResolvedRenderPassDepthStencilAttachment,
ArcCommand, ArcComputeCommand, ArcRayTracingCommand, ArcReferences, ArcRenderCommand,
BasePass, ColorAttachments, Command, ComputeCommand, PassTimestampWrites,
PointerReferences, RayTracingCommand, RenderCommand, RenderPassColorAttachment,
ResolvedRenderPassDepthStencilAttachment,
},
device::trace::{Data, DataKind},
device::trace::{Data, DataKind, TraceRayTracingPipelineDescriptor},
id::{markers, PointerId},
storage::StorageItem,
};
@@ -273,6 +274,9 @@ impl IntoTrace for ArcCommand {
occlusion_query_set: occlusion_query_set.map(|q| q.to_trace()),
multiview_mask,
},
ArcCommand::RunRayTracingPass { pass } => Command::RunRayTracingPass {
pass: pass.into_trace(),
},
ArcCommand::BuildAccelerationStructures { blas, tlas } => {
Command::BuildAccelerationStructures {
blas: blas.into_iter().map(|b| b.into_trace()).collect(),
@@ -431,6 +435,7 @@ impl IntoTrace for crate::ray_tracing::OwnedTlasInstance<ArcReferences> {
transform: self.transform,
custom_data: self.custom_data,
mask: self.mask,
intersection_index: self.intersection_index,
}
}
}
@@ -654,6 +659,30 @@ impl IntoTrace for ArcRenderCommand {
}
}
impl IntoTrace for ArcRayTracingCommand {
type Output = RayTracingCommand<PointerReferences>;
fn into_trace(self) -> Self::Output {
use RayTracingCommand as C;
match self {
C::SetBindGroup {
index,
num_dynamic_offsets,
bind_group,
} => C::SetBindGroup {
index,
num_dynamic_offsets,
bind_group: bind_group.map(|bg| bg.into_trace()),
},
C::SetPipeline(id) => C::SetPipeline(id.into_trace()),
C::SetImmediate { offset, data } => C::SetImmediate { offset, data },
C::TraceRays(groups) => C::TraceRays(groups),
C::PushDebugGroup { color, len } => C::PushDebugGroup { color, len },
C::PopDebugGroup => C::PopDebugGroup,
C::InsertDebugMarker { color, len } => C::InsertDebugMarker { color, len },
}
}
}
impl IntoTrace for crate::binding_model::PipelineLayoutDescriptor<'_> {
type Output = crate::binding_model::PipelineLayoutDescriptor<
'static,
@@ -773,6 +802,34 @@ impl<'a> IntoTrace for crate::pipeline::ComputePipelineDescriptor<'a> {
}
}
impl<'a> IntoTrace for crate::ray_tracing_pipeline::RayTracingPipelineDescriptor<'a> {
type Output = TraceRayTracingPipelineDescriptor<'a>;
fn into_trace(self) -> Self::Output {
TraceRayTracingPipelineDescriptor {
label: self.label,
layout: self.layout.into_trace(),
ray_generation: self.ray_generation.into_trace(),
miss: self.miss.into_trace(),
intersections: self
.intersections
.into_iter()
.map(|intersection| match intersection {
crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit,
any_hit,
} => crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit: closest_hit.into_trace(),
any_hit: any_hit.map(|a| a.into_trace()),
},
})
.collect(),
cache: self.cache.map(|c| c.into_trace()),
max_recursion_depth: self.max_recursion_depth,
}
}
}
impl<'a> IntoTrace for crate::pipeline::ProgrammableStageDescriptor<'a> {
type Output =
crate::pipeline::ProgrammableStageDescriptor<'a, PointerId<markers::ShaderModule>>;
@@ -912,11 +969,21 @@ fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, Poi
pipeline,
index,
},
A::GetRayTracingPipelineBindGroupLayout {
id,
pipeline,
index,
} => A::GetRayTracingPipelineBindGroupLayout {
id,
pipeline,
index,
},
A::DropPipelineLayout(layout) => A::DropPipelineLayout(layout),
A::DropBindGroup(bind_group) => A::DropBindGroup(bind_group),
A::DropShaderModule(shader_module) => A::DropShaderModule(shader_module),
A::DropComputePipeline(pipeline) => A::DropComputePipeline(pipeline),
A::DropRenderPipeline(pipeline) => A::DropRenderPipeline(pipeline),
A::DropRayTracingPipeline(pipeline) => A::DropRayTracingPipeline(pipeline),
A::DropPipelineCache(cache) => A::DropPipelineCache(cache),
A::DropRenderBundle(render_bundle) => A::DropRenderBundle(render_bundle),
A::DestroyQuerySet(query_set) => A::DestroyQuerySet(query_set),
@@ -1143,6 +1210,30 @@ fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, Poi
cache: desc.cache,
},
},
A::CreateRayTracingPipeline { id, desc } => A::CreateRayTracingPipeline {
id,
desc: crate::ray_tracing_pipeline::RayTracingPipelineDescriptor {
label: owned_label(&desc.label),
layout: desc.layout,
ray_generation: owned_stage(desc.ray_generation),
miss: owned_stage(desc.miss),
intersections: desc
.intersections
.into_iter()
.map(|i| match i {
crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit,
any_hit,
} => crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
closest_hit: owned_stage(closest_hit),
any_hit: any_hit.map(owned_stage),
},
})
.collect::<Vec<_>>(),
max_recursion_depth: desc.max_recursion_depth,
cache: desc.cache,
},
},
A::CreatePipelineCache { id, desc } => A::CreatePipelineCache {
id,
desc: crate::pipeline::PipelineCacheDescriptor {
+1
View File
@@ -84,6 +84,7 @@ mod pipeline_cache;
mod pool;
pub mod present;
pub mod ray_tracing;
pub mod ray_tracing_pipeline;
pub mod resource;
mod snatch;
pub mod storage;
+4
View File
@@ -177,6 +177,8 @@ define_lock_ranks! {
TEXTURE_INITIALIZATION_STATUS,
TLAS_BUILT_INDEX,
TLAS_DEPENDENCIES,
TLAS_MAX_INTERSECTION_IDX,
TLAS_REQUIRED_INTERSECTION_TYPES,
}
rank COMMAND_BUFFER_DATA "CommandBuffer::data" followed by {
BUFFER_MAP_STATE,
@@ -250,6 +252,8 @@ define_lock_ranks! {
rank TEXTURE_CLEAR_MODE "Texture::clear_mode" followed by { }
rank TEXTURE_INITIALIZATION_STATUS "Texture::initialization_status" followed by { }
rank TEXTURE_VIEWS "Texture::views" followed by { }
rank TLAS_MAX_INTERSECTION_IDX "Tlas::max_intersection_index" followed by { }
rank TLAS_REQUIRED_INTERSECTION_TYPES "Tlas::required_intersection_types" followed by { }
#[cfg(test)]
rank PAWN "pawn" followed by { ROOK, BISHOP }
+4
View File
@@ -14,6 +14,7 @@ use thiserror::Error;
use wgt::error::{ErrorType, WebGpuError};
pub use crate::pipeline_cache::PipelineCacheValidationError;
use crate::ray_tracing_pipeline::RayTracingPipelineError;
use crate::{
api_log,
binding_model::{
@@ -482,6 +483,8 @@ pub enum CreatePipelineError {
InvalidResource(#[from] InvalidResourceError),
#[error(transparent)]
Render(#[from] RenderError),
#[error(transparent)]
RayTracing(#[from] RayTracingPipelineError),
}
impl From<ColorAttachmentError> for CreatePipelineError {
@@ -579,6 +582,7 @@ impl WebGpuError for CreatePipelineError {
Self::Internal { .. } => ErrorType::Internal,
Self::PipelineConstants { .. } => ErrorType::Validation,
Self::Render(e) => e.webgpu_error_type(),
Self::RayTracing(e) => e.webgpu_error_type(),
}
}
}
+45 -9
View File
@@ -176,10 +176,8 @@ pub enum BuildAccelerationStructureError {
#[error("Blas {0:?} build sizes require index buffer but none was provided")]
MissingIndexBuffer(ResourceErrorIdent),
#[error(
"Tlas {0:?} an associated instances contains an invalid custom index (more than 24bits)"
)]
TlasInvalidCustomIndex(ResourceErrorIdent),
#[error("Tlas {0:?} instance {1} contains an invalid custom data (more than 24bits)")]
TlasInvalidCustomData(ResourceErrorIdent, usize),
#[error(
"Tlas {0:?} has {1} active instances but only {2} are allowed as specified by the descriptor at creation"
@@ -209,6 +207,10 @@ pub enum BuildAccelerationStructureError {
#[error("Blas {0:?} AABB stride is invalid (must be >= {1} and a multiple of 8)")]
InvalidAabbStride(ResourceErrorIdent, BufferAddress),
#[error(
"Tlas {0:?} instance {1} contains an intersection index {2} which is greater than 2^24 - 1"
)]
TlasInvalidIntersectionIndex(ResourceErrorIdent, usize, u32),
}
impl WebGpuError for BuildAccelerationStructureError {
@@ -237,11 +239,12 @@ impl WebGpuError for BuildAccelerationStructureError {
| Self::DifferentBlasIndexFormats(..)
| Self::CompactedBlas(..)
| Self::MissingIndexBuffer(..)
| Self::TlasInvalidCustomIndex(..)
| Self::TlasInvalidCustomData(..)
| Self::TlasInstanceCountExceeded(..)
| Self::TransformMissing(..)
| Self::UseTransformMissing(..)
| Self::TlasDependentMissingVertexReturn(..)
| Self::TlasInvalidIntersectionIndex(..)
| Self::BlasGeometryKindMismatch(..)
| Self::IncompatibleBlasAabbPrimitiveCount(..)
| Self::UnalignedAabbPrimitiveOffset(..)
@@ -263,15 +266,28 @@ pub enum ValidateAsActionsError {
#[error("Blas {0:?} is newer than the containing Tlas {1:?}")]
BlasNewerThenTlas(ResourceErrorIdent, ResourceErrorIdent),
#[error("Tlas {0:?} has an intersection index {1:?} out of bounds of the length of the intersection array {2:?}")]
TlasIntersectionInvalid(ResourceErrorIdent, u32, u32),
#[error("An instance of Tlas {0:?} requires an intersection type of {1:?} for index {2}, but got {3:?}")]
TlasInstancesIntersectionIndicesDiffer(
ResourceErrorIdent,
crate::ray_tracing_pipeline::RayTracingIntersectionType,
u32,
Option<crate::ray_tracing_pipeline::RayTracingIntersectionType>,
),
}
impl WebGpuError for ValidateAsActionsError {
fn webgpu_error_type(&self) -> ErrorType {
match self {
Self::DestroyedResource(e) => e.webgpu_error_type(),
Self::UsedUnbuiltTlas(..) | Self::UsedUnbuiltBlas(..) | Self::BlasNewerThenTlas(..) => {
ErrorType::Validation
}
Self::UsedUnbuiltTlas(..)
| Self::UsedUnbuiltBlas(..)
| Self::BlasNewerThenTlas(..)
| Self::TlasIntersectionInvalid(..)
| Self::TlasInstancesIntersectionIndicesDiffer(..) => ErrorType::Validation,
}
}
}
@@ -320,6 +336,7 @@ pub struct TlasInstance<'a, Blas = Arc<resource::Blas>> {
pub transform: &'a [f32; 12],
pub custom_data: u32,
pub mask: u8,
pub intersection_index: u32,
}
pub struct TlasPackage<'a, Tlas = Arc<resource::Tlas>, Blas = Arc<resource::Blas>> {
@@ -332,6 +349,8 @@ pub struct TlasPackage<'a, Tlas = Arc<resource::Tlas>, Blas = Arc<resource::Blas
pub(crate) struct TlasBuild {
pub tlas: Arc<Tlas>,
pub dependencies: Vec<Arc<Blas>>,
pub max_intersection_idx: Option<u32>,
pub required_intersection_types: Vec<resource::TlasIntersectionType>,
}
#[derive(Debug, Clone, Default)]
@@ -352,7 +371,23 @@ impl AsBuild {
#[derive(Debug, Clone)]
pub(crate) enum AsAction {
Build(AsBuild),
UseTlas(Arc<Tlas>),
/// A [`Tlas`] has been bound and used by any pass. The [`Blas`]es it
/// was built with must be validated to have not been built after the
/// [`Tlas`] as backends have undefined behaviour on this (it would
/// cause AABBs to be incorrect, etc.)
BindTlas(Arc<Tlas>),
/// A [`RayTracingPipeline`] has had a `trace_rays` call on it.
/// This [`Tlas`] has been put in a bindgroup, and so the validation
/// must ensure that the maximum intersection index in the [`Tlas`] is
/// less than the length of the intersection group array and that the
/// types of the [`Blas`]es are the same as those of the
/// [`RayTracingPipeline`].
///
/// [`RayTracingPipeline`]: crate::ray_tracing_pipeline::RayTracingPipeline
TraceTlas(
Arc<Tlas>,
Arc<[crate::ray_tracing_pipeline::RayTracingIntersectionType]>,
),
}
/// Like [`BlasTriangleGeometry`], but with owned data.
@@ -407,6 +442,7 @@ pub struct OwnedTlasInstance<R: ReferenceType> {
pub transform: [f32; 12],
pub custom_data: u32,
pub mask: u8,
pub intersection_index: u32,
}
pub type ArcTlasInstance = OwnedTlasInstance<ArcReferences>;
+369
View File
@@ -0,0 +1,369 @@
use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
use core::{mem::ManuallyDrop, num::NonZeroU64};
use hal::BufferDescriptor;
use arrayvec::ArrayVec;
use thiserror::Error;
use wgt::error::{ErrorType, WebGpuError};
use crate::pipeline::{
CreatePipelineError, LateSizedBufferGroup, PipelineCache, ProgrammableStageDescriptor,
ShaderModule,
};
use crate::{
binding_model::{BindGroupLayout, GetBindGroupLayoutError, PipelineLayout},
device::Device,
resource::{InvalidResourceError, Labeled, ResourceState, TrackingData},
resource_log, Label,
};
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum RayTracingPipelineError {
#[error("The number of intersection shaders {0} is greater than 2^24")]
TooManyIntersectionGroups(usize),
#[error(
"The ray recursion depth {0} is greater than the limit Limits::max_ray_recursion_depth {1}"
)]
TooHighRayRecursionDepth(u32, u32),
}
impl WebGpuError for RayTracingPipelineError {
fn webgpu_error_type(&self) -> ErrorType {
match self {
Self::TooManyIntersectionGroups(..) | Self::TooHighRayRecursionDepth(..) => {
ErrorType::Validation
}
}
}
}
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RayTracingIntersectionDescriptor<'a, SM = Arc<ShaderModule>> {
Triangle {
closest_hit: ProgrammableStageDescriptor<'a, SM>,
any_hit: Option<ProgrammableStageDescriptor<'a, SM>>,
},
}
/// Describes a ray tracing pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RayTracingPipelineDescriptor<
'a,
PLL = Arc<PipelineLayout>,
SM = Arc<ShaderModule>,
PLC = Arc<PipelineCache>,
> {
pub label: Label<'a>,
/// The layout of bind groups for this pipeline.
pub layout: Option<PLL>,
/// The ray generation stage descriptor
pub ray_generation: ProgrammableStageDescriptor<'a, SM>,
/// The miss stage descriptor
pub miss: ProgrammableStageDescriptor<'a, SM>,
/// All the descriptors for intersection functions
pub intersections: Vec<RayTracingIntersectionDescriptor<'a, SM>>,
/// The maximum number of nested `traceRay` calls. The ray generation stage is at depth 0.
pub max_recursion_depth: u32,
/// The pipeline cache to use when creating this pipeline.
pub cache: Option<PLC>,
}
/// The type of intersection of a index into `RayTracingPipelineDescriptor::intersections`
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum RayTracingIntersectionType {
/// The intersection is to be used for triangles.
Triangle,
/// The intersection is to be used for AABBs.
AABB,
}
/// Metal's shader binding data is opaque, but Vulkan's and DX12's has opaque data
/// but a non-opaque storage mechanism, so each require separate codepaths.
/// Therefore, this is a semi-opaque structure because if metal gets ray tracing pipelines,
/// this will need to turn into an enum so it shouldn't have other code
/// tangled with it.
#[derive(Debug)]
pub struct ShaderBindingData {
pub(crate) raw: ManuallyDrop<Box<dyn hal::DynBuffer>>,
pub(crate) device: Arc<Device>,
pub(crate) num_intersection_groups: u32,
pub(crate) miss_offset: wgt::BufferAddress,
pub(crate) intersection_offset: wgt::BufferAddress,
}
impl ShaderBindingData {
/// Panics if `num_intersection_groups` is above u32::MAX
pub(crate) fn from_raw_pipeline(
device: Arc<Device>,
pipeline: &dyn hal::DynRayTracingPipeline,
num_intersection_groups: usize,
) -> Result<Arc<Self>, CreatePipelineError> {
let mut base_data = Vec::new();
let ray_generation_data = unsafe {
device
.raw()
.get_raytracing_pipeline_group_data(pipeline, 0..1)
}
.map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?;
base_data.extend_from_slice(&ray_generation_data);
let padded_miss_offset = (base_data.len() as wgt::BufferAddress).next_multiple_of(
device.alignments.ray_tracing_pipeline_data_offset_alignment as wgt::BufferAddress,
);
base_data.resize(padded_miss_offset as _, 0);
let miss_data = unsafe {
device
.raw()
.get_raytracing_pipeline_group_data(pipeline, 1..2)
}
.map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?;
base_data.extend_from_slice(&miss_data);
let padded_intersection_offset = (base_data.len() as wgt::BufferAddress).next_multiple_of(
device.alignments.ray_tracing_pipeline_data_offset_alignment as wgt::BufferAddress,
);
base_data.resize(padded_intersection_offset as _, 0);
if num_intersection_groups != 0 {
let intersection_data = unsafe {
device.raw().get_raytracing_pipeline_group_data(
pipeline,
2..(2 + num_intersection_groups as u32),
)
}
.map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?;
base_data.extend_from_slice(&intersection_data);
}
// Don't need the exact allocated size as it will be grater than this.
let (buffer, _) = unsafe {
device.raw().create_buffer(&BufferDescriptor {
label: None,
size: base_data.len() as _,
usage: wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA
| wgt::BufferUses::COPY_DST,
memory_flags: hal::MemoryFlags::PREFER_COHERENT,
})
}
.map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?;
let sbd = Arc::new(Self {
raw: ManuallyDrop::new(buffer),
device: device.clone(),
num_intersection_groups: u32::try_from(num_intersection_groups).unwrap(),
miss_offset: padded_miss_offset,
intersection_offset: padded_intersection_offset,
});
// If there is no queue anymore, the ray tracing pipeline can't be accessed, so we don't have to worry about UB from uninitialized values
if let Some(queue) = device.get_queue() {
let mut staging = crate::resource::StagingBuffer::new(
&device,
NonZeroU64::new(base_data.len() as _).expect(
"The total number of groups is always greater than zero, \
and `ray_tracing_pipeline_group_data_size` must be too.",
),
)?;
staging.write_exact(&base_data);
let staging_buf = staging.flush();
let mut writes = queue.pending_writes.lock();
let encoder = writes.activate();
unsafe {
encoder.transition_buffers(&[
hal::BufferBarrier {
buffer: staging_buf.raw(),
usage: hal::StateTransition {
from: wgt::BufferUses::MAP_WRITE,
to: wgt::BufferUses::COPY_SRC,
},
},
hal::BufferBarrier {
buffer: sbd.raw.as_ref(),
usage: hal::StateTransition {
from: wgt::BufferUses::empty(),
to: wgt::BufferUses::COPY_DST,
},
},
]);
encoder.copy_buffer_to_buffer(
staging_buf.raw(),
sbd.raw.as_ref(),
&[hal::BufferCopy {
src_offset: 0,
dst_offset: 0,
size: NonZeroU64::new(base_data.len() as _)
.expect("Already checked size isn't zero."),
}],
);
encoder.transition_buffers(&[hal::BufferBarrier {
buffer: sbd.raw.as_ref(),
usage: hal::StateTransition {
from: wgt::BufferUses::COPY_DST,
to: wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA,
},
}]);
};
writes.consume(staging_buf);
writes.use_shader_binding_data(&sbd);
}
Ok(sbd)
}
}
impl Drop for ShaderBindingData {
fn drop(&mut self) {
// SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
unsafe {
self.device.raw().destroy_buffer(raw);
}
}
}
#[derive(Debug)]
pub(crate) struct RayTracingPipelineState {
pub(crate) raw: ManuallyDrop<Box<dyn hal::DynRayTracingPipeline>>,
pub(crate) layout: Arc<PipelineLayout>,
pub(crate) shader_binding_data: Arc<ShaderBindingData>,
pub(crate) _shader_modules: Vec<Arc<ShaderModule>>,
pub(crate) intersection_types: Arc<[RayTracingIntersectionType]>,
}
#[derive(Debug)]
pub struct RayTracingPipeline {
pub(crate) state: ResourceState<RayTracingPipelineState>,
pub(crate) device: Arc<Device>,
pub(crate) late_sized_buffer_groups: ArrayVec<LateSizedBufferGroup, { hal::MAX_BIND_GROUPS }>,
pub(crate) immediate_slots_required: naga::valid::ImmediateSlots,
/// The `label` from the descriptor used to create the resource.
pub(crate) label: String,
pub(crate) tracking_data: TrackingData,
}
impl Drop for RayTracingPipeline {
fn drop(&mut self) {
resource_log!("Destroy raw {}", self.error_ident());
#[cfg(feature = "trace")]
{
use crate::device::trace;
if let Some(t) = self.device.trace.lock().as_mut() {
t.add(trace::Action::DropRayTracingPipeline(unsafe {
trace::to_trace(self)
}));
}
}
let ResourceState::Valid(state) = &mut self.state else {
return;
};
// SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
let raw = unsafe { ManuallyDrop::take(&mut state.raw) };
unsafe {
self.device.raw().destroy_ray_tracing_pipeline(raw);
}
}
}
crate::impl_resource_type!(RayTracingPipeline);
crate::impl_labeled!(RayTracingPipeline);
crate::impl_parent_device!(RayTracingPipeline);
crate::impl_storage_item!(RayTracingPipeline);
crate::impl_trackable!(RayTracingPipeline);
impl RayTracingPipeline {
pub(crate) fn raw(&self) -> Result<&dyn hal::DynRayTracingPipeline, InvalidResourceError> {
let ResourceState::Valid(state) = &self.state else {
return Err(InvalidResourceError(self.error_ident()));
};
Ok(state.raw.as_ref())
}
pub(crate) fn invalid(device: Arc<Device>, label: String) -> Arc<Self> {
Arc::new(Self {
tracking_data: TrackingData::new(device.tracker_indices.ray_tracing_pipelines.clone()),
state: ResourceState::Invalid,
device,
immediate_slots_required: naga::valid::ImmediateSlots::default(),
late_sized_buffer_groups: ArrayVec::new(),
label,
})
}
pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
let ResourceState::Valid(_) = &self.state else {
return Err(InvalidResourceError(self.error_ident()));
};
Ok(())
}
pub(crate) fn layout(&self) -> Result<&Arc<PipelineLayout>, InvalidResourceError> {
let ResourceState::Valid(state) = &self.state else {
return Err(InvalidResourceError(self.error_ident()));
};
Ok(&state.layout)
}
pub(crate) fn shader_binding_data(&self) -> Result<&ShaderBindingData, InvalidResourceError> {
let ResourceState::Valid(state) = &self.state else {
return Err(InvalidResourceError(self.error_ident()));
};
Ok(&state.shader_binding_data)
}
pub(crate) fn intersection_types(
&self,
) -> Result<&Arc<[RayTracingIntersectionType]>, InvalidResourceError> {
let ResourceState::Valid(state) = &self.state else {
return Err(InvalidResourceError(self.error_ident()));
};
Ok(&state.intersection_types)
}
pub fn get_bind_group_layout_inner(
self: &Arc<Self>,
index: u32,
) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
self.layout()?.get_bind_group_layout(index, self.into())
}
pub fn get_bind_group_layout(
self: &Arc<Self>,
index: u32,
) -> (Arc<BindGroupLayout>, Option<GetBindGroupLayoutError>) {
let (bgl, error) = match self.get_bind_group_layout_inner(index) {
Ok(bgl) => (bgl, None),
Err(e) => (
BindGroupLayout::invalid(&self.device, String::new()),
Some(e),
),
};
#[cfg(feature = "trace")]
if let Some(ref mut trace) = *self.device.trace.lock() {
use crate::device::trace;
use trace::IntoTrace;
trace.add(trace::Action::GetRayTracingPipelineBindGroupLayout {
id: bgl.to_trace(),
pipeline: self.to_trace(),
index,
});
};
(bgl, error)
}
}
+15
View File
@@ -3714,6 +3714,12 @@ crate::impl_parent_device!(Blas);
crate::impl_storage_item!(Blas);
crate::impl_trackable!(Blas);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct TlasIntersectionType {
pub(crate) index: u32,
pub(crate) required_intersection_ty: crate::ray_tracing_pipeline::RayTracingIntersectionType,
}
#[derive(Debug)]
pub(crate) struct TlasState {
pub(crate) raw: Snatchable<Box<dyn hal::DynAccelerationStructure>>,
@@ -3730,9 +3736,13 @@ pub struct Tlas {
pub(crate) update_mode: wgt::AccelerationStructureUpdateMode,
pub(crate) built_index: RwLock<Option<NonZeroU64>>,
pub(crate) dependencies: RwLock<Vec<Arc<Blas>>>,
pub(crate) max_intersection_index: RwLock<Option<u32>>,
/// The `label` from the descriptor used to create the resource.
pub(crate) label: String,
pub(crate) tracking_data: TrackingData,
/// The intersections that are required to be of a certain type
/// if using a ray tracing pipeline.
pub(crate) required_intersection_types: RwLock<Vec<TlasIntersectionType>>,
}
impl Drop for Tlas {
@@ -3787,6 +3797,11 @@ impl Tlas {
built_index: RwLock::new(rank::TLAS_BUILT_INDEX, None),
dependencies: RwLock::new(rank::TLAS_DEPENDENCIES, Vec::new()),
device,
max_intersection_index: RwLock::new(rank::TLAS_MAX_INTERSECTION_IDX, None),
required_intersection_types: RwLock::new(
rank::TLAS_REQUIRED_INTERSECTION_TYPES,
Vec::new(),
),
})
}
}
+5 -1
View File
@@ -106,7 +106,7 @@ mod texture;
use crate::{
binding_model, command,
lock::{rank, Mutex},
pipeline,
pipeline, ray_tracing_pipeline,
resource::{self, Labeled, RawResourceAccess, ResourceErrorIdent, Trackable},
snatch::SnatchGuard,
track::blas::BlasTracker,
@@ -232,6 +232,7 @@ pub(crate) struct TrackerIndexAllocators {
pub bind_groups: Arc<SharedTrackerIndexAllocator>,
pub compute_pipelines: Arc<SharedTrackerIndexAllocator>,
pub render_pipelines: Arc<SharedTrackerIndexAllocator>,
pub ray_tracing_pipelines: Arc<SharedTrackerIndexAllocator>,
pub bundles: Arc<SharedTrackerIndexAllocator>,
pub query_sets: Arc<SharedTrackerIndexAllocator>,
pub blas_s: Arc<SharedTrackerIndexAllocator>,
@@ -248,6 +249,7 @@ impl TrackerIndexAllocators {
bind_groups: Arc::new(SharedTrackerIndexAllocator::new()),
compute_pipelines: Arc::new(SharedTrackerIndexAllocator::new()),
render_pipelines: Arc::new(SharedTrackerIndexAllocator::new()),
ray_tracing_pipelines: Arc::new(SharedTrackerIndexAllocator::new()),
bundles: Arc::new(SharedTrackerIndexAllocator::new()),
query_sets: Arc::new(SharedTrackerIndexAllocator::new()),
blas_s: Arc::new(SharedTrackerIndexAllocator::new()),
@@ -648,6 +650,7 @@ pub(crate) struct Tracker {
pub compute_pipelines: StatelessTracker<pipeline::ComputePipeline>,
pub render_pipelines: StatelessTracker<pipeline::RenderPipeline>,
pub ray_tracing_pipelines: StatelessTracker<ray_tracing_pipeline::RayTracingPipeline>,
pub bundles: StatelessTracker<command::RenderBundle>,
pub query_sets: QuerySetTracker,
}
@@ -666,6 +669,7 @@ impl Tracker {
bind_groups: StatelessTracker::new(),
compute_pipelines: StatelessTracker::new(),
render_pipelines: StatelessTracker::new(),
ray_tracing_pipelines: StatelessTracker::new(),
bundles: StatelessTracker::new(),
query_sets: QuerySetTracker::new(),
}
+158 -2
View File
@@ -4,7 +4,7 @@ use alloc::{
sync::Arc,
vec::Vec,
};
use core::fmt;
use core::{fmt, num::NonZeroU32};
use arrayvec::ArrayVec;
use hashbrown::hash_map::Entry;
@@ -362,6 +362,9 @@ struct EntryPoint {
/// Size of the immediate data, and which slots this entry point uses.
immediate_usage: naga::valid::ImmediateUsage,
/// The payload for ray tracing, if this is a ray tracing stage.
ray_tracing_payload: Option<RayTracingPayloadType>,
}
#[derive(Debug, Hash, PartialEq, Eq)]
@@ -376,6 +379,91 @@ impl hashbrown::Equivalent<EntryPointKey> for EntryPointKeyRef<'_> {
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
/// An enum containing the types allowed in a ray tracing payload, to be
/// stored in the interface so various shaders can be checked that they
/// all have the same types. Roughly equal to naga's type inner, but without names,
pub enum RayTracingPayloadType {
/// A single numeric type.
Numeric(NumericType),
/// A struct containing other payload types
Struct {
/// The members of the struct and their offset
members: Vec<RayTracingPayloadMember>,
/// The span of the struct
span: u32,
},
/// An array containing other payload types
Array {
/// The type the array contains within itself
inner: Box<RayTracingPayloadType>,
/// The size of the array, (non-override, non-dynamic).
size: NonZeroU32,
/// The stride of each element in the array.
stride: u32,
},
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RayTracingPayloadMember {
offset: u32,
ty: Box<RayTracingPayloadType>,
}
impl RayTracingPayloadType {
pub fn from_naga(ty: &naga::TypeInner, module: &naga::Module) -> Option<Self> {
Some(match ty {
naga::TypeInner::Scalar(scalar) => Self::Numeric(NumericType {
dim: NumericDimension::Scalar,
scalar: *scalar,
}),
naga::TypeInner::Vector { size, scalar } => Self::Numeric(NumericType {
dim: NumericDimension::Vector(*size),
scalar: *scalar,
}),
naga::TypeInner::Matrix {
columns,
rows,
scalar,
} => Self::Numeric(NumericType {
dim: NumericDimension::Matrix(*columns, *rows),
scalar: *scalar,
}),
naga::TypeInner::Struct { members, span } => {
let mut struct_members = Vec::with_capacity(members.len());
for member in members {
let ty = &module.types[member.ty].inner;
struct_members.push(RayTracingPayloadMember {
offset: member.offset,
ty: Box::new(Self::from_naga(ty, module)?),
});
}
Self::Struct {
members: struct_members,
span: *span,
}
}
naga::TypeInner::Array {
base,
size: naga::ArraySize::Constant(size),
stride,
} => {
let ty = &module.types[*base].inner;
Self::Array {
inner: Box::new(Self::from_naga(ty, module)?),
size: *size,
stride: *stride,
}
}
_ => return None,
})
}
}
/// A summary of the [shader interfaces][si] of the entry points in a [`naga::Module`].
///
/// [si]: https://www.w3.org/TR/WGSL/#shader-interface
@@ -633,6 +721,8 @@ pub enum StageError {
MeshTopologyMismatch,
#[error("Pipeline layout immediate size ({layout}) must be >= the required immediate size ({required}) of the shader entry point")]
LayoutImmediateSize { layout: u32, required: u32 },
#[error("Ray tracing payloads do not match.")]
RayTracingPayloadMismatch,
}
impl WebGpuError for StageError {
@@ -674,7 +764,8 @@ impl WebGpuError for StageError {
| Self::MissingFragDepthAttachment
| Self::PerVertexNotTriangles
| Self::MeshTopologyMismatch
| Self::LayoutImmediateSize { .. } => ErrorType::Validation,
| Self::LayoutImmediateSize { .. }
| Self::RayTracingPayloadMismatch => ErrorType::Validation,
}
}
}
@@ -1220,6 +1311,7 @@ pub struct StageIo {
///
/// This is `None` if the prior stage was not a mesh shader.
pub primitive_index: Option<bool>,
pub ray_tracing_payload: Option<RayTracingPayloadType>,
}
impl Interface {
@@ -1514,6 +1606,34 @@ impl Interface {
);
}
// Set the payload if there is an incoming payload set and it is a shader that should have one.
if matches!(
entry_point.stage,
naga::ShaderStage::ClosestHit | naga::ShaderStage::AnyHit | naga::ShaderStage::Miss
) {
let ray_payload = entry_point
.incoming_ray_payload
.expect("these stages must have an incoming payload");
let ty = module.global_variables[ray_payload].ty;
ep.ray_tracing_payload = Some(
RayTracingPayloadType::from_naga(&module.types[ty].inner, module)
.expect("naga should already validate invalid payloads out!"),
);
}
// Or if a payload global variable is used and it is a ray gen shader which doesn't have incoming
// payloads. This may not have a payload if it dispatches no trace rays which should be fine
else if matches!(entry_point.stage, naga::ShaderStage::RayGeneration) {
for (handle, gv) in module.global_variables.iter() {
if !func_info[handle].is_empty() && gv.space == naga::AddressSpace::RayPayload {
ep.ray_tracing_payload = Some(
RayTracingPayloadType::from_naga(&module.types[gv.ty].inner, module)
.expect("naga should already validate invalid payloads out!"),
);
}
}
}
entry_points.insert(
EntryPointKey(entry_point.stage, entry_point.name.clone()),
ep,
@@ -2112,6 +2232,25 @@ impl Interface {
*immediates = immediate_usage;
let mut ray_tracing_payload = inputs.ray_tracing_payload;
let current_ray_payload = entry_point.ray_tracing_payload.clone();
if let (Some(ray_tracing_payload), Some(current_ray_payload)) =
(ray_tracing_payload.as_ref(), current_ray_payload.as_ref())
{
if ray_tracing_payload != current_ray_payload {
return Err(StageError::RayTracingPayloadMismatch);
}
}
// We've just checked that if there was previously a payload, it is the same as
// the current payload (if any), so the two must be the same if both `Some`, so
// this doesn't go over any validation.
if let Some(current_ray_payload) = current_ray_payload {
ray_tracing_payload = Some(current_ray_payload)
}
Ok(StageIo {
task_payload_size: entry_point.task_payload_size,
varyings: outputs,
@@ -2120,6 +2259,7 @@ impl Interface {
} else {
None
},
ray_tracing_payload,
})
}
}
@@ -2252,6 +2392,14 @@ pub enum ShaderStageForValidation {
},
Compute,
Task,
RayGeneration,
Miss,
ClosestHit {
triangle: bool,
},
AnyHit {
triangle: bool,
},
}
impl ShaderStageForValidation {
@@ -2262,6 +2410,10 @@ impl ShaderStageForValidation {
Self::Fragment { .. } => naga::ShaderStage::Fragment,
Self::Compute => naga::ShaderStage::Compute,
Self::Task => naga::ShaderStage::Task,
Self::RayGeneration => naga::ShaderStage::RayGeneration,
Self::Miss => naga::ShaderStage::Miss,
Self::AnyHit { .. } => naga::ShaderStage::AnyHit,
Self::ClosestHit { .. } => naga::ShaderStage::ClosestHit,
}
}
@@ -2272,6 +2424,10 @@ impl ShaderStageForValidation {
Self::Fragment { .. } => wgt::ShaderStages::FRAGMENT,
Self::Compute => wgt::ShaderStages::COMPUTE,
Self::Task => wgt::ShaderStages::TASK,
Self::RayGeneration => wgt::ShaderStages::RAY_GENERATION,
Self::Miss => wgt::ShaderStages::MISS,
Self::AnyHit { .. } => wgt::ShaderStages::ANY_HIT,
Self::ClosestHit { .. } => wgt::ShaderStages::CLOSEST_HIT,
}
}
}
+1
View File
@@ -2531,6 +2531,7 @@ impl super::Instance {
.map(|maintenance_5| maintenance_5.depth_stencil_swizzle_one_support == vk::TRUE)
.unwrap_or(false),
ray_tracing_pipeline_group_data_size: alignments.ray_tracing_pipeline_group_data_size,
shader_binding_table_alignment: alignments.ray_tracing_pipeline_data_offset_alignment,
store_op_none: phd_capabilities.device_api_version >= vk::API_VERSION_1_3
|| (phd_capabilities.device_api_version >= vk::API_VERSION_1_2
&& phd_capabilities.supports_extension(khr::dynamic_rendering::NAME))
+4
View File
@@ -705,6 +705,10 @@ pub fn map_buffer_usage_to_barrier(
stages |= vk::PipelineStageFlags::TRANSFER;
access |= vk::AccessFlags::TRANSFER_WRITE;
}
if usage.contains(wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA) {
stages |= vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR;
access |= vk::AccessFlags::SHADER_READ;
}
(stages, access)
}
+9
View File
@@ -1056,6 +1056,15 @@ impl crate::Device for super::Device {
.max(self.shared.private_caps.scratch_buffer_alignment as u64);
}
if desc
.usage
.contains(wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA)
{
requirements.alignment = requirements
.alignment
.max(self.shared.private_caps.shader_binding_table_alignment as u64);
}
let allocation = self
.mem_allocator
.allocate(
+4
View File
@@ -520,6 +520,10 @@ struct PrivateCapabilities {
/// require an unnecessary parameter.
ray_tracing_pipeline_group_data_size: u32,
/// `shaderGroupBaseAlignment`. Shader binding table regions must start at a device
/// address that is a multiple of this, so shader binding table buffers use it as their alignment.
shader_binding_table_alignment: u32,
/// Whether `VK_ATTACHMENT_STORE_OP_NONE` is supported. This includes:
/// - `VK_ATTACHMENT_STORE_OP_NONE` provided by `VK_VERSION_1_3`.
/// - `VK_ATTACHMENT_STORE_OP_NONE_KHR` provided by `VK_KHR_dynamic_rendering`, or `VK_KHR_load_store_op_none` (promoted to Vulkan 1.4).
-4
View File
@@ -362,14 +362,10 @@ pub struct Limits {
/// The maximum total number (`x*y*z`) of rays able to be dispatched by a trace rays call in a ray
/// tracing pass. Requesting more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`]
/// is enabled.
///
/// Currently only affects wgpu-hal
pub max_ray_dispatch_count: u32,
/// The maximum number that one can pass into a ray tracing pipeline creation to be the maximum ray
/// recursion depth. (the maximum of the max ray recursion depth) Requesting more than 0 during device
/// creation only makes sense if [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`] is enabled.
///
/// Currently only affects wgpu-hal
pub max_ray_recursion_depth: u32,
}
+2
View File
@@ -56,9 +56,11 @@ ids! {
pub type CommandBuffer;
pub type RenderPassEncoder;
pub type ComputePassEncoder;
pub type RayTracingPassEncoder;
pub type RenderBundleEncoder;
pub type RenderBundle;
pub type QuerySet;
pub type Blas;
pub type Tlas;
pub type RayTracingPipeline;
}
+16 -1
View File
@@ -65,6 +65,13 @@ pub struct TlasInstance {
/// Mask for the instance used inside the shader to filter instances.
/// Reports hit only if `(shader_cull_mask & tlas_instance.mask) != 0u`.
pub mask: u8,
/// Intersection group index into a ray tracing pipeline. Must be less than the number of intersection groups in any ray tracing
/// pipeline a tlas built with this is used for. This can be read in ray queries. If this field is non-zero,
/// [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`] must be enabled. This must only use the lower 24 bits, if any bits are
/// outside that range (byte 4 does not equal 0) the TlasInstance becomes invalid and generates a validation error when built.
///
/// [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES
pub intersection_index: u32,
}
impl TlasInstance {
@@ -73,18 +80,26 @@ impl TlasInstance {
/// - transform: Transform buffer offset in bytes (optional, required if transform buffer is present)
/// - custom_data: Custom index for the instance used inside the shader (max 24 bits)
/// - mask: Mask for the instance used inside the shader to filter instances
/// - intersection_index: Either an index into an intersection group in a ray tracing pipeline or data for ray queries
///
/// Note: while one of these contains a reference to a BLAS that BLAS will not be dropped,
/// but it can still be destroyed. Destroying a BLAS that is referenced by one or more
/// TlasInstance(s) will immediately make them invalid. If one or more of those invalid
/// TlasInstances is inside a TlasPackage that is attempted to be built, the build will
/// generate a validation error.
pub fn new(blas: &Blas, transform: [f32; 12], custom_data: u32, mask: u8) -> Self {
pub fn new(
blas: &Blas,
transform: [f32; 12],
custom_data: u32,
mask: u8,
intersection_index: u32,
) -> Self {
Self {
blas: blas.inner.clone(),
transform,
custom_data,
mask,
intersection_index,
}
}
+22
View File
@@ -107,6 +107,28 @@ impl CommandEncoder {
}
}
/// Begins recording of a ray tracing pass.
///
/// This function returns a [`RayTracingPass`] object which records a single ray tracing pass.
///
/// As long as the returned [`RayTracingPass`] has not ended,
/// any mutating operation on this command encoder causes an error and invalidates it.
/// Note that the `'encoder` lifetime relationship protects against this,
/// but it is possible to opt out of it by calling [`RayTracingPass::forget_lifetime`].
/// This can be useful for runtime handling of the encoder->pass
/// dependency e.g. when pass and encoder are stored in the same data structure.
pub fn begin_ray_tracing_pass<'encoder>(
&'encoder mut self,
desc: &RayTracingPassDescriptor<'_>,
) -> RayTracingPass<'encoder> {
let rtpass = self.inner.begin_ray_tracing_pass(desc);
RayTracingPass {
inner: rtpass,
actions: Arc::clone(&self.actions),
_encoder_guard: api::PhantomDrop::default(),
}
}
/// Copy data from one buffer to another.
///
/// # Panics
+1
View File
@@ -97,6 +97,7 @@ pub struct ComputePipelineDescriptor<'a> {
/// selected.
// NOTE: keep phrasing in sync. with `FragmentState::entry_point`
// NOTE: keep phrasing in sync. with `VertexState::entry_point`
// NOTE: keep phrasing in sync. with `RayTracingStage::entry_point`
pub entry_point: Option<&'a str>,
/// Advanced options for when this pipeline is compiled
///
+11
View File
@@ -5,6 +5,7 @@ use core::{error, fmt, future::Future, marker::PhantomData};
use hashbrown::HashSet;
use crate::api::blas::{Blas, BlasGeometrySizeDescriptors, CreateBlasDescriptor};
use crate::api::ray_tracing_pipeline::{RayTracingPipeline, RayTracingPipelineDescriptor};
use crate::api::tlas::{CreateTlasDescriptor, Tlas};
use crate::util::Mutex;
use crate::*;
@@ -285,6 +286,16 @@ impl Device {
ComputePipeline { inner: pipeline }
}
/// Creates a [`RayTracingPipeline`].
#[must_use]
pub fn create_ray_tracing_pipeline(
&self,
desc: &RayTracingPipelineDescriptor<'_>,
) -> RayTracingPipeline {
let pipeline = self.inner.create_ray_tracing_pipeline(desc);
RayTracingPipeline { inner: pipeline }
}
/// Creates a [`Buffer`].
#[must_use]
pub fn create_buffer(&self, desc: &BufferDescriptor<'_>) -> Buffer {
+4
View File
@@ -40,6 +40,8 @@ mod pipeline_cache;
mod pipeline_layout;
mod query_set;
mod queue;
mod ray_tracing_pass;
mod ray_tracing_pipeline;
mod render_bundle;
mod render_bundle_encoder;
mod render_pass;
@@ -70,6 +72,8 @@ pub use pipeline_cache::*;
pub use pipeline_layout::*;
pub use query_set::*;
pub use queue::*;
pub use ray_tracing_pass::*;
pub use ray_tracing_pipeline::*;
pub use render_bundle::*;
pub use render_bundle_encoder::*;
pub use render_pass::*;
+112
View File
@@ -0,0 +1,112 @@
use wgt::DynamicOffset;
use crate::{api::SharedDeferredCommandBufferActions, *};
/// In-progress recording of a ray tracing pass.
///
/// It can be created with [`CommandEncoder::begin_ray_tracing_pass`].
#[derive(Debug)]
pub struct RayTracingPass<'encoder> {
pub(crate) inner: dispatch::DispatchRayTracingPass,
/// Shared with CommandEncoder to enqueue deferred actions from within a pass.
pub(crate) actions: SharedDeferredCommandBufferActions,
/// This lifetime is used to protect the [`CommandEncoder`] from being used
/// while the pass is alive. This needs to be PhantomDrop to prevent the lifetime
/// from being shortened.
pub(crate) _encoder_guard: crate::api::PhantomDrop<&'encoder ()>,
}
#[cfg(send_sync)]
static_assertions::assert_impl_all!(RayTracingPass<'_>: Send, Sync);
crate::cmp::impl_eq_ord_hash_proxy!(RayTracingPass<'_> => .inner);
impl RayTracingPass<'_> {
/// Drops the lifetime relationship to the parent command encoder, making usage of
/// the encoder while this pass is recorded a run-time error instead.
///
/// Attention: As long as the ray tracing pass has not been ended, any mutating operation on the parent
/// command encoder will cause a run-time error and invalidate it!
/// By default, the lifetime constraint prevents this, but it can be useful
/// to handle this at run time, such as when storing the pass and encoder in the same
/// data structure.
///
/// This operation has no effect on pass recording.
/// It's a safe operation, since [`CommandEncoder`] is in a locked state as long as the pass is active
/// regardless of the lifetime constraint or its absence.
pub fn forget_lifetime(self) -> RayTracingPass<'static> {
RayTracingPass {
inner: self.inner,
actions: self.actions,
_encoder_guard: crate::api::PhantomDrop::default(),
}
}
/// Sets the active ray tracing pipeline.
pub fn set_pipeline(&mut self, pipeline: &RayTracingPipeline) {
self.inner.set_pipeline(&pipeline.inner);
}
/// Sets the active bind group for a given bind group index. The bind group layout
/// in the active pipeline when the `trace_rays()` function is called must match the layout of this bind group.
///
/// If the bind group have dynamic offsets, provide them in the binding order.
/// These offsets have to be aligned to [`Limits::min_uniform_buffer_offset_alignment`]
/// or [`Limits::min_storage_buffer_offset_alignment`] appropriately.
pub fn set_bind_group<'a, BG>(&mut self, index: u32, bind_group: BG, offsets: &[DynamicOffset])
where
Option<&'a BindGroup>: From<BG>,
{
let bg: Option<&BindGroup> = bind_group.into();
let bg = bg.map(|bg| &bg.inner);
self.inner.set_bind_group(index, bg, offsets);
}
/// Inserts debug marker.
pub fn insert_debug_marker(&mut self, label: &str) {
self.inner.insert_debug_marker(label);
}
/// Start record commands and group it into debug marker group.
pub fn push_debug_group(&mut self, label: &str) {
self.inner.push_debug_group(label);
}
/// Stops command recording and creates debug group.
pub fn pop_debug_group(&mut self) {
self.inner.pop_debug_group();
}
/// Dispatches rays in the current ray tracing pipeline.
pub fn trace_rays(&mut self, x: u32, y: u32, z: u32) {
self.inner.trace_rays(x, y, z);
}
}
/// [`Features::IMMEDIATES`] must be enabled on the device in order to call these functions.
impl RayTracingPass<'_> {
/// Set immediate data for subsequent [RayTracingPass::trace_rays] calls.
///
/// Write the bytes in `data` at offset `offset` within immediate data
/// storage. Both `offset` and the length of `data` must be
/// multiples of [`crate::IMMEDIATE_DATA_ALIGNMENT`], which is always 4.
///
/// For example, if `offset` is `4` and `data` is eight bytes long, this
/// call will write `data` to bytes `4..12` of immediate data storage.
pub fn set_immediates(&mut self, offset: u32, data: &[u8]) {
self.inner.set_immediates(offset, data);
}
}
/// Describes the attachments of a ray tracing pass.
///
/// For use with [`CommandEncoder::begin_ray_tracing_pass`].
#[derive(Clone, Default, Debug)]
pub struct RayTracingPassDescriptor<'a> {
/// Debug label of the ray tracing pass. This will show up in graphics debuggers for easy identification.
pub label: Label<'a>,
}
#[cfg(send_sync)]
static_assertions::assert_impl_all!(RayTracingPassDescriptor<'_>: Send, Sync);
+143
View File
@@ -0,0 +1,143 @@
use crate::*;
/// Handle to a ray tracing pipeline.
///
/// A `RayTracingPipeline` object represents a ray tracing pipeline and its stages.
/// It can be created with [`Device::create_ray_tracing_pipeline`].
#[derive(Debug, Clone)]
pub struct RayTracingPipeline {
pub(crate) inner: dispatch::DispatchRayTracingPipeline,
}
#[cfg(send_sync)]
static_assertions::assert_impl_all!(RayTracingPipeline: Send, Sync);
crate::cmp::impl_eq_ord_hash_proxy!(RayTracingPipeline => .inner);
impl RayTracingPipeline {
/// Get an object representing the bind group layout at a given index.
///
/// If this pipeline was created with a [default layout][RayTracingPipelineDescriptor::layout], then
/// bind groups created with the returned `BindGroupLayout` can only be used with this pipeline.
///
/// This method will raise a validation error if there is no bind group layout at `index`.
pub fn get_bind_group_layout(&self, index: u32) -> BindGroupLayout {
let layout = self.inner.get_bind_group_layout(index);
BindGroupLayout { inner: layout }
}
#[cfg(custom)]
/// Returns custom implementation of RayTracingPipeline (if custom backend and is internally T)
pub fn as_custom<T: custom::RayTracingPipelineInterface>(&self) -> Option<&T> {
self.inner.as_custom()
}
}
/// Describes a stage in a ray tracing pipeline
///
/// For use in [`RayTracingPipelineDescriptor`]
#[derive(Clone, Debug)]
pub struct RayTracingStage<'a> {
/// The compiled shader module for this stage.
pub module: &'a ShaderModule,
/// The name of the entry point in the compiled shader to use.
///
/// If [`Some`], there must be a shader entry point with this name in `module` of the stage required.
/// Otherwise, expect exactly one entry point in `module` of the stage required, which will be
/// selected.
// NOTE: keep phrasing in sync. with `ComputePipelineDescriptor::entry_point`
// NOTE: keep phrasing in sync. with `VertexState::entry_point`
// NOTE: keep phrasing in sync. with `FragmentState::entry_point`
pub entry_point: Option<&'a str>,
/// Advanced options for when this pipeline is compiled
///
/// This implements `Default`, and for most users can be set to `Default::default()`
pub compilation_options: PipelineCompilationOptions<'a>,
}
/// Describes a group of stages to be called for an intersection in a ray tracing pipeline
///
/// For use in [`RayTracingPipelineDescriptor`]
#[derive(Clone, Debug)]
pub enum RayTracingIntersectionDescriptor<'a> {
/// This group of shaders may only be used when
/// a BLAS with triangle geometry is intersected.
Triangle {
/// Stage to call if, after the entire intersection process is complete, a triangle within an instance bound to this
/// descriptor is the closest hit.
closest_hit: RayTracingStage<'a>,
/// Optional stage to call when a triangle within an instance bound to this descriptor is hit at any point during the
/// intersection process.
any_hit: Option<RayTracingStage<'a>>,
},
}
/// Describes a ray tracing pipeline.
///
/// For use with [`Device::create_ray_tracing_pipeline`].
#[derive(Clone, Debug)]
pub struct RayTracingPipelineDescriptor<'a> {
/// Debug label of the pipeline. This will show up in graphics debuggers for easy identification.
pub label: Label<'a>,
/// The layout of bind groups for this pipeline.
///
/// If this is set, then [`Device::create_ray_tracing_pipeline`] will raise a validation error if
/// the layout doesn't match what the shader module(s) expect.
///
/// Using the same [`PipelineLayout`] for many [`RayTracingPipeline`] or [`RenderPipeline`] or [`ComputePipeline`]
/// pipelines guarantees that you don't have to rebind any resources when switching between
/// those pipelines.
///
/// ## Default pipeline layout
///
/// If `layout` is `None`, then the pipeline has a [default layout] created and used instead.
/// The default layout is deduced from the shader modules.
///
/// You can use [`RayTracingPipeline::get_bind_group_layout`] to create bind groups for use with the
/// default layout. However, these bind groups cannot be used with any other pipelines. This is
/// convenient for simple pipelines, but using an explicit layout is recommended in most cases.
///
/// Keep phrasing in sync. with [`RenderPipelineDescriptor`] and [`ComputePipelineDescriptor`].
///
/// [default layout]: https://www.w3.org/TR/webgpu/#default-pipeline-layout
pub layout: Option<&'a PipelineLayout>,
/// The ray generation stage. The shader stage invoked by command encoder trace rays.
pub ray_generation: RayTracingStage<'a>,
/// The miss stage. Called if a ray does not hit any object.
pub miss: RayTracingStage<'a>,
/// The list of intersection descriptors
pub intersections: &'a [RayTracingIntersectionDescriptor<'a>],
/// The maximum number of nested `traceRay` calls. The ray generation stage is at depth 0,
/// so it can call `traceRay` only if this is at least 1. Calling `traceRay` at a depth
/// equal to or greater than this value is undefined behavior.
pub max_recursion_depth: u32,
/// The pipeline cache to use when creating this pipeline.
pub cache: Option<&'a PipelineCache>,
}
#[cfg(send_sync)]
static_assertions::assert_impl_all!(RayTracingPipelineDescriptor<'_>: Send, Sync);
#[cfg(wgpu_core)]
impl RayTracingPipeline {
/// Create a new ray tracing pipeline of wgpu from a wgpu-core ray tracing pipeline.
///
/// # Arguments
///
/// - `core_ray_tracing_pipeline` - wgpu-core ray tracing pipeline.
pub fn from_core(
core_ray_tracing_pipeline: alloc::sync::Arc<wgc::ray_tracing_pipeline::RayTracingPipeline>,
) -> Self {
Self {
inner: crate::backend::wgpu_core::CoreRayTracingPipeline::from_core(
core_ray_tracing_pipeline,
)
.into(),
}
}
/// Returns the underlying wgpu-core ray tracing pipeline if this `RayTracingPipeline` is on the wgpu-core backend, otherwise `None`.
pub fn as_core(
&self,
) -> Option<alloc::sync::Arc<wgc::ray_tracing_pipeline::RayTracingPipeline>> {
self.inner.as_core_opt().map(|rtp| rtp.as_core())
}
}
+1
View File
@@ -124,6 +124,7 @@ pub struct VertexState<'a> {
/// selected.
// NOTE: keep phrasing in sync. with `ComputePipelineDescriptor::entry_point`
// NOTE: keep phrasing in sync. with `FragmentState::entry_point`
// NOTE: keep phrasing in sync. with `RayTracingStage::entry_point`
pub entry_point: Option<&'a str>,
/// Advanced options for when this pipeline is compiled
///
+2
View File
@@ -89,10 +89,12 @@ dyn_type!(pub ref struct DynQuerySet(dyn QuerySetInterface));
dyn_type!(pub ref struct DynPipelineLayout(dyn PipelineLayoutInterface));
dyn_type!(pub ref struct DynRenderPipeline(dyn RenderPipelineInterface));
dyn_type!(pub ref struct DynComputePipeline(dyn ComputePipelineInterface));
dyn_type!(pub ref struct DynRayTracingPipeline(dyn RayTracingPipelineInterface));
dyn_type!(pub ref struct DynPipelineCache(dyn PipelineCacheInterface));
dyn_type!(pub mut struct DynCommandEncoder(dyn CommandEncoderInterface));
dyn_type!(pub mut struct DynComputePass(dyn ComputePassInterface));
dyn_type!(pub mut struct DynRenderPass(dyn RenderPassInterface));
dyn_type!(pub mut struct DynRayTracingPass(dyn RayTracingPassInterface));
dyn_type!(pub mut struct DynCommandBuffer(dyn CommandBufferInterface));
static NEXT_RENDER_BUNDLE_ENCODER_ID: AtomicU64 = AtomicU64::new(0);
+78
View File
@@ -1435,6 +1435,12 @@ pub struct WebComputePipeline {
ident: crate::cmp::Identifier,
}
#[derive(Debug, Clone)]
pub struct WebRayTracingPipeline {
/// Unique identifier for this RayTracingPipeline.
ident: crate::cmp::Identifier,
} // no ray tracing pipelines on web
#[derive(Debug, Clone)]
pub struct WebPipelineCache {
/// Unique identifier for this PipelineCache.
@@ -1462,6 +1468,12 @@ pub struct WebRenderPassEncoder {
ident: crate::cmp::Identifier,
}
#[derive(Debug, Clone)]
pub struct WebRayTracingPassEncoder {
/// Unique identifier for this RayTracingPassEncoder.
ident: crate::cmp::Identifier,
} // no ray tracing pipelines on web
#[derive(Debug)]
pub struct WebCommandBuffer {
pub(crate) inner: webgpu_sys::GpuCommandBuffer,
@@ -1544,10 +1556,12 @@ impl_send_sync!(WebQuerySet);
impl_send_sync!(WebPipelineLayout);
impl_send_sync!(WebRenderPipeline);
impl_send_sync!(WebComputePipeline);
impl_send_sync!(WebRayTracingPipeline);
impl_send_sync!(WebPipelineCache);
impl_send_sync!(WebCommandEncoder);
impl_send_sync!(WebComputePassEncoder);
impl_send_sync!(WebRenderPassEncoder);
impl_send_sync!(WebRayTracingPassEncoder);
impl_send_sync!(WebCommandBuffer);
impl_send_sync!(WebRenderBundleEncoder);
impl_send_sync!(WebRenderBundle);
@@ -1574,11 +1588,13 @@ crate::cmp::impl_eq_ord_hash_proxy!(WebQuerySet => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebPipelineLayout => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebRenderPipeline => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebComputePipeline => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebRayTracingPipeline => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebPipelineCache => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebCommandEncoder => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebComputePassEncoder => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebRenderPassEncoder => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebCommandBuffer => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebRayTracingPassEncoder => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebRenderBundleEncoder => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebRenderBundle => .ident);
crate::cmp::impl_eq_ord_hash_proxy!(WebSurface => .ident);
@@ -2589,6 +2605,13 @@ impl dispatch::DeviceInterface for WebDevice {
.into()
}
fn create_ray_tracing_pipeline(
&self,
_desc: &crate::RayTracingPipelineDescriptor<'_>,
) -> dispatch::DispatchRayTracingPipeline {
unimplemented!("ray tracing is not on the web.")
}
unsafe fn create_pipeline_cache(
&self,
_desc: &crate::PipelineCacheDescriptor<'_>,
@@ -3343,6 +3366,17 @@ impl Drop for WebComputePipeline {
}
}
impl dispatch::RayTracingPipelineInterface for WebRayTracingPipeline {
fn get_bind_group_layout(&self, _index: u32) -> dispatch::DispatchBindGroupLayout {
unimplemented!("ray tracing is not on the web.")
}
}
impl Drop for WebRayTracingPipeline {
fn drop(&mut self) {
// no-op
}
}
impl dispatch::CommandEncoderInterface for WebCommandEncoder {
fn copy_buffer_to_buffer(
&self,
@@ -3573,6 +3607,13 @@ impl dispatch::CommandEncoderInterface for WebCommandEncoder {
.into()
}
fn begin_ray_tracing_pass(
&self,
_desc: &crate::RayTracingPassDescriptor<'_>,
) -> dispatch::DispatchRayTracingPass {
unimplemented!("ray tracing is not on the web.")
}
fn finish(&mut self) -> dispatch::DispatchCommandBuffer {
let label = self.inner.label();
let buffer = if label.is_empty() {
@@ -4077,6 +4118,43 @@ impl Drop for WebRenderPassEncoder {
}
}
impl dispatch::RayTracingPassInterface for WebRayTracingPassEncoder {
fn set_pipeline(&mut self, _pipeline: &dispatch::DispatchRayTracingPipeline) {
unreachable!("Ray tracing pipelines are unavailable on the web.")
}
fn set_bind_group(
&mut self,
_index: u32,
_bind_group: Option<&dispatch::DispatchBindGroup>,
_offsets: &[crate::DynamicOffset],
) {
unreachable!("Ray tracing pipelines are unavailable on the web.")
}
fn set_immediates(&mut self, _offset: u32, _data: &[u8]) {
unreachable!("Ray tracing pipelines are unavailable on the web.")
}
fn insert_debug_marker(&mut self, _label: &str) {
unreachable!("Ray tracing pipelines are unavailable on the web.")
}
fn push_debug_group(&mut self, _group_label: &str) {
unreachable!("Ray tracing pipelines are unavailable on the web.")
}
fn pop_debug_group(&mut self) {
unreachable!("Ray tracing pipelines are unavailable on the web.")
}
fn trace_rays(&mut self, _x: u32, _y: u32, _z: u32) {
unreachable!("Ray tracing pipelines are unavailable on the web.")
}
}
impl Drop for WebRayTracingPassEncoder {
fn drop(&mut self) {
// no-op
}
}
impl dispatch::CommandBufferInterface for WebCommandBuffer {}
impl Drop for WebCommandBuffer {
fn drop(&mut self) {
+179
View File
@@ -577,6 +577,25 @@ impl CoreRenderPipeline {
}
}
#[derive(Debug, Clone)]
pub struct CoreRayTracingPipeline {
pub(crate) wgpu_ray_tracing_pipeline: Arc<wgc::ray_tracing_pipeline::RayTracingPipeline>,
}
impl CoreRayTracingPipeline {
pub(crate) fn from_core(
core_ray_tracing_pipeline: Arc<wgc::ray_tracing_pipeline::RayTracingPipeline>,
) -> Self {
Self {
wgpu_ray_tracing_pipeline: core_ray_tracing_pipeline,
}
}
pub(crate) fn as_core(&self) -> Arc<wgc::ray_tracing_pipeline::RayTracingPipeline> {
self.wgpu_ray_tracing_pipeline.clone()
}
}
#[derive(Debug)]
pub struct CoreComputePass {
pass: wgc::command::ComputePass,
@@ -591,6 +610,13 @@ pub struct CoreRenderPass {
id: crate::cmp::Identifier,
}
#[derive(Debug)]
pub struct CoreRayTracingPass {
pass: wgc::command::RayTracingPass,
id: crate::cmp::Identifier,
}
pub struct CoreCommandEncoder {
pub(crate) wgpu_command_encoder: Arc<wgc::command::CommandEncoder>,
}
@@ -707,10 +733,12 @@ crate::cmp::impl_eq_ord_hash_arc_address!(CoreQuerySet => .wgpu_query_set);
crate::cmp::impl_eq_ord_hash_arc_address!(CorePipelineLayout => .wgpu_pipeline_layout);
crate::cmp::impl_eq_ord_hash_arc_address!(CoreRenderPipeline => .wgpu_render_pipeline);
crate::cmp::impl_eq_ord_hash_arc_address!(CoreComputePipeline => .wgpu_compute_pipeline);
crate::cmp::impl_eq_ord_hash_arc_address!(CoreRayTracingPipeline => .wgpu_ray_tracing_pipeline);
crate::cmp::impl_eq_ord_hash_arc_address!(CorePipelineCache => .wgpu_pipeline_cache);
crate::cmp::impl_eq_ord_hash_arc_address!(CoreCommandEncoder => .wgpu_command_encoder);
crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePass => .id);
crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPass => .id);
crate::cmp::impl_eq_ord_hash_proxy!(CoreRayTracingPass => .id);
crate::cmp::impl_eq_ord_hash_arc_address!(CoreCommandBuffer => .wgpu_command_buffer);
crate::cmp::impl_eq_ord_hash_box_address!(CoreRenderBundleEncoder => .encoder);
crate::cmp::impl_eq_ord_hash_arc_address!(CoreRenderBundle => .wgpu_render_bundle);
@@ -1420,6 +1448,77 @@ impl dispatch::DeviceInterface for CoreDevice {
.into()
}
fn create_ray_tracing_pipeline(
&self,
desc: &crate::RayTracingPipelineDescriptor<'_>,
) -> dispatch::DispatchRayTracingPipeline {
use wgc::pipeline as pipe;
use wgc::ray_tracing_pipeline as rt_pipe;
fn downcast_rt_stage<'a>(
stage: &'a crate::RayTracingStage<'a>,
) -> pipe::ProgrammableStageDescriptor<'a> {
pipe::ProgrammableStageDescriptor {
module: stage.module.inner.as_core().wgpu_shader_module.clone(),
entry_point: stage.entry_point.map(Borrowed),
constants: stage
.compilation_options
.constants
.iter()
.map(|&(key, value)| (String::from(key), value))
.collect(),
zero_initialize_workgroup_memory: stage
.compilation_options
.zero_initialize_workgroup_memory,
}
}
let descriptor = rt_pipe::RayTracingPipelineDescriptor {
label: desc.label.map(Borrowed),
layout: desc
.layout
.map(|pll| pll.inner.as_core().wgpu_pipeline_layout.clone()),
ray_generation: downcast_rt_stage(&desc.ray_generation),
miss: downcast_rt_stage(&desc.miss),
intersections: desc
.intersections
.iter()
.map(|intersection_desc| match intersection_desc {
crate::RayTracingIntersectionDescriptor::Triangle {
closest_hit,
any_hit,
} => rt_pipe::RayTracingIntersectionDescriptor::Triangle {
closest_hit: downcast_rt_stage(closest_hit),
any_hit: any_hit.as_ref().map(|stage| downcast_rt_stage(stage)),
},
})
.collect::<Vec<_>>(),
max_recursion_depth: desc.max_recursion_depth,
cache: desc
.cache
.map(|cache| cache.inner.as_core().wgpu_pipeline_cache.clone()),
};
let (wgpu_ray_tracing_pipeline, error) =
self.wgpu_device.create_ray_tracing_pipeline(descriptor);
if let Some(cause) = error {
if let pipe::CreatePipelineError::Internal { stage, ref message } = cause {
log::error!(
"Shader translation error for stage {:?}: {}",
stage,
message
);
log::error!("Please report it to https://github.com/gfx-rs/wgpu");
}
self.wgpu_device
.handle_error(cause, desc.label, "Device::create_ray_tracing_pipeline");
}
CoreRayTracingPipeline {
wgpu_ray_tracing_pipeline,
}
.into()
}
unsafe fn create_pipeline_cache(
&self,
desc: &crate::PipelineCacheDescriptor<'_>,
@@ -1975,6 +2074,22 @@ impl dispatch::RenderPipelineInterface for CoreRenderPipeline {
}
}
impl dispatch::RayTracingPipelineInterface for CoreRayTracingPipeline {
fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
let (wgpu_bind_group_layout, error) =
self.wgpu_ray_tracing_pipeline.get_bind_group_layout(index);
if let Some(err) = error {
self.wgpu_ray_tracing_pipeline
.device()
.handle_error_nolabel(err, "RayTracingPipeline::get_bind_group_layout")
}
CoreBindGroupLayout {
wgpu_bind_group_layout,
}
.into()
}
}
impl dispatch::ComputePipelineInterface for CoreComputePipeline {
fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
let wgpu_bind_group_layout = self.wgpu_compute_pipeline.get_bind_group_layout(index);
@@ -2136,6 +2251,23 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
.into()
}
fn begin_ray_tracing_pass(
&self,
desc: &crate::RayTracingPassDescriptor<'_>,
) -> dispatch::DispatchRayTracingPass {
let pass = self.wgpu_command_encoder.begin_ray_tracing_pass(
&wgc::command::RayTracingPassDescriptor {
label: desc.label.map(Borrowed),
},
);
CoreRayTracingPass {
pass,
id: crate::cmp::Identifier::create(),
}
.into()
}
fn finish(&mut self) -> dispatch::DispatchCommandBuffer {
let descriptor = wgt::CommandBufferDescriptor::default();
let wgpu_command_buffer = self.wgpu_command_encoder.finish(&descriptor);
@@ -2279,6 +2411,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
transform: instance.transform,
custom_data: instance.custom_data,
mask: instance.mask,
intersection_index: instance.intersection_index,
})
})
.collect();
@@ -2710,6 +2843,52 @@ impl Drop for CoreRenderPass {
}
}
impl dispatch::RayTracingPassInterface for CoreRayTracingPass {
fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRayTracingPipeline) {
let pipeline = pipeline.as_core();
self.pass
.set_pipeline(pipeline.wgpu_ray_tracing_pipeline.clone())
}
fn set_bind_group(
&mut self,
index: u32,
bind_group: Option<&dispatch::DispatchBindGroup>,
offsets: &[crate::DynamicOffset],
) {
let bg = bind_group.map(|bg| bg.as_core().wgpu_bind_group.clone());
self.pass.set_bind_group(index, bg, offsets)
}
fn set_immediates(&mut self, offset: u32, data: &[u8]) {
self.pass.set_immediates(offset, data)
}
fn insert_debug_marker(&mut self, label: &str) {
self.pass.insert_debug_marker(label, 0)
}
fn push_debug_group(&mut self, group_label: &str) {
self.pass.push_debug_group(group_label, 0)
}
fn pop_debug_group(&mut self) {
self.pass.pop_debug_group()
}
fn trace_rays(&mut self, x: u32, y: u32, z: u32) {
self.pass.trace_rays(x, y, z)
}
}
impl Drop for CoreRayTracingPass {
fn drop(&mut self) {
self.pass.end()
}
}
impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder {
fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
let pipeline = pipeline.as_core();
+29
View File
@@ -176,6 +176,10 @@ pub trait DeviceInterface: CommonTraits {
&self,
desc: &crate::ComputePipelineDescriptor<'_>,
) -> DispatchComputePipeline;
fn create_ray_tracing_pipeline(
&self,
desc: &crate::RayTracingPipelineDescriptor<'_>,
) -> DispatchRayTracingPipeline;
unsafe fn create_pipeline_cache(
&self,
desc: &crate::PipelineCacheDescriptor<'_>,
@@ -345,6 +349,9 @@ pub trait RenderPipelineInterface: CommonTraits {
pub trait ComputePipelineInterface: CommonTraits {
fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
}
pub trait RayTracingPipelineInterface: CommonTraits {
fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
}
pub trait PipelineCacheInterface: CommonTraits {
fn get_data(&self) -> Option<Vec<u8>>;
}
@@ -378,6 +385,10 @@ pub trait CommandEncoderInterface: CommonTraits {
fn begin_compute_pass(&self, desc: &crate::ComputePassDescriptor<'_>) -> DispatchComputePass;
fn begin_render_pass(&self, desc: &crate::RenderPassDescriptor<'_>) -> DispatchRenderPass;
fn begin_ray_tracing_pass(
&self,
desc: &crate::RayTracingPassDescriptor<'_>,
) -> DispatchRayTracingPass;
fn finish(&mut self) -> DispatchCommandBuffer;
fn clear_texture(
@@ -566,6 +577,22 @@ pub trait RenderPassInterface: CommonTraits + Drop {
fn execute_bundles(&mut self, render_bundles: &mut dyn Iterator<Item = &DispatchRenderBundle>);
}
pub trait RayTracingPassInterface: CommonTraits + Drop {
fn set_pipeline(&mut self, pipeline: &DispatchRayTracingPipeline);
fn set_bind_group(
&mut self,
index: u32,
bind_group: Option<&DispatchBindGroup>,
offsets: &[crate::DynamicOffset],
);
fn set_immediates(&mut self, offset: u32, data: &[u8]);
fn insert_debug_marker(&mut self, label: &str);
fn push_debug_group(&mut self, group_label: &str);
fn pop_debug_group(&mut self);
fn trace_rays(&mut self, x: u32, y: u32, z: u32);
}
pub trait RenderBundleEncoderInterface: CommonTraits {
fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);
@@ -1097,10 +1124,12 @@ dispatch_types! {ref type DispatchQuerySet: QuerySetInterface = CoreQuerySet, We
dispatch_types! {ref type DispatchPipelineLayout: PipelineLayoutInterface = CorePipelineLayout, WebPipelineLayout, DynPipelineLayout}
dispatch_types! {ref type DispatchRenderPipeline: RenderPipelineInterface = CoreRenderPipeline, WebRenderPipeline, DynRenderPipeline}
dispatch_types! {ref type DispatchComputePipeline: ComputePipelineInterface = CoreComputePipeline, WebComputePipeline, DynComputePipeline}
dispatch_types! {ref type DispatchRayTracingPipeline: RayTracingPipelineInterface = CoreRayTracingPipeline, WebRayTracingPipeline, DynRayTracingPipeline}
dispatch_types! {ref type DispatchPipelineCache: PipelineCacheInterface = CorePipelineCache, WebPipelineCache, DynPipelineCache}
dispatch_types! {mut type DispatchCommandEncoder: CommandEncoderInterface = CoreCommandEncoder, WebCommandEncoder, DynCommandEncoder}
dispatch_types! {mut type DispatchComputePass: ComputePassInterface = CoreComputePass, WebComputePassEncoder, DynComputePass}
dispatch_types! {mut type DispatchRenderPass: RenderPassInterface = CoreRenderPass, WebRenderPassEncoder, DynRenderPass}
dispatch_types! {mut type DispatchRayTracingPass: RayTracingPassInterface = CoreRayTracingPass, WebRayTracingPassEncoder, DynRayTracingPass}
dispatch_types! {mut type DispatchCommandBuffer: CommandBufferInterface = CoreCommandBuffer, WebCommandBuffer, DynCommandBuffer}
dispatch_types! {mut type DispatchRenderBundleEncoder: RenderBundleEncoderInterface = CoreRenderBundleEncoder, WebRenderBundleEncoder, DynRenderBundleEncoder}
dispatch_types! {ref type DispatchRenderBundle: RenderBundleInterface = CoreRenderBundle, WebRenderBundle, DynRenderBundle}