authoravatarclover caruso<git@paperclover.net>2026-12-01 14:24:03-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 14:35:36-08:00
logb6e8338c7db97497095cf5de5e4c4223db443428
tree38c26911849a0d348ffed5086350b94e5059404b
parent0d06255b2ac49ce8492948def1d13109fbe6e99a
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(model,engine): harden Lua bytecode cache, downstream RoI, Text3D offscreen scale, and PolylineMask clamp


5 files changed, 726 insertions(+), 128 deletions(-)

crates/engine/src/eval/composite.rs+216-38
...@@ -60,6 +60,8 @@ fn infer_node_canvas_size(...@@ -60,6 +60,8 @@ fn infer_node_canvas_size(
60 time: f64,60 time: f64,
61 expr: &ExprEngine,61 expr: &ExprEngine,
62 comp_dims: [u32; 2],62 comp_dims: [u32; 2],
63 proxy_scale: u32,
64 hiq: bool,
63 depth: usize,65 depth: usize,
64) -> Option<[u32; 2]> {66) -> Option<[u32; 2]> {
65 let mut cur_id = start_id;67 let mut cur_id = start_id;
...@@ -116,13 +118,23 @@ fn infer_node_canvas_size(...@@ -116,13 +118,23 @@ fn infer_node_canvas_size(
116 {118 {
117 return None;119 return None;
118 }120 }
119 let w = comp.eval_number(n, "Width", time, comp_dims[0] as f64, expr).max(1.0) as u32;
120 let h = comp.eval_number(n, "Height", time, comp_dims[1] as f64, expr).max(1.0) as u32;
121 // Only unambiguous when explicit dimensions aren't additionally proxy-scaled differently.
122 if !n.inputs.contains_key("Width") && !n.inputs.contains_key("Height") {121 if !n.inputs.contains_key("Width") && !n.inputs.contains_key("Height") {
123 return Some(comp_dims);122 return Some(comp_dims);
124 }123 }
125 return Some([w, h]);124 let w = comp.eval_number(n, "Width", time, comp.width as f64, expr).round().max(1.0) as u32;
125 let h = comp.eval_number(n, "Height", time, comp.height as f64, expr).round().max(1.0) as u32;
126 if matches!(n.kind.as_str(), "Background" | "FastNoise") && (w < 16 || h < 16) {
127 return Some(comp_dims);
128 }
129 let s = proxy_scale.max(1);
130 let scaled = [(w / s).max(1), (h / s).max(1)];
131 if n.kind == "FastNoise" {
132 let cap = if hiq { 8192 } else { 4096 };
133 if scaled[0].max(scaled[1]) > cap {
134 return None;
135 }
136 }
137 return Some(scaled);
126 }138 }
127 _ => return None,139 _ => return None,
128 }140 }
...@@ -353,6 +365,7 @@ fn roi_for_node(...@@ -353,6 +365,7 @@ fn roi_for_node(
353 node_id: NodeId,365 node_id: NodeId,
354 canvas_size: [u32; 2],366 canvas_size: [u32; 2],
355 comp_dims: [u32; 2],367 comp_dims: [u32; 2],
368 proxy_scale: u32,
356 time: f64,369 time: f64,
357 time_key: i64,370 time_key: i64,
358 hiq: bool,371 hiq: bool,
...@@ -365,7 +378,11 @@ fn roi_for_node(...@@ -365,7 +378,11 @@ fn roi_for_node(
365 if depth == 0 {378 if depth == 0 {
366 return None;379 return None;
367 }380 }
368 if let Some(&cached) = memo.get(&(node_id, time_key)) {381 let mut mh = DefaultHasher::new();
382 time_key.hash(&mut mh);
383 canvas_size.hash(&mut mh);
384 let memo_key = mh.finish() as i64;
385 if let Some(&cached) = memo.get(&(node_id, memo_key)) {
369 return cached;386 return cached;
370 }387 }
371 if !visiting.insert(node_id) {388 if !visiting.insert(node_id) {
...@@ -385,6 +402,7 @@ fn roi_for_node(...@@ -385,6 +402,7 @@ fn roi_for_node(
385 port,402 port,
386 canvas_size,403 canvas_size,
387 comp_dims,404 comp_dims,
405 proxy_scale,
388 time,406 time,
389 time_key,407 time_key,
390 hiq,408 hiq,
...@@ -404,7 +422,7 @@ fn roi_for_node(...@@ -404,7 +422,7 @@ fn roi_for_node(
404 };422 };
405423
406 visiting.remove(&node_id);424 visiting.remove(&node_id);
407 memo.insert((node_id, time_key), res);425 memo.insert((node_id, memo_key), res);
408 res426 res
409}427}
410428
...@@ -415,6 +433,7 @@ fn roi_from_consumer(...@@ -415,6 +433,7 @@ fn roi_from_consumer(
415 port: &str,433 port: &str,
416 canvas_size: [u32; 2],434 canvas_size: [u32; 2],
417 comp_dims: [u32; 2],435 comp_dims: [u32; 2],
436 proxy_scale: u32,
418 time: f64,437 time: f64,
419 time_key: i64,438 time_key: i64,
420 hiq: bool,439 hiq: bool,
...@@ -432,7 +451,7 @@ fn roi_from_consumer(...@@ -432,7 +451,7 @@ fn roi_from_consumer(
432 }451 }
433 let n = comp.node(cid);452 let n = comp.node(cid);
434 if port == "__macro_output" {453 if port == "__macro_output" {
435 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);454 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
436 }455 }
437 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {456 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
438 return None;457 return None;
...@@ -444,7 +463,7 @@ fn roi_from_consumer(...@@ -444,7 +463,7 @@ fn roi_from_consumer(
444 )463 )
445 {464 {
446 if port == default_main_input_port(&n.kind) {465 if port == default_main_input_port(&n.kind) {
447 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);466 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
448 }467 }
449 return None;468 return None;
450 }469 }
...@@ -461,12 +480,12 @@ fn roi_from_consumer(...@@ -461,12 +480,12 @@ fn roi_from_consumer(
461 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();480 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
462 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;481 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
463 if blend <= 1e-6 && !mbm {482 if blend <= 1e-6 && !mbm {
464 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);483 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
465 }484 }
466 if has_mask {485 if has_mask {
467 return Some(RoiBox::canvas(canvas_size));486 return Some(RoiBox::canvas(canvas_size));
468 }487 }
469 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)488 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
470 }489 }
471 "Fuse.Colorize" => {490 "Fuse.Colorize" => {
472 if port != "Image" && port != "Input" {491 if port != "Image" && port != "Input" {
...@@ -475,7 +494,7 @@ fn roi_from_consumer(...@@ -475,7 +494,7 @@ fn roi_from_consumer(
475 if Engine::resolve_effect_mask_id(comp, n).is_some() {494 if Engine::resolve_effect_mask_id(comp, n).is_some() {
476 return Some(RoiBox::canvas(canvas_size));495 return Some(RoiBox::canvas(canvas_size));
477 }496 }
478 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)497 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
479 }498 }
480 "ChannelBoolean" => {499 "ChannelBoolean" => {
481 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;500 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
...@@ -483,13 +502,13 @@ fn roi_from_consumer(...@@ -483,13 +502,13 @@ fn roi_from_consumer(
483 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;502 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
484 if blend <= 1e-6 && !mbm {503 if blend <= 1e-6 && !mbm {
485 return match port {504 return match port {
486 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),505 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
487 "Foreground" => Some(RoiBox::Empty),506 "Foreground" => Some(RoiBox::Empty),
488 _ => None,507 _ => None,
489 };508 };
490 }509 }
491 if port == "Background" || port == "Foreground" {510 if port == "Background" || port == "Foreground" {
492 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)511 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
493 } else {512 } else {
494 None513 None
495 }514 }
...@@ -502,7 +521,7 @@ fn roi_from_consumer(...@@ -502,7 +521,7 @@ fn roi_from_consumer(
502 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();521 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
503 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;522 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
504 if blend <= 1e-6 && !mbm {523 if blend <= 1e-6 && !mbm {
505 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);524 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
506 }525 }
507 if n.static_str("ClippingMode").unwrap_or("Frame") != "None" || has_mask {526 if n.static_str("ClippingMode").unwrap_or("Frame") != "None" || has_mask {
508 Some(RoiBox::canvas(canvas_size))527 Some(RoiBox::canvas(canvas_size))
...@@ -513,18 +532,18 @@ fn roi_from_consumer(...@@ -513,18 +532,18 @@ fn roi_from_consumer(
513 "Dissolve" => {532 "Dissolve" => {
514 let mix_v = comp.eval_number(n, "Mix", time, 1.0, expr).clamp(0.0, 1.0);533 let mix_v = comp.eval_number(n, "Mix", time, 1.0, expr).clamp(0.0, 1.0);
515 let blend = comp.eval_number(n, "Blend", time, 1.0, expr);534 let blend = comp.eval_number(n, "Blend", time, 1.0, expr);
516 let has_mask = n.connected_node("EffectMask").is_some();535 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
517 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;536 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
518 if (blend <= 1e-6 || mix_v <= 1e-6) && !mbm {537 if (blend <= 1e-6 || mix_v <= 1e-6) && !mbm {
519 return match port {538 return match port {
520 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),539 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
521 "Foreground" => Some(RoiBox::Empty),540 "Foreground" => Some(RoiBox::Empty),
522 _ => None,541 _ => None,
523 };542 };
524 }543 }
525 if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask {544 if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask {
526 return match port {545 return match port {
527 "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),546 "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
528 "Background" => Some(RoiBox::Empty),547 "Background" => Some(RoiBox::Empty),
529 _ => None,548 _ => None,
530 };549 };
...@@ -541,7 +560,7 @@ fn roi_from_consumer(...@@ -541,7 +560,7 @@ fn roi_from_consumer(
541 }560 }
542 let hiq_only = comp.eval_number(n, "HiQOnly", time, 0.0, expr) > 0.5;561 let hiq_only = comp.eval_number(n, "HiQOnly", time, 0.0, expr) > 0.5;
543 if n.kind == "Scale" && !hiq && hiq_only {562 if n.kind == "Scale" && !hiq && hiq_only {
544 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)563 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
545 } else {564 } else {
546 Some(RoiBox::canvas(canvas_size))565 Some(RoiBox::canvas(canvas_size))
547 }566 }
...@@ -552,10 +571,10 @@ fn roi_from_consumer(...@@ -552,10 +571,10 @@ fn roi_from_consumer(
552 }571 }
553 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;572 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
554 let mbm = n.kind != "Fuse.XGlow"573 let mbm = n.kind != "Fuse.XGlow"
555 && n.connected_node("EffectMask").is_some()574 && Engine::resolve_effect_mask_id(comp, n).is_some()
556 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;575 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
557 if blend <= 1e-6 && !mbm {576 if blend <= 1e-6 && !mbm {
558 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)577 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
559 } else {578 } else {
560 Some(RoiBox::canvas(canvas_size))579 Some(RoiBox::canvas(canvas_size))
561 }580 }
...@@ -565,23 +584,58 @@ fn roi_from_consumer(...@@ -565,23 +584,58 @@ fn roi_from_consumer(
565 return None;584 return None;
566 }585 }
567 let fg_none = n.connected_node("Foreground").and_then(|s| comp.find_node(s)).is_none();586 let fg_none = n.connected_node("Foreground").and_then(|s| comp.find_node(s)).is_none();
568 let mbm = n.connected_node("EffectMask").is_some()587 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
569 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;588 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
570 if fg_none && !mbm {589 if fg_none && !mbm {
571 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)590 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
572 } else {591 } else {
573 Some(RoiBox::canvas(canvas_size))592 Some(RoiBox::canvas(canvas_size))
574 }593 }
575 }594 }
576 "CameraShake" | "DVE" | "Vortex" | "Drip" | "Dent" | "GridWarp" | "VariBlur"595 "CameraShake" => {
577 | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Fuse.XfChroma"596 if port != "Input" {
578 | "Paint" => {597 return None;
598 }
599 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
600 let strength = comp.eval_number(n, "OverallStrength", time, 1.0, expr);
601 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
602 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
603 if (blend <= 1e-6 || strength.abs() <= 1e-6) && !mbm {
604 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
605 } else {
606 None
607 }
608 }
609 "GridWarp" => {
610 if port != "Input" {
611 return None;
612 }
613 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
614 if blend <= 1e-6 {
615 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
616 } else {
617 None
618 }
619 }
620 "Fuse.XfChroma" => {
621 if port != "Input" && port != "Image" {
622 return None;
623 }
624 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
625 if blend <= 1e-6 {
626 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
627 } else {
628 None
629 }
630 }
631 "DVE" | "Vortex" | "Drip" | "Dent" | "VariBlur"
632 | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Paint" => {
579 if port != default_main_input_port(&n.kind) && port != "Input" && port != "Image" {633 if port != default_main_input_port(&n.kind) && port != "Input" && port != "Image" {
580 return None;634 return None;
581 }635 }
582 // Conservatively union canvas crop with downstream RoI in case the node short-circuits636 // Conservatively union canvas crop with downstream RoI in case the node short-circuits
583 // on an idle parameter (e.g. Blend = 0, radius = 0, etc.).637 // on an idle parameter (e.g. Blend = 0, radius = 0, etc.).
584 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;638 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
585 Some(RoiBox::canvas(canvas_size).union(down))639 Some(RoiBox::canvas(canvas_size).union(down))
586 }640 }
587 "Blur" => {641 "Blur" => {
...@@ -606,7 +660,7 @@ fn roi_from_consumer(...@@ -606,7 +660,7 @@ fn roi_from_consumer(
606 let ry = y_raw * scale_ref * gauss_k;660 let ry = y_raw * scale_ref * gauss_k;
607 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;661 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
608 if rx.max(ry) < 0.25 || blend <= 1e-6 {662 if rx.max(ry) < 0.25 || blend <= 1e-6 {
609 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);663 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
610 }664 }
611 if Engine::resolve_effect_mask_id(comp, n).is_some() {665 if Engine::resolve_effect_mask_id(comp, n).is_some() {
612 return Some(RoiBox::canvas(canvas_size));666 return Some(RoiBox::canvas(canvas_size));
...@@ -614,7 +668,7 @@ fn roi_from_consumer(...@@ -614,7 +668,7 @@ fn roi_from_consumer(
614 if !rx.is_finite() || !ry.is_finite() || rx.abs() * 1.6 > 2048.0 || ry.abs() * 1.6 > 2048.0 {668 if !rx.is_finite() || !ry.is_finite() || rx.abs() * 1.6 > 2048.0 || ry.abs() * 1.6 > 2048.0 {
615 return None;669 return None;
616 }670 }
617 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;671 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
618 let RoiBox::Rect { x0, y0, x1, y1 } = down else {672 let RoiBox::Rect { x0, y0, x1, y1 } = down else {
619 return Some(RoiBox::Empty);673 return Some(RoiBox::Empty);
620 };674 };
...@@ -633,7 +687,7 @@ fn roi_from_consumer(...@@ -633,7 +687,7 @@ fn roi_from_consumer(
633 }687 }
634 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;688 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
635 if blend <= 1e-6 {689 if blend <= 1e-6 {
636 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);690 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
637 }691 }
638 if comp.eval_number(n, "InvertTransform", time, 0.0, expr) > 0.5 {692 if comp.eval_number(n, "InvertTransform", time, 0.0, expr) > 0.5 {
639 return None;693 return None;
...@@ -643,31 +697,39 @@ fn roi_from_consumer(...@@ -643,31 +697,39 @@ fn roi_from_consumer(
643 return None;697 return None;
644 }698 }
645 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();699 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
646 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;700 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
647 inverse_transform_box(comp, n, time, expr, canvas_size, has_mask, blend, down)701 inverse_transform_box(comp, n, time, expr, canvas_size, has_mask, blend, down)
648 }702 }
649 "Merge" => {703 "Merge" => {
650 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;704 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
651 let mbm = n.connected_node("EffectMask").is_some()705 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
652 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;706 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
653 if blend <= 1e-6 && !mbm {707 if blend <= 1e-6 && !mbm {
654 return match port {708 return match port {
655 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),709 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
656 "Foreground" => Some(RoiBox::Empty),710 "Foreground" => Some(RoiBox::Empty),
657 _ => None,711 _ => None,
658 };712 };
659 }713 }
660 if port == "Background" {714 if port == "Background" {
661 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);715 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
662 }716 }
663 if port == "Foreground" {717 if port == "Foreground" {
664 let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32;718 let raw_edges = comp.eval_number(n, "Edges", time, 0.0, expr) as f32;
665 if edges != 0 {719 let fg_id = n.connected_node("Foreground").and_then(|s| comp.find_node(s));
720 let edges = if raw_edges < 0.5 {
721 fg_id
722 .and_then(|fid| Engine::flattened_fg_edge_mode(comp, fid, time, expr))
723 .unwrap_or(raw_edges)
724 } else {
725 raw_edges
726 };
727 if edges.round() as i32 != 0 {
666 return None;728 return None;
667 }729 }
668 let bg_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?;730 let bg_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?;
669 let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, 16)?;731 let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, proxy_scale, hiq, 16)?;
670 let down = roi_for_node(comp, cid, bg_canvas, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;732 let down = roi_for_node(comp, cid, bg_canvas, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
671 return inverse_merge_fg_box(comp, n, time, expr, bg_canvas, canvas_size, down);733 return inverse_merge_fg_box(comp, n, time, expr, bg_canvas, canvas_size, down);
672 }734 }
673 None735 None
...@@ -725,6 +787,7 @@ impl Engine {...@@ -725,6 +787,7 @@ impl Engine {
725 merge_id,787 merge_id,
726 canvas_size,788 canvas_size,
727 comp_dims,789 comp_dims,
790 self.proxy_scale,
728 time,791 time,
729 time_key,792 time_key,
730 self.hiq,793 self.hiq,
...@@ -865,7 +928,18 @@ impl Engine {...@@ -865,7 +928,18 @@ impl Engine {
865 let mut dst_size = bg.size;928 let mut dst_size = bg.size;
866929
867 let roi_bounds = if bg.tex_scale >= 0.99 && fg.tex_scale >= 0.99 {930 let roi_bounds = if bg.tex_scale >= 0.99 && fg.tex_scale >= 0.99 {
868 self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time)931 self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time).map(|(rx0, ry0, rx1, ry1)| {
932 if visiting.len() == 1 {
933 (
934 rx0.min(0),
935 ry0.min(0),
936 rx1.max(bg.canvas_size[0].max(1) as i32),
937 ry1.max(bg.canvas_size[1].max(1) as i32),
938 )
939 } else {
940 (rx0, ry0, rx1, ry1)
941 }
942 })
869 } else {943 } else {
870 None944 None
871 };945 };
...@@ -2060,4 +2134,108 @@ mod tests {...@@ -2060,4 +2134,108 @@ mod tests {
2060 let cr_px = eng.readback_rgba(&cr_tex).unwrap();2134 let cr_px = eng.readback_rgba(&cr_tex).unwrap();
2061 assert!(px_at(&cr_px, cr_tex.size[0], 8, 8)[0] > 200, "Crop at negative offset must sample expanded DoD");2135 assert!(px_at(&cr_px, cr_tex.size[0], 8, 8)[0] > 200, "Crop at negative offset must sample expanded DoD");
2062 }2136 }
2137
2138 #[test]
2139 fn directly_evaluated_merge_upstream_of_zoomed_in_transform_renders_full_canvas() {
2140 let comp_src = r#"{
2141 Tools = ordered() {
2142 Bg = Background {
2143 Inputs = {
2144 Width = Input { Value = 64, },
2145 Height = Input { Value = 64, },
2146 TopLeftRed = Input { Value = 1.0, },
2147 TopLeftAlpha = Input { Value = 1.0, },
2148 },
2149 },
2150 Fg = Background {
2151 Inputs = {
2152 Width = Input { Value = 64, },
2153 Height = Input { Value = 64, },
2154 TopLeftGreen = Input { Value = 1.0, },
2155 TopLeftAlpha = Input { Value = 1.0, },
2156 },
2157 },
2158 M = Merge {
2159 Inputs = {
2160 Background = Input { SourceOp = "Bg", Source = "Output", },
2161 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2162 },
2163 },
2164 ZoomIn = Transform {
2165 Inputs = {
2166 Size = Input { Value = 2.0, },
2167 Input = Input { SourceOp = "M", Source = "Output", },
2168 },
2169 },
2170 }
2171 }"#;
2172 let comp = Comp::from_fusion_str(comp_src).expect("parse zoom-in comp");
2173 let mut eng = Engine::new_headless().expect("headless engine");
2174 let (m_tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
2175 assert_eq!(m_tex.size, [64, 64]);
2176 let m_px = eng.readback_rgba(&m_tex).unwrap();
2177 assert_eq!(px_at(&m_px, 64, 2, 2), [0, 255, 0, 255], "corner of directly-evaluated Merge must not be cropped by downstream ZoomIn");
2178 assert_eq!(px_at(&m_px, 64, 61, 61), [0, 255, 0, 255]);
2179
2180 let (z_tex, _) = eng.evaluate(&comp, comp.find_node("ZoomIn").unwrap(), 0.0);
2181 assert_eq!(z_tex.size, [64, 64]);
2182 let z_px = eng.readback_rgba(&z_tex).unwrap();
2183 assert_eq!(px_at(&z_px, 64, 32, 32), [0, 255, 0, 255]);
2184 }
2185
2186 #[test]
2187 fn camera_shake_and_xf_chroma_preserve_upstream_dod_when_active() {
2188 let comp_src = r#"{
2189 Tools = ordered() {
2190 Bg = Background {
2191 Inputs = {
2192 Width = Input { Value = 64, },
2193 Height = Input { Value = 64, },
2194 TopLeftAlpha = Input { Value = 1.0, },
2195 },
2196 },
2197 HugeFg = Background {
2198 Inputs = {
2199 Width = Input { Value = 256, },
2200 Height = Input { Value = 256, },
2201 TopLeftRed = Input { Value = 1.0, },
2202 TopLeftAlpha = Input { Value = 1.0, },
2203 },
2204 },
2205 MShake = Merge {
2206 Inputs = {
2207 Background = Input { SourceOp = "Bg", Source = "Output", },
2208 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2209 },
2210 },
2211 Shake = CameraShake {
2212 Inputs = {
2213 Input = Input { SourceOp = "MShake", Source = "Output", },
2214 },
2215 },
2216 MChroma = Merge {
2217 Inputs = {
2218 Background = Input { SourceOp = "Bg", Source = "Output", },
2219 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2220 },
2221 },
2222 Chroma = Fuse.XfChroma {
2223 Inputs = {
2224 Input = Input { SourceOp = "MChroma", Source = "Output", },
2225 },
2226 },
2227 }
2228 }"#;
2229 let comp = Comp::from_fusion_str(comp_src).expect("parse dod consumers comp");
2230 let mut eng = Engine::new_headless().expect("headless engine");
2231 let mut enc = eng.device.create_command_encoder(&Default::default());
2232 let mut visiting = std::collections::HashSet::new();
2233 let mut stats = super::EvalStats::default();
2234
2235 let ms_tex = eng.eval_node(&comp, comp.find_node("MShake").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
2236 assert_eq!(ms_tex.size, [260, 260], "CameraShake must preserve full upstream DoD");
2237 let mc_tex = eng.eval_node(&comp, comp.find_node("MChroma").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
2238 assert_eq!(mc_tex.size, [260, 260], "Fuse.XfChroma must preserve full upstream DoD");
2239 eng.queue.submit(Some(enc.finish()));
2240 }
2063}2241}
crates/engine/src/eval/masks.rs+39-3
...@@ -254,9 +254,10 @@ impl Engine {...@@ -254,9 +254,10 @@ impl Engine {
254 let soft_px = soft * size[0] as f32;254 let soft_px = soft * size[0] as f32;
255 let need_post = soft_px >= 0.5 || invert || (level - 1.0).abs() > 1e-4 || prev_mask.is_some();255 let need_post = soft_px >= 0.5 || invert || (level - 1.0).abs() > 1e-4 || prev_mask.is_some();
256 let raw_tex = self.alloc_tex(size, BitDepth::Int8, if need_post { 0 } else { key });256 let raw_tex = self.alloc_tex(size, BitDepth::Int8, if need_post { 0 } else { key });
257 let soft_px = soft * raw_tex.size[0] as f32;
257258
258 let has_coverage = match polyline_tight_commands(size, &points, [center[0] as f32, center[1] as f32], angle) {259 let has_coverage = match polyline_tight_commands(raw_tex.size, &points, [center[0] as f32, center[1] as f32], angle) {
259 Some(([bx0, by0, bx1, by1], cmds)) if raw_tex.size == size => {260 Some(([bx0, by0, bx1, by1], cmds)) => {
260 let bw = (bx1 - bx0) as u32;261 let bw = (bx1 - bx0) as u32;
261 let bh = (by1 - by0) as u32;262 let bh = (by1 - by0) as u32;
262 let mut cov_buf = vec![0u8; (bw as usize) * (bh as usize)];263 let mut cov_buf = vec![0u8; (bw as usize) * (bh as usize)];
...@@ -279,7 +280,7 @@ impl Engine {...@@ -279,7 +280,7 @@ impl Engine {
279 }280 }
280 }281 }
281282
282 if bw == size[0] && bh == size[1] {283 if bw == raw_tex.size[0] && bh == raw_tex.size[1] {
283 self.queue.write_texture(284 self.queue.write_texture(
284 raw_tex.texture.as_image_copy(),285 raw_tex.texture.as_image_copy(),
285 &rgba,286 &rgba,
...@@ -1316,4 +1317,39 @@ mod tests {...@@ -1316,4 +1317,39 @@ mod tests {
1316 let soft_px = eng.readback_rgba(&soft_tex).unwrap();1317 let soft_px = eng.readback_rgba(&soft_tex).unwrap();
1317 assert_eq!(soft_px, ref_px, "SoftEdge PolylineMask must match full-canvas pixel-for-pixel");1318 assert_eq!(soft_px, ref_px, "SoftEdge PolylineMask must match full-canvas pixel-for-pixel");
1318 }1319 }
1320
1321 #[test]
1322 fn polyline_mask_larger_than_max_texture_dimension_rasterizes_into_clamped_size() {
1323 let Ok(mut eng) = Engine::new_headless() else { return };
1324 let max_dim = eng.device.limits().max_texture_dimension_2d.max(1);
1325 let req_w = max_dim * 2;
1326 let comp_src = format!(
1327 r#"{{
1328 Tools = ordered() {{
1329 BigPoly = PolylineMask {{
1330 Inputs = {{
1331 MaskWidth = Input {{ Value = {req_w}, }},
1332 MaskHeight = Input {{ Value = 32, }},
1333 Polyline = Input {{
1334 Value = Polyline {{
1335 Closed = true,
1336 Points = {{
1337 {{ Linear = true, X = -0.25, Y = -0.25 }},
1338 {{ Linear = true, X = 0.25, Y = -0.25 }},
1339 {{ Linear = true, X = 0.25, Y = 0.25 }},
1340 {{ Linear = true, X = -0.25, Y = 0.25 }},
1341 }}
1342 }},
1343 }},
1344 }},
1345 }},
1346 }}
1347 }}"#
1348 );
1349 let comp = Comp::from_fusion_str(&comp_src).expect("parse clamped polyline comp");
1350 let (tex, _) = eng.evaluate(&comp, comp.find_node("BigPoly").unwrap(), 0.0);
1351 assert_eq!(tex.size, [max_dim, 16]);
1352 let px = eng.readback_rgba(&tex).unwrap();
1353 assert!(px.chunks_exact(4).any(|c| c[3] > 200), "clamped PolylineMask must rasterize cleanly instead of clearing to transparent");
1354 }
1319}1355}
crates/engine/src/eval/text_3d.rs+127-41
...@@ -265,7 +265,10 @@ fn scale_text_chars_x(...@@ -265,7 +265,10 @@ fn scale_text_chars_x(
265 out_x0 = out_x0.min((cx - hw).floor() as i32);265 out_x0 = out_x0.min((cx - hw).floor() as i32);
266 out_x1 = out_x1.max((cx + hw).ceil() as i32);266 out_x1 = out_x1.max((cx + hw).ceil() as i32);
267 }267 }
268 out_x0 = out_x0.clamp(0, cw);268 if cw <= 0 || out_x0 >= cw || out_x1 <= 0 {
269 return ([1, 1], [0, 0], vec![0; 4]);
270 }
271 out_x0 = out_x0.clamp(0, cw - 1);
269 out_x1 = out_x1.clamp(out_x0 + 1, cw);272 out_x1 = out_x1.clamp(out_x0 + 1, cw);
270 let out_w = (out_x1 - out_x0) as usize;273 let out_w = (out_x1 - out_x0) as usize;
271 let mut out = vec![0u8; out_w * th * 4];274 let mut out = vec![0u8; out_w * th * 4];
...@@ -306,52 +309,74 @@ fn scale_text_chars_x(...@@ -306,52 +309,74 @@ fn scale_text_chars_x(
306const _: fn([u32; 2], &TextPlusParams<'_>, i32) -> ([u32; 2], [i32; 2], Vec<u8>) = rasterize_text_plus;309const _: fn([u32; 2], &TextPlusParams<'_>, i32) -> ([u32; 2], [i32; 2], Vec<u8>) = rasterize_text_plus;
307310
308fn needs_canvas_aligned_text_output(comp: &Comp, node: &Node) -> bool {311fn needs_canvas_aligned_text_output(comp: &Comp, node: &Node) -> bool {
309 let mut target_names: Vec<&str> = vec![node.name.as_str()];312 let mut queue = std::collections::VecDeque::new();
310 let mut seen = HashSet::new();313 let mut seen = HashSet::new();
314 queue.push_back(node.id);
311 seen.insert(node.id);315 seen.insert(node.id);
312 for _ in 0..4 {316 while let Some(cur_id) = queue.pop_front() {
313 let mut added = false;317 let cur_name = comp.node(cur_id).name.as_str();
314 for other in &comp.nodes {318 for other in &comp.nodes {
315 if seen.contains(&other.id) {319 let mut is_passthrough = matches!(other.kind.as_str(), "MacroOperator" | "GroupOperator")
316 continue;320 && other.macro_output == Some(cur_id);
317 }321 for (port, b) in &other.inputs {
318 let reads_target = other322 if b.source_op.as_deref() != Some(cur_name) {
319 .inputs323 continue;
320 .values()324 }
321 .any(|b| b.source_op.as_deref().is_some_and(|s| target_names.contains(&s)));325 if other.bypassed
322 if !reads_target {326 || matches!(
323 continue;327 other.kind.as_str(),
324 }328 "PipeRouter"
325 if other.bypassed || matches!(other.kind.as_str(), "PipeRouter" | "Fuse.Wireless") {329 | "Fuse.Wireless"
326 seen.insert(other.id);330 | "Wireless"
327 target_names.push(other.name.as_str());331 | "Switch"
328 added = true;332 | "Fuse.Switch"
329 continue;333 | "Fuse.SwitchElse"
334 | "MacroOperator"
335 | "GroupOperator"
336 )
337 {
338 is_passthrough = true;
339 continue;
340 }
341 if (other.kind == "Merge" && port == "Background")
342 || matches!(
343 other.kind.as_str(),
344 "pEmitter"
345 | "Renderer3D"
346 | "Displace3D"
347 | "Texture2DOperator"
348 | "TextureTransformOperator"
349 | "BumpMap"
350 | "Shape3D"
351 | "ImagePlane3D"
352 | "ReplaceMaterial3D"
353 | "TimeStretcher"
354 | "TimeSpeed"
355 | "Fuse.Outline"
356 | "ErodeDilate"
357 | "Blur"
358 | "Glow"
359 | "SoftGlow"
360 | "InvertColor"
361 | "BrightnessContrast"
362 | "ColorCorrector"
363 | "Fuse.Colorize"
364 | "VariBlur"
365 | "Filter"
366 | "ColorCurves"
367 | "HueCurves"
368 | "ColorGain"
369 | "Custom"
370 )
371 || other.kind.starts_with("Mtl")
372 {
373 return true;
374 }
330 }375 }
331 if matches!(376 if is_passthrough && seen.insert(other.id) {
332 other.kind.as_str(),377 queue.push_back(other.id);
333 "Fuse.Outline"
334 | "ErodeDilate"
335 | "Blur"
336 | "Glow"
337 | "SoftGlow"
338 | "InvertColor"
339 | "BrightnessContrast"
340 | "ColorCorrector"
341 | "Fuse.Colorize"
342 | "VariBlur"
343 | "Filter"
344 | "ColorCurves"
345 | "HueCurves"
346 | "ColorGain"
347 | "Custom"
348 ) {
349 return true;
350 }378 }
351 }379 }
352 if !added {
353 break;
354 }
355 }380 }
356 false381 false
357}382}
...@@ -1494,4 +1519,65 @@ Composition {...@@ -1494,4 +1519,65 @@ Composition {
1494 let cov_tm = px_tm.chunks_exact(4).filter(|c| c[3] > 200).count();1519 let cov_tm = px_tm.chunks_exact(4).filter(|c| c[3] > 200).count();
1495 assert!(cov_ed > cov_tm + 50, "ErodeDilate downstream of TextPlus must dilate using canvas width: {cov_ed} vs {cov_tm}");1520 assert!(cov_ed > cov_tm + 50, "ErodeDilate downstream of TextPlus must dilate using canvas width: {cov_ed} vs {cov_tm}");
1496 }1521 }
1522
1523 #[test]
1524 fn offscreen_right_text3d_with_char_size_x_does_not_panic() {
1525 let (sz, orig, px) = super::scale_text_chars_x([8, 8], [150, 10], [128, 128], vec![255; 8 * 8 * 4], 1.5);
1526 assert_eq!(sz, [1, 1]);
1527 assert_eq!(orig, [0, 0]);
1528 assert_eq!(px, vec![0; 4]);
1529
1530 let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() {
1531 T = Text3D { Inputs = {
1532 StyledText = Input { Value = "OFF", },
1533 Size = Input { Value = 0.25, },
1534 Center = Input { Value = { 1.5, 0.5 }, },
1535 CharacterSizeX = Input { Value = 1.5, },
1536 }, },
1537 Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, }, },
1538 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "T", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },
1539 R = Renderer3D { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, SceneInput = Input { SourceOp = "M", Source = "Output", }, }, },
1540 } }"#;
1541 let comp = Comp::from_fusion_str(src).unwrap();
1542 let Ok(mut eng) = Engine::new_headless() else { return };
1543 let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0);
1544 assert_eq!(tex.size, [128, 128]);
1545 }
1546
1547 #[test]
1548 fn text_plus_feeding_merge_background_and_time_speed_gets_canvas_aligned_output() {
1549 let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 5 }, GlobalRange = { 0, 5 }, Tools = ordered() {
1550 TxtBg = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "BG", }, Size = Input { Value = 0.2, }, }, },
1551 TxtFg = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "FG", }, Size = Input { Value = 0.2, }, }, },
1552 M = Merge { Inputs = {
1553 Background = Input { SourceOp = "TxtBg", Source = "Output", },
1554 Foreground = Input { SourceOp = "TxtFg", Source = "Output", },
1555 }, },
1556 TxtTime = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "TM", }, Size = Input { Value = 0.2, }, }, },
1557 P1 = PipeRouter { Inputs = { Input = Input { SourceOp = "TxtTime", Source = "Output", }, }, },
1558 P2 = PipeRouter { Inputs = { Input = Input { SourceOp = "P1", Source = "Output", }, }, },
1559 P3 = PipeRouter { Inputs = { Input = Input { SourceOp = "P2", Source = "Output", }, }, },
1560 P4 = PipeRouter { Inputs = { Input = Input { SourceOp = "P3", Source = "Output", }, }, },
1561 Sw = Fuse.Switch { Inputs = { Input1 = Input { SourceOp = "P4", Source = "Output", }, }, },
1562 TS = TimeSpeed { Inputs = { Speed = Input { Value = 1.0, }, Input = Input { SourceOp = "Sw", Source = "Output", }, }, },
1563 } }"#;
1564 let comp = Comp::from_fusion_str(src).unwrap();
1565 assert!(super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtBg").unwrap())));
1566 assert!(!super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtFg").unwrap())));
1567 assert!(super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtTime").unwrap())));
1568
1569 let Ok(mut eng) = Engine::new_headless() else { return };
1570 let mut enc = eng.device.create_command_encoder(&Default::default());
1571 let mut visiting = std::collections::HashSet::new();
1572 let mut stats = super::EvalStats::default();
1573 let t_bg = eng.eval_node(&comp, comp.find_node("TxtBg").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
1574 assert_eq!(t_bg.origin, [0, 0]);
1575 assert_eq!(t_bg.size, [128, 64]);
1576 let t_fg = eng.eval_node(&comp, comp.find_node("TxtFg").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
1577 assert!(t_fg.has_dod(), "TextPlus feeding only Merge.Foreground keeps tight DoD");
1578 let t_time = eng.eval_node(&comp, comp.find_node("TxtTime").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
1579 assert_eq!(t_time.origin, [0, 0]);
1580 assert_eq!(t_time.size, [128, 64]);
1581 eng.queue.submit(Some(enc.finish()));
1582 }
1497}1583}
crates/model/src/comp/eval.rs+77-18
...@@ -13,6 +13,13 @@ thread_local! {...@@ -13,6 +13,13 @@ thread_local! {
13 RefCell::new((0, HashMap::new()));13 RefCell::new((0, HashMap::new()));
14}14}
1515
16/// Parses a bare `NodeName.ParamName` reference where both segments are identifier characters.
17fn parse_bare_node_param_ref(expr: &str) -> Option<(&str, &str)> {
18 let (n, p) = expr.trim().split_once('.')?;
19 let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
20 (ident(n) && ident(p)).then_some((n, p))
21}
22
16fn is_lua_keyword(tok: &str) -> bool {23fn is_lua_keyword(tok: &str) -> bool {
17 matches!(24 matches!(
18 tok,25 tok,
...@@ -153,11 +160,9 @@ impl Comp {...@@ -153,11 +160,9 @@ impl Comp {
153 }160 }
154 if let Some(expr) = &binding.expression {161 if let Some(expr) = &binding.expression {
155 // A bare `Node.Param` follows that input's own expression/animation instead of its baked value.162 // A bare `Node.Param` follows that input's own expression/animation instead of its baked value.
156 let referenced = expr.trim().split_once('.').and_then(|(n, p)| {163 let v = match parse_bare_node_param_ref(expr)
157 let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');164 .and_then(|(n, p)| Some((self.node(self.find_node(n)?), p)))
158 (ident(n) && ident(p)).then_some((n, p))165 {
159 });
160 let v = match referenced.and_then(|(n, p)| Some((self.node(self.find_node(n)?), p))) {
161 Some((other, p)) if other.inputs.contains_key(p) && other.id != node.id => {166 Some((other, p)) if other.inputs.contains_key(p) && other.id != node.id => {
162 Some(self.eval_number_at(other, p, time, f64::NAN, expr_engine, depth + 1))167 Some(self.eval_number_at(other, p, time, f64::NAN, expr_engine, depth + 1))
163 }168 }
...@@ -429,10 +434,10 @@ impl Comp {...@@ -429,10 +434,10 @@ impl Comp {
429 if let Some(expr) = &b.expression {434 if let Some(expr) = &b.expression {
430 let trimmed = expr.trim();435 let trimmed = expr.trim();
431 // Direct `NodeName.ParamName` reference to a Point input on another flow node.436 // Direct `NodeName.ParamName` reference to a Point input on another flow node.
432 if let Some((node_name, param_name)) = trimmed.split_once('.') {437 if let Some((node_name, param_name)) = parse_bare_node_param_ref(trimmed) {
433 if !param_name.contains('.') && !param_name.contains(' ') {438 if let Some(other) = self.find_node(node_name).map(|nid| self.node(nid)) {
434 if let Some(nid) = self.find_node(node_name.trim()) {439 if other.inputs.contains_key(param_name) {
435 return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1);440 return self.eval_point_at(other, param_name, time, default, expr_engine, depth + 1);
436 }441 }
437 }442 }
438 }443 }
...@@ -479,12 +484,12 @@ impl Comp {...@@ -479,12 +484,12 @@ impl Comp {
479 depth: usize,484 depth: usize,
480 ) -> Option<f64> {485 ) -> Option<f64> {
481 let trimmed = expr.trim();486 let trimmed = expr.trim();
482 if let Some((node_name, param_name)) = trimmed.split_once('.') {487 if let Some((node_name, param_name)) = parse_bare_node_param_ref(trimmed) {
483 if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') {488 if let Some(other) = self.find_node(node_name).map(|nid| self.node(nid)) {
484 if let Some(nid) = self.find_node(node_name.trim()) {489 if other.inputs.contains_key(param_name) {
485 return Some(self.eval_number_at(490 return Some(self.eval_number_at(
486 self.node(nid),491 other,
487 param_name.trim(),492 param_name,
488 time,493 time,
489 0.0,494 0.0,
490 expr_engine,495 expr_engine,
...@@ -497,7 +502,7 @@ impl Comp {...@@ -497,7 +502,7 @@ impl Comp {
497 expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en)502 expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en)
498 }503 }
499504
500 /// `node name -> numeric/text inputs` for the nodes `expr` can reach; every other node is skipped.505 /// `node name -> numeric/text/point inputs` for the nodes `expr` can reach; every other node is skipped.
501 fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, ExprValue>> {506 fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, ExprValue>> {
502 let mut env = HashMap::new();507 let mut env = HashMap::new();
503 for tok in expr508 for tok in expr
...@@ -511,7 +516,7 @@ impl Comp {...@@ -511,7 +516,7 @@ impl Comp {
511 .map(|n| (n.name.clone(), self.node_expr_vars(n, time)))516 .map(|n| (n.name.clone(), self.node_expr_vars(n, time)))
512 .collect();517 .collect();
513 }518 }
514 if tok == "self" || is_lua_keyword(tok) || env.contains_key(tok) {519 if is_lua_keyword(tok) || env.contains_key(tok) {
515 continue;520 continue;
516 }521 }
517 if let Some(nid) = self.find_node(tok) {522 if let Some(nid) = self.find_node(tok) {
...@@ -534,10 +539,24 @@ impl Comp {...@@ -534,10 +539,24 @@ impl Comp {
534 vars.insert(k.clone(), ExprValue::Text(t.clone()));539 vars.insert(k.clone(), ExprValue::Text(t.clone()));
535 continue;540 continue;
536 }541 }
542 Some(ParamValue::Point(pt)) => {
543 vars.insert(k.clone(), ExprValue::Point(*pt));
544 continue;
545 }
537 _ => {}546 _ => {}
538 }547 }
539 if let Some(sp) = b.source_op.as_ref().and_then(|src| self.splines.get(src)) {548 if let Some(src) = b.source_op.as_deref() {
540 vars.insert(k.clone(), ExprValue::Number(sp.eval(time)));549 if let Some(sp) = self.splines.get(src) {
550 vars.insert(k.clone(), ExprValue::Number(sp.eval(time)));
551 } else if let Some(pp) = self.poly_paths.get(src) {
552 let disp = pp
553 .displacement_op
554 .as_deref()
555 .and_then(|d| self.splines.get(d))
556 .map(|sp| sp.eval(time))
557 .unwrap_or(pp.displacement_value);
558 vars.insert(k.clone(), ExprValue::Point(pp.eval_center(disp)));
559 }
541 }560 }
542 }561 }
543 vars562 vars
...@@ -998,4 +1017,44 @@ mod tests {...@@ -998,4 +1017,44 @@ mod tests {
998 assert_eq!(comp.checker_piece_metrics(node("Tiny"), 0.0, &engine), (2, 0.2));1017 assert_eq!(comp.checker_piece_metrics(node("Tiny"), 0.0, &engine), (2, 0.2));
999 assert_eq!(comp.eval_number(m, "Angle", 0.0, 7.0, &engine), 7.0, "non-ExtraScale outputs stay unresolved");1018 assert_eq!(comp.eval_number(m, "Angle", 0.0, 7.0, &engine), 7.0, "non-ExtraScale outputs stay unresolved");
1000 }1019 }
1020
1021 #[test]
1022 fn expression_modifier_spaceless_arithmetic_and_self_named_node() {
1023 let src = r#"Composition {
1024 Tools = ordered() {
1025 BG1 = Background { Inputs = {
1026 Width = Input { Value = 320, },
1027 Center = Input { Value = { 0.25, 0.5 }, },
1028 }, },
1029 self = Background { Inputs = {
1030 Width = Input { Value = 100, },
1031 }, },
1032 Out = Transform { Inputs = {
1033 Size = Input { SourceOp = "NumMod", Source = "NumberResult", },
1034 Center = Input { SourceOp = "PtMod", Source = "PointResult", },
1035 Angle = Input { SourceOp = "SelfMod", Source = "NumberResult", },
1036 }, },
1037 NumMod = Expression { Inputs = {
1038 n1 = Input { Expression = "BG1.Width*2", },
1039 NumberExpression = Input { Value = "n1", },
1040 }, },
1041 PtMod = Expression { Inputs = {
1042 p1 = Input { Expression = "BG1.Center+Point(0.1,0)", },
1043 PointExpressionX = Input { Value = "p1x", },
1044 PointExpressionY = Input { Value = "p1y", },
1045 }, },
1046 SelfMod = Expression { Inputs = {
1047 n1 = Input { Expression = "self.Width*3", },
1048 NumberExpression = Input { Value = "n1", },
1049 }, },
1050 }
1051 }"#;
1052 let comp = Comp::from_fusion_str(src).unwrap();
1053 let engine = ExprEngine::new();
1054 let out = comp.node(comp.find_node("Out").unwrap());
1055 assert_eq!(comp.eval_number(out, "Size", 0.0, -1.0, &engine), 640.0);
1056 let c = comp.eval_point(out, "Center", 0.0, [0.0, 0.0], &engine);
1057 assert!((c[0] - 0.35).abs() < 1e-12 && (c[1] - 0.5).abs() < 1e-12, "got {c:?}");
1058 assert_eq!(comp.eval_number(out, "Angle", 0.0, -1.0, &engine), 300.0);
1059 }
1001}1060}
crates/model/src/expr.rs+267-28
...@@ -9,6 +9,7 @@...@@ -9,6 +9,7 @@
9pub enum ExprValue {9pub enum ExprValue {
10 Number(f64),10 Number(f64),
11 Text(String),11 Text(String),
12 Point([f64; 2]),
12}13}
1314
14/// Lua's `tostring` for a float: C `%.14g`, so `0.1 + 0.2` reads `0.3` and `3.0` reads `3`.15/// Lua's `tostring` for a float: C `%.14g`, so `0.1 + 0.2` reads `0.3` and `3.0` reads `3`.
...@@ -54,6 +55,56 @@ mod lua {...@@ -54,6 +55,56 @@ mod lua {
54 /// Max compiled expression bytecodes cached per `ExprEngine`.55 /// Max compiled expression bytecodes cached per `ExprEngine`.
55 const CHUNK_CACHE_CAP: usize = 512;56 const CHUNK_CACHE_CAP: usize = 512;
5657
58 /// Bounded LRU cache of compiled Lua chunk bytecodes (`None` for cached syntax errors).
59 struct ChunkCache {
60 entries: HashMap<String, (Option<Vec<u8>>, u64)>,
61 tick: u64,
62 }
63
64 impl ChunkCache {
65 fn new() -> Self {
66 Self {
67 entries: HashMap::new(),
68 tick: 0,
69 }
70 }
71
72 #[cfg(test)]
73 fn len(&self) -> usize {
74 self.entries.len()
75 }
76
77 #[cfg(test)]
78 fn get(&self, key: &str) -> Option<&Option<Vec<u8>>> {
79 self.entries.get(key).map(|(v, _)| v)
80 }
81
82 fn touch(&mut self, key: &str) -> Option<&Option<Vec<u8>>> {
83 let next = self.tick.wrapping_add(1);
84 self.tick = next;
85 self.entries.get_mut(key).map(|(v, t)| {
86 *t = next;
87 &*v
88 })
89 }
90
91 fn insert(&mut self, key: String, val: Option<Vec<u8>>) {
92 let next = self.tick.wrapping_add(1);
93 self.tick = next;
94 if !self.entries.contains_key(&key) && self.entries.len() >= CHUNK_CACHE_CAP {
95 if let Some(oldest) = self
96 .entries
97 .iter()
98 .min_by_key(|(_, (_, t))| *t)
99 .map(|(k, _)| k.clone())
100 {
101 self.entries.remove(&oldest);
102 }
103 }
104 self.entries.insert(key, (val, next));
105 }
106 }
107
57 /// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`,108 /// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`,
58 /// no code loading, and bounded instructions and memory per evaluation.109 /// no code loading, and bounded instructions and memory per evaluation.
59 pub struct ExprEngine {110 pub struct ExprEngine {
...@@ -64,7 +115,8 @@ mod lua {...@@ -64,7 +115,8 @@ mod lua {
64 env_mt: Table,115 env_mt: Table,
65 zero_mt: Table,116 zero_mt: Table,
66 text_mt: Table,117 text_mt: Table,
67 chunk_cache: RefCell<HashMap<String, Option<Vec<u8>>>>,118 point_mt: Table,
119 chunk_cache: RefCell<ChunkCache>,
68 }120 }
69121
70 impl Default for ExprEngine {122 impl Default for ExprEngine {
...@@ -105,7 +157,6 @@ mod lua {...@@ -105,7 +157,6 @@ mod lua {
105 tan = math.tan157 tan = math.tan
106 tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end158 tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end
107 iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end159 iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end
108 Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end
109 local lua_tostring = tostring160 local lua_tostring = tostring
110 tostring = function(v) if type(v) == "number" then return string.format("%.14g", v) end return lua_tostring(v) end161 tostring = function(v) if type(v) == "number" then return string.format("%.14g", v) end return lua_tostring(v) end
111 Text = function(s) return tostring(s or "") end162 Text = function(s) return tostring(s or "") end
...@@ -115,6 +166,108 @@ mod lua {...@@ -115,6 +166,108 @@ mod lua {
115 let _ = lua.load(init).exec();166 let _ = lua.load(init).exec();
116167
117 let globals = lua.globals();168 let globals = lua.globals();
169 let point_mt = lua.create_table().expect("table creates");
170 let make_pt = |lua: &Lua, mt: &Table, x: f64, y: f64| -> mlua::Result<Table> {
171 let pt = lua.create_table()?;
172 pt.set("X", x)?;
173 pt.set("Y", y)?;
174 pt.set(1, x)?;
175 pt.set(2, y)?;
176 pt.set_metatable(Some(mt.clone()));
177 Ok(pt)
178 };
179 let read_pt = |v: &Value| -> Option<[f64; 2]> {
180 let Value::Table(t) = v else { return None };
181 let x = t.get::<f64>("X").or_else(|_| t.get::<f64>(1)).ok()?;
182 let y = t.get::<f64>("Y").or_else(|_| t.get::<f64>(2)).ok()?;
183 Some([x, y])
184 };
185 let read_num = |v: &Value| -> Option<f64> {
186 match v {
187 Value::Number(n) => Some(*n),
188 Value::Integer(i) => Some(*i as f64),
189 _ => None,
190 }
191 };
192 let mt_ref = point_mt.clone();
193 point_mt
194 .set(
195 "__add",
196 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
197 let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else {
198 return Err(mlua::Error::runtime("Point addition requires two Points"));
199 };
200 make_pt(lua, &mt_ref, ax + bx, ay + by)
201 })
202 .expect("function creates"),
203 )
204 .expect("table sets");
205 let mt_ref = point_mt.clone();
206 point_mt
207 .set(
208 "__sub",
209 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
210 let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else {
211 return Err(mlua::Error::runtime("Point subtraction requires two Points"));
212 };
213 make_pt(lua, &mt_ref, ax - bx, ay - by)
214 })
215 .expect("function creates"),
216 )
217 .expect("table sets");
218 let mt_ref = point_mt.clone();
219 point_mt
220 .set(
221 "__mul",
222 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
223 match (read_pt(&a), read_pt(&b), read_num(&a), read_num(&b)) {
224 (Some([ax, ay]), Some([bx, by]), _, _) => make_pt(lua, &mt_ref, ax * bx, ay * by),
225 (Some([ax, ay]), None, _, Some(s)) | (None, Some([ax, ay]), Some(s), _) => {
226 make_pt(lua, &mt_ref, ax * s, ay * s)
227 }
228 _ => Err(mlua::Error::runtime("invalid Point multiplication")),
229 }
230 })
231 .expect("function creates"),
232 )
233 .expect("table sets");
234 let mt_ref = point_mt.clone();
235 point_mt
236 .set(
237 "__div",
238 lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> {
239 match (read_pt(&a), read_pt(&b), read_num(&b)) {
240 (Some([ax, ay]), Some([bx, by]), _) => make_pt(lua, &mt_ref, ax / bx, ay / by),
241 (Some([ax, ay]), None, Some(s)) => make_pt(lua, &mt_ref, ax / s, ay / s),
242 _ => Err(mlua::Error::runtime("invalid Point division")),
243 }
244 })
245 .expect("function creates"),
246 )
247 .expect("table sets");
248 let mt_ref = point_mt.clone();
249 point_mt
250 .set(
251 "__unm",
252 lua.create_function(move |lua, a: Value| -> mlua::Result<Table> {
253 let Some([ax, ay]) = read_pt(&a) else {
254 return Err(mlua::Error::runtime("invalid Point negation"));
255 };
256 make_pt(lua, &mt_ref, -ax, -ay)
257 })
258 .expect("function creates"),
259 )
260 .expect("table sets");
261 let mt_ref = point_mt.clone();
262 globals
263 .set(
264 "Point",
265 lua.create_function(move |lua, (x, y): (Option<f64>, Option<f64>)| {
266 make_pt(lua, &mt_ref, x.unwrap_or(0.0), y.unwrap_or(0.0))
267 })
268 .expect("function creates"),
269 )
270 .expect("global sets");
118 // Stdlib tables become write-protected proxies so no evaluation can alter them for the next.271 // Stdlib tables become write-protected proxies so no evaluation can alter them for the next.
119 let read_only = lua272 let read_only = lua
120 .create_function(|_, _: MultiValue| -> mlua::Result<()> {273 .create_function(|_, _: MultiValue| -> mlua::Result<()> {
...@@ -180,14 +333,15 @@ mod lua {...@@ -180,14 +333,15 @@ mod lua {
180 env_mt,333 env_mt,
181 zero_mt,334 zero_mt,
182 text_mt,335 text_mt,
183 chunk_cache: RefCell::new(HashMap::new()),336 point_mt,
337 chunk_cache: RefCell::new(ChunkCache::new()),
184 }338 }
185 }339 }
186340
187 fn load_cached(&self, expr: &str, env: Table) -> Option<Function> {341 fn load_cached(&self, expr: &str, env: Table) -> Option<Function> {
188 {342 {
189 let cache = self.chunk_cache.borrow();343 let mut cache = self.chunk_cache.borrow_mut();
190 if let Some(hit) = cache.get(expr) {344 if let Some(hit) = cache.touch(expr) {
191 let bytes = hit.as_ref()?;345 let bytes = hit.as_ref()?;
192 return self346 return self
193 .lua347 .lua
...@@ -199,26 +353,24 @@ mod lua {...@@ -199,26 +353,24 @@ mod lua {
199 }353 }
200 }354 }
201 let chunk_src = Self::expr_chunk(expr);355 let chunk_src = Self::expr_chunk(expr);
202 let compiled = self356 match self
203 .lua357 .lua
204 .load(&chunk_src)358 .load(&chunk_src)
359 .set_mode(ChunkMode::Text)
360 .set_environment(env)
205 .into_function()361 .into_function()
206 .ok()362 {
207 .map(|f| f.dump(true));363 Ok(func) => {
208 let func = compiled.as_ref().and_then(|bytes| {364 let bytes = func.dump(true);
209 self.lua365 self.chunk_cache.borrow_mut().insert(expr.to_owned(), Some(bytes));
210 .load(bytes.as_slice())366 Some(func)
211 .set_mode(ChunkMode::Binary)367 }
212 .set_environment(env)368 Err(mlua::Error::SyntaxError { .. }) => {
213 .into_function()369 self.chunk_cache.borrow_mut().insert(expr.to_owned(), None);
214 .ok()370 None
215 });371 }
216 let mut cache = self.chunk_cache.borrow_mut();372 Err(_) => None,
217 if cache.len() >= CHUNK_CACHE_CAP {
218 cache.clear();
219 }373 }
220 cache.insert(expr.to_owned(), compiled);
221 func
222 }374 }
223375
224 /// Evaluates `expr` in a fresh environment with a fresh instruction budget.376 /// Evaluates `expr` in a fresh environment with a fresh instruction budget.
...@@ -304,6 +456,16 @@ mod lua {...@@ -304,6 +456,16 @@ mod lua {
304 }456 }
305 }457 }
306458
459 fn make_point(&self, p: [f64; 2]) -> mlua::Result<Table> {
460 let pt = self.lua.create_table()?;
461 pt.set("X", p[0])?;
462 pt.set("Y", p[1])?;
463 pt.set(1, p[0])?;
464 pt.set(2, p[1])?;
465 pt.set_metatable(Some(self.point_mt.clone()));
466 Ok(pt)
467 }
468
307 fn build_env(469 fn build_env(
308 &self,470 &self,
309 time: f64,471 time: f64,
...@@ -319,12 +481,7 @@ mod lua {...@@ -319,12 +481,7 @@ mod lua {
319 env.set(k.as_str(), *v)?;481 env.set(k.as_str(), *v)?;
320 }482 }
321 for (k, p) in self_points {483 for (k, p) in self_points {
322 let pt = self.lua.create_table()?;484 env.set(k.as_str(), self.make_point(*p)?)?;
323 pt.set("X", p[0])?;
324 pt.set("Y", p[1])?;
325 pt.set(1, p[0])?;
326 pt.set(2, p[1])?;
327 env.set(k.as_str(), pt)?;
328 }485 }
329 // Missing node fields default to 0 so expressions don't nil-crash.486 // Missing node fields default to 0 so expressions don't nil-crash.
330 for (node_name, params) in env_nodes {487 for (node_name, params) in env_nodes {
...@@ -338,6 +495,7 @@ mod lua {...@@ -338,6 +495,7 @@ mod lua {
338 text.set_metatable(Some(self.text_mt.clone()));495 text.set_metatable(Some(self.text_mt.clone()));
339 nt.set(pk.as_str(), text)?;496 nt.set(pk.as_str(), text)?;
340 }497 }
498 ExprValue::Point(p) => nt.set(pk.as_str(), self.make_point(*p)?)?,
341 }499 }
342 }500 }
343 nt.set_metatable(Some(self.zero_mt.clone()));501 nt.set_metatable(Some(self.zero_mt.clone()));
...@@ -453,6 +611,66 @@ mod lua {...@@ -453,6 +611,66 @@ mod lua {
453 assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &HashMap::new()), None);611 assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &HashMap::new()), None);
454 assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None));612 assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None));
455 }613 }
614
615 #[test]
616 fn binary_bytecode_prefix_is_rejected_in_text_mode() {
617 let engine = ExprEngine::new();
618 let empty = HashMap::new();
619 // Even with a Lua binary signature `\x1bLua...`, ChunkMode::Text rejects it safely.
620 for bad in [":\x1bLua", ":\x1bLuaT\0\x19\x0d\x0a\x1a\x0a", "\x1bLua"] {
621 assert_eq!(engine.eval_number(bad, 0.0, &HashMap::new(), &HashMap::new(), &empty), None);
622 assert_eq!(engine.chunk_cache.borrow().get(bad), Some(&None));
623 }
624 // Valid expressions continue to evaluate cleanly afterwards.
625 assert_eq!(engine.eval_number("2 + 3", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(5.0));
626 }
627
628 #[test]
629 fn syntax_vs_runtime_and_memory_error_caching_and_lru() {
630 let engine = ExprEngine::new();
631 let empty = HashMap::new();
632
633 // SyntaxError is negative-cached as None.
634 assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &empty), None);
635 assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None));
636
637 // Runtime error compiles cleanly (cached as Some(bytecode)), fails on call, and doesn't poison valid runs.
638 assert_eq!(
639 engine.eval_number("1 + nil", 0.0, &HashMap::new(), &HashMap::new(), &empty),
640 None
641 );
642 assert!(matches!(engine.chunk_cache.borrow().get("1 + nil"), Some(Some(_))));
643
644 // MemoryError during compilation is NOT negative-cached.
645 engine.lua.set_memory_limit(1).expect("tight limit applies");
646 let mem_expr = format!("1{}", " + 1".repeat(200));
647 assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), None);
648 assert_eq!(engine.chunk_cache.borrow().get(&mem_expr), None);
649 engine.lua.set_memory_limit(MEMORY_LIMIT).expect("restore memory limit");
650 assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(201.0));
651 assert!(matches!(engine.chunk_cache.borrow().get(&mem_expr), Some(Some(_))));
652
653 // LRU eviction keeps hot entries when exceeding CHUNK_CACHE_CAP.
654 let lru_engine = ExprEngine::new();
655 for i in 0..CHUNK_CACHE_CAP {
656 let expr = format!("{i} + 1");
657 assert_eq!(
658 lru_engine.eval_number(&expr, 0.0, &HashMap::new(), &HashMap::new(), &empty),
659 Some((i + 1) as f64)
660 );
661 }
662 assert_eq!(lru_engine.chunk_cache.borrow().len(), CHUNK_CACHE_CAP);
663 // Touch entry 0 so entry 1 becomes the least recently used.
664 assert_eq!(lru_engine.eval_number("0 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(1.0));
665 assert_eq!(
666 lru_engine.eval_number("9999 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty),
667 Some(10000.0)
668 );
669 let cache = lru_engine.chunk_cache.borrow();
670 assert_eq!(cache.len(), CHUNK_CACHE_CAP);
671 assert!(cache.get("0 + 1").is_some(), "hot entry 0 must stay in LRU cache");
672 assert!(cache.get("1 + 1").is_none(), "cold entry 1 must be evicted");
673 }
456 }674 }
457}675}
458676
...@@ -809,7 +1027,10 @@ mod pure {...@@ -809,7 +1027,10 @@ mod pure {
809 Ast::Num(n) | Ast::Int(n) => Val::Num(*n),1027 Ast::Num(n) | Ast::Int(n) => Val::Num(*n),
810 Ast::Str(s) => Val::Str(s.clone()),1028 Ast::Str(s) => Val::Str(s.clone()),
811 Ast::Name(n) => self.name(n),1029 Ast::Name(n) => self.name(n),
812 Ast::Neg(a) => Val::Num(-self.eval(a)?.num()?),1030 Ast::Neg(a) => match self.eval(a)? {
1031 Val::Point([x, y]) => Val::Point([-x, -y]),
1032 v => Val::Num(-v.num()?),
1033 },
813 Ast::Not(a) => Val::Bool(!self.eval(a)?.truthy()),1034 Ast::Not(a) => Val::Bool(!self.eval(a)?.truthy()),
814 Ast::Index(base, key) => index(self.eval(base)?, self.eval(key)?)?,1035 Ast::Index(base, key) => index(self.eval(base)?, self.eval(key)?)?,
815 Ast::Call(callee, args) => {1036 Ast::Call(callee, args) => {
...@@ -853,6 +1074,7 @@ mod pure {...@@ -853,6 +1074,7 @@ mod pure {
853 Val::Str(k) => match fields.get(&k) {1074 Val::Str(k) => match fields.get(&k) {
854 Some(ExprValue::Number(n)) => Val::Num(*n),1075 Some(ExprValue::Number(n)) => Val::Num(*n),
855 Some(ExprValue::Text(s)) => Val::Text(s.clone()),1076 Some(ExprValue::Text(s)) => Val::Text(s.clone()),
1077 Some(ExprValue::Point(p)) => Val::Point(*p),
856 None => Val::Num(0.0),1078 None => Val::Num(0.0),
857 },1079 },
858 _ => Val::Num(0.0),1080 _ => Val::Num(0.0),
...@@ -888,6 +1110,23 @@ mod pure {...@@ -888,6 +1110,23 @@ mod pure {
888 ">" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o == Ordering::Greater)),1110 ">" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o == Ordering::Greater)),
889 ">=" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o != Ordering::Less)),1111 ">=" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o != Ordering::Less)),
890 ".." => Val::Str(a.text()? + &b.text()?),1112 ".." => Val::Str(a.text()? + &b.text()?),
1113 "+" | "-" | "*" | "/" if matches!((&a, &b), (Val::Point(_), _) | (_, Val::Point(_))) => {
1114 match (op, a, b) {
1115 ("+", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax + bx, ay + by]),
1116 ("-", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax - bx, ay - by]),
1117 ("*", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax * bx, ay * by]),
1118 ("/", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax / bx, ay / by]),
1119 ("*", Val::Point([ax, ay]), other) | ("*", other, Val::Point([ax, ay])) => {
1120 let s = other.num()?;
1121 Val::Point([ax * s, ay * s])
1122 }
1123 ("/", Val::Point([ax, ay]), other) => {
1124 let s = other.num()?;
1125 Val::Point([ax / s, ay / s])
1126 }
1127 _ => return None,
1128 }
1129 }
891 _ => {1130 _ => {
892 let (a, b) = (a.num()?, b.num()?);1131 let (a, b) = (a.num()?, b.num()?);
893 Val::Num(match op {1132 Val::Num(match op {