| author | |
| committer | |
| log | 181d489f7ee6df2510df91aab084020aeccbf112 |
| tree | 13289de00752c9ba41b11e501057984f9b2ec627 |
| parent | a410bb327c81f2970d3c7e9fa129158d7984c289 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
4 files changed, 427 insertions(+), 98 deletions(-)
crates/engine/src/cache.rs+77-24| ... | ... | @@ -5,6 +5,7 @@ |
| 5 | 5 | use crate::profile::{FrameProfile, ProfileRecorder}; |
| 6 | 6 | use model::{BitDepth, Comp, NodeId}; |
| 7 | 7 | use std::collections::{HashMap, VecDeque}; |
| 8 | use std::sync::atomic::{AtomicU64, Ordering}; | |
| 8 | 9 | use std::sync::{Arc, Mutex}; |
| 9 | 10 | |
| 10 | 11 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| ... | ... | @@ -456,6 +457,9 @@ pub struct NodeCache { |
| 456 | 457 | total_bytes: u64, |
| 457 | 458 | tick: u64, |
| 458 | 459 | evictions: u64, |
| 460 | /// Monotonic counter incremented whenever a texture is dropped without being pooled | |
| 461 | /// or evicted from `TexturePool`, used to invalidate `BindGroup` caches before they pin VRAM. | |
| 462 | vram_drops: AtomicU64, | |
| 459 | 463 | /// Monotonic salt bumped when busting GPU cache globally. |
| 460 | 464 | pub gpu_salt: u64, |
| 461 | 465 | /// Per-node salt bumped when surgically busting a subtree. |
| ... | ... | @@ -479,6 +483,7 @@ impl NodeCache { |
| 479 | 483 | total_bytes: 0, |
| 480 | 484 | tick: 0, |
| 481 | 485 | evictions: 0, |
| 486 | vram_drops: AtomicU64::new(0), | |
| 482 | 487 | gpu_salt: 0, |
| 483 | 488 | node_salts: HashMap::new(), |
| 484 | 489 | pool: Mutex::new(TexturePool::new()), |
| ... | ... | @@ -512,6 +517,10 @@ impl NodeCache { |
| 512 | 517 | self.evictions |
| 513 | 518 | } |
| 514 | 519 | |
| 520 | pub fn vram_drops(&self) -> u64 { | |
| 521 | self.vram_drops.load(Ordering::Relaxed) | |
| 522 | } | |
| 523 | ||
| 515 | 524 | pub fn node_salt(&self, id: NodeId) -> u64 { |
| 516 | 525 | self.node_salts.get(&id).copied().unwrap_or(0) |
| 517 | 526 | } |
| ... | ... | @@ -583,16 +592,7 @@ impl NodeCache { |
| 583 | 592 | } |
| 584 | 593 | pool.misses += 1; |
| 585 | 594 | // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget. |
| 586 | while self | |
| 587 | .total_bytes | |
| 588 | .saturating_add(pool.total_bytes) | |
| 589 | .saturating_add(bytes) | |
| 590 | > self.budget_bytes | |
| 591 | { | |
| 592 | if !pool.evict_oldest() { | |
| 593 | break; | |
| 594 | } | |
| 595 | } | |
| 595 | self.trim_pool_locked(&mut pool, bytes); | |
| 596 | 596 | } |
| 597 | 597 | |
| 598 | 598 | let texture = device.create_texture(&wgpu::TextureDescriptor { |
| ... | ... | @@ -741,6 +741,9 @@ impl NodeCache { |
| 741 | 741 | |
| 742 | 742 | fn defer_to_pool(&mut self, tex: CachedTexture) { |
| 743 | 743 | if tex.bytes == 0 || tex.bytes > self.budget_bytes { |
| 744 | if tex.bytes > 0 { | |
| 745 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 746 | } | |
| 744 | 747 | return; |
| 745 | 748 | } |
| 746 | 749 | let mut pending_bytes: u64 = self.pending_pool.iter().map(|t| t.bytes).sum(); |
| ... | ... | @@ -764,6 +767,7 @@ impl NodeCache { |
| 764 | 767 | } |
| 765 | 768 | pending_bytes = pending_bytes.saturating_sub(dropped.bytes); |
| 766 | 769 | self.pending_pool.pop_front(); |
| 770 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 767 | 771 | } |
| 768 | 772 | if self |
| 769 | 773 | .total_bytes |
| ... | ... | @@ -772,6 +776,8 @@ impl NodeCache { |
| 772 | 776 | <= self.budget_bytes |
| 773 | 777 | { |
| 774 | 778 | self.pending_pool.push_back(tex); |
| 779 | } else { | |
| 780 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 775 | 781 | } |
| 776 | 782 | } |
| 777 | 783 | } |
| ... | ... | @@ -795,26 +801,35 @@ impl NodeCache { |
| 795 | 801 | } |
| 796 | 802 | } |
| 797 | 803 | |
| 804 | fn trim_pool_locked(&self, pool: &mut TexturePool, reserve_bytes: u64) { | |
| 805 | while self | |
| 806 | .total_bytes | |
| 807 | .saturating_add(pool.total_bytes) | |
| 808 | .saturating_add(reserve_bytes) | |
| 809 | > self.budget_bytes | |
| 810 | { | |
| 811 | if !pool.evict_oldest() { | |
| 812 | break; | |
| 813 | } | |
| 814 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 815 | } | |
| 816 | } | |
| 817 | ||
| 798 | 818 | fn return_to_pool(&self, tex: &CachedTexture) { |
| 799 | 819 | if tex.bytes == 0 || tex.bytes > self.budget_bytes { |
| 820 | if tex.bytes > 0 { | |
| 821 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 822 | } | |
| 800 | 823 | return; |
| 801 | 824 | } |
| 802 | 825 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| 803 | 826 | pool.push(tex); |
| 804 | while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { | |
| 805 | if !pool.evict_oldest() { | |
| 806 | break; | |
| 807 | } | |
| 808 | } | |
| 827 | self.trim_pool_locked(&mut pool, 0); | |
| 809 | 828 | } |
| 810 | 829 | |
| 811 | 830 | fn trim_pool_to_budget(&self) { |
| 812 | 831 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| 813 | while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { | |
| 814 | if !pool.evict_oldest() { | |
| 815 | break; | |
| 816 | } | |
| 817 | } | |
| 832 | self.trim_pool_locked(&mut pool, 0); | |
| 818 | 833 | } |
| 819 | 834 | |
| 820 | 835 | fn evict_over_budget(&mut self) { |
| ... | ... | @@ -868,22 +883,31 @@ impl NodeCache { |
| 868 | 883 | for tex in recycle_scratch { |
| 869 | 884 | if tex.bytes > 0 && tex.bytes <= self.budget_bytes { |
| 870 | 885 | pool.push(&tex); |
| 886 | } else if tex.bytes > 0 { | |
| 887 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 871 | 888 | } |
| 872 | 889 | } |
| 873 | 890 | for tex in pending { |
| 874 | 891 | if tex.bytes > 0 && tex.bytes <= self.budget_bytes { |
| 875 | 892 | pool.push(&tex); |
| 893 | } else if tex.bytes > 0 { | |
| 894 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 876 | 895 | } |
| 877 | 896 | } |
| 878 | 897 | for entry in drained { |
| 879 | 898 | if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes { |
| 880 | 899 | pool.push(&entry.tex); |
| 900 | } else if entry.tex.bytes > 0 { | |
| 901 | self.vram_drops.fetch_add(1, Ordering::Relaxed); | |
| 881 | 902 | } |
| 882 | 903 | } |
| 883 | while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { | |
| 884 | if !pool.evict_oldest() { | |
| 885 | break; | |
| 886 | } | |
| 904 | self.trim_pool_locked(&mut pool, 0); | |
| 905 | } else { | |
| 906 | let dropped = drained.iter().filter(|e| e.tex.bytes > 0).count() | |
| 907 | + pending.iter().filter(|t| t.bytes > 0).count() | |
| 908 | + recycle_scratch.iter().filter(|t| t.bytes > 0).count(); | |
| 909 | if dropped > 0 { | |
| 910 | self.vram_drops.fetch_add(dropped as u64, Ordering::Relaxed); | |
| 887 | 911 | } |
| 888 | 912 | } |
| 889 | 913 | count |
| ... | ... | @@ -1235,4 +1259,33 @@ mod tests { |
| 1235 | 1259 | assert_eq!(Arc::as_ptr(&reused.texture), ptr); |
| 1236 | 1260 | assert_eq!(cache.pool_stats().hits, 1); |
| 1237 | 1261 | } |
| 1262 | ||
| 1263 | #[test] | |
| 1264 | fn vram_drops_increments_on_eviction_overflow_and_pool_trim() { | |
| 1265 | let eng = Engine::new_headless().expect("gpu"); | |
| 1266 | let device = eng.device(); | |
| 1267 | let usage = NodeCache::default_texture_usage(); | |
| 1268 | // 4 MiB budget: each 512x512 RGBA8 is 1 MiB. | |
| 1269 | let mut cache = NodeCache::new(4); | |
| 1270 | assert_eq!(cache.vram_drops(), 0); | |
| 1271 | ||
| 1272 | // Insert 5 entries -> 1 is evicted to pending_pool; flushing exceeds 4 MiB and drops it. | |
| 1273 | for i in 0..5u64 { | |
| 1274 | let t = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); | |
| 1275 | cache.insert(i, t, NodeId(i as usize), 0); | |
| 1276 | } | |
| 1277 | cache.flush_pending_pool(); | |
| 1278 | let after_overflow = cache.vram_drops(); | |
| 1279 | assert!(after_overflow >= 1, "expected vram_drops >= 1 after overflow, got {after_overflow}"); | |
| 1280 | ||
| 1281 | // Lowering budget below live bytes evicts & drops entries monotonically. | |
| 1282 | cache.set_budget_mb(1); | |
| 1283 | assert!(cache.vram_drops() > after_overflow); | |
| 1284 | ||
| 1285 | // Busting with 0 budget drops all remaining entries. | |
| 1286 | let before_bust = cache.vram_drops(); | |
| 1287 | cache.set_budget_mb(0); | |
| 1288 | cache.bust_all(); | |
| 1289 | assert!(cache.vram_drops() > before_bust); | |
| 1290 | } | |
| 1238 | 1291 | } |
crates/engine/src/eval/dispatch.rs+132-35| ... | ... | @@ -36,6 +36,8 @@ pub struct PendingReadback { |
| 36 | 36 | #[cfg(not(target_arch = "wasm32"))] |
| 37 | 37 | buf: wgpu::Buffer, |
| 38 | 38 | #[cfg(not(target_arch = "wasm32"))] |
| 39 | submission_index: wgpu::SubmissionIndex, | |
| 40 | #[cfg(not(target_arch = "wasm32"))] | |
| 39 | 41 | rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>, |
| 40 | 42 | #[cfg(not(target_arch = "wasm32"))] |
| 41 | 43 | width: u32, |
| ... | ... | @@ -60,15 +62,18 @@ impl PendingReadback { |
| 60 | 62 | } |
| 61 | 63 | #[cfg(not(target_arch = "wasm32"))] |
| 62 | 64 | { |
| 65 | // Poll non-blockingly first so already-completed readbacks fire immediately. | |
| 66 | let _ = engine.device.poll(wgpu::PollType::Poll); | |
| 63 | 67 | let map_res = match self.rx.try_recv() { |
| 64 | 68 | Ok(res) => res, |
| 65 | Err(_) => { | |
| 69 | Err(std::sync::mpsc::TryRecvError::Empty) => { | |
| 66 | 70 | engine.device.poll(wgpu::PollType::Wait { |
| 67 | submission_index: None, | |
| 71 | submission_index: Some(self.submission_index), | |
| 68 | 72 | timeout: Some(std::time::Duration::from_secs(10)), |
| 69 | 73 | })?; |
| 70 | 74 | self.rx.recv()? |
| 71 | 75 | } |
| 76 | Err(err @ std::sync::mpsc::TryRecvError::Disconnected) => return Err(err.into()), | |
| 72 | 77 | }; |
| 73 | 78 | map_res?; |
| 74 | 79 | let slice = self.buf.slice(..self.required_bytes); |
| ... | ... | @@ -98,6 +103,16 @@ impl Engine { |
| 98 | 103 | self.pipelines.borrow_mut().prewarm_core(&self.device); |
| 99 | 104 | } |
| 100 | 105 | |
| 106 | /// Pre-compiles core WGSL shader modules and compute pipelines for `Int8` (viewer/readback) | |
| 107 | /// and `depth` when `hiq` is active (e.g. `BitDepth::Float16` for EXR/HiQ comps). | |
| 108 | pub fn prewarm_for_depth(&self, depth: BitDepth) { | |
| 109 | self.pipelines.borrow_mut().prewarm_core(&self.device); | |
| 110 | let eff = self.effective_depth(depth); | |
| 111 | if eff != BitDepth::Int8 { | |
| 112 | self.pipelines_for(eff).borrow_mut().prewarm_core(&self.device); | |
| 113 | } | |
| 114 | } | |
| 115 | ||
| 101 | 116 | pub(super) fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture { |
| 102 | 117 | self.alloc_tex_dod(size, [0, 0], size, depth, content_hash) |
| 103 | 118 | } |
| ... | ... | @@ -239,7 +254,7 @@ impl Engine { |
| 239 | 254 | ]; |
| 240 | 255 | params.p[1] = display.uv_rect; |
| 241 | 256 | params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; |
| 242 | self.dispatch_to_view( | |
| 257 | self.dispatch_to_view_uncached( | |
| 243 | 258 | &mut encoder, |
| 244 | 259 | ShaderOp::DisplayBlit, |
| 245 | 260 | &src.view, |
| ... | ... | @@ -250,6 +265,7 @@ impl Engine { |
| 250 | 265 | &params, |
| 251 | 266 | ); |
| 252 | 267 | self.queue.submit(Some(encoder.finish())); |
| 268 | self.reset_uniform_cursors(); | |
| 253 | 269 | |
| 254 | 270 | EvalStats { |
| 255 | 271 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| ... | ... | @@ -276,30 +292,31 @@ impl Engine { |
| 276 | 292 | } |
| 277 | 293 | #[cfg(not(target_arch = "wasm32"))] |
| 278 | 294 | { |
| 279 | let [w, h] = tex.size; | |
| 295 | let needs_conv = tex.format != wgpu::TextureFormat::Rgba8Unorm; | |
| 296 | let converted = if needs_conv { | |
| 297 | let mut reg = self.pipelines.borrow_mut(); | |
| 298 | Some(reg.readback_pool.acquire_conv_tex(&self.device, tex.size)) | |
| 299 | } else { | |
| 300 | None | |
| 301 | }; | |
| 302 | let src_tex = converted.as_ref().unwrap_or(tex); | |
| 303 | let [w, h] = src_tex.size; | |
| 280 | 304 | let bpp = 4u32; |
| 281 | 305 | let unpadded_bpr = w * bpp; |
| 282 | 306 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 283 | 307 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 284 | 308 | let required_bytes = u64::from(padded_bpr) * u64::from(h); |
| 285 | let needs_conv = tex.format != wgpu::TextureFormat::Rgba8Unorm; | |
| 286 | ||
| 287 | let (buf, converted) = { | |
| 288 | let mut reg = self.pipelines.borrow_mut(); | |
| 289 | let buf = reg.readback_pool.acquire_buffer(&self.device, required_bytes); | |
| 290 | let conv = if needs_conv { | |
| 291 | Some(reg.readback_pool.acquire_conv_tex(&self.device, tex.size)) | |
| 292 | } else { | |
| 293 | None | |
| 294 | }; | |
| 295 | (buf, conv) | |
| 296 | }; | |
| 309 | let buf = self | |
| 310 | .pipelines | |
| 311 | .borrow_mut() | |
| 312 | .readback_pool | |
| 313 | .acquire_buffer(&self.device, required_bytes); | |
| 297 | 314 | |
| 298 | 315 | let mut enc = self.device.create_command_encoder(&Default::default()); |
| 299 | let src_tex = if let Some(conv) = converted.as_ref() { | |
| 316 | if let Some(conv) = converted.as_ref() { | |
| 300 | 317 | let mut params = UniformParams::default(); |
| 301 | 318 | params.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| 302 | self.dispatch_to_view( | |
| 319 | self.dispatch_to_view_uncached( | |
| 303 | 320 | &mut enc, |
| 304 | 321 | ShaderOp::DisplayBlit, |
| 305 | 322 | &tex.view, |
| ... | ... | @@ -309,10 +326,7 @@ impl Engine { |
| 309 | 326 | conv.size, |
| 310 | 327 | &params, |
| 311 | 328 | ); |
| 312 | conv | |
| 313 | } else { | |
| 314 | tex | |
| 315 | }; | |
| 329 | } | |
| 316 | 330 | enc.copy_texture_to_buffer( |
| 317 | 331 | src_tex.texture.as_image_copy(), |
| 318 | 332 | wgpu::TexelCopyBufferInfo { |
| ... | ... | @@ -325,7 +339,8 @@ impl Engine { |
| 325 | 339 | }, |
| 326 | 340 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 327 | 341 | ); |
| 328 | self.queue.submit(Some(enc.finish())); | |
| 342 | let submission_index = self.queue.submit(Some(enc.finish())); | |
| 343 | self.reset_uniform_cursors(); | |
| 329 | 344 | |
| 330 | 345 | let slice = buf.slice(..required_bytes); |
| 331 | 346 | let (tx, rx) = std::sync::mpsc::channel(); |
| ... | ... | @@ -334,6 +349,7 @@ impl Engine { |
| 334 | 349 | }); |
| 335 | 350 | Ok(PendingReadback { |
| 336 | 351 | buf, |
| 352 | submission_index, | |
| 337 | 353 | rx, |
| 338 | 354 | width: w, |
| 339 | 355 | height: h, |
| ... | ... | @@ -363,23 +379,40 @@ impl Engine { |
| 363 | 379 | dst_view: &wgpu::TextureView, |
| 364 | 380 | dst_size: [u32; 2], |
| 365 | 381 | params: &UniformParams, |
| 382 | cache_bg: bool, | |
| 366 | 383 | ) { |
| 367 | let (dynamic_offset, bg_hash, bg_idx) = { | |
| 384 | let (dynamic_offset, uncached_bg, cached_key) = { | |
| 368 | 385 | let mut reg = reg_cell.borrow_mut(); |
| 369 | 386 | reg.ensure_pipeline(&self.device, op); |
| 370 | 387 | let (chunk_idx, dynamic_offset) = reg.alloc_uniform_slot(&self.device, &self.queue, params); |
| 371 | let (bg_hash, bg_idx) = reg.ensure_bind_group( | |
| 372 | &self.device, | |
| 373 | src_a, | |
| 374 | src_b, | |
| 375 | mask, | |
| 376 | dst_view, | |
| 377 | chunk_idx, | |
| 378 | ); | |
| 379 | (dynamic_offset, bg_hash, bg_idx) | |
| 388 | if cache_bg { | |
| 389 | let (bg_hash, bg_idx) = reg.ensure_bind_group( | |
| 390 | &self.device, | |
| 391 | src_a, | |
| 392 | src_b, | |
| 393 | mask, | |
| 394 | dst_view, | |
| 395 | chunk_idx, | |
| 396 | ); | |
| 397 | (dynamic_offset, None, Some((bg_hash, bg_idx))) | |
| 398 | } else { | |
| 399 | let bg = reg.create_bind_group( | |
| 400 | &self.device, | |
| 401 | src_a, | |
| 402 | src_b, | |
| 403 | mask, | |
| 404 | dst_view, | |
| 405 | chunk_idx, | |
| 406 | ); | |
| 407 | (dynamic_offset, Some(bg), None) | |
| 408 | } | |
| 380 | 409 | }; |
| 381 | 410 | let reg = reg_cell.borrow(); |
| 382 | let bg = reg.get_bind_group(bg_hash, bg_idx); | |
| 411 | let bg = match (&uncached_bg, cached_key) { | |
| 412 | (Some(bg), _) => bg, | |
| 413 | (None, Some((bg_hash, bg_idx))) => reg.get_bind_group(bg_hash, bg_idx), | |
| 414 | (None, None) => unreachable!(), | |
| 415 | }; | |
| 383 | 416 | |
| 384 | 417 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 385 | 418 | label: Some("comp-op"), |
| ... | ... | @@ -412,11 +445,14 @@ impl Engine { |
| 412 | 445 | &dst.view, |
| 413 | 446 | dst.size, |
| 414 | 447 | params, |
| 448 | true, | |
| 415 | 449 | ); |
| 416 | 450 | } |
| 417 | 451 | |
| 452 | /// Dispatches a compute shader into an ephemeral `TextureView` (e.g. viewer surface or | |
| 453 | /// one-shot readback conversion) without inserting into `bg_cache`. | |
| 418 | 454 | #[allow(clippy::too_many_arguments)] |
| 419 | pub(super) fn dispatch_to_view( | |
| 455 | pub(super) fn dispatch_to_view_uncached( | |
| 420 | 456 | &self, |
| 421 | 457 | enc: &mut wgpu::CommandEncoder, |
| 422 | 458 | op: ShaderOp, |
| ... | ... | @@ -437,6 +473,7 @@ impl Engine { |
| 437 | 473 | dst_view, |
| 438 | 474 | dst_size, |
| 439 | 475 | params, |
| 476 | false, | |
| 440 | 477 | ); |
| 441 | 478 | } |
| 442 | 479 | } |
| ... | ... | @@ -719,4 +756,64 @@ mod tests { |
| 719 | 756 | eng.pipelines.borrow_mut().clear_bind_group_cache(); |
| 720 | 757 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); |
| 721 | 758 | } |
| 759 | ||
| 760 | #[test] | |
| 761 | fn pending_readback_tracks_submission_index_and_bypasses_bg_cache() { | |
| 762 | let Ok(eng) = Engine::new_headless() else { | |
| 763 | return; | |
| 764 | }; | |
| 765 | let fill = |tex: &CachedTexture, rgba: [f32; 4]| { | |
| 766 | let mut enc = eng.device.create_command_encoder(&Default::default()); | |
| 767 | let mut u = UniformParams::default(); | |
| 768 | u.p[0] = rgba; | |
| 769 | u.p[1] = rgba; | |
| 770 | u.p[2] = rgba; | |
| 771 | u.p[3] = rgba; | |
| 772 | eng.dispatch_op( | |
| 773 | &mut enc, | |
| 774 | ShaderOp::Bg, | |
| 775 | &eng.dummy.view, | |
| 776 | &eng.dummy.view, | |
| 777 | &eng.dummy.view, | |
| 778 | tex, | |
| 779 | &u, | |
| 780 | ); | |
| 781 | eng.queue.submit(Some(enc.finish())); | |
| 782 | eng.reset_uniform_cursors(); | |
| 783 | }; | |
| 784 | ||
| 785 | let f16_a = eng.alloc_tex([16, 16], BitDepth::Float16, 0); | |
| 786 | let f16_b = eng.alloc_tex([16, 16], BitDepth::Float16, 0); | |
| 787 | fill(&f16_a, [0.2, 0.4, 0.8, 1.0]); | |
| 788 | fill(&f16_b, [0.9, 0.1, 0.5, 1.0]); | |
| 789 | ||
| 790 | eng.pipelines.borrow_mut().clear_bind_group_cache(); | |
| 791 | let misses_before = eng.pipelines.borrow().bg_misses; | |
| 792 | ||
| 793 | // Overlapping double-buffered readbacks: finish out of order (b then a) via SubmissionIndex. | |
| 794 | let pend_a = eng.begin_readback_rgba(&f16_a).expect("begin a"); | |
| 795 | let pend_b = eng.begin_readback_rgba(&f16_b).expect("begin b"); | |
| 796 | assert_ne!( | |
| 797 | format!("{:?}", pend_a.submission_index), | |
| 798 | format!("{:?}", pend_b.submission_index) | |
| 799 | ); | |
| 800 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); | |
| 801 | assert_eq!(eng.pipelines.borrow().bg_misses, misses_before); | |
| 802 | ||
| 803 | let px_b = pend_b.finish(&eng).expect("finish b"); | |
| 804 | let px_a = pend_a.finish(&eng).expect("finish a"); | |
| 805 | assert!((px_a[0] as i32 - 51).abs() <= 2); | |
| 806 | assert!((px_b[0] as i32 - 230).abs() <= 2); | |
| 807 | ||
| 808 | // render_ram_frame_into_viewer must also bypass bg_cache and reset uniform cursors. | |
| 809 | let dst = eng.alloc_tex([16, 16], BitDepth::Int8, 0); | |
| 810 | let ram_frame = crate::ram_cache::RamFrame { | |
| 811 | size: [16, 16], | |
| 812 | rgba: std::sync::Arc::new(vec![128u8; 16 * 16 * 4]), | |
| 813 | eval_ms: 0.0, | |
| 814 | }; | |
| 815 | let _ = eng.render_ram_frame_into_viewer(&ram_frame, &dst.texture, DisplaySettings::default()); | |
| 816 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); | |
| 817 | assert_eq!(eng.pipelines.borrow().bg_misses, misses_before); | |
| 818 | } | |
| 722 | 819 | } |
crates/engine/src/eval/mod.rs+128-10| ... | ... | @@ -4,7 +4,7 @@ |
| 4 | 4 | use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; |
| 5 | 5 | use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; |
| 6 | 6 | use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port}; |
| 7 | use std::cell::{OnceCell, RefCell}; | |
| 7 | use std::cell::{Cell, OnceCell, RefCell}; | |
| 8 | 8 | use std::collections::{HashMap, HashSet}; |
| 9 | 9 | use std::collections::hash_map::DefaultHasher; |
| 10 | 10 | use std::hash::{Hash, Hasher}; |
| ... | ... | @@ -76,9 +76,12 @@ pub struct Engine { |
| 76 | 76 | ram_upload_tex: RefCell<Option<CachedTexture>>, |
| 77 | 77 | dummy: CachedTexture, |
| 78 | 78 | vram_budget_bytes: u64, |
| 79 | last_bg_vram_drops: Cell<u64>, | |
| 79 | 80 | pub cache: NodeCache, |
| 80 | 81 | pub media: MediaCache, |
| 81 | 82 | pub expr: ExprEngine, |
| 83 | /// Active evaluation target node (set during `evaluate` / `render_into_viewer`). | |
| 84 | pub(super) frame_eval_target: Option<NodeId>, | |
| 82 | 85 | /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. |
| 83 | 86 | frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, |
| 84 | 87 | /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current comp revision. |
| ... | ... | @@ -135,9 +138,11 @@ impl Engine { |
| 135 | 138 | ram_upload_tex: RefCell::new(None), |
| 136 | 139 | dummy, |
| 137 | 140 | vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024), |
| 141 | last_bg_vram_drops: Cell::new(0), | |
| 138 | 142 | cache: NodeCache::new(default_vram_mb), |
| 139 | media: MediaCache::new(512), | |
| 143 | media: MediaCache::default(), | |
| 140 | 144 | expr: ExprEngine::new(), |
| 145 | frame_eval_target: None, | |
| 141 | 146 | frame_memo: HashMap::new(), |
| 142 | 147 | frame_consumers: Vec::new(), |
| 143 | 148 | frame_consumers_rev: None, |
| ... | ... | @@ -240,16 +245,36 @@ impl Engine { |
| 240 | 245 | self.media.set_budget_mb(budget_mb); |
| 241 | 246 | } |
| 242 | 247 | |
| 243 | fn clear_bind_group_caches(&self) { | |
| 244 | self.pipelines.borrow_mut().clear_bind_group_cache(); | |
| 248 | fn for_each_registry(&self, mut f: impl FnMut(&mut ShaderRegistry)) { | |
| 249 | f(&mut self.pipelines.borrow_mut()); | |
| 245 | 250 | if let Some(r) = self.pipelines_int16.get() { |
| 246 | r.borrow_mut().clear_bind_group_cache(); | |
| 251 | f(&mut r.borrow_mut()); | |
| 247 | 252 | } |
| 248 | 253 | if let Some(r) = self.pipelines_f16.get() { |
| 249 | r.borrow_mut().clear_bind_group_cache(); | |
| 254 | f(&mut r.borrow_mut()); | |
| 250 | 255 | } |
| 251 | 256 | if let Some(r) = self.pipelines_f32.get() { |
| 252 | r.borrow_mut().clear_bind_group_cache(); | |
| 257 | f(&mut r.borrow_mut()); | |
| 258 | } | |
| 259 | } | |
| 260 | ||
| 261 | fn clear_bind_group_caches(&self) { | |
| 262 | self.for_each_registry(|r| r.clear_bind_group_cache()); | |
| 263 | self.last_bg_vram_drops.set(self.cache.vram_drops()); | |
| 264 | } | |
| 265 | ||
| 266 | pub(super) fn reset_uniform_cursors(&self) { | |
| 267 | self.for_each_registry(|r| r.reset_uniform_cursor()); | |
| 268 | } | |
| 269 | ||
| 270 | fn trim_uniform_chunks(&self) { | |
| 271 | self.for_each_registry(|r| r.trim_uniform_chunks(2)); | |
| 272 | } | |
| 273 | ||
| 274 | pub(super) fn sync_bg_cache_with_vram_drops(&self) { | |
| 275 | let drops = self.cache.vram_drops(); | |
| 276 | if drops != self.last_bg_vram_drops.get() { | |
| 277 | self.clear_bind_group_caches(); | |
| 253 | 278 | } |
| 254 | 279 | } |
| 255 | 280 | |
| ... | ... | @@ -258,6 +283,9 @@ impl Engine { |
| 258 | 283 | self.sync_node_cache_budget(); |
| 259 | 284 | self.cache.bust_all(); |
| 260 | 285 | self.clear_bind_group_caches(); |
| 286 | self.trim_uniform_chunks(); | |
| 287 | #[cfg(not(target_arch = "wasm32"))] | |
| 288 | self.pipelines.borrow_mut().readback_pool.clear(); | |
| 261 | 289 | self.media.clear(); |
| 262 | 290 | self.particles.clear(); |
| 263 | 291 | self.sprite_cache.clear(); |
| ... | ... | @@ -273,6 +301,9 @@ impl Engine { |
| 273 | 301 | self.sync_node_cache_budget(); |
| 274 | 302 | self.cache.bust_all(); |
| 275 | 303 | self.clear_bind_group_caches(); |
| 304 | self.trim_uniform_chunks(); | |
| 305 | #[cfg(not(target_arch = "wasm32"))] | |
| 306 | self.pipelines.borrow_mut().readback_pool.clear(); | |
| 276 | 307 | self.sprite_cache.clear(); |
| 277 | 308 | self.scene3d.clear_shadow_targets(); |
| 278 | 309 | *self.ram_upload_tex.borrow_mut() = None; |
| ... | ... | @@ -281,18 +312,21 @@ impl Engine { |
| 281 | 312 | pub fn bust_frame(&mut self, frame: i64) -> usize { |
| 282 | 313 | self.output_cache.clear(); |
| 283 | 314 | self.sync_node_cache_budget(); |
| 315 | let busted = self.cache.bust_frame(frame); | |
| 284 | 316 | self.clear_bind_group_caches(); |
| 285 | self.cache.bust_frame(frame) | |
| 317 | busted | |
| 286 | 318 | } |
| 287 | 319 | |
| 288 | 320 | pub fn bust_subtree(&mut self, node: NodeId) -> usize { |
| 289 | 321 | self.output_cache.clear(); |
| 290 | 322 | self.sync_node_cache_budget(); |
| 323 | let busted = self.cache.bust_subtree(node); | |
| 291 | 324 | self.clear_bind_group_caches(); |
| 292 | self.cache.bust_subtree(node) | |
| 325 | busted | |
| 293 | 326 | } |
| 294 | 327 | |
| 295 | 328 | fn prepare_frame_scratch(&mut self, comp: &Comp) -> HashSet<(NodeId, i64)> { |
| 329 | self.frame_eval_target = None; | |
| 296 | 330 | self.frame_memo.clear(); |
| 297 | 331 | self.frame_roi_memo.clear(); |
| 298 | 332 | if self.frame_consumers_rev != Some(comp.revision) |
| ... | ... | @@ -307,6 +341,7 @@ impl Engine { |
| 307 | 341 | } |
| 308 | 342 | |
| 309 | 343 | fn finish_frame_scratch(&mut self, mut visiting: HashSet<(NodeId, i64)>) { |
| 344 | self.frame_eval_target = None; | |
| 310 | 345 | self.frame_memo.clear(); |
| 311 | 346 | self.frame_roi_memo.clear(); |
| 312 | 347 | visiting.clear(); |
| ... | ... | @@ -321,6 +356,7 @@ impl Engine { |
| 321 | 356 | time: f64, |
| 322 | 357 | ) -> (CachedTexture, EvalStats) { |
| 323 | 358 | let t0 = Instant::now(); |
| 359 | self.sync_bg_cache_with_vram_drops(); | |
| 324 | 360 | let out_key = self.output_cache_key(comp, target, time); |
| 325 | 361 | if let Some((tex, unsupported)) = self.output_cache_get(out_key) { |
| 326 | 362 | let stats = EvalStats { |
| ... | ... | @@ -339,6 +375,7 @@ impl Engine { |
| 339 | 375 | self.media |
| 340 | 376 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 341 | 377 | let mut visiting = self.prepare_frame_scratch(comp); |
| 378 | self.frame_eval_target = Some(target); | |
| 342 | 379 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 343 | 380 | label: Some("comp-eval"), |
| 344 | 381 | }); |
| ... | ... | @@ -349,11 +386,13 @@ impl Engine { |
| 349 | 386 | tex = self.crop_to_canvas(&mut encoder, tex); |
| 350 | 387 | } |
| 351 | 388 | self.queue.submit(Some(encoder.finish())); |
| 389 | self.reset_uniform_cursors(); | |
| 352 | 390 | #[cfg(not(target_arch = "wasm32"))] |
| 353 | 391 | self.media.flush_upload_staging_after_submit(&self.device); |
| 354 | 392 | self.finish_frame_scratch(visiting); |
| 355 | 393 | self.cache.flush_pending_pool(); |
| 356 | 394 | self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); |
| 395 | self.sync_bg_cache_with_vram_drops(); | |
| 357 | 396 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 358 | 397 | stats.cached_entries = self.cache.entry_count(); |
| 359 | 398 | stats.cached_vram_mb = self.vram_mb(); |
| ... | ... | @@ -372,6 +411,7 @@ impl Engine { |
| 372 | 411 | display: DisplaySettings, |
| 373 | 412 | ) -> EvalStats { |
| 374 | 413 | let t0 = Instant::now(); |
| 414 | self.sync_bg_cache_with_vram_drops(); | |
| 375 | 415 | let out_key = self.output_cache_key(comp, target, time); |
| 376 | 416 | let mut stats = EvalStats::default(); |
| 377 | 417 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| ... | ... | @@ -386,6 +426,7 @@ impl Engine { |
| 386 | 426 | self.media |
| 387 | 427 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 388 | 428 | let mut visiting = self.prepare_frame_scratch(comp); |
| 429 | self.frame_eval_target = Some(target); | |
| 389 | 430 | let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 390 | 431 | (t, Some(visiting)) |
| 391 | 432 | }; |
| ... | ... | @@ -409,7 +450,7 @@ impl Engine { |
| 409 | 450 | tex.canvas_size[1] as f32, |
| 410 | 451 | ]; |
| 411 | 452 | } |
| 412 | self.dispatch_to_view( | |
| 453 | self.dispatch_to_view_uncached( | |
| 413 | 454 | &mut encoder, |
| 414 | 455 | ShaderOp::DisplayBlit, |
| 415 | 456 | &tex.view, |
| ... | ... | @@ -421,6 +462,7 @@ impl Engine { |
| 421 | 462 | ); |
| 422 | 463 | |
| 423 | 464 | self.queue.submit(Some(encoder.finish())); |
| 465 | self.reset_uniform_cursors(); | |
| 424 | 466 | #[cfg(not(target_arch = "wasm32"))] |
| 425 | 467 | self.media.flush_upload_staging_after_submit(&self.device); |
| 426 | 468 | if let Some(visiting) = visiting_opt { |
| ... | ... | @@ -428,6 +470,7 @@ impl Engine { |
| 428 | 470 | self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); |
| 429 | 471 | } |
| 430 | 472 | self.cache.flush_pending_pool(); |
| 473 | self.sync_bg_cache_with_vram_drops(); | |
| 431 | 474 | |
| 432 | 475 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 433 | 476 | stats.cached_entries = self.cache.entry_count(); |
| ... | ... | @@ -1472,4 +1515,79 @@ Composition { |
| 1472 | 1515 | assert!(!eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 1473 | 1516 | assert!(eng.frame_consumers[fg2_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 1474 | 1517 | } |
| 1518 | ||
| 1519 | #[test] | |
| 1520 | fn vram_drops_clear_bind_groups_and_viewer_blit_bypasses_bg_cache() { | |
| 1521 | let Ok(mut eng) = Engine::new_headless() else { | |
| 1522 | return; | |
| 1523 | }; | |
| 1524 | // Default Engine::new wires RAM-scaled MediaCache::default(). | |
| 1525 | assert!(crate::media::default_media_cache_budget_mb() >= 512); | |
| 1526 | ||
| 1527 | // Tight 8 MiB VRAM budget: 1024x1024 RGBA8 = 4 MiB per texture. | |
| 1528 | eng.set_vram_budget_mb(8); | |
| 1529 | ||
| 1530 | let src = r#" | |
| 1531 | Composition { | |
| 1532 | CurrentTime = 0, | |
| 1533 | RenderRange = { 0, 10 }, | |
| 1534 | GlobalRange = { 0, 10 }, | |
| 1535 | Tools = ordered() { | |
| 1536 | AnimRed = BezierSpline { | |
| 1537 | KeyFrames = { | |
| 1538 | [0] = { 0.1 }, | |
| 1539 | [10] = { 0.9 }, | |
| 1540 | }, | |
| 1541 | }, | |
| 1542 | BG = Background { | |
| 1543 | Inputs = { | |
| 1544 | Width = Input { Value = 1024, }, | |
| 1545 | Height = Input { Value = 1024, }, | |
| 1546 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, | |
| 1547 | TopLeftAlpha = Input { Value = 1.0, }, | |
| 1548 | }, | |
| 1549 | }, | |
| 1550 | BC = BrightnessContrast { | |
| 1551 | Inputs = { | |
| 1552 | Input = Input { SourceOp = "BG", Source = "Output", }, | |
| 1553 | Gain = Input { Value = 1.2, }, | |
| 1554 | }, | |
| 1555 | }, | |
| 1556 | }, | |
| 1557 | } | |
| 1558 | "#; | |
| 1559 | let comp = Comp::from_fusion_str(src).expect("parse vram bg test comp"); | |
| 1560 | let bc = comp.find_node("BC").unwrap(); | |
| 1561 | ||
| 1562 | // Evaluate frame 0 -> uniform_cursor resets to 0 after submit, bg_cache populated. | |
| 1563 | let _ = eng.evaluate(&comp, bc, 0.0); | |
| 1564 | assert!(eng.frame_eval_target.is_none()); | |
| 1565 | assert_eq!(eng.pipelines.borrow().uniform_chunks.len(), 1); | |
| 1566 | // Next uniform slot allocated must start at chunk 0, offset 0 (cursor was reset post-submit). | |
| 1567 | { | |
| 1568 | let mut reg = eng.pipelines.borrow_mut(); | |
| 1569 | let slot = reg.alloc_uniform_slot(&eng.device, &eng.queue, &UniformParams::default()); | |
| 1570 | assert_eq!(slot, (0, 0)); | |
| 1571 | reg.reset_uniform_cursor(); | |
| 1572 | } | |
| 1573 | assert!(eng.pipelines.borrow().bg_entry_count() > 0); | |
| 1574 | ||
| 1575 | // Render into ephemeral viewer textures on frame 0 (output_cache hit): must not grow bg_cache! | |
| 1576 | let bg_before_viewer = eng.pipelines.borrow().bg_entry_count(); | |
| 1577 | let misses_before_viewer = eng.pipelines.borrow().bg_misses; | |
| 1578 | let viewer_tex_a = create_texture(&eng.device, [512, 512], 0); | |
| 1579 | let viewer_tex_b = create_texture(&eng.device, [640, 360], 0); | |
| 1580 | let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_a.texture, DisplaySettings::default()); | |
| 1581 | let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_b.texture, DisplaySettings::default()); | |
| 1582 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), bg_before_viewer); | |
| 1583 | assert_eq!(eng.pipelines.borrow().bg_misses, misses_before_viewer); | |
| 1584 | ||
| 1585 | // Evaluate frames 1..=3 under 8 MiB budget -> organic eviction increments vram_drops | |
| 1586 | // and sync_bg_cache_with_vram_drops clears bg_cache so evicted textures aren't pinned. | |
| 1587 | for f in 1..=3 { | |
| 1588 | let _ = eng.evaluate(&comp, bc, f as f64); | |
| 1589 | } | |
| 1590 | assert!(eng.cache.vram_drops() > 0); | |
| 1591 | assert_eq!(eng.last_bg_vram_drops.get(), eng.cache.vram_drops()); | |
| 1592 | } | |
| 1475 | 1593 | } |
crates/engine/src/eval/registry.rs+90-29| ... | ... | @@ -238,7 +238,6 @@ impl ShaderOp { |
| 238 | 238 | |
| 239 | 239 | const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl"); |
| 240 | 240 | const UNIFORM_SLOTS_PER_CHUNK: u32 = 1024; |
| 241 | const MAX_UNIFORM_CHUNKS: usize = 16; | |
| 242 | 241 | const LUT_CACHE_CAPACITY: usize = 64; |
| 243 | 242 | #[cfg(not(target_arch = "wasm32"))] |
| 244 | 243 | const MAX_READBACK_BUFFERS: usize = 3; |
| ... | ... | @@ -401,7 +400,6 @@ impl ReadbackPool { |
| 401 | 400 | tex |
| 402 | 401 | } |
| 403 | 402 | |
| 404 | #[allow(dead_code)] | |
| 405 | 403 | pub(super) fn clear(&mut self) { |
| 406 | 404 | self.buffers.clear(); |
| 407 | 405 | self.conv_tex = None; |
| ... | ... | @@ -548,9 +546,8 @@ impl ShaderRegistry { |
| 548 | 546 | /// Writes `params` into the next aligned slot in the chunked dynamic uniform ring |
| 549 | 547 | /// and returns `(chunk_index, dynamic_byte_offset)`. |
| 550 | 548 | /// |
| 551 | /// Lazily allocates 1,024-slot chunks up to `MAX_UNIFORM_CHUNKS` (16,384 slots) so a | |
| 552 | /// single unsubmitted `CommandEncoder` never overwrites earlier slots while long | |
| 553 | /// multi-frame playback stays memory-bounded. | |
| 549 | /// Lazily allocates 1,024-slot chunks without wrapping mid-encoder; callers reset the | |
| 550 | /// cursor back to `0` after each `queue.submit` so normal frames stay in chunk `0`. | |
| 554 | 551 | pub(super) fn alloc_uniform_slot( |
| 555 | 552 | &mut self, |
| 556 | 553 | device: &wgpu::Device, |
| ... | ... | @@ -560,7 +557,7 @@ impl ShaderRegistry { |
| 560 | 557 | let slot_global = self.uniform_cursor; |
| 561 | 558 | let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 562 | 559 | let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK; |
| 563 | if chunk_idx >= self.uniform_chunks.len() { | |
| 560 | while chunk_idx >= self.uniform_chunks.len() { | |
| 564 | 561 | let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); |
| 565 | 562 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 566 | 563 | label: Some("op-params-ring"), |
| ... | ... | @@ -576,12 +573,21 @@ impl ShaderRegistry { |
| 576 | 573 | u64::from(offset), |
| 577 | 574 | bytemuck::bytes_of(params), |
| 578 | 575 | ); |
| 579 | let next = slot_global + 1; | |
| 580 | let max_slots = (MAX_UNIFORM_CHUNKS as u32) * UNIFORM_SLOTS_PER_CHUNK; | |
| 581 | self.uniform_cursor = if next >= max_slots { 0 } else { next }; | |
| 576 | self.uniform_cursor = slot_global + 1; | |
| 582 | 577 | (chunk_idx, offset) |
| 583 | 578 | } |
| 584 | 579 | |
| 580 | pub(super) fn reset_uniform_cursor(&mut self) { | |
| 581 | self.uniform_cursor = 0; | |
| 582 | } | |
| 583 | ||
| 584 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { | |
| 585 | self.uniform_cursor = 0; | |
| 586 | if self.uniform_chunks.len() > max_chunks { | |
| 587 | self.uniform_chunks.truncate(max_chunks); | |
| 588 | } | |
| 589 | } | |
| 590 | ||
| 585 | 591 | /// Returns a cached tiny LUT/curve texture for `(size, format, bytes)` or uploads and |
| 586 | 592 | /// inserts one into the bounded 64-entry LRU cache. |
| 587 | 593 | #[allow(clippy::too_many_arguments)] |
| ... | ... | @@ -657,6 +663,38 @@ impl ShaderRegistry { |
| 657 | 663 | tex |
| 658 | 664 | } |
| 659 | 665 | |
| 666 | /// Builds a `wgpu::BindGroup` for the four `TextureView` bindings and uniform `chunk_idx` | |
| 667 | /// without inserting into `bg_cache` (used for ephemeral viewer/readback targets). | |
| 668 | pub(super) fn create_bind_group( | |
| 669 | &self, | |
| 670 | device: &wgpu::Device, | |
| 671 | src_a: &wgpu::TextureView, | |
| 672 | src_b: &wgpu::TextureView, | |
| 673 | mask: &wgpu::TextureView, | |
| 674 | dst_view: &wgpu::TextureView, | |
| 675 | chunk_idx: usize, | |
| 676 | ) -> wgpu::BindGroup { | |
| 677 | device.create_bind_group(&wgpu::BindGroupDescriptor { | |
| 678 | label: Some("op-bg"), | |
| 679 | layout: &self.bgl, | |
| 680 | entries: &[ | |
| 681 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, | |
| 682 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, | |
| 683 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, | |
| 684 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) }, | |
| 685 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) }, | |
| 686 | wgpu::BindGroupEntry { | |
| 687 | binding: 5, | |
| 688 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | |
| 689 | buffer: &self.uniform_chunks[chunk_idx], | |
| 690 | offset: 0, | |
| 691 | size: NonZeroU64::new(std::mem::size_of::<super::dispatch::UniformParams>() as u64), | |
| 692 | }), | |
| 693 | }, | |
| 694 | ], | |
| 695 | }) | |
| 696 | } | |
| 697 | ||
| 660 | 698 | /// Looks up or creates a cached `wgpu::BindGroup` keyed by the four `TextureView` |
| 661 | 699 | /// handles and dynamic-uniform `chunk_idx`. Holding cloned `TextureView` handles inside |
| 662 | 700 | /// cached entries keeps their underlying resources alive while cached, preventing ABA reuse. |
| ... | ... | @@ -712,25 +750,7 @@ impl ShaderRegistry { |
| 712 | 750 | } |
| 713 | 751 | } |
| 714 | 752 | |
| 715 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | |
| 716 | label: Some("op-bg"), | |
| 717 | layout: &self.bgl, | |
| 718 | entries: &[ | |
| 719 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, | |
| 720 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, | |
| 721 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, | |
| 722 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) }, | |
| 723 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) }, | |
| 724 | wgpu::BindGroupEntry { | |
| 725 | binding: 5, | |
| 726 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | |
| 727 | buffer: &self.uniform_chunks[chunk_idx], | |
| 728 | offset: 0, | |
| 729 | size: NonZeroU64::new(std::mem::size_of::<super::dispatch::UniformParams>() as u64), | |
| 730 | }), | |
| 731 | }, | |
| 732 | ], | |
| 733 | }); | |
| 753 | let bg = self.create_bind_group(device, src_a, src_b, mask, dst_view, chunk_idx); | |
| 734 | 754 | |
| 735 | 755 | let bucket = self.bg_cache.entry(hash).or_default(); |
| 736 | 756 | let idx = bucket.len(); |
| ... | ... | @@ -753,7 +773,6 @@ impl ShaderRegistry { |
| 753 | 773 | &self.bg_cache[&hash][idx].bg |
| 754 | 774 | } |
| 755 | 775 | |
| 756 | #[allow(dead_code)] | |
| 757 | 776 | pub(super) fn clear_bind_group_cache(&mut self) { |
| 758 | 777 | self.bg_cache.clear(); |
| 759 | 778 | self.bg_count = 0; |
| ... | ... | @@ -918,4 +937,46 @@ mod tests { |
| 918 | 937 | } |
| 919 | 938 | let _ = prewarm_ms; |
| 920 | 939 | } |
| 940 | ||
| 941 | #[test] | |
| 942 | fn uniform_ring_grows_past_16_chunks_without_wrapping_and_resets() { | |
| 943 | let Ok(eng) = Engine::new_headless() else { | |
| 944 | return; | |
| 945 | }; | |
| 946 | let params = super::super::dispatch::UniformParams::default(); | |
| 947 | let mut reg = eng.pipelines.borrow_mut(); | |
| 948 | ||
| 949 | let total = 16 * UNIFORM_SLOTS_PER_CHUNK + 5; | |
| 950 | let mut last = (0usize, 0u32); | |
| 951 | for _ in 0..total { | |
| 952 | last = reg.alloc_uniform_slot(&eng.device, &eng.queue, &params); | |
| 953 | } | |
| 954 | assert_eq!(last.0, 16, "cursor must grow to chunk 16 instead of wrapping to 0"); | |
| 955 | assert_eq!(last.1, 4 * reg.uniform_stride); | |
| 956 | assert_eq!(reg.uniform_chunks.len(), 17); | |
| 957 | ||
| 958 | reg.reset_uniform_cursor(); | |
| 959 | let after_reset = reg.alloc_uniform_slot(&eng.device, &eng.queue, &params); | |
| 960 | assert_eq!(after_reset, (0, 0)); | |
| 961 | ||
| 962 | reg.trim_uniform_chunks(2); | |
| 963 | assert_eq!(reg.uniform_chunks.len(), 2); | |
| 964 | assert_eq!(reg.uniform_cursor, 0); | |
| 965 | } | |
| 966 | ||
| 967 | #[test] | |
| 968 | fn prewarm_for_depth_warms_float16_in_hiq_only() { | |
| 969 | let Ok(mut eng) = Engine::new_headless() else { | |
| 970 | return; | |
| 971 | }; | |
| 972 | eng.hiq = false; | |
| 973 | eng.prewarm_for_depth(model::BitDepth::Float16); | |
| 974 | assert_eq!(eng.pipelines.borrow().pipelines.len(), CORE_PREWARM_OPS.len()); | |
| 975 | assert!(eng.pipelines_f16.get().is_none()); | |
| 976 | ||
| 977 | eng.hiq = true; | |
| 978 | eng.prewarm_for_depth(model::BitDepth::Float16); | |
| 979 | let f16 = eng.pipelines_f16.get().expect("f16 registry initialized"); | |
| 980 | assert_eq!(f16.borrow().pipelines.len(), CORE_PREWARM_OPS.len()); | |
| 981 | } | |
| 921 | 982 | } |