Debian Codegraph @

third_party/rust/wgpu-core/src/resource.rs

raw
1 use alloc::{borrow::Cow, borrow::ToOwned as _, boxed::Box, string::String, sync::Arc, vec::Vec};
2 use core::{
3 borrow::Borrow,
4 fmt,
5 mem::{self, ManuallyDrop},
6 num::NonZeroU64,
7 ops::Range,
8 ptr::NonNull,
9 };
10
11 use smallvec::SmallVec;
12 use thiserror::Error;
13 use wgt::TextureSelector;
14
15 #[cfg(feature = "trace")]
16 use crate::device::trace;
17 use crate::{
18 binding_model::BindGroup,
19 device::{
20 queue, resource::DeferredDestroy, BufferMapPendingClosure, Device, DeviceError,
21 DeviceMismatch, HostMap, MissingDownlevelFlags, MissingFeatures,
22 },
23 global::Global,
24 hal_api::HalApi,
25 id::{
26 AdapterId, BufferId, CommandEncoderId, DeviceId, QueueId, SurfaceId, TextureId,
27 TextureViewId,
28 },
29 init_tracker::{BufferInitTracker, TextureInitTracker},
30 lock::{rank, Mutex, RwLock},
31 resource_log,
32 snatch::{SnatchGuard, Snatchable},
33 timestamp_normalization::TimestampNormalizationBindGroup,
34 track::{SharedTrackerIndexAllocator, TrackerIndex},
35 weak_vec::WeakVec,
36 Label, LabelHelpers, SubmissionIndex,
37 };
38
39 use crate::id::{BlasId, TlasId};
40
41 /// Information about the wgpu-core resource.
42 ///
43 /// Each type representing a `wgpu-core` resource, like [`Device`],
44 /// [`Buffer`], etc., contains a `ResourceInfo` which contains
45 /// its latest submission index and label.
46 ///
47 /// A resource may need to be retained for any of several reasons:
48 /// and any lifetime logic will be handled by `Arc<Resource>` refcount
49 ///
50 /// - The user may hold a reference to it (via a `wgpu::Buffer`, say).
51 ///
52 /// - Other resources may depend on it (a texture view's backing
53 /// texture, for example).
54 ///
55 /// - It may be used by commands sent to the GPU that have not yet
56 /// finished execution.
57 ///
58 /// [`Device`]: crate::device::resource::Device
59 /// [`Buffer`]: crate::resource::Buffer
60 #[derive(Debug)]
61 pub(crate) struct TrackingData {
62 tracker_index: TrackerIndex,
63 tracker_indices: Arc<SharedTrackerIndexAllocator>,
64 }
65
66 impl Drop for TrackingData {
67 fn drop(&mut self) {
68 self.tracker_indices.free(self.tracker_index);
69 }
70 }
71
72 impl TrackingData {
73 pub(crate) fn new(tracker_indices: Arc<SharedTrackerIndexAllocator>) -> Self {
74 Self {
75 tracker_index: tracker_indices.alloc(),
76 tracker_indices,
77 }
78 }
79
80 pub(crate) fn tracker_index(&self) -> TrackerIndex {
81 self.tracker_index
82 }
83 }
84
85 #[derive(Clone, Debug)]
86 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
87 pub struct ResourceErrorIdent {
88 r#type: Cow<'static, str>,
89 label: String,
90 }
91
92 impl fmt::Display for ResourceErrorIdent {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
94 write!(f, "{} with '{}' label", self.r#type, self.label)
95 }
96 }
97
98 pub trait ParentDevice: Labeled {
99 fn device(&self) -> &Arc<Device>;
100
101 fn is_equal(self: &Arc<Self>, other: &Arc<Self>) -> bool {
102 Arc::ptr_eq(self, other)
103 }
104
105 fn same_device_as<O: ParentDevice>(&self, other: &O) -> Result<(), DeviceError> {
106 if Arc::ptr_eq(self.device(), other.device()) {
107 Ok(())
108 } else {
109 Err(DeviceError::DeviceMismatch(Box::new(DeviceMismatch {
110 res: self.error_ident(),
111 res_device: self.device().error_ident(),
112 target: Some(other.error_ident()),
113 target_device: other.device().error_ident(),
114 })))
115 }
116 }
117
118 fn same_device(&self, device: &Device) -> Result<(), DeviceError> {
119 if core::ptr::eq(&**self.device(), device) {
120 Ok(())
121 } else {
122 Err(DeviceError::DeviceMismatch(Box::new(DeviceMismatch {
123 res: self.error_ident(),
124 res_device: self.device().error_ident(),
125 target: None,
126 target_device: device.error_ident(),
127 })))
128 }
129 }
130 }
131
132 #[macro_export]
133 macro_rules! impl_parent_device {
134 ($ty:ident) => {
135 impl $crate::resource::ParentDevice for $ty {
136 fn device(&self) -> &Arc<Device> {
137 &self.device
138 }
139 }
140 };
141 }
142
143 pub trait ResourceType {
144 const TYPE: &'static str;
145 }
146
147 #[macro_export]
148 macro_rules! impl_resource_type {
149 ($ty:ident) => {
150 impl $crate::resource::ResourceType for $ty {
151 const TYPE: &'static str = stringify!($ty);
152 }
153 };
154 }
155
156 pub trait Labeled: ResourceType {
157 /// Returns a string identifying this resource for logging and errors.
158 ///
159 /// It may be a user-provided string or it may be a placeholder from wgpu.
160 ///
161 /// It is non-empty unless the user-provided string was empty.
162 fn label(&self) -> &str;
163
164 fn error_ident(&self) -> ResourceErrorIdent {
165 ResourceErrorIdent {
166 r#type: Cow::Borrowed(Self::TYPE),
167 label: self.label().to_owned(),
168 }
169 }
170 }
171
172 #[macro_export]
173 macro_rules! impl_labeled {
174 ($ty:ident) => {
175 impl $crate::resource::Labeled for $ty {
176 fn label(&self) -> &str {
177 &self.label
178 }
179 }
180 };
181 }
182
183 pub(crate) trait Trackable {
184 fn tracker_index(&self) -> TrackerIndex;
185 }
186
187 #[macro_export]
188 macro_rules! impl_trackable {
189 ($ty:ident) => {
190 impl $crate::resource::Trackable for $ty {
191 fn tracker_index(&self) -> $crate::track::TrackerIndex {
192 self.tracking_data.tracker_index()
193 }
194 }
195 };
196 }
197
198 #[derive(Debug)]
199 pub(crate) enum BufferMapState {
200 /// Mapped at creation.
201 Init { staging_buffer: StagingBuffer },
202 /// Waiting for GPU to be done before mapping
203 Waiting(BufferPendingMapping),
204 /// Mapped
205 Active {
206 mapping: hal::BufferMapping,
207 range: hal::MemoryRange,
208 host: HostMap,
209 },
210 /// Not mapped
211 Idle,
212 }
213
214 #[cfg(send_sync)]
215 unsafe impl Send for BufferMapState {}
216 #[cfg(send_sync)]
217 unsafe impl Sync for BufferMapState {}
218
219 #[cfg(send_sync)]
220 pub type BufferMapCallback = Box<dyn FnOnce(BufferAccessResult) + Send + 'static>;
221 #[cfg(not(send_sync))]
222 pub type BufferMapCallback = Box<dyn FnOnce(BufferAccessResult) + 'static>;
223
224 pub struct BufferMapOperation {
225 pub host: HostMap,
226 pub callback: Option<BufferMapCallback>,
227 }
228
229 impl fmt::Debug for BufferMapOperation {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 f.debug_struct("BufferMapOperation")
232 .field("host", &self.host)
233 .field("callback", &self.callback.as_ref().map(|_| "?"))
234 .finish()
235 }
236 }
237
238 #[derive(Clone, Debug, Error)]
239 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
240 #[non_exhaustive]
241 pub enum BufferAccessError {
242 #[error(transparent)]
243 Device(#[from] DeviceError),
244 #[error("Buffer map failed")]
245 Failed,
246 #[error(transparent)]
247 DestroyedResource(#[from] DestroyedResourceError),
248 #[error("Buffer is already mapped")]
249 AlreadyMapped,
250 #[error("Buffer map is pending")]
251 MapAlreadyPending,
252 #[error(transparent)]
253 MissingBufferUsage(#[from] MissingBufferUsageError),
254 #[error("Buffer is not mapped")]
255 NotMapped,
256 #[error(
257 "Buffer map range must start aligned to `MAP_ALIGNMENT` and end to `COPY_BUFFER_ALIGNMENT`"
258 )]
259 UnalignedRange,
260 #[error("Buffer offset invalid: offset {offset} must be multiple of 8")]
261 UnalignedOffset { offset: wgt::BufferAddress },
262 #[error("Buffer range size invalid: range_size {range_size} must be multiple of 4")]
263 UnalignedRangeSize { range_size: wgt::BufferAddress },
264 #[error("Buffer access out of bounds: index {index} would underrun the buffer (limit: {min})")]
265 OutOfBoundsUnderrun {
266 index: wgt::BufferAddress,
267 min: wgt::BufferAddress,
268 },
269 #[error(
270 "Buffer access out of bounds: last index {index} would overrun the buffer (limit: {max})"
271 )]
272 OutOfBoundsOverrun {
273 index: wgt::BufferAddress,
274 max: wgt::BufferAddress,
275 },
276 #[error("Buffer map range start {start} is greater than end {end}")]
277 NegativeRange {
278 start: wgt::BufferAddress,
279 end: wgt::BufferAddress,
280 },
281 #[error("Buffer map aborted")]
282 MapAborted,
283 #[error(transparent)]
284 InvalidResource(#[from] InvalidResourceError),
285 }
286
287 #[derive(Clone, Debug, Error)]
288 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
289 #[error("Usage flags {actual:?} of {res} do not contain required usage flags {expected:?}")]
290 pub struct MissingBufferUsageError {
291 pub(crate) res: ResourceErrorIdent,
292 pub(crate) actual: wgt::BufferUsages,
293 pub(crate) expected: wgt::BufferUsages,
294 }
295
296 #[derive(Clone, Debug, Error)]
297 #[error("Usage flags {actual:?} of {res} do not contain required usage flags {expected:?}")]
298 pub struct MissingTextureUsageError {
299 pub(crate) res: ResourceErrorIdent,
300 pub(crate) actual: wgt::TextureUsages,
301 pub(crate) expected: wgt::TextureUsages,
302 }
303
304 #[derive(Clone, Debug, Error)]
305 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
306 #[error("{0} has been destroyed")]
307 pub struct DestroyedResourceError(pub ResourceErrorIdent);
308
309 #[derive(Clone, Debug, Error)]
310 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
311 #[error("{0} is invalid")]
312 pub struct InvalidResourceError(pub ResourceErrorIdent);
313
314 pub enum Fallible<T: ParentDevice> {
315 Valid(Arc<T>),
316 Invalid(Arc<String>),
317 }
318
319 impl<T: ParentDevice> Fallible<T> {
320 pub fn get(self) -> Result<Arc<T>, InvalidResourceError> {
321 match self {
322 Fallible::Valid(v) => Ok(v),
323 Fallible::Invalid(label) => Err(InvalidResourceError(ResourceErrorIdent {
324 r#type: Cow::Borrowed(T::TYPE),
325 label: (*label).clone(),
326 })),
327 }
328 }
329 }
330
331 impl<T: ParentDevice> Clone for Fallible<T> {
332 fn clone(&self) -> Self {
333 match self {
334 Self::Valid(v) => Self::Valid(v.clone()),
335 Self::Invalid(l) => Self::Invalid(l.clone()),
336 }
337 }
338 }
339
340 impl<T: ParentDevice> ResourceType for Fallible<T> {
341 const TYPE: &'static str = T::TYPE;
342 }
343
344 impl<T: ParentDevice + crate::storage::StorageItem> crate::storage::StorageItem for Fallible<T> {
345 type Marker = T::Marker;
346 }
347
348 pub type BufferAccessResult = Result<(), BufferAccessError>;
349
350 #[derive(Debug)]
351 pub(crate) struct BufferPendingMapping {
352 pub(crate) range: Range<wgt::BufferAddress>,
353 pub(crate) op: BufferMapOperation,
354 // hold the parent alive while the mapping is active
355 pub(crate) _parent_buffer: Arc<Buffer>,
356 }
357
358 pub type BufferDescriptor<'a> = wgt::BufferDescriptor<Label<'a>>;
359
360 #[derive(Debug)]
361 pub struct Buffer {
362 pub(crate) raw: Snatchable<Box<dyn hal::DynBuffer>>,
363 pub(crate) device: Arc<Device>,
364 pub(crate) usage: wgt::BufferUsages,
365 pub(crate) size: wgt::BufferAddress,
366 pub(crate) initialization_status: RwLock<BufferInitTracker>,
367 /// The `label` from the descriptor used to create the resource.
368 pub(crate) label: String,
369 pub(crate) tracking_data: TrackingData,
370 pub(crate) map_state: Mutex<BufferMapState>,
371 pub(crate) bind_groups: Mutex<WeakVec<BindGroup>>,
372 pub(crate) timestamp_normalization_bind_group: Snatchable<TimestampNormalizationBindGroup>,
373 pub(crate) indirect_validation_bind_groups: Snatchable<crate::indirect_validation::BindGroups>,
374 }
375
376 impl Drop for Buffer {
377 fn drop(&mut self) {
378 if let Some(raw) = self.timestamp_normalization_bind_group.take() {
379 raw.dispose(self.device.raw());
380 }
381
382 if let Some(raw) = self.indirect_validation_bind_groups.take() {
383 raw.dispose(self.device.raw());
384 }
385
386 if let Some(raw) = self.raw.take() {
387 resource_log!("Destroy raw {}", self.error_ident());
388 unsafe {
389 self.device.raw().destroy_buffer(raw);
390 }
391 }
392 }
393 }
394
395 impl Buffer {
396 pub(crate) fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a dyn hal::DynBuffer> {
397 self.raw.get(guard).map(|b| b.as_ref())
398 }
399
400 pub(crate) fn try_raw<'a>(
401 &'a self,
402 guard: &'a SnatchGuard,
403 ) -> Result<&'a dyn hal::DynBuffer, DestroyedResourceError> {
404 self.raw
405 .get(guard)
406 .map(|raw| raw.as_ref())
407 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
408 }
409
410 pub(crate) fn check_destroyed<'a>(
411 &'a self,
412 guard: &'a SnatchGuard,
413 ) -> Result<(), DestroyedResourceError> {
414 self.raw
415 .get(guard)
416 .map(|_| ())
417 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
418 }
419
420 /// Checks that the given buffer usage contains the required buffer usage,
421 /// returns an error otherwise.
422 pub(crate) fn check_usage(
423 &self,
424 expected: wgt::BufferUsages,
425 ) -> Result<(), MissingBufferUsageError> {
426 if self.usage.contains(expected) {
427 Ok(())
428 } else {
429 Err(MissingBufferUsageError {
430 res: self.error_ident(),
431 actual: self.usage,
432 expected,
433 })
434 }
435 }
436
437 /// Returns the mapping callback in case of error so that the callback can be fired outside
438 /// of the locks that are held in this function.
439 pub(crate) fn map_async(
440 self: &Arc<Self>,
441 offset: wgt::BufferAddress,
442 size: Option<wgt::BufferAddress>,
443 op: BufferMapOperation,
444 ) -> Result<SubmissionIndex, (BufferMapOperation, BufferAccessError)> {
445 let range_size = if let Some(size) = size {
446 size
447 } else {
448 self.size.saturating_sub(offset)
449 };
450
451 if offset % wgt::MAP_ALIGNMENT != 0 {
452 return Err((op, BufferAccessError::UnalignedOffset { offset }));
453 }
454 if range_size % wgt::COPY_BUFFER_ALIGNMENT != 0 {
455 return Err((op, BufferAccessError::UnalignedRangeSize { range_size }));
456 }
457
458 let range = offset..(offset + range_size);
459
460 if range.start % wgt::MAP_ALIGNMENT != 0 || range.end % wgt::COPY_BUFFER_ALIGNMENT != 0 {
461 return Err((op, BufferAccessError::UnalignedRange));
462 }
463
464 let (pub_usage, internal_use) = match op.host {
465 HostMap::Read => (wgt::BufferUsages::MAP_READ, wgt::BufferUses::MAP_READ),
466 HostMap::Write => (wgt::BufferUsages::MAP_WRITE, wgt::BufferUses::MAP_WRITE),
467 };
468
469 if let Err(e) = self.check_usage(pub_usage) {
470 return Err((op, e.into()));
471 }
472
473 if range.start > range.end {
474 return Err((
475 op,
476 BufferAccessError::NegativeRange {
477 start: range.start,
478 end: range.end,
479 },
480 ));
481 }
482 if range.end > self.size {
483 return Err((
484 op,
485 BufferAccessError::OutOfBoundsOverrun {
486 index: range.end,
487 max: self.size,
488 },
489 ));
490 }
491
492 let device = &self.device;
493 if let Err(e) = device.check_is_valid() {
494 return Err((op, e.into()));
495 }
496
497 {
498 let snatch_guard = device.snatchable_lock.read();
499 if let Err(e) = self.check_destroyed(&snatch_guard) {
500 return Err((op, e.into()));
501 }
502 }
503
504 {
505 let map_state = &mut *self.map_state.lock();
506 *map_state = match *map_state {
507 BufferMapState::Init { .. } | BufferMapState::Active { .. } => {
508 return Err((op, BufferAccessError::AlreadyMapped));
509 }
510 BufferMapState::Waiting(_) => {
511 return Err((op, BufferAccessError::MapAlreadyPending));
512 }
513 BufferMapState::Idle => BufferMapState::Waiting(BufferPendingMapping {
514 range,
515 op,
516 _parent_buffer: self.clone(),
517 }),
518 };
519 }
520
521 // TODO: we are ignoring the transition here, I think we need to add a barrier
522 // at the end of the submission
523 device
524 .trackers
525 .lock()
526 .buffers
527 .set_single(self, internal_use);
528
529 let submit_index = if let Some(queue) = device.get_queue() {
530 queue.lock_life().map(self).unwrap_or(0) // '0' means no wait is necessary
531 } else {
532 // We can safely unwrap below since we just set the `map_state` to `BufferMapState::Waiting`.
533 let (mut operation, status) = self.map(&device.snatchable_lock.read()).unwrap();
534 if let Some(callback) = operation.callback.take() {
535 callback(status);
536 }
537 0
538 };
539
540 Ok(submit_index)
541 }
542
543 /// This function returns [`None`] only if [`Self::map_state`] is not [`BufferMapState::Waiting`].
544 #[must_use]
545 pub(crate) fn map(&self, snatch_guard: &SnatchGuard) -> Option<BufferMapPendingClosure> {
546 // This _cannot_ be inlined into the match. If it is, the lock will be held
547 // open through the whole match, resulting in a deadlock when we try to re-lock
548 // the buffer back to active.
549 let mapping = mem::replace(&mut *self.map_state.lock(), BufferMapState::Idle);
550 let pending_mapping = match mapping {
551 BufferMapState::Waiting(pending_mapping) => pending_mapping,
552 // Mapping cancelled
553 BufferMapState::Idle => return None,
554 // Mapping queued at least twice by map -> unmap -> map
555 // and was already successfully mapped below
556 BufferMapState::Active { .. } => {
557 *self.map_state.lock() = mapping;
558 return None;
559 }
560 _ => panic!("No pending mapping."),
561 };
562 let status = if pending_mapping.range.start != pending_mapping.range.end {
563 let host = pending_mapping.op.host;
564 let size = pending_mapping.range.end - pending_mapping.range.start;
565 match crate::device::map_buffer(
566 self,
567 pending_mapping.range.start,
568 size,
569 host,
570 snatch_guard,
571 ) {
572 Ok(mapping) => {
573 *self.map_state.lock() = BufferMapState::Active {
574 mapping,
575 range: pending_mapping.range.clone(),
576 host,
577 };
578 Ok(())
579 }
580 Err(e) => Err(e),
581 }
582 } else {
583 *self.map_state.lock() = BufferMapState::Active {
584 mapping: hal::BufferMapping {
585 ptr: NonNull::dangling(),
586 is_coherent: true,
587 },
588 range: pending_mapping.range,
589 host: pending_mapping.op.host,
590 };
591 Ok(())
592 };
593 Some((pending_mapping.op, status))
594 }
595
596 // Note: This must not be called while holding a lock.
597 pub(crate) fn unmap(
598 self: &Arc<Self>,
599 #[cfg(feature = "trace")] buffer_id: BufferId,
600 ) -> Result<(), BufferAccessError> {
601 if let Some((mut operation, status)) = self.unmap_inner(
602 #[cfg(feature = "trace")]
603 buffer_id,
604 )? {
605 if let Some(callback) = operation.callback.take() {
606 callback(status);
607 }
608 }
609
610 Ok(())
611 }
612
613 fn unmap_inner(
614 self: &Arc<Self>,
615 #[cfg(feature = "trace")] buffer_id: BufferId,
616 ) -> Result<Option<BufferMapPendingClosure>, BufferAccessError> {
617 let device = &self.device;
618 let snatch_guard = device.snatchable_lock.read();
619 let raw_buf = self.try_raw(&snatch_guard)?;
620 match mem::replace(&mut *self.map_state.lock(), BufferMapState::Idle) {
621 BufferMapState::Init { staging_buffer } => {
622 #[cfg(feature = "trace")]
623 if let Some(ref mut trace) = *device.trace.lock() {
624 let data = trace.make_binary("bin", staging_buffer.get_data());
625 trace.add(trace::Action::WriteBuffer {
626 id: buffer_id,
627 data,
628 range: 0..self.size,
629 queued: true,
630 });
631 }
632
633 let staging_buffer = staging_buffer.flush();
634
635 if let Some(queue) = device.get_queue() {
636 let region = wgt::BufferSize::new(self.size).map(|size| hal::BufferCopy {
637 src_offset: 0,
638 dst_offset: 0,
639 size,
640 });
641 let transition_src = hal::BufferBarrier {
642 buffer: staging_buffer.raw(),
643 usage: hal::StateTransition {
644 from: wgt::BufferUses::MAP_WRITE,
645 to: wgt::BufferUses::COPY_SRC,
646 },
647 };
648 let transition_dst = hal::BufferBarrier::<dyn hal::DynBuffer> {
649 buffer: raw_buf,
650 usage: hal::StateTransition {
651 from: wgt::BufferUses::empty(),
652 to: wgt::BufferUses::COPY_DST,
653 },
654 };
655 let mut pending_writes = queue.pending_writes.lock();
656 let encoder = pending_writes.activate();
657 unsafe {
658 encoder.transition_buffers(&[transition_src, transition_dst]);
659 if self.size > 0 {
660 encoder.copy_buffer_to_buffer(
661 staging_buffer.raw(),
662 raw_buf,
663 region.as_slice(),
664 );
665 }
666 }
667 pending_writes.consume(staging_buffer);
668 pending_writes.insert_buffer(self);
669 }
670 }
671 BufferMapState::Idle => {
672 return Err(BufferAccessError::NotMapped);
673 }
674 BufferMapState::Waiting(pending) => {
675 return Ok(Some((pending.op, Err(BufferAccessError::MapAborted))));
676 }
677 BufferMapState::Active {
678 mapping,
679 range,
680 host,
681 } => {
682 #[allow(clippy::collapsible_if)]
683 if host == HostMap::Write {
684 #[cfg(feature = "trace")]
685 if let Some(ref mut trace) = *device.trace.lock() {
686 let size = range.end - range.start;
687 let data = trace.make_binary("bin", unsafe {
688 core::slice::from_raw_parts(mapping.ptr.as_ptr(), size as usize)
689 });
690 trace.add(trace::Action::WriteBuffer {
691 id: buffer_id,
692 data,
693 range: range.clone(),
694 queued: false,
695 });
696 }
697 if !mapping.is_coherent {
698 unsafe { device.raw().flush_mapped_ranges(raw_buf, &[range]) };
699 }
700 }
701 unsafe { device.raw().unmap_buffer(raw_buf) };
702 }
703 }
704 Ok(None)
705 }
706
707 pub(crate) fn destroy(self: &Arc<Self>) -> Result<(), DestroyError> {
708 let device = &self.device;
709
710 let temp = {
711 let mut snatch_guard = device.snatchable_lock.write();
712
713 let raw = match self.raw.snatch(&mut snatch_guard) {
714 Some(raw) => raw,
715 None => {
716 // Per spec, it is valid to call `destroy` multiple times.
717 return Ok(());
718 }
719 };
720
721 let timestamp_normalization_bind_group = self
722 .timestamp_normalization_bind_group
723 .snatch(&mut snatch_guard);
724
725 let indirect_validation_bind_groups = self
726 .indirect_validation_bind_groups
727 .snatch(&mut snatch_guard);
728
729 drop(snatch_guard);
730
731 let bind_groups = {
732 let mut guard = self.bind_groups.lock();
733 mem::take(&mut *guard)
734 };
735
736 queue::TempResource::DestroyedBuffer(DestroyedBuffer {
737 raw: ManuallyDrop::new(raw),
738 device: Arc::clone(&self.device),
739 label: self.label().to_owned(),
740 bind_groups,
741 timestamp_normalization_bind_group,
742 indirect_validation_bind_groups,
743 })
744 };
745
746 if let Some(queue) = device.get_queue() {
747 let mut pending_writes = queue.pending_writes.lock();
748 if pending_writes.contains_buffer(self) {
749 pending_writes.consume_temp(temp);
750 } else {
751 let mut life_lock = queue.lock_life();
752 let last_submit_index = life_lock.get_buffer_latest_submission_index(self);
753 if let Some(last_submit_index) = last_submit_index {
754 life_lock.schedule_resource_destruction(temp, last_submit_index);
755 }
756 }
757 }
758
759 Ok(())
760 }
761 }
762
763 #[derive(Clone, Debug, Error)]
764 #[non_exhaustive]
765 pub enum CreateBufferError {
766 #[error(transparent)]
767 Device(#[from] DeviceError),
768 #[error("Failed to map buffer while creating: {0}")]
769 AccessError(#[from] BufferAccessError),
770 #[error("Buffers that are mapped at creation have to be aligned to `COPY_BUFFER_ALIGNMENT`")]
771 UnalignedSize,
772 #[error("Invalid usage flags {0:?}")]
773 InvalidUsage(wgt::BufferUsages),
774 #[error("`MAP` usage can only be combined with the opposite `COPY`, requested {0:?}")]
775 UsageMismatch(wgt::BufferUsages),
776 #[error("Buffer size {requested} is greater than the maximum buffer size ({maximum})")]
777 MaxBufferSize { requested: u64, maximum: u64 },
778 #[error(transparent)]
779 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
780 #[error("Failed to create bind group for indirect buffer validation: {0}")]
781 IndirectValidationBindGroup(DeviceError),
782 }
783
784 crate::impl_resource_type!(Buffer);
785 crate::impl_labeled!(Buffer);
786 crate::impl_parent_device!(Buffer);
787 crate::impl_storage_item!(Buffer);
788 crate::impl_trackable!(Buffer);
789
790 /// A buffer that has been marked as destroyed and is staged for actual deletion soon.
791 #[derive(Debug)]
792 pub struct DestroyedBuffer {
793 raw: ManuallyDrop<Box<dyn hal::DynBuffer>>,
794 device: Arc<Device>,
795 label: String,
796 bind_groups: WeakVec<BindGroup>,
797 timestamp_normalization_bind_group: Option<TimestampNormalizationBindGroup>,
798 indirect_validation_bind_groups: Option<crate::indirect_validation::BindGroups>,
799 }
800
801 impl DestroyedBuffer {
802 pub fn label(&self) -> &dyn fmt::Debug {
803 &self.label
804 }
805 }
806
807 impl Drop for DestroyedBuffer {
808 fn drop(&mut self) {
809 let mut deferred = self.device.deferred_destroy.lock();
810 deferred.push(DeferredDestroy::BindGroups(mem::take(
811 &mut self.bind_groups,
812 )));
813 drop(deferred);
814
815 if let Some(raw) = self.timestamp_normalization_bind_group.take() {
816 raw.dispose(self.device.raw());
817 }
818
819 if let Some(raw) = self.indirect_validation_bind_groups.take() {
820 raw.dispose(self.device.raw());
821 }
822
823 resource_log!("Destroy raw Buffer (destroyed) {:?}", self.label());
824 // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
825 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
826 unsafe {
827 hal::DynDevice::destroy_buffer(self.device.raw(), raw);
828 }
829 }
830 }
831
832 #[cfg(send_sync)]
833 unsafe impl Send for StagingBuffer {}
834 #[cfg(send_sync)]
835 unsafe impl Sync for StagingBuffer {}
836
837 /// A temporary buffer, consumed by the command that uses it.
838 ///
839 /// A [`StagingBuffer`] is designed for one-shot uploads of data to the GPU. It
840 /// is always created mapped, and the command that uses it destroys the buffer
841 /// when it is done.
842 ///
843 /// [`StagingBuffer`]s can be created with [`queue_create_staging_buffer`] and
844 /// used with [`queue_write_staging_buffer`]. They are also used internally by
845 /// operations like [`queue_write_texture`] that need to upload data to the GPU,
846 /// but that don't belong to any particular wgpu command buffer.
847 ///
848 /// Used `StagingBuffer`s are accumulated in [`Device::pending_writes`], to be
849 /// freed once their associated operation's queue submission has finished
850 /// execution.
851 ///
852 /// [`queue_create_staging_buffer`]: Global::queue_create_staging_buffer
853 /// [`queue_write_staging_buffer`]: Global::queue_write_staging_buffer
854 /// [`queue_write_texture`]: Global::queue_write_texture
855 /// [`Device::pending_writes`]: crate::device::Device
856 #[derive(Debug)]
857 pub struct StagingBuffer {
858 raw: Box<dyn hal::DynBuffer>,
859 device: Arc<Device>,
860 pub(crate) size: wgt::BufferSize,
861 is_coherent: bool,
862 ptr: NonNull<u8>,
863 }
864
865 impl StagingBuffer {
866 pub(crate) fn new(device: &Arc<Device>, size: wgt::BufferSize) -> Result<Self, DeviceError> {
867 profiling::scope!("StagingBuffer::new");
868 let stage_desc = hal::BufferDescriptor {
869 label: crate::hal_label(Some("(wgpu internal) Staging"), device.instance_flags),
870 size: size.get(),
871 usage: wgt::BufferUses::MAP_WRITE | wgt::BufferUses::COPY_SRC,
872 memory_flags: hal::MemoryFlags::TRANSIENT,
873 };
874
875 let raw = unsafe { device.raw().create_buffer(&stage_desc) }
876 .map_err(|e| device.handle_hal_error(e))?;
877 let mapping = unsafe { device.raw().map_buffer(raw.as_ref(), 0..size.get()) }
878 .map_err(|e| device.handle_hal_error(e))?;
879
880 let staging_buffer = StagingBuffer {
881 raw,
882 device: device.clone(),
883 size,
884 is_coherent: mapping.is_coherent,
885 ptr: mapping.ptr,
886 };
887
888 Ok(staging_buffer)
889 }
890
891 /// SAFETY: You must not call any functions of `self`
892 /// until you stopped using the returned pointer.
893 pub(crate) unsafe fn ptr(&self) -> NonNull<u8> {
894 self.ptr
895 }
896
897 #[cfg(feature = "trace")]
898 pub(crate) fn get_data(&self) -> &[u8] {
899 unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.size.get() as usize) }
900 }
901
902 pub(crate) fn write_zeros(&mut self) {
903 unsafe { core::ptr::write_bytes(self.ptr.as_ptr(), 0, self.size.get() as usize) };
904 }
905
906 pub(crate) fn write(&mut self, data: &[u8]) {
907 assert!(data.len() >= self.size.get() as usize);
908 // SAFETY: With the assert above, all of `copy_nonoverlapping`'s
909 // requirements are satisfied.
910 unsafe {
911 core::ptr::copy_nonoverlapping(
912 data.as_ptr(),
913 self.ptr.as_ptr(),
914 self.size.get() as usize,
915 );
916 }
917 }
918
919 /// SAFETY: The offsets and size must be in-bounds.
920 pub(crate) unsafe fn write_with_offset(
921 &mut self,
922 data: &[u8],
923 src_offset: isize,
924 dst_offset: isize,
925 size: usize,
926 ) {
927 unsafe {
928 core::ptr::copy_nonoverlapping(
929 data.as_ptr().offset(src_offset),
930 self.ptr.as_ptr().offset(dst_offset),
931 size,
932 );
933 }
934 }
935
936 pub(crate) fn flush(self) -> FlushedStagingBuffer {
937 let device = self.device.raw();
938 if !self.is_coherent {
939 #[allow(clippy::single_range_in_vec_init)]
940 unsafe {
941 device.flush_mapped_ranges(self.raw.as_ref(), &[0..self.size.get()])
942 };
943 }
944 unsafe { device.unmap_buffer(self.raw.as_ref()) };
945
946 let StagingBuffer {
947 raw, device, size, ..
948 } = self;
949
950 FlushedStagingBuffer {
951 raw: ManuallyDrop::new(raw),
952 device,
953 size,
954 }
955 }
956 }
957
958 crate::impl_resource_type!(StagingBuffer);
959 crate::impl_storage_item!(StagingBuffer);
960
961 #[derive(Debug)]
962 pub struct FlushedStagingBuffer {
963 raw: ManuallyDrop<Box<dyn hal::DynBuffer>>,
964 device: Arc<Device>,
965 pub(crate) size: wgt::BufferSize,
966 }
967
968 impl FlushedStagingBuffer {
969 pub(crate) fn raw(&self) -> &dyn hal::DynBuffer {
970 self.raw.as_ref()
971 }
972 }
973
974 impl Drop for FlushedStagingBuffer {
975 fn drop(&mut self) {
976 resource_log!("Destroy raw StagingBuffer");
977 // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
978 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
979 unsafe { self.device.raw().destroy_buffer(raw) };
980 }
981 }
982
983 pub type TextureDescriptor<'a> = wgt::TextureDescriptor<Label<'a>, Vec<wgt::TextureFormat>>;
984
985 #[derive(Debug)]
986 pub(crate) enum TextureInner {
987 Native {
988 raw: Box<dyn hal::DynTexture>,
989 },
990 Surface {
991 raw: Box<dyn hal::DynSurfaceTexture>,
992 },
993 }
994
995 impl TextureInner {
996 pub(crate) fn raw(&self) -> &dyn hal::DynTexture {
997 match self {
998 Self::Native { raw } => raw.as_ref(),
999 Self::Surface { raw, .. } => raw.as_ref().borrow(),
1000 }
1001 }
1002 }
1003
1004 #[derive(Debug)]
1005 pub enum TextureClearMode {
1006 BufferCopy,
1007 // View for clear via RenderPass for every subsurface (mip/layer/slice)
1008 RenderPass {
1009 clear_views: SmallVec<[ManuallyDrop<Box<dyn hal::DynTextureView>>; 1]>,
1010 is_color: bool,
1011 },
1012 Surface {
1013 clear_view: ManuallyDrop<Box<dyn hal::DynTextureView>>,
1014 },
1015 // Texture can't be cleared, attempting to do so will cause panic.
1016 // (either because it is impossible for the type of texture or it is being destroyed)
1017 None,
1018 }
1019
1020 #[derive(Debug)]
1021 pub struct Texture {
1022 pub(crate) inner: Snatchable<TextureInner>,
1023 pub(crate) device: Arc<Device>,
1024 pub(crate) desc: wgt::TextureDescriptor<(), Vec<wgt::TextureFormat>>,
1025 pub(crate) _hal_usage: wgt::TextureUses,
1026 pub(crate) format_features: wgt::TextureFormatFeatures,
1027 pub(crate) initialization_status: RwLock<TextureInitTracker>,
1028 pub(crate) full_range: TextureSelector,
1029 /// The `label` from the descriptor used to create the resource.
1030 pub(crate) label: String,
1031 pub(crate) tracking_data: TrackingData,
1032 pub(crate) clear_mode: TextureClearMode,
1033 pub(crate) views: Mutex<WeakVec<TextureView>>,
1034 pub(crate) bind_groups: Mutex<WeakVec<BindGroup>>,
1035 }
1036
1037 impl Texture {
1038 pub(crate) fn new(
1039 device: &Arc<Device>,
1040 inner: TextureInner,
1041 hal_usage: wgt::TextureUses,
1042 desc: &TextureDescriptor,
1043 format_features: wgt::TextureFormatFeatures,
1044 clear_mode: TextureClearMode,
1045 init: bool,
1046 ) -> Self {
1047 Texture {
1048 inner: Snatchable::new(inner),
1049 device: device.clone(),
1050 desc: desc.map_label(|_| ()),
1051 _hal_usage: hal_usage,
1052 format_features,
1053 initialization_status: RwLock::new(
1054 rank::TEXTURE_INITIALIZATION_STATUS,
1055 if init {
1056 TextureInitTracker::new(desc.mip_level_count, desc.array_layer_count())
1057 } else {
1058 TextureInitTracker::new(desc.mip_level_count, 0)
1059 },
1060 ),
1061 full_range: TextureSelector {
1062 mips: 0..desc.mip_level_count,
1063 layers: 0..desc.array_layer_count(),
1064 },
1065 label: desc.label.to_string(),
1066 tracking_data: TrackingData::new(device.tracker_indices.textures.clone()),
1067 clear_mode,
1068 views: Mutex::new(rank::TEXTURE_VIEWS, WeakVec::new()),
1069 bind_groups: Mutex::new(rank::TEXTURE_BIND_GROUPS, WeakVec::new()),
1070 }
1071 }
1072
1073 /// Checks that the given texture usage contains the required texture usage,
1074 /// returns an error otherwise.
1075 pub(crate) fn check_usage(
1076 &self,
1077 expected: wgt::TextureUsages,
1078 ) -> Result<(), MissingTextureUsageError> {
1079 if self.desc.usage.contains(expected) {
1080 Ok(())
1081 } else {
1082 Err(MissingTextureUsageError {
1083 res: self.error_ident(),
1084 actual: self.desc.usage,
1085 expected,
1086 })
1087 }
1088 }
1089 }
1090
1091 impl Drop for Texture {
1092 fn drop(&mut self) {
1093 match self.clear_mode {
1094 TextureClearMode::Surface {
1095 ref mut clear_view, ..
1096 } => {
1097 // SAFETY: We are in the Drop impl and we don't use clear_view anymore after this point.
1098 let raw = unsafe { ManuallyDrop::take(clear_view) };
1099 unsafe {
1100 self.device.raw().destroy_texture_view(raw);
1101 }
1102 }
1103 TextureClearMode::RenderPass {
1104 ref mut clear_views,
1105 ..
1106 } => {
1107 clear_views.iter_mut().for_each(|clear_view| {
1108 // SAFETY: We are in the Drop impl and we don't use clear_view anymore after this point.
1109 let raw = unsafe { ManuallyDrop::take(clear_view) };
1110 unsafe {
1111 self.device.raw().destroy_texture_view(raw);
1112 }
1113 });
1114 }
1115 _ => {}
1116 };
1117
1118 if let Some(TextureInner::Native { raw }) = self.inner.take() {
1119 resource_log!("Destroy raw {}", self.error_ident());
1120 unsafe {
1121 self.device.raw().destroy_texture(raw);
1122 }
1123 }
1124 }
1125 }
1126
1127 impl Texture {
1128 pub(crate) fn try_inner<'a>(
1129 &'a self,
1130 guard: &'a SnatchGuard,
1131 ) -> Result<&'a TextureInner, DestroyedResourceError> {
1132 self.inner
1133 .get(guard)
1134 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
1135 }
1136
1137 pub(crate) fn raw<'a>(
1138 &'a self,
1139 snatch_guard: &'a SnatchGuard,
1140 ) -> Option<&'a dyn hal::DynTexture> {
1141 Some(self.inner.get(snatch_guard)?.raw())
1142 }
1143
1144 pub(crate) fn try_raw<'a>(
1145 &'a self,
1146 guard: &'a SnatchGuard,
1147 ) -> Result<&'a dyn hal::DynTexture, DestroyedResourceError> {
1148 self.inner
1149 .get(guard)
1150 .map(|t| t.raw())
1151 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
1152 }
1153
1154 pub(crate) fn get_clear_view<'a>(
1155 clear_mode: &'a TextureClearMode,
1156 desc: &'a wgt::TextureDescriptor<(), Vec<wgt::TextureFormat>>,
1157 mip_level: u32,
1158 depth_or_layer: u32,
1159 ) -> &'a dyn hal::DynTextureView {
1160 match *clear_mode {
1161 TextureClearMode::BufferCopy => {
1162 panic!("Given texture is cleared with buffer copies, not render passes")
1163 }
1164 TextureClearMode::None => {
1165 panic!("Given texture can't be cleared")
1166 }
1167 TextureClearMode::Surface { ref clear_view, .. } => clear_view.as_ref(),
1168 TextureClearMode::RenderPass {
1169 ref clear_views, ..
1170 } => {
1171 let index = if desc.dimension == wgt::TextureDimension::D3 {
1172 (0..mip_level).fold(0, |acc, mip| {
1173 acc + (desc.size.depth_or_array_layers >> mip).max(1)
1174 })
1175 } else {
1176 mip_level * desc.size.depth_or_array_layers
1177 } + depth_or_layer;
1178 clear_views[index as usize].as_ref()
1179 }
1180 }
1181 }
1182
1183 pub(crate) fn destroy(self: &Arc<Self>) -> Result<(), DestroyError> {
1184 let device = &self.device;
1185
1186 let temp = {
1187 let raw = match self.inner.snatch(&mut device.snatchable_lock.write()) {
1188 Some(TextureInner::Native { raw }) => raw,
1189 Some(TextureInner::Surface { .. }) => {
1190 return Ok(());
1191 }
1192 None => {
1193 // Per spec, it is valid to call `destroy` multiple times.
1194 return Ok(());
1195 }
1196 };
1197
1198 let views = {
1199 let mut guard = self.views.lock();
1200 mem::take(&mut *guard)
1201 };
1202
1203 let bind_groups = {
1204 let mut guard = self.bind_groups.lock();
1205 mem::take(&mut *guard)
1206 };
1207
1208 queue::TempResource::DestroyedTexture(DestroyedTexture {
1209 raw: ManuallyDrop::new(raw),
1210 views,
1211 bind_groups,
1212 device: Arc::clone(&self.device),
1213 label: self.label().to_owned(),
1214 })
1215 };
1216
1217 if let Some(queue) = device.get_queue() {
1218 let mut pending_writes = queue.pending_writes.lock();
1219 if pending_writes.contains_texture(self) {
1220 pending_writes.consume_temp(temp);
1221 } else {
1222 let mut life_lock = queue.lock_life();
1223 let last_submit_index = life_lock.get_texture_latest_submission_index(self);
1224 if let Some(last_submit_index) = last_submit_index {
1225 life_lock.schedule_resource_destruction(temp, last_submit_index);
1226 }
1227 }
1228 }
1229
1230 Ok(())
1231 }
1232 }
1233
1234 impl Global {
1235 /// # Safety
1236 ///
1237 /// - The raw buffer handle must not be manually destroyed
1238 pub unsafe fn buffer_as_hal<A: HalApi, F: FnOnce(Option<&A::Buffer>) -> R, R>(
1239 &self,
1240 id: BufferId,
1241 hal_buffer_callback: F,
1242 ) -> R {
1243 profiling::scope!("Buffer::as_hal");
1244
1245 let hub = &self.hub;
1246
1247 if let Ok(buffer) = hub.buffers.get(id).get() {
1248 let snatch_guard = buffer.device.snatchable_lock.read();
1249 let hal_buffer = buffer
1250 .raw(&snatch_guard)
1251 .and_then(|b| b.as_any().downcast_ref());
1252 hal_buffer_callback(hal_buffer)
1253 } else {
1254 hal_buffer_callback(None)
1255 }
1256 }
1257
1258 /// # Safety
1259 ///
1260 /// - The raw texture handle must not be manually destroyed
1261 pub unsafe fn texture_as_hal<A: HalApi, F: FnOnce(Option<&A::Texture>) -> R, R>(
1262 &self,
1263 id: TextureId,
1264 hal_texture_callback: F,
1265 ) -> R {
1266 profiling::scope!("Texture::as_hal");
1267
1268 let hub = &self.hub;
1269
1270 if let Ok(texture) = hub.textures.get(id).get() {
1271 let snatch_guard = texture.device.snatchable_lock.read();
1272 let hal_texture = texture.raw(&snatch_guard);
1273 let hal_texture = hal_texture
1274 .as_ref()
1275 .and_then(|it| it.as_any().downcast_ref());
1276 hal_texture_callback(hal_texture)
1277 } else {
1278 hal_texture_callback(None)
1279 }
1280 }
1281
1282 /// # Safety
1283 ///
1284 /// - The raw texture view handle must not be manually destroyed
1285 pub unsafe fn texture_view_as_hal<A: HalApi, F: FnOnce(Option<&A::TextureView>) -> R, R>(
1286 &self,
1287 id: TextureViewId,
1288 hal_texture_view_callback: F,
1289 ) -> R {
1290 profiling::scope!("TextureView::as_hal");
1291
1292 let hub = &self.hub;
1293
1294 if let Ok(texture_view) = hub.texture_views.get(id).get() {
1295 let snatch_guard = texture_view.device.snatchable_lock.read();
1296 let hal_texture_view = texture_view.raw(&snatch_guard);
1297 let hal_texture_view = hal_texture_view
1298 .as_ref()
1299 .and_then(|it| it.as_any().downcast_ref());
1300 hal_texture_view_callback(hal_texture_view)
1301 } else {
1302 hal_texture_view_callback(None)
1303 }
1304 }
1305
1306 /// # Safety
1307 ///
1308 /// - The raw adapter handle must not be manually destroyed
1309 pub unsafe fn adapter_as_hal<A: HalApi, F: FnOnce(Option<&A::Adapter>) -> R, R>(
1310 &self,
1311 id: AdapterId,
1312 hal_adapter_callback: F,
1313 ) -> R {
1314 profiling::scope!("Adapter::as_hal");
1315
1316 let hub = &self.hub;
1317 let adapter = hub.adapters.get(id);
1318 let hal_adapter = adapter.raw.adapter.as_any().downcast_ref();
1319
1320 hal_adapter_callback(hal_adapter)
1321 }
1322
1323 /// # Safety
1324 ///
1325 /// - The raw device handle must not be manually destroyed
1326 pub unsafe fn device_as_hal<A: HalApi, F: FnOnce(Option<&A::Device>) -> R, R>(
1327 &self,
1328 id: DeviceId,
1329 hal_device_callback: F,
1330 ) -> R {
1331 profiling::scope!("Device::as_hal");
1332
1333 let device = self.hub.devices.get(id);
1334 let hal_device = device.raw().as_any().downcast_ref();
1335
1336 hal_device_callback(hal_device)
1337 }
1338
1339 /// # Safety
1340 ///
1341 /// - The raw fence handle must not be manually destroyed
1342 pub unsafe fn device_fence_as_hal<A: HalApi, F: FnOnce(Option<&A::Fence>) -> R, R>(
1343 &self,
1344 id: DeviceId,
1345 hal_fence_callback: F,
1346 ) -> R {
1347 profiling::scope!("Device::fence_as_hal");
1348
1349 let device = self.hub.devices.get(id);
1350 let fence = device.fence.read();
1351 hal_fence_callback(fence.as_any().downcast_ref())
1352 }
1353
1354 /// # Safety
1355 /// - The raw surface handle must not be manually destroyed
1356 pub unsafe fn surface_as_hal<A: HalApi, F: FnOnce(Option<&A::Surface>) -> R, R>(
1357 &self,
1358 id: SurfaceId,
1359 hal_surface_callback: F,
1360 ) -> R {
1361 profiling::scope!("Surface::as_hal");
1362
1363 let surface = self.surfaces.get(id);
1364 let hal_surface = surface
1365 .raw(A::VARIANT)
1366 .and_then(|surface| surface.as_any().downcast_ref());
1367
1368 hal_surface_callback(hal_surface)
1369 }
1370
1371 /// # Safety
1372 ///
1373 /// - The raw command encoder handle must not be manually destroyed
1374 pub unsafe fn command_encoder_as_hal_mut<
1375 A: HalApi,
1376 F: FnOnce(Option<&mut A::CommandEncoder>) -> R,
1377 R,
1378 >(
1379 &self,
1380 id: CommandEncoderId,
1381 hal_command_encoder_callback: F,
1382 ) -> R {
1383 profiling::scope!("CommandEncoder::as_hal");
1384
1385 let hub = &self.hub;
1386
1387 let cmd_buf = hub.command_buffers.get(id.into_command_buffer_id());
1388 let mut cmd_buf_data = cmd_buf.data.lock();
1389 let cmd_buf_data_guard = cmd_buf_data.record();
1390
1391 if let Ok(mut cmd_buf_data_guard) = cmd_buf_data_guard {
1392 let cmd_buf_raw = cmd_buf_data_guard
1393 .encoder
1394 .open()
1395 .ok()
1396 .and_then(|encoder| encoder.as_any_mut().downcast_mut());
1397 let ret = hal_command_encoder_callback(cmd_buf_raw);
1398 cmd_buf_data_guard.mark_successful();
1399 ret
1400 } else {
1401 hal_command_encoder_callback(None)
1402 }
1403 }
1404
1405 /// # Safety
1406 ///
1407 /// - The raw queue handle must not be manually destroyed
1408 pub unsafe fn queue_as_hal<A: HalApi, F, R>(&self, id: QueueId, hal_queue_callback: F) -> R
1409 where
1410 F: FnOnce(Option<&A::Queue>) -> R,
1411 {
1412 profiling::scope!("Queue::as_hal");
1413
1414 let queue = self.hub.queues.get(id);
1415 let hal_queue = queue.raw().as_any().downcast_ref();
1416
1417 hal_queue_callback(hal_queue)
1418 }
1419
1420 /// # Safety
1421 ///
1422 /// - The raw blas handle must not be manually destroyed
1423 pub unsafe fn blas_as_hal<A: HalApi, F: FnOnce(Option<&A::AccelerationStructure>) -> R, R>(
1424 &self,
1425 id: BlasId,
1426 hal_blas_callback: F,
1427 ) -> R {
1428 profiling::scope!("Blas::as_hal");
1429
1430 let hub = &self.hub;
1431
1432 if let Ok(blas) = hub.blas_s.get(id).get() {
1433 let snatch_guard = blas.device.snatchable_lock.read();
1434 let hal_blas = blas
1435 .try_raw(&snatch_guard)
1436 .ok()
1437 .and_then(|b| b.as_any().downcast_ref());
1438 hal_blas_callback(hal_blas)
1439 } else {
1440 hal_blas_callback(None)
1441 }
1442 }
1443
1444 /// # Safety
1445 ///
1446 /// - The raw tlas handle must not be manually destroyed
1447 pub unsafe fn tlas_as_hal<A: HalApi, F: FnOnce(Option<&A::AccelerationStructure>) -> R, R>(
1448 &self,
1449 id: TlasId,
1450 hal_tlas_callback: F,
1451 ) -> R {
1452 profiling::scope!("Blas::as_hal");
1453
1454 let hub = &self.hub;
1455
1456 if let Ok(tlas) = hub.tlas_s.get(id).get() {
1457 let snatch_guard = tlas.device.snatchable_lock.read();
1458 let hal_tlas = tlas
1459 .try_raw(&snatch_guard)
1460 .ok()
1461 .and_then(|t| t.as_any().downcast_ref());
1462 hal_tlas_callback(hal_tlas)
1463 } else {
1464 hal_tlas_callback(None)
1465 }
1466 }
1467 }
1468
1469 /// A texture that has been marked as destroyed and is staged for actual deletion soon.
1470 #[derive(Debug)]
1471 pub struct DestroyedTexture {
1472 raw: ManuallyDrop<Box<dyn hal::DynTexture>>,
1473 views: WeakVec<TextureView>,
1474 bind_groups: WeakVec<BindGroup>,
1475 device: Arc<Device>,
1476 label: String,
1477 }
1478
1479 impl DestroyedTexture {
1480 pub fn label(&self) -> &dyn fmt::Debug {
1481 &self.label
1482 }
1483 }
1484
1485 impl Drop for DestroyedTexture {
1486 fn drop(&mut self) {
1487 let device = &self.device;
1488
1489 let mut deferred = device.deferred_destroy.lock();
1490 deferred.push(DeferredDestroy::TextureViews(mem::take(&mut self.views)));
1491 deferred.push(DeferredDestroy::BindGroups(mem::take(
1492 &mut self.bind_groups,
1493 )));
1494 drop(deferred);
1495
1496 resource_log!("Destroy raw Texture (destroyed) {:?}", self.label());
1497 // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
1498 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
1499 unsafe {
1500 self.device.raw().destroy_texture(raw);
1501 }
1502 }
1503 }
1504
1505 #[derive(Clone, Copy, Debug)]
1506 pub enum TextureErrorDimension {
1507 X,
1508 Y,
1509 Z,
1510 }
1511
1512 #[derive(Clone, Debug, Error)]
1513 #[non_exhaustive]
1514 pub enum TextureDimensionError {
1515 #[error("Dimension {0:?} is zero")]
1516 Zero(TextureErrorDimension),
1517 #[error("Dimension {dim:?} value {given} exceeds the limit of {limit}")]
1518 LimitExceeded {
1519 dim: TextureErrorDimension,
1520 given: u32,
1521 limit: u32,
1522 },
1523 #[error("Sample count {0} is invalid")]
1524 InvalidSampleCount(u32),
1525 #[error("Width {width} is not a multiple of {format:?}'s block width ({block_width})")]
1526 NotMultipleOfBlockWidth {
1527 width: u32,
1528 block_width: u32,
1529 format: wgt::TextureFormat,
1530 },
1531 #[error("Height {height} is not a multiple of {format:?}'s block height ({block_height})")]
1532 NotMultipleOfBlockHeight {
1533 height: u32,
1534 block_height: u32,
1535 format: wgt::TextureFormat,
1536 },
1537 #[error(
1538 "Width {width} is not a multiple of {format:?}'s width multiple requirement ({multiple})"
1539 )]
1540 WidthNotMultipleOf {
1541 width: u32,
1542 multiple: u32,
1543 format: wgt::TextureFormat,
1544 },
1545 #[error("Height {height} is not a multiple of {format:?}'s height multiple requirement ({multiple})")]
1546 HeightNotMultipleOf {
1547 height: u32,
1548 multiple: u32,
1549 format: wgt::TextureFormat,
1550 },
1551 #[error("Multisampled texture depth or array layers must be 1, got {0}")]
1552 MultisampledDepthOrArrayLayer(u32),
1553 }
1554
1555 #[derive(Clone, Debug, Error)]
1556 #[non_exhaustive]
1557 pub enum CreateTextureError {
1558 #[error(transparent)]
1559 Device(#[from] DeviceError),
1560 #[error(transparent)]
1561 CreateTextureView(#[from] CreateTextureViewError),
1562 #[error("Invalid usage flags {0:?}")]
1563 InvalidUsage(wgt::TextureUsages),
1564 #[error(transparent)]
1565 InvalidDimension(#[from] TextureDimensionError),
1566 #[error("Depth texture ({1:?}) can't be created as {0:?}")]
1567 InvalidDepthDimension(wgt::TextureDimension, wgt::TextureFormat),
1568 #[error("Compressed texture ({1:?}) can't be created as {0:?}")]
1569 InvalidCompressedDimension(wgt::TextureDimension, wgt::TextureFormat),
1570 #[error(
1571 "Texture descriptor mip level count {requested} is invalid, maximum allowed is {maximum}"
1572 )]
1573 InvalidMipLevelCount { requested: u32, maximum: u32 },
1574 #[error(
1575 "Texture usages {0:?} are not allowed on a texture of type {1:?}{downlevel_suffix}",
1576 downlevel_suffix = if *.2 { " due to downlevel restrictions" } else { "" }
1577 )]
1578 InvalidFormatUsages(wgt::TextureUsages, wgt::TextureFormat, bool),
1579 #[error("The view format {0:?} is not compatible with texture format {1:?}, only changing srgb-ness is allowed.")]
1580 InvalidViewFormat(wgt::TextureFormat, wgt::TextureFormat),
1581 #[error("Texture usages {0:?} are not allowed on a texture of dimensions {1:?}")]
1582 InvalidDimensionUsages(wgt::TextureUsages, wgt::TextureDimension),
1583 #[error("Texture usage STORAGE_BINDING is not allowed for multisampled textures")]
1584 InvalidMultisampledStorageBinding,
1585 #[error("Format {0:?} does not support multisampling")]
1586 InvalidMultisampledFormat(wgt::TextureFormat),
1587 #[error("Sample count {0} is not supported by format {1:?} on this device. The WebGPU spec guarantees {2:?} samples are supported by this format. With the TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES feature your device supports {3:?}.")]
1588 InvalidSampleCount(u32, wgt::TextureFormat, Vec<u32>, Vec<u32>),
1589 #[error("Multisampled textures must have RENDER_ATTACHMENT usage")]
1590 MultisampledNotRenderAttachment,
1591 #[error("Texture format {0:?} can't be used due to missing features")]
1592 MissingFeatures(wgt::TextureFormat, #[source] MissingFeatures),
1593 #[error(transparent)]
1594 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
1595 }
1596
1597 crate::impl_resource_type!(Texture);
1598 crate::impl_labeled!(Texture);
1599 crate::impl_parent_device!(Texture);
1600 crate::impl_storage_item!(Texture);
1601 crate::impl_trackable!(Texture);
1602
1603 impl Borrow<TextureSelector> for Texture {
1604 fn borrow(&self) -> &TextureSelector {
1605 &self.full_range
1606 }
1607 }
1608
1609 /// Describes a [`TextureView`].
1610 #[derive(Clone, Debug, Default, Eq, PartialEq)]
1611 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1612 #[cfg_attr(feature = "serde", serde(default))]
1613 pub struct TextureViewDescriptor<'a> {
1614 /// Debug label of the texture view.
1615 ///
1616 /// This will show up in graphics debuggers for easy identification.
1617 pub label: Label<'a>,
1618 /// Format of the texture view, or `None` for the same format as the texture
1619 /// itself.
1620 ///
1621 /// At this time, it must be the same the underlying format of the texture.
1622 pub format: Option<wgt::TextureFormat>,
1623 /// The dimension of the texture view.
1624 ///
1625 /// - For 1D textures, this must be `D1`.
1626 /// - For 2D textures it must be one of `D2`, `D2Array`, `Cube`, or `CubeArray`.
1627 /// - For 3D textures it must be `D3`.
1628 pub dimension: Option<wgt::TextureViewDimension>,
1629 /// The allowed usage(s) for the texture view. Must be a subset of the usage flags of the texture.
1630 /// If not provided, defaults to the full set of usage flags of the texture.
1631 pub usage: Option<wgt::TextureUsages>,
1632 /// Range within the texture that is accessible via this view.
1633 pub range: wgt::ImageSubresourceRange,
1634 }
1635
1636 #[derive(Debug)]
1637 pub(crate) struct HalTextureViewDescriptor {
1638 pub texture_format: wgt::TextureFormat,
1639 pub format: wgt::TextureFormat,
1640 pub usage: wgt::TextureUsages,
1641 pub dimension: wgt::TextureViewDimension,
1642 pub range: wgt::ImageSubresourceRange,
1643 }
1644
1645 impl HalTextureViewDescriptor {
1646 pub fn aspects(&self) -> hal::FormatAspects {
1647 hal::FormatAspects::new(self.texture_format, self.range.aspect)
1648 }
1649 }
1650
1651 #[derive(Debug, Copy, Clone, Error)]
1652 pub enum TextureViewNotRenderableReason {
1653 #[error("The texture this view references doesn't include the RENDER_ATTACHMENT usage. Provided usages: {0:?}")]
1654 Usage(wgt::TextureUsages),
1655 #[error("The dimension of this texture view is not 2D. View dimension: {0:?}")]
1656 Dimension(wgt::TextureViewDimension),
1657 #[error("This texture view has more than one mipmap level. View mipmap levels: {0:?}")]
1658 MipLevelCount(u32),
1659 #[error("This texture view has more than one array layer. View array layers: {0:?}")]
1660 ArrayLayerCount(u32),
1661 #[error(
1662 "The aspects of this texture view are a subset of the aspects in the original texture. Aspects: {0:?}"
1663 )]
1664 Aspects(hal::FormatAspects),
1665 }
1666
1667 #[derive(Debug)]
1668 pub struct TextureView {
1669 pub(crate) raw: Snatchable<Box<dyn hal::DynTextureView>>,
1670 // if it's a surface texture - it's none
1671 pub(crate) parent: Arc<Texture>,
1672 pub(crate) device: Arc<Device>,
1673 pub(crate) desc: HalTextureViewDescriptor,
1674 pub(crate) format_features: wgt::TextureFormatFeatures,
1675 /// This is `Err` only if the texture view is not renderable
1676 pub(crate) render_extent: Result<wgt::Extent3d, TextureViewNotRenderableReason>,
1677 pub(crate) samples: u32,
1678 pub(crate) selector: TextureSelector,
1679 /// The `label` from the descriptor used to create the resource.
1680 pub(crate) label: String,
1681 pub(crate) tracking_data: TrackingData,
1682 }
1683
1684 impl Drop for TextureView {
1685 fn drop(&mut self) {
1686 if let Some(raw) = self.raw.take() {
1687 resource_log!("Destroy raw {}", self.error_ident());
1688 unsafe {
1689 self.device.raw().destroy_texture_view(raw);
1690 }
1691 }
1692 }
1693 }
1694
1695 impl TextureView {
1696 pub(crate) fn raw<'a>(
1697 &'a self,
1698 snatch_guard: &'a SnatchGuard,
1699 ) -> Option<&'a dyn hal::DynTextureView> {
1700 self.raw.get(snatch_guard).map(|it| it.as_ref())
1701 }
1702
1703 pub(crate) fn try_raw<'a>(
1704 &'a self,
1705 guard: &'a SnatchGuard,
1706 ) -> Result<&'a dyn hal::DynTextureView, DestroyedResourceError> {
1707 self.raw
1708 .get(guard)
1709 .map(|it| it.as_ref())
1710 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
1711 }
1712
1713 /// Checks that the given texture usage contains the required texture usage,
1714 /// returns an error otherwise.
1715 pub(crate) fn check_usage(
1716 &self,
1717 expected: wgt::TextureUsages,
1718 ) -> Result<(), MissingTextureUsageError> {
1719 if self.desc.usage.contains(expected) {
1720 Ok(())
1721 } else {
1722 Err(MissingTextureUsageError {
1723 res: self.error_ident(),
1724 actual: self.desc.usage,
1725 expected,
1726 })
1727 }
1728 }
1729 }
1730
1731 #[derive(Clone, Debug, Error)]
1732 #[non_exhaustive]
1733 pub enum CreateTextureViewError {
1734 #[error(transparent)]
1735 Device(#[from] DeviceError),
1736 #[error(transparent)]
1737 DestroyedResource(#[from] DestroyedResourceError),
1738 #[error("Invalid texture view dimension `{view:?}` with texture of dimension `{texture:?}`")]
1739 InvalidTextureViewDimension {
1740 view: wgt::TextureViewDimension,
1741 texture: wgt::TextureDimension,
1742 },
1743 #[error("Texture view format `{0:?}` is not renderable")]
1744 TextureViewFormatNotRenderable(wgt::TextureFormat),
1745 #[error("Texture view format `{0:?}` is not storage bindable")]
1746 TextureViewFormatNotStorage(wgt::TextureFormat),
1747 #[error("Invalid texture view usage `{view:?}` with texture of usage `{texture:?}`")]
1748 InvalidTextureViewUsage {
1749 view: wgt::TextureUsages,
1750 texture: wgt::TextureUsages,
1751 },
1752 #[error("Invalid texture view dimension `{0:?}` of a multisampled texture")]
1753 InvalidMultisampledTextureViewDimension(wgt::TextureViewDimension),
1754 #[error("Invalid texture depth `{depth}` for texture view of dimension `Cubemap`. Cubemap views must use images of size 6.")]
1755 InvalidCubemapTextureDepth { depth: u32 },
1756 #[error("Invalid texture depth `{depth}` for texture view of dimension `CubemapArray`. Cubemap views must use images with sizes which are a multiple of 6.")]
1757 InvalidCubemapArrayTextureDepth { depth: u32 },
1758 #[error("Source texture width and height must be equal for a texture view of dimension `Cube`/`CubeArray`")]
1759 InvalidCubeTextureViewSize,
1760 #[error("Mip level count is 0")]
1761 ZeroMipLevelCount,
1762 #[error("Array layer count is 0")]
1763 ZeroArrayLayerCount,
1764 #[error(
1765 "TextureView mip level count + base mip level {requested} must be <= Texture mip level count {total}"
1766 )]
1767 TooManyMipLevels { requested: u32, total: u32 },
1768 #[error("TextureView array layer count + base array layer {requested} must be <= Texture depth/array layer count {total}")]
1769 TooManyArrayLayers { requested: u32, total: u32 },
1770 #[error("Requested array layer count {requested} is not valid for the target view dimension {dim:?}")]
1771 InvalidArrayLayerCount {
1772 requested: u32,
1773 dim: wgt::TextureViewDimension,
1774 },
1775 #[error("Aspect {requested_aspect:?} is not in the source texture format {texture_format:?}")]
1776 InvalidAspect {
1777 texture_format: wgt::TextureFormat,
1778 requested_aspect: wgt::TextureAspect,
1779 },
1780 #[error("Unable to view texture {texture:?} as {view:?}")]
1781 FormatReinterpretation {
1782 texture: wgt::TextureFormat,
1783 view: wgt::TextureFormat,
1784 },
1785 #[error(transparent)]
1786 InvalidResource(#[from] InvalidResourceError),
1787 #[error(transparent)]
1788 MissingFeatures(#[from] MissingFeatures),
1789 }
1790
1791 #[derive(Clone, Debug, Error)]
1792 #[non_exhaustive]
1793 pub enum TextureViewDestroyError {}
1794
1795 crate::impl_resource_type!(TextureView);
1796 crate::impl_labeled!(TextureView);
1797 crate::impl_parent_device!(TextureView);
1798 crate::impl_storage_item!(TextureView);
1799 crate::impl_trackable!(TextureView);
1800
1801 /// Describes a [`Sampler`]
1802 #[derive(Clone, Debug, PartialEq)]
1803 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1804 pub struct SamplerDescriptor<'a> {
1805 /// Debug label of the sampler.
1806 ///
1807 /// This will show up in graphics debuggers for easy identification.
1808 pub label: Label<'a>,
1809 /// How to deal with out of bounds accesses in the u (i.e. x) direction
1810 pub address_modes: [wgt::AddressMode; 3],
1811 /// How to filter the texture when it needs to be magnified (made larger)
1812 pub mag_filter: wgt::FilterMode,
1813 /// How to filter the texture when it needs to be minified (made smaller)
1814 pub min_filter: wgt::FilterMode,
1815 /// How to filter between mip map levels
1816 pub mipmap_filter: wgt::FilterMode,
1817 /// Minimum level of detail (i.e. mip level) to use
1818 pub lod_min_clamp: f32,
1819 /// Maximum level of detail (i.e. mip level) to use
1820 pub lod_max_clamp: f32,
1821 /// If this is enabled, this is a comparison sampler using the given comparison function.
1822 pub compare: Option<wgt::CompareFunction>,
1823 /// Must be at least 1. If this is not 1, all filter modes must be linear.
1824 pub anisotropy_clamp: u16,
1825 /// Border color to use when address_mode is
1826 /// [`AddressMode::ClampToBorder`](wgt::AddressMode::ClampToBorder)
1827 pub border_color: Option<wgt::SamplerBorderColor>,
1828 }
1829
1830 #[derive(Debug)]
1831 pub struct Sampler {
1832 pub(crate) raw: ManuallyDrop<Box<dyn hal::DynSampler>>,
1833 pub(crate) device: Arc<Device>,
1834 /// The `label` from the descriptor used to create the resource.
1835 pub(crate) label: String,
1836 pub(crate) tracking_data: TrackingData,
1837 /// `true` if this is a comparison sampler
1838 pub(crate) comparison: bool,
1839 /// `true` if this is a filtering sampler
1840 pub(crate) filtering: bool,
1841 }
1842
1843 impl Drop for Sampler {
1844 fn drop(&mut self) {
1845 resource_log!("Destroy raw {}", self.error_ident());
1846 // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
1847 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
1848 unsafe {
1849 self.device.raw().destroy_sampler(raw);
1850 }
1851 }
1852 }
1853
1854 impl Sampler {
1855 pub(crate) fn raw(&self) -> &dyn hal::DynSampler {
1856 self.raw.as_ref()
1857 }
1858 }
1859
1860 #[derive(Copy, Clone)]
1861 pub enum SamplerFilterErrorType {
1862 MagFilter,
1863 MinFilter,
1864 MipmapFilter,
1865 }
1866
1867 impl fmt::Debug for SamplerFilterErrorType {
1868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1869 match *self {
1870 SamplerFilterErrorType::MagFilter => write!(f, "magFilter"),
1871 SamplerFilterErrorType::MinFilter => write!(f, "minFilter"),
1872 SamplerFilterErrorType::MipmapFilter => write!(f, "mipmapFilter"),
1873 }
1874 }
1875 }
1876
1877 #[derive(Clone, Debug, Error)]
1878 #[non_exhaustive]
1879 pub enum CreateSamplerError {
1880 #[error(transparent)]
1881 Device(#[from] DeviceError),
1882 #[error("Invalid lodMinClamp: {0}. Must be greater or equal to 0.0")]
1883 InvalidLodMinClamp(f32),
1884 #[error("Invalid lodMaxClamp: {lod_max_clamp}. Must be greater or equal to lodMinClamp (which is {lod_min_clamp}).")]
1885 InvalidLodMaxClamp {
1886 lod_min_clamp: f32,
1887 lod_max_clamp: f32,
1888 },
1889 #[error("Invalid anisotropic clamp: {0}. Must be at least 1.")]
1890 InvalidAnisotropy(u16),
1891 #[error("Invalid filter mode for {filter_type:?}: {filter_mode:?}. When anistropic clamp is not 1 (it is {anisotropic_clamp}), all filter modes must be linear.")]
1892 InvalidFilterModeWithAnisotropy {
1893 filter_type: SamplerFilterErrorType,
1894 filter_mode: wgt::FilterMode,
1895 anisotropic_clamp: u16,
1896 },
1897 #[error(transparent)]
1898 MissingFeatures(#[from] MissingFeatures),
1899 }
1900
1901 crate::impl_resource_type!(Sampler);
1902 crate::impl_labeled!(Sampler);
1903 crate::impl_parent_device!(Sampler);
1904 crate::impl_storage_item!(Sampler);
1905 crate::impl_trackable!(Sampler);
1906
1907 #[derive(Clone, Debug, Error)]
1908 #[non_exhaustive]
1909 pub enum CreateQuerySetError {
1910 #[error(transparent)]
1911 Device(#[from] DeviceError),
1912 #[error("QuerySets cannot be made with zero queries")]
1913 ZeroCount,
1914 #[error("{count} is too many queries for a single QuerySet. QuerySets cannot be made more than {maximum} queries.")]
1915 TooManyQueries { count: u32, maximum: u32 },
1916 #[error(transparent)]
1917 MissingFeatures(#[from] MissingFeatures),
1918 }
1919
1920 pub type QuerySetDescriptor<'a> = wgt::QuerySetDescriptor<Label<'a>>;
1921
1922 #[derive(Debug)]
1923 pub struct QuerySet {
1924 pub(crate) raw: ManuallyDrop<Box<dyn hal::DynQuerySet>>,
1925 pub(crate) device: Arc<Device>,
1926 /// The `label` from the descriptor used to create the resource.
1927 pub(crate) label: String,
1928 pub(crate) tracking_data: TrackingData,
1929 pub(crate) desc: wgt::QuerySetDescriptor<()>,
1930 }
1931
1932 impl Drop for QuerySet {
1933 fn drop(&mut self) {
1934 resource_log!("Destroy raw {}", self.error_ident());
1935 // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
1936 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
1937 unsafe {
1938 self.device.raw().destroy_query_set(raw);
1939 }
1940 }
1941 }
1942
1943 crate::impl_resource_type!(QuerySet);
1944 crate::impl_labeled!(QuerySet);
1945 crate::impl_parent_device!(QuerySet);
1946 crate::impl_storage_item!(QuerySet);
1947 crate::impl_trackable!(QuerySet);
1948
1949 impl QuerySet {
1950 pub(crate) fn raw(&self) -> &dyn hal::DynQuerySet {
1951 self.raw.as_ref()
1952 }
1953 }
1954
1955 #[derive(Clone, Debug, Error)]
1956 #[non_exhaustive]
1957 pub enum DestroyError {
1958 #[error(transparent)]
1959 InvalidResource(#[from] InvalidResourceError),
1960 }
1961
1962 pub type BlasDescriptor<'a> = wgt::CreateBlasDescriptor<Label<'a>>;
1963 pub type TlasDescriptor<'a> = wgt::CreateTlasDescriptor<Label<'a>>;
1964
1965 pub(crate) trait AccelerationStructure: Trackable {
1966 fn try_raw<'a>(
1967 &'a self,
1968 guard: &'a SnatchGuard,
1969 ) -> Result<&'a dyn hal::DynAccelerationStructure, DestroyedResourceError>;
1970 }
1971
1972 #[derive(Debug)]
1973 pub struct Blas {
1974 pub(crate) raw: Snatchable<Box<dyn hal::DynAccelerationStructure>>,
1975 pub(crate) device: Arc<Device>,
1976 pub(crate) size_info: hal::AccelerationStructureBuildSizes,
1977 pub(crate) sizes: wgt::BlasGeometrySizeDescriptors,
1978 pub(crate) flags: wgt::AccelerationStructureFlags,
1979 pub(crate) update_mode: wgt::AccelerationStructureUpdateMode,
1980 pub(crate) built_index: RwLock<Option<NonZeroU64>>,
1981 pub(crate) handle: u64,
1982 /// The `label` from the descriptor used to create the resource.
1983 pub(crate) label: String,
1984 pub(crate) tracking_data: TrackingData,
1985 }
1986
1987 impl Drop for Blas {
1988 fn drop(&mut self) {
1989 resource_log!("Destroy raw {}", self.error_ident());
1990 // SAFETY: We are in the Drop impl, and we don't use self.raw anymore after this point.
1991 if let Some(raw) = self.raw.take() {
1992 unsafe {
1993 self.device.raw().destroy_acceleration_structure(raw);
1994 }
1995 }
1996 }
1997 }
1998
1999 impl AccelerationStructure for Blas {
2000 fn try_raw<'a>(
2001 &'a self,
2002 guard: &'a SnatchGuard,
2003 ) -> Result<&'a dyn hal::DynAccelerationStructure, DestroyedResourceError> {
2004 self.raw
2005 .get(guard)
2006 .map(|raw| raw.as_ref())
2007 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
2008 }
2009 }
2010
2011 crate::impl_resource_type!(Blas);
2012 crate::impl_labeled!(Blas);
2013 crate::impl_parent_device!(Blas);
2014 crate::impl_storage_item!(Blas);
2015 crate::impl_trackable!(Blas);
2016
2017 #[derive(Debug)]
2018 pub struct Tlas {
2019 pub(crate) raw: Snatchable<Box<dyn hal::DynAccelerationStructure>>,
2020 pub(crate) device: Arc<Device>,
2021 pub(crate) size_info: hal::AccelerationStructureBuildSizes,
2022 pub(crate) max_instance_count: u32,
2023 pub(crate) flags: wgt::AccelerationStructureFlags,
2024 pub(crate) update_mode: wgt::AccelerationStructureUpdateMode,
2025 pub(crate) built_index: RwLock<Option<NonZeroU64>>,
2026 pub(crate) dependencies: RwLock<Vec<Arc<Blas>>>,
2027 pub(crate) instance_buffer: ManuallyDrop<Box<dyn hal::DynBuffer>>,
2028 /// The `label` from the descriptor used to create the resource.
2029 pub(crate) label: String,
2030 pub(crate) tracking_data: TrackingData,
2031 }
2032
2033 impl Drop for Tlas {
2034 fn drop(&mut self) {
2035 unsafe {
2036 resource_log!("Destroy raw {}", self.error_ident());
2037 if let Some(structure) = self.raw.take() {
2038 self.device.raw().destroy_acceleration_structure(structure);
2039 }
2040 let buffer = ManuallyDrop::take(&mut self.instance_buffer);
2041 self.device.raw().destroy_buffer(buffer);
2042 }
2043 }
2044 }
2045
2046 impl AccelerationStructure for Tlas {
2047 fn try_raw<'a>(
2048 &'a self,
2049 guard: &'a SnatchGuard,
2050 ) -> Result<&'a dyn hal::DynAccelerationStructure, DestroyedResourceError> {
2051 self.raw
2052 .get(guard)
2053 .map(|raw| raw.as_ref())
2054 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
2055 }
2056 }
2057
2058 crate::impl_resource_type!(Tlas);
2059 crate::impl_labeled!(Tlas);
2060 crate::impl_parent_device!(Tlas);
2061 crate::impl_storage_item!(Tlas);
2062 crate::impl_trackable!(Tlas);