From 79c98cb78b7de4f5a3b178ce9c0cdf90a594d95d Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 20:00:17 -0800 Subject: [PATCH] Split shapes_warp.rs into shapes.rs and warps.rs and refine Drip edge handling --- crates/engine/src/eval/mod.rs | 3 +- crates/engine/src/eval/shapes.rs | 1009 ++++++++++++++++ .../src/eval/{shapes_warp.rs => warps.rs} | 1029 +---------------- crates/engine/src/shaders/archive_fx.wgsl | 2 +- 4 files changed, 1052 insertions(+), 991 deletions(-) create mode 100644 crates/engine/src/eval/shapes.rs rename crates/engine/src/eval/{shapes_warp.rs => warps.rs} (52%) diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 0dfeed94a629fa2ab65b7b01c89b73880c3367d3..bd900346bde2c8dfda895e09ecbc33dbdf763f5d 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -19,7 +19,8 @@ mod blur_glow; mod keyers; mod masks; mod paint; -mod shapes_warp; +mod shapes; +mod warps; mod text_3d; diff --git a/crates/engine/src/eval/shapes.rs b/crates/engine/src/eval/shapes.rs new file mode 100644 index 0000000000000000000000000000000000000000..96057888964a4724d1fd5daa8099df1fdde40c7e --- /dev/null +++ b/crates/engine/src/eval/shapes.rs @@ -0,0 +1,1009 @@ +//! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sGrid`, +//! `sMerge`, `sTransform`, `sBoolean`, `sOutline`). + +use super::*; + +#[derive(Clone, Copy, Debug)] +struct Affine2D { + // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty + m: [f32; 6], +} + +impl Affine2D { + fn identity() -> Self { + Self { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] } + } + + fn translate(tx: f32, ty: f32) -> Self { + Self { m: [1.0, 0.0, 0.0, 1.0, tx, ty] } + } + + fn scale(sx: f32, sy: f32) -> Self { + Self { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] } + } + + fn rotate_deg(deg: f32) -> Self { + let r = deg.to_radians(); + let (s, c) = r.sin_cos(); + Self { m: [c, -s, s, c, 0.0, 0.0] } + } + + fn mul(self, rhs: Self) -> Self { + let [a1, b1, c1, d1, tx1, ty1] = self.m; + let [a2, b2, c2, d2, tx2, ty2] = rhs.m; + Self { + m: [ + a1 * a2 + b1 * c2, + a1 * b2 + b1 * d2, + c1 * a2 + d1 * c2, + c1 * b2 + d1 * d2, + a1 * tx2 + b1 * ty2 + tx1, + c1 * tx2 + d1 * ty2 + ty1, + ], + } + } + + fn apply(self, p: [f32; 2]) -> [f32; 2] { + [ + self.m[0] * p[0] + self.m[1] * p[1] + self.m[4], + self.m[2] * p[0] + self.m[3] * p[1] + self.m[5], + ] + } + + fn avg_scale(self) -> f32 { + let sx = self.m[0].hypot(self.m[2]); + let sy = self.m[1].hypot(self.m[3]); + ((sx + sy) * 0.5).max(1e-4) + } + + fn hash_into(self, h: &mut DefaultHasher) { + for v in self.m { + v.to_bits().hash(h); + } + } +} + +#[derive(Clone, Copy, Debug)] +enum ShapePrimKind { + NGon { sides: u32, width: f32, height: f32 }, + Rectangle { width: f32, height: f32, corner_radius: f32 }, + Ellipse { width: f32, height: f32 }, +} + +#[derive(Clone, Copy, Debug)] +enum ShapeBoolOp { + Union, + Intersect, + Subtract, + Xor, +} + +#[derive(Clone, Debug)] +enum ShapeTree { + Primitive { + kind: ShapePrimKind, + xform: Affine2D, + color: [f32; 4], + solid: bool, + border_width: f32, + join_style: u8, + cap_style: u8, + }, + Group(Vec), + Boolean { + op: ShapeBoolOp, + color: [f32; 4], + a: Box, + b: Box, + }, +} + +impl ShapeTree { + fn hash_into(&self, h: &mut DefaultHasher) { + match self { + ShapeTree::Primitive { + kind, + xform, + color, + solid, + border_width, + join_style, + cap_style, + } => { + 0u8.hash(h); + match *kind { + ShapePrimKind::NGon { sides, width, height } => { + 1u8.hash(h); + sides.hash(h); + width.to_bits().hash(h); + height.to_bits().hash(h); + } + ShapePrimKind::Rectangle { width, height, corner_radius } => { + 2u8.hash(h); + width.to_bits().hash(h); + height.to_bits().hash(h); + corner_radius.to_bits().hash(h); + } + ShapePrimKind::Ellipse { width, height } => { + 3u8.hash(h); + width.to_bits().hash(h); + height.to_bits().hash(h); + } + } + xform.hash_into(h); + for c in color { + c.to_bits().hash(h); + } + solid.hash(h); + border_width.to_bits().hash(h); + join_style.hash(h); + cap_style.hash(h); + } + ShapeTree::Group(children) => { + 1u8.hash(h); + children.len().hash(h); + for ch in children { + ch.hash_into(h); + } + } + ShapeTree::Boolean { op, color, a, b } => { + 2u8.hash(h); + (*op as u8).hash(h); + for c in color { + c.to_bits().hash(h); + } + a.hash_into(h); + b.hash_into(h); + } + } + } +} + +fn eval_first_num( + comp: &Comp, + node: &Node, + keys: &[&str], + time: f64, + default: f64, + expr: &ExprEngine, +) -> f64 { + for &k in keys { + if node.inputs.contains_key(k) { + return comp.eval_number(node, k, time, default, expr); + } + } + default +} + +/// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. +fn parse_bool_op(node: &Node) -> Option { + if !node.inputs.contains_key("Operation") { + return Some(ShapeBoolOp::Intersect); + } + match node.static_str("Operation")? { + "Union" => Some(ShapeBoolOp::Union), + "Intersection" => Some(ShapeBoolOp::Intersect), + "Subtract" => Some(ShapeBoolOp::Subtract), + "Xor" => Some(ShapeBoolOp::Xor), + _ => None, + } +} + +#[allow(clippy::too_many_arguments)] +fn collect_shape_tree( + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &ExprEngine, + parent_xform: Affine2D, + outline_override: Option<(f32, u8, u8)>, + depth: usize, +) -> Option { + if depth > 32 { + return None; + } + let node = comp.node(node_id); + if node.bypassed { + return node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s)) + .and_then(|id| { + collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) + }); + } + + match node.kind.as_str() { + "sNGon" | "sRectangle" | "sEllipse" => { + let tx = eval_first_num(comp, node, &["Translate.X", "XOffset"], time, 0.0, expr) as f32; + let ty = eval_first_num(comp, node, &["Translate.Y", "YOffset"], time, 0.0, expr) as f32; + let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; + let local = Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)); + let xform = parent_xform.mul(local); + + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; + + let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; + let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32; + let mut join_style = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8; + let mut cap_style = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; + + if let Some((ov_w, ov_j, ov_c)) = outline_override { + solid = false; + border_width = ov_w; + join_style = ov_j; + cap_style = ov_c; + } + + let kind = match node.kind.as_str() { + "sNGon" => { + let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; + let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; + let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; + ShapePrimKind::NGon { sides, width, height } + } + "sRectangle" => { + let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; + let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; + let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; + ShapePrimKind::Rectangle { width, height, corner_radius } + } + _ => { + let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; + let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; + ShapePrimKind::Ellipse { width, height } + } + }; + + Some(ShapeTree::Primitive { + kind, + xform, + color: [r, g, b, a], + solid, + border_width, + join_style, + cap_style, + }) + } + "sTransform" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; + let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; + let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32; + let py = eval_first_num(comp, node, &["YPivot", "Pivot.Y"], time, 0.0, expr) as f32; + let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); + let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; + let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; + let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; + + let local = Affine2D::translate(ox + px, oy + py) + .mul(Affine2D::rotate_deg(rot)) + .mul(Affine2D::scale(sx, sy)) + .mul(Affine2D::translate(-px, -py)); + let combined = parent_xform.mul(local); + collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1) + } + "sMerge" => { + let mut ports: Vec<(u32, &str)> = node + .inputs + .keys() + .filter_map(|k| { + let rest = k.strip_prefix("Input")?; + let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? }; + Some((idx, k.as_str())) + }) + .collect(); + ports.sort_by_key(|&(idx, _)| idx); + let mut children = Vec::new(); + for (_, port) in ports { + if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { + if let Some(tree) = collect_shape_tree( + comp, + src_id, + time, + expr, + parent_xform, + outline_override, + depth + 1, + ) { + children.push(tree); + } + } + } + if children.is_empty() { + None + } else { + Some(ShapeTree::Group(children)) + } + } + "sGrid" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; + let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; + let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32; + let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32; + let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y)); + for iy in 0..cells_y { + let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off; + for ix in 0..cells_x { + let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off; + let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty)); + if let Some(tree) = collect_shape_tree( + comp, + src_id, + time, + expr, + cell_xf, + outline_override, + depth + 1, + ) { + children.push(tree); + } + } + } + if children.is_empty() { + None + } else { + Some(ShapeTree::Group(children)) + } + } + "sOutline" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr).abs() as f32; + let join = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8; + let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; + collect_shape_tree(comp, src_id, time, expr, parent_xform, Some((thickness, join, cap)), depth + 1) + } + "sBoolean" => { + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; + let color = [r, g, b_col, a_col]; + let child = |port: &str| { + node.connected_node(port) + .and_then(|s| comp.find_node(s)) + .and_then(|id| { + collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) + }) + }; + let a = child("Input1").or_else(|| child("Input"))?; + // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty. + let (op, b) = match (parse_bool_op(node), child("Input2")) { + (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())), + (Some(op), Some(b)) => (op, b), + (None, Some(_)) => return None, + }; + Some(ShapeTree::Boolean { + op, + color, + a: Box::new(a), + b: Box::new(b), + }) + } + "PipeRouter" | "Fuse.Wireless" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1) + } + "MacroOperator" | "GroupOperator" => { + let out_id = node.macro_output?; + collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1) + } + _ => None, + } +} + +fn build_primitive_commands(kind: ShapePrimKind, xform: Affine2D, dims: [u32; 2]) -> Vec { + let wf = dims[0] as f32; + let hf = dims[1] as f32; + let to_px = |local: [f32; 2]| -> zeno::Vector { + let wpt = xform.apply(local); + let px = (wpt[0] + 0.5) * wf; + let py = 0.5 * hf - wpt[1] * wf; + zeno::Vector::new(px, py) + }; + + const KAPPA: f32 = 0.55228475; + let mut cmds = Vec::new(); + match kind { + ShapePrimKind::NGon { sides, width, height } => { + let n = sides.max(3); + let rx = width * 0.5; + let ry = height * 0.5; + if rx <= 1e-6 || ry <= 1e-6 { + return cmds; + } + for k in 0..n { + let theta = (k as f32) * std::f32::consts::TAU / (n as f32); + let v = to_px([rx * theta.cos(), ry * theta.sin()]); + if k == 0 { + cmds.push(zeno::Command::MoveTo(v)); + } else { + cmds.push(zeno::Command::LineTo(v)); + } + } + cmds.push(zeno::Command::Close); + } + ShapePrimKind::Rectangle { width, height, corner_radius } => { + let hx = width * 0.5; + let hy = height * 0.5; + if hx <= 1e-6 || hy <= 1e-6 { + return cmds; + } + let r = corner_radius.min(hx.min(hy)); + if r <= 1e-5 { + cmds.push(zeno::Command::MoveTo(to_px([-hx, -hy]))); + cmds.push(zeno::Command::LineTo(to_px([hx, -hy]))); + cmds.push(zeno::Command::LineTo(to_px([hx, hy]))); + cmds.push(zeno::Command::LineTo(to_px([-hx, hy]))); + cmds.push(zeno::Command::Close); + } else { + let k = r * KAPPA; + cmds.push(zeno::Command::MoveTo(to_px([-hx + r, -hy]))); + cmds.push(zeno::Command::LineTo(to_px([hx - r, -hy]))); + cmds.push(zeno::Command::CurveTo( + to_px([hx - r + k, -hy]), + to_px([hx, -hy + r - k]), + to_px([hx, -hy + r]), + )); + cmds.push(zeno::Command::LineTo(to_px([hx, hy - r]))); + cmds.push(zeno::Command::CurveTo( + to_px([hx, hy - r + k]), + to_px([hx - r + k, hy]), + to_px([hx - r, hy]), + )); + cmds.push(zeno::Command::LineTo(to_px([-hx + r, hy]))); + cmds.push(zeno::Command::CurveTo( + to_px([-hx + r - k, hy]), + to_px([-hx, hy - r + k]), + to_px([-hx, hy - r]), + )); + cmds.push(zeno::Command::LineTo(to_px([-hx, -hy + r]))); + cmds.push(zeno::Command::CurveTo( + to_px([-hx, -hy + r - k]), + to_px([-hx + r - k, -hy]), + to_px([-hx + r, -hy]), + )); + cmds.push(zeno::Command::Close); + } + } + ShapePrimKind::Ellipse { width, height } => { + let rx = width * 0.5; + let ry = height * 0.5; + if rx <= 1e-6 || ry <= 1e-6 { + return cmds; + } + let kx = rx * KAPPA; + let ky = ry * KAPPA; + cmds.push(zeno::Command::MoveTo(to_px([rx, 0.0]))); + cmds.push(zeno::Command::CurveTo( + to_px([rx, ky]), + to_px([kx, ry]), + to_px([0.0, ry]), + )); + cmds.push(zeno::Command::CurveTo( + to_px([-kx, ry]), + to_px([-rx, ky]), + to_px([-rx, 0.0]), + )); + cmds.push(zeno::Command::CurveTo( + to_px([-rx, -ky]), + to_px([-kx, -ry]), + to_px([0.0, -ry]), + )); + cmds.push(zeno::Command::CurveTo( + to_px([kx, -ry]), + to_px([rx, -ky]), + to_px([rx, 0.0]), + )); + cmds.push(zeno::Command::Close); + } + } + cmds +} + +fn composite_over(dst: &mut [f32], src: &[f32]) { + for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) { + let sa = s[3].clamp(0.0, 1.0); + if sa <= 1e-6 { + continue; + } + let inv = 1.0 - sa; + d[0] = s[0] + d[0] * inv; + d[1] = s[1] + d[1] * inv; + d[2] = s[2] + d[2] * inv; + d[3] = sa + d[3] * inv; + } +} + +fn rasterize_shape_tree_f32( + tree: &ShapeTree, + dims: [u32; 2], + dst: &mut [f32], + cov_buf: &mut [u8], + scratch: &mut zeno::Scratch, +) { + let [w, h] = dims; + match tree { + ShapeTree::Primitive { + kind, + xform, + color, + solid, + border_width, + join_style, + cap_style, + } => { + let cmds = build_primitive_commands(*kind, *xform, dims); + if cmds.is_empty() { + return; + } + cov_buf.fill(0); + let style = if *solid { + zeno::Style::Fill(zeno::Fill::NonZero) + } else { + let stroke_px = (*border_width * xform.avg_scale() * (w as f32)).max(0.5); + let join = match *join_style { + 0 => zeno::Join::Bevel, + 1 => zeno::Join::Round, + _ => zeno::Join::Miter, + }; + let cap = match *cap_style { + 1 => zeno::Cap::Round, + 2 => zeno::Cap::Square, + _ => zeno::Cap::Butt, + }; + let mut st = zeno::Stroke::new(stroke_px); + st.join(join).cap(cap); + zeno::Style::Stroke(st) + }; + let _ = zeno::Mask::with_scratch(&cmds, scratch) + .style(style) + .size(w, h) + .origin(zeno::Origin::TopLeft) + .render_into(cov_buf, None); + + let ca = color[3].clamp(0.0, 1.0); + if ca <= 1e-6 { + return; + } + for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { + if cov == 0 { + continue; + } + let sa = (cov as f32 / 255.0) * ca; + let inv = 1.0 - sa; + px[0] = color[0] * sa + px[0] * inv; + px[1] = color[1] * sa + px[1] * inv; + px[2] = color[2] * sa + px[2] * inv; + px[3] = sa + px[3] * inv; + } + } + ShapeTree::Group(children) => { + for ch in children { + rasterize_shape_tree_f32(ch, dims, dst, cov_buf, scratch); + } + } + ShapeTree::Boolean { op, color, a, b } => { + let len = dst.len(); + let mut buf_a = vec![0.0f32; len]; + let mut buf_b = vec![0.0f32; len]; + rasterize_shape_tree_f32(a, dims, &mut buf_a, cov_buf, scratch); + rasterize_shape_tree_f32(b, dims, &mut buf_b, cov_buf, scratch); + let mut comb = vec![0.0f32; len]; + let ca = color[3].clamp(0.0, 1.0); + for ((ca_p, cb_p), out_p) in buf_a + .chunks_exact(4) + .zip(buf_b.chunks_exact(4)) + .zip(comb.chunks_exact_mut(4)) + { + let aa = ca_p[3].clamp(0.0, 1.0); + let ba = cb_p[3].clamp(0.0, 1.0); + let oa = match op { + ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0), + ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0), + ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0), + ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0), + }; + let sa = oa * ca; + out_p[0] = color[0] * sa; + out_p[1] = color[1] * sa; + out_p[2] = color[2] * sa; + out_p[3] = sa; + } + composite_over(dst, &comb); + } + } +} + +fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec { + let px_count = (dims[0] as usize) * (dims[1] as usize); + let mut out = vec![0u8; px_count * 4]; + let Some(tree) = tree else { + return out; + }; + let b = blend.clamp(0.0, 1.0); + if b <= 1e-6 { + return out; + } + let mut accum = vec![0.0f32; px_count * 4]; + let mut cov_buf = vec![0u8; px_count]; + let mut scratch = zeno::Scratch::new(); + rasterize_shape_tree_f32(tree, dims, &mut accum, &mut cov_buf, &mut scratch); + for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) { + dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8; + } + out +} + +impl Engine { + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_s_render( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32; + let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32; + let dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims }; + let dst_depth = self.node_depth(comp, node, time, None); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + + let shape_tree = node + .connected_node("Input") + .and_then(|s| comp.find_node(s)) + .and_then(|src_id| { + collect_shape_tree(comp, src_id, time, &self.expr, Affine2D::identity(), None, 0) + }); + + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut h_key = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut h_key); + self.hiq.hash(&mut h_key); + self.cache.node_salt(node.id).hash(&mut h_key); + "sRender".hash(&mut h_key); + dims.hash(&mut h_key); + dst_depth.hash(&mut h_key); + blend.to_bits().hash(&mut h_key); + mask_hash.hash(&mut h_key); + mask_inv.hash(&mut h_key); + if let Some(ref tree) = shape_tree { + 1u8.hash(&mut h_key); + tree.hash_into(&mut h_key); + } else { + 0u8.hash(&mut h_key); + } + let key = h_key.finish(); + + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let rgba = rasterize_shape_tree_rgba8(shape_tree.as_ref(), dims, blend); + let needs_post = dst_depth != BitDepth::Int8 || mask.is_some(); + let base_tex = create_texture(&self.device, dims, if needs_post { 0 } else { key }); + self.queue.write_texture( + base_tex.texture.as_image_copy(), + &rgba, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(dims[0] * 4), + rows_per_image: Some(dims[1]), + }, + wgpu::Extent3d { + width: dims[0], + height: dims[1], + depth_or_array_layers: 1, + }, + ); + + let mut out = if dst_depth != BitDepth::Int8 { + let promoted = self.alloc_tex(dims, dst_depth, if mask.is_some() { 0 } else { key }); + let u = UniformParams::default(); + self.dispatch_op( + enc, + ShaderOp::ChangeDepth, + &base_tex.view, + &self.dummy.view, + &self.dummy.view, + &promoted, + &u, + ); + promoted + } else { + base_tex + }; + + if let Some(ref mtex) = mask { + let masked = self.alloc_tex(dims, out.depth, key); + let mut u = UniformParams::default(); + u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + self.dispatch_op( + enc, + ShaderOp::MaskApply, + &out.view, + &self.dummy.view, + &mtex.view, + &masked, + &u, + ); + out = masked; + } + + self.cache.insert(key, out.clone(), node.id, frame_i); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + #[test] + fn test_s_render_ngon_transform_merge_and_boolean() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + NGon1 = sNGon { + Inputs = { + Sides = Input { Value = 6, }, + Width = Input { Value = 0.4, }, + Red = Input { Value = 1.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 0.0, }, + }, + }, + XF1 = sTransform { + Inputs = { + XOffset = Input { Value = -0.2, }, + YOffset = Input { Value = 0.0, }, + XSize = Input { Value = 1.0, }, + YSize = Input { Value = 1.0, }, + ZRotation = Input { Value = 15.0, }, + Input = Input { SourceOp = "NGon1", Source = "Output", }, + }, + }, + Rect1 = sRectangle { + Inputs = { + Width = Input { Value = 0.3, }, + Height = Input { Value = 0.3, }, + CornerRadius = Input { Value = 0.05, }, + Translate = Input { Value = { 0.0, 0.0 }, }, + ["Translate.X"] = Input { Value = 0.2, }, + Red = Input { Value = 0.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 1.0, }, + }, + }, + Merge1 = sMerge { + Inputs = { + Input1 = Input { SourceOp = "XF1", Source = "Output", }, + Input2 = Input { SourceOp = "Rect1", Source = "Output", }, + }, + }, + Render1 = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "Merge1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sRender comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let render_id = comp.find_node("Render1").unwrap(); + let (tex, stats) = eng.evaluate(&comp, render_id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + assert_eq!(tex.size, [128, 128]); + let px = eng.readback_rgba(&tex).expect("readback sRender"); + + // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red + let left = (64 * 128 + 38) * 4; + assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]); + // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue + let right = (64 * 128 + 90) * 4; + assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]); + // Top-left corner (0, 0) should be transparent + assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent"); + } + + + #[test] + fn test_s_boolean_uses_own_color_and_subtract_xor() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + NGon1 = sNGon { + Inputs = { + Sides = Input { Value = 5, }, + Width = Input { Value = 0.5, }, + Height = Input { Value = 0.5, }, + Red = Input { Value = 1.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 0.0, }, + }, + }, + Rect1 = sRectangle { + Inputs = { + Width = Input { Value = 0.35, }, + Height = Input { Value = 0.35, }, + ["Translate.X"] = Input { Value = 0.18, }, + Red = Input { Value = 0.0, }, + Green = Input { Value = 1.0, }, + Blue = Input { Value = 0.0, }, + }, + }, + BoolSub = sBoolean { + Inputs = { + Operation = Input { Value = FuID { "Subtract" }, }, + Input1 = Input { SourceOp = "Rect1", Source = "Output", }, + Input2 = Input { SourceOp = "NGon1", Source = "Output", }, + }, + }, + BoolXor = sBoolean { + Inputs = { + Operation = Input { Value = FuID { "Xor" }, }, + Input1 = Input { SourceOp = "NGon1", Source = "Output", }, + Input2 = Input { SourceOp = "Rect1", Source = "Output", }, + }, + }, + RSub = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "BoolSub", Source = "Output", }, + }, + }, + RXor = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "BoolXor", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0); + let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0); + let px_sub = eng.readback_rgba(&tex_sub).unwrap(); + let px_xor = eng.readback_rgba(&tex_xor).unwrap(); + + // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white! + let rect_only = (64 * 128 + 102) * 4; + assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]); + assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]); + + // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent! + let overlap = (64 * 128 + 77) * 4; + assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]); + assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]); + + // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor! + let ngon_only = (64 * 128 + 54) * 4; + assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]); + } + + #[test] + fn test_s_boolean_operation_names_and_missing_inputs() { + let boolean = |name: &str, op: &str, inputs: &str| { + format!( + r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }}, + R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }}, + Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"# + ) + }; + let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; + let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#; + let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; + let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#); + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }}, + Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }}, + Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }}, + {} {} {} {} {} {} + }} }}"#, + boolean("Inter", &fu("Intersection"), both), + boolean("Default", "", both), + boolean("Unknown", &fu("Intersect"), both), + boolean("SubFirst", &fu("Subtract"), first), + boolean("SubSecond", &fu("Subtract"), second), + boolean("UnionBoth", &fu("Union"), both), + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let mut px = |name: &str, x: usize| { + let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let i = (64 * 128 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + let white = [255; 4]; + let empty = [0; 4]; + // x=64 is inside both shapes, x=90 is inside only the rectangle. + assert_eq!(px("Inter", 64), white); + assert_eq!(px("Inter", 90), empty); + assert_eq!(px("Default", 64), white, "Operation defaults to Intersection"); + assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing"); + assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color"); + assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing"); + assert_eq!(px("UnionBoth", 90), white); + } + + #[test] + fn test_s_grid() { + let src = r#"{ + Tools = ordered() { + El1 = sEllipse { + Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, + }, + Gr1 = sGrid { + Inputs = { + Input = Input { SourceOp = "El1", Source = "Output", }, + CellsX = Input { Value = 3, }, + CellsY = Input { Value = 3, }, + XOffset = Input { Value = 0.25, }, + YOffset = Input { Value = 0.25, }, + }, + }, + SR1 = sRender { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Input = Input { SourceOp = "Gr1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return; }; + let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0); + let px_sr = eng.readback_rgba(&t_sr).unwrap(); + assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]); + assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]); + assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]); + } +} diff --git a/crates/engine/src/eval/shapes_warp.rs b/crates/engine/src/eval/warps.rs similarity index 52% rename from crates/engine/src/eval/shapes_warp.rs rename to crates/engine/src/eval/warps.rs index 1d049ef8a2ac0e46a64289590af1e62d859e8c01..6e4bd7fb434dbecea759bda2276b91afe97a0f28 100644 --- a/crates/engine/src/eval/shapes_warp.rs +++ b/crates/engine/src/eval/warps.rs @@ -1,659 +1,7 @@ -//! GPU Archive FX Warps (`Drip`, `Dent`) and 2D Vector Shape Pipeline -//! (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sMerge`, `sTransform`, `sBoolean`, `sOutline`). +//! 2D Warp & Sky Generators (`Drip`, `Dent`, `PerspectivePositioner`, `DaySky`, `GridWarp`). use super::*; -#[derive(Clone, Copy, Debug)] -struct Affine2D { - // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty - m: [f32; 6], -} - -impl Affine2D { - fn identity() -> Self { - Self { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] } - } - - fn translate(tx: f32, ty: f32) -> Self { - Self { m: [1.0, 0.0, 0.0, 1.0, tx, ty] } - } - - fn scale(sx: f32, sy: f32) -> Self { - Self { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] } - } - - fn rotate_deg(deg: f32) -> Self { - let r = deg.to_radians(); - let (s, c) = r.sin_cos(); - Self { m: [c, -s, s, c, 0.0, 0.0] } - } - - fn mul(self, rhs: Self) -> Self { - let [a1, b1, c1, d1, tx1, ty1] = self.m; - let [a2, b2, c2, d2, tx2, ty2] = rhs.m; - Self { - m: [ - a1 * a2 + b1 * c2, - a1 * b2 + b1 * d2, - c1 * a2 + d1 * c2, - c1 * b2 + d1 * d2, - a1 * tx2 + b1 * ty2 + tx1, - c1 * tx2 + d1 * ty2 + ty1, - ], - } - } - - fn apply(self, p: [f32; 2]) -> [f32; 2] { - [ - self.m[0] * p[0] + self.m[1] * p[1] + self.m[4], - self.m[2] * p[0] + self.m[3] * p[1] + self.m[5], - ] - } - - fn avg_scale(self) -> f32 { - let sx = self.m[0].hypot(self.m[2]); - let sy = self.m[1].hypot(self.m[3]); - ((sx + sy) * 0.5).max(1e-4) - } - - fn hash_into(self, h: &mut DefaultHasher) { - for v in self.m { - v.to_bits().hash(h); - } - } -} - -#[derive(Clone, Copy, Debug)] -enum ShapePrimKind { - NGon { sides: u32, width: f32, height: f32 }, - Rectangle { width: f32, height: f32, corner_radius: f32 }, - Ellipse { width: f32, height: f32 }, -} - -#[derive(Clone, Copy, Debug)] -enum ShapeBoolOp { - Union, - Intersect, - Subtract, - Xor, -} - -#[derive(Clone, Debug)] -enum ShapeTree { - Primitive { - kind: ShapePrimKind, - xform: Affine2D, - color: [f32; 4], - solid: bool, - border_width: f32, - join_style: u8, - cap_style: u8, - }, - Group(Vec), - Boolean { - op: ShapeBoolOp, - color: [f32; 4], - a: Box, - b: Box, - }, -} - -impl ShapeTree { - fn hash_into(&self, h: &mut DefaultHasher) { - match self { - ShapeTree::Primitive { - kind, - xform, - color, - solid, - border_width, - join_style, - cap_style, - } => { - 0u8.hash(h); - match *kind { - ShapePrimKind::NGon { sides, width, height } => { - 1u8.hash(h); - sides.hash(h); - width.to_bits().hash(h); - height.to_bits().hash(h); - } - ShapePrimKind::Rectangle { width, height, corner_radius } => { - 2u8.hash(h); - width.to_bits().hash(h); - height.to_bits().hash(h); - corner_radius.to_bits().hash(h); - } - ShapePrimKind::Ellipse { width, height } => { - 3u8.hash(h); - width.to_bits().hash(h); - height.to_bits().hash(h); - } - } - xform.hash_into(h); - for c in color { - c.to_bits().hash(h); - } - solid.hash(h); - border_width.to_bits().hash(h); - join_style.hash(h); - cap_style.hash(h); - } - ShapeTree::Group(children) => { - 1u8.hash(h); - children.len().hash(h); - for ch in children { - ch.hash_into(h); - } - } - ShapeTree::Boolean { op, color, a, b } => { - 2u8.hash(h); - (*op as u8).hash(h); - for c in color { - c.to_bits().hash(h); - } - a.hash_into(h); - b.hash_into(h); - } - } - } -} - -fn eval_first_num( - comp: &Comp, - node: &Node, - keys: &[&str], - time: f64, - default: f64, - expr: &ExprEngine, -) -> f64 { - for &k in keys { - if node.inputs.contains_key(k) { - return comp.eval_number(node, k, time, default, expr); - } - } - default -} - -/// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. -fn parse_bool_op(node: &Node) -> Option { - if !node.inputs.contains_key("Operation") { - return Some(ShapeBoolOp::Intersect); - } - match node.static_str("Operation")? { - "Union" => Some(ShapeBoolOp::Union), - "Intersection" => Some(ShapeBoolOp::Intersect), - "Subtract" => Some(ShapeBoolOp::Subtract), - "Xor" => Some(ShapeBoolOp::Xor), - _ => None, - } -} - -#[allow(clippy::too_many_arguments)] -fn collect_shape_tree( - comp: &Comp, - node_id: NodeId, - time: f64, - expr: &ExprEngine, - parent_xform: Affine2D, - outline_override: Option<(f32, u8, u8)>, - depth: usize, -) -> Option { - if depth > 32 { - return None; - } - let node = comp.node(node_id); - if node.bypassed { - return node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s)) - .and_then(|id| { - collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) - }); - } - - match node.kind.as_str() { - "sNGon" | "sRectangle" | "sEllipse" => { - let tx = eval_first_num(comp, node, &["Translate.X", "XOffset"], time, 0.0, expr) as f32; - let ty = eval_first_num(comp, node, &["Translate.Y", "YOffset"], time, 0.0, expr) as f32; - let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; - let local = Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)); - let xform = parent_xform.mul(local); - - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; - - let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; - let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32; - let mut join_style = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8; - let mut cap_style = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; - - if let Some((ov_w, ov_j, ov_c)) = outline_override { - solid = false; - border_width = ov_w; - join_style = ov_j; - cap_style = ov_c; - } - - let kind = match node.kind.as_str() { - "sNGon" => { - let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; - let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; - let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; - ShapePrimKind::NGon { sides, width, height } - } - "sRectangle" => { - let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; - let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; - let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; - ShapePrimKind::Rectangle { width, height, corner_radius } - } - _ => { - let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; - let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; - ShapePrimKind::Ellipse { width, height } - } - }; - - Some(ShapeTree::Primitive { - kind, - xform, - color: [r, g, b, a], - solid, - border_width, - join_style, - cap_style, - }) - } - "sTransform" => { - let src_id = node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; - let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; - let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32; - let py = eval_first_num(comp, node, &["YPivot", "Pivot.Y"], time, 0.0, expr) as f32; - let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); - let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; - let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; - let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; - - let local = Affine2D::translate(ox + px, oy + py) - .mul(Affine2D::rotate_deg(rot)) - .mul(Affine2D::scale(sx, sy)) - .mul(Affine2D::translate(-px, -py)); - let combined = parent_xform.mul(local); - collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1) - } - "sMerge" => { - let mut ports: Vec<(u32, &str)> = node - .inputs - .keys() - .filter_map(|k| { - let rest = k.strip_prefix("Input")?; - let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? }; - Some((idx, k.as_str())) - }) - .collect(); - ports.sort_by_key(|&(idx, _)| idx); - let mut children = Vec::new(); - for (_, port) in ports { - if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { - if let Some(tree) = collect_shape_tree( - comp, - src_id, - time, - expr, - parent_xform, - outline_override, - depth + 1, - ) { - children.push(tree); - } - } - } - if children.is_empty() { - None - } else { - Some(ShapeTree::Group(children)) - } - } - "sGrid" => { - let src_id = node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; - let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; - let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32; - let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32; - let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y)); - for iy in 0..cells_y { - let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off; - for ix in 0..cells_x { - let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off; - let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty)); - if let Some(tree) = collect_shape_tree( - comp, - src_id, - time, - expr, - cell_xf, - outline_override, - depth + 1, - ) { - children.push(tree); - } - } - } - if children.is_empty() { - None - } else { - Some(ShapeTree::Group(children)) - } - } - "sOutline" => { - let src_id = node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr).abs() as f32; - let join = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8; - let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; - collect_shape_tree(comp, src_id, time, expr, parent_xform, Some((thickness, join, cap)), depth + 1) - } - "sBoolean" => { - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; - let color = [r, g, b_col, a_col]; - let child = |port: &str| { - node.connected_node(port) - .and_then(|s| comp.find_node(s)) - .and_then(|id| { - collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) - }) - }; - let a = child("Input1").or_else(|| child("Input"))?; - // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty. - let (op, b) = match (parse_bool_op(node), child("Input2")) { - (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())), - (Some(op), Some(b)) => (op, b), - (None, Some(_)) => return None, - }; - Some(ShapeTree::Boolean { - op, - color, - a: Box::new(a), - b: Box::new(b), - }) - } - "PipeRouter" | "Fuse.Wireless" => { - let src_id = node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1) - } - "MacroOperator" | "GroupOperator" => { - let out_id = node.macro_output?; - collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1) - } - _ => None, - } -} - -fn build_primitive_commands(kind: ShapePrimKind, xform: Affine2D, dims: [u32; 2]) -> Vec { - let wf = dims[0] as f32; - let hf = dims[1] as f32; - let to_px = |local: [f32; 2]| -> zeno::Vector { - let wpt = xform.apply(local); - let px = (wpt[0] + 0.5) * wf; - let py = 0.5 * hf - wpt[1] * wf; - zeno::Vector::new(px, py) - }; - - const KAPPA: f32 = 0.55228475; - let mut cmds = Vec::new(); - match kind { - ShapePrimKind::NGon { sides, width, height } => { - let n = sides.max(3); - let rx = width * 0.5; - let ry = height * 0.5; - if rx <= 1e-6 || ry <= 1e-6 { - return cmds; - } - for k in 0..n { - let theta = (k as f32) * std::f32::consts::TAU / (n as f32); - let v = to_px([rx * theta.cos(), ry * theta.sin()]); - if k == 0 { - cmds.push(zeno::Command::MoveTo(v)); - } else { - cmds.push(zeno::Command::LineTo(v)); - } - } - cmds.push(zeno::Command::Close); - } - ShapePrimKind::Rectangle { width, height, corner_radius } => { - let hx = width * 0.5; - let hy = height * 0.5; - if hx <= 1e-6 || hy <= 1e-6 { - return cmds; - } - let r = corner_radius.min(hx.min(hy)); - if r <= 1e-5 { - cmds.push(zeno::Command::MoveTo(to_px([-hx, -hy]))); - cmds.push(zeno::Command::LineTo(to_px([hx, -hy]))); - cmds.push(zeno::Command::LineTo(to_px([hx, hy]))); - cmds.push(zeno::Command::LineTo(to_px([-hx, hy]))); - cmds.push(zeno::Command::Close); - } else { - let k = r * KAPPA; - cmds.push(zeno::Command::MoveTo(to_px([-hx + r, -hy]))); - cmds.push(zeno::Command::LineTo(to_px([hx - r, -hy]))); - cmds.push(zeno::Command::CurveTo( - to_px([hx - r + k, -hy]), - to_px([hx, -hy + r - k]), - to_px([hx, -hy + r]), - )); - cmds.push(zeno::Command::LineTo(to_px([hx, hy - r]))); - cmds.push(zeno::Command::CurveTo( - to_px([hx, hy - r + k]), - to_px([hx - r + k, hy]), - to_px([hx - r, hy]), - )); - cmds.push(zeno::Command::LineTo(to_px([-hx + r, hy]))); - cmds.push(zeno::Command::CurveTo( - to_px([-hx + r - k, hy]), - to_px([-hx, hy - r + k]), - to_px([-hx, hy - r]), - )); - cmds.push(zeno::Command::LineTo(to_px([-hx, -hy + r]))); - cmds.push(zeno::Command::CurveTo( - to_px([-hx, -hy + r - k]), - to_px([-hx + r - k, -hy]), - to_px([-hx + r, -hy]), - )); - cmds.push(zeno::Command::Close); - } - } - ShapePrimKind::Ellipse { width, height } => { - let rx = width * 0.5; - let ry = height * 0.5; - if rx <= 1e-6 || ry <= 1e-6 { - return cmds; - } - let kx = rx * KAPPA; - let ky = ry * KAPPA; - cmds.push(zeno::Command::MoveTo(to_px([rx, 0.0]))); - cmds.push(zeno::Command::CurveTo( - to_px([rx, ky]), - to_px([kx, ry]), - to_px([0.0, ry]), - )); - cmds.push(zeno::Command::CurveTo( - to_px([-kx, ry]), - to_px([-rx, ky]), - to_px([-rx, 0.0]), - )); - cmds.push(zeno::Command::CurveTo( - to_px([-rx, -ky]), - to_px([-kx, -ry]), - to_px([0.0, -ry]), - )); - cmds.push(zeno::Command::CurveTo( - to_px([kx, -ry]), - to_px([rx, -ky]), - to_px([rx, 0.0]), - )); - cmds.push(zeno::Command::Close); - } - } - cmds -} - -fn composite_over(dst: &mut [f32], src: &[f32]) { - for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) { - let sa = s[3].clamp(0.0, 1.0); - if sa <= 1e-6 { - continue; - } - let inv = 1.0 - sa; - d[0] = s[0] + d[0] * inv; - d[1] = s[1] + d[1] * inv; - d[2] = s[2] + d[2] * inv; - d[3] = sa + d[3] * inv; - } -} - -fn rasterize_shape_tree_f32( - tree: &ShapeTree, - dims: [u32; 2], - dst: &mut [f32], - cov_buf: &mut [u8], - scratch: &mut zeno::Scratch, -) { - let [w, h] = dims; - match tree { - ShapeTree::Primitive { - kind, - xform, - color, - solid, - border_width, - join_style, - cap_style, - } => { - let cmds = build_primitive_commands(*kind, *xform, dims); - if cmds.is_empty() { - return; - } - cov_buf.fill(0); - let style = if *solid { - zeno::Style::Fill(zeno::Fill::NonZero) - } else { - let stroke_px = (*border_width * xform.avg_scale() * (w as f32)).max(0.5); - let join = match *join_style { - 0 => zeno::Join::Bevel, - 1 => zeno::Join::Round, - _ => zeno::Join::Miter, - }; - let cap = match *cap_style { - 1 => zeno::Cap::Round, - 2 => zeno::Cap::Square, - _ => zeno::Cap::Butt, - }; - let mut st = zeno::Stroke::new(stroke_px); - st.join(join).cap(cap); - zeno::Style::Stroke(st) - }; - let _ = zeno::Mask::with_scratch(&cmds, scratch) - .style(style) - .size(w, h) - .origin(zeno::Origin::TopLeft) - .render_into(cov_buf, None); - - let ca = color[3].clamp(0.0, 1.0); - if ca <= 1e-6 { - return; - } - for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { - if cov == 0 { - continue; - } - let sa = (cov as f32 / 255.0) * ca; - let inv = 1.0 - sa; - px[0] = color[0] * sa + px[0] * inv; - px[1] = color[1] * sa + px[1] * inv; - px[2] = color[2] * sa + px[2] * inv; - px[3] = sa + px[3] * inv; - } - } - ShapeTree::Group(children) => { - for ch in children { - rasterize_shape_tree_f32(ch, dims, dst, cov_buf, scratch); - } - } - ShapeTree::Boolean { op, color, a, b } => { - let len = dst.len(); - let mut buf_a = vec![0.0f32; len]; - let mut buf_b = vec![0.0f32; len]; - rasterize_shape_tree_f32(a, dims, &mut buf_a, cov_buf, scratch); - rasterize_shape_tree_f32(b, dims, &mut buf_b, cov_buf, scratch); - let mut comb = vec![0.0f32; len]; - let ca = color[3].clamp(0.0, 1.0); - for ((ca_p, cb_p), out_p) in buf_a - .chunks_exact(4) - .zip(buf_b.chunks_exact(4)) - .zip(comb.chunks_exact_mut(4)) - { - let aa = ca_p[3].clamp(0.0, 1.0); - let ba = cb_p[3].clamp(0.0, 1.0); - let oa = match op { - ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0), - ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0), - ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0), - ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0), - }; - let sa = oa * ca; - out_p[0] = color[0] * sa; - out_p[1] = color[1] * sa; - out_p[2] = color[2] * sa; - out_p[3] = sa; - } - composite_over(dst, &comb); - } - } -} - -fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec { - let px_count = (dims[0] as usize) * (dims[1] as usize); - let mut out = vec![0u8; px_count * 4]; - let Some(tree) = tree else { - return out; - }; - let b = blend.clamp(0.0, 1.0); - if b <= 1e-6 { - return out; - } - let mut accum = vec![0.0f32; px_count * 4]; - let mut cov_buf = vec![0u8; px_count]; - let mut scratch = zeno::Scratch::new(); - rasterize_shape_tree_f32(tree, dims, &mut accum, &mut cov_buf, &mut scratch); - for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) { - dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8; - dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8; - dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8; - dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8; - } - out -} - impl Engine { #[allow(clippy::too_many_arguments)] pub(super) fn eval_drip( @@ -761,114 +109,6 @@ impl Engine { dst } - #[allow(clippy::too_many_arguments)] - pub(super) fn eval_s_render( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - comp_dims: [u32; 2], - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32; - let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32; - let dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims }; - let dst_depth = self.node_depth(comp, node, time, None); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - - let shape_tree = node - .connected_node("Input") - .and_then(|s| comp.find_node(s)) - .and_then(|src_id| { - collect_shape_tree(comp, src_id, time, &self.expr, Affine2D::identity(), None, 0) - }); - - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut h_key = DefaultHasher::new(); - self.cache.gpu_salt.hash(&mut h_key); - self.hiq.hash(&mut h_key); - self.cache.node_salt(node.id).hash(&mut h_key); - "sRender".hash(&mut h_key); - dims.hash(&mut h_key); - dst_depth.hash(&mut h_key); - blend.to_bits().hash(&mut h_key); - mask_hash.hash(&mut h_key); - mask_inv.hash(&mut h_key); - if let Some(ref tree) = shape_tree { - 1u8.hash(&mut h_key); - tree.hash_into(&mut h_key); - } else { - 0u8.hash(&mut h_key); - } - let key = h_key.finish(); - - if let Some(hit) = self.cache.get(key, node.id, frame_i) { - stats.cache_hits += 1; - return hit; - } - stats.cache_misses += 1; - stats.nodes_evaluated += 1; - - let rgba = rasterize_shape_tree_rgba8(shape_tree.as_ref(), dims, blend); - let needs_post = dst_depth != BitDepth::Int8 || mask.is_some(); - let base_tex = create_texture(&self.device, dims, if needs_post { 0 } else { key }); - self.queue.write_texture( - base_tex.texture.as_image_copy(), - &rgba, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(dims[0] * 4), - rows_per_image: Some(dims[1]), - }, - wgpu::Extent3d { - width: dims[0], - height: dims[1], - depth_or_array_layers: 1, - }, - ); - - let mut out = if dst_depth != BitDepth::Int8 { - let promoted = self.alloc_tex(dims, dst_depth, if mask.is_some() { 0 } else { key }); - let u = UniformParams::default(); - self.dispatch_op( - enc, - ShaderOp::ChangeDepth, - &base_tex.view, - &self.dummy.view, - &self.dummy.view, - &promoted, - &u, - ); - promoted - } else { - base_tex - }; - - if let Some(ref mtex) = mask { - let masked = self.alloc_tex(dims, out.depth, key); - let mut u = UniformParams::default(); - u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; - self.dispatch_op( - enc, - ShaderOp::MaskApply, - &out.view, - &self.dummy.view, - &mtex.view, - &masked, - &u, - ); - out = masked; - } - - self.cache.insert(key, out.clone(), node.id, frame_i); - out - } - #[allow(clippy::too_many_arguments)] pub(super) fn eval_perspective_positioner( &mut self, @@ -1485,79 +725,6 @@ mod tests { assert!(interior_diff > 2_000, "Dent interior should visibly distort, got {interior_diff}"); } - #[test] - fn test_s_render_ngon_transform_merge_and_boolean() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - NGon1 = sNGon { - Inputs = { - Sides = Input { Value = 6, }, - Width = Input { Value = 0.4, }, - Red = Input { Value = 1.0, }, - Green = Input { Value = 0.0, }, - Blue = Input { Value = 0.0, }, - }, - }, - XF1 = sTransform { - Inputs = { - XOffset = Input { Value = -0.2, }, - YOffset = Input { Value = 0.0, }, - XSize = Input { Value = 1.0, }, - YSize = Input { Value = 1.0, }, - ZRotation = Input { Value = 15.0, }, - Input = Input { SourceOp = "NGon1", Source = "Output", }, - }, - }, - Rect1 = sRectangle { - Inputs = { - Width = Input { Value = 0.3, }, - Height = Input { Value = 0.3, }, - CornerRadius = Input { Value = 0.05, }, - Translate = Input { Value = { 0.0, 0.0 }, }, - ["Translate.X"] = Input { Value = 0.2, }, - Red = Input { Value = 0.0, }, - Green = Input { Value = 0.0, }, - Blue = Input { Value = 1.0, }, - }, - }, - Merge1 = sMerge { - Inputs = { - Input1 = Input { SourceOp = "XF1", Source = "Output", }, - Input2 = Input { SourceOp = "Rect1", Source = "Output", }, - }, - }, - Render1 = sRender { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Input = Input { SourceOp = "Merge1", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse sRender comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let render_id = comp.find_node("Render1").unwrap(); - let (tex, stats) = eng.evaluate(&comp, render_id, 0.0); - assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); - assert_eq!(tex.size, [128, 128]); - let px = eng.readback_rgba(&tex).expect("readback sRender"); - - // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red - let left = (64 * 128 + 38) * 4; - assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]); - // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue - let right = (64 * 128 + 90) * 4; - assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]); - // Top-left corner (0, 0) should be transparent - assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent"); - } - #[test] fn test_drip_shapes_and_strength_independence() { let make_comp = |strength: f64, shape: i32| { @@ -1656,87 +823,6 @@ mod tests { ); } - #[test] - fn test_s_boolean_uses_own_color_and_subtract_xor() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - NGon1 = sNGon { - Inputs = { - Sides = Input { Value = 5, }, - Width = Input { Value = 0.5, }, - Height = Input { Value = 0.5, }, - Red = Input { Value = 1.0, }, - Green = Input { Value = 0.0, }, - Blue = Input { Value = 0.0, }, - }, - }, - Rect1 = sRectangle { - Inputs = { - Width = Input { Value = 0.35, }, - Height = Input { Value = 0.35, }, - ["Translate.X"] = Input { Value = 0.18, }, - Red = Input { Value = 0.0, }, - Green = Input { Value = 1.0, }, - Blue = Input { Value = 0.0, }, - }, - }, - BoolSub = sBoolean { - Inputs = { - Operation = Input { Value = FuID { "Subtract" }, }, - Input1 = Input { SourceOp = "Rect1", Source = "Output", }, - Input2 = Input { SourceOp = "NGon1", Source = "Output", }, - }, - }, - BoolXor = sBoolean { - Inputs = { - Operation = Input { Value = FuID { "Xor" }, }, - Input1 = Input { SourceOp = "NGon1", Source = "Output", }, - Input2 = Input { SourceOp = "Rect1", Source = "Output", }, - }, - }, - RSub = sRender { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Input = Input { SourceOp = "BoolSub", Source = "Output", }, - }, - }, - RXor = sRender { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Input = Input { SourceOp = "BoolXor", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0); - let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0); - let px_sub = eng.readback_rgba(&tex_sub).unwrap(); - let px_xor = eng.readback_rgba(&tex_xor).unwrap(); - - // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white! - let rect_only = (64 * 128 + 102) * 4; - assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]); - assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]); - - // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent! - let overlap = (64 * 128 + 77) * 4; - assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]); - assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]); - - // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor! - let ngon_only = (64 * 128 + 54) * 4; - assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]); - } - #[test] fn test_dent_sine_falls_off_linearly_from_strength_at_center() { let src = r#"Composition { @@ -1764,56 +850,48 @@ mod tests { } #[test] - fn test_s_boolean_operation_names_and_missing_inputs() { - let boolean = |name: &str, op: &str, inputs: &str| { - format!( - r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }}, - R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }}, - Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"# - ) - }; - let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; - let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#; - let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; - let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#); - let src = format!( - r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ - Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }}, - Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }}, - Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }}, - {} {} {} {} {} {} - }} }}"#, - boolean("Inter", &fu("Intersection"), both), - boolean("Default", "", both), - boolean("Unknown", &fu("Intersect"), both), - boolean("SubFirst", &fu("Subtract"), first), - boolean("SubSecond", &fu("Subtract"), second), - boolean("UnionBoth", &fu("Union"), both), - ); - let comp = Comp::from_fusion_str(&src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let mut px = |name: &str, x: usize| { - let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0); - let rgba = eng.readback_rgba(&tex).unwrap(); - let i = (64 * 128 + x) * 4; - [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] - }; - let white = [255; 4]; - let empty = [0; 4]; - // x=64 is inside both shapes, x=90 is inside only the rectangle. - assert_eq!(px("Inter", 64), white); - assert_eq!(px("Inter", 90), empty); - assert_eq!(px("Default", 64), white, "Operation defaults to Intersection"); - assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing"); - assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color"); - assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing"); - assert_eq!(px("UnionBoth", 90), white); + fn test_drip_out_of_bounds_edges_transparent() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 0 }, + GlobalRange = { 0, 0 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 1.0, }, + TopLeftBlue = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + Drip1 = Drip { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Center = Input { Value = { 0.5, 0.5 }, }, + Amplitude = Input { Value = 0.5, }, + Frequency = Input { Value = 1.0, }, + Phase = Input { Value = 0.25, }, + Dampening = Input { Value = 0.0, }, + Shape = Input { Value = 1, }, + }, + }, + }, + }"#; + 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("Drip1").unwrap(), 0.0); + let px = eng.readback_rgba(&tex).unwrap(); + // Corner samples outside [0, 1] -> transparent black (Canvas edges=0). + assert_eq!(&px[0..4], &[0, 0, 0, 0], "out-of-bounds Drip UV must be transparent"); + // Center stays white (raw_rel=0 -> disp=0). + let c = (64 * 128 + 64) * 4; + assert_eq!(&px[c..c + 4], &[255, 255, 255, 255]); } #[test] - fn test_perspective_positioner_and_s_grid() { + fn test_perspective_positioner() { let src = r#"{ Tools = ordered() { Bg1 = Background { @@ -1835,41 +913,14 @@ mod tests { Input = Input { SourceOp = "Bg1", Source = "Output", }, }, }, - El1 = sEllipse { - Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, - }, - Gr1 = sGrid { - Inputs = { - Input = Input { SourceOp = "El1", Source = "Output", }, - CellsX = Input { Value = 3, }, - CellsY = Input { Value = 3, }, - XOffset = Input { Value = 0.25, }, - YOffset = Input { Value = 0.25, }, - }, - }, - SR1 = sRender { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Input = Input { SourceOp = "Gr1", Source = "Output", }, - }, - }, }, }"#; let comp = Comp::from_fusion_str(src).unwrap(); let Ok(mut eng) = Engine::new_headless() else { return; }; let (t_pp, _) = eng.evaluate(&comp, comp.find_node("PP_Lin").unwrap(), 0.0); let px_pp = eng.readback_rgba(&t_pp).unwrap(); - // Top-left output pixel samples around (0.25, 0.75) in Bg1 -> ~75% red, ~25% blue! let p0 = &px_pp[0..4]; assert!(p0[0] > 165 && p0[2] > 40 && p0[2] < 90, "got {p0:?}"); - - let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0); - let px_sr = eng.readback_rgba(&t_sr).unwrap(); - // Center cell (32, 32) and offset (+0.25*64 = 48, 32) should be lit white - assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]); - assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]); - assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]); } #[test] diff --git a/crates/engine/src/shaders/archive_fx.wgsl b/crates/engine/src/shaders/archive_fx.wgsl index a900e143e6c3e75a0311b916a17dbcf9f5cff65c..063dd32b6b1369160ffaf0852a86cad27d7aba14 100644 --- a/crates/engine/src/shaders/archive_fx.wgsl +++ b/crates/engine/src/shaders/archive_fx.wgsl @@ -52,7 +52,7 @@ fn drip_op(@builtin(global_invocation_id) gid: vec3) { let disp = sin((dist * freq - phase) * 6.28318530718) * amp * falloff; src_fu = fu + raw_rel * disp; } - let warped = sample_edges(src_a, src_fu, 2); + let warped = sample_edges(src_a, src_fu, 0); let m = read_mask(gid.xy, dims, u.p[2].z, u.p[2].w) * blend; store_dst(vec2(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0))); -- 2.54.1