Skip to main content

wgpu_core/track/
mod.rs

1/*! Resource State and Lifetime Trackers
2
3These structures are responsible for keeping track of resource state,
4generating barriers where needednd making sure resources are kept
5alive until the trackers die.
6
7## General Architecture
8
9Tracking is some of the hottest code in the entire codebase, so the trackers
10are designed to be as cache efficient as possible. They store resource state
11in flat vectors, storing metadata SOA style, one vector per type of metadata.
12
13A lot of the tracker code is deeply unsafe, using unchecked accesses all over
14to make performance as good as possible. However, for all unsafe accesses, there
15is a corresponding debug assert the checks if that access is valid. This helps
16get bugs caught fast, while still letting users not need to pay for the bounds
17checks.
18
19In wgpu, each resource ID includes a bitfield holding an index.
20Indices are allocated and re-used, so they will always be as low as
21reasonably possible. This allows us to use IDs to index into an array
22of tracking information.
23
24## Statefulness
25
26There are two main types of trackers, stateful and stateless.
27
28Stateful trackers are for buffers and textures. They both have
29resource state attached to them which needs to be used to generate
30automatic synchronization. Because of the different requirements of
31buffers and textures, they have two separate tracking structures.
32
33Stateless trackers only store metadata and own the given resource.
34
35## Use Case
36
37Within each type of tracker, the trackers are further split into 3 different
38use cases, Bind Group, Usage Scopend a full Tracker.
39
40Bind Group trackers are just a list of different resources, their refcount,
41and how they are used. Textures are used via a selector and a usage type.
42Buffers by just a usage type. Stateless resources don't have a usage type.
43
44Usage Scope trackers are only for stateful resources. These trackers represent
45a single [`UsageScope`] in the spec. When a use is added to a usage scope,
46it is merged with all other uses of that resource in that scope. If there
47is a usage conflict, merging will fail and an error will be reported.
48
49Full trackers represent a before and after state of a resource. These
50are used for tracking on the device and on command buffers. The before
51state represents the state the resource is first used as in the command buffer,
52the after state is the state the command buffer leaves the resource in.
53These double ended buffers can then be used to generate the needed transitions
54between command buffers.
55
56## Dense Datastructure with Sparse Data
57
58This tracking system is based on having completely dense data, but trackers do
59not always contain every resource. Some resources (or even most resources) go
60unused in any given command buffer. So to help speed up the process of iterating
61through possibly thousands of resources, we use a bit vector to represent if
62a resource is in the buffer or not. This allows us extremely efficient memory
63utilizations well as being able to bail out of whole blocks of 32-64 resources
64with a single usize comparison with zero. In practice this means that merging
65partially resident buffers is extremely quick.
66
67The main advantage of this dense datastructure is that we can do merging
68of trackers in an extremely efficient fashion that results in us doing linear
69scans down a couple of buffers. CPUs and their caches absolutely eat this up.
70
71## Stateful Resource Operations
72
73All operations on stateful trackers boil down to one of four operations:
74- `insert(tracker, new_state)` adds a resource with a given state to the tracker
75  for the first time.
76- `merge(tracker, new_state)` merges this new state with the previous state, checking
77  for usage conflicts.
78- `barrier(tracker, new_state)` compares the given state to the existing state and
79  generates the needed barriers.
80- `update(tracker, new_state)` takes the given new state and overrides the old state.
81
82This allows us to compose the operations to form the various kinds of tracker merges
83that need to happen in the codebase. For each resource in the given merger, the following
84operation applies:
85
86```text
87UsageScope <- Resource = insert(scope, usage) OR merge(scope, usage)
88UsageScope <- UsageScope = insert(scope, scope) OR merge(scope, scope)
89CommandBuffer <- UsageScope = insert(buffer.start, buffer.end, scope)
90                              OR barrier(buffer.end, scope) + update(buffer.end, scope)
91Device <- CommandBuffer = insert(device.start, device.end, buffer.start, buffer.end)
92                          OR barrier(device.end, buffer.start) + update(device.end, buffer.end)
93```
94
95[`UsageScope`]: https://gpuweb.github.io/gpuweb/#programming-model-synchronization
96*/
97
98mod blas;
99mod buffer;
100mod metadata;
101mod query_set;
102mod range;
103mod stateless;
104mod texture;
105
106use crate::{
107    binding_model, command,
108    lock::{rank, Mutex},
109    pipeline, ray_tracing_pipeline,
110    resource::{self, Labeled, RawResourceAccess, ResourceErrorIdent, Trackable},
111    snatch::SnatchGuard,
112    track::blas::BlasTracker,
113};
114
115use alloc::{sync::Arc, vec::Vec};
116use bitflags::Flags;
117use core::{fmt, mem, ops};
118
119use thiserror::Error;
120
121pub(crate) use crate::track::query_set::QuerySetTracker;
122pub(crate) use buffer::{
123    BufferBindGroupState, BufferTracker, BufferUsageScope, DeviceBufferTracker,
124};
125use metadata::{ResourceMetadata, ResourceMetadataProvider};
126pub(crate) use stateless::StatelessTracker;
127pub(crate) use texture::{
128    DeviceTextureTracker, TextureTracker, TextureTrackerSetSingle, TextureUsageScope,
129    TextureViewBindGroupState,
130};
131use wgt::{
132    error::{ErrorType, WebGpuError},
133    strict_assert_ne,
134};
135
136#[repr(transparent)]
137#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
138pub(crate) struct TrackerIndex(u32);
139
140impl TrackerIndex {
141    pub fn as_usize(self) -> usize {
142        self.0 as usize
143    }
144}
145
146/// wgpu-core internally use some array-like storage for tracking resources.
147/// To that end, there needs to be a uniquely assigned index for each live resource
148/// of a certain type. This index is separate from the resource ID for various reasons:
149/// - There can be multiple resource IDs pointing to the same resource.
150/// - IDs of dead handles can be recycled while resources are internally held alive (and tracked).
151/// - The plan is to remove IDs in the long run
152///   ([#5121](https://github.com/gfx-rs/wgpu/issues/5121)).
153///
154/// In order to produce these tracker indices, there is a shared TrackerIndexAllocator
155/// per resource type. Indices have the same lifetime as the internal resource they
156/// are associated to (alloc happens when creating the resource and free is called when
157/// the resource is dropped).
158struct TrackerIndexAllocator {
159    unused: Vec<TrackerIndex>,
160    next_index: TrackerIndex,
161}
162
163impl TrackerIndexAllocator {
164    pub fn new() -> Self {
165        TrackerIndexAllocator {
166            unused: Vec::new(),
167            next_index: TrackerIndex(0),
168        }
169    }
170
171    pub fn alloc(&mut self) -> TrackerIndex {
172        if let Some(index) = self.unused.pop() {
173            return index;
174        }
175
176        let index = self.next_index;
177        self.next_index.0 += 1;
178
179        index
180    }
181
182    pub fn free(&mut self, index: TrackerIndex) {
183        self.unused.push(index);
184    }
185
186    // This is used to pre-allocate the tracker storage.
187    pub fn size(&self) -> usize {
188        self.next_index.0 as usize
189    }
190}
191
192impl fmt::Debug for TrackerIndexAllocator {
193    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
194        Ok(())
195    }
196}
197
198/// See TrackerIndexAllocator.
199#[derive(Debug)]
200pub(crate) struct SharedTrackerIndexAllocator {
201    inner: Mutex<TrackerIndexAllocator>,
202}
203
204impl SharedTrackerIndexAllocator {
205    pub fn new() -> Self {
206        SharedTrackerIndexAllocator {
207            inner: Mutex::new(
208                rank::SHARED_TRACKER_INDEX_ALLOCATOR_INNER,
209                TrackerIndexAllocator::new(),
210            ),
211        }
212    }
213
214    pub fn alloc(&self) -> TrackerIndex {
215        self.inner.lock().alloc()
216    }
217
218    pub fn free(&self, index: TrackerIndex) {
219        self.inner.lock().free(index);
220    }
221
222    pub fn size(&self) -> usize {
223        self.inner.lock().size()
224    }
225}
226
227pub(crate) struct TrackerIndexAllocators {
228    pub buffers: Arc<SharedTrackerIndexAllocator>,
229    pub textures: Arc<SharedTrackerIndexAllocator>,
230    pub external_textures: Arc<SharedTrackerIndexAllocator>,
231    pub samplers: Arc<SharedTrackerIndexAllocator>,
232    pub bind_groups: Arc<SharedTrackerIndexAllocator>,
233    pub compute_pipelines: Arc<SharedTrackerIndexAllocator>,
234    pub render_pipelines: Arc<SharedTrackerIndexAllocator>,
235    pub ray_tracing_pipelines: Arc<SharedTrackerIndexAllocator>,
236    pub bundles: Arc<SharedTrackerIndexAllocator>,
237    pub query_sets: Arc<SharedTrackerIndexAllocator>,
238    pub blas_s: Arc<SharedTrackerIndexAllocator>,
239    pub tlas_s: Arc<SharedTrackerIndexAllocator>,
240}
241
242impl TrackerIndexAllocators {
243    pub fn new() -> Self {
244        TrackerIndexAllocators {
245            buffers: Arc::new(SharedTrackerIndexAllocator::new()),
246            textures: Arc::new(SharedTrackerIndexAllocator::new()),
247            external_textures: Arc::new(SharedTrackerIndexAllocator::new()),
248            samplers: Arc::new(SharedTrackerIndexAllocator::new()),
249            bind_groups: Arc::new(SharedTrackerIndexAllocator::new()),
250            compute_pipelines: Arc::new(SharedTrackerIndexAllocator::new()),
251            render_pipelines: Arc::new(SharedTrackerIndexAllocator::new()),
252            ray_tracing_pipelines: Arc::new(SharedTrackerIndexAllocator::new()),
253            bundles: Arc::new(SharedTrackerIndexAllocator::new()),
254            query_sets: Arc::new(SharedTrackerIndexAllocator::new()),
255            blas_s: Arc::new(SharedTrackerIndexAllocator::new()),
256            tlas_s: Arc::new(SharedTrackerIndexAllocator::new()),
257        }
258    }
259}
260
261/// A structure containing all the information about a particular resource
262/// transition. User code should be able to generate a pipeline barrier
263/// based on the contents.
264#[derive(Debug, PartialEq)]
265pub(crate) struct PendingTransition<S: ResourceUses> {
266    pub id: u32,
267    pub selector: S::Selector,
268    pub usage: hal::StateTransition<S>,
269}
270
271pub(crate) type PendingTransitionList = Vec<PendingTransition<wgt::TextureUses>>;
272
273impl PendingTransition<wgt::BufferUses> {
274    /// Produce the hal barrier corresponding to the transition.
275    pub fn into_hal<'a>(
276        self,
277        buf: &'a resource::Buffer,
278        snatch_guard: &'a SnatchGuard<'a>,
279    ) -> hal::BufferBarrier<'a, dyn hal::DynBuffer> {
280        let buffer = buf.raw(snatch_guard).expect("Buffer is destroyed");
281        hal::BufferBarrier {
282            buffer,
283            usage: self.usage,
284        }
285    }
286}
287
288impl PendingTransition<wgt::TextureUses> {
289    /// Produce the hal barrier corresponding to the transition.
290    pub fn into_hal(
291        self,
292        texture: &dyn hal::DynTexture,
293    ) -> hal::TextureBarrier<'_, dyn hal::DynTexture> {
294        // These showing up in a barrier is always a bug
295        strict_assert_ne!(self.usage.from, wgt::TextureUses::UNKNOWN);
296        strict_assert_ne!(self.usage.to, wgt::TextureUses::UNKNOWN);
297
298        let mip_count = self.selector.mips.end - self.selector.mips.start;
299        strict_assert_ne!(mip_count, 0);
300        let layer_count = self.selector.layers.end - self.selector.layers.start;
301        strict_assert_ne!(layer_count, 0);
302
303        hal::TextureBarrier {
304            texture,
305            range: wgt::ImageSubresourceRange {
306                aspect: wgt::TextureAspect::All,
307                base_mip_level: self.selector.mips.start,
308                mip_level_count: Some(mip_count),
309                base_array_layer: self.selector.layers.start,
310                array_layer_count: Some(layer_count),
311            },
312            usage: self.usage,
313            queue_family_ownership_transfer: None,
314        }
315    }
316}
317
318/// The uses that a resource or subresource can be in.
319pub(crate) trait ResourceUses:
320    fmt::Debug + ops::BitAnd<Output = Self> + ops::BitOr<Output = Self> + PartialEq + Sized + Copy
321{
322    /// All flags that are exclusive.
323    const EXCLUSIVE: Self;
324
325    /// The selector used by this resource.
326    type Selector: fmt::Debug;
327
328    /// Turn the resource into a pile of bits.
329    fn bits(self) -> u32;
330    /// Returns true if any of the uses are exclusive.
331    fn any_exclusive(self) -> bool;
332
333    /// Returns true if the given states violates the usage scope rule
334    /// of any(inclusive) XOR one(exclusive)
335    fn is_invalid(self) -> bool {
336        // If we're in any exclusive state, we must only be in a single state.
337        self.any_exclusive() && self.bits().count_ones() != 1
338    }
339}
340
341/// Returns true if the transition from one state to another does not require
342/// a barrier.
343fn skip_barrier<F: Flags>(old_state: F, ordered_uses_mask: F, new_state: F) -> bool {
344    // If the state didn't change and all the usages are ordered, the hardware
345    // will guarantee the order of accesses, so we do not need to issue a barrier at all
346    old_state.bits() == new_state.bits() && ordered_uses_mask.contains(old_state)
347}
348
349#[derive(Clone, Debug, Error)]
350pub enum ResourceUsageCompatibilityError {
351    #[error("Attempted to use {res} with {invalid_use}.")]
352    Buffer {
353        res: ResourceErrorIdent,
354        invalid_use: InvalidUse<wgt::BufferUses>,
355    },
356    #[error(
357        "Attempted to use {res} (mips {mip_levels:?} layers {array_layers:?}) with {invalid_use}."
358    )]
359    Texture {
360        res: ResourceErrorIdent,
361        mip_levels: ops::Range<u32>,
362        array_layers: ops::Range<u32>,
363        invalid_use: InvalidUse<wgt::TextureUses>,
364    },
365}
366
367impl WebGpuError for ResourceUsageCompatibilityError {
368    fn webgpu_error_type(&self) -> ErrorType {
369        ErrorType::Validation
370    }
371}
372
373impl ResourceUsageCompatibilityError {
374    fn from_buffer(
375        buffer: &resource::Buffer,
376        current_state: wgt::BufferUses,
377        new_state: wgt::BufferUses,
378    ) -> Self {
379        Self::Buffer {
380            res: buffer.error_ident(),
381            invalid_use: InvalidUse {
382                current_state,
383                new_state,
384            },
385        }
386    }
387
388    fn from_texture(
389        texture: &resource::Texture,
390        selector: wgt::TextureSelector,
391        current_state: wgt::TextureUses,
392        new_state: wgt::TextureUses,
393    ) -> Self {
394        Self::Texture {
395            res: texture.error_ident(),
396            mip_levels: selector.mips,
397            array_layers: selector.layers,
398            invalid_use: InvalidUse {
399                current_state,
400                new_state,
401            },
402        }
403    }
404}
405
406/// Pretty print helper that shows helpful descriptions of a conflicting usage.
407#[derive(Clone, Debug, Eq, PartialEq)]
408pub struct InvalidUse<T> {
409    current_state: T,
410    new_state: T,
411}
412
413impl<T: ResourceUses> fmt::Display for InvalidUse<T> {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        let current = self.current_state;
416        let new = self.new_state;
417
418        let current_exclusive = current & T::EXCLUSIVE;
419        let new_exclusive = new & T::EXCLUSIVE;
420
421        let exclusive = current_exclusive | new_exclusive;
422
423        // The text starts with "tried to use X resource with {self}"
424        write!(
425            f,
426            "conflicting usages. Current usage {current:?} and new usage {new:?}. \
427            {exclusive:?} is an exclusive usage and cannot be used with any other \
428            usages within the usage scope (renderpass or compute dispatch)"
429        )
430    }
431}
432
433/// All the usages that a bind group contains. The uses are not deduplicated in any way
434/// and may include conflicting uses. This is fully compliant by the WebGPU spec.
435///
436/// All bind group states are sorted by their ID so that when adding to a tracker,
437/// they are added in the most efficient order possible (ascending order).
438#[derive(Debug)]
439pub(crate) struct BindGroupStates {
440    pub buffers: BufferBindGroupState,
441    pub views: TextureViewBindGroupState,
442    pub external_textures: StatelessTracker<resource::ExternalTexture>,
443    pub samplers: StatelessTracker<resource::Sampler>,
444    pub acceleration_structures: StatelessTracker<resource::Tlas>,
445}
446
447impl BindGroupStates {
448    pub fn new() -> Self {
449        Self {
450            buffers: BufferBindGroupState::new(),
451            views: TextureViewBindGroupState::new(),
452            external_textures: StatelessTracker::new(),
453            samplers: StatelessTracker::new(),
454            acceleration_structures: StatelessTracker::new(),
455        }
456    }
457
458    /// Optimize the bind group states by sorting them by ID.
459    ///
460    /// When this list of states is merged into a tracker, the memory
461    /// accesses will be in a constant ascending order.
462    pub fn optimize(&mut self) {
463        self.buffers.optimize();
464        // Views are stateless, however, `TextureViewBindGroupState`
465        // is special as it will be merged with other texture trackers.
466        self.views.optimize();
467        // Samplers and Tlas's are stateless and don't need to be optimized
468        // since the tracker is never merged with any other tracker.
469    }
470}
471
472/// This is a render bundle specific usage scope. It includes stateless resources
473/// that are not normally included in a usage scope, but are used by render bundles
474/// and need to be owned by the render bundles.
475#[derive(Debug)]
476pub(crate) struct RenderBundleScope {
477    pub buffers: BufferUsageScope,
478    pub textures: TextureUsageScope,
479    // Don't need to track views and samplers, they are never used directly, only by bind groups.
480    pub bind_groups: StatelessTracker<binding_model::BindGroup>,
481    pub render_pipelines: StatelessTracker<pipeline::RenderPipeline>,
482}
483
484impl RenderBundleScope {
485    /// Create the render bundle scope and pull the maximum IDs from the hubs.
486    pub fn new() -> Self {
487        Self {
488            buffers: BufferUsageScope::default(),
489            textures: TextureUsageScope::default(),
490            bind_groups: StatelessTracker::new(),
491            render_pipelines: StatelessTracker::new(),
492        }
493    }
494
495    /// Merge the inner contents of a bind group into the render bundle tracker.
496    ///
497    /// Only stateful things are merged in herell other resources are owned
498    /// indirectly by the bind group.
499    ///
500    /// # Safety
501    ///
502    /// The maximum ID given by each bind group resource must be less than the
503    /// length of the storage given at the call to `new`.
504    pub unsafe fn merge_bind_group(
505        &mut self,
506        bind_group: &BindGroupStates,
507    ) -> Result<(), ResourceUsageCompatibilityError> {
508        unsafe { self.buffers.merge_bind_group(&bind_group.buffers)? };
509        unsafe { self.textures.merge_bind_group(&bind_group.views)? };
510
511        Ok(())
512    }
513}
514
515/// A pool for storing the memory used by [`UsageScope`]s. We take and store this memory when the
516/// scope is dropped to avoid reallocating. The memory required only grows and allocation cost is
517/// significant when a large number of resources have been used.
518pub(crate) type UsageScopePool = Mutex<Vec<(BufferUsageScope, TextureUsageScope)>>;
519
520/// A usage scope tracker. Only needs to store stateful resources as stateless
521/// resources cannot possibly have a usage conflict.
522#[derive(Debug)]
523pub(crate) struct UsageScope<'a> {
524    pub pool: &'a UsageScopePool,
525    pub buffers: BufferUsageScope,
526    pub textures: TextureUsageScope,
527}
528
529impl<'a> Drop for UsageScope<'a> {
530    fn drop(&mut self) {
531        // clear vecs and push into pool
532        self.buffers.clear();
533        self.textures.clear();
534        self.pool
535            .lock()
536            .push((mem::take(&mut self.buffers), mem::take(&mut self.textures)));
537    }
538}
539
540impl UsageScope<'static> {
541    pub fn new_pooled<'d>(
542        pool: &'d UsageScopePool,
543        tracker_indices: &TrackerIndexAllocators,
544        ordered_buffer_usages: wgt::BufferUses,
545        ordered_texture_usages: wgt::TextureUses,
546    ) -> UsageScope<'d> {
547        let pooled = pool.lock().pop().unwrap_or_default();
548
549        let mut scope = UsageScope::<'d> {
550            pool,
551            buffers: pooled.0,
552            textures: pooled.1,
553        };
554
555        scope.buffers.set_size(tracker_indices.buffers.size());
556        scope.buffers.set_ordered_uses_mask(ordered_buffer_usages);
557        scope.textures.set_size(tracker_indices.textures.size());
558        scope.textures.set_ordered_uses_mask(ordered_texture_usages);
559        scope
560    }
561}
562
563impl<'a> UsageScope<'a> {
564    /// Merge the inner contents of a bind group into the usage scope.
565    ///
566    /// Only stateful things are merged in herell other resources are owned
567    /// indirectly by the bind group.
568    ///
569    /// # Safety
570    ///
571    /// The maximum ID given by each bind group resource must be less than the
572    /// length of the storage given at the call to `new`.
573    pub unsafe fn merge_bind_group(
574        &mut self,
575        bind_group: &BindGroupStates,
576    ) -> Result<(), ResourceUsageCompatibilityError> {
577        unsafe {
578            self.buffers.merge_bind_group(&bind_group.buffers)?;
579            self.textures.merge_bind_group(&bind_group.views)?;
580        }
581
582        Ok(())
583    }
584
585    /// Merge the inner contents of a bind group into the usage scope.
586    ///
587    /// Only stateful things are merged in herell other resources are owned
588    /// indirectly by a bind group or are merged directly into the command buffer tracker.
589    ///
590    /// # Safety
591    ///
592    /// The maximum ID given by each bind group resource must be less than the
593    /// length of the storage given at the call to `new`.
594    pub unsafe fn merge_render_bundle(
595        &mut self,
596        render_bundle: &RenderBundleScope,
597    ) -> Result<(), ResourceUsageCompatibilityError> {
598        self.buffers.merge_usage_scope(&render_bundle.buffers)?;
599        self.textures.merge_usage_scope(&render_bundle.textures)?;
600
601        Ok(())
602    }
603}
604
605/// A tracker used by Device.
606pub(crate) struct DeviceTracker {
607    pub buffers: DeviceBufferTracker,
608    pub textures: DeviceTextureTracker,
609}
610
611impl DeviceTracker {
612    pub fn new(
613        ordered_buffer_usages: wgt::BufferUses,
614        ordered_texture_usages: wgt::TextureUses,
615    ) -> Self {
616        Self {
617            buffers: DeviceBufferTracker::new(ordered_buffer_usages),
618            textures: DeviceTextureTracker::new(ordered_texture_usages),
619        }
620    }
621}
622
623/// A full double sided tracker used by CommandBuffers.
624pub(crate) struct Tracker {
625    /// Buffers used within this command buffer.
626    ///
627    /// For compute passes, this only includes buffers actually used by the
628    /// pipeline (contrast with the `bind_groups` member).
629    pub buffers: BufferTracker,
630
631    /// Textures used within this command buffer.
632    ///
633    /// For compute passes, this only includes textures actually used by the
634    /// pipeline (contrast with the `bind_groups` member).
635    pub textures: TextureTracker,
636
637    pub blas_s: BlasTracker,
638    pub tlas_s: StatelessTracker<resource::Tlas>,
639    pub views: StatelessTracker<resource::TextureView>,
640
641    /// Contains all bind groups that were passed in any call to
642    /// `set_bind_group` on the encoder.
643    ///
644    /// WebGPU requires that submission fails if any resource in any of these
645    /// bind groups is destroyed, even if the resource is not actually used by
646    /// the pipeline (e.g. because the pipeline does not use the bound slot, or
647    /// because the bind group was replaced by a subsequent call to
648    /// `set_bind_group`).
649    pub bind_groups: StatelessTracker<binding_model::BindGroup>,
650
651    pub compute_pipelines: StatelessTracker<pipeline::ComputePipeline>,
652    pub render_pipelines: StatelessTracker<pipeline::RenderPipeline>,
653    pub ray_tracing_pipelines: StatelessTracker<ray_tracing_pipeline::RayTracingPipeline>,
654    pub bundles: StatelessTracker<command::RenderBundle>,
655    pub query_sets: QuerySetTracker,
656}
657
658impl Tracker {
659    pub fn new(
660        ordered_buffer_usages: wgt::BufferUses,
661        ordered_texture_usages: wgt::TextureUses,
662    ) -> Self {
663        Self {
664            buffers: BufferTracker::new(ordered_buffer_usages),
665            textures: TextureTracker::new(ordered_texture_usages),
666            blas_s: BlasTracker::new(),
667            tlas_s: StatelessTracker::new(),
668            views: StatelessTracker::new(),
669            bind_groups: StatelessTracker::new(),
670            compute_pipelines: StatelessTracker::new(),
671            render_pipelines: StatelessTracker::new(),
672            ray_tracing_pipelines: StatelessTracker::new(),
673            bundles: StatelessTracker::new(),
674            query_sets: QuerySetTracker::new(),
675        }
676    }
677
678    /// Iterates through all resources in the given bind group and adopts
679    /// the state given for those resources in the UsageScope. It also
680    /// removes all touched resources from the usage scope.
681    ///
682    /// If a transition is needed to get the resources into the needed
683    /// state, those transitions are stored within the tracker. A
684    /// subsequent call to [`BufferTracker::drain_transitions`] or
685    /// [`TextureTracker::drain_transitions`] is needed to get those transitions.
686    ///
687    /// This is a really funky method used by Compute Passes to generate
688    /// barriers after a call to dispatch without needing to iterate
689    /// over all elements in the usage scope. We use each the
690    /// bind group as a source of which IDs to look at. The bind groups
691    /// must have first been added to the usage scope.
692    ///
693    /// Only stateful things are merged in here, all other resources are owned
694    /// indirectly by the bind group.
695    ///
696    /// # Panics
697    ///
698    /// If a resource in the `bind_group` is not found in the usage scope.
699    pub fn set_and_remove_from_usage_scope_sparse(
700        &mut self,
701        scope: &mut UsageScope,
702        bind_group: &BindGroupStates,
703    ) {
704        self.buffers.set_and_remove_from_usage_scope_sparse(
705            &mut scope.buffers,
706            bind_group
707                .buffers
708                .used_resources()
709                .map(|b| b.tracker_index()),
710        );
711        self.textures
712            .set_and_remove_from_usage_scope_sparse(&mut scope.textures, &bind_group.views);
713    }
714}