diff --git a/crates/engine/src/eval/composite.rs b/crates/engine/src/eval/composite.rs index 93e3ec2a2ba1d4f2f80add6e56adb99a7dc2d534..8037576cb9d59bd987cc98888f20290941d1349f 100644 --- a/crates/engine/src/eval/composite.rs +++ b/crates/engine/src/eval/composite.rs @@ -60,6 +60,8 @@ fn infer_node_canvas_size( time: f64, expr: &ExprEngine, comp_dims: [u32; 2], + proxy_scale: u32, + hiq: bool, depth: usize, ) -> Option<[u32; 2]> { let mut cur_id = start_id; @@ -116,13 +118,23 @@ fn infer_node_canvas_size( { return None; } - let w = comp.eval_number(n, "Width", time, comp_dims[0] as f64, expr).max(1.0) as u32; - let h = comp.eval_number(n, "Height", time, comp_dims[1] as f64, expr).max(1.0) as u32; - // Only unambiguous when explicit dimensions aren't additionally proxy-scaled differently. if !n.inputs.contains_key("Width") && !n.inputs.contains_key("Height") { return Some(comp_dims); } - return Some([w, h]); + let w = comp.eval_number(n, "Width", time, comp.width as f64, expr).round().max(1.0) as u32; + let h = comp.eval_number(n, "Height", time, comp.height as f64, expr).round().max(1.0) as u32; + if matches!(n.kind.as_str(), "Background" | "FastNoise") && (w < 16 || h < 16) { + return Some(comp_dims); + } + let s = proxy_scale.max(1); + let scaled = [(w / s).max(1), (h / s).max(1)]; + if n.kind == "FastNoise" { + let cap = if hiq { 8192 } else { 4096 }; + if scaled[0].max(scaled[1]) > cap { + return None; + } + } + return Some(scaled); } _ => return None, } @@ -353,6 +365,7 @@ fn roi_for_node( node_id: NodeId, canvas_size: [u32; 2], comp_dims: [u32; 2], + proxy_scale: u32, time: f64, time_key: i64, hiq: bool, @@ -365,7 +378,11 @@ fn roi_for_node( if depth == 0 { return None; } - if let Some(&cached) = memo.get(&(node_id, time_key)) { + let mut mh = DefaultHasher::new(); + time_key.hash(&mut mh); + canvas_size.hash(&mut mh); + let memo_key = mh.finish() as i64; + if let Some(&cached) = memo.get(&(node_id, memo_key)) { return cached; } if !visiting.insert(node_id) { @@ -385,6 +402,7 @@ fn roi_for_node( port, canvas_size, comp_dims, + proxy_scale, time, time_key, hiq, @@ -404,7 +422,7 @@ fn roi_for_node( }; visiting.remove(&node_id); - memo.insert((node_id, time_key), res); + memo.insert((node_id, memo_key), res); res } @@ -415,6 +433,7 @@ fn roi_from_consumer( port: &str, canvas_size: [u32; 2], comp_dims: [u32; 2], + proxy_scale: u32, time: f64, time_key: i64, hiq: bool, @@ -432,7 +451,7 @@ fn roi_from_consumer( } let n = comp.node(cid); if port == "__macro_output" { - return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth); } if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { return None; @@ -444,7 +463,7 @@ fn roi_from_consumer( ) { if port == default_main_input_port(&n.kind) { - return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth); } return None; } @@ -461,12 +480,12 @@ fn roi_from_consumer( let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some(); let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; if blend <= 1e-6 && !mbm { - return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth); } if has_mask { return Some(RoiBox::canvas(canvas_size)); } - roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) } "Fuse.Colorize" => { if port != "Image" && port != "Input" { @@ -475,7 +494,7 @@ fn roi_from_consumer( if Engine::resolve_effect_mask_id(comp, n).is_some() { return Some(RoiBox::canvas(canvas_size)); } - roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) } "ChannelBoolean" => { let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; @@ -483,13 +502,13 @@ fn roi_from_consumer( && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; if blend <= 1e-6 && !mbm { return match port { - "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth), "Foreground" => Some(RoiBox::Empty), _ => None, }; } if port == "Background" || port == "Foreground" { - roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) } else { None } @@ -502,7 +521,7 @@ fn roi_from_consumer( let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some(); let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; if blend <= 1e-6 && !mbm { - return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth); } if n.static_str("ClippingMode").unwrap_or("Frame") != "None" || has_mask { Some(RoiBox::canvas(canvas_size)) @@ -513,18 +532,18 @@ fn roi_from_consumer( "Dissolve" => { let mix_v = comp.eval_number(n, "Mix", time, 1.0, expr).clamp(0.0, 1.0); let blend = comp.eval_number(n, "Blend", time, 1.0, expr); - let has_mask = n.connected_node("EffectMask").is_some(); + let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some(); let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; if (blend <= 1e-6 || mix_v <= 1e-6) && !mbm { return match port { - "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth), "Foreground" => Some(RoiBox::Empty), _ => None, }; } if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask { return match port { - "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth), "Background" => Some(RoiBox::Empty), _ => None, }; @@ -541,7 +560,7 @@ fn roi_from_consumer( } let hiq_only = comp.eval_number(n, "HiQOnly", time, 0.0, expr) > 0.5; if n.kind == "Scale" && !hiq && hiq_only { - roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) } else { Some(RoiBox::canvas(canvas_size)) } @@ -552,10 +571,10 @@ fn roi_from_consumer( } let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; let mbm = n.kind != "Fuse.XGlow" - && n.connected_node("EffectMask").is_some() + && Engine::resolve_effect_mask_id(comp, n).is_some() && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; if blend <= 1e-6 && !mbm { - roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) } else { Some(RoiBox::canvas(canvas_size)) } @@ -565,23 +584,58 @@ fn roi_from_consumer( return None; } let fg_none = n.connected_node("Foreground").and_then(|s| comp.find_node(s)).is_none(); - let mbm = n.connected_node("EffectMask").is_some() + let mbm = Engine::resolve_effect_mask_id(comp, n).is_some() && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; if fg_none && !mbm { - roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) } else { Some(RoiBox::canvas(canvas_size)) } } - "CameraShake" | "DVE" | "Vortex" | "Drip" | "Dent" | "GridWarp" | "VariBlur" - | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Fuse.XfChroma" - | "Paint" => { + "CameraShake" => { + if port != "Input" { + return None; + } + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + let strength = comp.eval_number(n, "OverallStrength", time, 1.0, expr); + let mbm = Engine::resolve_effect_mask_id(comp, n).is_some() + && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if (blend <= 1e-6 || strength.abs() <= 1e-6) && !mbm { + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } else { + None + } + } + "GridWarp" => { + if port != "Input" { + return None; + } + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + if blend <= 1e-6 { + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } else { + None + } + } + "Fuse.XfChroma" => { + if port != "Input" && port != "Image" { + return None; + } + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + if blend <= 1e-6 { + roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } else { + None + } + } + "DVE" | "Vortex" | "Drip" | "Dent" | "VariBlur" + | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Paint" => { if port != default_main_input_port(&n.kind) && port != "Input" && port != "Image" { return None; } // Conservatively union canvas crop with downstream RoI in case the node short-circuits // on an idle parameter (e.g. Blend = 0, radius = 0, etc.). - let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; Some(RoiBox::canvas(canvas_size).union(down)) } "Blur" => { @@ -606,7 +660,7 @@ fn roi_from_consumer( let ry = y_raw * scale_ref * gauss_k; let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; if rx.max(ry) < 0.25 || blend <= 1e-6 { - return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth); } if Engine::resolve_effect_mask_id(comp, n).is_some() { return Some(RoiBox::canvas(canvas_size)); @@ -614,7 +668,7 @@ fn roi_from_consumer( if !rx.is_finite() || !ry.is_finite() || rx.abs() * 1.6 > 2048.0 || ry.abs() * 1.6 > 2048.0 { return None; } - let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; let RoiBox::Rect { x0, y0, x1, y1 } = down else { return Some(RoiBox::Empty); }; @@ -633,7 +687,7 @@ fn roi_from_consumer( } let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; if blend <= 1e-6 { - return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth); } if comp.eval_number(n, "InvertTransform", time, 0.0, expr) > 0.5 { return None; @@ -643,31 +697,39 @@ fn roi_from_consumer( return None; } let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some(); - let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; inverse_transform_box(comp, n, time, expr, canvas_size, has_mask, blend, down) } "Merge" => { let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; - let mbm = n.connected_node("EffectMask").is_some() + let mbm = Engine::resolve_effect_mask_id(comp, n).is_some() && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; if blend <= 1e-6 && !mbm { return match port { - "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth), "Foreground" => Some(RoiBox::Empty), _ => None, }; } if port == "Background" { - return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth); } if port == "Foreground" { - let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32; - if edges != 0 { + let raw_edges = comp.eval_number(n, "Edges", time, 0.0, expr) as f32; + let fg_id = n.connected_node("Foreground").and_then(|s| comp.find_node(s)); + let edges = if raw_edges < 0.5 { + fg_id + .and_then(|fid| Engine::flattened_fg_edge_mode(comp, fid, time, expr)) + .unwrap_or(raw_edges) + } else { + raw_edges + }; + if edges.round() as i32 != 0 { return None; } let bg_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?; - let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, 16)?; - let down = roi_for_node(comp, cid, bg_canvas, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, proxy_scale, hiq, 16)?; + let down = roi_for_node(comp, cid, bg_canvas, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; return inverse_merge_fg_box(comp, n, time, expr, bg_canvas, canvas_size, down); } None @@ -725,6 +787,7 @@ impl Engine { merge_id, canvas_size, comp_dims, + self.proxy_scale, time, time_key, self.hiq, @@ -865,7 +928,18 @@ impl Engine { let mut dst_size = bg.size; let roi_bounds = if bg.tex_scale >= 0.99 && fg.tex_scale >= 0.99 { - self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time) + self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time).map(|(rx0, ry0, rx1, ry1)| { + if visiting.len() == 1 { + ( + rx0.min(0), + ry0.min(0), + rx1.max(bg.canvas_size[0].max(1) as i32), + ry1.max(bg.canvas_size[1].max(1) as i32), + ) + } else { + (rx0, ry0, rx1, ry1) + } + }) } else { None }; @@ -2060,4 +2134,108 @@ mod tests { let cr_px = eng.readback_rgba(&cr_tex).unwrap(); assert!(px_at(&cr_px, cr_tex.size[0], 8, 8)[0] > 200, "Crop at negative offset must sample expanded DoD"); } + + #[test] + fn directly_evaluated_merge_upstream_of_zoomed_in_transform_renders_full_canvas() { + let comp_src = r#"{ + Tools = ordered() { + Bg = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + Fg = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftGreen = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + M = Merge { + Inputs = { + Background = Input { SourceOp = "Bg", Source = "Output", }, + Foreground = Input { SourceOp = "Fg", Source = "Output", }, + }, + }, + ZoomIn = Transform { + Inputs = { + Size = Input { Value = 2.0, }, + Input = Input { SourceOp = "M", Source = "Output", }, + }, + }, + } + }"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse zoom-in comp"); + let mut eng = Engine::new_headless().expect("headless engine"); + let (m_tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0); + assert_eq!(m_tex.size, [64, 64]); + let m_px = eng.readback_rgba(&m_tex).unwrap(); + 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"); + assert_eq!(px_at(&m_px, 64, 61, 61), [0, 255, 0, 255]); + + let (z_tex, _) = eng.evaluate(&comp, comp.find_node("ZoomIn").unwrap(), 0.0); + assert_eq!(z_tex.size, [64, 64]); + let z_px = eng.readback_rgba(&z_tex).unwrap(); + assert_eq!(px_at(&z_px, 64, 32, 32), [0, 255, 0, 255]); + } + + #[test] + fn camera_shake_and_xf_chroma_preserve_upstream_dod_when_active() { + let comp_src = r#"{ + Tools = ordered() { + Bg = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + HugeFg = Background { + Inputs = { + Width = Input { Value = 256, }, + Height = Input { Value = 256, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + MShake = Merge { + Inputs = { + Background = Input { SourceOp = "Bg", Source = "Output", }, + Foreground = Input { SourceOp = "HugeFg", Source = "Output", }, + }, + }, + Shake = CameraShake { + Inputs = { + Input = Input { SourceOp = "MShake", Source = "Output", }, + }, + }, + MChroma = Merge { + Inputs = { + Background = Input { SourceOp = "Bg", Source = "Output", }, + Foreground = Input { SourceOp = "HugeFg", Source = "Output", }, + }, + }, + Chroma = Fuse.XfChroma { + Inputs = { + Input = Input { SourceOp = "MChroma", Source = "Output", }, + }, + }, + } + }"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse dod consumers comp"); + let mut eng = Engine::new_headless().expect("headless engine"); + let mut enc = eng.device.create_command_encoder(&Default::default()); + let mut visiting = std::collections::HashSet::new(); + let mut stats = super::EvalStats::default(); + + let ms_tex = eng.eval_node(&comp, comp.find_node("MShake").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats); + assert_eq!(ms_tex.size, [260, 260], "CameraShake must preserve full upstream DoD"); + let mc_tex = eng.eval_node(&comp, comp.find_node("MChroma").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats); + assert_eq!(mc_tex.size, [260, 260], "Fuse.XfChroma must preserve full upstream DoD"); + eng.queue.submit(Some(enc.finish())); + } } diff --git a/crates/engine/src/eval/masks.rs b/crates/engine/src/eval/masks.rs index 5cf784bc2723fa331270250aa40bcbc7d5afcab7..ed646e63185ca6c4ff3664c0adbd95441cd5cc1b 100644 --- a/crates/engine/src/eval/masks.rs +++ b/crates/engine/src/eval/masks.rs @@ -254,9 +254,10 @@ impl Engine { let soft_px = soft * size[0] as f32; let need_post = soft_px >= 0.5 || invert || (level - 1.0).abs() > 1e-4 || prev_mask.is_some(); let raw_tex = self.alloc_tex(size, BitDepth::Int8, if need_post { 0 } else { key }); + let soft_px = soft * raw_tex.size[0] as f32; - let has_coverage = match polyline_tight_commands(size, &points, [center[0] as f32, center[1] as f32], angle) { - Some(([bx0, by0, bx1, by1], cmds)) if raw_tex.size == size => { + let has_coverage = match polyline_tight_commands(raw_tex.size, &points, [center[0] as f32, center[1] as f32], angle) { + Some(([bx0, by0, bx1, by1], cmds)) => { let bw = (bx1 - bx0) as u32; let bh = (by1 - by0) as u32; let mut cov_buf = vec![0u8; (bw as usize) * (bh as usize)]; @@ -279,7 +280,7 @@ impl Engine { } } - if bw == size[0] && bh == size[1] { + if bw == raw_tex.size[0] && bh == raw_tex.size[1] { self.queue.write_texture( raw_tex.texture.as_image_copy(), &rgba, @@ -1316,4 +1317,39 @@ mod tests { let soft_px = eng.readback_rgba(&soft_tex).unwrap(); assert_eq!(soft_px, ref_px, "SoftEdge PolylineMask must match full-canvas pixel-for-pixel"); } + + #[test] + fn polyline_mask_larger_than_max_texture_dimension_rasterizes_into_clamped_size() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let max_dim = eng.device.limits().max_texture_dimension_2d.max(1); + let req_w = max_dim * 2; + let comp_src = format!( + r#"{{ + Tools = ordered() {{ + BigPoly = PolylineMask {{ + Inputs = {{ + MaskWidth = Input {{ Value = {req_w}, }}, + MaskHeight = Input {{ Value = 32, }}, + Polyline = Input {{ + Value = Polyline {{ + Closed = true, + Points = {{ + {{ Linear = true, X = -0.25, Y = -0.25 }}, + {{ Linear = true, X = 0.25, Y = -0.25 }}, + {{ Linear = true, X = 0.25, Y = 0.25 }}, + {{ Linear = true, X = -0.25, Y = 0.25 }}, + }} + }}, + }}, + }}, + }}, + }} + }}"# + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse clamped polyline comp"); + let (tex, _) = eng.evaluate(&comp, comp.find_node("BigPoly").unwrap(), 0.0); + assert_eq!(tex.size, [max_dim, 16]); + let px = eng.readback_rgba(&tex).unwrap(); + assert!(px.chunks_exact(4).any(|c| c[3] > 200), "clamped PolylineMask must rasterize cleanly instead of clearing to transparent"); + } } diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index 345db022956e3e7a0562737c939f1e694c32fbcc..f13aad09bd7f462f0f2ad8ddc3b3a794403ba605 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -265,7 +265,10 @@ fn scale_text_chars_x( out_x0 = out_x0.min((cx - hw).floor() as i32); out_x1 = out_x1.max((cx + hw).ceil() as i32); } - out_x0 = out_x0.clamp(0, cw); + if cw <= 0 || out_x0 >= cw || out_x1 <= 0 { + return ([1, 1], [0, 0], vec![0; 4]); + } + out_x0 = out_x0.clamp(0, cw - 1); out_x1 = out_x1.clamp(out_x0 + 1, cw); let out_w = (out_x1 - out_x0) as usize; let mut out = vec![0u8; out_w * th * 4]; @@ -306,51 +309,73 @@ fn scale_text_chars_x( const _: fn([u32; 2], &TextPlusParams<'_>, i32) -> ([u32; 2], [i32; 2], Vec) = rasterize_text_plus; fn needs_canvas_aligned_text_output(comp: &Comp, node: &Node) -> bool { - let mut target_names: Vec<&str> = vec![node.name.as_str()]; + let mut queue = std::collections::VecDeque::new(); let mut seen = HashSet::new(); + queue.push_back(node.id); seen.insert(node.id); - for _ in 0..4 { - let mut added = false; + while let Some(cur_id) = queue.pop_front() { + let cur_name = comp.node(cur_id).name.as_str(); for other in &comp.nodes { - if seen.contains(&other.id) { - continue; + let mut is_passthrough = matches!(other.kind.as_str(), "MacroOperator" | "GroupOperator") + && other.macro_output == Some(cur_id); + for (port, b) in &other.inputs { + if b.source_op.as_deref() != Some(cur_name) { + continue; + } + if other.bypassed + || matches!( + other.kind.as_str(), + "PipeRouter" + | "Fuse.Wireless" + | "Wireless" + | "Switch" + | "Fuse.Switch" + | "Fuse.SwitchElse" + | "MacroOperator" + | "GroupOperator" + ) + { + is_passthrough = true; + continue; + } + if (other.kind == "Merge" && port == "Background") + || matches!( + other.kind.as_str(), + "pEmitter" + | "Renderer3D" + | "Displace3D" + | "Texture2DOperator" + | "TextureTransformOperator" + | "BumpMap" + | "Shape3D" + | "ImagePlane3D" + | "ReplaceMaterial3D" + | "TimeStretcher" + | "TimeSpeed" + | "Fuse.Outline" + | "ErodeDilate" + | "Blur" + | "Glow" + | "SoftGlow" + | "InvertColor" + | "BrightnessContrast" + | "ColorCorrector" + | "Fuse.Colorize" + | "VariBlur" + | "Filter" + | "ColorCurves" + | "HueCurves" + | "ColorGain" + | "Custom" + ) + || other.kind.starts_with("Mtl") + { + return true; + } } - let reads_target = other - .inputs - .values() - .any(|b| b.source_op.as_deref().is_some_and(|s| target_names.contains(&s))); - if !reads_target { - continue; + if is_passthrough && seen.insert(other.id) { + queue.push_back(other.id); } - if other.bypassed || matches!(other.kind.as_str(), "PipeRouter" | "Fuse.Wireless") { - seen.insert(other.id); - target_names.push(other.name.as_str()); - added = true; - continue; - } - if matches!( - other.kind.as_str(), - "Fuse.Outline" - | "ErodeDilate" - | "Blur" - | "Glow" - | "SoftGlow" - | "InvertColor" - | "BrightnessContrast" - | "ColorCorrector" - | "Fuse.Colorize" - | "VariBlur" - | "Filter" - | "ColorCurves" - | "HueCurves" - | "ColorGain" - | "Custom" - ) { - return true; - } - } - if !added { - break; } } false @@ -1494,4 +1519,65 @@ Composition { let cov_tm = px_tm.chunks_exact(4).filter(|c| c[3] > 200).count(); assert!(cov_ed > cov_tm + 50, "ErodeDilate downstream of TextPlus must dilate using canvas width: {cov_ed} vs {cov_tm}"); } + + #[test] + fn offscreen_right_text3d_with_char_size_x_does_not_panic() { + let (sz, orig, px) = super::scale_text_chars_x([8, 8], [150, 10], [128, 128], vec![255; 8 * 8 * 4], 1.5); + assert_eq!(sz, [1, 1]); + assert_eq!(orig, [0, 0]); + assert_eq!(px, vec![0; 4]); + + let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { + T = Text3D { Inputs = { + StyledText = Input { Value = "OFF", }, + Size = Input { Value = 0.25, }, + Center = Input { Value = { 1.5, 0.5 }, }, + CharacterSizeX = Input { Value = 1.5, }, + }, }, + Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "T", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, }, + R = Renderer3D { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, SceneInput = Input { SourceOp = "M", Source = "Output", }, }, }, + } }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return }; + let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); + assert_eq!(tex.size, [128, 128]); + } + + #[test] + fn text_plus_feeding_merge_background_and_time_speed_gets_canvas_aligned_output() { + let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 5 }, GlobalRange = { 0, 5 }, Tools = ordered() { + TxtBg = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "BG", }, Size = Input { Value = 0.2, }, }, }, + TxtFg = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "FG", }, Size = Input { Value = 0.2, }, }, }, + M = Merge { Inputs = { + Background = Input { SourceOp = "TxtBg", Source = "Output", }, + Foreground = Input { SourceOp = "TxtFg", Source = "Output", }, + }, }, + TxtTime = TextPlus { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, StyledText = Input { Value = "TM", }, Size = Input { Value = 0.2, }, }, }, + P1 = PipeRouter { Inputs = { Input = Input { SourceOp = "TxtTime", Source = "Output", }, }, }, + P2 = PipeRouter { Inputs = { Input = Input { SourceOp = "P1", Source = "Output", }, }, }, + P3 = PipeRouter { Inputs = { Input = Input { SourceOp = "P2", Source = "Output", }, }, }, + P4 = PipeRouter { Inputs = { Input = Input { SourceOp = "P3", Source = "Output", }, }, }, + Sw = Fuse.Switch { Inputs = { Input1 = Input { SourceOp = "P4", Source = "Output", }, }, }, + TS = TimeSpeed { Inputs = { Speed = Input { Value = 1.0, }, Input = Input { SourceOp = "Sw", Source = "Output", }, }, }, + } }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + assert!(super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtBg").unwrap()))); + assert!(!super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtFg").unwrap()))); + assert!(super::needs_canvas_aligned_text_output(&comp, comp.node(comp.find_node("TxtTime").unwrap()))); + + let Ok(mut eng) = Engine::new_headless() else { return }; + let mut enc = eng.device.create_command_encoder(&Default::default()); + let mut visiting = std::collections::HashSet::new(); + let mut stats = super::EvalStats::default(); + let t_bg = eng.eval_node(&comp, comp.find_node("TxtBg").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats); + assert_eq!(t_bg.origin, [0, 0]); + assert_eq!(t_bg.size, [128, 64]); + let t_fg = eng.eval_node(&comp, comp.find_node("TxtFg").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats); + assert!(t_fg.has_dod(), "TextPlus feeding only Merge.Foreground keeps tight DoD"); + let t_time = eng.eval_node(&comp, comp.find_node("TxtTime").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats); + assert_eq!(t_time.origin, [0, 0]); + assert_eq!(t_time.size, [128, 64]); + eng.queue.submit(Some(enc.finish())); + } } diff --git a/crates/model/src/comp/eval.rs b/crates/model/src/comp/eval.rs index ce5d12550d6b3527e21c07b084210f1c25796657..1a3fe76e6a928ba6b6da51b64bdde5f0babc6ea4 100644 --- a/crates/model/src/comp/eval.rs +++ b/crates/model/src/comp/eval.rs @@ -13,6 +13,13 @@ thread_local! { RefCell::new((0, HashMap::new())); } +/// Parses a bare `NodeName.ParamName` reference where both segments are identifier characters. +fn parse_bare_node_param_ref(expr: &str) -> Option<(&str, &str)> { + let (n, p) = expr.trim().split_once('.')?; + let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + (ident(n) && ident(p)).then_some((n, p)) +} + fn is_lua_keyword(tok: &str) -> bool { matches!( tok, @@ -153,11 +160,9 @@ impl Comp { } if let Some(expr) = &binding.expression { // A bare `Node.Param` follows that input's own expression/animation instead of its baked value. - let referenced = expr.trim().split_once('.').and_then(|(n, p)| { - let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); - (ident(n) && ident(p)).then_some((n, p)) - }); - let v = match referenced.and_then(|(n, p)| Some((self.node(self.find_node(n)?), p))) { + let v = match parse_bare_node_param_ref(expr) + .and_then(|(n, p)| Some((self.node(self.find_node(n)?), p))) + { Some((other, p)) if other.inputs.contains_key(p) && other.id != node.id => { Some(self.eval_number_at(other, p, time, f64::NAN, expr_engine, depth + 1)) } @@ -429,10 +434,10 @@ impl Comp { if let Some(expr) = &b.expression { let trimmed = expr.trim(); // Direct `NodeName.ParamName` reference to a Point input on another flow node. - if let Some((node_name, param_name)) = trimmed.split_once('.') { - if !param_name.contains('.') && !param_name.contains(' ') { - if let Some(nid) = self.find_node(node_name.trim()) { - return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1); + if let Some((node_name, param_name)) = parse_bare_node_param_ref(trimmed) { + if let Some(other) = self.find_node(node_name).map(|nid| self.node(nid)) { + if other.inputs.contains_key(param_name) { + return self.eval_point_at(other, param_name, time, default, expr_engine, depth + 1); } } } @@ -479,12 +484,12 @@ impl Comp { depth: usize, ) -> Option { let trimmed = expr.trim(); - if let Some((node_name, param_name)) = trimmed.split_once('.') { - if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') { - if let Some(nid) = self.find_node(node_name.trim()) { + if let Some((node_name, param_name)) = parse_bare_node_param_ref(trimmed) { + if let Some(other) = self.find_node(node_name).map(|nid| self.node(nid)) { + if other.inputs.contains_key(param_name) { return Some(self.eval_number_at( - self.node(nid), - param_name.trim(), + other, + param_name, time, 0.0, expr_engine, @@ -497,7 +502,7 @@ impl Comp { expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en) } - /// `node name -> numeric/text inputs` for the nodes `expr` can reach; every other node is skipped. + /// `node name -> numeric/text/point inputs` for the nodes `expr` can reach; every other node is skipped. fn collect_node_env(&self, expr: &str, time: f64) -> HashMap> { let mut env = HashMap::new(); for tok in expr @@ -511,7 +516,7 @@ impl Comp { .map(|n| (n.name.clone(), self.node_expr_vars(n, time))) .collect(); } - if tok == "self" || is_lua_keyword(tok) || env.contains_key(tok) { + if is_lua_keyword(tok) || env.contains_key(tok) { continue; } if let Some(nid) = self.find_node(tok) { @@ -534,10 +539,24 @@ impl Comp { vars.insert(k.clone(), ExprValue::Text(t.clone())); continue; } + Some(ParamValue::Point(pt)) => { + vars.insert(k.clone(), ExprValue::Point(*pt)); + continue; + } _ => {} } - if let Some(sp) = b.source_op.as_ref().and_then(|src| self.splines.get(src)) { - vars.insert(k.clone(), ExprValue::Number(sp.eval(time))); + if let Some(src) = b.source_op.as_deref() { + if let Some(sp) = self.splines.get(src) { + vars.insert(k.clone(), ExprValue::Number(sp.eval(time))); + } else if let Some(pp) = self.poly_paths.get(src) { + let disp = pp + .displacement_op + .as_deref() + .and_then(|d| self.splines.get(d)) + .map(|sp| sp.eval(time)) + .unwrap_or(pp.displacement_value); + vars.insert(k.clone(), ExprValue::Point(pp.eval_center(disp))); + } } } vars @@ -998,4 +1017,44 @@ mod tests { assert_eq!(comp.checker_piece_metrics(node("Tiny"), 0.0, &engine), (2, 0.2)); assert_eq!(comp.eval_number(m, "Angle", 0.0, 7.0, &engine), 7.0, "non-ExtraScale outputs stay unresolved"); } + + #[test] + fn expression_modifier_spaceless_arithmetic_and_self_named_node() { + let src = r#"Composition { + Tools = ordered() { + BG1 = Background { Inputs = { + Width = Input { Value = 320, }, + Center = Input { Value = { 0.25, 0.5 }, }, + }, }, + self = Background { Inputs = { + Width = Input { Value = 100, }, + }, }, + Out = Transform { Inputs = { + Size = Input { SourceOp = "NumMod", Source = "NumberResult", }, + Center = Input { SourceOp = "PtMod", Source = "PointResult", }, + Angle = Input { SourceOp = "SelfMod", Source = "NumberResult", }, + }, }, + NumMod = Expression { Inputs = { + n1 = Input { Expression = "BG1.Width*2", }, + NumberExpression = Input { Value = "n1", }, + }, }, + PtMod = Expression { Inputs = { + p1 = Input { Expression = "BG1.Center+Point(0.1,0)", }, + PointExpressionX = Input { Value = "p1x", }, + PointExpressionY = Input { Value = "p1y", }, + }, }, + SelfMod = Expression { Inputs = { + n1 = Input { Expression = "self.Width*3", }, + NumberExpression = Input { Value = "n1", }, + }, }, + } + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let engine = ExprEngine::new(); + let out = comp.node(comp.find_node("Out").unwrap()); + assert_eq!(comp.eval_number(out, "Size", 0.0, -1.0, &engine), 640.0); + let c = comp.eval_point(out, "Center", 0.0, [0.0, 0.0], &engine); + assert!((c[0] - 0.35).abs() < 1e-12 && (c[1] - 0.5).abs() < 1e-12, "got {c:?}"); + assert_eq!(comp.eval_number(out, "Angle", 0.0, -1.0, &engine), 300.0); + } } diff --git a/crates/model/src/expr.rs b/crates/model/src/expr.rs index ec35c950cd5cc5dc5086c42b903ddc49ae7f0a43..76663e86e1c3f889f4198b0220dce2cd88b77ae5 100644 --- a/crates/model/src/expr.rs +++ b/crates/model/src/expr.rs @@ -9,6 +9,7 @@ pub enum ExprValue { Number(f64), Text(String), + Point([f64; 2]), } /// 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 { /// Max compiled expression bytecodes cached per `ExprEngine`. const CHUNK_CACHE_CAP: usize = 512; + /// Bounded LRU cache of compiled Lua chunk bytecodes (`None` for cached syntax errors). + struct ChunkCache { + entries: HashMap>, u64)>, + tick: u64, + } + + impl ChunkCache { + fn new() -> Self { + Self { + entries: HashMap::new(), + tick: 0, + } + } + + #[cfg(test)] + fn len(&self) -> usize { + self.entries.len() + } + + #[cfg(test)] + fn get(&self, key: &str) -> Option<&Option>> { + self.entries.get(key).map(|(v, _)| v) + } + + fn touch(&mut self, key: &str) -> Option<&Option>> { + let next = self.tick.wrapping_add(1); + self.tick = next; + self.entries.get_mut(key).map(|(v, t)| { + *t = next; + &*v + }) + } + + fn insert(&mut self, key: String, val: Option>) { + let next = self.tick.wrapping_add(1); + self.tick = next; + if !self.entries.contains_key(&key) && self.entries.len() >= CHUNK_CACHE_CAP { + if let Some(oldest) = self + .entries + .iter() + .min_by_key(|(_, (_, t))| *t) + .map(|(k, _)| k.clone()) + { + self.entries.remove(&oldest); + } + } + self.entries.insert(key, (val, next)); + } + } + /// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`, /// no code loading, and bounded instructions and memory per evaluation. pub struct ExprEngine { @@ -64,7 +115,8 @@ mod lua { env_mt: Table, zero_mt: Table, text_mt: Table, - chunk_cache: RefCell>>>, + point_mt: Table, + chunk_cache: RefCell, } impl Default for ExprEngine { @@ -105,7 +157,6 @@ mod lua { tan = math.tan tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end - Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end local lua_tostring = tostring tostring = function(v) if type(v) == "number" then return string.format("%.14g", v) end return lua_tostring(v) end Text = function(s) return tostring(s or "") end @@ -115,6 +166,108 @@ mod lua { let _ = lua.load(init).exec(); let globals = lua.globals(); + let point_mt = lua.create_table().expect("table creates"); + let make_pt = |lua: &Lua, mt: &Table, x: f64, y: f64| -> mlua::Result { + let pt = lua.create_table()?; + pt.set("X", x)?; + pt.set("Y", y)?; + pt.set(1, x)?; + pt.set(2, y)?; + pt.set_metatable(Some(mt.clone())); + Ok(pt) + }; + let read_pt = |v: &Value| -> Option<[f64; 2]> { + let Value::Table(t) = v else { return None }; + let x = t.get::("X").or_else(|_| t.get::(1)).ok()?; + let y = t.get::("Y").or_else(|_| t.get::(2)).ok()?; + Some([x, y]) + }; + let read_num = |v: &Value| -> Option { + match v { + Value::Number(n) => Some(*n), + Value::Integer(i) => Some(*i as f64), + _ => None, + } + }; + let mt_ref = point_mt.clone(); + point_mt + .set( + "__add", + lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result
{ + let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else { + return Err(mlua::Error::runtime("Point addition requires two Points")); + }; + make_pt(lua, &mt_ref, ax + bx, ay + by) + }) + .expect("function creates"), + ) + .expect("table sets"); + let mt_ref = point_mt.clone(); + point_mt + .set( + "__sub", + lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result
{ + let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else { + return Err(mlua::Error::runtime("Point subtraction requires two Points")); + }; + make_pt(lua, &mt_ref, ax - bx, ay - by) + }) + .expect("function creates"), + ) + .expect("table sets"); + let mt_ref = point_mt.clone(); + point_mt + .set( + "__mul", + lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result
{ + match (read_pt(&a), read_pt(&b), read_num(&a), read_num(&b)) { + (Some([ax, ay]), Some([bx, by]), _, _) => make_pt(lua, &mt_ref, ax * bx, ay * by), + (Some([ax, ay]), None, _, Some(s)) | (None, Some([ax, ay]), Some(s), _) => { + make_pt(lua, &mt_ref, ax * s, ay * s) + } + _ => Err(mlua::Error::runtime("invalid Point multiplication")), + } + }) + .expect("function creates"), + ) + .expect("table sets"); + let mt_ref = point_mt.clone(); + point_mt + .set( + "__div", + lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result
{ + match (read_pt(&a), read_pt(&b), read_num(&b)) { + (Some([ax, ay]), Some([bx, by]), _) => make_pt(lua, &mt_ref, ax / bx, ay / by), + (Some([ax, ay]), None, Some(s)) => make_pt(lua, &mt_ref, ax / s, ay / s), + _ => Err(mlua::Error::runtime("invalid Point division")), + } + }) + .expect("function creates"), + ) + .expect("table sets"); + let mt_ref = point_mt.clone(); + point_mt + .set( + "__unm", + lua.create_function(move |lua, a: Value| -> mlua::Result
{ + let Some([ax, ay]) = read_pt(&a) else { + return Err(mlua::Error::runtime("invalid Point negation")); + }; + make_pt(lua, &mt_ref, -ax, -ay) + }) + .expect("function creates"), + ) + .expect("table sets"); + let mt_ref = point_mt.clone(); + globals + .set( + "Point", + lua.create_function(move |lua, (x, y): (Option, Option)| { + make_pt(lua, &mt_ref, x.unwrap_or(0.0), y.unwrap_or(0.0)) + }) + .expect("function creates"), + ) + .expect("global sets"); // Stdlib tables become write-protected proxies so no evaluation can alter them for the next. let read_only = lua .create_function(|_, _: MultiValue| -> mlua::Result<()> { @@ -180,14 +333,15 @@ mod lua { env_mt, zero_mt, text_mt, - chunk_cache: RefCell::new(HashMap::new()), + point_mt, + chunk_cache: RefCell::new(ChunkCache::new()), } } fn load_cached(&self, expr: &str, env: Table) -> Option { { - let cache = self.chunk_cache.borrow(); - if let Some(hit) = cache.get(expr) { + let mut cache = self.chunk_cache.borrow_mut(); + if let Some(hit) = cache.touch(expr) { let bytes = hit.as_ref()?; return self .lua @@ -199,26 +353,24 @@ mod lua { } } let chunk_src = Self::expr_chunk(expr); - let compiled = self + match self .lua .load(&chunk_src) + .set_mode(ChunkMode::Text) + .set_environment(env) .into_function() - .ok() - .map(|f| f.dump(true)); - let func = compiled.as_ref().and_then(|bytes| { - self.lua - .load(bytes.as_slice()) - .set_mode(ChunkMode::Binary) - .set_environment(env) - .into_function() - .ok() - }); - let mut cache = self.chunk_cache.borrow_mut(); - if cache.len() >= CHUNK_CACHE_CAP { - cache.clear(); + { + Ok(func) => { + let bytes = func.dump(true); + self.chunk_cache.borrow_mut().insert(expr.to_owned(), Some(bytes)); + Some(func) + } + Err(mlua::Error::SyntaxError { .. }) => { + self.chunk_cache.borrow_mut().insert(expr.to_owned(), None); + None + } + Err(_) => None, } - cache.insert(expr.to_owned(), compiled); - func } /// Evaluates `expr` in a fresh environment with a fresh instruction budget. @@ -304,6 +456,16 @@ mod lua { } } + fn make_point(&self, p: [f64; 2]) -> mlua::Result
{ + let pt = self.lua.create_table()?; + pt.set("X", p[0])?; + pt.set("Y", p[1])?; + pt.set(1, p[0])?; + pt.set(2, p[1])?; + pt.set_metatable(Some(self.point_mt.clone())); + Ok(pt) + } + fn build_env( &self, time: f64, @@ -319,12 +481,7 @@ mod lua { env.set(k.as_str(), *v)?; } for (k, p) in self_points { - let pt = self.lua.create_table()?; - pt.set("X", p[0])?; - pt.set("Y", p[1])?; - pt.set(1, p[0])?; - pt.set(2, p[1])?; - env.set(k.as_str(), pt)?; + env.set(k.as_str(), self.make_point(*p)?)?; } // Missing node fields default to 0 so expressions don't nil-crash. for (node_name, params) in env_nodes { @@ -338,6 +495,7 @@ mod lua { text.set_metatable(Some(self.text_mt.clone())); nt.set(pk.as_str(), text)?; } + ExprValue::Point(p) => nt.set(pk.as_str(), self.make_point(*p)?)?, } } nt.set_metatable(Some(self.zero_mt.clone())); @@ -453,6 +611,66 @@ mod lua { assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &HashMap::new()), None); assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None)); } + + #[test] + fn binary_bytecode_prefix_is_rejected_in_text_mode() { + let engine = ExprEngine::new(); + let empty = HashMap::new(); + // Even with a Lua binary signature `\x1bLua...`, ChunkMode::Text rejects it safely. + for bad in [":\x1bLua", ":\x1bLuaT\0\x19\x0d\x0a\x1a\x0a", "\x1bLua"] { + assert_eq!(engine.eval_number(bad, 0.0, &HashMap::new(), &HashMap::new(), &empty), None); + assert_eq!(engine.chunk_cache.borrow().get(bad), Some(&None)); + } + // Valid expressions continue to evaluate cleanly afterwards. + assert_eq!(engine.eval_number("2 + 3", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(5.0)); + } + + #[test] + fn syntax_vs_runtime_and_memory_error_caching_and_lru() { + let engine = ExprEngine::new(); + let empty = HashMap::new(); + + // SyntaxError is negative-cached as None. + assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &empty), None); + assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None)); + + // Runtime error compiles cleanly (cached as Some(bytecode)), fails on call, and doesn't poison valid runs. + assert_eq!( + engine.eval_number("1 + nil", 0.0, &HashMap::new(), &HashMap::new(), &empty), + None + ); + assert!(matches!(engine.chunk_cache.borrow().get("1 + nil"), Some(Some(_)))); + + // MemoryError during compilation is NOT negative-cached. + engine.lua.set_memory_limit(1).expect("tight limit applies"); + let mem_expr = format!("1{}", " + 1".repeat(200)); + assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), None); + assert_eq!(engine.chunk_cache.borrow().get(&mem_expr), None); + engine.lua.set_memory_limit(MEMORY_LIMIT).expect("restore memory limit"); + assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(201.0)); + assert!(matches!(engine.chunk_cache.borrow().get(&mem_expr), Some(Some(_)))); + + // LRU eviction keeps hot entries when exceeding CHUNK_CACHE_CAP. + let lru_engine = ExprEngine::new(); + for i in 0..CHUNK_CACHE_CAP { + let expr = format!("{i} + 1"); + assert_eq!( + lru_engine.eval_number(&expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), + Some((i + 1) as f64) + ); + } + assert_eq!(lru_engine.chunk_cache.borrow().len(), CHUNK_CACHE_CAP); + // Touch entry 0 so entry 1 becomes the least recently used. + assert_eq!(lru_engine.eval_number("0 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(1.0)); + assert_eq!( + lru_engine.eval_number("9999 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty), + Some(10000.0) + ); + let cache = lru_engine.chunk_cache.borrow(); + assert_eq!(cache.len(), CHUNK_CACHE_CAP); + assert!(cache.get("0 + 1").is_some(), "hot entry 0 must stay in LRU cache"); + assert!(cache.get("1 + 1").is_none(), "cold entry 1 must be evicted"); + } } } @@ -809,7 +1027,10 @@ mod pure { Ast::Num(n) | Ast::Int(n) => Val::Num(*n), Ast::Str(s) => Val::Str(s.clone()), Ast::Name(n) => self.name(n), - Ast::Neg(a) => Val::Num(-self.eval(a)?.num()?), + Ast::Neg(a) => match self.eval(a)? { + Val::Point([x, y]) => Val::Point([-x, -y]), + v => Val::Num(-v.num()?), + }, Ast::Not(a) => Val::Bool(!self.eval(a)?.truthy()), Ast::Index(base, key) => index(self.eval(base)?, self.eval(key)?)?, Ast::Call(callee, args) => { @@ -853,6 +1074,7 @@ mod pure { Val::Str(k) => match fields.get(&k) { Some(ExprValue::Number(n)) => Val::Num(*n), Some(ExprValue::Text(s)) => Val::Text(s.clone()), + Some(ExprValue::Point(p)) => Val::Point(*p), None => Val::Num(0.0), }, _ => Val::Num(0.0), @@ -888,6 +1110,23 @@ mod pure { ">" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o == Ordering::Greater)), ">=" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o != Ordering::Less)), ".." => Val::Str(a.text()? + &b.text()?), + "+" | "-" | "*" | "/" if matches!((&a, &b), (Val::Point(_), _) | (_, Val::Point(_))) => { + match (op, a, b) { + ("+", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax + bx, ay + by]), + ("-", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax - bx, ay - by]), + ("*", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax * bx, ay * by]), + ("/", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax / bx, ay / by]), + ("*", Val::Point([ax, ay]), other) | ("*", other, Val::Point([ax, ay])) => { + let s = other.num()?; + Val::Point([ax * s, ay * s]) + } + ("/", Val::Point([ax, ay]), other) => { + let s = other.num()?; + Val::Point([ax / s, ay / s]) + } + _ => return None, + } + } _ => { let (a, b) = (a.num()?, b.num()?); Val::Num(match op {