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