authoravatarclover caruso<git@paperclover.net>2026-11-30 20:23:42-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:40:12-08:00
log5432bcf4b7db251c55263591b6ccf9d81738923c
treea5578697a92d4c738b28f26e2ce882341e7ece98
parent0e7a2c62afd19b813b5077fad79c34ab0389ebe4
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix engine cache keys, frame_memo sub-frame/mask keys, HDR blit, texture clamp, and safety P0s


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,6 +59,22 @@ fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 {
59 .saturating_mul(bytes_per_pixel(format))59 .saturating_mul(bytes_per_pixel(format))
60}60}
6161
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).
64pub(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
62impl CachedTexture {78impl CachedTexture {
63 pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self {79 pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self {
64 Self::from_texture_dod(texture, size, [0, 0], size, content_hash)80 Self::from_texture_dod(texture, size, [0, 0], size, content_hash)
...@@ -343,6 +359,9 @@ pub struct NodeCache {...@@ -343,6 +359,9 @@ pub struct NodeCache {
343 /// Per-node salt bumped when surgically busting a subtree.359 /// Per-node salt bumped when surgically busting a subtree.
344 node_salts: HashMap<NodeId, u64>,360 node_salts: HashMap<NodeId, u64>,
345 pool: Mutex<TexturePool>,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 profiler: Option<ProfileRecorder>,365 profiler: Option<ProfileRecorder>,
347}366}
348367
...@@ -358,6 +377,7 @@ impl NodeCache {...@@ -358,6 +377,7 @@ impl NodeCache {
358 gpu_salt: 0,377 gpu_salt: 0,
359 node_salts: HashMap::new(),378 node_salts: HashMap::new(),
360 pool: Mutex::new(TexturePool::new()),379 pool: Mutex::new(TexturePool::new()),
380 pending_pool: Vec::new(),
361 profiler: None,381 profiler: None,
362 }382 }
363 }383 }
...@@ -416,6 +436,8 @@ impl NodeCache {...@@ -416,6 +436,8 @@ impl NodeCache {
416436
417 /// Acquires a GPU texture matching `(width, height, format, usage)` from the pool if an437 /// Acquires a GPU texture matching `(width, height, format, usage)` from the pool if an
418 /// exclusively-owned texture is available, otherwise allocates a fresh one on `device`.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 pub fn acquire_texture(441 pub fn acquire_texture(
420 &self,442 &self,
421 device: &wgpu::Device,443 device: &wgpu::Device,
...@@ -424,7 +446,8 @@ impl NodeCache {...@@ -424,7 +446,8 @@ impl NodeCache {
424 format: wgpu::TextureFormat,446 format: wgpu::TextureFormat,
425 usage: wgpu::TextureUsages,447 usage: wgpu::TextureUsages,
426 ) -> CachedTexture {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 let bytes = texture_bytes(clamped, format);451 let bytes = texture_bytes(clamped, format);
429 let key = TexturePoolKey {452 let key = TexturePoolKey {
430 width: clamped[0],453 width: clamped[0],
...@@ -438,7 +461,7 @@ impl NodeCache {...@@ -438,7 +461,7 @@ impl NodeCache {
438 let mut pool = self.pool.lock().expect("texture pool lock");461 let mut pool = self.pool.lock().expect("texture pool lock");
439 if let Some((texture, view, pooled_bytes)) = pool.pop(key) {462 if let Some((texture, view, pooled_bytes)) = pool.pop(key) {
440 pool.hits += 1;463 pool.hits += 1;
441 return CachedTexture::from_parts(464 let mut tex = CachedTexture::from_parts(
442 texture,465 texture,
443 view,466 view,
444 clamped,467 clamped,
...@@ -449,6 +472,8 @@ impl NodeCache {...@@ -449,6 +472,8 @@ impl NodeCache {
449 0,472 0,
450 pooled_bytes,473 pooled_bytes,
451 );474 );
475 tex.tex_scale = tex_scale;
476 return tex;
452 }477 }
453 pool.misses += 1;478 pool.misses += 1;
454 // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget.479 // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget.
...@@ -478,7 +503,9 @@ impl NodeCache {...@@ -478,7 +503,9 @@ impl NodeCache {
478 usage,503 usage,
479 view_formats: &[],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 }
483510
484 /// Pool-backed DoD texture allocation matching `create_texture_dod_fmt` semantics.511 /// Pool-backed DoD texture allocation matching `create_texture_dod_fmt` semantics.
...@@ -500,8 +527,24 @@ impl NodeCache {...@@ -500,8 +527,24 @@ impl NodeCache {
500 format,527 format,
501 Self::default_texture_usage(),528 Self::default_texture_usage(),
502 );529 );
503 tex.origin = origin;530 tex.origin = if tex.tex_scale < 1.0 {
504 tex.canvas_size = [canvas_size[0].max(1), canvas_size[1].max(1)];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 tex.depth = depth;548 tex.depth = depth;
506 tex.content_hash = content_hash;549 tex.content_hash = content_hash;
507 tex550 tex
...@@ -553,7 +596,7 @@ impl NodeCache {...@@ -553,7 +596,7 @@ impl NodeCache {
553 if let Some(old) = self.entries.remove(&key) {596 if let Some(old) = self.entries.remove(&key) {
554 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);597 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);
555 if !Arc::ptr_eq(&old.tex.texture, &tex.texture) {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 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);602 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);
...@@ -576,6 +619,54 @@ impl NodeCache {...@@ -576,6 +619,54 @@ impl NodeCache {
576 self.trim_pool_to_budget();619 self.trim_pool_to_budget();
577 }620 }
578621
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 fn return_to_pool(&self, tex: &CachedTexture) {670 fn return_to_pool(&self, tex: &CachedTexture) {
580 if tex.bytes == 0 || tex.bytes > self.budget_bytes {671 if tex.bytes == 0 || tex.bytes > self.budget_bytes {
581 return;672 return;
...@@ -607,14 +698,7 @@ impl NodeCache {...@@ -607,14 +698,7 @@ impl NodeCache {
607 if let Some(removed) = self.entries.remove(&oldest_key) {698 if let Some(removed) = self.entries.remove(&oldest_key) {
608 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);699 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
609 self.evictions += 1;700 self.evictions += 1;
610 if self701 self.defer_to_pool(removed.tex);
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 }
618 }702 }
619 }703 }
620 }704 }
...@@ -628,10 +712,16 @@ impl NodeCache {...@@ -628,10 +712,16 @@ impl NodeCache {
628 pub fn clear_dynamic(&mut self) -> usize {712 pub fn clear_dynamic(&mut self) -> usize {
629 let count = self.entries.len();713 let count = self.entries.len();
630 let drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();714 let drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();
715 let pending = std::mem::take(&mut self.pending_pool);
631 self.total_bytes = 0;716 self.total_bytes = 0;
632 self.gpu_salt += 1;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 let mut pool = self.pool.lock().expect("texture pool lock");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 for entry in drained {725 for entry in drained {
636 if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes {726 if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes {
637 pool.push(&entry.tex);727 pool.push(&entry.tex);
...@@ -852,4 +942,63 @@ mod tests {...@@ -852,4 +942,63 @@ mod tests {
852 assert_eq!(p_warm.entries.len(), 1);942 assert_eq!(p_warm.entries.len(), 1);
853 assert!(p_warm.entries[0].cache_hit);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,15 +197,12 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> {
197 *pos += 1; // consume opening '"'197 *pos += 1; // consume opening '"'
198 let mut out = String::new();198 let mut out = String::new();
199 while *pos < bytes.len() {199 while *pos < bytes.len() {
200 let ch = src[*pos..].chars().next()?;200 let ch = src.get(*pos..)?.chars().next()?;
201 *pos += ch.len_utf8();201 *pos += ch.len_utf8();
202 match ch {202 match ch {
203 '"' => return Some(out),203 '"' => return Some(out),
204 '\\' => {204 '\\' => {
205 if *pos >= bytes.len() {205 let esc = src.get(*pos..)?.chars().next()?;
206 return None;
207 }
208 let esc = src[*pos..].chars().next()?;
209 *pos += esc.len_utf8();206 *pos += esc.len_utf8();
210 match esc {207 match esc {
211 '"' => out.push('"'),208 '"' => out.push('"'),
...@@ -220,7 +217,7 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> {...@@ -220,7 +217,7 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> {
220 let code_unit = parse_hex4(src, pos)?;217 let code_unit = parse_hex4(src, pos)?;
221 if (0xD800..=0xDBFF).contains(&code_unit) {218 if (0xD800..=0xDBFF).contains(&code_unit) {
222 // UTF-16 surrogate pair219 // 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 *pos += 2;221 *pos += 2;
225 let low = parse_hex4(src, pos)?;222 let low = parse_hex4(src, pos)?;
226 if (0xDC00..=0xDFFF).contains(&low) {223 if (0xDC00..=0xDFFF).contains(&low) {
...@@ -246,12 +243,10 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> {...@@ -246,12 +243,10 @@ fn parse_json_string(src: &str, pos: &mut usize) -> Option<String> {
246}243}
247244
248fn parse_hex4(src: &str, pos: &mut usize) -> Option<u16> {245fn parse_hex4(src: &str, pos: &mut usize) -> Option<u16> {
249 if *pos + 4 > src.len() {246 let end = pos.checked_add(4)?;
250 return None;247 let slice = src.get(*pos..end)?;
251 }
252 let slice = &src[*pos..*pos + 4];
253 let val = u16::from_str_radix(slice, 16).ok()?;248 let val = u16::from_str_radix(slice, 16).ok()?;
254 *pos += 4;249 *pos = end;
255 Some(val)250 Some(val)
256}251}
257252
...@@ -853,4 +848,18 @@ mod tests {...@@ -853,4 +848,18 @@ mod tests {
853848
854 let _ = std::fs::remove_file(&tmp_path);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,12 +277,15 @@ fn tokenize(src: &str) -> Result<Vec<Token>, String> {
277 Ok(out)277 Ok(out)
278}278}
279279
280const MAX_PARSE_DEPTH: usize = 64;
281
280struct ExprCompiler<'a> {282struct ExprCompiler<'a> {
281 tokens: &'a [Token],283 tokens: &'a [Token],
282 pos: usize,284 pos: usize,
283 channel: Channel,285 channel: Channel,
284 max_setup: usize,286 max_setup: usize,
285 max_inter: usize,287 max_inter: usize,
288 depth: usize,
286}289}
287290
288impl<'a> ExprCompiler<'a> {291impl<'a> ExprCompiler<'a> {
...@@ -299,6 +302,19 @@ impl<'a> ExprCompiler<'a> {...@@ -299,6 +302,19 @@ impl<'a> ExprCompiler<'a> {
299 }302 }
300 }303 }
301304
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 fn compile(&mut self) -> Result<String, String> {318 fn compile(&mut self) -> Result<String, String> {
303 if self.tokens.is_empty() {319 if self.tokens.is_empty() {
304 return Ok("0.0".to_owned());320 return Ok("0.0".to_owned());
...@@ -386,7 +402,7 @@ impl<'a> ExprCompiler<'a> {...@@ -386,7 +402,7 @@ impl<'a> ExprCompiler<'a> {
386 let base = self.parse_unary()?;402 let base = self.parse_unary()?;
387 if self.eat(&Token::Caret) {403 if self.eat(&Token::Caret) {
388 // Right-associative and allows unary rhs (e.g. `e^-x`, `2^-3`)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 Ok(format!("fu_pow(({base}), ({exp}))"))406 Ok(format!("fu_pow(({base}), ({exp}))"))
391 } else {407 } else {
392 Ok(base)408 Ok(base)
...@@ -395,12 +411,12 @@ impl<'a> ExprCompiler<'a> {...@@ -395,12 +411,12 @@ impl<'a> ExprCompiler<'a> {
395411
396 fn parse_unary(&mut self) -> Result<String, String> {412 fn parse_unary(&mut self) -> Result<String, String> {
397 if self.eat(&Token::Minus) {413 if self.eat(&Token::Minus) {
398 let inner = self.parse_unary()?;414 let inner = self.with_depth(Self::parse_unary)?;
399 Ok(format!("(-({inner}))"))415 Ok(format!("(-({inner}))"))
400 } else if self.eat(&Token::Plus) {416 } else if self.eat(&Token::Plus) {
401 self.parse_unary()417 self.with_depth(Self::parse_unary)
402 } else if self.eat(&Token::Bang) {418 } else if self.eat(&Token::Bang) {
403 let inner = self.parse_unary()?;419 let inner = self.with_depth(Self::parse_unary)?;
404 Ok(format!("select(0.0, 1.0, ({inner}) == 0.0)"))420 Ok(format!("select(0.0, 1.0, ({inner}) == 0.0)"))
405 } else {421 } else {
406 self.parse_primary()422 self.parse_primary()
...@@ -411,7 +427,7 @@ impl<'a> ExprCompiler<'a> {...@@ -411,7 +427,7 @@ impl<'a> ExprCompiler<'a> {
411 match self.peek().cloned() {427 match self.peek().cloned() {
412 Some(Token::LParen) => {428 Some(Token::LParen) => {
413 self.pos += 1;429 self.pos += 1;
414 let inner = self.parse_or()?;430 let inner = self.with_depth(Self::parse_or)?;
415 if !self.eat(&Token::RParen) {431 if !self.eat(&Token::RParen) {
416 return Err("expected ')'".to_owned());432 return Err("expected ')'".to_owned());
417 }433 }
...@@ -427,7 +443,7 @@ impl<'a> ExprCompiler<'a> {...@@ -427,7 +443,7 @@ impl<'a> ExprCompiler<'a> {
427 let mut args = Vec::new();443 let mut args = Vec::new();
428 if self.peek() != Some(&Token::RParen) {444 if self.peek() != Some(&Token::RParen) {
429 loop {445 loop {
430 args.push(self.parse_or()?);446 args.push(self.with_depth(Self::parse_or)?);
431 if !self.eat(&Token::Comma) {447 if !self.eat(&Token::Comma) {
432 break;448 break;
433 }449 }
...@@ -682,6 +698,7 @@ fn compile_single_expr(...@@ -682,6 +698,7 @@ fn compile_single_expr(
682 channel,698 channel,
683 max_setup,699 max_setup,
684 max_inter,700 max_inter,
701 depth: 0,
685 };702 };
686 compiler.compile()703 compiler.compile()
687}704}
...@@ -972,6 +989,34 @@ impl CustomShaderCache {...@@ -972,6 +989,34 @@ impl CustomShaderCache {
972 }989 }
973 }990 }
974991
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 /// Compiles and caches the compute pipeline for `program` at `format`, returning `false`1020 /// Compiles and caches the compute pipeline for `program` at `format`, returning `false`
976 /// if the program contains unsupported syntax (graceful fallback to passthrough).1021 /// if the program contains unsupported syntax (graceful fallback to passthrough).
977 pub fn ensure_compiled(1022 pub fn ensure_compiled(
...@@ -985,23 +1030,8 @@ impl CustomShaderCache {...@@ -985,23 +1030,8 @@ impl CustomShaderCache {
985 if let Some(entry) = self.pipelines.get(&key) {1030 if let Some(entry) = self.pipelines.get(&key) {
986 return entry.is_some();1031 return entry.is_some();
987 }1032 }
988 self.ensure_format_layouts(device, format);
989 let pipeline = match compile_wgsl(&norm, format) {1033 let pipeline = match compile_wgsl(&norm, format) {
990 Ok(wgsl) => {1034 Ok(wgsl) => self.compile_wgsl_pipeline(device, format, &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 }
1005 Err(_) => None,1035 Err(_) => None,
1006 };1036 };
1007 let ok = pipeline.is_some();1037 let ok = pipeline.is_some();
...@@ -1293,4 +1323,44 @@ mod tests {...@@ -1293,4 +1323,44 @@ mod tests {
1293 assert_eq!(rgba[2], 255);1323 assert_eq!(rgba[2], 255);
1294 assert_eq!(rgba[3], 255);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,10 +1,19 @@
1use super::*;1use super::*;
2use std::path::PathBuf;
3use std::sync::{Mutex, OnceLock};
4
5static DIMS_CACHE: OnceLock<Mutex<HashMap<PathBuf, Option<[u32; 2]>>>> = OnceLock::new();
6
7pub(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}
214
3impl Engine {15impl Engine {
4 fn probe_clip_dims(clip: &model::ClipSpec) -> Option<[u32; 2]> {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 let base = PathBuf::from(&clip.filename);17 let base = PathBuf::from(&clip.filename);
9 let cache = DIMS_CACHE.get_or_init(|| Mutex::new(HashMap::new()));18 let cache = DIMS_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
10 if let Ok(guard) = cache.lock() {19 if let Ok(guard) = cache.lock() {
...@@ -163,6 +172,7 @@ impl Engine {...@@ -163,6 +172,7 @@ impl Engine {
163 resolved.hash(&mut h);172 resolved.hash(&mut h);
164 local_idx.hash(&mut h);173 local_idx.hash(&mut h);
165 post_mult.hash(&mut h);174 post_mult.hash(&mut h);
175 exr_channels.hash(&mut h);
166 target_size.hash(&mut h);176 target_size.hash(&mut h);
167 mask_hash.hash(&mut h);177 mask_hash.hash(&mut h);
168 mask_inv.hash(&mut h);178 mask_inv.hash(&mut h);
...@@ -577,8 +587,8 @@ impl Engine {...@@ -577,8 +587,8 @@ impl Engine {
577 let sx = comp.eval_number(node, "XSize", time, 1.0, &self.expr);587 let sx = comp.eval_number(node, "XSize", time, 1.0, &self.expr);
578 let sy = comp.eval_number(node, "YSize", time, sx, &self.expr);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),590 ((src.size[0] as f64 * sx).round() as u32).max(1),
581 ((src.size[1] as f64 * sy).round() as u32).clamp(1, 8192),591 ((src.size[1] as f64 * sy).round() as u32).max(1),
582 ]592 ]
583 };593 };
584 let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 };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,7 +767,7 @@ impl Engine {
757 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },767 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
758 );768 );
759 let mut dst = self.alloc_tex(size, self.node_depth(comp, node, time, None), key);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 self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u);771 self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u);
762 self.cache.insert(key, dst.clone(), node.id, frame_i);772 self.cache.insert(key, dst.clone(), node.id, frame_i);
763 dst773 dst
crates/engine/src/eval/mod.rs+330-41
...@@ -405,7 +405,8 @@ pub struct Engine {...@@ -405,7 +405,8 @@ pub struct Engine {
405 optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>,405 optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>,
406 particles: crate::particles::ParticleCache,406 particles: crate::particles::ParticleCache,
407 custom_shaders: crate::custom_shader::CustomShaderCache,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 dummy: CachedTexture,410 dummy: CachedTexture,
410 pub cache: NodeCache,411 pub cache: NodeCache,
411 pub media: MediaCache,412 pub media: MediaCache,
...@@ -456,6 +457,7 @@ impl Engine {...@@ -456,6 +457,7 @@ impl Engine {
456 particles: crate::particles::ParticleCache::default(),457 particles: crate::particles::ParticleCache::default(),
457 custom_shaders: crate::custom_shader::CustomShaderCache::new(),458 custom_shaders: crate::custom_shader::CustomShaderCache::new(),
458 sprite_cache: HashMap::new(),459 sprite_cache: HashMap::new(),
460 ram_upload_tex: RefCell::new(None),
459 dummy,461 dummy,
460 cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB),462 cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB),
461 media: MediaCache::new(512),463 media: MediaCache::new(512),
...@@ -469,6 +471,23 @@ impl Engine {...@@ -469,6 +471,23 @@ impl Engine {
469 }471 }
470 }472 }
471473
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 pub fn new_headless() -> Result<Self, Box<dyn std::error::Error>> {491 pub fn new_headless() -> Result<Self, Box<dyn std::error::Error>> {
473 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());492 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
474 let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?;493 let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?;
...@@ -616,21 +635,46 @@ impl Engine {...@@ -616,21 +635,46 @@ impl Engine {
616 display: DisplaySettings,635 display: DisplaySettings,
617 ) -> EvalStats {636 ) -> EvalStats {
618 let t0 = Instant::now();637 let t0 = Instant::now();
619 let src = create_texture(&self.device, frame.size, 0);638 let mut upload_slot = self.ram_upload_tex.borrow_mut();
620 self.queue.write_texture(639 let needs_alloc = upload_slot
621 src.texture.as_image_copy(),640 .as_ref()
622 &frame.rgba,641 .is_none_or(|t| t.size != frame.size);
623 wgpu::TexelCopyBufferLayout {642 if needs_alloc {
624 offset: 0,643 let max_dim = self.device.limits().max_texture_dimension_2d.max(1);
625 bytes_per_row: Some(frame.size[0] * 4),644 let (clamped, _) = crate::cache::clamp_dims_to_limit(frame.size[0], frame.size[1], max_dim);
626 rows_per_image: Some(frame.size[1]),645 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
627 },646 label: Some("ram-viewer-upload"),
628 wgpu::Extent3d {647 size: wgpu::Extent3d {
629 width: frame.size[0],648 width: clamped[0],
630 height: frame.size[1],649 height: clamped[1],
631 depth_or_array_layers: 1,650 depth_or_array_layers: 1,
632 },651 },
633 );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 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {678 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
635 label: Some("comp-ram-viewer-blit"),679 label: Some("comp-ram-viewer-blit"),
636 });680 });
...@@ -674,11 +718,15 @@ impl Engine {...@@ -674,11 +718,15 @@ impl Engine {
674 self.media.clear();718 self.media.clear();
675 self.particles.clear();719 self.particles.clear();
676 self.sprite_cache.clear();720 self.sprite_cache.clear();
721 *self.ram_upload_tex.borrow_mut() = None;
722 io::clear_dims_cache();
677 }723 }
678724
679 pub fn bust_gpu_cache(&mut self) {725 pub fn bust_gpu_cache(&mut self) {
680 self.cache.bust_all();726 self.cache.bust_all();
681 self.output_cache.clear();727 self.output_cache.clear();
728 self.sprite_cache.clear();
729 *self.ram_upload_tex.borrow_mut() = None;
682 }730 }
683731
684 pub fn bust_frame(&mut self, frame: i64) -> usize {732 pub fn bust_frame(&mut self, frame: i64) -> usize {
...@@ -762,19 +810,11 @@ impl Engine {...@@ -762,19 +810,11 @@ impl Engine {
762 let mut tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);810 let mut tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);
763 if tex.has_dod() {811 if tex.has_dod() {
764 // Crop expanded DoD cleanly back to logical canvas_size for final readback/export812 // 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);813 tex = self.crop_to_canvas(&mut encoder, tex);
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;
776 }814 }
777 self.queue.submit(Some(encoder.finish()));815 self.queue.submit(Some(encoder.finish()));
816 self.frame_memo.clear();
817 self.cache.flush_pending_pool();
778818
779 self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone());819 self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone());
780 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;820 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
...@@ -844,6 +884,8 @@ impl Engine {...@@ -844,6 +884,8 @@ impl Engine {
844 );884 );
845885
846 self.queue.submit(Some(encoder.finish()));886 self.queue.submit(Some(encoder.finish()));
887 self.frame_memo.clear();
888 self.cache.flush_pending_pool();
847889
848 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;890 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
849 stats.cached_entries = self.cache.entry_count();891 stats.cached_entries = self.cache.entry_count();
...@@ -937,23 +979,20 @@ impl Engine {...@@ -937,23 +979,20 @@ impl Engine {
937 stats: &mut EvalStats,979 stats: &mut EvalStats,
938 ) -> CachedTexture {980 ) -> CachedTexture {
939 let frame_i = time.round() as i64;981 let frame_i = time.round() as i64;
940 let is_mask_node = matches!(982 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
941 comp.node(id).kind.as_str(),983 let memo_sz = self.mask_target_size;
942 "EllipseMask" | "RectangleMask" | "PolylineMask" | "PaintMask"
943 );
944 let memo_sz = if is_mask_node { self.mask_target_size } else { None };
945 // Always memoize within a single frame's DAG pass so diamond graphs never explode984 // Always memoize within a single frame's DAG pass so diamond graphs never explode
946 // exponentially (even in CacheMode::Bypass, which bypasses the cross-frame cache).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 stats.cache_hits += 1;987 stats.cache_hits += 1;
949 return hit;988 return hit;
950 }989 }
951 if !visiting.insert((id, frame_i)) {990 if !visiting.insert((id, time_key)) {
952 return self.dummy.clone();991 return self.dummy.clone();
953 }992 }
954 let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats);993 let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats);
955 visiting.remove(&(id, frame_i));994 visiting.remove(&(id, time_key));
956 self.frame_memo.insert((id, frame_i, memo_sz), res.clone());995 self.frame_memo.insert((id, time_key, memo_sz), res.clone());
957 res996 res
958 }997 }
959998
...@@ -1362,7 +1401,26 @@ pub fn create_texture_dod_fmt(...@@ -1362,7 +1401,26 @@ pub fn create_texture_dod_fmt(
1362 format: wgpu::TextureFormat,1401 format: wgpu::TextureFormat,
1363 content_hash: u64,1402 content_hash: u64,
1364) -> CachedTexture {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 let tex = device.create_texture(&wgpu::TextureDescriptor {1424 let tex = device.create_texture(&wgpu::TextureDescriptor {
1367 label: Some("comp-tex"),1425 label: Some("comp-tex"),
1368 size: wgpu::Extent3d {1426 size: wgpu::Extent3d {
...@@ -1381,14 +1439,16 @@ pub fn create_texture_dod_fmt(...@@ -1381,14 +1439,16 @@ pub fn create_texture_dod_fmt(
1381 | wgpu::TextureUsages::RENDER_ATTACHMENT,1439 | wgpu::TextureUsages::RENDER_ATTACHMENT,
1382 view_formats: &[],1440 view_formats: &[],
1383 });1441 });
1384 CachedTexture::from_texture_dod_depth(1442 let mut cached = CachedTexture::from_texture_dod_depth(
1385 tex,1443 tex,
1386 clamped,1444 clamped,
1387 origin,1445 eff_origin,
1388 [canvas_size[0].max(1), canvas_size[1].max(1)],1446 eff_canvas,
1389 depth,1447 depth,
1390 content_hash,1448 content_hash,
1391 )1449 );
1450 cached.tex_scale = tex_scale;
1451 cached
1392}1452}
13931453
1394#[cfg(test)]1454#[cfg(test)]
...@@ -1517,4 +1577,233 @@ Composition {...@@ -1517,4 +1577,233 @@ Composition {
1517 let pl = eng.readback_rgba(&tl).unwrap();1577 let pl = eng.readback_rgba(&tl).unwrap();
1518 assert!(pl[2] > 240 && pl[0] < 15 && pl[1] < 15, "SwLegacy2 expected blue, got {:?}", &pl[..4]);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#"
1588Composition {
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#"
1654Composition {
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#"
1709Composition {
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,37 +15,53 @@ impl Engine {
15 ) -> CachedTexture {15 ) -> CachedTexture {
16 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32;16 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32;
17 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32;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 let dst_depth = self.node_depth(comp, node, time, None);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;
2023
21 let bitmap_sources = crate::particles::collect_bitmap_sources(comp, node.id);24 let bitmap_sources = crate::particles::collect_bitmap_sources(comp, node.id);
22 let mut sprites: HashMap<NodeId, crate::particles::SpriteImage> = HashMap::new();25 let mut sprites: HashMap<NodeId, crate::particles::SpriteImage> = HashMap::new();
23 let mut sprite_hashes: Vec<(NodeId, u64)> = Vec::with_capacity(bitmap_sources.len());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();
2428
25 for (emitter_id, sprite_node_id) in bitmap_sources {29 for (emitter_id, sprite_node_id) in bitmap_sources {
26 let spr_key = (sprite_node_id, comp.revision, frame_i);30 let spr_key = (sprite_node_id, comp.revision, time_key);
27 if let Some(cached) = self.sprite_cache.get(&spr_key).cloned() {31 if let Some((cached, spr_hash)) = self.sprite_cache.get(&spr_key).cloned() {
28 sprite_hashes.push((emitter_id, (cached.size[0] as u64) << 32 | cached.size[1] as u64));32 sprite_hashes.push((emitter_id, spr_hash));
29 sprites.insert(emitter_id, cached);33 sprites.insert(emitter_id, cached);
30 continue;34 continue;
31 }35 }
32 let mut sprite_enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {36 let sprite_tex = self.eval_node(comp, sprite_node_id, time, enc, visiting, stats);
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()));
38 sprite_hashes.push((emitter_id, sprite_tex.content_hash));37 sprite_hashes.push((emitter_id, sprite_tex.content_hash));
39 if let Ok(rgba) = self.readback_rgba(&sprite_tex) {38 pending_sprites.push((emitter_id, sprite_node_id, sprite_tex));
40 let spr = crate::particles::SpriteImage {39 }
41 size: sprite_tex.size,40
42 rgba,41 if !pending_sprites.is_empty() {
43 };42 // Flush the main encoder so even already-memoized upstream sprites are submitted
44 if self.sprite_cache.len() > 64 {43 // before `readback_rgba` maps their GPU memory.
45 self.sprite_cache.clear();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 }
5167
...@@ -54,7 +70,7 @@ impl Engine {...@@ -54,7 +70,7 @@ impl Engine {
54 self.cache.node_salt(node.id).hash(&mut h_key);70 self.cache.node_salt(node.id).hash(&mut h_key);
55 "pRender".hash(&mut h_key);71 "pRender".hash(&mut h_key);
56 comp.revision.hash(&mut h_key);72 comp.revision.hash(&mut h_key);
57 frame_i.hash(&mut h_key);73 time_key.hash(&mut h_key);
58 dims.hash(&mut h_key);74 dims.hash(&mut h_key);
59 dst_depth.hash(&mut h_key);75 dst_depth.hash(&mut h_key);
60 sprite_hashes.hash(&mut h_key);76 sprite_hashes.hash(&mut h_key);
...@@ -92,7 +108,7 @@ impl Engine {...@@ -92,7 +108,7 @@ impl Engine {
92 },108 },
93 );109 );
94110
95 let out = if dst_depth != BitDepth::Int8 {111 let mut out = if dst_depth != BitDepth::Int8 {
96 let promoted = self.alloc_tex(dims, dst_depth, key);112 let promoted = self.alloc_tex(dims, dst_depth, key);
97 let u = UniformParams::default();113 let u = UniformParams::default();
98 self.dispatch_op(enc, ShaderOp::ChangeDepth, &base_tex.view, &self.dummy.view, &self.dummy.view, &promoted, &u);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,6 +116,7 @@ impl Engine {
100 } else {116 } else {
101 base_tex117 base_tex
102 };118 };
119 out.tex_scale = tex_scale;
103 self.cache.insert(key, out.clone(), node.id, frame_i);120 self.cache.insert(key, out.clone(), node.id, frame_i);
104 out121 out
105 }122 }
...@@ -116,7 +133,9 @@ impl Engine {...@@ -116,7 +133,9 @@ impl Engine {
116 ) -> CachedTexture {133 ) -> CachedTexture {
117 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;134 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;
118 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32;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);
120139
121 let text_str = comp.eval_text(node, "StyledText", time, "", &self.expr);140 let text_str = comp.eval_text(node, "StyledText", time, "", &self.expr);
122 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue");141 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue");
...@@ -434,12 +453,36 @@ impl Engine {...@@ -434,12 +453,36 @@ impl Engine {
434 }453 }
435 }454 }
436455
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 self.queue.write_texture(473 self.queue.write_texture(
439 final_tex.texture.as_image_copy(),474 final_tex.texture.as_image_copy(),
440 &pixels,475 &upload_pixels,
441 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) },476 wgpu::TexelCopyBufferLayout {
442 wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 },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 );
444487
445 self.cache.insert(key, final_tex.clone(), node.id, frame_i);488 self.cache.insert(key, final_tex.clone(), node.id, frame_i);
...@@ -460,18 +503,23 @@ impl Engine {...@@ -460,18 +503,23 @@ impl Engine {
460 ) -> CachedTexture {503 ) -> CachedTexture {
461 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;504 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;
462 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32;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 let aspect = (size[0] as f32 / size[1].max(1) as f32).max(1e-4);509 let aspect = (size[0] as f32 / size[1].max(1) as f32).max(1e-4);
465510
466 let Some(scene_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {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 };
469516
470 let lighting_enabled = comp.eval_number(node, "RendererSoftware.LightingEnabled", time, 0.0, &self.expr) > 0.5;517 let lighting_enabled = comp.eval_number(node, "RendererSoftware.LightingEnabled", time, 0.0, &self.expr) > 0.5;
471 let mut cameras = Vec::new();518 let mut cameras = Vec::new();
472 let mut mesh_specs = Vec::new();519 let mut mesh_specs = Vec::new();
473 let mut lights = crate::scene3d::SceneLights::default();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 comp,523 comp,
476 scene_id,524 scene_id,
477 time,525 time,
...@@ -481,6 +529,7 @@ impl Engine {...@@ -481,6 +529,7 @@ impl Engine {
481 &mut cameras,529 &mut cameras,
482 &mut mesh_specs,530 &mut mesh_specs,
483 &mut lights,531 &mut lights,
532 &mut visited_nodes,
484 0,533 0,
485 );534 );
486535
...@@ -518,6 +567,12 @@ impl Engine {...@@ -518,6 +567,12 @@ impl Engine {
518 hash_floats.push(sl.decay_type);567 hash_floats.push(sl.decay_type);
519 }568 }
520569
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 // First resolve all 2D textures & Text3D plates & Displace3D heightmaps576 // First resolve all 2D textures & Text3D plates & Displace3D heightmaps
522 let mut pending_displace_tex: Vec<Option<(CachedTexture, f32, f32, i32)>> = Vec::with_capacity(mesh_specs.len());577 let mut pending_displace_tex: Vec<Option<(CachedTexture, f32, f32, i32)>> = Vec::with_capacity(mesh_specs.len());
523 for ms in &mesh_specs {578 for ms in &mesh_specs {
...@@ -531,6 +586,7 @@ impl Engine {...@@ -531,6 +586,7 @@ impl Engine {
531 let dtex = self.eval_node(comp, ds.input_node, time, enc, visiting, stats);586 let dtex = self.eval_node(comp, ds.input_node, time, enc, visiting, stats);
532 (dtex, ds.scale, ds.bias, ds.channel)587 (dtex, ds.scale, ds.bias, ds.channel)
533 });588 });
589 ms.shape.hash_into(&mut h_scene);
534 upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash));590 upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash));
535 upstream_hashes.push(disp_entry.as_ref().map_or(0, |(t, _, _, _)| t.content_hash));591 upstream_hashes.push(disp_entry.as_ref().map_or(0, |(t, _, _, _)| t.content_hash));
536 hash_floats.extend_from_slice(&ms.world);592 hash_floats.extend_from_slice(&ms.world);
...@@ -559,6 +615,7 @@ impl Engine {...@@ -559,6 +615,7 @@ impl Engine {
559 });615 });
560 pending_displace_tex.push(disp_entry);616 pending_displace_tex.push(disp_entry);
561 }617 }
618 upstream_hashes.push(h_scene.finish());
562619
563 let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats);620 let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats);
564 if let Some(hit) = self.cache.get(key, node.id, frame_i) {621 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
...@@ -577,6 +634,7 @@ impl Engine {...@@ -577,6 +634,7 @@ impl Engine {
577 }),634 }),
578 );635 );
579 self.queue.submit(Some(flush_enc.finish()));636 self.queue.submit(Some(flush_enc.finish()));
637 self.cache.flush_pending_pool();
580 for (dm, entry) in draw_meshes.iter_mut().zip(pending_displace_tex.into_iter()) {638 for (dm, entry) in draw_meshes.iter_mut().zip(pending_displace_tex.into_iter()) {
581 if let Some((dtex, scale, bias, channel)) = entry {639 if let Some((dtex, scale, bias, channel)) = entry {
582 if let Ok(rgba) = self.readback_rgba(&dtex) {640 if let Ok(rgba) = self.readback_rgba(&dtex) {
...@@ -592,7 +650,8 @@ impl Engine {...@@ -592,7 +650,8 @@ impl Engine {
592 }650 }
593 }651 }
594652
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 self.scene3d.render_meshes(655 self.scene3d.render_meshes(
597 &self.device,656 &self.device,
598 &self.queue,657 &self.queue,
...@@ -700,4 +759,55 @@ mod tests {...@@ -700,4 +759,55 @@ mod tests {
700 "LineSpacing 2.0 vs 1.0 on 320px wide frame should expand ~51px, got {diff}"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#"
766Composition {
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,6 +44,38 @@ pub fn collect_scene(
44 meshes: &mut Vec<MeshInstance>,44 meshes: &mut Vec<MeshInstance>,
45 lights: &mut SceneLights,45 lights: &mut SceneLights,
46 depth: usize,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)]
67pub 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 collect_scene_inner(80 collect_scene_inner(
49 comp,81 comp,
...@@ -56,6 +88,7 @@ pub fn collect_scene(...@@ -56,6 +88,7 @@ pub fn collect_scene(
56 cameras,88 cameras,
57 meshes,89 meshes,
58 lights,90 lights,
91 visited,
59 depth,92 depth,
60 );93 );
61}94}
...@@ -72,11 +105,13 @@ fn collect_scene_inner(...@@ -72,11 +105,13 @@ fn collect_scene_inner(
72 cameras: &mut Vec<CameraInstance>,105 cameras: &mut Vec<CameraInstance>,
73 meshes: &mut Vec<MeshInstance>,106 meshes: &mut Vec<MeshInstance>,
74 lights: &mut SceneLights,107 lights: &mut SceneLights,
108 visited: &mut Vec<NodeId>,
75 depth: usize,109 depth: usize,
76) {110) {
77 if depth > 32 {111 if depth > 32 {
78 return;112 return;
79 }113 }
114 visited.push(node_id);
80 let node = comp.node(node_id);115 let node = comp.node(node_id);
81 if node.bypassed {116 if node.bypassed {
82 return;117 return;
...@@ -94,7 +129,7 @@ fn collect_scene_inner(...@@ -94,7 +129,7 @@ fn collect_scene_inner(
94 input_names.sort();129 input_names.sort();
95 for in_name in input_names {130 for in_name in input_names {
96 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {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,7 +139,7 @@ fn collect_scene_inner(
104 next_ovr.material_override = Some(mid);139 next_ovr.material_override = Some(mid);
105 }140 }
106 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {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 "Override3D" => {145 "Override3D" => {
...@@ -120,7 +155,7 @@ fn collect_scene_inner(...@@ -120,7 +155,7 @@ fn collect_scene_inner(
120 next_ovr.affected_by_lights = Some(is_lit);155 next_ovr.affected_by_lights = Some(is_lit);
121 }156 }
122 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {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 "ReplaceNormals3D" => {161 "ReplaceNormals3D" => {
...@@ -129,7 +164,7 @@ fn collect_scene_inner(...@@ -129,7 +164,7 @@ fn collect_scene_inner(
129 next_ovr.flip_normals = !next_ovr.flip_normals;164 next_ovr.flip_normals = !next_ovr.flip_normals;
130 }165 }
131 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {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 "Displace3D" => {170 "Displace3D" => {
...@@ -146,7 +181,7 @@ fn collect_scene_inner(...@@ -146,7 +181,7 @@ fn collect_scene_inner(
146 });181 });
147 }182 }
148 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {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 "Duplicate3D" => {187 "Duplicate3D" => {
...@@ -185,7 +220,7 @@ fn collect_scene_inner(...@@ -185,7 +220,7 @@ fn collect_scene_inner(
185 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))));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 m = mat4_mul(m, jm);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 acc = mat4_mul(acc, step);224 acc = mat4_mul(acc, step);
190 }225 }
191 }226 }
...@@ -278,7 +313,7 @@ fn collect_scene_inner(...@@ -278,7 +313,7 @@ fn collect_scene_inner(
278 .or_else(|| node.connected_node("SceneInput"))313 .or_else(|| node.connected_node("SceneInput"))
279 .and_then(|s| comp.find_node(s))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 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own));317 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own));
283 }318 }
284 "Shape3D" => {319 "Shape3D" => {
...@@ -318,7 +353,7 @@ fn collect_scene_inner(...@@ -318,7 +353,7 @@ fn collect_scene_inner(
318 node.connected_node("MaterialInput")353 node.connected_node("MaterialInput")
319 .and_then(|s| comp.find_node(s))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 if mat_node.is_none() {357 if mat_node.is_none() {
323 apply_mtl_std(&mut mat, comp, node, "", time, expr);358 apply_mtl_std(&mut mat, comp, node, "", time, expr);
324 }359 }
...@@ -337,7 +372,7 @@ fn collect_scene_inner(...@@ -337,7 +372,7 @@ fn collect_scene_inner(
337 node.connected_node(&format!("{face}MaterialInput"))372 node.connected_node(&format!("{face}MaterialInput"))
338 .and_then(|s| comp.find_node(s))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 if mat_node.is_none() {376 if mat_node.is_none() {
342 apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr);377 apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr);
343 }378 }
...@@ -352,7 +387,7 @@ fn collect_scene_inner(...@@ -352,7 +387,7 @@ fn collect_scene_inner(
352 }387 }
353 }388 }
354 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {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 "SurfaceFBXMesh" => {393 "SurfaceFBXMesh" => {
...@@ -375,14 +410,14 @@ fn collect_scene_inner(...@@ -375,14 +410,14 @@ fn collect_scene_inner(
375 })410 })
376 .and_then(|s| comp.find_node(s))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 if mat_node.is_none() {414 if mat_node.is_none() {
380 apply_mtl_std(&mut mat, comp, node, "", time, expr);415 apply_mtl_std(&mut mat, comp, node, "", time, expr);
381 }416 }
382 meshes.push(make_mesh_instance(world, shape, mat, None, &own));417 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
383 }418 }
384 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {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 "Text3D" => {423 "Text3D" => {
...@@ -391,7 +426,7 @@ fn collect_scene_inner(...@@ -391,7 +426,7 @@ fn collect_scene_inner(
391 node.connected_node("MaterialInput")426 node.connected_node("MaterialInput")
392 .and_then(|s| comp.find_node(s))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 if mat_node.is_none() {430 if mat_node.is_none() {
396 mat.diffuse_col = [1.0, 1.0, 1.0, 1.0];431 mat.diffuse_col = [1.0, 1.0, 1.0, 1.0];
397 }432 }
...@@ -406,7 +441,7 @@ fn collect_scene_inner(...@@ -406,7 +441,7 @@ fn collect_scene_inner(
406 }441 }
407 "MacroOperator" | "GroupOperator" => {442 "MacroOperator" | "GroupOperator" => {
408 if let Some(out_id) = node.macro_output {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,8 +583,9 @@ fn resolve_material(
548 mat_node: Option<NodeId>,583 mat_node: Option<NodeId>,
549 time: f64,584 time: f64,
550 expr: &ExprEngine,585 expr: &ExprEngine,
586 visited: &mut Vec<NodeId>,
551) -> ResolvedMaterial {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}
554590
555fn resolve_material_inner(591fn resolve_material_inner(
...@@ -557,6 +593,7 @@ fn resolve_material_inner(...@@ -557,6 +593,7 @@ fn resolve_material_inner(
557 mat_node: Option<NodeId>,593 mat_node: Option<NodeId>,
558 time: f64,594 time: f64,
559 expr: &ExprEngine,595 expr: &ExprEngine,
596 visited: &mut Vec<NodeId>,
560 depth: usize,597 depth: usize,
561) -> ResolvedMaterial {598) -> ResolvedMaterial {
562 let default_mat = ResolvedMaterial::default();599 let default_mat = ResolvedMaterial::default();
...@@ -566,6 +603,7 @@ fn resolve_material_inner(...@@ -566,6 +603,7 @@ fn resolve_material_inner(
566 let Some(mid) = mat_node else {603 let Some(mid) = mat_node else {
567 return default_mat;604 return default_mat;
568 };605 };
606 visited.push(mid);
569 let n = comp.node(mid);607 let n = comp.node(mid);
570 match n.kind.as_str() {608 match n.kind.as_str() {
571 "Texture2DOperator" => {609 "Texture2DOperator" => {
...@@ -582,7 +620,7 @@ fn resolve_material_inner(...@@ -582,7 +620,7 @@ fn resolve_material_inner(
582 }620 }
583 "TextureTransformOperator" => {621 "TextureTransformOperator" => {
584 let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s));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 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;624 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
587 let xf = texture_transform_uv(625 let xf = texture_transform_uv(
588 [f("Translation.U", 0.0), f("Translation.V", 0.0)],626 [f("Translation.U", 0.0), f("Translation.V", 0.0)],
...@@ -622,11 +660,11 @@ fn resolve_material_inner(...@@ -622,11 +660,11 @@ fn resolve_material_inner(
622 .connected_node("Diffuse.Color.Material")660 .connected_node("Diffuse.Color.Material")
623 .or_else(|| n.connected_node("MaterialInput"))661 .or_else(|| n.connected_node("MaterialInput"))
624 .and_then(|s| comp.find_node(s));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 let bump_in = n664 let bump_in = n
627 .connected_node("Bumpmap.Material")665 .connected_node("Bumpmap.Material")
628 .and_then(|s| comp.find_node(s));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));
630668
631 let col = [669 let col = [
632 comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32,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,7 +12,7 @@ mod math;
12mod mesh;12mod mesh;
13mod shader;13mod shader;
1414
15pub use collect::{collect_scene, eval_transform3d};15pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d};
16pub use math::{16pub use math::{
17 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y,17 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y,
18 mat4_rot_z, mat4_scale, mat4_translate,18 mat4_rot_z, mat4_scale, mat4_translate,
...@@ -91,6 +91,16 @@ impl UvAffine {...@@ -91,6 +91,16 @@ impl UvAffine {
91 t: o,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}
95105
96/// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for106/// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for
...@@ -136,6 +146,21 @@ impl Default for MaterialFx {...@@ -136,6 +146,21 @@ impl Default for MaterialFx {
136 }146 }
137}147}
138148
149impl 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
139impl ShapeKind {164impl ShapeKind {
140 /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper.165 /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper.
141 pub fn base_shape(&self) -> &ShapeKind {166 pub fn base_shape(&self) -> &ShapeKind {
...@@ -148,6 +173,61 @@ impl ShapeKind {...@@ -148,6 +173,61 @@ impl ShapeKind {
148 other => (other, MaterialFx::default()),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}
152232
153#[derive(Clone, Debug)]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,7 +486,13 @@ fn display_blit_op(@builtin(global_invocation_id) gid: vec3<u32>) {
486 } else if (ch == 4) {486 } else if (ch == 4) {
487 out_col = vec4<f32>(src.a, src.a, src.a, 1.0);487 out_col = vec4<f32>(src.a, src.a, src.a, 1.0);
488 } else {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 if (checker) {496 if (checker) {
491 let cx = (gid.x / 16u) & 1u;497 let cx = (gid.x / 16u) & 1u;
492 let cy = (gid.y / 16u) & 1u;498 let cy = (gid.y / 16u) & 1u;
...@@ -497,7 +503,7 @@ fn display_blit_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -497,7 +503,7 @@ fn display_blit_op(@builtin(global_invocation_id) gid: vec3<u32>) {
497 out_col = vec4<f32>(rgb, src.a);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// 17b. ChannelBoolean (full Fusion Operation + per-channel ToRed/Green/Blue/Alpha)509// 17b. ChannelBoolean (full Fusion Operation + per-channel ToRed/Green/Blue/Alpha)