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},
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,
init_tracker::MemoryInitKind,
ray_tracing::AsAction,
ray_tracing_pipeline::RayTracingPipeline,
resource::{
Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError,
Labeled, MissingBufferUsageError, ParentDevice, RawResourceAccess, Trackable,
},
track::{ResourceUsageCompatibilityError, Tracker},
Label,
};
pub type RayTracingBasePass = BasePass<ArcRayTracingCommand, RayTracingPassError>;
pub struct RayTracingPass {
base: RayTracingBasePass,
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 {
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;
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("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
}
}
#[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),
}
}
}
#[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(), &pipeline.late_sized_buffer_groups)?;
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);
}
fn flush_bindings(
&mut self,
indirect_buffer: Option<&Arc<Buffer>>,
track_indirect_buffer: bool,
) -> Result<(), RayTracingPassErrorInner> {
for bind_group in self.pass.binder.list_active() {
unsafe { self.pass.scope.merge_bind_group(&bind_group.used)? };
}
if let Some(buffer) = indirect_buffer {
self.pass
.scope
.buffers
.merge_single(buffer, wgt::BufferUses::INDIRECT)?;
}
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(),
));
}
}
if track_indirect_buffer {
self.intermediate_trackers
.buffers
.set_and_remove_from_usage_scope_sparse(
&mut self.pass.scope.buffers,
indirect_buffer.map(|buf| buf.tracker_index()),
);
} else if let Some(buffer) = indirect_buffer {
self.pass
.scope
.buffers
.remove_usage(buffer, wgt::BufferUses::INDIRECT);
}
flush_bindings_helper(&mut self.pass)?;
CommandEncoder::drain_barriers(
self.pass.base.raw_encoder,
&mut self.intermediate_trackers,
self.pass.base.snatch_guard,
);
Ok(())
}
}
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);
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()
{
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 { indirect: false };
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");
}
}
pub fn trace_rays_indirect_inner(
&mut self,
buffer: Arc<Buffer>,
offset: BufferAddress,
) -> Result<(), PassStateError> {
let scope = PassErrorScope::TraceRays { indirect: true };
let base = pass_base!(self, scope);
pass_try!(base, scope, buffer.check_is_valid());
base.commands
.push(ArcRayTracingCommand::TraceRaysIndirect { buffer, offset });
Ok(())
}
pub fn trace_rays_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
if let Err(err) = self.trace_rays_indirect_inner(buffer, offset) {
self.device
.handle_error(err, self.label(), "RayTracingPass::trace_rays_indirect");
}
}
}
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) => {
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)) => {
drop(cmd_buf_data);
(
RayTracingPass::new_invalid(
self.clone(),
&label,
err.clone().map_pass_err(scope),
),
Some(err.into()),
)
}
Err(err @ SErr::Invalid) => {
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;
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 pass_label = hal_label(base.label.as_deref(), device.instance_flags);
if let Some(label) = pass_label {
unsafe { state.pass.base.raw_encoder.begin_debug_marker(label) };
}
unsafe {
state
.pass
.base
.raw_encoder
.begin_ray_tracing_pass(&hal::RayTracingPassDescriptor { label: None });
}
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 { indirect: false };
trace_rays(&mut state, groups, device).map_pass_err(scope)?;
}
ArcRayTracingCommand::TraceRaysIndirect { buffer, offset } => {
let scope = PassErrorScope::TraceRays { indirect: true };
trace_rays_indirect(&mut state, device, buffer, offset).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();
}
if pass_label.is_some() {
unsafe { state.pass.base.raw_encoder.end_debug_marker() };
}
let State {
pass: pass::PassState {
pending_discard_init_fixups,
..
},
intermediate_trackers,
..
} = state;
parent_state.raw_encoder.close().map_pass_err(pass_scope)?;
let transit = parent_state
.raw_encoder
.open_pass(hal_label(
Some("(wgpu internal) Pre Pass"),
device.instance_flags,
))
.map_pass_err(pass_scope)?;
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,
);
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()?);
}
let pipeline_layout = pipeline.layout()?;
pass::change_pipeline_layout::<RayTracingPassErrorInner>(&mut state.pass, pipeline_layout)
}
pub(crate) fn max_trace_rays_dimensions(limits: &wgt::Limits) -> [u32; 3] {
[
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),
]
}
fn shader_binding_table<'a>(
pipeline: &'a RayTracingPipeline,
device: &Device,
) -> Result<[hal::PipelineGroupData<'a, dyn hal::DynBuffer>; 3], InvalidResourceError> {
let shader_binding_data = pipeline.shader_binding_data()?;
let stride = device.alignments.ray_tracing_pipeline_group_data_size as _;
Ok([
hal::PipelineGroupData {
buffer: shader_binding_data.raw.as_ref(),
offset: 0,
stride,
count: 1,
},
hal::PipelineGroupData {
buffer: shader_binding_data.raw.as_ref(),
offset: shader_binding_data.miss_offset,
stride,
count: 1,
},
hal::PipelineGroupData {
buffer: shader_binding_data.raw.as_ref(),
offset: shader_binding_data.intersection_offset,
stride,
count: shader_binding_data.num_intersection_groups as _,
},
])
}
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(None, false)?;
state.flush_immediates();
let limits = &state.pass.base.device.limits;
let dim_size_limit = max_trace_rays_dimensions(limits);
if dims
.iter()
.zip(dim_size_limit)
.any(|(&dim, limit)| dim > limit)
{
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 [ray_generation, miss, intersection] =
shader_binding_table(state.pipeline.as_ref().unwrap(), device)?;
unsafe {
state
.pass
.base
.raw_encoder
.trace_rays(dims, ray_generation, miss, intersection);
}
Ok(())
}
fn trace_rays_indirect(
state: &mut State,
device: &Arc<Device>,
buffer: Arc<Buffer>,
offset: u64,
) -> Result<(), RayTracingPassErrorInner> {
api_log!("RayTracingPass::trace_rays_indirect");
buffer.same_device(device)?;
device.require_features(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES_INDIRECT)?;
state.is_ready()?;
state
.pass
.base
.device
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
buffer.check_usage(wgt::BufferUsages::INDIRECT)?;
if !offset.is_multiple_of(4) {
return Err(RayTracingPassErrorInner::UnalignedIndirectBufferOffset(
offset,
));
}
let args_size = size_of::<wgt::DispatchIndirectArgs>() as u64;
let end_offset = offset.saturating_add(args_size);
if end_offset > buffer.size {
return Err(RayTracingPassErrorInner::IndirectBufferOverrun {
offset,
end_offset,
buffer_size: buffer.size,
});
}
buffer.check_destroyed(state.pass.base.snatch_guard)?;
state.pass.base.buffer_memory_init_actions.extend(
buffer.initialization_status.read().create_action(
&buffer,
offset..end_offset,
MemoryInitKind::NeedsInitializedMemory,
),
);
let (indirect_buffer, indirect_offset) = if let Some(ref indirect_validation) =
state.pass.base.device.indirect_validation
{
let params = indirect_validation
.dispatch
.trace_rays_params(&state.pass.base.device.limits, offset, buffer.size)
.expect("Indirect trace rays requires `Features::EXPERIMENTAL_RAY_TRACING_PIPELINES_INDIRECT`");
unsafe {
let raw_encoder = &mut *state.pass.base.raw_encoder;
raw_encoder.end_ray_tracing_pass();
raw_encoder.begin_compute_pass(&hal::ComputePassDescriptor {
label: None,
timestamp_writes: None,
});
raw_encoder.set_compute_pipeline(params.pipeline);
raw_encoder.set_immediates(
params.pipeline_layout,
0,
&[params.offset_remainder as u32 / 4],
);
raw_encoder.set_bind_group(params.pipeline_layout, 0, params.dst_bind_group, &[]);
raw_encoder.set_bind_group(
params.pipeline_layout,
1,
buffer
.indirect_validation_bind_groups
.get(state.pass.base.snatch_guard)
.unwrap()
.dispatch
.as_ref(),
&[params.aligned_offset as u32],
);
}
let src_transition = state
.intermediate_trackers
.buffers
.set_single(&buffer, wgt::BufferUses::STORAGE_READ_ONLY);
let src_barrier = src_transition
.map(|transition| transition.into_hal(&buffer, state.pass.base.snatch_guard));
unsafe {
let raw_encoder = &mut *state.pass.base.raw_encoder;
raw_encoder.transition_buffers(src_barrier.as_slice());
raw_encoder.transition_buffers(&[hal::BufferBarrier {
buffer: params.dst_buffer,
usage: hal::StateTransition {
from: wgt::BufferUses::INDIRECT,
to: wgt::BufferUses::STORAGE_READ_WRITE,
},
}]);
raw_encoder.dispatch_workgroups([1, 1, 1]);
raw_encoder.transition_buffers(&[hal::BufferBarrier {
buffer: params.dst_buffer,
usage: hal::StateTransition {
from: wgt::BufferUses::STORAGE_READ_WRITE,
to: wgt::BufferUses::INDIRECT,
},
}]);
raw_encoder.end_compute_pass();
raw_encoder.begin_ray_tracing_pass(&hal::RayTracingPassDescriptor { label: None });
}
let pipeline = state.pipeline.as_ref().unwrap();
unsafe {
state
.pass
.base
.raw_encoder
.set_ray_tracing_pipeline(pipeline.raw()?);
}
let pipeline_layout = pipeline.layout()?.raw()?;
for (i, group, dynamic_offsets) in state.pass.binder.list_valid() {
let raw_bg = group.try_raw(state.pass.base.snatch_guard)?;
unsafe {
state.pass.base.raw_encoder.set_bind_group(
pipeline_layout,
i as u32,
raw_bg,
dynamic_offsets,
);
}
}
state.pass.immediate_state.immediates_dirty = true;
state.flush_bindings(Some(&buffer), false)?;
(params.dst_buffer, 0)
} else {
state.flush_bindings(Some(&buffer), true)?;
(buffer.try_raw(state.pass.base.snatch_guard)?, offset)
};
state.flush_immediates();
let [ray_generation, miss, intersection] =
shader_binding_table(state.pipeline.as_ref().unwrap(), device)?;
unsafe {
state.pass.base.raw_encoder.trace_rays_indirect(
indirect_buffer,
indirect_offset,
ray_generation,
miss,
intersection,
);
}
Ok(())
}