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/shapes_warp.rs deleted file mode 100644 index 1d049ef8a2ac0e46a64289590af1e62d859e8c01..0000000000000000000000000000000000000000 --- a/crates/engine/src/eval/shapes_warp.rs +++ /dev/null @@ -1,1947 +0,0 @@ -//! GPU Archive FX Warps (`Drip`, `Dent`) and 2D Vector Shape Pipeline -//! (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `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_drip( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - let amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32; - if blend <= 1e-6 || amp.abs() <= 1e-7 { - return src; - } - let src = self.crop_to_canvas(enc, src); - let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); - let freq = comp.eval_number(node, "Frequency", time, 10.0, &self.expr) as f32; - let aspect = comp.eval_number(node, "Aspect", time, 1.0, &self.expr).max(1e-4) as f32; - let phase = comp.eval_number(node, "Phase", time, 0.0, &self.expr) as f32; - let dampening = comp.eval_number(node, "Dampening", time, 0.0, &self.expr).max(0.0) as f32; - let shape = comp.eval_number(node, "Shape", time, 0.0, &self.expr).round() as f32; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut u = UniformParams::default(); - u.p[0] = [center[0] as f32, center[1] as f32, 0.0, amp]; - u.p[1] = [freq, aspect, phase, dampening]; - u.p[2] = [shape, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; - - let key = self.make_key( - node, - "Drip", - src.size, - &[src.content_hash, mask_hash], - bytemuck::cast_slice(&u.p[..3]), - ); - 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 dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Drip, &src.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn eval_dent( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - let strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32; - if blend <= 1e-6 || strength.abs() <= 1e-6 { - return src; - } - let src = self.crop_to_canvas(enc, src); - let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); - let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32; - let dent_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as f32; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut u = UniformParams::default(); - u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, strength]; - u.p[1] = [dent_type, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; - - let key = self.make_key( - node, - "Dent", - src.size, - &[src.content_hash, mask_hash], - bytemuck::cast_slice(&u.p[..2]), - ); - 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 dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Dent, &src.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - 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, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - if blend <= 1e-6 { - return src; - } - let src = self.crop_to_canvas(enc, src); - let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr); - let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr); - let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr); - let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr); - let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32; - let h_fwd = quad_forward_homography(bl, br, tr, tl); - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut u = UniformParams::default(); - u.p[0] = [bl[0] as f32, bl[1] as f32, br[0] as f32, br[1] as f32]; - u.p[1] = [tr[0] as f32, tr[1] as f32, tl[0] as f32, tl[1] as f32]; - u.p[2] = [h_fwd[0], h_fwd[1], h_fwd[2], h_fwd[3]]; - u.p[3] = [h_fwd[4], h_fwd[5], h_fwd[6], h_fwd[7]]; - u.p[4] = [ - h_fwd[8], - if mapping_type == 1 { 1.0 } else { 0.0 }, - blend, - if mask.is_some() { 1.0 } else { 0.0 }, - ]; - u.p[5] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; - - let key = self.make_key( - node, - "PerspectivePositioner", - src.size, - &[src.content_hash, mask_hash], - bytemuck::cast_slice(&u.p[..6]), - ); - 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 dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn eval_day_sky( - &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 use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; - let w = if use_ff { - comp.width - } else { - comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32 - }; - let h = if use_ff { - comp.height - } else { - comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32 - }; - let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) }; - 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 lat_deg = comp.eval_number(node, "Latitude", time, 43.65, &self.expr); - let lon_deg = comp.eval_number(node, "Longitude", time, -79.38, &self.expr); - let month = parse_month_index(node, comp, time, &self.expr); - let day = node - .static_str("Day") - .and_then(|s| s.parse::().ok()) - .unwrap_or_else(|| comp.eval_number(node, "Day", time, 1.0, &self.expr)); - let hour = comp.eval_number(node, "Time", time, 12.0, &self.expr); - let turbidity_in = comp.eval_number(node, "Turbidity", time, 0.0, &self.expr).max(0.0); - let exposure = comp.eval_number(node, "Exposure", time, 0.72, &self.expr).max(0.0); - let hb = comp.eval_number(node, "Horizon.Brightness", time, 1.0, &self.expr).max(0.0); - let hl = comp.eval_number(node, "Horizon.Luminance", time, 1.0, &self.expr).max(0.0); - let ci = comp.eval_number(node, "Circumsolar.Intensity", time, 1.0, &self.expr).max(0.0); - let cw = comp.eval_number(node, "Circumsolar.Width", time, 1.0, &self.expr).max(0.0); - let bs = comp.eval_number(node, "BackscatteredLight", time, 1.0, &self.expr).max(0.0); - - let (sun_dir, ts) = solar_direction(lat_deg, lon_deg, month, day, hour); - // Calibrated to Fusion 21.1 DaySky: Turbidity in [0,1] maps to T = 1.9 + 4.0 * turb - let t_preetham = 1.9 + turbidity_in * 4.0; - let (xz, yz, _yz_lum) = preetham_zenith_xyy(t_preetham, ts); - let c_y0 = [ - 0.1787 * t_preetham - 1.4630, - (-0.3554 * t_preetham + 0.4275) * 1.20, - -0.0227 * t_preetham + 5.3251, - 0.1206 * t_preetham - 2.5771, - -0.0670 * t_preetham + 0.3703, - ]; - let c_x0 = [ - -0.0193 * t_preetham - 0.2592, - -0.0665 * t_preetham + 0.0008, - -0.0004 * t_preetham + 0.2125, - -0.0641 * t_preetham - 0.8989, - -0.0033 * t_preetham + 0.0452, - ]; - let c_y_c0 = [ - -0.0167 * t_preetham - 0.2608, - -0.0950 * t_preetham + 0.0092, - -0.0079 * t_preetham + 0.2102, - -0.0441 * t_preetham - 1.6537, - -0.0109 * t_preetham + 0.0529, - ]; - - let scale_perez = |base: [f64; 5]| -> [f64; 5] { - let a = if hb <= 1e-4 || hl <= 1e-4 { 0.0 } else { base[0] * hb }; - let b = base[1] / hl.max(1e-3); - let c = if cw <= 1e-4 { 0.0 } else { base[2] * ci }; - let d = base[3] * cw; - let e = base[4] * bs; - [a, b, c, d, e] - }; - let c_y = scale_perez(c_y0); - let c_x = scale_perez(c_x0); - let c_yc = scale_perez(c_y_c0); - - // Log-average Perez luminance normalization: geom_mean(Y_hdr) == Exposure - const N_TH: usize = 32; - const N_PH: usize = 32; - let mut sum_log = 0.0_f64; - for iy in 0..N_TH { - let th = (iy as f64 + 0.5) / N_TH as f64 * std::f64::consts::FRAC_PI_2; - let (st, ct) = th.sin_cos(); - for ix in 0..N_PH { - let ph = (ix as f64 + 0.5) / N_PH as f64 * std::f64::consts::TAU; - let (sp, cp) = ph.sin_cos(); - let cos_g = (st * cp * sun_dir[0] + st * sp * sun_dir[1] + ct * sun_dir[2]).clamp(-1.0, 1.0); - let fy = eval_perez(th, cos_g.acos(), c_y).max(1e-5); - sum_log += fy.ln(); - } - } - let geomean_fy = (sum_log / (N_TH * N_PH) as f64).exp().max(1e-5); - let lum_gain = (exposure / geomean_fy) as f32; - let f_y0 = 1.0_f64; - let f_x0 = eval_perez(0.0, ts, c_x); - let f_yc0 = eval_perez(0.0, ts, c_yc); - let yz_scaled = lum_gain; - - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut u = UniformParams::default(); - u.p[0] = [sun_dir[0] as f32, sun_dir[1] as f32, sun_dir[2] as f32, yz_scaled]; - u.p[1] = [xz as f32, yz as f32, f_y0 as f32, f_x0 as f32]; - u.p[2] = [f_yc0 as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; - u.p[3] = [c_y[0] as f32, c_y[1] as f32, c_y[2] as f32, c_y[3] as f32]; - u.p[4] = [c_y[4] as f32, c_x[0] as f32, c_x[1] as f32, c_x[2] as f32]; - u.p[5] = [c_x[3] as f32, c_x[4] as f32, c_yc[0] as f32, c_yc[1] as f32]; - u.p[6] = [c_yc[2] as f32, c_yc[3] as f32, c_yc[4] as f32, 0.0]; - - let key = self.make_key( - node, - "DaySky", - size, - &[mask_hash, dst_depth as u64], - bytemuck::cast_slice(&u.p[..7]), - ); - 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 dst = self.alloc_tex(size, dst_depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::DaySky, &self.dummy.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn eval_grid_warp( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - if blend <= 1e-6 { - return src; - } - let src_mesh = comp.eval_grid_mesh(node, "SrcGridChange", time); - let dst_mesh = comp.eval_grid_mesh(node, "DstGridChange", time); - let (Some(src_mesh), Some(dst_mesh)) = (src_mesh, dst_mesh) else { - return src; - }; - if src_mesh == dst_mesh { - return src; - } - let src = self.crop_to_canvas(enc, src); - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut u = UniformParams::default(); - u.p[0] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0]; - - let mut mesh_params: Vec = Vec::with_capacity(4 + (src_mesh.points.len() + dst_mesh.points.len()) * 10); - mesh_params.extend_from_slice(&[blend, src_mesh.cols as f32, src_mesh.rows as f32, dst_mesh.cols as f32]); - for m in [&src_mesh, &dst_mesh] { - for p in &m.points { - mesh_params.extend_from_slice(&[ - p.x as f32, - p.y as f32, - p.l_cx.unwrap_or(f32::NAN as f64) as f32, - p.l_cy.unwrap_or(0.0) as f32, - p.r_cx.unwrap_or(f32::NAN as f64) as f32, - p.r_cy.unwrap_or(0.0) as f32, - p.t_cx.unwrap_or(0.0) as f32, - p.t_cy.unwrap_or(f32::NAN as f64) as f32, - p.b_cx.unwrap_or(0.0) as f32, - p.b_cy.unwrap_or(f32::NAN as f64) as f32, - ]); - } - } - - let key = self.make_key(node, "GridWarp", src.size, &[src.content_hash, mask_hash], &mesh_params); - 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 uv_f16 = rasterize_grid_warp_uv_f16(&src_mesh, &dst_mesh, src.size); - let uv_tex = create_texture_dod_fmt( - &self.device, - src.size, - [0, 0], - src.size, - BitDepth::Float16, - wgpu::TextureFormat::Rgba16Float, - 0, - ); - self.queue.write_texture( - uv_tex.texture.as_image_copy(), - bytemuck::cast_slice(&uv_f16), - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(src.size[0] * 8), - rows_per_image: Some(src.size[1]), - }, - wgpu::Extent3d { - width: src.size[0], - height: src.size[1], - depth_or_array_layers: 1, - }, - ); - - let dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::GridWarp, &src.view, &uv_tex.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } -} - -fn quad_forward_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] { - let dx1 = br[0] - tr[0]; - let dy1 = br[1] - tr[1]; - let dx2 = tl[0] - tr[0]; - let dy2 = tl[1] - tr[1]; - let sx = bl[0] - br[0] + tr[0] - tl[0]; - let sy = bl[1] - br[1] + tr[1] - tl[1]; - let denom = dx1 * dy2 - dx2 * dy1; - if denom.abs() < 1e-10 { - return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]; - } - let g = (sx * dy2 - sy * dx2) / denom; - let h = (dx1 * sy - dy1 * sx) / denom; - let a = br[0] - bl[0] + g * br[0]; - let b = tl[0] - bl[0] + h * tl[0]; - let c = bl[0]; - let d = br[1] - bl[1] + g * br[1]; - let e = tl[1] - bl[1] + h * tl[1]; - let f = bl[1]; - [a as f32, b as f32, c as f32, d as f32, e as f32, f as f32, g as f32, h as f32, 1.0] -} - -fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize { - if let Some(m) = node.static_str("Month") { - let low = m.to_ascii_lowercase(); - let names = [ - "january", "february", "march", "april", "may", "june", - "july", "august", "september", "october", "november", "december", - ]; - if let Some(idx) = names.iter().position(|&n| low.starts_with(&n[..3])) { - return idx + 1; - } - if let Ok(v) = m.parse::() { - return v.clamp(1, 12); - } - } - (comp.eval_number(node, "Month", time, 0.0, expr).round() as usize + 1).clamp(1, 12) -} - -fn solar_direction(lat_deg: f64, lon_deg: f64, month: usize, day: f64, hour: f64) -> ([f64; 3], f64) { - const CUM_DAYS: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; - let doy = CUM_DAYS[month.saturating_sub(1).min(11)] as f64 + day; - let b = 2.0 * std::f64::consts::PI * (doy - 81.0) / 365.0; - let eot_min = 9.87 * (2.0 * b).sin() - 7.53 * b.cos() - 1.5 * b.sin(); - let decl = 23.44_f64.to_radians() * ((2.0 * std::f64::consts::PI / 365.0) * (doy - 81.0)).sin(); - let std_meridian = (lon_deg / 15.0).round() * 15.0; - let solar_hour = hour + (lon_deg - std_meridian) / 15.0 + eot_min / 60.0; - let hour_angle = ((solar_hour - 12.0) * 15.0).to_radians(); - let lat = lat_deg.to_radians(); - let sin_alt = (lat.sin() * decl.sin() + lat.cos() * decl.cos() * hour_angle.cos()).clamp(-1.0, 1.0); - let ts = (std::f64::consts::FRAC_PI_2 - sin_alt.asin()).max(0.0); - // Azimuth measured from South (0=South, pi/2=East morning, pi=North, 3*pi/2=West afternoon) - let cos_az_south = (-(decl.sin() * lat.cos() - decl.cos() * lat.sin() * hour_angle.cos()) - / ts.sin().max(1e-5)) - .clamp(-1.0, 1.0); - let mut phi_s = cos_az_south.acos(); - if hour_angle > 0.0 { - phi_s = 2.0 * std::f64::consts::PI - phi_s; - } - let dir = [ts.sin() * phi_s.cos(), ts.sin() * phi_s.sin(), ts.cos()]; - (dir, ts) -} - -fn preetham_zenith_xyy(t: f64, ts: f64) -> (f64, f64, f64) { - let t2 = t * t; - let ts2 = ts * ts; - let ts3 = ts2 * ts; - let chi = (4.0 / 9.0 - t / 120.0) * (std::f64::consts::PI - 2.0 * ts); - let yz_lum = ((4.0453 * t - 4.9710) * chi.tan() - 0.2155 * t + 2.4192).max(0.05); - let xz = (0.00166 * ts3 - 0.00375 * ts2 + 0.00209 * ts) * t2 - + (-0.02903 * ts3 + 0.06377 * ts2 - 0.03202 * ts + 0.00394) * t - + (0.11693 * ts3 - 0.21196 * ts2 + 0.06052 * ts + 0.25886); - let yz = (0.00275 * ts3 - 0.00610 * ts2 + 0.00317 * ts) * t2 - + (-0.04214 * ts3 + 0.08970 * ts2 - 0.04153 * ts + 0.00516) * t - + (0.15346 * ts3 - 0.26756 * ts2 + 0.06670 * ts + 0.26688); - (xz, yz, yz_lum) -} - -fn eval_perez(theta: f64, gamma: f64, c: [f64; 5]) -> f64 { - let ct = theta.cos().max(0.02); - let cg = gamma.cos(); - (1.0 + c[0] * (c[1] / ct).exp()) * (1.0 + c[2] * (c[3] * gamma).exp() + c[4] * cg * cg) -} - -#[derive(Clone, Copy)] -struct CoonsPt { - p: [f32; 2], - l: [f32; 2], - r: [f32; 2], - t: [f32; 2], - b: [f32; 2], -} - -fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> { - let cols = mesh.cols; - let rows = mesh.rows; - let dc = (mesh.delta_c as f32) / 3.0; - let dr = (mesh.delta_r as f32) / 3.0; - let pts: Vec = mesh - .points - .iter() - .map(|mp| { - let p = [mp.x as f32, mp.y as f32]; - let l = [p[0] + mp.l_cx.map_or(-dc, |v| v as f32), p[1] + mp.l_cy.unwrap_or(0.0) as f32]; - let r = [p[0] + mp.r_cx.map_or(dc, |v| v as f32), p[1] + mp.r_cy.unwrap_or(0.0) as f32]; - let t = [p[0] + mp.t_cx.unwrap_or(0.0) as f32, p[1] + mp.t_cy.map_or(-dr, |v| v as f32)]; - let b = [p[0] + mp.b_cx.unwrap_or(0.0) as f32, p[1] + mp.b_cy.map_or(dr, |v| v as f32)]; - CoonsPt { p, l, r, t, b } - }) - .collect(); - let mut cells = Vec::with_capacity((cols - 1) * (rows - 1)); - for r in 0..(rows - 1) { - for c in 0..(cols - 1) { - cells.push([ - pts[r * cols + c], - pts[r * cols + c + 1], - pts[(r + 1) * cols + c], - pts[(r + 1) * cols + c + 1], - ]); - } - } - cells -} - -fn bez3_2d(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] { - let u = 1.0 - t; - let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); - [ - w0 * p0[0] + w1 * p1[0] + w2 * p2[0] + w3 * p3[0], - w0 * p0[1] + w1 * p1[1] + w2 * p2[1] + w3 * p3[1], - ] -} - -fn eval_coons_cell(cell: &[CoonsPt; 4], u: f32, v: f32) -> [f32; 2] { - let [p00, p10, p01, p11] = *cell; - let bot = bez3_2d(p00.p, p00.r, p10.l, p10.p, u); - let top = bez3_2d(p01.p, p01.r, p11.l, p11.p, u); - let lft = bez3_2d(p00.p, p00.b, p01.t, p01.p, v); - let rgt = bez3_2d(p10.p, p10.b, p11.t, p11.p, v); - let bi0 = (1.0 - u) * (1.0 - v) * p00.p[0] + u * (1.0 - v) * p10.p[0] + (1.0 - u) * v * p01.p[0] + u * v * p11.p[0]; - let bi1 = (1.0 - u) * (1.0 - v) * p00.p[1] + u * (1.0 - v) * p10.p[1] + (1.0 - u) * v * p01.p[1] + u * v * p11.p[1]; - [ - (1.0 - v) * bot[0] + v * top[0] + (1.0 - u) * lft[0] + u * rgt[0] - bi0, - (1.0 - v) * bot[1] + v * top[1] + (1.0 - u) * lft[1] + u * rgt[1] - bi1, - ] -} - -fn rasterize_grid_warp_uv_f16( - src_mesh: &model::comp::GridMesh, - dst_mesh: &model::comp::GridMesh, - dims: [u32; 2], -) -> Vec { - let [w, h] = dims; - let (wf, hf) = (w as f32, h as f32); - let mut uv_buf = vec![0u16; (w as usize) * (h as usize) * 4]; - let src_cells = mesh_coons_cells(src_mesh); - let dst_cells = mesh_coons_cells(dst_mesh); - let sub = 24usize; - let one_f16 = crate::media::f32_to_f16_bits(1.0); - - for (sc, dc) in src_cells.iter().zip(dst_cells.iter()) { - for j in 0..sub { - let (v0, v1) = (j as f32 / sub as f32, (j + 1) as f32 / sub as f32); - for i in 0..sub { - let (u0, u1) = (i as f32 / sub as f32, (i + 1) as f32 / sub as f32); - let da = eval_coons_cell(dc, u0, v0); - let db = eval_coons_cell(dc, u1, v0); - let dc2 = eval_coons_cell(dc, u1, v1); - let dd = eval_coons_cell(dc, u0, v1); - let sa = eval_coons_cell(sc, u0, v0); - let sb = eval_coons_cell(sc, u1, v0); - let sc2 = eval_coons_cell(sc, u1, v1); - let sd = eval_coons_cell(sc, u0, v1); - - for ([pa, pb, pc], [qa, qb, qc]) in [([da, db, dc2], [sa, sb, sc2]), ([da, dc2, dd], [sa, sc2, sd])] { - let (ax, ay) = ((pa[0] + 0.5) * wf, (0.5 - pa[1]) * hf); - let (bx, by) = ((pb[0] + 0.5) * wf, (0.5 - pb[1]) * hf); - let (cx, cy) = ((pc[0] + 0.5) * wf, (0.5 - pc[1]) * hf); - let area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); - if area.abs() < 1e-6 { - continue; - } - let inv_area = 1.0 / area; - let x0 = ax.min(bx).min(cx).floor().max(0.0) as u32; - let x1 = (ax.max(bx).max(cx).ceil() as u32).min(w.saturating_sub(1)); - let y0 = ay.min(by).min(cy).floor().max(0.0) as u32; - let y1 = (ay.max(by).max(cy).ceil() as u32).min(h.saturating_sub(1)); - for py in y0..=y1 { - let qy = py as f32 + 0.5; - for px in x0..=x1 { - let qx = px as f32 + 0.5; - let w0 = ((bx - qx) * (cy - qy) - (by - qy) * (cx - qx)) * inv_area; - let w1 = ((cx - qx) * (ay - qy) - (cy - qy) * (ax - qx)) * inv_area; - let w2 = 1.0 - w0 - w1; - if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 { - let su = w0 * qa[0] + w1 * qb[0] + w2 * qc[0] + 0.5; - let sv = w0 * qa[1] + w1 * qb[1] + w2 * qc[1] + 0.5; - let idx = (py as usize * w as usize + px as usize) * 4; - uv_buf[idx] = crate::media::f32_to_f16_bits(su); - uv_buf[idx + 1] = crate::media::f32_to_f16_bits(sv); - uv_buf[idx + 2] = one_f16; - } - } - } - } - } - } - } - uv_buf -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Engine; - - #[test] - fn test_drip_concentric_ripple_displacement() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopRightRed = Input { Value = 0.0, }, - TopRightGreen = Input { Value = 0.0, }, - TopRightBlue = Input { Value = 1.0, }, - }, - }, - Drip1 = Drip { - Inputs = { - Input = Input { SourceOp = "BG1", Source = "Output", }, - Center = Input { Value = { 0.5, 0.5 }, }, - Strength = Input { Value = 1.0, }, - Amplitude = Input { Value = 0.12, }, - Frequency = Input { Value = 4.0, }, - Phase = Input { Value = 0.0, }, - Shape = Input { Value = 0, }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse Drip comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let bg_id = comp.find_node("BG1").unwrap(); - let drip_id = comp.find_node("Drip1").unwrap(); - let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0); - let (drip_tex, stats) = eng.evaluate(&comp, drip_id, 0.0); - assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); - let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg"); - let drip_px = eng.readback_rgba(&drip_tex).expect("readback drip"); - - let diff_sum: u64 = bg_px - .iter() - .zip(drip_px.iter()) - .map(|(&a, &b)| a.abs_diff(b) as u64) - .sum(); - assert!(diff_sum > 10_000, "Drip should visibly displace pixels, got diff_sum={diff_sum}"); - } - - #[test] - fn test_dent_radial_distortion() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopRightRed = Input { Value = 0.0, }, - TopRightGreen = Input { Value = 1.0, }, - TopRightBlue = Input { Value = 0.0, }, - }, - }, - Dent1 = Dent { - Inputs = { - Input = Input { SourceOp = "BG1", Source = "Output", }, - Center = Input { Value = { 0.5, 0.5 }, }, - Size = Input { Value = 0.6, }, - Strength = Input { Value = 0.8, }, - Type = Input { Value = 0, }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse Dent comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let bg_id = comp.find_node("BG1").unwrap(); - let dent_id = comp.find_node("Dent1").unwrap(); - let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0); - let (dent_tex, stats) = eng.evaluate(&comp, dent_id, 0.0); - assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); - let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg"); - let dent_px = eng.readback_rgba(&dent_tex).expect("readback dent"); - - // Corners outside radius=0.3 must remain unchanged; interior must be distorted! - assert_eq!(&bg_px[0..4], &dent_px[0..4], "corner pixel outside dent radius should match"); - let mut interior_diff = 0u64; - for y in 44..84 { - for x in 44..84 { - let idx = (y * 128 + x) * 4; - interior_diff += bg_px[idx].abs_diff(dent_px[idx]) as u64; - interior_diff += bg_px[idx + 1].abs_diff(dent_px[idx + 1]) as u64; - } - } - 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| { - format!( - r#"Composition {{ - CurrentTime = 0, - RenderRange = {{ 0, 1 }}, - GlobalRange = {{ 0, 1 }}, - Tools = ordered() {{ - BG1 = Background {{ - Inputs = {{ - Width = Input {{ Value = 128, }}, - Height = Input {{ Value = 128, }}, - Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, - TopLeftRed = Input {{ Value = 1.0, }}, - TopRightBlue = Input {{ Value = 1.0, }}, - }}, - }}, - Drip1 = Drip {{ - Inputs = {{ - Input = Input {{ SourceOp = "BG1", Source = "Output", }}, - Center = Input {{ Value = {{ 0.4, 0.6 }}, }}, - Strength = Input {{ Value = {strength}, }}, - Amplitude = Input {{ Value = 0.08, }}, - Frequency = Input {{ Value = 4.0, }}, - Phase = Input {{ Value = 0.75, }}, - Shape = Input {{ Value = {shape}, }}, - }}, - }}, - }}, - }}"# - ) - }; - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let comp_a = Comp::from_fusion_str(&make_comp(0.25, 1)).unwrap(); - let comp_b = Comp::from_fusion_str(&make_comp(1.0, 1)).unwrap(); - let (tex_a, _) = eng.evaluate(&comp_a, comp_a.find_node("Drip1").unwrap(), 0.0); - let (tex_b, _) = eng.evaluate(&comp_b, comp_b.find_node("Drip1").unwrap(), 0.0); - let px_a = eng.readback_rgba(&tex_a).unwrap(); - let px_b = eng.readback_rgba(&tex_b).unwrap(); - assert_eq!(px_a, px_b, "Fusion Drip ignores Strength and uses Amplitude directly"); - - // Center pixel (0.4*128=51, (1-0.6)*128=51) must remain smooth (raw_rel=0 -> disp=0) - let (bg_tex, _) = eng.evaluate(&comp_a, comp_a.find_node("BG1").unwrap(), 0.0); - let bg_px = eng.readback_rgba(&bg_tex).unwrap(); - let diff_sum: u64 = bg_px.iter().zip(px_a.iter()).map(|(&a, &b)| a.abs_diff(b) as u64).sum(); - assert!(diff_sum > 5_000, "Square Drip should displace pixels, got {diff_sum}"); - } - - #[test] - fn test_dent_type0_signed_inversion() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopRightRed = Input { Value = 0.0, }, - TopRightGreen = Input { Value = 1.0, }, - TopRightBlue = Input { Value = 0.0, }, - }, - }, - Dent1 = Dent { - Inputs = { - Input = Input { SourceOp = "BG1", Source = "Output", }, - Center = Input { Value = { 0.5, 0.5 }, }, - Size = Input { Value = 0.65, }, - Strength = Input { Value = 0.75, }, - Type = Input { Value = 0, }, - }, - }, - }, - }"#; - 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("Dent1").unwrap(), 0.0); - let px = eng.readback_rgba(&tex).unwrap(); - // Just right of center (x=72, r~0.066): new_r = r - 0.75*(0.325 - r) < 0, - // so it samples the LEFT (red-dominant) side! - let right_near = (64 * 128 + 72) * 4; - assert!( - px[right_near] > px[right_near + 1] + 40, - "Dent Type=0 should invert radially near center: {:?}", - &px[right_near..right_near + 4] - ); - } - - #[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 { - CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, - Tools = ordered() { - BG1 = Background { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, - TopRightRed = Input { Value = 0, }, TopRightGreen = Input { Value = 1, }, TopRightBlue = Input { Value = 0, }, TopRightAlpha = Input { Value = 1, }, }, }, - Dent1 = Dent { Inputs = { Input = Input { SourceOp = "BG1", Source = "Output", }, - Center = Input { Value = { 0.5, 0.5 }, }, Size = Input { Value = 0.5, }, - Strength = Input { Value = 0.5, }, Type = 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("Dent1").unwrap(), 0.0); - let px = eng.readback_rgba(&tex).unwrap(); - // x=72 (r=0.066 of the 0.25 radius): new_r = r - 0.5 * (1 - r / R) = -0.30 -> source at x=0.20, - // so the gradient reads ~80% red / ~20% green. - let i = (64 * 128 + 72) * 4; - assert!(px[i].abs_diff(204) < 8 && px[i + 1].abs_diff(51) < 8, "got {:?}", &px[i..i + 4]); - } - - #[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_perspective_positioner_and_s_grid() { - let src = r#"{ - Tools = ordered() { - Bg1 = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1, }, - TopRightRed = Input { Value = 0, }, - TopRightBlue = Input { Value = 1, }, - }, - }, - PP_Lin = PerspectivePositioner { - Inputs = { - TopLeft = Input { Value = { 0.25, 0.75 }, }, - TopRight = Input { Value = { 0.75, 0.75 }, }, - BottomLeft = Input { Value = { 0.25, 0.25 }, }, - BottomRight = Input { Value = { 0.75, 0.25 }, }, - 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] - fn test_day_sky_and_grid_warp() { - let src = r#"{ - Tools = ordered() { - DS1 = DaySky { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Latitude = Input { Value = 37.0, }, - Longitude = Input { Value = 0.0, }, - Time = Input { Value = 12.0, }, - Exposure = Input { Value = 1.0, }, - }, - }, - BgW = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1, }, - TopRightGreen = Input { Value = 1, }, - }, - }, - GW1 = GridWarp { - Inputs = { - SrcGridChange = Input { - Value = Mesh { - Columns = 2, Rows = 2, - DeltaC = 1, DeltaR = 1, - Center = { 0, 0 }, - Corners = { -0.5, -0.5, 0.5, 0.5 }, - Points = { - { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 }, - { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 }, - }, - }, - }, - DstGridChange = Input { - Value = Mesh { - Columns = 2, Rows = 2, - DeltaC = 1, DeltaR = 1, - Center = { 0, 0 }, - Corners = { -0.5, -0.5, 0.5, 0.5 }, - Points = { - { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 }, - { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 }, - }, - }, - }, - Input = Input { SourceOp = "BgW", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { return; }; - let (t_ds, _) = eng.evaluate(&comp, comp.find_node("DS1").unwrap(), 0.0); - let px_ds = eng.readback_rgba(&t_ds).unwrap(); - // Zenith row (y=0) is sky blue (B > R), horizon (y=63) is brighter haze - let zen = &px_ds[(0 * 64 + 32) * 4..(0 * 64 + 32) * 4 + 4]; - let hor = &px_ds[(62 * 64 + 32) * 4..(62 * 64 + 32) * 4 + 4]; - assert!(zen[2] > zen[0] && zen[3] == 255, "zen={zen:?}"); - assert!(hor[0] > zen[0], "hor={hor:?} zen={zen:?}"); - - let (t_bg, _) = eng.evaluate(&comp, comp.find_node("BgW").unwrap(), 0.0); - let (t_gw, _) = eng.evaluate(&comp, comp.find_node("GW1").unwrap(), 0.0); - let px_bg = eng.readback_rgba(&t_bg).unwrap(); - let px_gw = eng.readback_rgba(&t_gw).unwrap(); - let mae: f64 = px_bg.iter().zip(&px_gw).map(|(a, b)| (*a as f64 - *b as f64).abs()).sum::() - / px_bg.len() as f64; - assert!(mae < 1.5, "identity GridWarp should match source, mae={mae}"); - } -} diff --git a/crates/engine/src/eval/warps.rs b/crates/engine/src/eval/warps.rs new file mode 100644 index 0000000000000000000000000000000000000000..6e4bd7fb434dbecea759bda2276b91afe97a0f28 --- /dev/null +++ b/crates/engine/src/eval/warps.rs @@ -0,0 +1,998 @@ +//! 2D Warp & Sky Generators (`Drip`, `Dent`, `PerspectivePositioner`, `DaySky`, `GridWarp`). + +use super::*; + +impl Engine { + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_drip( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32; + if blend <= 1e-6 || amp.abs() <= 1e-7 { + return src; + } + let src = self.crop_to_canvas(enc, src); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let freq = comp.eval_number(node, "Frequency", time, 10.0, &self.expr) as f32; + let aspect = comp.eval_number(node, "Aspect", time, 1.0, &self.expr).max(1e-4) as f32; + let phase = comp.eval_number(node, "Phase", time, 0.0, &self.expr) as f32; + let dampening = comp.eval_number(node, "Dampening", time, 0.0, &self.expr).max(0.0) as f32; + let shape = comp.eval_number(node, "Shape", time, 0.0, &self.expr).round() as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, 0.0, amp]; + u.p[1] = [freq, aspect, phase, dampening]; + u.p[2] = [shape, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + + let key = self.make_key( + node, + "Drip", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..3]), + ); + 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 dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Drip, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_dent( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32; + if blend <= 1e-6 || strength.abs() <= 1e-6 { + return src; + } + let src = self.crop_to_canvas(enc, src); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32; + let dent_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, strength]; + u.p[1] = [dent_type, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + + let key = self.make_key( + node, + "Dent", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..2]), + ); + 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 dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Dent, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_perspective_positioner( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let src = self.crop_to_canvas(enc, src); + let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr); + let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr); + let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr); + let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr); + let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32; + let h_fwd = quad_forward_homography(bl, br, tr, tl); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [bl[0] as f32, bl[1] as f32, br[0] as f32, br[1] as f32]; + u.p[1] = [tr[0] as f32, tr[1] as f32, tl[0] as f32, tl[1] as f32]; + u.p[2] = [h_fwd[0], h_fwd[1], h_fwd[2], h_fwd[3]]; + u.p[3] = [h_fwd[4], h_fwd[5], h_fwd[6], h_fwd[7]]; + u.p[4] = [ + h_fwd[8], + if mapping_type == 1 { 1.0 } else { 0.0 }, + blend, + if mask.is_some() { 1.0 } else { 0.0 }, + ]; + u.p[5] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + + let key = self.make_key( + node, + "PerspectivePositioner", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..6]), + ); + 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 dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_day_sky( + &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 use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; + let w = if use_ff { + comp.width + } else { + comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32 + }; + let h = if use_ff { + comp.height + } else { + comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32 + }; + let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) }; + 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 lat_deg = comp.eval_number(node, "Latitude", time, 43.65, &self.expr); + let lon_deg = comp.eval_number(node, "Longitude", time, -79.38, &self.expr); + let month = parse_month_index(node, comp, time, &self.expr); + let day = node + .static_str("Day") + .and_then(|s| s.parse::().ok()) + .unwrap_or_else(|| comp.eval_number(node, "Day", time, 1.0, &self.expr)); + let hour = comp.eval_number(node, "Time", time, 12.0, &self.expr); + let turbidity_in = comp.eval_number(node, "Turbidity", time, 0.0, &self.expr).max(0.0); + let exposure = comp.eval_number(node, "Exposure", time, 0.72, &self.expr).max(0.0); + let hb = comp.eval_number(node, "Horizon.Brightness", time, 1.0, &self.expr).max(0.0); + let hl = comp.eval_number(node, "Horizon.Luminance", time, 1.0, &self.expr).max(0.0); + let ci = comp.eval_number(node, "Circumsolar.Intensity", time, 1.0, &self.expr).max(0.0); + let cw = comp.eval_number(node, "Circumsolar.Width", time, 1.0, &self.expr).max(0.0); + let bs = comp.eval_number(node, "BackscatteredLight", time, 1.0, &self.expr).max(0.0); + + let (sun_dir, ts) = solar_direction(lat_deg, lon_deg, month, day, hour); + // Calibrated to Fusion 21.1 DaySky: Turbidity in [0,1] maps to T = 1.9 + 4.0 * turb + let t_preetham = 1.9 + turbidity_in * 4.0; + let (xz, yz, _yz_lum) = preetham_zenith_xyy(t_preetham, ts); + let c_y0 = [ + 0.1787 * t_preetham - 1.4630, + (-0.3554 * t_preetham + 0.4275) * 1.20, + -0.0227 * t_preetham + 5.3251, + 0.1206 * t_preetham - 2.5771, + -0.0670 * t_preetham + 0.3703, + ]; + let c_x0 = [ + -0.0193 * t_preetham - 0.2592, + -0.0665 * t_preetham + 0.0008, + -0.0004 * t_preetham + 0.2125, + -0.0641 * t_preetham - 0.8989, + -0.0033 * t_preetham + 0.0452, + ]; + let c_y_c0 = [ + -0.0167 * t_preetham - 0.2608, + -0.0950 * t_preetham + 0.0092, + -0.0079 * t_preetham + 0.2102, + -0.0441 * t_preetham - 1.6537, + -0.0109 * t_preetham + 0.0529, + ]; + + let scale_perez = |base: [f64; 5]| -> [f64; 5] { + let a = if hb <= 1e-4 || hl <= 1e-4 { 0.0 } else { base[0] * hb }; + let b = base[1] / hl.max(1e-3); + let c = if cw <= 1e-4 { 0.0 } else { base[2] * ci }; + let d = base[3] * cw; + let e = base[4] * bs; + [a, b, c, d, e] + }; + let c_y = scale_perez(c_y0); + let c_x = scale_perez(c_x0); + let c_yc = scale_perez(c_y_c0); + + // Log-average Perez luminance normalization: geom_mean(Y_hdr) == Exposure + const N_TH: usize = 32; + const N_PH: usize = 32; + let mut sum_log = 0.0_f64; + for iy in 0..N_TH { + let th = (iy as f64 + 0.5) / N_TH as f64 * std::f64::consts::FRAC_PI_2; + let (st, ct) = th.sin_cos(); + for ix in 0..N_PH { + let ph = (ix as f64 + 0.5) / N_PH as f64 * std::f64::consts::TAU; + let (sp, cp) = ph.sin_cos(); + let cos_g = (st * cp * sun_dir[0] + st * sp * sun_dir[1] + ct * sun_dir[2]).clamp(-1.0, 1.0); + let fy = eval_perez(th, cos_g.acos(), c_y).max(1e-5); + sum_log += fy.ln(); + } + } + let geomean_fy = (sum_log / (N_TH * N_PH) as f64).exp().max(1e-5); + let lum_gain = (exposure / geomean_fy) as f32; + let f_y0 = 1.0_f64; + let f_x0 = eval_perez(0.0, ts, c_x); + let f_yc0 = eval_perez(0.0, ts, c_yc); + let yz_scaled = lum_gain; + + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [sun_dir[0] as f32, sun_dir[1] as f32, sun_dir[2] as f32, yz_scaled]; + u.p[1] = [xz as f32, yz as f32, f_y0 as f32, f_x0 as f32]; + u.p[2] = [f_yc0 as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + u.p[3] = [c_y[0] as f32, c_y[1] as f32, c_y[2] as f32, c_y[3] as f32]; + u.p[4] = [c_y[4] as f32, c_x[0] as f32, c_x[1] as f32, c_x[2] as f32]; + u.p[5] = [c_x[3] as f32, c_x[4] as f32, c_yc[0] as f32, c_yc[1] as f32]; + u.p[6] = [c_yc[2] as f32, c_yc[3] as f32, c_yc[4] as f32, 0.0]; + + let key = self.make_key( + node, + "DaySky", + size, + &[mask_hash, dst_depth as u64], + bytemuck::cast_slice(&u.p[..7]), + ); + 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 dst = self.alloc_tex(size, dst_depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::DaySky, &self.dummy.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_grid_warp( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let src_mesh = comp.eval_grid_mesh(node, "SrcGridChange", time); + let dst_mesh = comp.eval_grid_mesh(node, "DstGridChange", time); + let (Some(src_mesh), Some(dst_mesh)) = (src_mesh, dst_mesh) else { + return src; + }; + if src_mesh == dst_mesh { + return src; + } + let src = self.crop_to_canvas(enc, src); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0]; + + let mut mesh_params: Vec = Vec::with_capacity(4 + (src_mesh.points.len() + dst_mesh.points.len()) * 10); + mesh_params.extend_from_slice(&[blend, src_mesh.cols as f32, src_mesh.rows as f32, dst_mesh.cols as f32]); + for m in [&src_mesh, &dst_mesh] { + for p in &m.points { + mesh_params.extend_from_slice(&[ + p.x as f32, + p.y as f32, + p.l_cx.unwrap_or(f32::NAN as f64) as f32, + p.l_cy.unwrap_or(0.0) as f32, + p.r_cx.unwrap_or(f32::NAN as f64) as f32, + p.r_cy.unwrap_or(0.0) as f32, + p.t_cx.unwrap_or(0.0) as f32, + p.t_cy.unwrap_or(f32::NAN as f64) as f32, + p.b_cx.unwrap_or(0.0) as f32, + p.b_cy.unwrap_or(f32::NAN as f64) as f32, + ]); + } + } + + let key = self.make_key(node, "GridWarp", src.size, &[src.content_hash, mask_hash], &mesh_params); + 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 uv_f16 = rasterize_grid_warp_uv_f16(&src_mesh, &dst_mesh, src.size); + let uv_tex = create_texture_dod_fmt( + &self.device, + src.size, + [0, 0], + src.size, + BitDepth::Float16, + wgpu::TextureFormat::Rgba16Float, + 0, + ); + self.queue.write_texture( + uv_tex.texture.as_image_copy(), + bytemuck::cast_slice(&uv_f16), + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(src.size[0] * 8), + rows_per_image: Some(src.size[1]), + }, + wgpu::Extent3d { + width: src.size[0], + height: src.size[1], + depth_or_array_layers: 1, + }, + ); + + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::GridWarp, &src.view, &uv_tex.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +fn quad_forward_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] { + let dx1 = br[0] - tr[0]; + let dy1 = br[1] - tr[1]; + let dx2 = tl[0] - tr[0]; + let dy2 = tl[1] - tr[1]; + let sx = bl[0] - br[0] + tr[0] - tl[0]; + let sy = bl[1] - br[1] + tr[1] - tl[1]; + let denom = dx1 * dy2 - dx2 * dy1; + if denom.abs() < 1e-10 { + return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]; + } + let g = (sx * dy2 - sy * dx2) / denom; + let h = (dx1 * sy - dy1 * sx) / denom; + let a = br[0] - bl[0] + g * br[0]; + let b = tl[0] - bl[0] + h * tl[0]; + let c = bl[0]; + let d = br[1] - bl[1] + g * br[1]; + let e = tl[1] - bl[1] + h * tl[1]; + let f = bl[1]; + [a as f32, b as f32, c as f32, d as f32, e as f32, f as f32, g as f32, h as f32, 1.0] +} + +fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize { + if let Some(m) = node.static_str("Month") { + let low = m.to_ascii_lowercase(); + let names = [ + "january", "february", "march", "april", "may", "june", + "july", "august", "september", "october", "november", "december", + ]; + if let Some(idx) = names.iter().position(|&n| low.starts_with(&n[..3])) { + return idx + 1; + } + if let Ok(v) = m.parse::() { + return v.clamp(1, 12); + } + } + (comp.eval_number(node, "Month", time, 0.0, expr).round() as usize + 1).clamp(1, 12) +} + +fn solar_direction(lat_deg: f64, lon_deg: f64, month: usize, day: f64, hour: f64) -> ([f64; 3], f64) { + const CUM_DAYS: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + let doy = CUM_DAYS[month.saturating_sub(1).min(11)] as f64 + day; + let b = 2.0 * std::f64::consts::PI * (doy - 81.0) / 365.0; + let eot_min = 9.87 * (2.0 * b).sin() - 7.53 * b.cos() - 1.5 * b.sin(); + let decl = 23.44_f64.to_radians() * ((2.0 * std::f64::consts::PI / 365.0) * (doy - 81.0)).sin(); + let std_meridian = (lon_deg / 15.0).round() * 15.0; + let solar_hour = hour + (lon_deg - std_meridian) / 15.0 + eot_min / 60.0; + let hour_angle = ((solar_hour - 12.0) * 15.0).to_radians(); + let lat = lat_deg.to_radians(); + let sin_alt = (lat.sin() * decl.sin() + lat.cos() * decl.cos() * hour_angle.cos()).clamp(-1.0, 1.0); + let ts = (std::f64::consts::FRAC_PI_2 - sin_alt.asin()).max(0.0); + // Azimuth measured from South (0=South, pi/2=East morning, pi=North, 3*pi/2=West afternoon) + let cos_az_south = (-(decl.sin() * lat.cos() - decl.cos() * lat.sin() * hour_angle.cos()) + / ts.sin().max(1e-5)) + .clamp(-1.0, 1.0); + let mut phi_s = cos_az_south.acos(); + if hour_angle > 0.0 { + phi_s = 2.0 * std::f64::consts::PI - phi_s; + } + let dir = [ts.sin() * phi_s.cos(), ts.sin() * phi_s.sin(), ts.cos()]; + (dir, ts) +} + +fn preetham_zenith_xyy(t: f64, ts: f64) -> (f64, f64, f64) { + let t2 = t * t; + let ts2 = ts * ts; + let ts3 = ts2 * ts; + let chi = (4.0 / 9.0 - t / 120.0) * (std::f64::consts::PI - 2.0 * ts); + let yz_lum = ((4.0453 * t - 4.9710) * chi.tan() - 0.2155 * t + 2.4192).max(0.05); + let xz = (0.00166 * ts3 - 0.00375 * ts2 + 0.00209 * ts) * t2 + + (-0.02903 * ts3 + 0.06377 * ts2 - 0.03202 * ts + 0.00394) * t + + (0.11693 * ts3 - 0.21196 * ts2 + 0.06052 * ts + 0.25886); + let yz = (0.00275 * ts3 - 0.00610 * ts2 + 0.00317 * ts) * t2 + + (-0.04214 * ts3 + 0.08970 * ts2 - 0.04153 * ts + 0.00516) * t + + (0.15346 * ts3 - 0.26756 * ts2 + 0.06670 * ts + 0.26688); + (xz, yz, yz_lum) +} + +fn eval_perez(theta: f64, gamma: f64, c: [f64; 5]) -> f64 { + let ct = theta.cos().max(0.02); + let cg = gamma.cos(); + (1.0 + c[0] * (c[1] / ct).exp()) * (1.0 + c[2] * (c[3] * gamma).exp() + c[4] * cg * cg) +} + +#[derive(Clone, Copy)] +struct CoonsPt { + p: [f32; 2], + l: [f32; 2], + r: [f32; 2], + t: [f32; 2], + b: [f32; 2], +} + +fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> { + let cols = mesh.cols; + let rows = mesh.rows; + let dc = (mesh.delta_c as f32) / 3.0; + let dr = (mesh.delta_r as f32) / 3.0; + let pts: Vec = mesh + .points + .iter() + .map(|mp| { + let p = [mp.x as f32, mp.y as f32]; + let l = [p[0] + mp.l_cx.map_or(-dc, |v| v as f32), p[1] + mp.l_cy.unwrap_or(0.0) as f32]; + let r = [p[0] + mp.r_cx.map_or(dc, |v| v as f32), p[1] + mp.r_cy.unwrap_or(0.0) as f32]; + let t = [p[0] + mp.t_cx.unwrap_or(0.0) as f32, p[1] + mp.t_cy.map_or(-dr, |v| v as f32)]; + let b = [p[0] + mp.b_cx.unwrap_or(0.0) as f32, p[1] + mp.b_cy.map_or(dr, |v| v as f32)]; + CoonsPt { p, l, r, t, b } + }) + .collect(); + let mut cells = Vec::with_capacity((cols - 1) * (rows - 1)); + for r in 0..(rows - 1) { + for c in 0..(cols - 1) { + cells.push([ + pts[r * cols + c], + pts[r * cols + c + 1], + pts[(r + 1) * cols + c], + pts[(r + 1) * cols + c + 1], + ]); + } + } + cells +} + +fn bez3_2d(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] { + let u = 1.0 - t; + let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + [ + w0 * p0[0] + w1 * p1[0] + w2 * p2[0] + w3 * p3[0], + w0 * p0[1] + w1 * p1[1] + w2 * p2[1] + w3 * p3[1], + ] +} + +fn eval_coons_cell(cell: &[CoonsPt; 4], u: f32, v: f32) -> [f32; 2] { + let [p00, p10, p01, p11] = *cell; + let bot = bez3_2d(p00.p, p00.r, p10.l, p10.p, u); + let top = bez3_2d(p01.p, p01.r, p11.l, p11.p, u); + let lft = bez3_2d(p00.p, p00.b, p01.t, p01.p, v); + let rgt = bez3_2d(p10.p, p10.b, p11.t, p11.p, v); + let bi0 = (1.0 - u) * (1.0 - v) * p00.p[0] + u * (1.0 - v) * p10.p[0] + (1.0 - u) * v * p01.p[0] + u * v * p11.p[0]; + let bi1 = (1.0 - u) * (1.0 - v) * p00.p[1] + u * (1.0 - v) * p10.p[1] + (1.0 - u) * v * p01.p[1] + u * v * p11.p[1]; + [ + (1.0 - v) * bot[0] + v * top[0] + (1.0 - u) * lft[0] + u * rgt[0] - bi0, + (1.0 - v) * bot[1] + v * top[1] + (1.0 - u) * lft[1] + u * rgt[1] - bi1, + ] +} + +fn rasterize_grid_warp_uv_f16( + src_mesh: &model::comp::GridMesh, + dst_mesh: &model::comp::GridMesh, + dims: [u32; 2], +) -> Vec { + let [w, h] = dims; + let (wf, hf) = (w as f32, h as f32); + let mut uv_buf = vec![0u16; (w as usize) * (h as usize) * 4]; + let src_cells = mesh_coons_cells(src_mesh); + let dst_cells = mesh_coons_cells(dst_mesh); + let sub = 24usize; + let one_f16 = crate::media::f32_to_f16_bits(1.0); + + for (sc, dc) in src_cells.iter().zip(dst_cells.iter()) { + for j in 0..sub { + let (v0, v1) = (j as f32 / sub as f32, (j + 1) as f32 / sub as f32); + for i in 0..sub { + let (u0, u1) = (i as f32 / sub as f32, (i + 1) as f32 / sub as f32); + let da = eval_coons_cell(dc, u0, v0); + let db = eval_coons_cell(dc, u1, v0); + let dc2 = eval_coons_cell(dc, u1, v1); + let dd = eval_coons_cell(dc, u0, v1); + let sa = eval_coons_cell(sc, u0, v0); + let sb = eval_coons_cell(sc, u1, v0); + let sc2 = eval_coons_cell(sc, u1, v1); + let sd = eval_coons_cell(sc, u0, v1); + + for ([pa, pb, pc], [qa, qb, qc]) in [([da, db, dc2], [sa, sb, sc2]), ([da, dc2, dd], [sa, sc2, sd])] { + let (ax, ay) = ((pa[0] + 0.5) * wf, (0.5 - pa[1]) * hf); + let (bx, by) = ((pb[0] + 0.5) * wf, (0.5 - pb[1]) * hf); + let (cx, cy) = ((pc[0] + 0.5) * wf, (0.5 - pc[1]) * hf); + let area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); + if area.abs() < 1e-6 { + continue; + } + let inv_area = 1.0 / area; + let x0 = ax.min(bx).min(cx).floor().max(0.0) as u32; + let x1 = (ax.max(bx).max(cx).ceil() as u32).min(w.saturating_sub(1)); + let y0 = ay.min(by).min(cy).floor().max(0.0) as u32; + let y1 = (ay.max(by).max(cy).ceil() as u32).min(h.saturating_sub(1)); + for py in y0..=y1 { + let qy = py as f32 + 0.5; + for px in x0..=x1 { + let qx = px as f32 + 0.5; + let w0 = ((bx - qx) * (cy - qy) - (by - qy) * (cx - qx)) * inv_area; + let w1 = ((cx - qx) * (ay - qy) - (cy - qy) * (ax - qx)) * inv_area; + let w2 = 1.0 - w0 - w1; + if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 { + let su = w0 * qa[0] + w1 * qb[0] + w2 * qc[0] + 0.5; + let sv = w0 * qa[1] + w1 * qb[1] + w2 * qc[1] + 0.5; + let idx = (py as usize * w as usize + px as usize) * 4; + uv_buf[idx] = crate::media::f32_to_f16_bits(su); + uv_buf[idx + 1] = crate::media::f32_to_f16_bits(sv); + uv_buf[idx + 2] = one_f16; + } + } + } + } + } + } + } + uv_buf +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + #[test] + fn test_drip_concentric_ripple_displacement() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 0.0, }, + TopRightBlue = Input { Value = 1.0, }, + }, + }, + Drip1 = Drip { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Center = Input { Value = { 0.5, 0.5 }, }, + Strength = Input { Value = 1.0, }, + Amplitude = Input { Value = 0.12, }, + Frequency = Input { Value = 4.0, }, + Phase = Input { Value = 0.0, }, + Shape = Input { Value = 0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse Drip comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let bg_id = comp.find_node("BG1").unwrap(); + let drip_id = comp.find_node("Drip1").unwrap(); + let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0); + let (drip_tex, stats) = eng.evaluate(&comp, drip_id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg"); + let drip_px = eng.readback_rgba(&drip_tex).expect("readback drip"); + + let diff_sum: u64 = bg_px + .iter() + .zip(drip_px.iter()) + .map(|(&a, &b)| a.abs_diff(b) as u64) + .sum(); + assert!(diff_sum > 10_000, "Drip should visibly displace pixels, got diff_sum={diff_sum}"); + } + + #[test] + fn test_dent_radial_distortion() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 1.0, }, + TopRightBlue = Input { Value = 0.0, }, + }, + }, + Dent1 = Dent { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Center = Input { Value = { 0.5, 0.5 }, }, + Size = Input { Value = 0.6, }, + Strength = Input { Value = 0.8, }, + Type = Input { Value = 0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse Dent comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let bg_id = comp.find_node("BG1").unwrap(); + let dent_id = comp.find_node("Dent1").unwrap(); + let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0); + let (dent_tex, stats) = eng.evaluate(&comp, dent_id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg"); + let dent_px = eng.readback_rgba(&dent_tex).expect("readback dent"); + + // Corners outside radius=0.3 must remain unchanged; interior must be distorted! + assert_eq!(&bg_px[0..4], &dent_px[0..4], "corner pixel outside dent radius should match"); + let mut interior_diff = 0u64; + for y in 44..84 { + for x in 44..84 { + let idx = (y * 128 + x) * 4; + interior_diff += bg_px[idx].abs_diff(dent_px[idx]) as u64; + interior_diff += bg_px[idx + 1].abs_diff(dent_px[idx + 1]) as u64; + } + } + assert!(interior_diff > 2_000, "Dent interior should visibly distort, got {interior_diff}"); + } + + #[test] + fn test_drip_shapes_and_strength_independence() { + let make_comp = |strength: f64, shape: i32| { + format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 1 }}, + GlobalRange = {{ 0, 1 }}, + Tools = ordered() {{ + BG1 = Background {{ + Inputs = {{ + Width = Input {{ Value = 128, }}, + Height = Input {{ Value = 128, }}, + Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, + TopLeftRed = Input {{ Value = 1.0, }}, + TopRightBlue = Input {{ Value = 1.0, }}, + }}, + }}, + Drip1 = Drip {{ + Inputs = {{ + Input = Input {{ SourceOp = "BG1", Source = "Output", }}, + Center = Input {{ Value = {{ 0.4, 0.6 }}, }}, + Strength = Input {{ Value = {strength}, }}, + Amplitude = Input {{ Value = 0.08, }}, + Frequency = Input {{ Value = 4.0, }}, + Phase = Input {{ Value = 0.75, }}, + Shape = Input {{ Value = {shape}, }}, + }}, + }}, + }}, + }}"# + ) + }; + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let comp_a = Comp::from_fusion_str(&make_comp(0.25, 1)).unwrap(); + let comp_b = Comp::from_fusion_str(&make_comp(1.0, 1)).unwrap(); + let (tex_a, _) = eng.evaluate(&comp_a, comp_a.find_node("Drip1").unwrap(), 0.0); + let (tex_b, _) = eng.evaluate(&comp_b, comp_b.find_node("Drip1").unwrap(), 0.0); + let px_a = eng.readback_rgba(&tex_a).unwrap(); + let px_b = eng.readback_rgba(&tex_b).unwrap(); + assert_eq!(px_a, px_b, "Fusion Drip ignores Strength and uses Amplitude directly"); + + // Center pixel (0.4*128=51, (1-0.6)*128=51) must remain smooth (raw_rel=0 -> disp=0) + let (bg_tex, _) = eng.evaluate(&comp_a, comp_a.find_node("BG1").unwrap(), 0.0); + let bg_px = eng.readback_rgba(&bg_tex).unwrap(); + let diff_sum: u64 = bg_px.iter().zip(px_a.iter()).map(|(&a, &b)| a.abs_diff(b) as u64).sum(); + assert!(diff_sum > 5_000, "Square Drip should displace pixels, got {diff_sum}"); + } + + #[test] + fn test_dent_type0_signed_inversion() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 1.0, }, + TopRightBlue = Input { Value = 0.0, }, + }, + }, + Dent1 = Dent { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Center = Input { Value = { 0.5, 0.5 }, }, + Size = Input { Value = 0.65, }, + Strength = Input { Value = 0.75, }, + Type = Input { Value = 0, }, + }, + }, + }, + }"#; + 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("Dent1").unwrap(), 0.0); + let px = eng.readback_rgba(&tex).unwrap(); + // Just right of center (x=72, r~0.066): new_r = r - 0.75*(0.325 - r) < 0, + // so it samples the LEFT (red-dominant) side! + let right_near = (64 * 128 + 72) * 4; + assert!( + px[right_near] > px[right_near + 1] + 40, + "Dent Type=0 should invert radially near center: {:?}", + &px[right_near..right_near + 4] + ); + } + + #[test] + fn test_dent_sine_falls_off_linearly_from_strength_at_center() { + 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, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, + TopRightRed = Input { Value = 0, }, TopRightGreen = Input { Value = 1, }, TopRightBlue = Input { Value = 0, }, TopRightAlpha = Input { Value = 1, }, }, }, + Dent1 = Dent { Inputs = { Input = Input { SourceOp = "BG1", Source = "Output", }, + Center = Input { Value = { 0.5, 0.5 }, }, Size = Input { Value = 0.5, }, + Strength = Input { Value = 0.5, }, Type = 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("Dent1").unwrap(), 0.0); + let px = eng.readback_rgba(&tex).unwrap(); + // x=72 (r=0.066 of the 0.25 radius): new_r = r - 0.5 * (1 - r / R) = -0.30 -> source at x=0.20, + // so the gradient reads ~80% red / ~20% green. + let i = (64 * 128 + 72) * 4; + assert!(px[i].abs_diff(204) < 8 && px[i + 1].abs_diff(51) < 8, "got {:?}", &px[i..i + 4]); + } + + #[test] + 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() { + let src = r#"{ + Tools = ordered() { + Bg1 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1, }, + TopRightRed = Input { Value = 0, }, + TopRightBlue = Input { Value = 1, }, + }, + }, + PP_Lin = PerspectivePositioner { + Inputs = { + TopLeft = Input { Value = { 0.25, 0.75 }, }, + TopRight = Input { Value = { 0.75, 0.75 }, }, + BottomLeft = Input { Value = { 0.25, 0.25 }, }, + BottomRight = Input { Value = { 0.75, 0.25 }, }, + Input = Input { SourceOp = "Bg1", 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(); + let p0 = &px_pp[0..4]; + assert!(p0[0] > 165 && p0[2] > 40 && p0[2] < 90, "got {p0:?}"); + } + + #[test] + fn test_day_sky_and_grid_warp() { + let src = r#"{ + Tools = ordered() { + DS1 = DaySky { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Latitude = Input { Value = 37.0, }, + Longitude = Input { Value = 0.0, }, + Time = Input { Value = 12.0, }, + Exposure = Input { Value = 1.0, }, + }, + }, + BgW = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1, }, + TopRightGreen = Input { Value = 1, }, + }, + }, + GW1 = GridWarp { + Inputs = { + SrcGridChange = Input { + Value = Mesh { + Columns = 2, Rows = 2, + DeltaC = 1, DeltaR = 1, + Center = { 0, 0 }, + Corners = { -0.5, -0.5, 0.5, 0.5 }, + Points = { + { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 }, + { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 }, + }, + }, + }, + DstGridChange = Input { + Value = Mesh { + Columns = 2, Rows = 2, + DeltaC = 1, DeltaR = 1, + Center = { 0, 0 }, + Corners = { -0.5, -0.5, 0.5, 0.5 }, + Points = { + { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 }, + { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 }, + }, + }, + }, + Input = Input { SourceOp = "BgW", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return; }; + let (t_ds, _) = eng.evaluate(&comp, comp.find_node("DS1").unwrap(), 0.0); + let px_ds = eng.readback_rgba(&t_ds).unwrap(); + // Zenith row (y=0) is sky blue (B > R), horizon (y=63) is brighter haze + let zen = &px_ds[(0 * 64 + 32) * 4..(0 * 64 + 32) * 4 + 4]; + let hor = &px_ds[(62 * 64 + 32) * 4..(62 * 64 + 32) * 4 + 4]; + assert!(zen[2] > zen[0] && zen[3] == 255, "zen={zen:?}"); + assert!(hor[0] > zen[0], "hor={hor:?} zen={zen:?}"); + + let (t_bg, _) = eng.evaluate(&comp, comp.find_node("BgW").unwrap(), 0.0); + let (t_gw, _) = eng.evaluate(&comp, comp.find_node("GW1").unwrap(), 0.0); + let px_bg = eng.readback_rgba(&t_bg).unwrap(); + let px_gw = eng.readback_rgba(&t_gw).unwrap(); + let mae: f64 = px_bg.iter().zip(&px_gw).map(|(a, b)| (*a as f64 - *b as f64).abs()).sum::() + / px_bg.len() as f64; + assert!(mae < 1.5, "identity GridWarp should match source, mae={mae}"); + } +} 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)));