diff --git a/CHANGELOG.md b/CHANGELOG.md index e21b21f69..00485b778 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,7 @@ Bottom level categories: - Fix missing dependency feature activations when building wgpu-hal with gles/dx12 in isolation. By @wumpf in [#9325](https://github.com/gfx-rs/wgpu/pull/9325) - Make `wgpu_types::texture::format::TextureChannel` accessible as `wgpu::TextureChannel`. By @TornaxO7 in [#9394](https://github.com/gfx-rs/wgpu/pull/9349). - Add support for `per_vertex` in Metal and DX12, as well as some validation for `per_vertex`, and a new enable extension, `wgpu_per_vertex`. By @inner-daemons in [#9219](https://github.com/gfx-rs/wgpu/pull/9219). +- Add `ComputePass` version of `CommandEncoder::transition_resources` that allows intra-pass transitions. By @wingertge in [#9371](https://github.com/gfx-rs/wgpu/pull/9371). #### Metal diff --git a/player/src/lib.rs b/player/src/lib.rs index 5a6d35476..3e23c5d70 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -1079,6 +1079,26 @@ impl Player { query_index, }, C::EndPipelineStatisticsQuery => C::EndPipelineStatisticsQuery, + C::TransitionResources { + buffer_transitions, + texture_transitions, + } => C::TransitionResources { + buffer_transitions: buffer_transitions + .into_iter() + .map(|buffer_transition| wgt::BufferTransition { + buffer: self.resolve_buffer_id(buffer_transition.buffer), + state: buffer_transition.state, + }) + .collect(), + texture_transitions: texture_transitions + .into_iter() + .map(|texture_transition| wgt::TextureTransition { + texture: self.resolve_texture_view_id(texture_transition.texture), + selector: texture_transition.selector, + state: texture_transition.state, + }) + .collect(), + }, } } diff --git a/tests/tests/wgpu-gpu/compute_pass_transition_resources.rs b/tests/tests/wgpu-gpu/compute_pass_transition_resources.rs new file mode 100644 index 000000000..ea1d5fb7a --- /dev/null +++ b/tests/tests/wgpu-gpu/compute_pass_transition_resources.rs @@ -0,0 +1,38 @@ +use wgpu_test::{gpu_test, GpuTestConfiguration, GpuTestInitializer, TestParameters}; + +pub fn all_tests(vec: &mut Vec) { + vec.push(COMPUTE_PASS_TRANSITION_RESOURCES); +} + +#[gpu_test] +static COMPUTE_PASS_TRANSITION_RESOURCES: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters(TestParameters::default().enable_noop()) + .run_sync(|ctx| { + let buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 128, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let mut encoder = ctx + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: None, + timestamp_writes: None, + }); + + pass.transition_resources( + [wgpu::BufferTransition { + buffer: &buffer, + state: wgpu::BufferUses::STORAGE_READ_WRITE, + }] + .into_iter(), + core::iter::empty(), + ); + + drop(pass); + + ctx.queue.submit([encoder.finish()]); + }); diff --git a/tests/tests/wgpu-gpu/main.rs b/tests/tests/wgpu-gpu/main.rs index a3c7f2462..970b27578 100644 --- a/tests/tests/wgpu-gpu/main.rs +++ b/tests/tests/wgpu-gpu/main.rs @@ -23,6 +23,7 @@ mod clear_texture; mod clip_distances; mod cloneable_types; mod compute_pass_ownership; +mod compute_pass_transition_resources; mod create_surface_error; mod device; mod dispatch_workgroups_indirect; @@ -155,6 +156,7 @@ fn all_tests() -> Vec { transfer::all_tests(&mut tests); transient::all_tests(&mut tests); transition_resources::all_tests(&mut tests); + compute_pass_transition_resources::all_tests(&mut tests); vertex_formats::all_tests(&mut tests); vertex_indices::all_tests(&mut tests); vertex_state::all_tests(&mut tests); diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 06850292e..3404cf449 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -21,7 +21,7 @@ use crate::{ ArcCommand, ArcPassTimestampWrites, BasePass, BindGroupStateChange, CommandEncoder, CommandEncoderError, DebugGroupError, EncoderStateError, InnerCommandEncoder, MapPassErr, PassErrorScope, PassStateError, PassTimestampWrites, QueryUseError, StateChange, - TimestampWritesError, + TimestampWritesError, TransitionResourcesError, }, device::{Device, DeviceError, MissingDownlevelFlags, MissingFeatures}, global::Global, @@ -30,9 +30,9 @@ use crate::{ pipeline::ComputePipeline, resource::{ self, Buffer, DestroyedResourceError, InvalidResourceError, Labeled, - MissingBufferUsageError, ParentDevice, RawResourceAccess, Trackable, + MissingBufferUsageError, ParentDevice, RawResourceAccess, TextureView, Trackable, }, - track::{ResourceUsageCompatibilityError, Tracker}, + track::{ResourceUsageCompatibilityError, TextureViewBindGroupState, Tracker}, Label, }; @@ -179,6 +179,8 @@ pub enum ComputePassErrorInner { #[error(transparent)] QueryUse(#[from] QueryUseError), #[error(transparent)] + TransitionResources(#[from] TransitionResourcesError), + #[error(transparent)] MissingFeatures(#[from] MissingFeatures), #[error(transparent)] MissingDownlevelFlags(#[from] MissingDownlevelFlags), @@ -235,6 +237,7 @@ impl WebGpuError for ComputePassError { ComputePassErrorInner::Bind(e) => e.webgpu_error_type(), ComputePassErrorInner::ImmediateData(e) => e.webgpu_error_type(), ComputePassErrorInner::QueryUse(e) => e.webgpu_error_type(), + ComputePassErrorInner::TransitionResources(e) => e.webgpu_error_type(), ComputePassErrorInner::MissingFeatures(e) => e.webgpu_error_type(), ComputePassErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(), ComputePassErrorInner::InvalidResource(e) => e.webgpu_error_type(), @@ -368,6 +371,70 @@ impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> { } } +/// Compute pass version of [`command::transition_resources`](crate::command::transition_resources). +/// See also `State::flush_bindings` for details on the implementation. +fn transition_resources( + state: &mut State, + buffer_transitions: Vec>>, + texture_transitions: Vec>>, +) -> Result<(), TransitionResourcesError> { + let indices = &state.pass.base.device.tracker_indices; + state.pass.scope.buffers.set_size(indices.buffers.size()); + state.pass.scope.textures.set_size(indices.textures.size()); + + let mut buffer_ids = Vec::with_capacity(buffer_transitions.len()); + let mut textures = TextureViewBindGroupState::new(); + + // Process buffer transitions + for buffer_transition in buffer_transitions { + buffer_transition + .buffer + .same_device(state.pass.base.device)?; + + state + .pass + .scope + .buffers + .merge_single(&buffer_transition.buffer, buffer_transition.state)?; + buffer_ids.push(buffer_transition.buffer.tracker_index()); + } + + state + .intermediate_trackers + .buffers + .set_and_remove_from_usage_scope_sparse(&mut state.pass.scope.buffers, buffer_ids); + + // Process texture transitions + for texture_transition in texture_transitions { + texture_transition + .texture + .same_device(state.pass.base.device)?; + + unsafe { + state.pass.scope.textures.merge_single( + &texture_transition.texture.parent, + texture_transition.selector, + texture_transition.state, + ) + }?; + + textures.insert_single(texture_transition.texture, texture_transition.state); + } + + state + .intermediate_trackers + .textures + .set_and_remove_from_usage_scope_sparse(&mut state.pass.scope.textures, &textures); + + // Record any needed barriers based on tracker data + CommandEncoder::drain_barriers( + state.pass.base.raw_encoder, + &mut state.intermediate_trackers, + state.pass.base.snatch_guard, + ); + Ok(()) +} + // Running the compute pass. impl Global { @@ -729,6 +796,14 @@ pub(super) fn encode_compute_pass( end_pipeline_statistics_query(state.pass.base.raw_encoder, &mut state.active_query) .map_pass_err(scope)?; } + ArcComputeCommand::TransitionResources { + buffer_transitions, + texture_transitions, + } => { + let scope = PassErrorScope::TransitionResources; + transition_resources(&mut state, buffer_transitions, texture_transitions) + .map_pass_err(scope)?; + } } } @@ -1316,4 +1391,49 @@ impl Global { Ok(()) } + + pub fn compute_pass_transition_resources( + &self, + pass: &mut ComputePass, + buffer_transitions: impl Iterator>, + texture_transitions: impl Iterator>, + ) -> Result<(), PassStateError> { + let scope = PassErrorScope::TransitionResources; + let base = pass_base!(pass, scope); + + let hub = &self.hub; + let buffer_transitions = pass_try!( + base, + scope, + buffer_transitions + .map(|buffer_transition| -> Result<_, InvalidResourceError> { + Ok(wgt::BufferTransition { + buffer: hub.buffers.get(buffer_transition.buffer).get()?, + state: buffer_transition.state, + }) + }) + .collect::, _>>() + ); + + let texture_transitions = pass_try!( + base, + scope, + texture_transitions + .map(|texture_transition| -> Result<_, InvalidResourceError> { + Ok(wgt::TextureTransition { + texture: hub.texture_views.get(texture_transition.texture).get()?, + selector: texture_transition.selector, + state: texture_transition.state, + }) + }) + .collect::, _>>() + ); + + base.commands.push(ArcComputeCommand::TransitionResources { + buffer_transitions, + texture_transitions, + }); + + Ok(()) + } } diff --git a/wgpu-core/src/command/compute_command.rs b/wgpu-core/src/command/compute_command.rs index ce653a7d9..957b985d1 100644 --- a/wgpu-core/src/command/compute_command.rs +++ b/wgpu-core/src/command/compute_command.rs @@ -1,3 +1,5 @@ +use alloc::vec::Vec; + #[cfg(feature = "serde")] use crate::command::serde_object_reference_struct; use crate::command::{ArcReferences, ReferenceType}; @@ -64,6 +66,11 @@ pub enum ComputeCommand { }, EndPipelineStatisticsQuery, + + TransitionResources { + buffer_transitions: Vec>, + texture_transitions: Vec>, + }, } /// cbindgen:ignore diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index 9160cdb1e..ec759826c 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -2047,6 +2047,8 @@ pub enum PassErrorScope { BeginPipelineStatisticsQuery, #[error("In a end_pipeline_statistics_query command")] EndPipelineStatisticsQuery, + #[error("In a transition_resources command")] + TransitionResources, #[error("In a execute_bundle command")] ExecuteBundle, #[error("In a dispatch command, indirect:{indirect}")] diff --git a/wgpu-core/src/device/trace/record.rs b/wgpu-core/src/device/trace/record.rs index 8c63c7fcc..8757cb01c 100644 --- a/wgpu-core/src/device/trace/record.rs +++ b/wgpu-core/src/device/trace/record.rs @@ -492,6 +492,26 @@ impl IntoTrace for ArcComputeCommand { query_index, }, C::EndPipelineStatisticsQuery => C::EndPipelineStatisticsQuery, + C::TransitionResources { + buffer_transitions, + texture_transitions, + } => C::TransitionResources { + buffer_transitions: buffer_transitions + .into_iter() + .map(|buffer_transition| wgt::BufferTransition { + buffer: buffer_transition.buffer.into_trace(), + state: buffer_transition.state, + }) + .collect(), + texture_transitions: texture_transitions + .into_iter() + .map(|texture_transition| wgt::TextureTransition { + texture: texture_transition.texture.into_trace(), + selector: texture_transition.selector, + state: texture_transition.state, + }) + .collect(), + }, } } } diff --git a/wgpu/src/api/compute_pass.rs b/wgpu/src/api/compute_pass.rs index cbd970be9..034282bc4 100644 --- a/wgpu/src/api/compute_pass.rs +++ b/wgpu/src/api/compute_pass.rs @@ -102,6 +102,53 @@ impl ComputePass<'_> { .dispatch_workgroups_indirect(&indirect_buffer.inner, indirect_offset); } + /// Transition resources to an underlying hal resource state. Compute pass version of + /// [`CommandEncoder::transition_resources`]. + /// + /// This is an advanced, native-only API (no-op on web). Useful for native interoperability. + /// + /// A user wanting to interoperate with the underlying native graphics APIs (Vulkan, DirectX12, Metal, etc) + /// can use this API to generate barriers between wgpu commands and the native API commands, + /// for synchronization and resource state transition purposes. + /// Unlike [`CommandEncoder::transition_resources`], this does not require ending the pass and will + /// use the same semantics and granularity as the automatic barriers inserted for bindings. + /// + /// For example, users might want to pass buffer device addresses into a SPIR-V passthrough shader. + /// These resources cannot be tracked by wgpu since they do not appear in the bindings and will + /// cause data races if not handled - this function allows marking the underlying buffers behind + /// the address as used: + /// + /// ```ignore + /// let buffer_transitions = + /// custom_resources + /// .iter() + /// .map(|resource| wgpu::BufferTransition { + /// buffer: &resource.buffer, + /// state: wgpu::BufferUses::STORAGE_READ_WRITE, + /// }); + /// pass.transition_resources(buffer_transitions, iter::empty()) + /// + /// pass.dispatch_workgroups(x, y, z); + /// ``` + /// + pub fn transition_resources<'a>( + &mut self, + buffer_transitions: impl Iterator>, + texture_transitions: impl Iterator>, + ) { + self.inner.transition_resources( + &mut buffer_transitions.map(|t| wgt::BufferTransition { + buffer: &t.buffer.inner, + state: t.state, + }), + &mut texture_transitions.map(|t| wgt::TextureTransition { + texture: &t.texture.inner, + selector: t.selector, + state: t.state, + }), + ); + } + impl_deferred_command_buffer_actions!(); #[cfg(custom)] diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index c2b37dfb8..b95c1a8e2 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -3406,6 +3406,18 @@ impl dispatch::ComputePassInterface for WebComputePassEncoder { self.inner .dispatch_workgroups_indirect_with_f64(&indirect_buffer.inner, indirect_offset as f64); } + + fn transition_resources<'a>( + &mut self, + _buffer_transitions: &mut dyn Iterator< + Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>, + >, + _texture_transitions: &mut dyn Iterator< + Item = wgt::TextureTransition<&'a dispatch::DispatchTextureView>, + >, + ) { + // noop + } } impl Drop for WebComputePassEncoder { fn drop(&mut self) { diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index 3efe1a5fa..fa810afe4 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -3117,6 +3117,38 @@ impl dispatch::ComputePassInterface for CoreComputePass { ); } } + + fn transition_resources<'a>( + &mut self, + buffer_transitions: &mut dyn Iterator< + Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>, + >, + texture_transitions: &mut dyn Iterator< + Item = wgt::TextureTransition<&'a dispatch::DispatchTextureView>, + >, + ) { + let result = self.context.0.compute_pass_transition_resources( + &mut self.pass, + buffer_transitions.map(|t| wgt::BufferTransition { + buffer: t.buffer.as_core().id, + state: t.state, + }), + texture_transitions.map(|t| wgt::TextureTransition { + texture: t.texture.as_core().id, + selector: t.selector.clone(), + state: t.state, + }), + ); + + if let Err(cause) = result { + self.context.handle_error( + &self.error_sink, + cause, + self.pass.label(), + "ComputePass::transition_resources", + ); + } + } } impl Drop for CoreComputePass { diff --git a/wgpu/src/dispatch.rs b/wgpu/src/dispatch.rs index c497585a8..7df5b8c98 100644 --- a/wgpu/src/dispatch.rs +++ b/wgpu/src/dispatch.rs @@ -409,6 +409,14 @@ pub trait ComputePassInterface: CommonTraits + Drop { indirect_buffer: &DispatchBuffer, indirect_offset: crate::BufferAddress, ); + + fn transition_resources<'a>( + &mut self, + buffer_transitions: &mut dyn Iterator>, + texture_transitions: &mut dyn Iterator< + Item = wgt::TextureTransition<&'a DispatchTextureView>, + >, + ); } pub trait RenderPassInterface: CommonTraits + Drop { fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);