wgpu/api/command_encoder.rs
1use alloc::sync::Arc;
2use core::ops::Range;
3
4use crate::{
5 api::{
6 blas::BlasBuildEntry, impl_deferred_command_buffer_actions, tlas::Tlas,
7 SharedDeferredCommandBufferActions,
8 },
9 *,
10};
11
12/// Encodes a series of GPU operations.
13///
14/// A command encoder can record [`RenderPass`]es, [`ComputePass`]es,
15/// and transfer operations between driver-managed resources like [`Buffer`]s and [`Texture`]s.
16///
17/// When finished recording, call [`CommandEncoder::finish`] to obtain a [`CommandBuffer`] which may
18/// be submitted for execution.
19///
20/// Corresponds to [WebGPU `GPUCommandEncoder`](https://gpuweb.github.io/gpuweb/#command-encoder).
21#[derive(Debug)]
22pub struct CommandEncoder {
23 pub(crate) inner: dispatch::DispatchCommandEncoder,
24 pub(crate) actions: SharedDeferredCommandBufferActions,
25}
26#[cfg(send_sync)]
27static_assertions::assert_impl_all!(CommandEncoder: Send, Sync);
28
29crate::cmp::impl_eq_ord_hash_proxy!(CommandEncoder => .inner);
30
31/// Describes a [`CommandEncoder`].
32///
33/// For use with [`Device::create_command_encoder`].
34///
35/// Corresponds to [WebGPU `GPUCommandEncoderDescriptor`](
36/// https://gpuweb.github.io/gpuweb/#dictdef-gpucommandencoderdescriptor).
37pub type CommandEncoderDescriptor<'a> = wgt::CommandEncoderDescriptor<Label<'a>>;
38static_assertions::assert_impl_all!(CommandEncoderDescriptor<'_>: Send, Sync);
39
40pub use wgt::TexelCopyBufferInfo as TexelCopyBufferInfoBase;
41/// View of a buffer which can be used to copy to/from a texture.
42///
43/// Corresponds to [WebGPU `GPUTexelCopyBufferInfo`](
44/// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopybuffer).
45pub type TexelCopyBufferInfo<'a> = TexelCopyBufferInfoBase<&'a Buffer>;
46#[cfg(send_sync)]
47static_assertions::assert_impl_all!(TexelCopyBufferInfo<'_>: Send, Sync);
48
49pub use wgt::TexelCopyTextureInfo as TexelCopyTextureInfoBase;
50/// View of a texture which can be used to copy to/from a buffer/texture.
51///
52/// Corresponds to [WebGPU `GPUTexelCopyTextureInfo`](
53/// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopytexture).
54pub type TexelCopyTextureInfo<'a> = TexelCopyTextureInfoBase<&'a Texture>;
55#[cfg(send_sync)]
56static_assertions::assert_impl_all!(TexelCopyTextureInfo<'_>: Send, Sync);
57
58impl CommandEncoder {
59 /// Finishes recording and returns a [`CommandBuffer`] that can be submitted for execution.
60 pub fn finish(self) -> CommandBuffer {
61 let Self { mut inner, actions } = self;
62 let buffer = inner.finish();
63 CommandBuffer { buffer, actions }
64 }
65
66 /// Begins recording of a render pass.
67 ///
68 /// This function returns a [`RenderPass`] object which records a single render pass.
69 ///
70 /// As long as the returned [`RenderPass`] has not ended,
71 /// any mutating operation on this command encoder causes an error and invalidates it.
72 /// Note that the `'encoder` lifetime relationship protects against this,
73 /// but it is possible to opt out of it by calling [`RenderPass::forget_lifetime`].
74 /// This can be useful for runtime handling of the encoder->pass
75 /// dependency e.g. when pass and encoder are stored in the same data structure.
76 pub fn begin_render_pass<'encoder>(
77 &'encoder mut self,
78 desc: &RenderPassDescriptor<'_>,
79 ) -> RenderPass<'encoder> {
80 let rpass = self.inner.begin_render_pass(desc);
81 RenderPass {
82 inner: rpass,
83 actions: Arc::clone(&self.actions),
84 _encoder_guard: api::PhantomDrop::default(),
85 }
86 }
87
88 /// Begins recording of a compute pass.
89 ///
90 /// This function returns a [`ComputePass`] object which records a single compute pass.
91 ///
92 /// As long as the returned [`ComputePass`] has not ended,
93 /// any mutating operation on this command encoder causes an error and invalidates it.
94 /// Note that the `'encoder` lifetime relationship protects against this,
95 /// but it is possible to opt out of it by calling [`ComputePass::forget_lifetime`].
96 /// This can be useful for runtime handling of the encoder->pass
97 /// dependency e.g. when pass and encoder are stored in the same data structure.
98 pub fn begin_compute_pass<'encoder>(
99 &'encoder mut self,
100 desc: &ComputePassDescriptor<'_>,
101 ) -> ComputePass<'encoder> {
102 let cpass = self.inner.begin_compute_pass(desc);
103 ComputePass {
104 inner: cpass,
105 actions: Arc::clone(&self.actions),
106 _encoder_guard: api::PhantomDrop::default(),
107 }
108 }
109
110 /// Begins recording of a ray tracing pass.
111 ///
112 /// This function returns a [`RayTracingPass`] object which records a single ray tracing pass.
113 ///
114 /// As long as the returned [`RayTracingPass`] has not ended,
115 /// any mutating operation on this command encoder causes an error and invalidates it.
116 /// Note that the `'encoder` lifetime relationship protects against this,
117 /// but it is possible to opt out of it by calling [`RayTracingPass::forget_lifetime`].
118 /// This can be useful for runtime handling of the encoder->pass
119 /// dependency e.g. when pass and encoder are stored in the same data structure.
120 pub fn begin_ray_tracing_pass<'encoder>(
121 &'encoder mut self,
122 desc: &RayTracingPassDescriptor<'_>,
123 ) -> RayTracingPass<'encoder> {
124 let rtpass = self.inner.begin_ray_tracing_pass(desc);
125 RayTracingPass {
126 inner: rtpass,
127 actions: Arc::clone(&self.actions),
128 _encoder_guard: api::PhantomDrop::default(),
129 }
130 }
131
132 /// Copy data from one buffer to another.
133 ///
134 /// # Panics
135 ///
136 /// - Buffer offsets or copy size not a multiple of [`COPY_BUFFER_ALIGNMENT`].
137 /// - Copy would overrun buffer.
138 /// - Copy within the same buffer.
139 pub fn copy_buffer_to_buffer(
140 &mut self,
141 source: &Buffer,
142 source_offset: BufferAddress,
143 destination: &Buffer,
144 destination_offset: BufferAddress,
145 copy_size: impl Into<Option<BufferAddress>>,
146 ) {
147 self.inner.copy_buffer_to_buffer(
148 &source.inner,
149 source_offset,
150 &destination.inner,
151 destination_offset,
152 copy_size.into(),
153 );
154 }
155
156 /// Copy data from a buffer to a texture.
157 pub fn copy_buffer_to_texture(
158 &mut self,
159 source: TexelCopyBufferInfo<'_>,
160 destination: TexelCopyTextureInfo<'_>,
161 copy_size: Extent3d,
162 ) {
163 self.inner
164 .copy_buffer_to_texture(source, destination, copy_size);
165 }
166
167 /// Copy data from a texture to a buffer.
168 pub fn copy_texture_to_buffer(
169 &mut self,
170 source: TexelCopyTextureInfo<'_>,
171 destination: TexelCopyBufferInfo<'_>,
172 copy_size: Extent3d,
173 ) {
174 self.inner
175 .copy_texture_to_buffer(source, destination, copy_size);
176 }
177
178 /// Copy data from one texture to another.
179 ///
180 /// # Panics
181 ///
182 /// - Textures are not the same type
183 /// - If a depth texture, or a multisampled texture, the entire texture must be copied
184 /// - Copy would overrun either texture
185 pub fn copy_texture_to_texture(
186 &mut self,
187 source: TexelCopyTextureInfo<'_>,
188 destination: TexelCopyTextureInfo<'_>,
189 copy_size: Extent3d,
190 ) {
191 self.inner
192 .copy_texture_to_texture(source, destination, copy_size);
193 }
194
195 /// Clears texture to zero.
196 ///
197 /// Requires [`Features::CLEAR_TEXTURE`].
198 ///
199 /// Unlike [`Self::clear_buffer`], `COPY_DST` usage is not required. The
200 /// texture will be cleared either by buffer copies or by a render pass with
201 /// [`LoadOp::Clear`], depending on the texture format and enabled usages.
202 ///
203 /// Unlike when `wgpu` internally marks a texture as uninitialized, the
204 /// clear will always occur at the point in the command stream where
205 /// `clear_texture` is called. It will not be deferred until a subsequent
206 /// operation reads data from the texture.
207 ///
208 /// Although [`ImageSubresourceRange`] contains an `aspect` member, it must
209 /// either be [`wgt::TextureAspect::All`], or it must select all aspects of
210 /// the texture. Requesting to selectively clear only some aspects is an
211 /// error.
212 pub fn clear_texture(&mut self, texture: &Texture, subresource_range: &ImageSubresourceRange) {
213 self.inner.clear_texture(&texture.inner, subresource_range);
214 }
215
216 /// Clears buffer to zero.
217 ///
218 /// # Panics
219 ///
220 /// - Buffer does not have `COPY_DST` usage.
221 /// - Range is out of bounds
222 pub fn clear_buffer(
223 &mut self,
224 buffer: &Buffer,
225 offset: BufferAddress,
226 size: Option<BufferAddress>,
227 ) {
228 self.inner.clear_buffer(&buffer.inner, offset, size);
229 }
230
231 /// Inserts debug marker.
232 pub fn insert_debug_marker(&mut self, label: &str) {
233 self.inner.insert_debug_marker(label);
234 }
235
236 /// Start record commands and group it into debug marker group.
237 pub fn push_debug_group(&mut self, label: &str) {
238 self.inner.push_debug_group(label);
239 }
240
241 /// Stops command recording and creates debug group.
242 pub fn pop_debug_group(&mut self) {
243 self.inner.pop_debug_group();
244 }
245
246 /// Copies query results stored in `query_set` into `destination` so that they can be read
247 /// by compute shaders or buffer operations.
248 ///
249 /// * `query_range` is the range of query result indices to copy from `query_set`.
250 /// Occlusion and timestamp queries occupy 1 result index each;
251 /// for pipeline statistics queries, see [`PipelineStatisticsTypes`].
252 /// * `destination_offset` is the offset within `destination` to start writing at.
253 /// It must be a multiple of [`QUERY_RESOLVE_BUFFER_ALIGNMENT`].
254 ///
255 /// The length of the data written to `destination` will be 8 bytes ([`QUERY_SIZE`])
256 /// times the number of elements in `query_range`.
257 ///
258 /// For further information about using queries, see [`QuerySet`].
259 pub fn resolve_query_set(
260 &mut self,
261 query_set: &QuerySet,
262 query_range: Range<u32>,
263 destination: &Buffer,
264 destination_offset: BufferAddress,
265 ) {
266 self.inner.resolve_query_set(
267 &query_set.inner,
268 query_range.start,
269 query_range.end - query_range.start,
270 &destination.inner,
271 destination_offset,
272 );
273 }
274
275 impl_deferred_command_buffer_actions!();
276
277 /// Get the [`wgpu_hal`] command encoder from this `CommandEncoder`.
278 ///
279 /// The returned command encoder will be ready to record onto.
280 ///
281 /// # Errors
282 ///
283 /// This method will pass in [`None`] if:
284 /// - The encoder is not from the backend specified by `A`.
285 /// - The encoder is from the `webgpu` or `custom` backend.
286 ///
287 /// # Types
288 ///
289 /// The callback argument depends on the backend:
290 ///
291 #[doc = crate::macros::hal_type_vulkan!("CommandEncoder")]
292 #[doc = crate::macros::hal_type_metal!("CommandEncoder")]
293 #[doc = crate::macros::hal_type_dx12!("CommandEncoder")]
294 #[doc = crate::macros::hal_type_gles!("CommandEncoder")]
295 ///
296 /// # Safety
297 ///
298 /// - The raw handle obtained from the `A::CommandEncoder` must not be manually destroyed.
299 /// - You must not end the command buffer; wgpu will do it when you call finish.
300 /// - The wgpu command encoder must not be interacted with in any way while recording is
301 /// happening to the wgpu_hal or backend command encoder.
302 #[cfg(wgpu_core)]
303 pub unsafe fn as_hal_mut<A: hal::Api, F: FnOnce(Option<&mut A::CommandEncoder>) -> R, R>(
304 &mut self,
305 hal_command_encoder_callback: F,
306 ) -> R {
307 if let Some(encoder) = self.inner.as_core_mut_opt() {
308 unsafe { encoder.as_hal_mut::<A, F, R>(hal_command_encoder_callback) }
309 } else {
310 hal_command_encoder_callback(None)
311 }
312 }
313
314 #[cfg(custom)]
315 /// Returns custom implementation of CommandEncoder (if custom backend and is internally T)
316 pub fn as_custom<T: custom::CommandEncoderInterface>(&self) -> Option<&T> {
317 self.inner.as_custom()
318 }
319}
320
321/// [`Features::TIMESTAMP_QUERY_INSIDE_ENCODERS`] must be enabled on the device in order to call these functions.
322impl CommandEncoder {
323 /// Issue a timestamp command at this point in the queue.
324 /// The timestamp will be written to the specified query set, at the specified index.
325 ///
326 /// Must be multiplied by [`Queue::get_timestamp_period`] to get
327 /// the value in nanoseconds. Absolute values have no meaning,
328 /// but timestamps can be subtracted to get the time it takes
329 /// for a string of operations to complete.
330 ///
331 /// Attention: Since commands within a command recorder may be reordered,
332 /// there is no strict guarantee that timestamps are taken after all commands
333 /// recorded so far and all before all commands recorded after.
334 /// This may depend both on the backend and the driver.
335 pub fn write_timestamp(&mut self, query_set: &QuerySet, query_index: u32) {
336 self.inner.write_timestamp(&query_set.inner, query_index);
337 }
338}
339
340/// [`Features::EXPERIMENTAL_RAY_QUERY`] must be enabled on the device in order to call these functions.
341impl CommandEncoder {
342 /// When encoding the acceleration structure build with the raw Hal encoder
343 /// (obtained from [`CommandEncoder::as_hal_mut`]), this function marks the
344 /// acceleration structures as having been built.
345 ///
346 /// This function must only be used with the raw encoder API. When using the
347 /// wgpu encoding API, acceleration structure build is tracked automatically.
348 ///
349 /// # Panics
350 ///
351 /// - If the encoder is being used with the wgpu encoding API.
352 ///
353 /// # Safety
354 ///
355 /// - All acceleration structures must have been build in this command encoder.
356 /// - All BLASes inputted must have been built before all TLASes that were inputted here and
357 /// which use them.
358 pub unsafe fn mark_acceleration_structures_built<'a>(
359 &self,
360 blas: impl IntoIterator<Item = &'a Blas>,
361 tlas: impl IntoIterator<Item = &'a Tlas>,
362 ) {
363 self.inner
364 .mark_acceleration_structures_built(&mut blas.into_iter(), &mut tlas.into_iter())
365 }
366 /// Build bottom and top level acceleration structures.
367 ///
368 /// Builds the BLASes then the TLASes, but does ***not*** build the BLASes into the TLASes,
369 /// that must be done by setting a TLAS instance in the TLAS package to one that contains the BLAS (and with an appropriate transform)
370 ///
371 /// # Validation
372 ///
373 /// - blas: Iterator of bottom level acceleration structure entries to build.
374 /// For each entry, the provided size descriptor must be strictly smaller or equal to the descriptor given at BLAS creation, this means:
375 /// - Less or equal number of geometries
376 /// - Same kind of geometry (with index buffer or without) (same vertex/index format)
377 /// - Same flags
378 /// - Less or equal number of vertices
379 /// - Less or equal number of indices (if applicable)
380 /// - tlas: iterator of top level acceleration structure packages to build
381 /// For each entry:
382 /// - Each BLAS in each TLAS instance must have been being built in the current call or in a previous call to `build_acceleration_structures` or `build_acceleration_structures_unsafe_tlas`
383 /// - The number of TLAS instances must be less than or equal to the max number of tlas instances when creating (if creating a package with `TlasPackage::new()` this is already satisfied)
384 ///
385 /// If the device the command encoder is created from does not have [Features::EXPERIMENTAL_RAY_QUERY] enabled then a validation error is generated
386 ///
387 /// A bottom level acceleration structure may be build and used as a reference in a top level acceleration structure in the same invocation of this function.
388 ///
389 /// # Bind group usage
390 ///
391 /// When a top level acceleration structure is used in a bind group, some validation takes place:
392 /// - The top level acceleration structure is valid and has been built.
393 /// - All the bottom level acceleration structures referenced by the top level acceleration structure are valid and have been built prior,
394 /// or at same time as the containing top level acceleration structure.
395 ///
396 /// [Features::EXPERIMENTAL_RAY_QUERY]: wgt::Features::EXPERIMENTAL_RAY_QUERY
397 pub fn build_acceleration_structures<'a>(
398 &mut self,
399 blas: impl IntoIterator<Item = &'a BlasBuildEntry<'a>>,
400 tlas: impl IntoIterator<Item = &'a Tlas>,
401 ) {
402 self.inner
403 .build_acceleration_structures(&mut blas.into_iter(), &mut tlas.into_iter());
404 }
405
406 /// Transition resources to an underlying hal resource state.
407 ///
408 /// This is an advanced, native-only API (no-op on web) that has two main use cases:
409 ///
410 /// # Batching Barriers
411 ///
412 /// Wgpu does not have a global view of the frame when recording command buffers. When you submit multiple command buffers in a single queue submission, wgpu may need to record and
413 /// insert new command buffers (holding 1 or more barrier commands) in between the user-supplied command buffers in order to ensure that resources are transitioned to the correct state
414 /// for the start of the next user-supplied command buffer.
415 ///
416 /// Wgpu does not currently attempt to batch multiple of these generated command buffers/barriers together, which may lead to suboptimal barrier placement.
417 ///
418 /// Consider the following scenario, where the user does `queue.submit(&[a, b, c])`:
419 /// * CommandBuffer A: Use resource X as a render pass attachment
420 /// * CommandBuffer B: Use resource Y as a render pass attachment
421 /// * CommandBuffer C: Use resources X and Y in a bind group
422 ///
423 /// At submission time, wgpu will record and insert some new command buffers, resulting in a submission that looks like `queue.submit(&[0, a, 1, b, 2, c])`:
424 /// * CommandBuffer 0: Barrier to transition resource X from TextureUses::RESOURCE (from last frame) to TextureUses::COLOR_TARGET
425 /// * CommandBuffer A: Use resource X as a render pass attachment
426 /// * CommandBuffer 1: Barrier to transition resource Y from TextureUses::RESOURCE (from last frame) to TextureUses::COLOR_TARGET
427 /// * CommandBuffer B: Use resource Y as a render pass attachment
428 /// * CommandBuffer 2: Barrier to transition resources X and Y from TextureUses::COLOR_TARGET to TextureUses::RESOURCE
429 /// * CommandBuffer C: Use resources X and Y in a bind group
430 ///
431 /// To prevent this, after profiling their app, an advanced user might choose to instead do `queue.submit(&[a, b, c])`:
432 /// * CommandBuffer A:
433 /// * Use [`CommandEncoder::transition_resources`] to transition resources X and Y from TextureUses::RESOURCE (from last frame) to TextureUses::COLOR_TARGET
434 /// * Use resource X as a render pass attachment
435 /// * CommandBuffer B: Use resource Y as a render pass attachment
436 /// * CommandBuffer C:
437 /// * Use [`CommandEncoder::transition_resources`] to transition resources X and Y from TextureUses::COLOR_TARGET to TextureUses::RESOURCE
438 /// * Use resources X and Y in a bind group
439 ///
440 /// At submission time, wgpu will record and insert some new command buffers, resulting in a submission that looks like `queue.submit(&[0, a, b, 1, c])`:
441 /// * CommandBuffer 0: Barrier to transition resources X and Y from TextureUses::RESOURCE (from last frame) to TextureUses::COLOR_TARGET
442 /// * CommandBuffer A: Use resource X as a render pass attachment
443 /// * CommandBuffer B: Use resource Y as a render pass attachment
444 /// * CommandBuffer 1: Barrier to transition resources X and Y from TextureUses::COLOR_TARGET to TextureUses::RESOURCE
445 /// * CommandBuffer C: Use resources X and Y in a bind group
446 ///
447 /// Which eliminates the extra command buffer and barrier between command buffers A and B.
448 ///
449 /// # Native Interoperability
450 ///
451 /// 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
452 /// the native API commands, for synchronization and resource state transition purposes.
453 pub fn transition_resources<'a>(
454 &mut self,
455 buffer_transitions: impl Iterator<Item = wgt::BufferTransition<&'a Buffer>>,
456 texture_transitions: impl Iterator<Item = wgt::TextureTransition<&'a Texture>>,
457 ) {
458 self.inner.transition_resources(
459 &mut buffer_transitions.map(|t| wgt::BufferTransition {
460 buffer: &t.buffer.inner,
461 state: t.state,
462 }),
463 &mut texture_transitions.map(|t| wgt::TextureTransition {
464 texture: &t.texture.inner,
465 selector: t.selector,
466 state: t.state,
467 }),
468 );
469 }
470}
471
472#[cfg(wgpu_core)]
473impl CommandEncoder {
474 /// Create a new command encoder of wgpu from a wgpu-core command encoder.
475 ///
476 /// # Arguments
477 ///
478 /// - `core_encoder` - wgpu-core command encoder.
479 pub fn from_core(core_encoder: alloc::sync::Arc<wgc::command::CommandEncoder>) -> Self {
480 Self {
481 inner: crate::backend::wgpu_core::CoreCommandEncoder::from_core(core_encoder).into(),
482 actions: SharedDeferredCommandBufferActions::default(),
483 }
484 }
485
486 /// Returns the underlying wgpu-core command encoder if this `CommandEncoder` is on the wgpu-core backend, otherwise `None`.
487 pub fn as_core(&self) -> Option<alloc::sync::Arc<wgc::command::CommandEncoder>> {
488 self.inner.as_core_opt().map(|cd| cd.as_core())
489 }
490}