Skip to main content

wgpu_core/command/
clear.rs

1use alloc::{string::String, sync::Arc, vec::Vec};
2use core::ops::Range;
3
4use crate::{
5    api_log,
6    command::{encoder::EncodingState, ArcCommand, EncoderStateError},
7    device::{DeviceError, MissingFeatures},
8    get_lowest_common_denom,
9    global::Global,
10    hal_label,
11    id::{BufferId, CommandEncoderId, TextureId},
12    init_tracker::{MemoryInitKind, TextureInitRange},
13    resource::{
14        Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError,
15        Labeled, MissingBufferUsageError, ParentDevice, RawResourceAccess, ResourceErrorIdent,
16        Texture, TextureClearMode,
17    },
18    snatch::SnatchGuard,
19    track::TextureTrackerSetSingle,
20};
21
22use thiserror::Error;
23use wgt::{
24    error::{ErrorType, WebGpuError},
25    math::align_to,
26    BufferAddress, BufferUsages, ImageSubresourceRange, TextureAspect, TextureSelector,
27};
28
29/// Error encountered while attempting a clear.
30#[derive(Clone, Debug, Error)]
31#[non_exhaustive]
32pub enum ClearError {
33    #[error(transparent)]
34    DestroyedResource(#[from] DestroyedResourceError),
35    #[error(transparent)]
36    MissingFeatures(#[from] MissingFeatures),
37    #[error("{0} can not be cleared")]
38    NoValidTextureClearMode(ResourceErrorIdent),
39    #[error("Buffer clear size {0:?} is not a multiple of `COPY_BUFFER_ALIGNMENT`")]
40    UnalignedFillSize(BufferAddress),
41    #[error("Buffer offset {0:?} is not a multiple of `COPY_BUFFER_ALIGNMENT`")]
42    UnalignedBufferOffset(BufferAddress),
43    #[error("Clear starts at offset {start_offset} with size of {requested_size}, but these added together exceed `u64::MAX`")]
44    OffsetPlusSizeExceeds64BitBounds {
45        start_offset: BufferAddress,
46        requested_size: BufferAddress,
47    },
48    #[error("Clear of {start_offset}..{end_offset} would end up overrunning the bounds of the buffer of size {buffer_size}")]
49    BufferOverrun {
50        start_offset: BufferAddress,
51        end_offset: BufferAddress,
52        buffer_size: BufferAddress,
53    },
54    #[error(transparent)]
55    MissingBufferUsage(#[from] MissingBufferUsageError),
56    #[error("Texture lacks the aspects that were specified in the image subresource range. Texture with format {texture_format:?}, specified was {subresource_range_aspects:?}")]
57    MissingTextureAspect {
58        texture_format: wgt::TextureFormat,
59        subresource_range_aspects: TextureAspect,
60    },
61    #[error("Image subresource level range is outside of the texture's level range. texture range is {texture_level_range:?},  \
62whereas subesource range specified start {subresource_base_mip_level} and count {subresource_mip_level_count:?}")]
63    InvalidTextureLevelRange {
64        texture_level_range: Range<u32>,
65        subresource_base_mip_level: u32,
66        subresource_mip_level_count: Option<u32>,
67    },
68    #[error("Image subresource layer range is outside of the texture's layer range. texture range is {texture_layer_range:?},  \
69whereas subesource range specified start {subresource_base_array_layer} and count {subresource_array_layer_count:?}")]
70    InvalidTextureLayerRange {
71        texture_layer_range: Range<u32>,
72        subresource_base_array_layer: u32,
73        subresource_array_layer_count: Option<u32>,
74    },
75    #[error(transparent)]
76    Device(#[from] DeviceError),
77    #[error(transparent)]
78    EncoderState(#[from] EncoderStateError),
79    #[error(transparent)]
80    InvalidResource(#[from] InvalidResourceError),
81}
82
83impl From<InvalidOrDestroyedResourceError> for ClearError {
84    fn from(value: InvalidOrDestroyedResourceError) -> Self {
85        match value {
86            InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
87            InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
88        }
89    }
90}
91
92impl WebGpuError for ClearError {
93    fn webgpu_error_type(&self) -> ErrorType {
94        match self {
95            Self::DestroyedResource(e) => e.webgpu_error_type(),
96            Self::MissingFeatures(e) => e.webgpu_error_type(),
97            Self::MissingBufferUsage(e) => e.webgpu_error_type(),
98            Self::Device(e) => e.webgpu_error_type(),
99            Self::EncoderState(e) => e.webgpu_error_type(),
100            Self::InvalidResource(e) => e.webgpu_error_type(),
101            Self::NoValidTextureClearMode(..)
102            | Self::UnalignedFillSize(..)
103            | Self::UnalignedBufferOffset(..)
104            | Self::OffsetPlusSizeExceeds64BitBounds { .. }
105            | Self::BufferOverrun { .. }
106            | Self::MissingTextureAspect { .. }
107            | Self::InvalidTextureLevelRange { .. }
108            | Self::InvalidTextureLayerRange { .. } => ErrorType::Validation,
109        }
110    }
111}
112
113impl Global {
114    pub fn command_encoder_clear_buffer(
115        &self,
116        command_encoder_id: CommandEncoderId,
117        dst: BufferId,
118        offset: BufferAddress,
119        size: Option<BufferAddress>,
120    ) -> Result<(), EncoderStateError> {
121        profiling::scope!("CommandEncoder::clear_buffer");
122        api_log!("CommandEncoder::clear_buffer {dst:?}");
123
124        let hub = &self.hub;
125
126        let cmd_enc = hub.command_encoders.get(command_encoder_id);
127        let mut cmd_buf_data = cmd_enc.data.lock();
128
129        cmd_buf_data.push_with(|| -> Result<_, ClearError> {
130            Ok(ArcCommand::ClearBuffer {
131                dst: self.resolve_buffer_id(dst)?,
132                offset,
133                size,
134            })
135        })
136    }
137
138    pub fn command_encoder_clear_texture(
139        &self,
140        command_encoder_id: CommandEncoderId,
141        dst: TextureId,
142        subresource_range: &ImageSubresourceRange,
143    ) -> Result<(), EncoderStateError> {
144        profiling::scope!("CommandEncoder::clear_texture");
145        api_log!("CommandEncoder::clear_texture {dst:?}");
146
147        let hub = &self.hub;
148
149        let cmd_enc = hub.command_encoders.get(command_encoder_id);
150
151        let mut cmd_buf_data = cmd_enc.data.lock();
152
153        cmd_buf_data.push_with(|| -> Result<_, ClearError> {
154            let texture = self.resolve_texture_id(dst);
155            texture.check_valid(&cmd_enc.device.snatchable_lock.read())?;
156            Ok(ArcCommand::ClearTexture {
157                dst: texture,
158                subresource_range: *subresource_range,
159            })
160        })
161    }
162}
163
164#[inline(never)]
165pub(super) fn clear_buffer(
166    state: &mut EncodingState,
167    dst_buffer: Arc<Buffer>,
168    offset: BufferAddress,
169    size: Option<BufferAddress>,
170) -> Result<(), ClearError> {
171    dst_buffer.same_device(state.device)?;
172
173    let dst_pending = state
174        .tracker
175        .buffers
176        .set_single(&dst_buffer, wgt::BufferUses::COPY_DST);
177
178    let dst_raw = dst_buffer.try_raw(state.snatch_guard)?;
179    dst_buffer.check_usage(BufferUsages::COPY_DST)?;
180
181    // Check if offset & size are valid.
182    if !offset.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
183        return Err(ClearError::UnalignedBufferOffset(offset));
184    }
185
186    let size = size.unwrap_or(dst_buffer.size.saturating_sub(offset));
187    if !size.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
188        return Err(ClearError::UnalignedFillSize(size));
189    }
190    let end_offset =
191        offset
192            .checked_add(size)
193            .ok_or(ClearError::OffsetPlusSizeExceeds64BitBounds {
194                start_offset: offset,
195                requested_size: size,
196            })?;
197    if end_offset > dst_buffer.size {
198        return Err(ClearError::BufferOverrun {
199            start_offset: offset,
200            end_offset,
201            buffer_size: dst_buffer.size,
202        });
203    }
204
205    // This must happen after parameter validation (so that errors are reported
206    // as required by the spec), but before any side effects.
207    if offset == end_offset {
208        log::trace!("Ignoring fill_buffer of size 0");
209        return Ok(());
210    }
211
212    // Mark dest as initialized.
213    state
214        .buffer_memory_init_actions
215        .extend(dst_buffer.initialization_status.read().create_action(
216            &dst_buffer,
217            offset..end_offset,
218            MemoryInitKind::ImplicitlyInitialized,
219        ));
220
221    // actual hal barrier & operation
222    let dst_barrier = dst_pending.map(|pending| pending.into_hal(&dst_buffer, state.snatch_guard));
223    unsafe {
224        state.raw_encoder.transition_buffers(dst_barrier.as_slice());
225        state.raw_encoder.clear_buffer(dst_raw, offset..end_offset);
226    }
227
228    Ok(())
229}
230
231/// Validate and encode a "Clear Texture" command.
232///
233/// This function implements `CommandEncoder::clear_texture` when invoked via
234/// the command encoder APIs or trace playback. It has the suffix `_cmd` to
235/// distinguish it from [`clear_texture`]. [`clear_texture`], used internally by
236/// this function, is a lower-level function that encodes a texture clear
237/// operation without validating it.
238#[inline(never)]
239pub(super) fn clear_texture_cmd(
240    state: &mut EncodingState,
241    dst_texture: Arc<Texture>,
242    subresource_range: &ImageSubresourceRange,
243) -> Result<(), ClearError> {
244    dst_texture.same_device(state.device)?;
245    state
246        .device
247        .require_features(wgt::Features::CLEAR_TEXTURE)?;
248
249    // Check if subresource aspects are valid.
250    let clear_aspects = hal::FormatAspects::new(dst_texture.desc.format, subresource_range.aspect);
251    if clear_aspects.is_empty() {
252        return Err(ClearError::MissingTextureAspect {
253            texture_format: dst_texture.desc.format,
254            subresource_range_aspects: subresource_range.aspect,
255        });
256    };
257
258    // Check if subresource level range is valid
259    let subresource_mip_range = subresource_range.mip_range(dst_texture.full_range.mips.end);
260    if dst_texture.full_range.mips.start > subresource_mip_range.start
261        || dst_texture.full_range.mips.end < subresource_mip_range.end
262    {
263        return Err(ClearError::InvalidTextureLevelRange {
264            texture_level_range: dst_texture.full_range.mips.clone(),
265            subresource_base_mip_level: subresource_range.base_mip_level,
266            subresource_mip_level_count: subresource_range.mip_level_count,
267        });
268    }
269    // Check if subresource layer range is valid
270    let subresource_layer_range = subresource_range.layer_range(dst_texture.full_range.layers.end);
271    if dst_texture.full_range.layers.start > subresource_layer_range.start
272        || dst_texture.full_range.layers.end < subresource_layer_range.end
273    {
274        return Err(ClearError::InvalidTextureLayerRange {
275            texture_layer_range: dst_texture.full_range.layers.clone(),
276            subresource_base_array_layer: subresource_range.base_array_layer,
277            subresource_array_layer_count: subresource_range.array_layer_count,
278        });
279    }
280
281    clear_texture(
282        &dst_texture,
283        TextureInitRange {
284            mip_range: subresource_mip_range,
285            layer_range: subresource_layer_range,
286        },
287        state.raw_encoder,
288        &mut state.tracker.textures,
289        &state.device.alignments,
290        state.device.zero_buffer.as_ref(),
291        state.snatch_guard,
292        state.device.instance_flags,
293    )?;
294
295    Ok(())
296}
297
298/// Encode a texture clear operation.
299///
300/// This function encodes a texture clear operation without validating it.
301/// Texture clears requested via the API call this function via
302/// [`clear_texture_cmd`], which does the validation. This function is also
303/// called directly from various places within wgpu that need to clear a
304/// texture.
305pub(crate) fn clear_texture<T: TextureTrackerSetSingle>(
306    dst_texture: &Arc<Texture>,
307    range: TextureInitRange,
308    encoder: &mut dyn hal::DynCommandEncoder,
309    texture_tracker: &mut T,
310    alignments: &hal::Alignments,
311    zero_buffer: &dyn hal::DynBuffer,
312    snatch_guard: &SnatchGuard<'_>,
313    instance_flags: wgt::InstanceFlags,
314) -> Result<(), ClearError> {
315    let dst_raw = dst_texture.try_inner(snatch_guard)?.raw();
316
317    // Issue the right barrier.
318    let clear_usage = match *dst_texture.clear_mode.read() {
319        TextureClearMode::BufferCopy => wgt::TextureUses::COPY_DST,
320        TextureClearMode::RenderPass {
321            is_color: false, ..
322        } => wgt::TextureUses::DEPTH_STENCIL_WRITE,
323        TextureClearMode::Surface { .. } | TextureClearMode::RenderPass { is_color: true, .. } => {
324            wgt::TextureUses::COLOR_TARGET
325        }
326        TextureClearMode::None => {
327            return Err(ClearError::NoValidTextureClearMode(
328                dst_texture.error_ident(),
329            ));
330        }
331    };
332
333    let selector = TextureSelector {
334        mips: range.mip_range.clone(),
335        layers: range.layer_range.clone(),
336    };
337
338    // If we're in a texture-init usecase, we know that the texture is already
339    // tracked since whatever caused the init requirement, will have caused the
340    // usage tracker to be aware of the texture. Meaning, that it is safe to
341    // call call change_replace_tracked if the life_guard is already gone (i.e.
342    // the user no longer holds on to this texture).
343    //
344    // On the other hand, when coming via command_encoder_clear_texture, the
345    // life_guard is still there since in order to call it a texture object is
346    // needed.
347    //
348    // We could in theory distinguish these two scenarios in the internal
349    // clear_texture api in order to remove this check and call the cheaper
350    // change_replace_tracked whenever possible.
351    let dst_barrier = texture_tracker
352        .set_single(dst_texture, selector, clear_usage)
353        .map(|pending| pending.into_hal(dst_raw))
354        .collect::<Vec<_>>();
355    unsafe {
356        encoder.transition_textures(&dst_barrier);
357    }
358
359    // Record actual clearing
360    let clear_mode = dst_texture.clear_mode.read();
361    match *clear_mode {
362        TextureClearMode::BufferCopy => clear_texture_via_buffer_copies(
363            &dst_texture.desc,
364            alignments,
365            zero_buffer,
366            range,
367            encoder,
368            dst_raw,
369        ),
370        TextureClearMode::Surface { .. } => {
371            drop(clear_mode);
372            clear_texture_via_render_passes(dst_texture, range, true, encoder, instance_flags)?
373        }
374        TextureClearMode::RenderPass { is_color, .. } => {
375            drop(clear_mode);
376            clear_texture_via_render_passes(dst_texture, range, is_color, encoder, instance_flags)?
377        }
378        TextureClearMode::None => {
379            return Err(ClearError::NoValidTextureClearMode(
380                dst_texture.error_ident(),
381            ));
382        }
383    }
384    Ok(())
385}
386
387fn clear_texture_via_buffer_copies(
388    texture_desc: &wgt::TextureDescriptor<String, Vec<wgt::TextureFormat>>,
389    alignments: &hal::Alignments,
390    zero_buffer: &dyn hal::DynBuffer, // Buffer of size device::ZERO_BUFFER_SIZE
391    range: TextureInitRange,
392    encoder: &mut dyn hal::DynCommandEncoder,
393    dst_raw: &dyn hal::DynTexture,
394) {
395    assert!(!texture_desc.format.is_depth_stencil_format());
396
397    if texture_desc.format == wgt::TextureFormat::NV12
398        || texture_desc.format == wgt::TextureFormat::P010
399    {
400        // TODO: Currently COPY_DST for NV12 and P010 textures is unsupported.
401        return;
402    }
403
404    // Gather list of zero_buffer copies and issue a single command then to perform them
405    let mut zero_buffer_copy_regions = Vec::new();
406    let buffer_copy_pitch = alignments.buffer_copy_pitch.get() as u32;
407    let (block_width, block_height) = texture_desc.format.block_dimensions();
408    let block_size = texture_desc.format.block_copy_size(None).unwrap();
409
410    let bytes_per_row_alignment = get_lowest_common_denom(buffer_copy_pitch, block_size);
411
412    for mip_level in range.mip_range {
413        let mut mip_size = texture_desc.mip_level_size(mip_level).unwrap();
414        // Round to multiple of block size
415        mip_size.width = align_to(mip_size.width, block_width);
416        mip_size.height = align_to(mip_size.height, block_height);
417
418        let bytes_per_row = align_to(
419            mip_size.width / block_width * block_size,
420            bytes_per_row_alignment,
421        );
422
423        let max_rows_per_copy = crate::device::ZERO_BUFFER_SIZE as u32 / bytes_per_row;
424        // round down to a multiple of rows needed by the texture format
425        let max_rows_per_copy = max_rows_per_copy / block_height * block_height;
426        assert!(
427            max_rows_per_copy > 0,
428            "Zero buffer size is too small to fill a single row \
429            of a texture with format {:?} and desc {:?}",
430            texture_desc.format,
431            texture_desc.size
432        );
433
434        let z_range = 0..(if texture_desc.dimension == wgt::TextureDimension::D3 {
435            mip_size.depth_or_array_layers
436        } else {
437            1
438        });
439
440        for array_layer in range.layer_range.clone() {
441            // TODO: Only doing one layer at a time for volume textures right now.
442            for z in z_range.clone() {
443                // May need multiple copies for each subresource! However, we
444                // assume that we never need to split a row.
445                let mut num_rows_left = mip_size.height;
446                while num_rows_left > 0 {
447                    let num_rows = num_rows_left.min(max_rows_per_copy);
448
449                    zero_buffer_copy_regions.push(hal::BufferTextureCopy {
450                        buffer_layout: wgt::TexelCopyBufferLayout {
451                            offset: 0,
452                            bytes_per_row: Some(bytes_per_row),
453                            rows_per_image: None,
454                        },
455                        texture_base: hal::TextureCopyBase {
456                            mip_level,
457                            array_layer,
458                            origin: wgt::Origin3d {
459                                x: 0, // Always full rows
460                                y: mip_size.height - num_rows_left,
461                                z,
462                            },
463                            aspect: hal::FormatAspects::COLOR,
464                        },
465                        size: hal::CopyExtent {
466                            width: mip_size.width, // full row
467                            height: num_rows,
468                            depth: 1, // Only single slice of volume texture at a time right now
469                        },
470                    });
471
472                    num_rows_left -= num_rows;
473                }
474            }
475        }
476    }
477
478    unsafe {
479        encoder.copy_buffer_to_texture(zero_buffer, dst_raw, &zero_buffer_copy_regions);
480    }
481}
482
483fn clear_texture_via_render_passes(
484    dst_texture: &Texture,
485    range: TextureInitRange,
486    is_color: bool,
487    encoder: &mut dyn hal::DynCommandEncoder,
488    instance_flags: wgt::InstanceFlags,
489) -> Result<(), ClearError> {
490    assert_eq!(dst_texture.desc.dimension, wgt::TextureDimension::D2);
491
492    let extent_base = wgt::Extent3d {
493        width: dst_texture.desc.size.width,
494        height: dst_texture.desc.size.height,
495        depth_or_array_layers: 1, // Only one layer is cleared at a time.
496    };
497
498    let clear_mode = dst_texture.clear_mode.read();
499
500    for mip_level in range.mip_range {
501        let extent = extent_base.mip_level_size(mip_level, dst_texture.desc.dimension);
502        for depth_or_layer in range.layer_range.clone() {
503            let color_attachments_tmp;
504            let (color_attachments, depth_stencil_attachment) = if is_color {
505                color_attachments_tmp = [Some(hal::ColorAttachment {
506                    target: hal::Attachment {
507                        view: Texture::get_clear_view(
508                            &clear_mode,
509                            &dst_texture.desc,
510                            mip_level,
511                            depth_or_layer,
512                        ),
513                        usage: wgt::TextureUses::COLOR_TARGET,
514                    },
515                    depth_slice: None,
516                    resolve_target: None,
517                    ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
518                    clear_value: wgt::Color::TRANSPARENT,
519                })];
520                (&color_attachments_tmp[..], None)
521            } else {
522                (
523                    &[][..],
524                    Some(hal::DepthStencilAttachment {
525                        target: hal::Attachment {
526                            view: Texture::get_clear_view(
527                                &clear_mode,
528                                &dst_texture.desc,
529                                mip_level,
530                                depth_or_layer,
531                            ),
532                            usage: wgt::TextureUses::DEPTH_STENCIL_WRITE,
533                        },
534                        depth_ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
535                        stencil_ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
536                        clear_value: (0.0, 0),
537                    }),
538                )
539            };
540            unsafe {
541                encoder
542                    .begin_render_pass(&hal::RenderPassDescriptor {
543                        label: hal_label(
544                            Some("(wgpu internal) clear_texture clear pass"),
545                            instance_flags,
546                        ),
547                        extent,
548                        sample_count: dst_texture.desc.sample_count,
549                        color_attachments,
550                        depth_stencil_attachment,
551                        multiview_mask: None,
552                        timestamp_writes: None,
553                        occlusion_query_set: None,
554                    })
555                    .map_err(|e| dst_texture.device.handle_hal_error(e))?;
556                encoder.end_render_pass();
557            }
558        }
559    }
560
561    Ok(())
562}