| author | |
| committer | |
| log | 5432bcf4b7db251c55263591b6ccf9d81738923c |
| tree | a5578697a92d4c738b28f26e2ce882341e7ece98 |
| parent | 0e7a2c62afd19b813b5077fad79c34ab0389ebe4 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
9 files changed, 907 insertions(+), 146 deletions(-)
crates/engine/src/cache.rs+164-15| ... | ... | @@ -59,6 +59,22 @@ fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 { |
| 59 | 59 | .saturating_mul(bytes_per_pixel(format)) |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | /// Clamps `(width, height)` to at least 1 and at most `max_dim` while preserving aspect ratio. | |
| 63 | /// Returns `(clamped_size, tex_scale)` where `tex_scale = physical / logical` (`1.0` if unclamped). | |
| 64 | pub(crate) fn clamp_dims_to_limit(width: u32, height: u32, max_dim: u32) -> ([u32; 2], f32) { | |
| 65 | let w = width.max(1); | |
| 66 | let h = height.max(1); | |
| 67 | let max_d = max_dim.max(1); | |
| 68 | let peak = w.max(h); | |
| 69 | if peak <= max_d { | |
| 70 | return ([w, h], 1.0); | |
| 71 | } | |
| 72 | let scale = max_d as f32 / peak as f32; | |
| 73 | let cw = ((f64::from(w) * f64::from(max_d) / f64::from(peak)).round() as u32).clamp(1, max_d); | |
| 74 | let ch = ((f64::from(h) * f64::from(max_d) / f64::from(peak)).round() as u32).clamp(1, max_d); | |
| 75 | ([cw, ch], scale) | |
| 76 | } | |
| 77 | ||
| 62 | 78 | impl CachedTexture { |
| 63 | 79 | pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self { |
| 64 | 80 | Self::from_texture_dod(texture, size, [0, 0], size, content_hash) |
| ... | ... | @@ -343,6 +359,9 @@ pub struct NodeCache { |
| 343 | 359 | /// Per-node salt bumped when surgically busting a subtree. |
| 344 | 360 | node_salts: HashMap<NodeId, u64>, |
| 345 | 361 | pool: Mutex<TexturePool>, |
| 362 | /// Evicted textures deferred until after `queue.submit` so `queue.write_texture` | |
| 363 | /// never aliases a texture still referenced by in-flight commands in the current encoder. | |
| 364 | pending_pool: Vec<CachedTexture>, | |
| 346 | 365 | profiler: Option<ProfileRecorder>, |
| 347 | 366 | } |
| 348 | 367 | |
| ... | ... | @@ -358,6 +377,7 @@ impl NodeCache { |
| 358 | 377 | gpu_salt: 0, |
| 359 | 378 | node_salts: HashMap::new(), |
| 360 | 379 | pool: Mutex::new(TexturePool::new()), |
| 380 | pending_pool: Vec::new(), | |
| 361 | 381 | profiler: None, |
| 362 | 382 | } |
| 363 | 383 | } |
| ... | ... | @@ -416,6 +436,8 @@ impl NodeCache { |
| 416 | 436 | |
| 417 | 437 | /// Acquires a GPU texture matching `(width, height, format, usage)` from the pool if an |
| 418 | 438 | /// exclusively-owned texture is available, otherwise allocates a fresh one on `device`. |
| 439 | /// Dimensions exceeding `device.limits().max_texture_dimension_2d` are clamped proportionally | |
| 440 | /// and the resulting scale factor is recorded in `tex_scale`. | |
| 419 | 441 | pub fn acquire_texture( |
| 420 | 442 | &self, |
| 421 | 443 | device: &wgpu::Device, |
| ... | ... | @@ -424,7 +446,8 @@ impl NodeCache { |
| 424 | 446 | format: wgpu::TextureFormat, |
| 425 | 447 | usage: wgpu::TextureUsages, |
| 426 | 448 | ) -> CachedTexture { |
| 427 | let clamped = [width.max(1), height.max(1)]; | |
| 449 | let max_dim = device.limits().max_texture_dimension_2d.max(1); | |
| 450 | let (clamped, tex_scale) = clamp_dims_to_limit(width, height, max_dim); | |
| 428 | 451 | let bytes = texture_bytes(clamped, format); |
| 429 | 452 | let key = TexturePoolKey { |
| 430 | 453 | width: clamped[0], |
| ... | ... | @@ -438,7 +461,7 @@ impl NodeCache { |
| 438 | 461 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| 439 | 462 | if let Some((texture, view, pooled_bytes)) = pool.pop(key) { |
| 440 | 463 | pool.hits += 1; |
| 441 | return CachedTexture::from_parts( | |
| 464 | let mut tex = CachedTexture::from_parts( | |
| 442 | 465 | texture, |
| 443 | 466 | view, |
| 444 | 467 | clamped, |
| ... | ... | @@ -449,6 +472,8 @@ impl NodeCache { |
| 449 | 472 | 0, |
| 450 | 473 | pooled_bytes, |
| 451 | 474 | ); |
| 475 | tex.tex_scale = tex_scale; | |
| 476 | return tex; | |
| 452 | 477 | } |
| 453 | 478 | pool.misses += 1; |
| 454 | 479 | // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget. |
| ... | ... | @@ -478,7 +503,9 @@ impl NodeCache { |
| 478 | 503 | usage, |
| 479 | 504 | view_formats: &[], |
| 480 | 505 | }); |
| 481 | CachedTexture::from_texture_dod_depth(texture, clamped, [0, 0], clamped, depth, 0) | |
| 506 | let mut tex = CachedTexture::from_texture_dod_depth(texture, clamped, [0, 0], clamped, depth, 0); | |
| 507 | tex.tex_scale = tex_scale; | |
| 508 | tex | |
| 482 | 509 | } |
| 483 | 510 | |
| 484 | 511 | /// Pool-backed DoD texture allocation matching `create_texture_dod_fmt` semantics. |
| ... | ... | @@ -500,8 +527,24 @@ impl NodeCache { |
| 500 | 527 | format, |
| 501 | 528 | Self::default_texture_usage(), |
| 502 | 529 | ); |
| 503 | tex.origin = origin; | |
| 504 | tex.canvas_size = [canvas_size[0].max(1), canvas_size[1].max(1)]; | |
| 530 | tex.origin = if tex.tex_scale < 1.0 { | |
| 531 | [ | |
| 532 | (origin[0] as f32 * tex.tex_scale).round() as i32, | |
| 533 | (origin[1] as f32 * tex.tex_scale).round() as i32, | |
| 534 | ] | |
| 535 | } else { | |
| 536 | origin | |
| 537 | }; | |
| 538 | tex.canvas_size = if size == canvas_size { | |
| 539 | tex.size | |
| 540 | } else if tex.tex_scale < 1.0 { | |
| 541 | [ | |
| 542 | ((canvas_size[0].max(1) as f32 * tex.tex_scale).round() as u32).max(1), | |
| 543 | ((canvas_size[1].max(1) as f32 * tex.tex_scale).round() as u32).max(1), | |
| 544 | ] | |
| 545 | } else { | |
| 546 | [canvas_size[0].max(1), canvas_size[1].max(1)] | |
| 547 | }; | |
| 505 | 548 | tex.depth = depth; |
| 506 | 549 | tex.content_hash = content_hash; |
| 507 | 550 | tex |
| ... | ... | @@ -553,7 +596,7 @@ impl NodeCache { |
| 553 | 596 | if let Some(old) = self.entries.remove(&key) { |
| 554 | 597 | self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes); |
| 555 | 598 | if !Arc::ptr_eq(&old.tex.texture, &tex.texture) { |
| 556 | self.return_to_pool(&old.tex); | |
| 599 | self.defer_to_pool(old.tex); | |
| 557 | 600 | } |
| 558 | 601 | } |
| 559 | 602 | self.total_bytes = self.total_bytes.saturating_add(tex.bytes); |
| ... | ... | @@ -576,6 +619,54 @@ impl NodeCache { |
| 576 | 619 | self.trim_pool_to_budget(); |
| 577 | 620 | } |
| 578 | 621 | |
| 622 | fn defer_to_pool(&mut self, tex: CachedTexture) { | |
| 623 | if tex.bytes == 0 || tex.bytes > self.budget_bytes { | |
| 624 | return; | |
| 625 | } | |
| 626 | let mut pending_bytes: u64 = self.pending_pool.iter().map(|t| t.bytes).sum(); | |
| 627 | if self | |
| 628 | .total_bytes | |
| 629 | .saturating_add(pending_bytes) | |
| 630 | .saturating_add(tex.bytes) | |
| 631 | <= self.budget_bytes | |
| 632 | { | |
| 633 | self.pending_pool.push(tex); | |
| 634 | } else { | |
| 635 | // Keep most recently evicted textures within budget; drop older pending ones. | |
| 636 | while !self.pending_pool.is_empty() | |
| 637 | && self | |
| 638 | .total_bytes | |
| 639 | .saturating_add(pending_bytes) | |
| 640 | .saturating_add(tex.bytes) | |
| 641 | > self.budget_bytes | |
| 642 | { | |
| 643 | let dropped = self.pending_pool.remove(0); | |
| 644 | pending_bytes = pending_bytes.saturating_sub(dropped.bytes); | |
| 645 | } | |
| 646 | if self | |
| 647 | .total_bytes | |
| 648 | .saturating_add(pending_bytes) | |
| 649 | .saturating_add(tex.bytes) | |
| 650 | <= self.budget_bytes | |
| 651 | { | |
| 652 | self.pending_pool.push(tex); | |
| 653 | } | |
| 654 | } | |
| 655 | } | |
| 656 | ||
| 657 | /// Moves textures evicted during the current frame into `TexturePool`. | |
| 658 | /// Must be called right after `queue.submit` so `queue.write_texture` cannot | |
| 659 | /// overwrite a texture still used by commands in the submitted encoder. | |
| 660 | pub fn flush_pending_pool(&mut self) { | |
| 661 | if self.pending_pool.is_empty() { | |
| 662 | return; | |
| 663 | } | |
| 664 | let drained = std::mem::take(&mut self.pending_pool); | |
| 665 | for tex in drained { | |
| 666 | self.return_to_pool(&tex); | |
| 667 | } | |
| 668 | } | |
| 669 | ||
| 579 | 670 | fn return_to_pool(&self, tex: &CachedTexture) { |
| 580 | 671 | if tex.bytes == 0 || tex.bytes > self.budget_bytes { |
| 581 | 672 | return; |
| ... | ... | @@ -607,14 +698,7 @@ impl NodeCache { |
| 607 | 698 | if let Some(removed) = self.entries.remove(&oldest_key) { |
| 608 | 699 | self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); |
| 609 | 700 | self.evictions += 1; |
| 610 | if self | |
| 611 | .total_bytes | |
| 612 | .saturating_add(self.pooled_bytes()) | |
| 613 | .saturating_add(removed.tex.bytes) | |
| 614 | <= self.budget_bytes | |
| 615 | { | |
| 616 | self.return_to_pool(&removed.tex); | |
| 617 | } | |
| 701 | self.defer_to_pool(removed.tex); | |
| 618 | 702 | } |
| 619 | 703 | } |
| 620 | 704 | } |
| ... | ... | @@ -628,10 +712,16 @@ impl NodeCache { |
| 628 | 712 | pub fn clear_dynamic(&mut self) -> usize { |
| 629 | 713 | let count = self.entries.len(); |
| 630 | 714 | let drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect(); |
| 715 | let pending = std::mem::take(&mut self.pending_pool); | |
| 631 | 716 | self.total_bytes = 0; |
| 632 | 717 | self.gpu_salt += 1; |
| 633 | if !drained.is_empty() && self.budget_bytes > 0 { | |
| 718 | if (!drained.is_empty() || !pending.is_empty()) && self.budget_bytes > 0 { | |
| 634 | 719 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| 720 | for tex in pending { | |
| 721 | if tex.bytes > 0 && tex.bytes <= self.budget_bytes { | |
| 722 | pool.push(&tex); | |
| 723 | } | |
| 724 | } | |
| 635 | 725 | for entry in drained { |
| 636 | 726 | if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes { |
| 637 | 727 | pool.push(&entry.tex); |
| ... | ... | @@ -852,4 +942,63 @@ mod tests { |
| 852 | 942 | assert_eq!(p_warm.entries.len(), 1); |
| 853 | 943 | assert!(p_warm.entries[0].cache_hit); |
| 854 | 944 | } |
| 945 | ||
| 946 | #[test] | |
| 947 | fn oversized_texture_clamps_to_device_limit_preserving_aspect_and_tex_scale() { | |
| 948 | let eng = Engine::new_headless().expect("gpu"); | |
| 949 | let device = eng.device(); | |
| 950 | let max_dim = device.limits().max_texture_dimension_2d; | |
| 951 | let usage = NodeCache::default_texture_usage(); | |
| 952 | let cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB); | |
| 953 | ||
| 954 | let req_w = max_dim + 4096; | |
| 955 | let req_h = (max_dim + 4096) / 2; | |
| 956 | let expected_scale = max_dim as f32 / req_w as f32; | |
| 957 | ||
| 958 | let t_pool = cache.acquire_texture(device, req_w, req_h, wgpu::TextureFormat::Rgba8Unorm, usage); | |
| 959 | assert_eq!(t_pool.size[0], max_dim); | |
| 960 | assert!((t_pool.size[1] as i32 - (max_dim as i32 / 2)).abs() <= 1); | |
| 961 | assert!((t_pool.tex_scale - expected_scale).abs() < 1e-5); | |
| 962 | assert_eq!(t_pool.canvas_size, t_pool.size); | |
| 963 | ||
| 964 | let t_raw = crate::eval::create_texture_dod_fmt( | |
| 965 | device, | |
| 966 | [req_w, req_h], | |
| 967 | [0, 0], | |
| 968 | [req_w, req_h], | |
| 969 | BitDepth::Int8, | |
| 970 | wgpu::TextureFormat::Rgba8Unorm, | |
| 971 | 77, | |
| 972 | ); | |
| 973 | assert_eq!(t_raw.size, t_pool.size); | |
| 974 | assert!((t_raw.tex_scale - expected_scale).abs() < 1e-5); | |
| 975 | } | |
| 976 | ||
| 977 | #[test] | |
| 978 | fn deferred_evictions_flush_into_pool_after_submit() { | |
| 979 | let eng = Engine::new_headless().expect("gpu"); | |
| 980 | let device = eng.device(); | |
| 981 | let usage = NodeCache::default_texture_usage(); | |
| 982 | // 4 MiB budget: each 512x512 RGBA8 is 1 MiB. | |
| 983 | let mut cache = NodeCache::new(4); | |
| 984 | for i in 0..5u64 { | |
| 985 | let t = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); | |
| 986 | cache.insert(i, t, NodeId(i as usize), 0); | |
| 987 | } | |
| 988 | // Evicted texture is deferred until flush_pending_pool() so mid-frame uploads can't alias. | |
| 989 | assert_eq!(cache.eviction_count(), 1); | |
| 990 | assert_eq!(cache.pooled_bytes(), 0); | |
| 991 | cache.flush_pending_pool(); | |
| 992 | assert_eq!(cache.pooled_bytes(), 0); // 4 MiB live + 0 pooled <= 4 MiB (budget full) | |
| 993 | ||
| 994 | // With 2 MiB live and 1 evicted texture, flush moves it into pool. | |
| 995 | let mut cache2 = NodeCache::new(4); | |
| 996 | let a = cache2.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); | |
| 997 | let b = cache2.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); | |
| 998 | cache2.insert(1, a, NodeId(0), 0); | |
| 999 | cache2.insert(1, b, NodeId(0), 0); // Overwrites key 1 -> defers `a` | |
| 1000 | assert_eq!(cache2.pooled_bytes(), 0); | |
| 1001 | cache2.flush_pending_pool(); | |
| 1002 | assert_eq!(cache2.pooled_bytes(), 1024 * 1024); | |
| 1003 | } | |
| 855 | 1004 | } |
crates/engine/src/cryptomatte.rs+20-11| ... | ... | @@ -197,15 +197,12 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> { |
| 197 | 197 | *pos += 1; // consume opening '"' |
| 198 | 198 | let mut out = String::new(); |
| 199 | 199 | while *pos < bytes.len() { |
| 200 | let ch = src[*pos..].chars().next()?; | |
| 200 | let ch = src.get(*pos..)?.chars().next()?; | |
| 201 | 201 | *pos += ch.len_utf8(); |
| 202 | 202 | match ch { |
| 203 | 203 | '"' => return Some(out), |
| 204 | 204 | '\\' => { |
| 205 | if *pos >= bytes.len() { | |
| 206 | return None; | |
| 207 | } | |
| 208 | let esc = src[*pos..].chars().next()?; | |
| 205 | let esc = src.get(*pos..)?.chars().next()?; | |
| 209 | 206 | *pos += esc.len_utf8(); |
| 210 | 207 | match esc { |
| 211 | 208 | '"' => out.push('"'), |
| ... | ... | @@ -220,7 +217,7 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> { |
| 220 | 217 | let code_unit = parse_hex4(src, pos)?; |
| 221 | 218 | if (0xD800..=0xDBFF).contains(&code_unit) { |
| 222 | 219 | // UTF-16 surrogate pair |
| 223 | if src[*pos..].starts_with("\\u") { | |
| 220 | if src.get(*pos..).is_some_and(|s| s.starts_with("\\u")) { | |
| 224 | 221 | *pos += 2; |
| 225 | 222 | let low = parse_hex4(src, pos)?; |
| 226 | 223 | if (0xDC00..=0xDFFF).contains(&low) { |
| ... | ... | @@ -246,12 +243,10 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> { |
| 246 | 243 | } |
| 247 | 244 | |
| 248 | 245 | fn parse_hex4(src: &str, pos: &mut usize) -> Option<u16> { |
| 249 | if *pos + 4 > src.len() { | |
| 250 | return None; | |
| 251 | } | |
| 252 | let slice = &src[*pos..*pos + 4]; | |
| 246 | let end = pos.checked_add(4)?; | |
| 247 | let slice = src.get(*pos..end)?; | |
| 253 | 248 | let val = u16::from_str_radix(slice, 16).ok()?; |
| 254 | *pos += 4; | |
| 249 | *pos = end; | |
| 255 | 250 | Some(val) |
| 256 | 251 | } |
| 257 | 252 | |
| ... | ... | @@ -853,4 +848,18 @@ mod tests { |
| 853 | 848 | |
| 854 | 849 | let _ = std::fs::remove_file(&tmp_path); |
| 855 | 850 | } |
| 851 | ||
| 852 | #[test] | |
| 853 | fn parse_manifest_json_handles_multibyte_utf8_after_u_escape_without_panicking() { | |
| 854 | // Malformed \u escapes whose 4-byte window would split multi-byte UTF-8 sequences | |
| 855 | // must return cleanly instead of panicking on non-char-boundary slicing. | |
| 856 | let malformed = r#"{"\u00é": "12345678", "\u🦀a": "deadbeef", "日本語": "a1b2c3d4"}"#; | |
| 857 | let parsed = parse_manifest_json(malformed); | |
| 858 | assert!(parsed.is_empty()); | |
| 859 | ||
| 860 | let valid_utf8 = r#"{"Hero_日本語": "a1b2c3d4", "élan_\u0041": "0x00ff00ff"}"#; | |
| 861 | let parsed_valid = parse_manifest_json(valid_utf8); | |
| 862 | assert_eq!(parsed_valid.get("Hero_日本語"), Some(&0xa1b2_c3d4)); | |
| 863 | assert_eq!(parsed_valid.get("élan_A"), Some(&0x00ff_00ff)); | |
| 864 | } | |
| 856 | 865 | } |
crates/engine/src/custom_shader.rs+92-22| ... | ... | @@ -277,12 +277,15 @@ fn tokenize(src: &str) -> Result<Vec<Token>, String> { |
| 277 | 277 | Ok(out) |
| 278 | 278 | } |
| 279 | 279 | |
| 280 | const MAX_PARSE_DEPTH: usize = 64; | |
| 281 | ||
| 280 | 282 | struct ExprCompiler<'a> { |
| 281 | 283 | tokens: &'a [Token], |
| 282 | 284 | pos: usize, |
| 283 | 285 | channel: Channel, |
| 284 | 286 | max_setup: usize, |
| 285 | 287 | max_inter: usize, |
| 288 | depth: usize, | |
| 286 | 289 | } |
| 287 | 290 | |
| 288 | 291 | impl<'a> ExprCompiler<'a> { |
| ... | ... | @@ -299,6 +302,19 @@ impl<'a> ExprCompiler<'a> { |
| 299 | 302 | } |
| 300 | 303 | } |
| 301 | 304 | |
| 305 | fn with_depth( | |
| 306 | &mut self, | |
| 307 | f: impl FnOnce(&mut Self) -> Result<String, String>, | |
| 308 | ) -> Result<String, String> { | |
| 309 | if self.depth >= MAX_PARSE_DEPTH { | |
| 310 | return Err(format!("expression exceeds maximum nesting depth ({MAX_PARSE_DEPTH})")); | |
| 311 | } | |
| 312 | self.depth += 1; | |
| 313 | let res = f(self); | |
| 314 | self.depth -= 1; | |
| 315 | res | |
| 316 | } | |
| 317 | ||
| 302 | 318 | fn compile(&mut self) -> Result<String, String> { |
| 303 | 319 | if self.tokens.is_empty() { |
| 304 | 320 | return Ok("0.0".to_owned()); |
| ... | ... | @@ -386,7 +402,7 @@ impl<'a> ExprCompiler<'a> { |
| 386 | 402 | let base = self.parse_unary()?; |
| 387 | 403 | if self.eat(&Token::Caret) { |
| 388 | 404 | // Right-associative and allows unary rhs (e.g. `e^-x`, `2^-3`) |
| 389 | let exp = self.parse_pow()?; | |
| 405 | let exp = self.with_depth(Self::parse_pow)?; | |
| 390 | 406 | Ok(format!("fu_pow(({base}), ({exp}))")) |
| 391 | 407 | } else { |
| 392 | 408 | Ok(base) |
| ... | ... | @@ -395,12 +411,12 @@ impl<'a> ExprCompiler<'a> { |
| 395 | 411 | |
| 396 | 412 | fn parse_unary(&mut self) -> Result<String, String> { |
| 397 | 413 | if self.eat(&Token::Minus) { |
| 398 | let inner = self.parse_unary()?; | |
| 414 | let inner = self.with_depth(Self::parse_unary)?; | |
| 399 | 415 | Ok(format!("(-({inner}))")) |
| 400 | 416 | } else if self.eat(&Token::Plus) { |
| 401 | self.parse_unary() | |
| 417 | self.with_depth(Self::parse_unary) | |
| 402 | 418 | } else if self.eat(&Token::Bang) { |
| 403 | let inner = self.parse_unary()?; | |
| 419 | let inner = self.with_depth(Self::parse_unary)?; | |
| 404 | 420 | Ok(format!("select(0.0, 1.0, ({inner}) == 0.0)")) |
| 405 | 421 | } else { |
| 406 | 422 | self.parse_primary() |
| ... | ... | @@ -411,7 +427,7 @@ impl<'a> ExprCompiler<'a> { |
| 411 | 427 | match self.peek().cloned() { |
| 412 | 428 | Some(Token::LParen) => { |
| 413 | 429 | self.pos += 1; |
| 414 | let inner = self.parse_or()?; | |
| 430 | let inner = self.with_depth(Self::parse_or)?; | |
| 415 | 431 | if !self.eat(&Token::RParen) { |
| 416 | 432 | return Err("expected ')'".to_owned()); |
| 417 | 433 | } |
| ... | ... | @@ -427,7 +443,7 @@ impl<'a> ExprCompiler<'a> { |
| 427 | 443 | let mut args = Vec::new(); |
| 428 | 444 | if self.peek() != Some(&Token::RParen) { |
| 429 | 445 | loop { |
| 430 | args.push(self.parse_or()?); | |
| 446 | args.push(self.with_depth(Self::parse_or)?); | |
| 431 | 447 | if !self.eat(&Token::Comma) { |
| 432 | 448 | break; |
| 433 | 449 | } |
| ... | ... | @@ -682,6 +698,7 @@ fn compile_single_expr( |
| 682 | 698 | channel, |
| 683 | 699 | max_setup, |
| 684 | 700 | max_inter, |
| 701 | depth: 0, | |
| 685 | 702 | }; |
| 686 | 703 | compiler.compile() |
| 687 | 704 | } |
| ... | ... | @@ -972,6 +989,34 @@ impl CustomShaderCache { |
| 972 | 989 | } |
| 973 | 990 | } |
| 974 | 991 | |
| 992 | fn compile_wgsl_pipeline( | |
| 993 | &mut self, | |
| 994 | device: &wgpu::Device, | |
| 995 | format: wgpu::TextureFormat, | |
| 996 | wgsl: &str, | |
| 997 | ) -> Option<wgpu::ComputePipeline> { | |
| 998 | self.ensure_format_layouts(device, format); | |
| 999 | let pl = &self.layouts[&format].pl; | |
| 1000 | let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); | |
| 1001 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | |
| 1002 | label: Some("custom-tool-shader"), | |
| 1003 | source: wgpu::ShaderSource::Wgsl(wgsl.into()), | |
| 1004 | }); | |
| 1005 | let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | |
| 1006 | label: Some("custom_tool_op"), | |
| 1007 | layout: Some(pl), | |
| 1008 | module: &module, | |
| 1009 | entry_point: Some("custom_tool_op"), | |
| 1010 | compilation_options: Default::default(), | |
| 1011 | cache: None, | |
| 1012 | }); | |
| 1013 | if pollster::block_on(scope.pop()).is_some() { | |
| 1014 | None | |
| 1015 | } else { | |
| 1016 | Some(pipeline) | |
| 1017 | } | |
| 1018 | } | |
| 1019 | ||
| 975 | 1020 | /// Compiles and caches the compute pipeline for `program` at `format`, returning `false` |
| 976 | 1021 | /// if the program contains unsupported syntax (graceful fallback to passthrough). |
| 977 | 1022 | pub fn ensure_compiled( |
| ... | ... | @@ -985,23 +1030,8 @@ impl CustomShaderCache { |
| 985 | 1030 | if let Some(entry) = self.pipelines.get(&key) { |
| 986 | 1031 | return entry.is_some(); |
| 987 | 1032 | } |
| 988 | self.ensure_format_layouts(device, format); | |
| 989 | 1033 | let pipeline = match compile_wgsl(&norm, format) { |
| 990 | Ok(wgsl) => { | |
| 991 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | |
| 992 | label: Some("custom-tool-shader"), | |
| 993 | source: wgpu::ShaderSource::Wgsl(wgsl.into()), | |
| 994 | }); | |
| 995 | let pl = &self.layouts[&format].pl; | |
| 996 | Some(device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | |
| 997 | label: Some("custom_tool_op"), | |
| 998 | layout: Some(pl), | |
| 999 | module: &module, | |
| 1000 | entry_point: Some("custom_tool_op"), | |
| 1001 | compilation_options: Default::default(), | |
| 1002 | cache: None, | |
| 1003 | })) | |
| 1004 | } | |
| 1034 | Ok(wgsl) => self.compile_wgsl_pipeline(device, format, &wgsl), | |
| 1005 | 1035 | Err(_) => None, |
| 1006 | 1036 | }; |
| 1007 | 1037 | let ok = pipeline.is_some(); |
| ... | ... | @@ -1293,4 +1323,44 @@ mod tests { |
| 1293 | 1323 | assert_eq!(rgba[2], 255); |
| 1294 | 1324 | assert_eq!(rgba[3], 255); |
| 1295 | 1325 | } |
| 1326 | ||
| 1327 | #[test] | |
| 1328 | fn rejects_deeply_nested_expressions_without_stack_overflow() { | |
| 1329 | let mut p = CustomProgram::default(); | |
| 1330 | let depth = MAX_PARSE_DEPTH + 16; | |
| 1331 | p.red = format!("{}r1{}", "(".repeat(depth), ")".repeat(depth)); | |
| 1332 | let err = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect_err("must reject deep parens"); | |
| 1333 | assert!(err.contains("nesting depth"), "unexpected err: {err}"); | |
| 1334 | ||
| 1335 | p.red = format!("{}r1", "-".repeat(depth)); | |
| 1336 | let err_unary = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect_err("must reject deep unary"); | |
| 1337 | assert!(err_unary.contains("nesting depth"), "unexpected err: {err_unary}"); | |
| 1338 | ||
| 1339 | p.red = format!("{}1", "2^".repeat(depth)); | |
| 1340 | let err_pow = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect_err("must reject deep pow"); | |
| 1341 | assert!(err_pow.contains("nesting depth"), "unexpected err: {err_pow}"); | |
| 1342 | ||
| 1343 | // Within limit should still compile cleanly. | |
| 1344 | let ok_depth = 16; | |
| 1345 | p.red = format!("{}r1{}", "(".repeat(ok_depth), ")".repeat(ok_depth)); | |
| 1346 | assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_ok()); | |
| 1347 | } | |
| 1348 | ||
| 1349 | #[test] | |
| 1350 | fn validation_error_scope_catches_invalid_wgsl_without_panicking() { | |
| 1351 | let eng = Engine::new_headless().expect("gpu"); | |
| 1352 | let mut cache = CustomShaderCache::new(); | |
| 1353 | let res = cache.compile_wgsl_pipeline( | |
| 1354 | eng.device(), | |
| 1355 | wgpu::TextureFormat::Rgba8Unorm, | |
| 1356 | "this is not valid wgsl @@@", | |
| 1357 | ); | |
| 1358 | assert!(res.is_none(), "invalid WGSL must return None cleanly"); | |
| 1359 | ||
| 1360 | // Caching failure in pipelines map returns false on subsequent queries too. | |
| 1361 | let mut bad_prog = CustomProgram::default(); | |
| 1362 | bad_prog.red = "unknown_ident_xyz".to_owned(); | |
| 1363 | assert!(!cache.ensure_compiled(eng.device(), &bad_prog, wgpu::TextureFormat::Rgba8Unorm)); | |
| 1364 | assert!(!cache.ensure_compiled(eng.device(), &bad_prog, wgpu::TextureFormat::Rgba8Unorm)); | |
| 1365 | } | |
| 1296 | 1366 | } |
crates/engine/src/eval/io.rs+16-6| ... | ... | @@ -1,10 +1,19 @@ |
| 1 | 1 | use super::*; |
| 2 | use std::path::PathBuf; | |
| 3 | use std::sync::{Mutex, OnceLock}; | |
| 4 | ||
| 5 | static DIMS_CACHE: OnceLock<Mutex<HashMap<PathBuf, Option<[u32; 2]>>>> = OnceLock::new(); | |
| 6 | ||
| 7 | pub(super) fn clear_dims_cache() { | |
| 8 | if let Some(cache) = DIMS_CACHE.get() { | |
| 9 | if let Ok(mut guard) = cache.lock() { | |
| 10 | guard.clear(); | |
| 11 | } | |
| 12 | } | |
| 13 | } | |
| 2 | 14 | |
| 3 | 15 | impl Engine { |
| 4 | 16 | fn probe_clip_dims(clip: &model::ClipSpec) -> Option<[u32; 2]> { |
| 5 | use std::path::PathBuf; | |
| 6 | use std::sync::{Mutex, OnceLock}; | |
| 7 | static DIMS_CACHE: OnceLock<Mutex<HashMap<PathBuf, Option<[u32; 2]>>>> = OnceLock::new(); | |
| 8 | 17 | let base = PathBuf::from(&clip.filename); |
| 9 | 18 | let cache = DIMS_CACHE.get_or_init(|| Mutex::new(HashMap::new())); |
| 10 | 19 | if let Ok(guard) = cache.lock() { |
| ... | ... | @@ -163,6 +172,7 @@ impl Engine { |
| 163 | 172 | resolved.hash(&mut h); |
| 164 | 173 | local_idx.hash(&mut h); |
| 165 | 174 | post_mult.hash(&mut h); |
| 175 | exr_channels.hash(&mut h); | |
| 166 | 176 | target_size.hash(&mut h); |
| 167 | 177 | mask_hash.hash(&mut h); |
| 168 | 178 | mask_inv.hash(&mut h); |
| ... | ... | @@ -577,8 +587,8 @@ impl Engine { |
| 577 | 587 | let sx = comp.eval_number(node, "XSize", time, 1.0, &self.expr); |
| 578 | 588 | let sy = comp.eval_number(node, "YSize", time, sx, &self.expr); |
| 579 | 589 | [ |
| 580 | ((src.size[0] as f64 * sx).round() as u32).clamp(1, 8192), | |
| 581 | ((src.size[1] as f64 * sy).round() as u32).clamp(1, 8192), | |
| 590 | ((src.size[0] as f64 * sx).round() as u32).max(1), | |
| 591 | ((src.size[1] as f64 * sy).round() as u32).max(1), | |
| 582 | 592 | ] |
| 583 | 593 | }; |
| 584 | 594 | let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 }; |
| ... | ... | @@ -757,7 +767,7 @@ impl Engine { |
| 757 | 767 | wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, |
| 758 | 768 | ); |
| 759 | 769 | let mut dst = self.alloc_tex(size, self.node_depth(comp, node, time, None), key); |
| 760 | dst.tex_scale = tex_scale; | |
| 770 | dst.tex_scale *= tex_scale; | |
| 761 | 771 | self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u); |
| 762 | 772 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 763 | 773 | dst |
crates/engine/src/eval/mod.rs+330-41| ... | ... | @@ -405,7 +405,8 @@ pub struct Engine { |
| 405 | 405 | optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>, |
| 406 | 406 | particles: crate::particles::ParticleCache, |
| 407 | 407 | custom_shaders: crate::custom_shader::CustomShaderCache, |
| 408 | sprite_cache: HashMap<(NodeId, u64, i64), crate::particles::SpriteImage>, | |
| 408 | sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, | |
| 409 | ram_upload_tex: RefCell<Option<CachedTexture>>, | |
| 409 | 410 | dummy: CachedTexture, |
| 410 | 411 | pub cache: NodeCache, |
| 411 | 412 | pub media: MediaCache, |
| ... | ... | @@ -456,6 +457,7 @@ impl Engine { |
| 456 | 457 | particles: crate::particles::ParticleCache::default(), |
| 457 | 458 | custom_shaders: crate::custom_shader::CustomShaderCache::new(), |
| 458 | 459 | sprite_cache: HashMap::new(), |
| 460 | ram_upload_tex: RefCell::new(None), | |
| 459 | 461 | dummy, |
| 460 | 462 | cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), |
| 461 | 463 | media: MediaCache::new(512), |
| ... | ... | @@ -469,6 +471,23 @@ impl Engine { |
| 469 | 471 | } |
| 470 | 472 | } |
| 471 | 473 | |
| 474 | pub fn new_with_device( | |
| 475 | device: std::sync::Arc<wgpu::Device>, | |
| 476 | queue: std::sync::Arc<wgpu::Queue>, | |
| 477 | vram_budget_bytes: u64, | |
| 478 | media_budget_bytes: u64, | |
| 479 | ) -> Self { | |
| 480 | let mut eng = Self::new((*device).clone(), (*queue).clone()); | |
| 481 | eng.cache.budget_bytes = vram_budget_bytes; | |
| 482 | let media_mb = if media_budget_bytes == 0 { | |
| 483 | 0 | |
| 484 | } else { | |
| 485 | media_budget_bytes.div_ceil(1024 * 1024) | |
| 486 | }; | |
| 487 | eng.media.set_budget_mb(media_mb); | |
| 488 | eng | |
| 489 | } | |
| 490 | ||
| 472 | 491 | pub fn new_headless() -> Result<Self, Box<dyn std::error::Error>> { |
| 473 | 492 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 474 | 493 | let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?; |
| ... | ... | @@ -616,21 +635,46 @@ impl Engine { |
| 616 | 635 | display: DisplaySettings, |
| 617 | 636 | ) -> EvalStats { |
| 618 | 637 | let t0 = Instant::now(); |
| 619 | let src = create_texture(&self.device, frame.size, 0); | |
| 620 | self.queue.write_texture( | |
| 621 | src.texture.as_image_copy(), | |
| 622 | &frame.rgba, | |
| 623 | wgpu::TexelCopyBufferLayout { | |
| 624 | offset: 0, | |
| 625 | bytes_per_row: Some(frame.size[0] * 4), | |
| 626 | rows_per_image: Some(frame.size[1]), | |
| 627 | }, | |
| 628 | wgpu::Extent3d { | |
| 629 | width: frame.size[0], | |
| 630 | height: frame.size[1], | |
| 631 | depth_or_array_layers: 1, | |
| 632 | }, | |
| 633 | ); | |
| 638 | let mut upload_slot = self.ram_upload_tex.borrow_mut(); | |
| 639 | let needs_alloc = upload_slot | |
| 640 | .as_ref() | |
| 641 | .is_none_or(|t| t.size != frame.size); | |
| 642 | if needs_alloc { | |
| 643 | let max_dim = self.device.limits().max_texture_dimension_2d.max(1); | |
| 644 | let (clamped, _) = crate::cache::clamp_dims_to_limit(frame.size[0], frame.size[1], max_dim); | |
| 645 | let tex = self.device.create_texture(&wgpu::TextureDescriptor { | |
| 646 | label: Some("ram-viewer-upload"), | |
| 647 | size: wgpu::Extent3d { | |
| 648 | width: clamped[0], | |
| 649 | height: clamped[1], | |
| 650 | depth_or_array_layers: 1, | |
| 651 | }, | |
| 652 | mip_level_count: 1, | |
| 653 | sample_count: 1, | |
| 654 | dimension: wgpu::TextureDimension::D2, | |
| 655 | format: wgpu::TextureFormat::Rgba8Unorm, | |
| 656 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, | |
| 657 | view_formats: &[], | |
| 658 | }); | |
| 659 | *upload_slot = Some(CachedTexture::from_texture(tex, clamped, 0)); | |
| 660 | } | |
| 661 | let src = upload_slot.as_ref().expect("ram upload texture initialized"); | |
| 662 | if src.size == frame.size { | |
| 663 | self.queue.write_texture( | |
| 664 | src.texture.as_image_copy(), | |
| 665 | &frame.rgba, | |
| 666 | wgpu::TexelCopyBufferLayout { | |
| 667 | offset: 0, | |
| 668 | bytes_per_row: Some(frame.size[0] * 4), | |
| 669 | rows_per_image: Some(frame.size[1]), | |
| 670 | }, | |
| 671 | wgpu::Extent3d { | |
| 672 | width: frame.size[0], | |
| 673 | height: frame.size[1], | |
| 674 | depth_or_array_layers: 1, | |
| 675 | }, | |
| 676 | ); | |
| 677 | } | |
| 634 | 678 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 635 | 679 | label: Some("comp-ram-viewer-blit"), |
| 636 | 680 | }); |
| ... | ... | @@ -674,11 +718,15 @@ impl Engine { |
| 674 | 718 | self.media.clear(); |
| 675 | 719 | self.particles.clear(); |
| 676 | 720 | self.sprite_cache.clear(); |
| 721 | *self.ram_upload_tex.borrow_mut() = None; | |
| 722 | io::clear_dims_cache(); | |
| 677 | 723 | } |
| 678 | 724 | |
| 679 | 725 | pub fn bust_gpu_cache(&mut self) { |
| 680 | 726 | self.cache.bust_all(); |
| 681 | 727 | self.output_cache.clear(); |
| 728 | self.sprite_cache.clear(); | |
| 729 | *self.ram_upload_tex.borrow_mut() = None; | |
| 682 | 730 | } |
| 683 | 731 | |
| 684 | 732 | pub fn bust_frame(&mut self, frame: i64) -> usize { |
| ... | ... | @@ -762,19 +810,11 @@ impl Engine { |
| 762 | 810 | let mut tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 763 | 811 | if tex.has_dod() { |
| 764 | 812 | // Crop expanded DoD cleanly back to logical canvas_size for final readback/export |
| 765 | let cropped = self.alloc_tex(tex.canvas_size, tex.depth, tex.content_hash ^ 0xD0D0); | |
| 766 | let mut params = UniformParams::default(); | |
| 767 | params.p[0] = [1.0, 1.0, 0.0, 0.0]; | |
| 768 | params.p[4] = [ | |
| 769 | tex.origin[0] as f32, | |
| 770 | tex.origin[1] as f32, | |
| 771 | tex.canvas_size[0] as f32, | |
| 772 | tex.canvas_size[1] as f32, | |
| 773 | ]; | |
| 774 | self.dispatch_op(&mut encoder, ShaderOp::DisplayBlit, &tex.view, &self.dummy.view, &self.dummy.view, &cropped, &params); | |
| 775 | tex = cropped; | |
| 813 | tex = self.crop_to_canvas(&mut encoder, tex); | |
| 776 | 814 | } |
| 777 | 815 | self.queue.submit(Some(encoder.finish())); |
| 816 | self.frame_memo.clear(); | |
| 817 | self.cache.flush_pending_pool(); | |
| 778 | 818 | |
| 779 | 819 | self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); |
| 780 | 820 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| ... | ... | @@ -844,6 +884,8 @@ impl Engine { |
| 844 | 884 | ); |
| 845 | 885 | |
| 846 | 886 | self.queue.submit(Some(encoder.finish())); |
| 887 | self.frame_memo.clear(); | |
| 888 | self.cache.flush_pending_pool(); | |
| 847 | 889 | |
| 848 | 890 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 849 | 891 | stats.cached_entries = self.cache.entry_count(); |
| ... | ... | @@ -937,23 +979,20 @@ impl Engine { |
| 937 | 979 | stats: &mut EvalStats, |
| 938 | 980 | ) -> CachedTexture { |
| 939 | 981 | let frame_i = time.round() as i64; |
| 940 | let is_mask_node = matches!( | |
| 941 | comp.node(id).kind.as_str(), | |
| 942 | "EllipseMask" | "RectangleMask" | "PolylineMask" | "PaintMask" | |
| 943 | ); | |
| 944 | let memo_sz = if is_mask_node { self.mask_target_size } else { None }; | |
| 982 | let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; | |
| 983 | let memo_sz = self.mask_target_size; | |
| 945 | 984 | // Always memoize within a single frame's DAG pass so diamond graphs never explode |
| 946 | 985 | // exponentially (even in CacheMode::Bypass, which bypasses the cross-frame cache). |
| 947 | if let Some(hit) = self.frame_memo.get(&(id, frame_i, memo_sz)).cloned() { | |
| 986 | if let Some(hit) = self.frame_memo.get(&(id, time_key, memo_sz)).cloned() { | |
| 948 | 987 | stats.cache_hits += 1; |
| 949 | 988 | return hit; |
| 950 | 989 | } |
| 951 | if !visiting.insert((id, frame_i)) { | |
| 990 | if !visiting.insert((id, time_key)) { | |
| 952 | 991 | return self.dummy.clone(); |
| 953 | 992 | } |
| 954 | 993 | let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats); |
| 955 | visiting.remove(&(id, frame_i)); | |
| 956 | self.frame_memo.insert((id, frame_i, memo_sz), res.clone()); | |
| 994 | visiting.remove(&(id, time_key)); | |
| 995 | self.frame_memo.insert((id, time_key, memo_sz), res.clone()); | |
| 957 | 996 | res |
| 958 | 997 | } |
| 959 | 998 | |
| ... | ... | @@ -1362,7 +1401,26 @@ pub fn create_texture_dod_fmt( |
| 1362 | 1401 | format: wgpu::TextureFormat, |
| 1363 | 1402 | content_hash: u64, |
| 1364 | 1403 | ) -> CachedTexture { |
| 1365 | let clamped = [size[0].max(1), size[1].max(1)]; | |
| 1404 | let max_dim = device.limits().max_texture_dimension_2d.max(1); | |
| 1405 | let (clamped, tex_scale) = crate::cache::clamp_dims_to_limit(size[0], size[1], max_dim); | |
| 1406 | let eff_origin = if tex_scale < 1.0 { | |
| 1407 | [ | |
| 1408 | (origin[0] as f32 * tex_scale).round() as i32, | |
| 1409 | (origin[1] as f32 * tex_scale).round() as i32, | |
| 1410 | ] | |
| 1411 | } else { | |
| 1412 | origin | |
| 1413 | }; | |
| 1414 | let eff_canvas = if size == canvas_size { | |
| 1415 | clamped | |
| 1416 | } else if tex_scale < 1.0 { | |
| 1417 | [ | |
| 1418 | ((canvas_size[0].max(1) as f32 * tex_scale).round() as u32).max(1), | |
| 1419 | ((canvas_size[1].max(1) as f32 * tex_scale).round() as u32).max(1), | |
| 1420 | ] | |
| 1421 | } else { | |
| 1422 | [canvas_size[0].max(1), canvas_size[1].max(1)] | |
| 1423 | }; | |
| 1366 | 1424 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 1367 | 1425 | label: Some("comp-tex"), |
| 1368 | 1426 | size: wgpu::Extent3d { |
| ... | ... | @@ -1381,14 +1439,16 @@ pub fn create_texture_dod_fmt( |
| 1381 | 1439 | | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 1382 | 1440 | view_formats: &[], |
| 1383 | 1441 | }); |
| 1384 | CachedTexture::from_texture_dod_depth( | |
| 1442 | let mut cached = CachedTexture::from_texture_dod_depth( | |
| 1385 | 1443 | tex, |
| 1386 | 1444 | clamped, |
| 1387 | origin, | |
| 1388 | [canvas_size[0].max(1), canvas_size[1].max(1)], | |
| 1445 | eff_origin, | |
| 1446 | eff_canvas, | |
| 1389 | 1447 | depth, |
| 1390 | 1448 | content_hash, |
| 1391 | ) | |
| 1449 | ); | |
| 1450 | cached.tex_scale = tex_scale; | |
| 1451 | cached | |
| 1392 | 1452 | } |
| 1393 | 1453 | |
| 1394 | 1454 | #[cfg(test)] |
| ... | ... | @@ -1517,4 +1577,233 @@ Composition { |
| 1517 | 1577 | let pl = eng.readback_rgba(&tl).unwrap(); |
| 1518 | 1578 | assert!(pl[2] > 240 && pl[0] < 15 && pl[1] < 15, "SwLegacy2 expected blue, got {:?}", &pl[..4]); |
| 1519 | 1579 | } |
| 1580 | ||
| 1581 | #[test] | |
| 1582 | fn frame_memo_distinguishes_subframe_times_within_same_rounded_frame() { | |
| 1583 | // BG1 animates TopLeftRed from 0.0 at t=9.0 to 1.0 at t=10.0. | |
| 1584 | // At t=10.0: BG1 is evaluated directly (red=1.0). | |
| 1585 | // At t=9.6 (via TimeSpeed Speed=0.96, Delay=0.0): time.round() is ALSO 10, | |
| 1586 | // so frame_memo keyed by rounded frame would wrongly return t=10.0's red=1.0! | |
| 1587 | let src = r#" | |
| 1588 | Composition { | |
| 1589 | CurrentTime = 10, | |
| 1590 | RenderRange = { 0, 20 }, | |
| 1591 | GlobalRange = { 0, 20 }, | |
| 1592 | Tools = ordered() { | |
| 1593 | AnimRed = BezierSpline { | |
| 1594 | KeyFrames = { | |
| 1595 | [9] = { 0.0, Flags = { Linear = true } }, | |
| 1596 | [10] = { 1.0, Flags = { Linear = true } }, | |
| 1597 | }, | |
| 1598 | }, | |
| 1599 | BG1 = Background { | |
| 1600 | Inputs = { | |
| 1601 | Width = Input { Value = 32, }, | |
| 1602 | Height = Input { Value = 32, }, | |
| 1603 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, | |
| 1604 | TopLeftAlpha = Input { Value = 1.0, }, | |
| 1605 | }, | |
| 1606 | }, | |
| 1607 | TS = TimeSpeed { | |
| 1608 | Inputs = { | |
| 1609 | Speed = Input { Value = 0.96, }, | |
| 1610 | Input = Input { SourceOp = "BG1", Source = "Output", }, | |
| 1611 | }, | |
| 1612 | }, | |
| 1613 | Out = Merge { | |
| 1614 | Inputs = { | |
| 1615 | Background = Input { SourceOp = "BG1", Source = "Output", }, | |
| 1616 | Foreground = Input { SourceOp = "TS", Source = "Output", }, | |
| 1617 | Size = Input { Value = 0.5, }, | |
| 1618 | }, | |
| 1619 | }, | |
| 1620 | }, | |
| 1621 | } | |
| 1622 | "#; | |
| 1623 | let comp = Comp::from_fusion_str(src).expect("parse subframe comp"); | |
| 1624 | let mut eng = Engine::new_headless().expect("gpu"); | |
| 1625 | let out_id = comp.find_node("Out").unwrap(); | |
| 1626 | let (tex, _) = eng.evaluate(&comp, out_id, 10.0); | |
| 1627 | assert_eq!(tex.size, [32, 32]); | |
| 1628 | let rgba = eng.readback_rgba(&tex).unwrap(); | |
| 1629 | // Corner pixel (0, 0) is BG1 at t=10.0 -> red ~255. | |
| 1630 | assert!(rgba[0] > 240, "corner pixel (BG1 @10.0) expected ~255, got {}", rgba[0]); | |
| 1631 | // Center pixel (16, 16) is TS (BG1 @9.6) -> red ~0.6 * 255 = 153! | |
| 1632 | let mid_idx = (16 * 32 + 16) * 4; | |
| 1633 | assert!( | |
| 1634 | (rgba[mid_idx] as i32 - 153).abs() <= 6, | |
| 1635 | "center pixel (BG1 @9.6) expected ~153, got {}", | |
| 1636 | rgba[mid_idx] | |
| 1637 | ); | |
| 1638 | // Also verify frame_memo was cleared after evaluate. | |
| 1639 | assert!(eng.frame_memo.is_empty()); | |
| 1640 | } | |
| 1641 | ||
| 1642 | #[test] | |
| 1643 | fn frame_memo_includes_mask_target_size_and_new_with_device_sets_budgets() { | |
| 1644 | let eng0 = Engine::new_headless().expect("gpu"); | |
| 1645 | let mut eng = Engine::new_with_device( | |
| 1646 | std::sync::Arc::new(eng0.device().clone()), | |
| 1647 | std::sync::Arc::new(eng0.queue().clone()), | |
| 1648 | 64 * 1024 * 1024, | |
| 1649 | 32 * 1024 * 1024, | |
| 1650 | ); | |
| 1651 | assert_eq!(eng.vram_budget_mb(), 64); | |
| 1652 | ||
| 1653 | let src = r#" | |
| 1654 | Composition { | |
| 1655 | CurrentTime = 0, | |
| 1656 | RenderRange = { 0, 1 }, | |
| 1657 | GlobalRange = { 0, 1 }, | |
| 1658 | Tools = ordered() { | |
| 1659 | MaskImg = Background { | |
| 1660 | Inputs = { | |
| 1661 | Width = Input { Value = 64, }, | |
| 1662 | Height = Input { Value = 64, }, | |
| 1663 | TopLeftRed = Input { Value = 1.0, }, | |
| 1664 | TopLeftAlpha = Input { Value = 1.0, }, | |
| 1665 | }, | |
| 1666 | }, | |
| 1667 | BM = BitmapMask { | |
| 1668 | Inputs = { | |
| 1669 | Image = Input { SourceOp = "MaskImg", Source = "Output", }, | |
| 1670 | }, | |
| 1671 | }, | |
| 1672 | SmallBG = Background { | |
| 1673 | Inputs = { | |
| 1674 | Width = Input { Value = 32, }, | |
| 1675 | Height = Input { Value = 32, }, | |
| 1676 | TopLeftGreen = Input { Value = 1.0, }, | |
| 1677 | TopLeftAlpha = Input { Value = 1.0, }, | |
| 1678 | EffectMask = Input { SourceOp = "BM", Source = "Mask", }, | |
| 1679 | }, | |
| 1680 | }, | |
| 1681 | LargeBG = Background { | |
| 1682 | Inputs = { | |
| 1683 | Width = Input { Value = 64, }, | |
| 1684 | Height = Input { Value = 64, }, | |
| 1685 | TopLeftBlue = Input { Value = 1.0, }, | |
| 1686 | TopLeftAlpha = Input { Value = 1.0, }, | |
| 1687 | EffectMask = Input { SourceOp = "BM", Source = "Mask", }, | |
| 1688 | }, | |
| 1689 | }, | |
| 1690 | Out = Merge { | |
| 1691 | Inputs = { | |
| 1692 | Background = Input { SourceOp = "LargeBG", Source = "Output", }, | |
| 1693 | Foreground = Input { SourceOp = "SmallBG", Source = "Output", }, | |
| 1694 | }, | |
| 1695 | }, | |
| 1696 | }, | |
| 1697 | } | |
| 1698 | "#; | |
| 1699 | let comp = Comp::from_fusion_str(src).expect("parse mask target size comp"); | |
| 1700 | let out_id = comp.find_node("Out").unwrap(); | |
| 1701 | let (tex, _) = eng.evaluate(&comp, out_id, 0.0); | |
| 1702 | assert_eq!(tex.size, [64, 64]); | |
| 1703 | assert!(eng.frame_memo.is_empty()); | |
| 1704 | } | |
| 1705 | ||
| 1706 | #[test] | |
| 1707 | fn display_blit_preserves_hdr_highlights_and_negatives_across_scale_and_crop() { | |
| 1708 | let src = r#" | |
| 1709 | Composition { | |
| 1710 | CurrentTime = 0, | |
| 1711 | RenderRange = { 0, 1 }, | |
| 1712 | GlobalRange = { 0, 1 }, | |
| 1713 | Prefs = { Comp = { FrameFormat = { Width = 8, Height = 8, DepthFull = 4 } } }, | |
| 1714 | Tools = ordered() { | |
| 1715 | BG1 = Background { | |
| 1716 | Inputs = { | |
| 1717 | Width = Input { Value = 8, }, | |
| 1718 | Height = Input { Value = 8, }, | |
| 1719 | Depth = Input { Value = 4, }, | |
| 1720 | TopLeftRed = Input { Value = 3.5, }, | |
| 1721 | TopLeftGreen = Input { Value = -0.25, }, | |
| 1722 | TopLeftBlue = Input { Value = 0.5, }, | |
| 1723 | TopLeftAlpha = Input { Value = 1.0, }, | |
| 1724 | }, | |
| 1725 | }, | |
| 1726 | SC = Scale { | |
| 1727 | Inputs = { | |
| 1728 | Input = Input { SourceOp = "BG1", Source = "Output", }, | |
| 1729 | XSize = Input { Value = 0.5, }, | |
| 1730 | YSize = Input { Value = 0.5, }, | |
| 1731 | }, | |
| 1732 | }, | |
| 1733 | }, | |
| 1734 | } | |
| 1735 | "#; | |
| 1736 | let comp = Comp::from_fusion_str(src).expect("parse hdr scale comp"); | |
| 1737 | let mut eng = Engine::new_headless().expect("gpu"); | |
| 1738 | let sc_id = comp.find_node("SC").unwrap(); | |
| 1739 | let (tex, _) = eng.evaluate(&comp, sc_id, 0.0); | |
| 1740 | assert!(tex.depth.is_float()); | |
| 1741 | ||
| 1742 | // Read raw float pixels from tex (Float32 or Float16) to verify > 1.0 and < 0.0 survived Scale's DisplayBlit! | |
| 1743 | let [w, h] = tex.size; | |
| 1744 | let bpp = if tex.format == wgpu::TextureFormat::Rgba32Float { 16u32 } else { 8u32 }; | |
| 1745 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; | |
| 1746 | let padded_bpr = (w * bpp).div_ceil(align) * align; | |
| 1747 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { | |
| 1748 | label: Some("hdr-readback"), | |
| 1749 | size: u64::from(padded_bpr) * u64::from(h), | |
| 1750 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, | |
| 1751 | mapped_at_creation: false, | |
| 1752 | }); | |
| 1753 | let mut enc = eng.device.create_command_encoder(&Default::default()); | |
| 1754 | enc.copy_texture_to_buffer( | |
| 1755 | tex.texture.as_image_copy(), | |
| 1756 | wgpu::TexelCopyBufferInfo { | |
| 1757 | buffer: &buf, | |
| 1758 | layout: wgpu::TexelCopyBufferLayout { | |
| 1759 | offset: 0, | |
| 1760 | bytes_per_row: Some(padded_bpr), | |
| 1761 | rows_per_image: Some(h), | |
| 1762 | }, | |
| 1763 | }, | |
| 1764 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, | |
| 1765 | ); | |
| 1766 | eng.queue.submit(Some(enc.finish())); | |
| 1767 | let slice = buf.slice(..); | |
| 1768 | let (tx, rx) = std::sync::mpsc::channel(); | |
| 1769 | slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); }); | |
| 1770 | eng.device.poll(wgpu::PollType::Wait { | |
| 1771 | submission_index: None, | |
| 1772 | timeout: Some(std::time::Duration::from_secs(5)), | |
| 1773 | }).unwrap(); | |
| 1774 | rx.recv().unwrap().unwrap(); | |
| 1775 | let data = slice.get_mapped_range().unwrap(); | |
| 1776 | let f16_to_f32 = |h: u16| -> f32 { | |
| 1777 | let sign = u32::from(h >> 15) << 31; | |
| 1778 | let exp = u32::from((h >> 10) & 0x1F); | |
| 1779 | let mant = u32::from(h & 0x3FF); | |
| 1780 | if exp == 0 { | |
| 1781 | if mant == 0 { | |
| 1782 | f32::from_bits(sign) | |
| 1783 | } else { | |
| 1784 | let mut m = mant; | |
| 1785 | let mut e = 127 - 14; | |
| 1786 | while (m & 0x400) == 0 { | |
| 1787 | m <<= 1; | |
| 1788 | e -= 1; | |
| 1789 | } | |
| 1790 | f32::from_bits(sign | (e << 23) | ((m & 0x3FF) << 13)) | |
| 1791 | } | |
| 1792 | } else if exp == 31 { | |
| 1793 | f32::from_bits(sign | 0x7F80_0000 | (mant << 13)) | |
| 1794 | } else { | |
| 1795 | f32::from_bits(sign | ((exp + 112) << 23) | (mant << 13)) | |
| 1796 | } | |
| 1797 | }; | |
| 1798 | let (r, g, b) = if tex.format == wgpu::TextureFormat::Rgba32Float { | |
| 1799 | let px: &[f32] = bytemuck::cast_slice(&data[..16]); | |
| 1800 | (px[0], px[1], px[2]) | |
| 1801 | } else { | |
| 1802 | let px: &[u16] = bytemuck::cast_slice(&data[..8]); | |
| 1803 | (f16_to_f32(px[0]), f16_to_f32(px[1]), f16_to_f32(px[2])) | |
| 1804 | }; | |
| 1805 | assert!((r - 3.5).abs() < 0.05, "expected HDR red ~3.5, got {r}"); | |
| 1806 | assert!((g - (-0.25)).abs() < 0.05, "expected negative HDR green ~-0.25, got {g}"); | |
| 1807 | assert!((b - 0.5).abs() < 0.05, "expected blue ~0.5, got {b}"); | |
| 1808 | } | |
| 1520 | 1809 | } |
crates/engine/src/eval/text_3d.rs+140-30| ... | ... | @@ -15,37 +15,53 @@ impl Engine { |
| 15 | 15 | ) -> CachedTexture { |
| 16 | 16 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32; |
| 17 | 17 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32; |
| 18 | let dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims }; | |
| 18 | let raw_dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims }; | |
| 19 | let max_dim = self.device.limits().max_texture_dimension_2d.max(1); | |
| 20 | let (dims, tex_scale) = crate::cache::clamp_dims_to_limit(raw_dims[0], raw_dims[1], max_dim); | |
| 19 | 21 | let dst_depth = self.node_depth(comp, node, time, None); |
| 22 | let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; | |
| 20 | 23 | |
| 21 | 24 | let bitmap_sources = crate::particles::collect_bitmap_sources(comp, node.id); |
| 22 | 25 | let mut sprites: HashMap<NodeId, crate::particles::SpriteImage> = HashMap::new(); |
| 23 | 26 | let mut sprite_hashes: Vec<(NodeId, u64)> = Vec::with_capacity(bitmap_sources.len()); |
| 27 | let mut pending_sprites: Vec<(NodeId, NodeId, CachedTexture)> = Vec::new(); | |
| 24 | 28 | |
| 25 | 29 | for (emitter_id, sprite_node_id) in bitmap_sources { |
| 26 | let spr_key = (sprite_node_id, comp.revision, frame_i); | |
| 27 | if let Some(cached) = self.sprite_cache.get(&spr_key).cloned() { | |
| 28 | sprite_hashes.push((emitter_id, (cached.size[0] as u64) << 32 | cached.size[1] as u64)); | |
| 30 | let spr_key = (sprite_node_id, comp.revision, time_key); | |
| 31 | if let Some((cached, spr_hash)) = self.sprite_cache.get(&spr_key).cloned() { | |
| 32 | sprite_hashes.push((emitter_id, spr_hash)); | |
| 29 | 33 | sprites.insert(emitter_id, cached); |
| 30 | 34 | continue; |
| 31 | 35 | } |
| 32 | let mut sprite_enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | |
| 33 | label: Some("particle-sprite-eval"), | |
| 34 | }); | |
| 35 | let mut sprite_vis = visiting.clone(); | |
| 36 | let sprite_tex = self.eval_node(comp, sprite_node_id, time, &mut sprite_enc, &mut sprite_vis, stats); | |
| 37 | self.queue.submit(Some(sprite_enc.finish())); | |
| 36 | let sprite_tex = self.eval_node(comp, sprite_node_id, time, enc, visiting, stats); | |
| 38 | 37 | sprite_hashes.push((emitter_id, sprite_tex.content_hash)); |
| 39 | if let Ok(rgba) = self.readback_rgba(&sprite_tex) { | |
| 40 | let spr = crate::particles::SpriteImage { | |
| 41 | size: sprite_tex.size, | |
| 42 | rgba, | |
| 43 | }; | |
| 44 | if self.sprite_cache.len() > 64 { | |
| 45 | self.sprite_cache.clear(); | |
| 38 | pending_sprites.push((emitter_id, sprite_node_id, sprite_tex)); | |
| 39 | } | |
| 40 | ||
| 41 | if !pending_sprites.is_empty() { | |
| 42 | // Flush the main encoder so even already-memoized upstream sprites are submitted | |
| 43 | // before `readback_rgba` maps their GPU memory. | |
| 44 | let flush_enc = std::mem::replace( | |
| 45 | enc, | |
| 46 | self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | |
| 47 | label: Some("comp-eval-post-particle-sprite"), | |
| 48 | }), | |
| 49 | ); | |
| 50 | self.queue.submit(Some(flush_enc.finish())); | |
| 51 | self.cache.flush_pending_pool(); | |
| 52 | for (emitter_id, sprite_node_id, sprite_tex) in pending_sprites { | |
| 53 | let spr_key = (sprite_node_id, comp.revision, time_key); | |
| 54 | if let Ok(rgba) = self.readback_rgba(&sprite_tex) { | |
| 55 | let spr = crate::particles::SpriteImage { | |
| 56 | size: sprite_tex.size, | |
| 57 | rgba, | |
| 58 | }; | |
| 59 | if self.sprite_cache.len() > 64 { | |
| 60 | self.sprite_cache.clear(); | |
| 61 | } | |
| 62 | self.sprite_cache.insert(spr_key, (spr.clone(), sprite_tex.content_hash)); | |
| 63 | sprites.insert(emitter_id, spr); | |
| 46 | 64 | } |
| 47 | self.sprite_cache.insert(spr_key, spr.clone()); | |
| 48 | sprites.insert(emitter_id, spr); | |
| 49 | 65 | } |
| 50 | 66 | } |
| 51 | 67 | |
| ... | ... | @@ -54,7 +70,7 @@ impl Engine { |
| 54 | 70 | self.cache.node_salt(node.id).hash(&mut h_key); |
| 55 | 71 | "pRender".hash(&mut h_key); |
| 56 | 72 | comp.revision.hash(&mut h_key); |
| 57 | frame_i.hash(&mut h_key); | |
| 73 | time_key.hash(&mut h_key); | |
| 58 | 74 | dims.hash(&mut h_key); |
| 59 | 75 | dst_depth.hash(&mut h_key); |
| 60 | 76 | sprite_hashes.hash(&mut h_key); |
| ... | ... | @@ -92,7 +108,7 @@ impl Engine { |
| 92 | 108 | }, |
| 93 | 109 | ); |
| 94 | 110 | |
| 95 | let out = if dst_depth != BitDepth::Int8 { | |
| 111 | let mut out = if dst_depth != BitDepth::Int8 { | |
| 96 | 112 | let promoted = self.alloc_tex(dims, dst_depth, key); |
| 97 | 113 | let u = UniformParams::default(); |
| 98 | 114 | self.dispatch_op(enc, ShaderOp::ChangeDepth, &base_tex.view, &self.dummy.view, &self.dummy.view, &promoted, &u); |
| ... | ... | @@ -100,6 +116,7 @@ impl Engine { |
| 100 | 116 | } else { |
| 101 | 117 | base_tex |
| 102 | 118 | }; |
| 119 | out.tex_scale = tex_scale; | |
| 103 | 120 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 104 | 121 | out |
| 105 | 122 | } |
| ... | ... | @@ -116,7 +133,9 @@ impl Engine { |
| 116 | 133 | ) -> CachedTexture { |
| 117 | 134 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; |
| 118 | 135 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; |
| 119 | let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; | |
| 136 | let raw_size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; | |
| 137 | let max_dim = self.device.limits().max_texture_dimension_2d.max(1); | |
| 138 | let (size, tex_scale) = crate::cache::clamp_dims_to_limit(raw_size[0], raw_size[1], max_dim); | |
| 120 | 139 | |
| 121 | 140 | let text_str = comp.eval_text(node, "StyledText", time, "", &self.expr); |
| 122 | 141 | let font_family = node.static_str("Font").unwrap_or("Helvetica Neue"); |
| ... | ... | @@ -434,12 +453,36 @@ impl Engine { |
| 434 | 453 | } |
| 435 | 454 | } |
| 436 | 455 | |
| 437 | let final_tex = create_texture_dod(&self.device, tex_size, origin, size, key); | |
| 456 | let mut final_tex = create_texture_dod(&self.device, tex_size, origin, size, key); | |
| 457 | let upload_pixels: std::borrow::Cow<'_, [u8]> = if final_tex.size != tex_size { | |
| 458 | if let Some(img_buf) = image::RgbaImage::from_raw(tex_size[0], tex_size[1], pixels) { | |
| 459 | let resized = image::imageops::resize( | |
| 460 | &img_buf, | |
| 461 | final_tex.size[0], | |
| 462 | final_tex.size[1], | |
| 463 | image::imageops::FilterType::Triangle, | |
| 464 | ); | |
| 465 | std::borrow::Cow::Owned(resized.into_raw()) | |
| 466 | } else { | |
| 467 | std::borrow::Cow::Owned(vec![0u8; (final_tex.size[0] * final_tex.size[1] * 4) as usize]) | |
| 468 | } | |
| 469 | } else { | |
| 470 | std::borrow::Cow::Owned(pixels) | |
| 471 | }; | |
| 472 | final_tex.tex_scale *= tex_scale; | |
| 438 | 473 | self.queue.write_texture( |
| 439 | 474 | final_tex.texture.as_image_copy(), |
| 440 | &pixels, | |
| 441 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) }, | |
| 442 | wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 }, | |
| 475 | &upload_pixels, | |
| 476 | wgpu::TexelCopyBufferLayout { | |
| 477 | offset: 0, | |
| 478 | bytes_per_row: Some(final_tex.size[0] * 4), | |
| 479 | rows_per_image: Some(final_tex.size[1]), | |
| 480 | }, | |
| 481 | wgpu::Extent3d { | |
| 482 | width: final_tex.size[0], | |
| 483 | height: final_tex.size[1], | |
| 484 | depth_or_array_layers: 1, | |
| 485 | }, | |
| 443 | 486 | ); |
| 444 | 487 | |
| 445 | 488 | self.cache.insert(key, final_tex.clone(), node.id, frame_i); |
| ... | ... | @@ -460,18 +503,23 @@ impl Engine { |
| 460 | 503 | ) -> CachedTexture { |
| 461 | 504 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; |
| 462 | 505 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; |
| 463 | let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; | |
| 506 | let raw_size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; | |
| 507 | let max_dim = self.device.limits().max_texture_dimension_2d.max(1); | |
| 508 | let (size, tex_scale) = crate::cache::clamp_dims_to_limit(raw_size[0], raw_size[1], max_dim); | |
| 464 | 509 | let aspect = (size[0] as f32 / size[1].max(1) as f32).max(1e-4); |
| 465 | 510 | |
| 466 | 511 | let Some(scene_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { |
| 467 | return create_texture(&self.device, size, 0); | |
| 512 | let mut empty = create_texture(&self.device, size, 0); | |
| 513 | empty.tex_scale = tex_scale; | |
| 514 | return empty; | |
| 468 | 515 | }; |
| 469 | 516 | |
| 470 | 517 | let lighting_enabled = comp.eval_number(node, "RendererSoftware.LightingEnabled", time, 0.0, &self.expr) > 0.5; |
| 471 | 518 | let mut cameras = Vec::new(); |
| 472 | 519 | let mut mesh_specs = Vec::new(); |
| 473 | 520 | let mut lights = crate::scene3d::SceneLights::default(); |
| 474 | crate::scene3d::collect_scene( | |
| 521 | let mut visited_nodes = Vec::new(); | |
| 522 | crate::scene3d::collect_scene_with_nodes( | |
| 475 | 523 | comp, |
| 476 | 524 | scene_id, |
| 477 | 525 | time, |
| ... | ... | @@ -481,6 +529,7 @@ impl Engine { |
| 481 | 529 | &mut cameras, |
| 482 | 530 | &mut mesh_specs, |
| 483 | 531 | &mut lights, |
| 532 | &mut visited_nodes, | |
| 484 | 533 | 0, |
| 485 | 534 | ); |
| 486 | 535 | |
| ... | ... | @@ -518,6 +567,12 @@ impl Engine { |
| 518 | 567 | hash_floats.push(sl.decay_type); |
| 519 | 568 | } |
| 520 | 569 | |
| 570 | let mut h_scene = DefaultHasher::new(); | |
| 571 | for vid in &visited_nodes { | |
| 572 | vid.hash(&mut h_scene); | |
| 573 | self.cache.node_salt(*vid).hash(&mut h_scene); | |
| 574 | } | |
| 575 | ||
| 521 | 576 | // First resolve all 2D textures & Text3D plates & Displace3D heightmaps |
| 522 | 577 | let mut pending_displace_tex: Vec<Option<(CachedTexture, f32, f32, i32)>> = Vec::with_capacity(mesh_specs.len()); |
| 523 | 578 | for ms in &mesh_specs { |
| ... | ... | @@ -531,6 +586,7 @@ impl Engine { |
| 531 | 586 | let dtex = self.eval_node(comp, ds.input_node, time, enc, visiting, stats); |
| 532 | 587 | (dtex, ds.scale, ds.bias, ds.channel) |
| 533 | 588 | }); |
| 589 | ms.shape.hash_into(&mut h_scene); | |
| 534 | 590 | upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash)); |
| 535 | 591 | upstream_hashes.push(disp_entry.as_ref().map_or(0, |(t, _, _, _)| t.content_hash)); |
| 536 | 592 | hash_floats.extend_from_slice(&ms.world); |
| ... | ... | @@ -559,6 +615,7 @@ impl Engine { |
| 559 | 615 | }); |
| 560 | 616 | pending_displace_tex.push(disp_entry); |
| 561 | 617 | } |
| 618 | upstream_hashes.push(h_scene.finish()); | |
| 562 | 619 | |
| 563 | 620 | let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats); |
| 564 | 621 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| ... | ... | @@ -577,6 +634,7 @@ impl Engine { |
| 577 | 634 | }), |
| 578 | 635 | ); |
| 579 | 636 | self.queue.submit(Some(flush_enc.finish())); |
| 637 | self.cache.flush_pending_pool(); | |
| 580 | 638 | for (dm, entry) in draw_meshes.iter_mut().zip(pending_displace_tex.into_iter()) { |
| 581 | 639 | if let Some((dtex, scale, bias, channel)) = entry { |
| 582 | 640 | if let Ok(rgba) = self.readback_rgba(&dtex) { |
| ... | ... | @@ -592,7 +650,8 @@ impl Engine { |
| 592 | 650 | } |
| 593 | 651 | } |
| 594 | 652 | |
| 595 | let dst = create_texture(&self.device, size, key); | |
| 653 | let mut dst = create_texture(&self.device, size, key); | |
| 654 | dst.tex_scale = tex_scale; | |
| 596 | 655 | self.scene3d.render_meshes( |
| 597 | 656 | &self.device, |
| 598 | 657 | &self.queue, |
| ... | ... | @@ -700,4 +759,55 @@ mod tests { |
| 700 | 759 | "LineSpacing 2.0 vs 1.0 on 320px wide frame should expand ~51px, got {diff}" |
| 701 | 760 | ); |
| 702 | 761 | } |
| 762 | ||
| 763 | #[test] | |
| 764 | fn renderer3d_invalidates_cache_when_shape3d_radius_animates() { | |
| 765 | let src = r#" | |
| 766 | Composition { | |
| 767 | CurrentTime = 0, | |
| 768 | RenderRange = { 0, 10 }, | |
| 769 | GlobalRange = { 0, 10 }, | |
| 770 | Tools = ordered() { | |
| 771 | RadAnim = BezierSpline { | |
| 772 | KeyFrames = { | |
| 773 | [0] = { 0.2, Flags = { Linear = true } }, | |
| 774 | [5] = { 1.6, Flags = { Linear = true } }, | |
| 775 | }, | |
| 776 | }, | |
| 777 | Sphere1 = Shape3D { | |
| 778 | Inputs = { | |
| 779 | Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, | |
| 780 | ["SurfaceSphereInputs.Radius"] = Input { SourceOp = "RadAnim", Source = "Value", }, | |
| 781 | ["Transform3DOp.Translate.Z"] = Input { Value = -3.0, }, | |
| 782 | }, | |
| 783 | }, | |
| 784 | R3D = Renderer3D { | |
| 785 | Inputs = { | |
| 786 | Width = Input { Value = 64, }, | |
| 787 | Height = Input { Value = 64, }, | |
| 788 | SceneInput = Input { SourceOp = "Sphere1", Source = "Output", }, | |
| 789 | }, | |
| 790 | }, | |
| 791 | }, | |
| 792 | } | |
| 793 | "#; | |
| 794 | let comp = Comp::from_fusion_str(src).expect("parse Renderer3D animated radius comp"); | |
| 795 | let Ok(mut eng) = Engine::new_headless() else { | |
| 796 | return; | |
| 797 | }; | |
| 798 | let r3d = comp.find_node("R3D").unwrap(); | |
| 799 | let (t0, _) = eng.evaluate(&comp, r3d, 0.0); | |
| 800 | let p0 = eng.readback_rgba(&t0).unwrap(); | |
| 801 | let (t5, _) = eng.evaluate(&comp, r3d, 5.0); | |
| 802 | let p5 = eng.readback_rgba(&t5).unwrap(); | |
| 803 | ||
| 804 | let cov = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 16).count(); | |
| 805 | let c0 = cov(&p0); | |
| 806 | let c5 = cov(&p5); | |
| 807 | assert!(c0 > 10, "frame 0 small sphere should be visible, got {c0} pixels"); | |
| 808 | assert!( | |
| 809 | c5 > c0 * 2, | |
| 810 | "frame 5 larger Radius must invalidate Renderer3D cache and cover far more pixels (f0={c0}, f5={c5})" | |
| 811 | ); | |
| 812 | } | |
| 703 | 813 | } |
crates/engine/src/scene3d/collect.rs+56-18| ... | ... | @@ -44,6 +44,38 @@ pub fn collect_scene( |
| 44 | 44 | meshes: &mut Vec<MeshInstance>, |
| 45 | 45 | lights: &mut SceneLights, |
| 46 | 46 | depth: usize, |
| 47 | ) { | |
| 48 | let mut visited = Vec::new(); | |
| 49 | collect_scene_with_nodes( | |
| 50 | comp, | |
| 51 | node_id, | |
| 52 | time, | |
| 53 | expr, | |
| 54 | parent_xform, | |
| 55 | render_aspect, | |
| 56 | cameras, | |
| 57 | meshes, | |
| 58 | lights, | |
| 59 | &mut visited, | |
| 60 | depth, | |
| 61 | ); | |
| 62 | } | |
| 63 | ||
| 64 | /// Recursively traverses a Fusion 3D scene graph and records every visited 3D/material `NodeId` | |
| 65 | /// in `visited` so callers (`Renderer3D`) can include each visited node's `node_salt` in cache keys. | |
| 66 | #[allow(clippy::too_many_arguments)] | |
| 67 | pub fn collect_scene_with_nodes( | |
| 68 | comp: &Comp, | |
| 69 | node_id: NodeId, | |
| 70 | time: f64, | |
| 71 | expr: &ExprEngine, | |
| 72 | parent_xform: Mat4, | |
| 73 | render_aspect: f32, | |
| 74 | cameras: &mut Vec<CameraInstance>, | |
| 75 | meshes: &mut Vec<MeshInstance>, | |
| 76 | lights: &mut SceneLights, | |
| 77 | visited: &mut Vec<NodeId>, | |
| 78 | depth: usize, | |
| 47 | 79 | ) { |
| 48 | 80 | collect_scene_inner( |
| 49 | 81 | comp, |
| ... | ... | @@ -56,6 +88,7 @@ pub fn collect_scene( |
| 56 | 88 | cameras, |
| 57 | 89 | meshes, |
| 58 | 90 | lights, |
| 91 | visited, | |
| 59 | 92 | depth, |
| 60 | 93 | ); |
| 61 | 94 | } |
| ... | ... | @@ -72,11 +105,13 @@ fn collect_scene_inner( |
| 72 | 105 | cameras: &mut Vec<CameraInstance>, |
| 73 | 106 | meshes: &mut Vec<MeshInstance>, |
| 74 | 107 | lights: &mut SceneLights, |
| 108 | visited: &mut Vec<NodeId>, | |
| 75 | 109 | depth: usize, |
| 76 | 110 | ) { |
| 77 | 111 | if depth > 32 { |
| 78 | 112 | return; |
| 79 | 113 | } |
| 114 | visited.push(node_id); | |
| 80 | 115 | let node = comp.node(node_id); |
| 81 | 116 | if node.bypassed { |
| 82 | 117 | return; |
| ... | ... | @@ -94,7 +129,7 @@ fn collect_scene_inner( |
| 94 | 129 | input_names.sort(); |
| 95 | 130 | for in_name in input_names { |
| 96 | 131 | if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { |
| 97 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | |
| 132 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | |
| 98 | 133 | } |
| 99 | 134 | } |
| 100 | 135 | } |
| ... | ... | @@ -104,7 +139,7 @@ fn collect_scene_inner( |
| 104 | 139 | next_ovr.material_override = Some(mid); |
| 105 | 140 | } |
| 106 | 141 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { |
| 107 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | |
| 142 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); | |
| 108 | 143 | } |
| 109 | 144 | } |
| 110 | 145 | "Override3D" => { |
| ... | ... | @@ -120,7 +155,7 @@ fn collect_scene_inner( |
| 120 | 155 | next_ovr.affected_by_lights = Some(is_lit); |
| 121 | 156 | } |
| 122 | 157 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { |
| 123 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | |
| 158 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); | |
| 124 | 159 | } |
| 125 | 160 | } |
| 126 | 161 | "ReplaceNormals3D" => { |
| ... | ... | @@ -129,7 +164,7 @@ fn collect_scene_inner( |
| 129 | 164 | next_ovr.flip_normals = !next_ovr.flip_normals; |
| 130 | 165 | } |
| 131 | 166 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { |
| 132 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | |
| 167 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); | |
| 133 | 168 | } |
| 134 | 169 | } |
| 135 | 170 | "Displace3D" => { |
| ... | ... | @@ -146,7 +181,7 @@ fn collect_scene_inner( |
| 146 | 181 | }); |
| 147 | 182 | } |
| 148 | 183 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { |
| 149 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | |
| 184 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); | |
| 150 | 185 | } |
| 151 | 186 | } |
| 152 | 187 | "Duplicate3D" => { |
| ... | ... | @@ -185,7 +220,7 @@ fn collect_scene_inner( |
| 185 | 220 | let jm = mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)))); |
| 186 | 221 | m = mat4_mul(m, jm); |
| 187 | 222 | } |
| 188 | collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, depth + 1); | |
| 223 | collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | |
| 189 | 224 | acc = mat4_mul(acc, step); |
| 190 | 225 | } |
| 191 | 226 | } |
| ... | ... | @@ -278,7 +313,7 @@ fn collect_scene_inner( |
| 278 | 313 | .or_else(|| node.connected_node("SceneInput")) |
| 279 | 314 | .and_then(|s| comp.find_node(s)) |
| 280 | 315 | }); |
| 281 | let mat = resolve_material(comp, mat_node, time, expr); | |
| 316 | let mat = resolve_material(comp, mat_node, time, expr, visited); | |
| 282 | 317 | meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own)); |
| 283 | 318 | } |
| 284 | 319 | "Shape3D" => { |
| ... | ... | @@ -318,7 +353,7 @@ fn collect_scene_inner( |
| 318 | 353 | node.connected_node("MaterialInput") |
| 319 | 354 | .and_then(|s| comp.find_node(s)) |
| 320 | 355 | }); |
| 321 | let mut mat = resolve_material(comp, mat_node, time, expr); | |
| 356 | let mut mat = resolve_material(comp, mat_node, time, expr, visited); | |
| 322 | 357 | if mat_node.is_none() { |
| 323 | 358 | apply_mtl_std(&mut mat, comp, node, "", time, expr); |
| 324 | 359 | } |
| ... | ... | @@ -337,7 +372,7 @@ fn collect_scene_inner( |
| 337 | 372 | node.connected_node(&format!("{face}MaterialInput")) |
| 338 | 373 | .and_then(|s| comp.find_node(s)) |
| 339 | 374 | }); |
| 340 | let mut mat = resolve_material(comp, mat_node, time, expr); | |
| 375 | let mut mat = resolve_material(comp, mat_node, time, expr, visited); | |
| 341 | 376 | if mat_node.is_none() { |
| 342 | 377 | apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr); |
| 343 | 378 | } |
| ... | ... | @@ -352,7 +387,7 @@ fn collect_scene_inner( |
| 352 | 387 | } |
| 353 | 388 | } |
| 354 | 389 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { |
| 355 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | |
| 390 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | |
| 356 | 391 | } |
| 357 | 392 | } |
| 358 | 393 | "SurfaceFBXMesh" => { |
| ... | ... | @@ -375,14 +410,14 @@ fn collect_scene_inner( |
| 375 | 410 | }) |
| 376 | 411 | .and_then(|s| comp.find_node(s)) |
| 377 | 412 | }); |
| 378 | let mut mat = resolve_material(comp, mat_node, time, expr); | |
| 413 | let mut mat = resolve_material(comp, mat_node, time, expr, visited); | |
| 379 | 414 | if mat_node.is_none() { |
| 380 | 415 | apply_mtl_std(&mut mat, comp, node, "", time, expr); |
| 381 | 416 | } |
| 382 | 417 | meshes.push(make_mesh_instance(world, shape, mat, None, &own)); |
| 383 | 418 | } |
| 384 | 419 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { |
| 385 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | |
| 420 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | |
| 386 | 421 | } |
| 387 | 422 | } |
| 388 | 423 | "Text3D" => { |
| ... | ... | @@ -391,7 +426,7 @@ fn collect_scene_inner( |
| 391 | 426 | node.connected_node("MaterialInput") |
| 392 | 427 | .and_then(|s| comp.find_node(s)) |
| 393 | 428 | }); |
| 394 | let mut mat = resolve_material(comp, mat_node, time, expr); | |
| 429 | let mut mat = resolve_material(comp, mat_node, time, expr, visited); | |
| 395 | 430 | if mat_node.is_none() { |
| 396 | 431 | mat.diffuse_col = [1.0, 1.0, 1.0, 1.0]; |
| 397 | 432 | } |
| ... | ... | @@ -406,7 +441,7 @@ fn collect_scene_inner( |
| 406 | 441 | } |
| 407 | 442 | "MacroOperator" | "GroupOperator" => { |
| 408 | 443 | if let Some(out_id) = node.macro_output { |
| 409 | collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | |
| 444 | collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | |
| 410 | 445 | } |
| 411 | 446 | } |
| 412 | 447 | _ => {} |
| ... | ... | @@ -548,8 +583,9 @@ fn resolve_material( |
| 548 | 583 | mat_node: Option<NodeId>, |
| 549 | 584 | time: f64, |
| 550 | 585 | expr: &ExprEngine, |
| 586 | visited: &mut Vec<NodeId>, | |
| 551 | 587 | ) -> ResolvedMaterial { |
| 552 | resolve_material_inner(comp, mat_node, time, expr, 0) | |
| 588 | resolve_material_inner(comp, mat_node, time, expr, visited, 0) | |
| 553 | 589 | } |
| 554 | 590 | |
| 555 | 591 | fn resolve_material_inner( |
| ... | ... | @@ -557,6 +593,7 @@ fn resolve_material_inner( |
| 557 | 593 | mat_node: Option<NodeId>, |
| 558 | 594 | time: f64, |
| 559 | 595 | expr: &ExprEngine, |
| 596 | visited: &mut Vec<NodeId>, | |
| 560 | 597 | depth: usize, |
| 561 | 598 | ) -> ResolvedMaterial { |
| 562 | 599 | let default_mat = ResolvedMaterial::default(); |
| ... | ... | @@ -566,6 +603,7 @@ fn resolve_material_inner( |
| 566 | 603 | let Some(mid) = mat_node else { |
| 567 | 604 | return default_mat; |
| 568 | 605 | }; |
| 606 | visited.push(mid); | |
| 569 | 607 | let n = comp.node(mid); |
| 570 | 608 | match n.kind.as_str() { |
| 571 | 609 | "Texture2DOperator" => { |
| ... | ... | @@ -582,7 +620,7 @@ fn resolve_material_inner( |
| 582 | 620 | } |
| 583 | 621 | "TextureTransformOperator" => { |
| 584 | 622 | let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s)); |
| 585 | let mut mat = resolve_material_inner(comp, inner_id, time, expr, depth + 1); | |
| 623 | let mut mat = resolve_material_inner(comp, inner_id, time, expr, visited, depth + 1); | |
| 586 | 624 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; |
| 587 | 625 | let xf = texture_transform_uv( |
| 588 | 626 | [f("Translation.U", 0.0), f("Translation.V", 0.0)], |
| ... | ... | @@ -622,11 +660,11 @@ fn resolve_material_inner( |
| 622 | 660 | .connected_node("Diffuse.Color.Material") |
| 623 | 661 | .or_else(|| n.connected_node("MaterialInput")) |
| 624 | 662 | .and_then(|s| comp.find_node(s)); |
| 625 | let diff_mat = resolve_material_inner(comp, diff_in, time, expr, depth + 1); | |
| 663 | let diff_mat = resolve_material_inner(comp, diff_in, time, expr, visited, depth + 1); | |
| 626 | 664 | let bump_in = n |
| 627 | 665 | .connected_node("Bumpmap.Material") |
| 628 | 666 | .and_then(|s| comp.find_node(s)); |
| 629 | let bump_mat = bump_in.map(|bid| resolve_material_inner(comp, Some(bid), time, expr, depth + 1)); | |
| 667 | let bump_mat = bump_in.map(|bid| resolve_material_inner(comp, Some(bid), time, expr, visited, depth + 1)); | |
| 630 | 668 | |
| 631 | 669 | let col = [ |
| 632 | 670 | comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, |
crates/engine/src/scene3d/mod.rs+81-1| ... | ... | @@ -12,7 +12,7 @@ mod math; |
| 12 | 12 | mod mesh; |
| 13 | 13 | mod shader; |
| 14 | 14 | |
| 15 | pub use collect::{collect_scene, eval_transform3d}; | |
| 15 | pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d}; | |
| 16 | 16 | pub use math::{ |
| 17 | 17 | mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y, |
| 18 | 18 | mat4_rot_z, mat4_scale, mat4_translate, |
| ... | ... | @@ -91,6 +91,16 @@ impl UvAffine { |
| 91 | 91 | t: o, |
| 92 | 92 | } |
| 93 | 93 | } |
| 94 | ||
| 95 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { | |
| 96 | use std::hash::Hash; | |
| 97 | for v in self.m { | |
| 98 | v.to_bits().hash(h); | |
| 99 | } | |
| 100 | for v in self.t { | |
| 101 | v.to_bits().hash(h); | |
| 102 | } | |
| 103 | } | |
| 94 | 104 | } |
| 95 | 105 | |
| 96 | 106 | /// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for |
| ... | ... | @@ -136,6 +146,21 @@ impl Default for MaterialFx { |
| 136 | 146 | } |
| 137 | 147 | } |
| 138 | 148 | |
| 149 | impl MaterialFx { | |
| 150 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { | |
| 151 | use std::hash::Hash; | |
| 152 | self.uv.hash_into(h); | |
| 153 | self.uv_wrap.hash(h); | |
| 154 | self.bump_scale.to_bits().hash(h); | |
| 155 | self.bump_mode.hash(h); | |
| 156 | self.bump_only.hash(h); | |
| 157 | (self.spec_model as u8).hash(h); | |
| 158 | self.wireframe.hash(h); | |
| 159 | self.cull_back.hash(h); | |
| 160 | self.cull_front.hash(h); | |
| 161 | } | |
| 162 | } | |
| 163 | ||
| 139 | 164 | impl ShapeKind { |
| 140 | 165 | /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper. |
| 141 | 166 | pub fn base_shape(&self) -> &ShapeKind { |
| ... | ... | @@ -148,6 +173,61 @@ impl ShapeKind { |
| 148 | 173 | other => (other, MaterialFx::default()), |
| 149 | 174 | } |
| 150 | 175 | } |
| 176 | ||
| 177 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { | |
| 178 | use std::hash::Hash; | |
| 179 | match self { | |
| 180 | ShapeKind::ImagePlane => 0u8.hash(h), | |
| 181 | ShapeKind::Sphere { radius, sub_base, sub_height } => { | |
| 182 | 1u8.hash(h); | |
| 183 | radius.to_bits().hash(h); | |
| 184 | sub_base.hash(h); | |
| 185 | sub_height.hash(h); | |
| 186 | } | |
| 187 | ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base } => { | |
| 188 | 2u8.hash(h); | |
| 189 | radius.to_bits().hash(h); | |
| 190 | height.to_bits().hash(h); | |
| 191 | start_sweep_deg.to_bits().hash(h); | |
| 192 | end_sweep_deg.to_bits().hash(h); | |
| 193 | sub_base.hash(h); | |
| 194 | } | |
| 195 | ShapeKind::Plane { width, height, sub_w, sub_h } => { | |
| 196 | 3u8.hash(h); | |
| 197 | width.to_bits().hash(h); | |
| 198 | height.to_bits().hash(h); | |
| 199 | sub_w.hash(h); | |
| 200 | sub_h.hash(h); | |
| 201 | } | |
| 202 | ShapeKind::Cube { width, sub, faces } => { | |
| 203 | 4u8.hash(h); | |
| 204 | width.to_bits().hash(h); | |
| 205 | sub.hash(h); | |
| 206 | faces.hash(h); | |
| 207 | } | |
| 208 | ShapeKind::TextPlate { width, height, depth, slices } => { | |
| 209 | 5u8.hash(h); | |
| 210 | width.to_bits().hash(h); | |
| 211 | height.to_bits().hash(h); | |
| 212 | depth.to_bits().hash(h); | |
| 213 | slices.hash(h); | |
| 214 | } | |
| 215 | ShapeKind::CustomMesh(verts) => { | |
| 216 | 6u8.hash(h); | |
| 217 | verts.len().hash(h); | |
| 218 | (verts.as_ptr() as usize).hash(h); | |
| 219 | let step = (verts.len() / 64).max(1); | |
| 220 | for v in verts.iter().step_by(step) { | |
| 221 | bytemuck::bytes_of(v).hash(h); | |
| 222 | } | |
| 223 | } | |
| 224 | ShapeKind::WithMaterialFx { inner, fx } => { | |
| 225 | 7u8.hash(h); | |
| 226 | inner.hash_into(h); | |
| 227 | fx.hash_into(h); | |
| 228 | } | |
| 229 | } | |
| 230 | } | |
| 151 | 231 | } |
| 152 | 232 | |
| 153 | 233 | #[derive(Clone, Debug)] |
crates/engine/src/shaders/composite.wgsl+8-2| ... | ... | @@ -486,7 +486,13 @@ fn display_blit_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 486 | 486 | } else if (ch == 4) { |
| 487 | 487 | out_col = vec4<f32>(src.a, src.a, src.a, 1.0); |
| 488 | 488 | } else { |
| 489 | var rgb = pow(max(src.rgb * exp_mul, vec3<f32>(0.0)), vec3<f32>(inv_gamma)); | |
| 489 | let is_identity_grade = abs(exp_mul - 1.0) < 1e-5 && abs(u.p[0].y - 1.0) < 1e-5; | |
| 490 | var rgb: vec3<f32>; | |
| 491 | if (is_identity_grade) { | |
| 492 | rgb = src.rgb; | |
| 493 | } else { | |
| 494 | rgb = pow(max(src.rgb * exp_mul, vec3<f32>(0.0)), vec3<f32>(inv_gamma)); | |
| 495 | } | |
| 490 | 496 | if (checker) { |
| 491 | 497 | let cx = (gid.x / 16u) & 1u; |
| 492 | 498 | let cy = (gid.y / 16u) & 1u; |
| ... | ... | @@ -497,7 +503,7 @@ fn display_blit_op(@builtin(global_invocation_id) gid: vec3<u32>) { |
| 497 | 503 | out_col = vec4<f32>(rgb, src.a); |
| 498 | 504 | } |
| 499 | 505 | } |
| 500 | textureStore(dst_tex, vec2<i32>(gid.xy), clamp(out_col, vec4<f32>(0.0), vec4<f32>(1.0))); | |
| 506 | store_dst(vec2<i32>(gid.xy), out_col); | |
| 501 | 507 | } |
| 502 | 508 | // ============================================================================ |
| 503 | 509 | // 17b. ChannelBoolean (full Fusion Operation + per-channel ToRed/Green/Blue/Alpha) |