| author | |
| committer | |
| log | 5fd17bff6a750204f867078cbf48d377f638ac2b |
| tree | a3b9b00086acf342594b9515477483eadc952029 |
| parent | 02e4f5004f51636f215726c475a75eb3421a4a07 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
12 files changed, 4049 insertions(+), 1146 deletions(-)
crates/engine/src/eval/mod.rs+11-1| ... | @@ -986,9 +986,14 @@ impl Engine { | ... | @@ -986,9 +986,14 @@ impl Engine { |
| 986 | | "sRectangle" | 986 | | "sRectangle" |
| 987 | | "sEllipse" | 987 | | "sEllipse" |
| 988 | | "sStar" | 988 | | "sStar" |
| 989 | | "sPolygon" | ||
| 989 | | "sGrid" | 990 | | "sGrid" |
| 990 | | "sMerge" | 991 | | "sMerge" |
| 991 | | "sTransform" | 992 | | "sTransform" |
| 993 | | "sDuplicate" | ||
| 994 | | "sJitter" | ||
| 995 | | "sExpand" | ||
| 996 | | "sOffset" | ||
| 992 | | "sBoolean" | 997 | | "sBoolean" |
| 993 | | "sOutline" => self.dummy.clone(), | 998 | | "sOutline" => self.dummy.clone(), |
| 994 | "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), | 999 | "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), |
| ... | @@ -1015,7 +1020,12 @@ impl Engine { | ... | @@ -1015,7 +1020,12 @@ impl Engine { |
| 1015 | | "pFriction" | 1020 | | "pFriction" |
| 1016 | | "pKill" | 1021 | | "pKill" |
| 1017 | | "pMerge" | 1022 | | "pMerge" |
| 1018 | | "pBounce" => self.dummy.clone(), | 1023 | | "pBounce" |
| 1024 | | "pVortex" | ||
| 1025 | | "pFlock" | ||
| 1026 | | "pSpawn" | ||
| 1027 | | "pChangeStyle" | ||
| 1028 | | "pGradientForce" => self.dummy.clone(), | ||
| 1019 | "Custom" if node.connected_node("Image1").and_then(|s| comp.find_node(s)).is_none() => self.dummy.clone(), | 1029 | "Custom" if node.connected_node("Image1").and_then(|s| comp.find_node(s)).is_none() => self.dummy.clone(), |
| 1020 | "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | 1030 | "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1021 | "SurfaceTracker" => self.eval_surface_tracker(comp, node, time, frame_i, enc, visiting, stats), | 1031 | "SurfaceTracker" => self.eval_surface_tracker(comp, node, time, frame_i, enc, visiting, stats), |
crates/engine/src/eval/shapes.rs+113-1128| ... | @@ -1,8 +1,20 @@ | ... | @@ -1,8 +1,20 @@ |
| 1 | //! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sStar`, `sGrid`, | 1 | //! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sStar`, `sPolygon`, |
| 2 | //! `sMerge`, `sTransform`, `sBoolean`, `sOutline`). | 2 | //! `sGrid`, `sMerge`, `sTransform`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, `sBoolean`, `sOutline`). |
| 3 | |||
| 4 | mod collect; | ||
| 5 | mod geometry; | ||
| 6 | mod raster; | ||
| 7 | #[cfg(test)] | ||
| 8 | mod tests; | ||
| 3 | 9 | ||
| 4 | use super::*; | 10 | use super::*; |
| 5 | 11 | ||
| 12 | use collect::collect_shape_tree; | ||
| 13 | use raster::rasterize_shape_tree_rgba8; | ||
| 14 | |||
| 15 | /// Safety cap on total collected leaf primitives so nested `sDuplicate`/`sGrid` cannot blow up memory. | ||
| 16 | const MAX_SHAPE_PRIMITIVES: usize = 4096; | ||
| 17 | |||
| 6 | #[derive(Clone, Copy, Debug)] | 18 | #[derive(Clone, Copy, Debug)] |
| 7 | struct Affine2D { | 19 | struct Affine2D { |
| 8 | // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty | 20 | // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty |
| ... | @@ -63,12 +75,13 @@ impl Affine2D { | ... | @@ -63,12 +75,13 @@ impl Affine2D { |
| 63 | } | 75 | } |
| 64 | } | 76 | } |
| 65 | 77 | ||
| 66 | #[derive(Clone, Copy, Debug)] | 78 | #[derive(Clone, Debug)] |
| 67 | enum ShapePrimKind { | 79 | enum ShapePrimKind { |
| 68 | NGon { sides: u32, width: f32, height: f32 }, | 80 | NGon { sides: u32, width: f32, height: f32 }, |
| 69 | Rectangle { width: f32, height: f32, corner_radius: f32 }, | 81 | Rectangle { width: f32, height: f32, corner_radius: f32 }, |
| 70 | Ellipse { width: f32, height: f32 }, | 82 | Ellipse { width: f32, height: f32 }, |
| 71 | Star { points: u32, depth: f32, width: f32, height: f32, corner_radius: f32 }, | 83 | Star { points: u32, depth: f32, width: f32, height: f32, corner_radius: f32 }, |
| 84 | Polygon { points: Vec<model::PolyPoint>, closed: bool }, | ||
| 72 | } | 85 | } |
| 73 | 86 | ||
| 74 | #[derive(Clone, Copy, Debug)] | 87 | #[derive(Clone, Copy, Debug)] |
| ... | @@ -89,6 +102,67 @@ struct OutlineStyle { | ... | @@ -89,6 +102,67 @@ struct OutlineStyle { |
| 89 | write_len: f32, | 102 | write_len: f32, |
| 90 | } | 103 | } |
| 91 | 104 | ||
| 105 | #[derive(Clone, Copy, Debug)] | ||
| 106 | enum PathModifier { | ||
| 107 | Expand { | ||
| 108 | amount: f32, | ||
| 109 | join_style: u8, | ||
| 110 | miter_limit: f32, | ||
| 111 | }, | ||
| 112 | Jitter { | ||
| 113 | x_amount: f32, | ||
| 114 | y_amount: f32, | ||
| 115 | seed: i64, | ||
| 116 | smoothness: f32, | ||
| 117 | per_shape: bool, | ||
| 118 | }, | ||
| 119 | Offset { | ||
| 120 | offset_x: f32, | ||
| 121 | offset_y: f32, | ||
| 122 | contour_offset: f32, | ||
| 123 | position: f32, | ||
| 124 | join_style: u8, | ||
| 125 | miter_limit: f32, | ||
| 126 | }, | ||
| 127 | } | ||
| 128 | |||
| 129 | impl PathModifier { | ||
| 130 | fn hash_into(self, h: &mut DefaultHasher) { | ||
| 131 | match self { | ||
| 132 | PathModifier::Expand { amount, join_style, miter_limit } => { | ||
| 133 | 0u8.hash(h); | ||
| 134 | amount.to_bits().hash(h); | ||
| 135 | join_style.hash(h); | ||
| 136 | miter_limit.to_bits().hash(h); | ||
| 137 | } | ||
| 138 | PathModifier::Jitter { x_amount, y_amount, seed, smoothness, per_shape } => { | ||
| 139 | 1u8.hash(h); | ||
| 140 | x_amount.to_bits().hash(h); | ||
| 141 | y_amount.to_bits().hash(h); | ||
| 142 | seed.hash(h); | ||
| 143 | smoothness.to_bits().hash(h); | ||
| 144 | per_shape.hash(h); | ||
| 145 | } | ||
| 146 | PathModifier::Offset { | ||
| 147 | offset_x, | ||
| 148 | offset_y, | ||
| 149 | contour_offset, | ||
| 150 | position, | ||
| 151 | join_style, | ||
| 152 | miter_limit, | ||
| 153 | } => { | ||
| 154 | 2u8.hash(h); | ||
| 155 | offset_x.to_bits().hash(h); | ||
| 156 | offset_y.to_bits().hash(h); | ||
| 157 | contour_offset.to_bits().hash(h); | ||
| 158 | position.to_bits().hash(h); | ||
| 159 | join_style.hash(h); | ||
| 160 | miter_limit.to_bits().hash(h); | ||
| 161 | } | ||
| 162 | } | ||
| 163 | } | ||
| 164 | } | ||
| 165 | |||
| 92 | #[derive(Clone, Debug)] | 166 | #[derive(Clone, Debug)] |
| 93 | enum ShapeTree { | 167 | enum ShapeTree { |
| 94 | Primitive { | 168 | Primitive { |
| ... | @@ -112,6 +186,11 @@ enum ShapeTree { | ... | @@ -112,6 +186,11 @@ enum ShapeTree { |
| 112 | a: Box<ShapeTree>, | 186 | a: Box<ShapeTree>, |
| 113 | b: Box<ShapeTree>, | 187 | b: Box<ShapeTree>, |
| 114 | }, | 188 | }, |
| 189 | Modify { | ||
| 190 | op: PathModifier, | ||
| 191 | post_xform: Affine2D, | ||
| 192 | child: Box<ShapeTree>, | ||
| 193 | }, | ||
| 115 | } | 194 | } |
| 116 | 195 | ||
| 117 | impl ShapeTree { | 196 | impl ShapeTree { |
| ... | @@ -130,7 +209,7 @@ impl ShapeTree { | ... | @@ -130,7 +209,7 @@ impl ShapeTree { |
| 130 | write_len, | 209 | write_len, |
| 131 | } => { | 210 | } => { |
| 132 | 0u8.hash(h); | 211 | 0u8.hash(h); |
| 133 | match *kind { | 212 | match kind { |
| 134 | ShapePrimKind::NGon { sides, width, height } => { | 213 | ShapePrimKind::NGon { sides, width, height } => { |
| 135 | 1u8.hash(h); | 214 | 1u8.hash(h); |
| 136 | sides.hash(h); | 215 | sides.hash(h); |
| ... | @@ -156,6 +235,20 @@ impl ShapeTree { | ... | @@ -156,6 +235,20 @@ impl ShapeTree { |
| 156 | height.to_bits().hash(h); | 235 | height.to_bits().hash(h); |
| 157 | corner_radius.to_bits().hash(h); | 236 | corner_radius.to_bits().hash(h); |
| 158 | } | 237 | } |
| 238 | ShapePrimKind::Polygon { points, closed } => { | ||
| 239 | 5u8.hash(h); | ||
| 240 | closed.hash(h); | ||
| 241 | points.len().hash(h); | ||
| 242 | for pt in points { | ||
| 243 | pt.x.to_bits().hash(h); | ||
| 244 | pt.y.to_bits().hash(h); | ||
| 245 | pt.lx.to_bits().hash(h); | ||
| 246 | pt.ly.to_bits().hash(h); | ||
| 247 | pt.rx.to_bits().hash(h); | ||
| 248 | pt.ry.to_bits().hash(h); | ||
| 249 | pt.linear.hash(h); | ||
| 250 | } | ||
| 251 | } | ||
| 159 | } | 252 | } |
| 160 | xform.hash_into(h); | 253 | xform.hash_into(h); |
| 161 | for c in color { | 254 | for c in color { |
| ... | @@ -187,757 +280,14 @@ impl ShapeTree { | ... | @@ -187,757 +280,14 @@ impl ShapeTree { |
| 187 | a.hash_into(h); | 280 | a.hash_into(h); |
| 188 | b.hash_into(h); | 281 | b.hash_into(h); |
| 189 | } | 282 | } |
| 190 | } | 283 | ShapeTree::Modify { op, post_xform, child } => { |
| 191 | } | 284 | 3u8.hash(h); |
| 192 | } | 285 | op.hash_into(h); |
| 193 | 286 | post_xform.hash_into(h); | |
| 194 | fn eval_first_num( | 287 | child.hash_into(h); |
| 195 | comp: &Comp, | ||
| 196 | node: &Node, | ||
| 197 | keys: &[&str], | ||
| 198 | time: f64, | ||
| 199 | default: f64, | ||
| 200 | expr: &ExprEngine, | ||
| 201 | ) -> f64 { | ||
| 202 | for &k in keys { | ||
| 203 | if node.inputs.contains_key(k) { | ||
| 204 | return comp.eval_number(node, k, time, default, expr); | ||
| 205 | } | ||
| 206 | } | ||
| 207 | default | ||
| 208 | } | ||
| 209 | |||
| 210 | /// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. | ||
| 211 | fn parse_bool_op(node: &Node) -> Option<ShapeBoolOp> { | ||
| 212 | if !node.inputs.contains_key("Operation") { | ||
| 213 | return Some(ShapeBoolOp::Intersect); | ||
| 214 | } | ||
| 215 | match node.static_str("Operation")? { | ||
| 216 | "Union" => Some(ShapeBoolOp::Union), | ||
| 217 | "Intersection" => Some(ShapeBoolOp::Intersect), | ||
| 218 | "Subtract" => Some(ShapeBoolOp::Subtract), | ||
| 219 | "Xor" => Some(ShapeBoolOp::Xor), | ||
| 220 | _ => None, | ||
| 221 | } | ||
| 222 | } | ||
| 223 | |||
| 224 | #[allow(clippy::too_many_arguments)] | ||
| 225 | fn collect_shape_tree( | ||
| 226 | comp: &Comp, | ||
| 227 | node_id: NodeId, | ||
| 228 | time: f64, | ||
| 229 | expr: &ExprEngine, | ||
| 230 | parent_xform: Affine2D, | ||
| 231 | outline_override: Option<OutlineStyle>, | ||
| 232 | depth: usize, | ||
| 233 | ) -> Option<ShapeTree> { | ||
| 234 | if depth > 32 { | ||
| 235 | return None; | ||
| 236 | } | ||
| 237 | let node = comp.node(node_id); | ||
| 238 | if node.bypassed { | ||
| 239 | return node | ||
| 240 | .connected_node("Input") | ||
| 241 | .or_else(|| node.connected_node("Input1")) | ||
| 242 | .and_then(|s| comp.find_node(s)) | ||
| 243 | .and_then(|id| { | ||
| 244 | collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) | ||
| 245 | }); | ||
| 246 | } | ||
| 247 | |||
| 248 | match node.kind.as_str() { | ||
| 249 | "sNGon" | "sRectangle" | "sEllipse" | "sStar" => { | ||
| 250 | let tx = eval_first_num(comp, node, &["Translate.X", "XOffset"], time, 0.0, expr) as f32; | ||
| 251 | let ty = eval_first_num(comp, node, &["Translate.Y", "YOffset"], time, 0.0, expr) as f32; | ||
| 252 | let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; | ||
| 253 | let local = Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)); | ||
| 254 | let xform = parent_xform.mul(local); | ||
| 255 | |||
| 256 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 257 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 258 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 259 | let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; | ||
| 260 | let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; | ||
| 261 | |||
| 262 | let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; | ||
| 263 | let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32; | ||
| 264 | let mut join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; | ||
| 265 | let mut cap_style = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; | ||
| 266 | let mut miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; | ||
| 267 | let mut write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; | ||
| 268 | let mut write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 269 | |||
| 270 | if let Some(ov) = outline_override { | ||
| 271 | solid = false; | ||
| 272 | border_width = ov.thickness; | ||
| 273 | join_style = ov.join; | ||
| 274 | cap_style = ov.cap; | ||
| 275 | miter_limit = ov.miter_limit; | ||
| 276 | write_pos = ov.write_pos; | ||
| 277 | write_len = ov.write_len; | ||
| 278 | } | ||
| 279 | |||
| 280 | let kind = match node.kind.as_str() { | ||
| 281 | "sNGon" => { | ||
| 282 | let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; | ||
| 283 | let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; | ||
| 284 | let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; | ||
| 285 | ShapePrimKind::NGon { sides, width, height } | ||
| 286 | } | ||
| 287 | "sRectangle" => { | ||
| 288 | let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; | ||
| 289 | let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; | ||
| 290 | let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; | ||
| 291 | ShapePrimKind::Rectangle { width, height, corner_radius } | ||
| 292 | } | ||
| 293 | "sStar" => { | ||
| 294 | let points = eval_first_num(comp, node, &["Points", "NumberOfPoints"], time, 6.0, expr) | ||
| 295 | .round() | ||
| 296 | .clamp(3.0, 256.0) as u32; | ||
| 297 | let depth = comp.eval_number(node, "Depth", time, 0.5, expr).clamp(0.0, 2.0) as f32; | ||
| 298 | let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; | ||
| 299 | let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; | ||
| 300 | let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; | ||
| 301 | ShapePrimKind::Star { points, depth, width, height, corner_radius } | ||
| 302 | } | ||
| 303 | _ => { | ||
| 304 | let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; | ||
| 305 | let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; | ||
| 306 | ShapePrimKind::Ellipse { width, height } | ||
| 307 | } | ||
| 308 | }; | ||
| 309 | |||
| 310 | Some(ShapeTree::Primitive { | ||
| 311 | kind, | ||
| 312 | xform, | ||
| 313 | color: [r * opacity, g * opacity, b * opacity, a * opacity], | ||
| 314 | solid, | ||
| 315 | border_width, | ||
| 316 | join_style, | ||
| 317 | cap_style, | ||
| 318 | miter_limit, | ||
| 319 | write_pos, | ||
| 320 | write_len, | ||
| 321 | }) | ||
| 322 | } | ||
| 323 | "sTransform" => { | ||
| 324 | let src_id = node | ||
| 325 | .connected_node("Input") | ||
| 326 | .or_else(|| node.connected_node("Input1")) | ||
| 327 | .and_then(|s| comp.find_node(s))?; | ||
| 328 | let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; | ||
| 329 | let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; | ||
| 330 | let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32; | ||
| 331 | let py = eval_first_num(comp, node, &["YPivot", "Pivot.Y"], time, 0.0, expr) as f32; | ||
| 332 | let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); | ||
| 333 | let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; | ||
| 334 | let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; | ||
| 335 | let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; | ||
| 336 | |||
| 337 | let local = Affine2D::translate(ox + px, oy + py) | ||
| 338 | .mul(Affine2D::rotate_deg(rot)) | ||
| 339 | .mul(Affine2D::scale(sx, sy)) | ||
| 340 | .mul(Affine2D::translate(-px, -py)); | ||
| 341 | let combined = parent_xform.mul(local); | ||
| 342 | collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1) | ||
| 343 | } | ||
| 344 | "sMerge" => { | ||
| 345 | let mut ports: Vec<(u32, &str)> = node | ||
| 346 | .inputs | ||
| 347 | .keys() | ||
| 348 | .filter_map(|k| { | ||
| 349 | let rest = k.strip_prefix("Input")?; | ||
| 350 | let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? }; | ||
| 351 | Some((idx, k.as_str())) | ||
| 352 | }) | ||
| 353 | .collect(); | ||
| 354 | ports.sort_by_key(|&(idx, _)| idx); | ||
| 355 | let mut children = Vec::new(); | ||
| 356 | for (_, port) in ports { | ||
| 357 | if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { | ||
| 358 | if let Some(tree) = collect_shape_tree( | ||
| 359 | comp, | ||
| 360 | src_id, | ||
| 361 | time, | ||
| 362 | expr, | ||
| 363 | parent_xform, | ||
| 364 | outline_override, | ||
| 365 | depth + 1, | ||
| 366 | ) { | ||
| 367 | children.push(tree); | ||
| 368 | } | ||
| 369 | } | ||
| 370 | } | ||
| 371 | if children.is_empty() { | ||
| 372 | None | ||
| 373 | } else { | ||
| 374 | Some(ShapeTree::Group(children)) | ||
| 375 | } | ||
| 376 | } | ||
| 377 | "sGrid" => { | ||
| 378 | let src_id = node | ||
| 379 | .connected_node("Input") | ||
| 380 | .or_else(|| node.connected_node("Input1")) | ||
| 381 | .and_then(|s| comp.find_node(s))?; | ||
| 382 | let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; | ||
| 383 | let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; | ||
| 384 | let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32; | ||
| 385 | let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32; | ||
| 386 | let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y)); | ||
| 387 | for iy in 0..cells_y { | ||
| 388 | let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off; | ||
| 389 | for ix in 0..cells_x { | ||
| 390 | let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off; | ||
| 391 | let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty)); | ||
| 392 | if let Some(tree) = collect_shape_tree( | ||
| 393 | comp, | ||
| 394 | src_id, | ||
| 395 | time, | ||
| 396 | expr, | ||
| 397 | cell_xf, | ||
| 398 | outline_override, | ||
| 399 | depth + 1, | ||
| 400 | ) { | ||
| 401 | children.push(tree); | ||
| 402 | } | ||
| 403 | } | ||
| 404 | } | ||
| 405 | if children.is_empty() { | ||
| 406 | None | ||
| 407 | } else { | ||
| 408 | Some(ShapeTree::Group(children)) | ||
| 409 | } | ||
| 410 | } | ||
| 411 | "sOutline" => { | ||
| 412 | let src_id = node | ||
| 413 | .connected_node("Input") | ||
| 414 | .or_else(|| node.connected_node("Input1")) | ||
| 415 | .and_then(|s| comp.find_node(s))?; | ||
| 416 | let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr) as f32; | ||
| 417 | if thickness <= 0.0 { | ||
| 418 | return None; | ||
| 419 | } | ||
| 420 | let join = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; | ||
| 421 | let cap = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; | ||
| 422 | let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; | ||
| 423 | let write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; | ||
| 424 | let write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 425 | let style = OutlineStyle { thickness, join, cap, miter_limit, write_pos, write_len }; | ||
| 426 | collect_shape_tree(comp, src_id, time, expr, parent_xform, Some(style), depth + 1) | ||
| 427 | } | ||
| 428 | "sBoolean" => { | ||
| 429 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 430 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 431 | let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 432 | let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; | ||
| 433 | let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; | ||
| 434 | let keep_style = node.static_str("StyleMode").unwrap_or("Replace") == "Keep"; | ||
| 435 | let color = [r * opacity, g * opacity, b_col * opacity, a_col * opacity]; | ||
| 436 | let child = |port: &str| { | ||
| 437 | node.connected_node(port) | ||
| 438 | .and_then(|s| comp.find_node(s)) | ||
| 439 | .and_then(|id| { | ||
| 440 | collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) | ||
| 441 | }) | ||
| 442 | }; | ||
| 443 | let a = child("Input1").or_else(|| child("Input"))?; | ||
| 444 | // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty. | ||
| 445 | let (op, b) = match (parse_bool_op(node), child("Input2")) { | ||
| 446 | (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())), | ||
| 447 | (Some(op), Some(b)) => (op, b), | ||
| 448 | (None, Some(_)) => return None, | ||
| 449 | }; | ||
| 450 | Some(ShapeTree::Boolean { | ||
| 451 | op, | ||
| 452 | color, | ||
| 453 | opacity, | ||
| 454 | keep_style, | ||
| 455 | a: Box::new(a), | ||
| 456 | b: Box::new(b), | ||
| 457 | }) | ||
| 458 | } | ||
| 459 | "PipeRouter" | "Fuse.Wireless" => { | ||
| 460 | let src_id = node | ||
| 461 | .connected_node("Input") | ||
| 462 | .or_else(|| node.connected_node("Input1")) | ||
| 463 | .and_then(|s| comp.find_node(s))?; | ||
| 464 | collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1) | ||
| 465 | } | ||
| 466 | "MacroOperator" | "GroupOperator" => { | ||
| 467 | let out_id = node.macro_output?; | ||
| 468 | collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1) | ||
| 469 | } | ||
| 470 | _ => None, | ||
| 471 | } | ||
| 472 | } | ||
| 473 | |||
| 474 | fn build_primitive_commands(kind: ShapePrimKind, xform: Affine2D, dims: [u32; 2]) -> Vec<zeno::Command> { | ||
| 475 | let wf = dims[0] as f32; | ||
| 476 | let hf = dims[1] as f32; | ||
| 477 | let to_px = |local: [f32; 2]| -> zeno::Vector { | ||
| 478 | let wpt = xform.apply(local); | ||
| 479 | let px = (wpt[0] + 0.5) * wf; | ||
| 480 | let py = 0.5 * hf - wpt[1] * wf; | ||
| 481 | zeno::Vector::new(px, py) | ||
| 482 | }; | ||
| 483 | |||
| 484 | const KAPPA: f32 = 0.55228475; | ||
| 485 | let mut cmds = Vec::new(); | ||
| 486 | match kind { | ||
| 487 | ShapePrimKind::NGon { sides, width, height } => { | ||
| 488 | let n = sides.max(3); | ||
| 489 | let rx = width * 0.5; | ||
| 490 | let ry = height * 0.5; | ||
| 491 | if rx <= 1e-6 || ry <= 1e-6 { | ||
| 492 | return cmds; | ||
| 493 | } | ||
| 494 | for k in 0..n { | ||
| 495 | let theta = (k as f32) * std::f32::consts::TAU / (n as f32); | ||
| 496 | let v = to_px([rx * theta.cos(), ry * theta.sin()]); | ||
| 497 | if k == 0 { | ||
| 498 | cmds.push(zeno::Command::MoveTo(v)); | ||
| 499 | } else { | ||
| 500 | cmds.push(zeno::Command::LineTo(v)); | ||
| 501 | } | ||
| 502 | } | ||
| 503 | cmds.push(zeno::Command::Close); | ||
| 504 | } | ||
| 505 | ShapePrimKind::Rectangle { width, height, corner_radius } => { | ||
| 506 | let hx = width * 0.5; | ||
| 507 | let hy = height * 0.5; | ||
| 508 | if hx <= 1e-6 || hy <= 1e-6 { | ||
| 509 | return cmds; | ||
| 510 | } | ||
| 511 | let r = corner_radius.min(hx.min(hy)); | ||
| 512 | if r <= 1e-5 { | ||
| 513 | // Start at mid-right (+hx, 0) counter-clockwise so WritePosition matches sNGon/sEllipse. | ||
| 514 | cmds.push(zeno::Command::MoveTo(to_px([hx, 0.0]))); | ||
| 515 | cmds.push(zeno::Command::LineTo(to_px([hx, hy]))); | ||
| 516 | cmds.push(zeno::Command::LineTo(to_px([-hx, hy]))); | ||
| 517 | cmds.push(zeno::Command::LineTo(to_px([-hx, -hy]))); | ||
| 518 | cmds.push(zeno::Command::LineTo(to_px([hx, -hy]))); | ||
| 519 | cmds.push(zeno::Command::Close); | ||
| 520 | } else { | ||
| 521 | let k = r * KAPPA; | ||
| 522 | cmds.push(zeno::Command::MoveTo(to_px([hx, 0.0]))); | ||
| 523 | cmds.push(zeno::Command::LineTo(to_px([hx, hy - r]))); | ||
| 524 | cmds.push(zeno::Command::CurveTo( | ||
| 525 | to_px([hx, hy - r + k]), | ||
| 526 | to_px([hx - r + k, hy]), | ||
| 527 | to_px([hx - r, hy]), | ||
| 528 | )); | ||
| 529 | cmds.push(zeno::Command::LineTo(to_px([-hx + r, hy]))); | ||
| 530 | cmds.push(zeno::Command::CurveTo( | ||
| 531 | to_px([-hx + r - k, hy]), | ||
| 532 | to_px([-hx, hy - r + k]), | ||
| 533 | to_px([-hx, hy - r]), | ||
| 534 | )); | ||
| 535 | cmds.push(zeno::Command::LineTo(to_px([-hx, -hy + r]))); | ||
| 536 | cmds.push(zeno::Command::CurveTo( | ||
| 537 | to_px([-hx, -hy + r - k]), | ||
| 538 | to_px([-hx + r - k, -hy]), | ||
| 539 | to_px([-hx + r, -hy]), | ||
| 540 | )); | ||
| 541 | cmds.push(zeno::Command::LineTo(to_px([hx - r, -hy]))); | ||
| 542 | cmds.push(zeno::Command::CurveTo( | ||
| 543 | to_px([hx - r + k, -hy]), | ||
| 544 | to_px([hx, -hy + r - k]), | ||
| 545 | to_px([hx, -hy + r]), | ||
| 546 | )); | ||
| 547 | cmds.push(zeno::Command::Close); | ||
| 548 | } | ||
| 549 | } | ||
| 550 | ShapePrimKind::Ellipse { width, height } => { | ||
| 551 | let rx = width * 0.5; | ||
| 552 | let ry = height * 0.5; | ||
| 553 | if rx <= 1e-6 || ry <= 1e-6 { | ||
| 554 | return cmds; | ||
| 555 | } | ||
| 556 | let kx = rx * KAPPA; | ||
| 557 | let ky = ry * KAPPA; | ||
| 558 | cmds.push(zeno::Command::MoveTo(to_px([rx, 0.0]))); | ||
| 559 | cmds.push(zeno::Command::CurveTo( | ||
| 560 | to_px([rx, ky]), | ||
| 561 | to_px([kx, ry]), | ||
| 562 | to_px([0.0, ry]), | ||
| 563 | )); | ||
| 564 | cmds.push(zeno::Command::CurveTo( | ||
| 565 | to_px([-kx, ry]), | ||
| 566 | to_px([-rx, ky]), | ||
| 567 | to_px([-rx, 0.0]), | ||
| 568 | )); | ||
| 569 | cmds.push(zeno::Command::CurveTo( | ||
| 570 | to_px([-rx, -ky]), | ||
| 571 | to_px([-kx, -ry]), | ||
| 572 | to_px([0.0, -ry]), | ||
| 573 | )); | ||
| 574 | cmds.push(zeno::Command::CurveTo( | ||
| 575 | to_px([kx, -ry]), | ||
| 576 | to_px([rx, -ky]), | ||
| 577 | to_px([rx, 0.0]), | ||
| 578 | )); | ||
| 579 | cmds.push(zeno::Command::Close); | ||
| 580 | } | ||
| 581 | ShapePrimKind::Star { points, depth, width, height, corner_radius } => { | ||
| 582 | let n = points.max(3) as usize; | ||
| 583 | let rx = width * 0.5; | ||
| 584 | let ry = height * 0.5; | ||
| 585 | if rx <= 1e-6 || ry <= 1e-6 { | ||
| 586 | return cmds; | ||
| 587 | } | ||
| 588 | let total = n * 2; | ||
| 589 | let mut verts = Vec::with_capacity(total); | ||
| 590 | for k in 0..total { | ||
| 591 | let theta = (k as f32) * std::f32::consts::PI / (n as f32); | ||
| 592 | let s = if k % 2 == 0 { 1.0 } else { depth }; | ||
| 593 | verts.push([rx * s * theta.cos(), ry * s * theta.sin()]); | ||
| 594 | } | ||
| 595 | if corner_radius <= 1e-5 { | ||
| 596 | for (k, &pt) in verts.iter().enumerate() { | ||
| 597 | let v = to_px(pt); | ||
| 598 | if k == 0 { | ||
| 599 | cmds.push(zeno::Command::MoveTo(v)); | ||
| 600 | } else { | ||
| 601 | cmds.push(zeno::Command::LineTo(v)); | ||
| 602 | } | ||
| 603 | } | ||
| 604 | cmds.push(zeno::Command::Close); | ||
| 605 | } else { | ||
| 606 | for k in 0..total { | ||
| 607 | let prev = verts[(k + total - 1) % total]; | ||
| 608 | let curr = verts[k]; | ||
| 609 | let next = verts[(k + 1) % total]; | ||
| 610 | let d_prev = [prev[0] - curr[0], prev[1] - curr[1]]; | ||
| 611 | let d_next = [next[0] - curr[0], next[1] - curr[1]]; | ||
| 612 | let l_prev = d_prev[0].hypot(d_prev[1]); | ||
| 613 | let l_next = d_next[0].hypot(d_next[1]); | ||
| 614 | let r = corner_radius.min(0.45 * l_prev.min(l_next)); | ||
| 615 | if r <= 1e-6 { | ||
| 616 | let v = to_px(curr); | ||
| 617 | if k == 0 { | ||
| 618 | cmds.push(zeno::Command::MoveTo(v)); | ||
| 619 | } else { | ||
| 620 | cmds.push(zeno::Command::LineTo(v)); | ||
| 621 | } | ||
| 622 | } else { | ||
| 623 | let p_in = [curr[0] + d_prev[0] * (r / l_prev), curr[1] + d_prev[1] * (r / l_prev)]; | ||
| 624 | let p_out = [curr[0] + d_next[0] * (r / l_next), curr[1] + d_next[1] * (r / l_next)]; | ||
| 625 | if k == 0 { | ||
| 626 | cmds.push(zeno::Command::MoveTo(to_px(p_in))); | ||
| 627 | } else { | ||
| 628 | cmds.push(zeno::Command::LineTo(to_px(p_in))); | ||
| 629 | } | ||
| 630 | cmds.push(zeno::Command::QuadTo(to_px(curr), to_px(p_out))); | ||
| 631 | } | ||
| 632 | } | ||
| 633 | cmds.push(zeno::Command::Close); | ||
| 634 | } | ||
| 635 | } | ||
| 636 | } | ||
| 637 | cmds | ||
| 638 | } | ||
| 639 | |||
| 640 | fn flatten_commands_to_poly(cmds: &[zeno::Command]) -> Vec<[f32; 2]> { | ||
| 641 | use zeno::Command::{CurveTo, LineTo, MoveTo, QuadTo}; | ||
| 642 | let mut poly: Vec<[f32; 2]> = Vec::new(); | ||
| 643 | for c in cmds { | ||
| 644 | match c { | ||
| 645 | MoveTo(p) | LineTo(p) => poly.push([p.x, p.y]), | ||
| 646 | QuadTo(a, p) => { | ||
| 647 | let p0 = poly.last().copied().unwrap_or([a.x, a.y]); | ||
| 648 | let len = (a.x - p0[0]).hypot(a.y - p0[1]) + (p.x - a.x).hypot(p.y - a.y); | ||
| 649 | let n = ((len.sqrt() * 1.5).ceil() as usize).clamp(8, 1024); | ||
| 650 | for i in 1..=n { | ||
| 651 | let t = i as f32 / n as f32; | ||
| 652 | let u = 1.0 - t; | ||
| 653 | poly.push([ | ||
| 654 | u * u * p0[0] + 2.0 * u * t * a.x + t * t * p.x, | ||
| 655 | u * u * p0[1] + 2.0 * u * t * a.y + t * t * p.y, | ||
| 656 | ]); | ||
| 657 | } | ||
| 658 | } | ||
| 659 | CurveTo(a, b, p) => { | ||
| 660 | let p0 = poly.last().copied().unwrap_or([a.x, a.y]); | ||
| 661 | let len = (a.x - p0[0]).hypot(a.y - p0[1]) + (b.x - a.x).hypot(b.y - a.y) + (p.x - b.x).hypot(p.y - b.y); | ||
| 662 | let n = ((len.sqrt() * 1.5).ceil() as usize).clamp(16, 2048); | ||
| 663 | for i in 1..=n { | ||
| 664 | let t = i as f32 / n as f32; | ||
| 665 | let u = 1.0 - t; | ||
| 666 | let (c0, c1, c2, c3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); | ||
| 667 | poly.push([ | ||
| 668 | c0 * p0[0] + c1 * a.x + c2 * b.x + c3 * p.x, | ||
| 669 | c0 * p0[1] + c1 * a.y + c2 * b.y + c3 * p.y, | ||
| 670 | ]); | ||
| 671 | } | ||
| 672 | } | ||
| 673 | _ => {} | ||
| 674 | } | ||
| 675 | } | ||
| 676 | poly | ||
| 677 | } | ||
| 678 | |||
| 679 | /// Trims a closed command loop to arc-length fraction `[write_pos, write_pos + write_len]`. | ||
| 680 | fn trim_path_commands(cmds: Vec<zeno::Command>, write_pos: f32, write_len: f32) -> Vec<zeno::Command> { | ||
| 681 | if write_len <= 1e-5 { | ||
| 682 | return Vec::new(); | ||
| 683 | } | ||
| 684 | if write_len >= 1.0 - 1e-5 { | ||
| 685 | return cmds; | ||
| 686 | } | ||
| 687 | let poly = flatten_commands_to_poly(&cmds); | ||
| 688 | let n = poly.len(); | ||
| 689 | if n < 2 { | ||
| 690 | return Vec::new(); | ||
| 691 | } | ||
| 692 | let mut segs = Vec::with_capacity(n); | ||
| 693 | let mut total = 0.0_f32; | ||
| 694 | for i in 0..n { | ||
| 695 | let a = poly[i]; | ||
| 696 | let b = poly[(i + 1) % n]; | ||
| 697 | let len = (b[0] - a[0]).hypot(b[1] - a[1]); | ||
| 698 | segs.push((a, b, len)); | ||
| 699 | total += len; | ||
| 700 | } | ||
| 701 | if total <= 1e-5 { | ||
| 702 | return Vec::new(); | ||
| 703 | } | ||
| 704 | let s0 = write_pos.rem_euclid(1.0) * total; | ||
| 705 | let target = write_len * total; | ||
| 706 | let mut out = Vec::new(); | ||
| 707 | let mut acc = 0.0_f32; | ||
| 708 | let mut started = false; | ||
| 709 | let mut idx = 0usize; | ||
| 710 | while acc < s0 + target - 1e-5 && idx < n * 2 + 2 { | ||
| 711 | let (a, b, len) = segs[idx % n]; | ||
| 712 | idx += 1; | ||
| 713 | if len <= 1e-6 { | ||
| 714 | continue; | ||
| 715 | } | ||
| 716 | let seg_start = acc; | ||
| 717 | let seg_end = acc + len; | ||
| 718 | acc = seg_end; | ||
| 719 | if seg_end <= s0 { | ||
| 720 | continue; | ||
| 721 | } | ||
| 722 | let t0 = if !started { ((s0 - seg_start) / len).clamp(0.0, 1.0) } else { 0.0 }; | ||
| 723 | let t1 = ((s0 + target - seg_start) / len).clamp(0.0, 1.0); | ||
| 724 | if !started { | ||
| 725 | let p = [a[0] + t0 * (b[0] - a[0]), a[1] + t0 * (b[1] - a[1])]; | ||
| 726 | out.push(zeno::Command::MoveTo(zeno::Vector::new(p[0], p[1]))); | ||
| 727 | started = true; | ||
| 728 | } | ||
| 729 | let q = [a[0] + t1 * (b[0] - a[0]), a[1] + t1 * (b[1] - a[1])]; | ||
| 730 | out.push(zeno::Command::LineTo(zeno::Vector::new(q[0], q[1]))); | ||
| 731 | } | ||
| 732 | out | ||
| 733 | } | ||
| 734 | |||
| 735 | /// Flattens `cmds` and clips the polygon to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long. | ||
| 736 | fn clip_to_viewport(cmds: Vec<zeno::Command>, dims: [u32; 2], margin: f32) -> Vec<zeno::Command> { | ||
| 737 | use zeno::Command::{Close, CurveTo, LineTo, MoveTo}; | ||
| 738 | let [w, h] = [dims[0] as f32, dims[1] as f32]; | ||
| 739 | let limit = 4.0 * w.max(h); | ||
| 740 | let far = |v: &zeno::Vector| v.x.abs() > limit || v.y.abs() > limit; | ||
| 741 | let huge = cmds.iter().any(|c| match c { | ||
| 742 | MoveTo(p) | LineTo(p) => far(p), | ||
| 743 | zeno::Command::QuadTo(a, p) => far(a) || far(p), | ||
| 744 | CurveTo(a, b, p) => far(a) || far(b) || far(p), | ||
| 745 | _ => false, | ||
| 746 | }); | ||
| 747 | if !huge { | ||
| 748 | return cmds; | ||
| 749 | } | ||
| 750 | let mut poly = flatten_commands_to_poly(&cmds); | ||
| 751 | let edges: [(usize, f32, f32); 4] = [(0, 1.0, -margin), (0, -1.0, w + margin), (1, 1.0, -margin), (1, -1.0, h + margin)]; | ||
| 752 | for (axis, sign, bound) in edges { | ||
| 753 | let inside = |p: [f32; 2]| sign * (p[axis] - bound) >= 0.0; | ||
| 754 | let input = std::mem::take(&mut poly); | ||
| 755 | for (i, &cur) in input.iter().enumerate() { | ||
| 756 | let prev = input[(i + input.len() - 1) % input.len()]; | ||
| 757 | if inside(cur) != inside(prev) { | ||
| 758 | let t = (bound - prev[axis]) / (cur[axis] - prev[axis]); | ||
| 759 | poly.push([prev[0] + t * (cur[0] - prev[0]), prev[1] + t * (cur[1] - prev[1])]); | ||
| 760 | } | ||
| 761 | if inside(cur) { | ||
| 762 | poly.push(cur); | ||
| 763 | } | ||
| 764 | } | ||
| 765 | } | ||
| 766 | let mut out = Vec::with_capacity(poly.len() + 1); | ||
| 767 | for (i, p) in poly.iter().enumerate() { | ||
| 768 | let v = zeno::Vector::new(p[0], p[1]); | ||
| 769 | out.push(if i == 0 { MoveTo(v) } else { LineTo(v) }); | ||
| 770 | } | ||
| 771 | if !out.is_empty() { | ||
| 772 | out.push(Close); | ||
| 773 | } | ||
| 774 | out | ||
| 775 | } | ||
| 776 | |||
| 777 | fn composite_over(dst: &mut [f32], src: &[f32]) { | ||
| 778 | for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) { | ||
| 779 | let sa = s[3].clamp(0.0, 1.0); | ||
| 780 | if sa <= 1e-6 { | ||
| 781 | continue; | ||
| 782 | } | ||
| 783 | let inv = 1.0 - sa; | ||
| 784 | d[0] = s[0] + d[0] * inv; | ||
| 785 | d[1] = s[1] + d[1] * inv; | ||
| 786 | d[2] = s[2] + d[2] * inv; | ||
| 787 | d[3] = sa + d[3] * inv; | ||
| 788 | } | ||
| 789 | } | ||
| 790 | |||
| 791 | fn rasterize_shape_tree_f32( | ||
| 792 | tree: &ShapeTree, | ||
| 793 | dims: [u32; 2], | ||
| 794 | dst: &mut [f32], | ||
| 795 | cov_buf: &mut [u8], | ||
| 796 | scratch: &mut zeno::Scratch, | ||
| 797 | ) { | ||
| 798 | let [w, h] = dims; | ||
| 799 | match tree { | ||
| 800 | ShapeTree::Primitive { | ||
| 801 | kind, | ||
| 802 | xform, | ||
| 803 | color, | ||
| 804 | solid, | ||
| 805 | border_width, | ||
| 806 | join_style, | ||
| 807 | cap_style, | ||
| 808 | miter_limit, | ||
| 809 | write_pos, | ||
| 810 | write_len, | ||
| 811 | } => { | ||
| 812 | let cmds = build_primitive_commands(*kind, *xform, dims); | ||
| 813 | let finite = |v: &zeno::Vector| v.x.is_finite() && v.y.is_finite(); | ||
| 814 | let degenerate = cmds.iter().any(|c| match c { | ||
| 815 | zeno::Command::MoveTo(p) | zeno::Command::LineTo(p) => !finite(p), | ||
| 816 | zeno::Command::QuadTo(a, p) => !(finite(a) && finite(p)), | ||
| 817 | zeno::Command::CurveTo(a, b, p) => !(finite(a) && finite(b) && finite(p)), | ||
| 818 | _ => false, | ||
| 819 | }); | ||
| 820 | if cmds.is_empty() || degenerate { | ||
| 821 | return; | ||
| 822 | } | ||
| 823 | cov_buf.fill(0); | ||
| 824 | let reach = 4.0 * w.max(h) as f32; | ||
| 825 | let stroke_px = (*border_width * xform.avg_scale() * (w as f32)).clamp(0.5, reach); | ||
| 826 | let cmds = clip_to_viewport(cmds, dims, if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }); | ||
| 827 | let cmds = if !*solid && (write_pos.abs() > 1e-5 || (*write_len - 1.0).abs() > 1e-5) { | ||
| 828 | trim_path_commands(cmds, *write_pos, *write_len) | ||
| 829 | } else { | ||
| 830 | cmds | ||
| 831 | }; | ||
| 832 | if cmds.is_empty() { | ||
| 833 | return; | ||
| 834 | } | ||
| 835 | let style = if *solid { | ||
| 836 | zeno::Style::Fill(zeno::Fill::NonZero) | ||
| 837 | } else { | ||
| 838 | let join = match *join_style { | ||
| 839 | 0 => zeno::Join::Bevel, | ||
| 840 | 1 => zeno::Join::Round, | ||
| 841 | _ => zeno::Join::Miter, | ||
| 842 | }; | ||
| 843 | let cap = match *cap_style { | ||
| 844 | 1 => zeno::Cap::Round, | ||
| 845 | 2 => zeno::Cap::Square, | ||
| 846 | _ => zeno::Cap::Butt, | ||
| 847 | }; | ||
| 848 | let mut st = zeno::Stroke::new(stroke_px); | ||
| 849 | st.join(join).cap(cap).miter_limit(*miter_limit); | ||
| 850 | zeno::Style::Stroke(st) | ||
| 851 | }; | ||
| 852 | let _ = zeno::Mask::with_scratch(&cmds, scratch) | ||
| 853 | .style(style) | ||
| 854 | .size(w, h) | ||
| 855 | .origin(zeno::Origin::TopLeft) | ||
| 856 | .render_into(cov_buf, None); | ||
| 857 | |||
| 858 | let ca = color[3].clamp(0.0, 1.0); | ||
| 859 | if ca <= 1e-6 { | ||
| 860 | return; | ||
| 861 | } | ||
| 862 | // Fusion keeps the colour unpremultiplied: Alpha scales coverage into alpha only, not RGB. | ||
| 863 | for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { | ||
| 864 | if cov == 0 { | ||
| 865 | continue; | ||
| 866 | } | ||
| 867 | let c = cov as f32 / 255.0; | ||
| 868 | let inv = 1.0 - c * ca; | ||
| 869 | px[0] = color[0] * c + px[0] * inv; | ||
| 870 | px[1] = color[1] * c + px[1] * inv; | ||
| 871 | px[2] = color[2] * c + px[2] * inv; | ||
| 872 | px[3] = c * ca + px[3] * inv; | ||
| 873 | } | ||
| 874 | } | ||
| 875 | ShapeTree::Group(children) => { | ||
| 876 | for ch in children { | ||
| 877 | rasterize_shape_tree_f32(ch, dims, dst, cov_buf, scratch); | ||
| 878 | } | 288 | } |
| 879 | } | 289 | } |
| 880 | ShapeTree::Boolean { op, color, opacity: _, keep_style, a, b } => { | ||
| 881 | let len = dst.len(); | ||
| 882 | let mut buf_a = vec![0.0f32; len]; | ||
| 883 | let mut buf_b = vec![0.0f32; len]; | ||
| 884 | rasterize_shape_tree_f32(a, dims, &mut buf_a, cov_buf, scratch); | ||
| 885 | rasterize_shape_tree_f32(b, dims, &mut buf_b, cov_buf, scratch); | ||
| 886 | let mut comb = vec![0.0f32; len]; | ||
| 887 | let ca = color[3].clamp(0.0, 1.0); | ||
| 888 | for ((ca_p, cb_p), out_p) in buf_a | ||
| 889 | .chunks_exact(4) | ||
| 890 | .zip(buf_b.chunks_exact(4)) | ||
| 891 | .zip(comb.chunks_exact_mut(4)) | ||
| 892 | { | ||
| 893 | let aa = ca_p[3].clamp(0.0, 1.0); | ||
| 894 | let ba = cb_p[3].clamp(0.0, 1.0); | ||
| 895 | let oa = match op { | ||
| 896 | ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0), | ||
| 897 | ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0), | ||
| 898 | ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0), | ||
| 899 | ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0), | ||
| 900 | }; | ||
| 901 | if *keep_style { | ||
| 902 | let s = if aa > 1e-6 { oa / aa } else { 0.0 }; | ||
| 903 | out_p[0] = ca_p[0] * s; | ||
| 904 | out_p[1] = ca_p[1] * s; | ||
| 905 | out_p[2] = ca_p[2] * s; | ||
| 906 | out_p[3] = oa; | ||
| 907 | } else { | ||
| 908 | // Opacity scales RGBA (baked into color); Alpha scales alpha only (not RGB). | ||
| 909 | out_p[0] = color[0] * oa; | ||
| 910 | out_p[1] = color[1] * oa; | ||
| 911 | out_p[2] = color[2] * oa; | ||
| 912 | out_p[3] = oa * ca; | ||
| 913 | } | ||
| 914 | } | ||
| 915 | composite_over(dst, &comb); | ||
| 916 | } | ||
| 917 | } | ||
| 918 | } | ||
| 919 | |||
| 920 | fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec<u8> { | ||
| 921 | let px_count = (dims[0] as usize) * (dims[1] as usize); | ||
| 922 | let mut out = vec![0u8; px_count * 4]; | ||
| 923 | let Some(tree) = tree else { | ||
| 924 | return out; | ||
| 925 | }; | ||
| 926 | let b = blend.clamp(0.0, 1.0); | ||
| 927 | if b <= 1e-6 { | ||
| 928 | return out; | ||
| 929 | } | 290 | } |
| 930 | let mut accum = vec![0.0f32; px_count * 4]; | ||
| 931 | let mut cov_buf = vec![0u8; px_count]; | ||
| 932 | let mut scratch = zeno::Scratch::new(); | ||
| 933 | rasterize_shape_tree_f32(tree, dims, &mut accum, &mut cov_buf, &mut scratch); | ||
| 934 | for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) { | ||
| 935 | dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 936 | dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 937 | dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 938 | dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 939 | } | ||
| 940 | out | ||
| 941 | } | 291 | } |
| 942 | 292 | ||
| 943 | impl Engine { | 293 | impl Engine { |
| ... | @@ -960,11 +310,21 @@ impl Engine { | ... | @@ -960,11 +310,21 @@ impl Engine { |
| 960 | // Fusion sRender ignores Blend (always renders at full 1.0 opacity). | 310 | // Fusion sRender ignores Blend (always renders at full 1.0 opacity). |
| 961 | let blend = 1.0_f32; | 311 | let blend = 1.0_f32; |
| 962 | 312 | ||
| 313 | let mut prim_budget = MAX_SHAPE_PRIMITIVES; | ||
| 963 | let shape_tree = node | 314 | let shape_tree = node |
| 964 | .connected_node("Input") | 315 | .connected_node("Input") |
| 965 | .and_then(|s| comp.find_node(s)) | 316 | .and_then(|s| comp.find_node(s)) |
| 966 | .and_then(|src_id| { | 317 | .and_then(|src_id| { |
| 967 | collect_shape_tree(comp, src_id, time, &self.expr, Affine2D::identity(), None, 0) | 318 | collect_shape_tree( |
| 319 | comp, | ||
| 320 | src_id, | ||
| 321 | time, | ||
| 322 | &self.expr, | ||
| 323 | Affine2D::identity(), | ||
| 324 | None, | ||
| 325 | 0, | ||
| 326 | &mut prim_budget, | ||
| 327 | ) | ||
| 968 | }); | 328 | }); |
| 969 | 329 | ||
| 970 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); | 330 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); |
| ... | @@ -1050,378 +410,3 @@ impl Engine { | ... | @@ -1050,378 +410,3 @@ impl Engine { |
| 1050 | out | 410 | out |
| 1051 | } | 411 | } |
| 1052 | } | 412 | } |
| 1053 | |||
| 1054 | #[cfg(test)] | ||
| 1055 | mod tests { | ||
| 1056 | use super::*; | ||
| 1057 | use crate::Engine; | ||
| 1058 | |||
| 1059 | #[test] | ||
| 1060 | fn test_s_render_ngon_transform_merge_and_boolean() { | ||
| 1061 | let src = r#"Composition { | ||
| 1062 | CurrentTime = 0, | ||
| 1063 | RenderRange = { 0, 1 }, | ||
| 1064 | GlobalRange = { 0, 1 }, | ||
| 1065 | Tools = ordered() { | ||
| 1066 | NGon1 = sNGon { | ||
| 1067 | Inputs = { | ||
| 1068 | Sides = Input { Value = 6, }, | ||
| 1069 | Width = Input { Value = 0.4, }, | ||
| 1070 | Red = Input { Value = 1.0, }, | ||
| 1071 | Green = Input { Value = 0.0, }, | ||
| 1072 | Blue = Input { Value = 0.0, }, | ||
| 1073 | }, | ||
| 1074 | }, | ||
| 1075 | XF1 = sTransform { | ||
| 1076 | Inputs = { | ||
| 1077 | XOffset = Input { Value = -0.2, }, | ||
| 1078 | YOffset = Input { Value = 0.0, }, | ||
| 1079 | XSize = Input { Value = 1.0, }, | ||
| 1080 | YSize = Input { Value = 1.0, }, | ||
| 1081 | ZRotation = Input { Value = 15.0, }, | ||
| 1082 | Input = Input { SourceOp = "NGon1", Source = "Output", }, | ||
| 1083 | }, | ||
| 1084 | }, | ||
| 1085 | Rect1 = sRectangle { | ||
| 1086 | Inputs = { | ||
| 1087 | Width = Input { Value = 0.3, }, | ||
| 1088 | Height = Input { Value = 0.3, }, | ||
| 1089 | CornerRadius = Input { Value = 0.05, }, | ||
| 1090 | Translate = Input { Value = { 0.0, 0.0 }, }, | ||
| 1091 | ["Translate.X"] = Input { Value = 0.2, }, | ||
| 1092 | Red = Input { Value = 0.0, }, | ||
| 1093 | Green = Input { Value = 0.0, }, | ||
| 1094 | Blue = Input { Value = 1.0, }, | ||
| 1095 | }, | ||
| 1096 | }, | ||
| 1097 | Merge1 = sMerge { | ||
| 1098 | Inputs = { | ||
| 1099 | Input1 = Input { SourceOp = "XF1", Source = "Output", }, | ||
| 1100 | Input2 = Input { SourceOp = "Rect1", Source = "Output", }, | ||
| 1101 | }, | ||
| 1102 | }, | ||
| 1103 | Render1 = sRender { | ||
| 1104 | Inputs = { | ||
| 1105 | Width = Input { Value = 128, }, | ||
| 1106 | Height = Input { Value = 128, }, | ||
| 1107 | Input = Input { SourceOp = "Merge1", Source = "Output", }, | ||
| 1108 | }, | ||
| 1109 | }, | ||
| 1110 | }, | ||
| 1111 | }"#; | ||
| 1112 | let comp = Comp::from_fusion_str(src).expect("parse sRender comp"); | ||
| 1113 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 1114 | return; | ||
| 1115 | }; | ||
| 1116 | let render_id = comp.find_node("Render1").unwrap(); | ||
| 1117 | let (tex, stats) = eng.evaluate(&comp, render_id, 0.0); | ||
| 1118 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | ||
| 1119 | assert_eq!(tex.size, [128, 128]); | ||
| 1120 | let px = eng.readback_rgba(&tex).expect("readback sRender"); | ||
| 1121 | |||
| 1122 | // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red | ||
| 1123 | let left = (64 * 128 + 38) * 4; | ||
| 1124 | assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]); | ||
| 1125 | // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue | ||
| 1126 | let right = (64 * 128 + 90) * 4; | ||
| 1127 | assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]); | ||
| 1128 | // Top-left corner (0, 0) should be transparent | ||
| 1129 | assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent"); | ||
| 1130 | } | ||
| 1131 | |||
| 1132 | |||
| 1133 | #[test] | ||
| 1134 | fn test_s_boolean_uses_own_color_and_subtract_xor() { | ||
| 1135 | let src = r#"Composition { | ||
| 1136 | CurrentTime = 0, | ||
| 1137 | RenderRange = { 0, 1 }, | ||
| 1138 | GlobalRange = { 0, 1 }, | ||
| 1139 | Tools = ordered() { | ||
| 1140 | NGon1 = sNGon { | ||
| 1141 | Inputs = { | ||
| 1142 | Sides = Input { Value = 5, }, | ||
| 1143 | Width = Input { Value = 0.5, }, | ||
| 1144 | Height = Input { Value = 0.5, }, | ||
| 1145 | Red = Input { Value = 1.0, }, | ||
| 1146 | Green = Input { Value = 0.0, }, | ||
| 1147 | Blue = Input { Value = 0.0, }, | ||
| 1148 | }, | ||
| 1149 | }, | ||
| 1150 | Rect1 = sRectangle { | ||
| 1151 | Inputs = { | ||
| 1152 | Width = Input { Value = 0.35, }, | ||
| 1153 | Height = Input { Value = 0.35, }, | ||
| 1154 | ["Translate.X"] = Input { Value = 0.18, }, | ||
| 1155 | Red = Input { Value = 0.0, }, | ||
| 1156 | Green = Input { Value = 1.0, }, | ||
| 1157 | Blue = Input { Value = 0.0, }, | ||
| 1158 | }, | ||
| 1159 | }, | ||
| 1160 | BoolSub = sBoolean { | ||
| 1161 | Inputs = { | ||
| 1162 | Operation = Input { Value = FuID { "Subtract" }, }, | ||
| 1163 | Input1 = Input { SourceOp = "Rect1", Source = "Output", }, | ||
| 1164 | Input2 = Input { SourceOp = "NGon1", Source = "Output", }, | ||
| 1165 | }, | ||
| 1166 | }, | ||
| 1167 | BoolXor = sBoolean { | ||
| 1168 | Inputs = { | ||
| 1169 | Operation = Input { Value = FuID { "Xor" }, }, | ||
| 1170 | Input1 = Input { SourceOp = "NGon1", Source = "Output", }, | ||
| 1171 | Input2 = Input { SourceOp = "Rect1", Source = "Output", }, | ||
| 1172 | }, | ||
| 1173 | }, | ||
| 1174 | RSub = sRender { | ||
| 1175 | Inputs = { | ||
| 1176 | Width = Input { Value = 128, }, | ||
| 1177 | Height = Input { Value = 128, }, | ||
| 1178 | Input = Input { SourceOp = "BoolSub", Source = "Output", }, | ||
| 1179 | }, | ||
| 1180 | }, | ||
| 1181 | RXor = sRender { | ||
| 1182 | Inputs = { | ||
| 1183 | Width = Input { Value = 128, }, | ||
| 1184 | Height = Input { Value = 128, }, | ||
| 1185 | Input = Input { SourceOp = "BoolXor", Source = "Output", }, | ||
| 1186 | }, | ||
| 1187 | }, | ||
| 1188 | }, | ||
| 1189 | }"#; | ||
| 1190 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 1191 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 1192 | return; | ||
| 1193 | }; | ||
| 1194 | let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0); | ||
| 1195 | let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0); | ||
| 1196 | let px_sub = eng.readback_rgba(&tex_sub).unwrap(); | ||
| 1197 | let px_xor = eng.readback_rgba(&tex_xor).unwrap(); | ||
| 1198 | |||
| 1199 | // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white! | ||
| 1200 | let rect_only = (64 * 128 + 102) * 4; | ||
| 1201 | assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]); | ||
| 1202 | assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]); | ||
| 1203 | |||
| 1204 | // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent! | ||
| 1205 | let overlap = (64 * 128 + 77) * 4; | ||
| 1206 | assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]); | ||
| 1207 | assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]); | ||
| 1208 | |||
| 1209 | // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor! | ||
| 1210 | let ngon_only = (64 * 128 + 54) * 4; | ||
| 1211 | assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]); | ||
| 1212 | } | ||
| 1213 | |||
| 1214 | #[test] | ||
| 1215 | fn test_s_boolean_operation_names_and_missing_inputs() { | ||
| 1216 | let boolean = |name: &str, op: &str, inputs: &str| { | ||
| 1217 | format!( | ||
| 1218 | r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }}, | ||
| 1219 | R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }}, | ||
| 1220 | Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"# | ||
| 1221 | ) | ||
| 1222 | }; | ||
| 1223 | let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; | ||
| 1224 | let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#; | ||
| 1225 | let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; | ||
| 1226 | let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#); | ||
| 1227 | let src = format!( | ||
| 1228 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ | ||
| 1229 | Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }}, | ||
| 1230 | Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }}, | ||
| 1231 | Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }}, | ||
| 1232 | {} {} {} {} {} {} | ||
| 1233 | }} }}"#, | ||
| 1234 | boolean("Inter", &fu("Intersection"), both), | ||
| 1235 | boolean("Default", "", both), | ||
| 1236 | boolean("Unknown", &fu("Intersect"), both), | ||
| 1237 | boolean("SubFirst", &fu("Subtract"), first), | ||
| 1238 | boolean("SubSecond", &fu("Subtract"), second), | ||
| 1239 | boolean("UnionBoth", &fu("Union"), both), | ||
| 1240 | ); | ||
| 1241 | let comp = Comp::from_fusion_str(&src).unwrap(); | ||
| 1242 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 1243 | return; | ||
| 1244 | }; | ||
| 1245 | let mut px = |name: &str, x: usize| { | ||
| 1246 | let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0); | ||
| 1247 | let rgba = eng.readback_rgba(&tex).unwrap(); | ||
| 1248 | let i = (64 * 128 + x) * 4; | ||
| 1249 | [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] | ||
| 1250 | }; | ||
| 1251 | let white = [255; 4]; | ||
| 1252 | let empty = [0; 4]; | ||
| 1253 | // x=64 is inside both shapes, x=90 is inside only the rectangle. | ||
| 1254 | assert_eq!(px("Inter", 64), white); | ||
| 1255 | assert_eq!(px("Inter", 90), empty); | ||
| 1256 | assert_eq!(px("Default", 64), white, "Operation defaults to Intersection"); | ||
| 1257 | assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing"); | ||
| 1258 | assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color"); | ||
| 1259 | assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing"); | ||
| 1260 | assert_eq!(px("UnionBoth", 90), white); | ||
| 1261 | } | ||
| 1262 | |||
| 1263 | #[test] | ||
| 1264 | fn test_s_grid() { | ||
| 1265 | let src = r#"{ | ||
| 1266 | Tools = ordered() { | ||
| 1267 | El1 = sEllipse { | ||
| 1268 | Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, | ||
| 1269 | }, | ||
| 1270 | Gr1 = sGrid { | ||
| 1271 | Inputs = { | ||
| 1272 | Input = Input { SourceOp = "El1", Source = "Output", }, | ||
| 1273 | CellsX = Input { Value = 3, }, | ||
| 1274 | CellsY = Input { Value = 3, }, | ||
| 1275 | XOffset = Input { Value = 0.25, }, | ||
| 1276 | YOffset = Input { Value = 0.25, }, | ||
| 1277 | }, | ||
| 1278 | }, | ||
| 1279 | SR1 = sRender { | ||
| 1280 | Inputs = { | ||
| 1281 | Width = Input { Value = 64, }, | ||
| 1282 | Height = Input { Value = 64, }, | ||
| 1283 | Input = Input { SourceOp = "Gr1", Source = "Output", }, | ||
| 1284 | }, | ||
| 1285 | }, | ||
| 1286 | }, | ||
| 1287 | }"#; | ||
| 1288 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 1289 | let Ok(mut eng) = Engine::new_headless() else { return; }; | ||
| 1290 | let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0); | ||
| 1291 | let px_sr = eng.readback_rgba(&t_sr).unwrap(); | ||
| 1292 | assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]); | ||
| 1293 | assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]); | ||
| 1294 | assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]); | ||
| 1295 | } | ||
| 1296 | #[test] | ||
| 1297 | fn test_giant_rotated_shapes_clip_instead_of_hanging_and_alpha_stays_unpremultiplied() { | ||
| 1298 | let src = r#"Composition { | ||
| 1299 | CurrentTime = 0, | ||
| 1300 | RenderRange = { 0, 1 }, | ||
| 1301 | GlobalRange = { 0, 1 }, | ||
| 1302 | Tools = ordered() { | ||
| 1303 | NG = sNGon { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Alpha = Input { Value = 0.25, }, Opacity = Input { Value = 0.5, }, Blue = Input { Value = 0.5, }, }, }, | ||
| 1304 | Rect = sRectangle { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Angle = Input { Value = 33, }, }, }, | ||
| 1305 | SRN = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "NG", Source = "Output", }, }, }, | ||
| 1306 | SRR = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, | ||
| 1307 | }, | ||
| 1308 | }"#; | ||
| 1309 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 1310 | let Ok(mut eng) = Engine::new_headless() else { return; }; | ||
| 1311 | let (t, _) = eng.evaluate(&comp, comp.find_node("SRN").unwrap(), 0.0); | ||
| 1312 | let px = eng.readback_rgba(&t).unwrap(); | ||
| 1313 | let mid = (16 * 32 + 16) * 4; | ||
| 1314 | assert_eq!(&px[mid..mid + 4], &[128, 128, 64, 32], "Opacity scales RGBA, Alpha scales alpha only"); | ||
| 1315 | let (t, _) = eng.evaluate(&comp, comp.find_node("SRR").unwrap(), 0.0); | ||
| 1316 | let px = eng.readback_rgba(&t).unwrap(); | ||
| 1317 | assert_eq!(&px[mid..mid + 4], &[255, 255, 255, 255]); | ||
| 1318 | assert_eq!(&px[0..4], &[255, 255, 255, 255], "giant rotated rectangle covers the corner"); | ||
| 1319 | } | ||
| 1320 | |||
| 1321 | #[test] | ||
| 1322 | fn s_outline_negative_thickness_s_boolean_keep_style_and_s_render_blend() { | ||
| 1323 | let src = r#"Composition { | ||
| 1324 | CurrentTime = 0, | ||
| 1325 | RenderRange = { 0, 1 }, | ||
| 1326 | GlobalRange = { 0, 1 }, | ||
| 1327 | Tools = ordered() { | ||
| 1328 | R1 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Red = Input { Value = 1.0, }, Green = Input { Value = 0.0, }, Blue = Input { Value = 0.0, }, }, }, | ||
| 1329 | R2 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Blue = Input { Value = 1.0, }, }, }, | ||
| 1330 | OutNeg = sOutline { Inputs = { Input = Input { SourceOp = "R1", Source = "Output", }, Thickness = Input { Value = -0.05, }, }, }, | ||
| 1331 | SROutNeg = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "OutNeg", Source = "Output", }, }, }, | ||
| 1332 | BoolKeep = sBoolean { Inputs = { | ||
| 1333 | Input1 = Input { SourceOp = "R1", Source = "Output", }, | ||
| 1334 | Input2 = Input { SourceOp = "R2", Source = "Output", }, | ||
| 1335 | Operation = Input { Value = FuID { "Intersection" }, }, | ||
| 1336 | StyleMode = Input { Value = FuID { "Keep" }, }, | ||
| 1337 | Opacity = Input { Value = 0.2, }, | ||
| 1338 | Green = Input { Value = 1.0, }, | ||
| 1339 | }, }, | ||
| 1340 | SRBool = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Blend = Input { Value = 0.2, }, Input = Input { SourceOp = "BoolKeep", Source = "Output", }, }, }, | ||
| 1341 | }, | ||
| 1342 | }"#; | ||
| 1343 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 1344 | let Ok(mut eng) = Engine::new_headless() else { return; }; | ||
| 1345 | let (t_out, _) = eng.evaluate(&comp, comp.find_node("SROutNeg").unwrap(), 0.0); | ||
| 1346 | let px_out = eng.readback_rgba(&t_out).unwrap(); | ||
| 1347 | assert!(px_out.iter().all(|&b| b == 0), "negative sOutline thickness should render empty"); | ||
| 1348 | |||
| 1349 | let (t_bool, _) = eng.evaluate(&comp, comp.find_node("SRBool").unwrap(), 0.0); | ||
| 1350 | let px_bool = eng.readback_rgba(&t_bool).unwrap(); | ||
| 1351 | let mid = (16 * 32 + 16) * 4; | ||
| 1352 | assert_eq!(&px_bool[mid..mid + 4], &[255, 0, 0, 255], "sBoolean Keep preserves Input1 style ignoring Opacity, and sRender ignores Blend"); | ||
| 1353 | } | ||
| 1354 | |||
| 1355 | #[test] | ||
| 1356 | fn test_s_star_points_depth_rotation_and_outline() { | ||
| 1357 | let src = r#"Composition { | ||
| 1358 | CurrentTime = 0, | ||
| 1359 | RenderRange = { 0, 1 }, | ||
| 1360 | GlobalRange = { 0, 1 }, | ||
| 1361 | Tools = ordered() { | ||
| 1362 | Star5 = sStar { | ||
| 1363 | Inputs = { | ||
| 1364 | Points = Input { Value = 5, }, | ||
| 1365 | Depth = Input { Value = 0.5, }, | ||
| 1366 | Width = Input { Value = 0.6, }, | ||
| 1367 | Height = Input { Value = 0.6, }, | ||
| 1368 | Red = Input { Value = 1.0, }, | ||
| 1369 | Green = Input { Value = 0.5, }, | ||
| 1370 | Blue = Input { Value = 0.0, }, | ||
| 1371 | }, | ||
| 1372 | }, | ||
| 1373 | StarOutline = sStar { | ||
| 1374 | Inputs = { | ||
| 1375 | NumberOfPoints = Input { Value = 6, }, | ||
| 1376 | Depth = Input { Value = 0.4, }, | ||
| 1377 | Width = Input { Value = 0.6, }, | ||
| 1378 | Height = Input { Value = 0.6, }, | ||
| 1379 | Solid = Input { Value = 0, }, | ||
| 1380 | BorderWidth = Input { Value = 0.04, }, | ||
| 1381 | CornerRadius = Input { Value = 0.02, }, | ||
| 1382 | ZRotation = Input { Value = 30.0, }, | ||
| 1383 | }, | ||
| 1384 | }, | ||
| 1385 | SRFill = sRender { | ||
| 1386 | Inputs = { | ||
| 1387 | Width = Input { Value = 64, }, | ||
| 1388 | Height = Input { Value = 64, }, | ||
| 1389 | Input = Input { SourceOp = "Star5", Source = "Output", }, | ||
| 1390 | }, | ||
| 1391 | }, | ||
| 1392 | SROutline = sRender { | ||
| 1393 | Inputs = { | ||
| 1394 | Width = Input { Value = 64, }, | ||
| 1395 | Height = Input { Value = 64, }, | ||
| 1396 | Input = Input { SourceOp = "StarOutline", Source = "Output", }, | ||
| 1397 | }, | ||
| 1398 | }, | ||
| 1399 | }, | ||
| 1400 | }"#; | ||
| 1401 | let comp = Comp::from_fusion_str(src).expect("parse sStar comp"); | ||
| 1402 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 1403 | |||
| 1404 | let (tf, sf) = eng.evaluate(&comp, comp.find_node("SRFill").unwrap(), 0.0); | ||
| 1405 | assert!(sf.unsupported_nodes.is_empty()); | ||
| 1406 | let pf = eng.readback_rgba(&tf).unwrap(); | ||
| 1407 | let px = |buf: &[u8], x: usize, y: usize| -> [u8; 4] { | ||
| 1408 | let i = (y * 64 + x) * 4; | ||
| 1409 | [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] | ||
| 1410 | }; | ||
| 1411 | // Center (32, 32) is solid orange. | ||
| 1412 | let ctr = px(&pf, 32, 32); | ||
| 1413 | assert!(ctr[0] > 240 && (ctr[1] as i32 - 128).abs() <= 4 && ctr[2] < 5 && ctr[3] == 255, "center={ctr:?}"); | ||
| 1414 | // Rightmost outer tip at +X (r = 0.30 -> x ~ 50, y = 32) is covered! | ||
| 1415 | assert!(px(&pf, 49, 32)[3] > 200, "outer tip at +X must be covered"); | ||
| 1416 | // Opposite -X valley for odd 5-point star is at r = 0.15 (x ~ 22.4): x=24 inside, x=15 outside! | ||
| 1417 | assert!(px(&pf, 24, 32)[3] > 200, "inner valley interior must be covered"); | ||
| 1418 | assert_eq!(px(&pf, 15, 32)[3], 0, "outside -X inner valley must be empty"); | ||
| 1419 | |||
| 1420 | // Outline mode: hollow center, non-empty stroke ring. | ||
| 1421 | let (to, _) = eng.evaluate(&comp, comp.find_node("SROutline").unwrap(), 0.0); | ||
| 1422 | let po = eng.readback_rgba(&to).unwrap(); | ||
| 1423 | assert_eq!(px(&po, 32, 32)[3], 0, "outline sStar center must be hollow"); | ||
| 1424 | let lit_px = po.chunks_exact(4).filter(|c| c[3] > 127).count(); | ||
| 1425 | assert!(lit_px > 50, "outline sStar should render visible stroke pixels, got {lit_px}"); | ||
| 1426 | } | ||
| 1427 | } |
crates/engine/src/eval/shapes/collect.rs created+707| ... | @@ -0,0 +1,707 @@ | ||
| 1 | //! Graph collection for 2D vector shape nodes (`sNGon`, `sRectangle`, `sEllipse`, `sStar`, | ||
| 2 | //! `sPolygon`, `sTransform`, `sMerge`, `sGrid`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, | ||
| 3 | //! `sOutline`, `sBoolean`). | ||
| 4 | |||
| 5 | use model::{Comp, ExprEngine, Node, NodeId, ParamValue}; | ||
| 6 | |||
| 7 | use super::{Affine2D, OutlineStyle, PathModifier, ShapeBoolOp, ShapePrimKind, ShapeTree}; | ||
| 8 | |||
| 9 | fn eval_first_num( | ||
| 10 | comp: &Comp, | ||
| 11 | node: &Node, | ||
| 12 | keys: &[&str], | ||
| 13 | time: f64, | ||
| 14 | default: f64, | ||
| 15 | expr: &ExprEngine, | ||
| 16 | ) -> f64 { | ||
| 17 | for &k in keys { | ||
| 18 | if node.inputs.contains_key(k) { | ||
| 19 | return comp.eval_number(node, k, time, default, expr); | ||
| 20 | } | ||
| 21 | } | ||
| 22 | default | ||
| 23 | } | ||
| 24 | |||
| 25 | fn eval_xy_or_point( | ||
| 26 | comp: &Comp, | ||
| 27 | node: &Node, | ||
| 28 | x_keys: &[&str], | ||
| 29 | y_keys: &[&str], | ||
| 30 | point_key: &str, | ||
| 31 | time: f64, | ||
| 32 | default: [f32; 2], | ||
| 33 | expr: &ExprEngine, | ||
| 34 | ) -> [f32; 2] { | ||
| 35 | let pt = if node.inputs.contains_key(point_key) { | ||
| 36 | let p = comp.eval_point(node, point_key, time, [default[0] as f64, default[1] as f64], expr); | ||
| 37 | [p[0] as f32, p[1] as f32] | ||
| 38 | } else { | ||
| 39 | default | ||
| 40 | }; | ||
| 41 | let x = eval_first_num(comp, node, x_keys, time, pt[0] as f64, expr) as f32; | ||
| 42 | let y = eval_first_num(comp, node, y_keys, time, pt[1] as f64, expr) as f32; | ||
| 43 | [x, y] | ||
| 44 | } | ||
| 45 | |||
| 46 | fn is_point_binding(comp: &Comp, node: &Node, key: &str) -> bool { | ||
| 47 | let Some(binding) = node.inputs.get(key) else { | ||
| 48 | return false; | ||
| 49 | }; | ||
| 50 | if matches!(binding.value, Some(ParamValue::Point(_))) { | ||
| 51 | return true; | ||
| 52 | } | ||
| 53 | if let Some(src) = &binding.source_op { | ||
| 54 | if comp.poly_paths.contains_key(src) { | ||
| 55 | return true; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | false | ||
| 59 | } | ||
| 60 | |||
| 61 | /// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. | ||
| 62 | fn parse_bool_op(node: &Node) -> Option<ShapeBoolOp> { | ||
| 63 | if !node.inputs.contains_key("Operation") { | ||
| 64 | return Some(ShapeBoolOp::Intersect); | ||
| 65 | } | ||
| 66 | match node.static_str("Operation")? { | ||
| 67 | "Union" => Some(ShapeBoolOp::Union), | ||
| 68 | "Intersection" => Some(ShapeBoolOp::Intersect), | ||
| 69 | "Subtract" => Some(ShapeBoolOp::Subtract), | ||
| 70 | "Xor" => Some(ShapeBoolOp::Xor), | ||
| 71 | _ => None, | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | /// Extracts `(points, closed)` for `sPolygon` from an animated `Polyline` spline, | ||
| 76 | /// a `PolyPath` modifier, or an inline `Polyline` table. | ||
| 77 | fn extract_polygon_polyline( | ||
| 78 | comp: &Comp, | ||
| 79 | node: &Node, | ||
| 80 | time: f64, | ||
| 81 | solid: bool, | ||
| 82 | expr: &ExprEngine, | ||
| 83 | ) -> (Vec<model::PolyPoint>, bool) { | ||
| 84 | let explicit_closed = if node.inputs.contains_key("Closed") { | ||
| 85 | Some(comp.eval_number(node, "Closed", time, if solid { 1.0 } else { 0.0 }, expr) > 0.5) | ||
| 86 | } else { | ||
| 87 | None | ||
| 88 | }; | ||
| 89 | |||
| 90 | if let Some(src) = node.connected_node("Polyline").or_else(|| node.connected_node("PolyLine")) { | ||
| 91 | if let Some(pts) = comp.eval_polyline_spline(src, time) { | ||
| 92 | return (pts, explicit_closed.unwrap_or(true)); | ||
| 93 | } | ||
| 94 | if let Some(pp) = comp.poly_paths.get(src) { | ||
| 95 | return (pp.points.clone(), explicit_closed.unwrap_or(pp.closed || solid)); | ||
| 96 | } | ||
| 97 | } | ||
| 98 | |||
| 99 | if let Some(tbl) = node | ||
| 100 | .raw | ||
| 101 | .get_table("Inputs") | ||
| 102 | .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine"))) | ||
| 103 | .and_then(|p| p.get_table("Value")) | ||
| 104 | { | ||
| 105 | let has_closed_key = tbl.get_bool("Closed").is_some(); | ||
| 106 | let (parsed_closed, pts) = model::PolyPath::parse_polyline_table(tbl); | ||
| 107 | let closed = explicit_closed.unwrap_or(if has_closed_key { parsed_closed } else { solid }); | ||
| 108 | return (pts, closed); | ||
| 109 | } | ||
| 110 | |||
| 111 | (Vec::new(), explicit_closed.unwrap_or(solid)) | ||
| 112 | } | ||
| 113 | |||
| 114 | #[allow(clippy::too_many_arguments)] | ||
| 115 | pub(super) fn collect_shape_tree( | ||
| 116 | comp: &Comp, | ||
| 117 | node_id: NodeId, | ||
| 118 | time: f64, | ||
| 119 | expr: &ExprEngine, | ||
| 120 | parent_xform: Affine2D, | ||
| 121 | outline_override: Option<OutlineStyle>, | ||
| 122 | depth: usize, | ||
| 123 | prim_budget: &mut usize, | ||
| 124 | ) -> Option<ShapeTree> { | ||
| 125 | if depth > 32 || *prim_budget == 0 { | ||
| 126 | return None; | ||
| 127 | } | ||
| 128 | let node = comp.node(node_id); | ||
| 129 | if node.bypassed { | ||
| 130 | return node | ||
| 131 | .connected_node("Input") | ||
| 132 | .or_else(|| node.connected_node("Input1")) | ||
| 133 | .and_then(|s| comp.find_node(s)) | ||
| 134 | .and_then(|id| { | ||
| 135 | collect_shape_tree( | ||
| 136 | comp, | ||
| 137 | id, | ||
| 138 | time, | ||
| 139 | expr, | ||
| 140 | parent_xform, | ||
| 141 | outline_override, | ||
| 142 | depth + 1, | ||
| 143 | prim_budget, | ||
| 144 | ) | ||
| 145 | }); | ||
| 146 | } | ||
| 147 | |||
| 148 | match node.kind.as_str() { | ||
| 149 | "sNGon" | "sRectangle" | "sEllipse" | "sStar" | "sPolygon" => { | ||
| 150 | *prim_budget = prim_budget.saturating_sub(1); | ||
| 151 | let [tx, ty] = eval_xy_or_point( | ||
| 152 | comp, | ||
| 153 | node, | ||
| 154 | &["Translate.X", "XOffset"], | ||
| 155 | &["Translate.Y", "YOffset"], | ||
| 156 | "Translate", | ||
| 157 | time, | ||
| 158 | [0.0, 0.0], | ||
| 159 | expr, | ||
| 160 | ); | ||
| 161 | let [px, py] = eval_xy_or_point( | ||
| 162 | comp, | ||
| 163 | node, | ||
| 164 | &["XPivot", "Pivot.X"], | ||
| 165 | &["YPivot", "Pivot.Y"], | ||
| 166 | "Pivot", | ||
| 167 | time, | ||
| 168 | [0.0, 0.0], | ||
| 169 | expr, | ||
| 170 | ); | ||
| 171 | let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); | ||
| 172 | let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; | ||
| 173 | let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; | ||
| 174 | let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; | ||
| 175 | |||
| 176 | let local = if (sx - 1.0).abs() > 1e-6 || (sy - 1.0).abs() > 1e-6 || px.abs() > 1e-6 || py.abs() > 1e-6 { | ||
| 177 | Affine2D::translate(tx + px, ty + py) | ||
| 178 | .mul(Affine2D::rotate_deg(angle)) | ||
| 179 | .mul(Affine2D::scale(sx, sy)) | ||
| 180 | .mul(Affine2D::translate(-px, -py)) | ||
| 181 | } else { | ||
| 182 | Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)) | ||
| 183 | }; | ||
| 184 | let xform = parent_xform.mul(local); | ||
| 185 | |||
| 186 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 187 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 188 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 189 | let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; | ||
| 190 | let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; | ||
| 191 | |||
| 192 | let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; | ||
| 193 | let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32; | ||
| 194 | let mut join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; | ||
| 195 | let mut cap_style = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; | ||
| 196 | let mut miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; | ||
| 197 | let mut write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; | ||
| 198 | let mut write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 199 | |||
| 200 | if let Some(ov) = outline_override { | ||
| 201 | solid = false; | ||
| 202 | border_width = ov.thickness; | ||
| 203 | join_style = ov.join; | ||
| 204 | cap_style = ov.cap; | ||
| 205 | miter_limit = ov.miter_limit; | ||
| 206 | write_pos = ov.write_pos; | ||
| 207 | write_len = ov.write_len; | ||
| 208 | } | ||
| 209 | |||
| 210 | let kind = match node.kind.as_str() { | ||
| 211 | "sNGon" => { | ||
| 212 | let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; | ||
| 213 | let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; | ||
| 214 | let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; | ||
| 215 | ShapePrimKind::NGon { sides, width, height } | ||
| 216 | } | ||
| 217 | "sRectangle" => { | ||
| 218 | let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; | ||
| 219 | let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; | ||
| 220 | let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; | ||
| 221 | ShapePrimKind::Rectangle { width, height, corner_radius } | ||
| 222 | } | ||
| 223 | "sStar" => { | ||
| 224 | let points = eval_first_num(comp, node, &["Points", "NumberOfPoints"], time, 6.0, expr) | ||
| 225 | .round() | ||
| 226 | .clamp(3.0, 256.0) as u32; | ||
| 227 | let depth = comp.eval_number(node, "Depth", time, 0.5, expr).clamp(0.0, 2.0) as f32; | ||
| 228 | let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; | ||
| 229 | let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; | ||
| 230 | let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; | ||
| 231 | ShapePrimKind::Star { points, depth, width, height, corner_radius } | ||
| 232 | } | ||
| 233 | "sPolygon" => { | ||
| 234 | let (points, closed) = extract_polygon_polyline(comp, node, time, solid, expr); | ||
| 235 | if points.len() < 2 { | ||
| 236 | return None; | ||
| 237 | } | ||
| 238 | ShapePrimKind::Polygon { points, closed } | ||
| 239 | } | ||
| 240 | _ => { | ||
| 241 | let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; | ||
| 242 | let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; | ||
| 243 | ShapePrimKind::Ellipse { width, height } | ||
| 244 | } | ||
| 245 | }; | ||
| 246 | |||
| 247 | Some(ShapeTree::Primitive { | ||
| 248 | kind, | ||
| 249 | xform, | ||
| 250 | color: [r * opacity, g * opacity, b * opacity, a * opacity], | ||
| 251 | solid, | ||
| 252 | border_width, | ||
| 253 | join_style, | ||
| 254 | cap_style, | ||
| 255 | miter_limit, | ||
| 256 | write_pos, | ||
| 257 | write_len, | ||
| 258 | }) | ||
| 259 | } | ||
| 260 | "sTransform" => { | ||
| 261 | let src_id = node | ||
| 262 | .connected_node("Input") | ||
| 263 | .or_else(|| node.connected_node("Input1")) | ||
| 264 | .and_then(|s| comp.find_node(s))?; | ||
| 265 | let [ox, oy] = eval_xy_or_point( | ||
| 266 | comp, | ||
| 267 | node, | ||
| 268 | &["XOffset", "Translate.X"], | ||
| 269 | &["YOffset", "Translate.Y"], | ||
| 270 | "Translate", | ||
| 271 | time, | ||
| 272 | [0.0, 0.0], | ||
| 273 | expr, | ||
| 274 | ); | ||
| 275 | let [px, py] = eval_xy_or_point( | ||
| 276 | comp, | ||
| 277 | node, | ||
| 278 | &["XPivot", "Pivot.X"], | ||
| 279 | &["YPivot", "Pivot.Y"], | ||
| 280 | "Pivot", | ||
| 281 | time, | ||
| 282 | [0.0, 0.0], | ||
| 283 | expr, | ||
| 284 | ); | ||
| 285 | let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); | ||
| 286 | let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; | ||
| 287 | let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; | ||
| 288 | let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; | ||
| 289 | |||
| 290 | let local = Affine2D::translate(ox + px, oy + py) | ||
| 291 | .mul(Affine2D::rotate_deg(rot)) | ||
| 292 | .mul(Affine2D::scale(sx, sy)) | ||
| 293 | .mul(Affine2D::translate(-px, -py)); | ||
| 294 | let combined = parent_xform.mul(local); | ||
| 295 | collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1, prim_budget) | ||
| 296 | } | ||
| 297 | "sDuplicate" => { | ||
| 298 | let src_id = node | ||
| 299 | .connected_node("Input") | ||
| 300 | .or_else(|| node.connected_node("Input1")) | ||
| 301 | .and_then(|s| comp.find_node(s))?; | ||
| 302 | let copies = comp.eval_number(node, "Copies", time, 2.0, expr).round().clamp(0.0, 256.0) as usize; | ||
| 303 | if copies == 0 { | ||
| 304 | return None; | ||
| 305 | } | ||
| 306 | let [ox, oy] = eval_xy_or_point( | ||
| 307 | comp, | ||
| 308 | node, | ||
| 309 | &["XOffset", "Translate.X"], | ||
| 310 | &["YOffset", "Translate.Y"], | ||
| 311 | "Translate", | ||
| 312 | time, | ||
| 313 | [0.0, 0.0], | ||
| 314 | expr, | ||
| 315 | ); | ||
| 316 | let [px, py] = eval_xy_or_point( | ||
| 317 | comp, | ||
| 318 | node, | ||
| 319 | &["XPivot", "Pivot.X"], | ||
| 320 | &["YPivot", "Pivot.Y"], | ||
| 321 | "Pivot", | ||
| 322 | time, | ||
| 323 | [0.0, 0.0], | ||
| 324 | expr, | ||
| 325 | ); | ||
| 326 | let lock_size = comp.eval_number(node, "LockSize", time, 1.0, expr) > 0.5; | ||
| 327 | let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); | ||
| 328 | let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; | ||
| 329 | let sy = if node.inputs.contains_key("YSize") { | ||
| 330 | comp.eval_number(node, "YSize", time, base_scale, expr) as f32 | ||
| 331 | } else if lock_size && node.inputs.contains_key("XSize") { | ||
| 332 | sx | ||
| 333 | } else { | ||
| 334 | base_scale as f32 | ||
| 335 | }; | ||
| 336 | let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; | ||
| 337 | let time_offset = comp.eval_number(node, "TimeOffset", time, 0.0, expr); | ||
| 338 | |||
| 339 | let step_xf = Affine2D::translate(ox + px, oy + py) | ||
| 340 | .mul(Affine2D::rotate_deg(rot)) | ||
| 341 | .mul(Affine2D::scale(sx, sy)) | ||
| 342 | .mul(Affine2D::translate(-px, -py)); | ||
| 343 | |||
| 344 | let mut children = Vec::with_capacity(copies); | ||
| 345 | let mut cum_xf = Affine2D::identity(); | ||
| 346 | for i in 0..copies { | ||
| 347 | if *prim_budget == 0 { | ||
| 348 | break; | ||
| 349 | } | ||
| 350 | let copy_time = time + (i as f64) * time_offset; | ||
| 351 | let copy_xf = parent_xform.mul(cum_xf); | ||
| 352 | if let Some(tree) = collect_shape_tree( | ||
| 353 | comp, | ||
| 354 | src_id, | ||
| 355 | copy_time, | ||
| 356 | expr, | ||
| 357 | copy_xf, | ||
| 358 | outline_override, | ||
| 359 | depth + 1, | ||
| 360 | prim_budget, | ||
| 361 | ) { | ||
| 362 | children.push(tree); | ||
| 363 | } | ||
| 364 | cum_xf = cum_xf.mul(step_xf); | ||
| 365 | } | ||
| 366 | if children.is_empty() { | ||
| 367 | None | ||
| 368 | } else { | ||
| 369 | Some(ShapeTree::Group(children)) | ||
| 370 | } | ||
| 371 | } | ||
| 372 | "sJitter" => { | ||
| 373 | let src_id = node | ||
| 374 | .connected_node("Input") | ||
| 375 | .or_else(|| node.connected_node("Input1")) | ||
| 376 | .and_then(|s| comp.find_node(s))?; | ||
| 377 | |||
| 378 | let has_x = node.inputs.contains_key("XAmount") | ||
| 379 | || node.inputs.contains_key("PositionX") | ||
| 380 | || node.inputs.contains_key("XPosition"); | ||
| 381 | let has_y = node.inputs.contains_key("YAmount") | ||
| 382 | || node.inputs.contains_key("PositionY") | ||
| 383 | || node.inputs.contains_key("YPosition"); | ||
| 384 | let has_amt = node.inputs.contains_key("Amount"); | ||
| 385 | let amt = comp.eval_number(node, "Amount", time, 0.02, expr); | ||
| 386 | let x_amount = if has_x { | ||
| 387 | eval_first_num(comp, node, &["XAmount", "PositionX", "XPosition"], time, 0.0, expr) as f32 | ||
| 388 | } else if has_amt { | ||
| 389 | amt as f32 | ||
| 390 | } else if has_y { | ||
| 391 | 0.0 | ||
| 392 | } else { | ||
| 393 | 0.02 | ||
| 394 | }; | ||
| 395 | let y_amount = if has_y { | ||
| 396 | eval_first_num(comp, node, &["YAmount", "PositionY", "YPosition"], time, 0.0, expr) as f32 | ||
| 397 | } else if has_amt { | ||
| 398 | amt as f32 | ||
| 399 | } else if has_x { | ||
| 400 | 0.0 | ||
| 401 | } else { | ||
| 402 | 0.02 | ||
| 403 | }; | ||
| 404 | |||
| 405 | let seed = eval_first_num(comp, node, &["Seed", "RandomSeed"], time, 0.0, expr).round() as i64; | ||
| 406 | let smoothness = eval_first_num(comp, node, &["Smoothness", "Smooth"], time, 0.0, expr) | ||
| 407 | .clamp(0.0, 100.0) as f32; | ||
| 408 | let per_shape = matches!(node.static_str("Mode").or_else(|| node.static_str("JitterMode")), Some("Shape" | "PerShape")) | ||
| 409 | || comp.eval_number(node, "PerShape", time, 0.0, expr) > 0.5; | ||
| 410 | |||
| 411 | let child = collect_shape_tree( | ||
| 412 | comp, | ||
| 413 | src_id, | ||
| 414 | time, | ||
| 415 | expr, | ||
| 416 | Affine2D::identity(), | ||
| 417 | outline_override, | ||
| 418 | depth + 1, | ||
| 419 | prim_budget, | ||
| 420 | )?; | ||
| 421 | |||
| 422 | if x_amount.abs() <= 1e-6 && y_amount.abs() <= 1e-6 { | ||
| 423 | return Some(ShapeTree::Modify { | ||
| 424 | op: PathModifier::Offset { | ||
| 425 | offset_x: 0.0, | ||
| 426 | offset_y: 0.0, | ||
| 427 | contour_offset: 0.0, | ||
| 428 | position: 0.0, | ||
| 429 | join_style: 1, | ||
| 430 | miter_limit: 10.0, | ||
| 431 | }, | ||
| 432 | post_xform: parent_xform, | ||
| 433 | child: Box::new(child), | ||
| 434 | }); | ||
| 435 | } | ||
| 436 | |||
| 437 | Some(ShapeTree::Modify { | ||
| 438 | op: PathModifier::Jitter { | ||
| 439 | x_amount, | ||
| 440 | y_amount, | ||
| 441 | seed, | ||
| 442 | smoothness, | ||
| 443 | per_shape, | ||
| 444 | }, | ||
| 445 | post_xform: parent_xform, | ||
| 446 | child: Box::new(child), | ||
| 447 | }) | ||
| 448 | } | ||
| 449 | "sExpand" => { | ||
| 450 | let src_id = node | ||
| 451 | .connected_node("Input") | ||
| 452 | .or_else(|| node.connected_node("Input1")) | ||
| 453 | .and_then(|s| comp.find_node(s))?; | ||
| 454 | let amount = eval_first_num(comp, node, &["Amount", "Distance", "Expand", "Offset"], time, 0.0, expr) as f32; | ||
| 455 | let join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; | ||
| 456 | let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; | ||
| 457 | |||
| 458 | if amount.abs() <= 1e-6 { | ||
| 459 | return collect_shape_tree( | ||
| 460 | comp, | ||
| 461 | src_id, | ||
| 462 | time, | ||
| 463 | expr, | ||
| 464 | parent_xform, | ||
| 465 | outline_override, | ||
| 466 | depth + 1, | ||
| 467 | prim_budget, | ||
| 468 | ); | ||
| 469 | } | ||
| 470 | |||
| 471 | let child = collect_shape_tree( | ||
| 472 | comp, | ||
| 473 | src_id, | ||
| 474 | time, | ||
| 475 | expr, | ||
| 476 | Affine2D::identity(), | ||
| 477 | outline_override, | ||
| 478 | depth + 1, | ||
| 479 | prim_budget, | ||
| 480 | )?; | ||
| 481 | Some(ShapeTree::Modify { | ||
| 482 | op: PathModifier::Expand { | ||
| 483 | amount, | ||
| 484 | join_style, | ||
| 485 | miter_limit, | ||
| 486 | }, | ||
| 487 | post_xform: parent_xform, | ||
| 488 | child: Box::new(child), | ||
| 489 | }) | ||
| 490 | } | ||
| 491 | "sOffset" => { | ||
| 492 | let src_id = node | ||
| 493 | .connected_node("Input") | ||
| 494 | .or_else(|| node.connected_node("Input1")) | ||
| 495 | .and_then(|s| comp.find_node(s))?; | ||
| 496 | |||
| 497 | let mut offset_x = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; | ||
| 498 | let mut offset_y = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; | ||
| 499 | let mut contour_offset = 0.0_f32; | ||
| 500 | if node.inputs.contains_key("Offset") { | ||
| 501 | if is_point_binding(comp, node, "Offset") { | ||
| 502 | let pt = comp.eval_point(node, "Offset", time, [0.0, 0.0], expr); | ||
| 503 | offset_x += pt[0] as f32; | ||
| 504 | offset_y += pt[1] as f32; | ||
| 505 | } else { | ||
| 506 | contour_offset = comp.eval_number(node, "Offset", time, 0.0, expr) as f32; | ||
| 507 | } | ||
| 508 | } | ||
| 509 | let position = eval_first_num(comp, node, &["Position", "PathPosition"], time, 0.0, expr) as f32; | ||
| 510 | let join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; | ||
| 511 | let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; | ||
| 512 | |||
| 513 | // Fast path: pure 2D translation with no contour normal offset or path position shift. | ||
| 514 | if contour_offset.abs() <= 1e-6 && position.abs() <= 1e-6 { | ||
| 515 | let combined = parent_xform.mul(Affine2D::translate(offset_x, offset_y)); | ||
| 516 | return collect_shape_tree( | ||
| 517 | comp, | ||
| 518 | src_id, | ||
| 519 | time, | ||
| 520 | expr, | ||
| 521 | combined, | ||
| 522 | outline_override, | ||
| 523 | depth + 1, | ||
| 524 | prim_budget, | ||
| 525 | ); | ||
| 526 | } | ||
| 527 | |||
| 528 | let child = collect_shape_tree( | ||
| 529 | comp, | ||
| 530 | src_id, | ||
| 531 | time, | ||
| 532 | expr, | ||
| 533 | Affine2D::identity(), | ||
| 534 | outline_override, | ||
| 535 | depth + 1, | ||
| 536 | prim_budget, | ||
| 537 | )?; | ||
| 538 | Some(ShapeTree::Modify { | ||
| 539 | op: PathModifier::Offset { | ||
| 540 | offset_x, | ||
| 541 | offset_y, | ||
| 542 | contour_offset, | ||
| 543 | position, | ||
| 544 | join_style, | ||
| 545 | miter_limit, | ||
| 546 | }, | ||
| 547 | post_xform: parent_xform, | ||
| 548 | child: Box::new(child), | ||
| 549 | }) | ||
| 550 | } | ||
| 551 | "sMerge" => { | ||
| 552 | let mut ports: Vec<(u32, &str)> = node | ||
| 553 | .inputs | ||
| 554 | .keys() | ||
| 555 | .filter_map(|k| { | ||
| 556 | let rest = k.strip_prefix("Input")?; | ||
| 557 | let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? }; | ||
| 558 | Some((idx, k.as_str())) | ||
| 559 | }) | ||
| 560 | .collect(); | ||
| 561 | ports.sort_by_key(|&(idx, _)| idx); | ||
| 562 | let mut children = Vec::new(); | ||
| 563 | for (_, port) in ports { | ||
| 564 | if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { | ||
| 565 | if let Some(tree) = collect_shape_tree( | ||
| 566 | comp, | ||
| 567 | src_id, | ||
| 568 | time, | ||
| 569 | expr, | ||
| 570 | parent_xform, | ||
| 571 | outline_override, | ||
| 572 | depth + 1, | ||
| 573 | prim_budget, | ||
| 574 | ) { | ||
| 575 | children.push(tree); | ||
| 576 | } | ||
| 577 | } | ||
| 578 | } | ||
| 579 | if children.is_empty() { | ||
| 580 | None | ||
| 581 | } else { | ||
| 582 | Some(ShapeTree::Group(children)) | ||
| 583 | } | ||
| 584 | } | ||
| 585 | "sGrid" => { | ||
| 586 | let src_id = node | ||
| 587 | .connected_node("Input") | ||
| 588 | .or_else(|| node.connected_node("Input1")) | ||
| 589 | .and_then(|s| comp.find_node(s))?; | ||
| 590 | let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; | ||
| 591 | let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; | ||
| 592 | let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32; | ||
| 593 | let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32; | ||
| 594 | let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y).min(*prim_budget)); | ||
| 595 | for iy in 0..cells_y { | ||
| 596 | let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off; | ||
| 597 | for ix in 0..cells_x { | ||
| 598 | if *prim_budget == 0 { | ||
| 599 | break; | ||
| 600 | } | ||
| 601 | let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off; | ||
| 602 | let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty)); | ||
| 603 | if let Some(tree) = collect_shape_tree( | ||
| 604 | comp, | ||
| 605 | src_id, | ||
| 606 | time, | ||
| 607 | expr, | ||
| 608 | cell_xf, | ||
| 609 | outline_override, | ||
| 610 | depth + 1, | ||
| 611 | prim_budget, | ||
| 612 | ) { | ||
| 613 | children.push(tree); | ||
| 614 | } | ||
| 615 | } | ||
| 616 | } | ||
| 617 | if children.is_empty() { | ||
| 618 | None | ||
| 619 | } else { | ||
| 620 | Some(ShapeTree::Group(children)) | ||
| 621 | } | ||
| 622 | } | ||
| 623 | "sOutline" => { | ||
| 624 | let src_id = node | ||
| 625 | .connected_node("Input") | ||
| 626 | .or_else(|| node.connected_node("Input1")) | ||
| 627 | .and_then(|s| comp.find_node(s))?; | ||
| 628 | let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr) as f32; | ||
| 629 | if thickness <= 0.0 { | ||
| 630 | return None; | ||
| 631 | } | ||
| 632 | let join = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; | ||
| 633 | let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; | ||
| 634 | let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; | ||
| 635 | let write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; | ||
| 636 | let write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 637 | let style = OutlineStyle { thickness, join, cap, miter_limit, write_pos, write_len }; | ||
| 638 | collect_shape_tree(comp, src_id, time, expr, parent_xform, Some(style), depth + 1, prim_budget) | ||
| 639 | } | ||
| 640 | "sBoolean" => { | ||
| 641 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 642 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 643 | let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 644 | let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; | ||
| 645 | let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; | ||
| 646 | let keep_style = node.static_str("StyleMode").unwrap_or("Replace") == "Keep"; | ||
| 647 | let color = [r * opacity, g * opacity, b_col * opacity, a_col * opacity]; | ||
| 648 | let a = node | ||
| 649 | .connected_node("Input1") | ||
| 650 | .or_else(|| node.connected_node("Input")) | ||
| 651 | .and_then(|s| comp.find_node(s)) | ||
| 652 | .and_then(|id| { | ||
| 653 | collect_shape_tree( | ||
| 654 | comp, | ||
| 655 | id, | ||
| 656 | time, | ||
| 657 | expr, | ||
| 658 | parent_xform, | ||
| 659 | outline_override, | ||
| 660 | depth + 1, | ||
| 661 | prim_budget, | ||
| 662 | ) | ||
| 663 | })?; | ||
| 664 | let b_opt = node | ||
| 665 | .connected_node("Input2") | ||
| 666 | .and_then(|s| comp.find_node(s)) | ||
| 667 | .and_then(|id| { | ||
| 668 | collect_shape_tree( | ||
| 669 | comp, | ||
| 670 | id, | ||
| 671 | time, | ||
| 672 | expr, | ||
| 673 | parent_xform, | ||
| 674 | outline_override, | ||
| 675 | depth + 1, | ||
| 676 | prim_budget, | ||
| 677 | ) | ||
| 678 | }); | ||
| 679 | // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty. | ||
| 680 | let (op, b) = match (parse_bool_op(node), b_opt) { | ||
| 681 | (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())), | ||
| 682 | (Some(op), Some(b)) => (op, b), | ||
| 683 | (None, Some(_)) => return None, | ||
| 684 | }; | ||
| 685 | Some(ShapeTree::Boolean { | ||
| 686 | op, | ||
| 687 | color, | ||
| 688 | opacity, | ||
| 689 | keep_style, | ||
| 690 | a: Box::new(a), | ||
| 691 | b: Box::new(b), | ||
| 692 | }) | ||
| 693 | } | ||
| 694 | "PipeRouter" | "Fuse.Wireless" => { | ||
| 695 | let src_id = node | ||
| 696 | .connected_node("Input") | ||
| 697 | .or_else(|| node.connected_node("Input1")) | ||
| 698 | .and_then(|s| comp.find_node(s))?; | ||
| 699 | collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1, prim_budget) | ||
| 700 | } | ||
| 701 | "MacroOperator" | "GroupOperator" => { | ||
| 702 | let out_id = node.macro_output?; | ||
| 703 | collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1, prim_budget) | ||
| 704 | } | ||
| 705 | _ => None, | ||
| 706 | } | ||
| 707 | } | ||
crates/engine/src/eval/shapes/geometry.rs created+892| ... | @@ -0,0 +1,892 @@ | ||
| 1 | //! 2D vector shape command generation, contour flattening, path modifiers | ||
| 2 | //! (`sExpand`, `sJitter`, `sOffset`), path trimming, and viewport clipping. | ||
| 3 | |||
| 4 | use super::{Affine2D, PathModifier, ShapePrimKind}; | ||
| 5 | |||
| 6 | #[derive(Clone, Debug)] | ||
| 7 | pub(super) struct Contour { | ||
| 8 | pub(super) points: Vec<[f32; 2]>, | ||
| 9 | pub(super) closed: bool, | ||
| 10 | } | ||
| 11 | |||
| 12 | #[inline] | ||
| 13 | fn shape_to_px(wpt: [f32; 2], dims: [u32; 2]) -> zeno::Vector { | ||
| 14 | let wf = dims[0] as f32; | ||
| 15 | let hf = dims[1] as f32; | ||
| 16 | zeno::Vector::new((wpt[0] + 0.5) * wf, 0.5 * hf - wpt[1] * wf) | ||
| 17 | } | ||
| 18 | |||
| 19 | /// Builds shape-space `zeno::Command`s for a primitive and returns `(cmds, closed)`. | ||
| 20 | fn build_primitive_commands_shape(kind: &ShapePrimKind, xform: Affine2D) -> (Vec<zeno::Command>, bool) { | ||
| 21 | let to_v = |local: [f32; 2]| -> zeno::Vector { | ||
| 22 | let p = xform.apply(local); | ||
| 23 | zeno::Vector::new(p[0], p[1]) | ||
| 24 | }; | ||
| 25 | |||
| 26 | const KAPPA: f32 = 0.55228475; | ||
| 27 | let mut cmds = Vec::new(); | ||
| 28 | match kind { | ||
| 29 | ShapePrimKind::NGon { sides, width, height } => { | ||
| 30 | let n = (*sides).max(3); | ||
| 31 | let rx = width * 0.5; | ||
| 32 | let ry = height * 0.5; | ||
| 33 | if rx <= 1e-6 || ry <= 1e-6 { | ||
| 34 | return (cmds, true); | ||
| 35 | } | ||
| 36 | for k in 0..n { | ||
| 37 | let theta = (k as f32) * std::f32::consts::TAU / (n as f32); | ||
| 38 | let v = to_v([rx * theta.cos(), ry * theta.sin()]); | ||
| 39 | if k == 0 { | ||
| 40 | cmds.push(zeno::Command::MoveTo(v)); | ||
| 41 | } else { | ||
| 42 | cmds.push(zeno::Command::LineTo(v)); | ||
| 43 | } | ||
| 44 | } | ||
| 45 | cmds.push(zeno::Command::Close); | ||
| 46 | (cmds, true) | ||
| 47 | } | ||
| 48 | ShapePrimKind::Rectangle { width, height, corner_radius } => { | ||
| 49 | let hx = width * 0.5; | ||
| 50 | let hy = height * 0.5; | ||
| 51 | if hx <= 1e-6 || hy <= 1e-6 { | ||
| 52 | return (cmds, true); | ||
| 53 | } | ||
| 54 | let r = corner_radius.min(hx.min(hy)); | ||
| 55 | if r <= 1e-5 { | ||
| 56 | // Start at mid-right (+hx, 0) counter-clockwise so WritePosition matches sNGon/sEllipse. | ||
| 57 | cmds.push(zeno::Command::MoveTo(to_v([hx, 0.0]))); | ||
| 58 | cmds.push(zeno::Command::LineTo(to_v([hx, hy]))); | ||
| 59 | cmds.push(zeno::Command::LineTo(to_v([-hx, hy]))); | ||
| 60 | cmds.push(zeno::Command::LineTo(to_v([-hx, -hy]))); | ||
| 61 | cmds.push(zeno::Command::LineTo(to_v([hx, -hy]))); | ||
| 62 | cmds.push(zeno::Command::Close); | ||
| 63 | } else { | ||
| 64 | let k = r * KAPPA; | ||
| 65 | cmds.push(zeno::Command::MoveTo(to_v([hx, 0.0]))); | ||
| 66 | cmds.push(zeno::Command::LineTo(to_v([hx, hy - r]))); | ||
| 67 | cmds.push(zeno::Command::CurveTo( | ||
| 68 | to_v([hx, hy - r + k]), | ||
| 69 | to_v([hx - r + k, hy]), | ||
| 70 | to_v([hx - r, hy]), | ||
| 71 | )); | ||
| 72 | cmds.push(zeno::Command::LineTo(to_v([-hx + r, hy]))); | ||
| 73 | cmds.push(zeno::Command::CurveTo( | ||
| 74 | to_v([-hx + r - k, hy]), | ||
| 75 | to_v([-hx, hy - r + k]), | ||
| 76 | to_v([-hx, hy - r]), | ||
| 77 | )); | ||
| 78 | cmds.push(zeno::Command::LineTo(to_v([-hx, -hy + r]))); | ||
| 79 | cmds.push(zeno::Command::CurveTo( | ||
| 80 | to_v([-hx, -hy + r - k]), | ||
| 81 | to_v([-hx + r - k, -hy]), | ||
| 82 | to_v([-hx + r, -hy]), | ||
| 83 | )); | ||
| 84 | cmds.push(zeno::Command::LineTo(to_v([hx - r, -hy]))); | ||
| 85 | cmds.push(zeno::Command::CurveTo( | ||
| 86 | to_v([hx - r + k, -hy]), | ||
| 87 | to_v([hx, -hy + r - k]), | ||
| 88 | to_v([hx, -hy + r]), | ||
| 89 | )); | ||
| 90 | cmds.push(zeno::Command::Close); | ||
| 91 | } | ||
| 92 | (cmds, true) | ||
| 93 | } | ||
| 94 | ShapePrimKind::Ellipse { width, height } => { | ||
| 95 | let rx = width * 0.5; | ||
| 96 | let ry = height * 0.5; | ||
| 97 | if rx <= 1e-6 || ry <= 1e-6 { | ||
| 98 | return (cmds, true); | ||
| 99 | } | ||
| 100 | let kx = rx * KAPPA; | ||
| 101 | let ky = ry * KAPPA; | ||
| 102 | cmds.push(zeno::Command::MoveTo(to_v([rx, 0.0]))); | ||
| 103 | cmds.push(zeno::Command::CurveTo( | ||
| 104 | to_v([rx, ky]), | ||
| 105 | to_v([kx, ry]), | ||
| 106 | to_v([0.0, ry]), | ||
| 107 | )); | ||
| 108 | cmds.push(zeno::Command::CurveTo( | ||
| 109 | to_v([-kx, ry]), | ||
| 110 | to_v([-rx, ky]), | ||
| 111 | to_v([-rx, 0.0]), | ||
| 112 | )); | ||
| 113 | cmds.push(zeno::Command::CurveTo( | ||
| 114 | to_v([-rx, -ky]), | ||
| 115 | to_v([-kx, -ry]), | ||
| 116 | to_v([0.0, -ry]), | ||
| 117 | )); | ||
| 118 | cmds.push(zeno::Command::CurveTo( | ||
| 119 | to_v([kx, -ry]), | ||
| 120 | to_v([rx, -ky]), | ||
| 121 | to_v([rx, 0.0]), | ||
| 122 | )); | ||
| 123 | cmds.push(zeno::Command::Close); | ||
| 124 | (cmds, true) | ||
| 125 | } | ||
| 126 | ShapePrimKind::Star { points, depth, width, height, corner_radius } => { | ||
| 127 | let n = (*points).max(3) as usize; | ||
| 128 | let rx = width * 0.5; | ||
| 129 | let ry = height * 0.5; | ||
| 130 | if rx <= 1e-6 || ry <= 1e-6 { | ||
| 131 | return (cmds, true); | ||
| 132 | } | ||
| 133 | let total = n * 2; | ||
| 134 | let mut verts = Vec::with_capacity(total); | ||
| 135 | for k in 0..total { | ||
| 136 | let theta = (k as f32) * std::f32::consts::PI / (n as f32); | ||
| 137 | let s = if k % 2 == 0 { 1.0 } else { *depth }; | ||
| 138 | verts.push([rx * s * theta.cos(), ry * s * theta.sin()]); | ||
| 139 | } | ||
| 140 | if *corner_radius <= 1e-5 { | ||
| 141 | for (k, &pt) in verts.iter().enumerate() { | ||
| 142 | let v = to_v(pt); | ||
| 143 | if k == 0 { | ||
| 144 | cmds.push(zeno::Command::MoveTo(v)); | ||
| 145 | } else { | ||
| 146 | cmds.push(zeno::Command::LineTo(v)); | ||
| 147 | } | ||
| 148 | } | ||
| 149 | cmds.push(zeno::Command::Close); | ||
| 150 | } else { | ||
| 151 | for k in 0..total { | ||
| 152 | let prev = verts[(k + total - 1) % total]; | ||
| 153 | let curr = verts[k]; | ||
| 154 | let next = verts[(k + 1) % total]; | ||
| 155 | let d_prev = [prev[0] - curr[0], prev[1] - curr[1]]; | ||
| 156 | let d_next = [next[0] - curr[0], next[1] - curr[1]]; | ||
| 157 | let l_prev = d_prev[0].hypot(d_prev[1]); | ||
| 158 | let l_next = d_next[0].hypot(d_next[1]); | ||
| 159 | let r = corner_radius.min(0.45 * l_prev.min(l_next)); | ||
| 160 | if r <= 1e-6 { | ||
| 161 | let v = to_v(curr); | ||
| 162 | if k == 0 { | ||
| 163 | cmds.push(zeno::Command::MoveTo(v)); | ||
| 164 | } else { | ||
| 165 | cmds.push(zeno::Command::LineTo(v)); | ||
| 166 | } | ||
| 167 | } else { | ||
| 168 | let p_in = [curr[0] + d_prev[0] * (r / l_prev), curr[1] + d_prev[1] * (r / l_prev)]; | ||
| 169 | let p_out = [curr[0] + d_next[0] * (r / l_next), curr[1] + d_next[1] * (r / l_next)]; | ||
| 170 | if k == 0 { | ||
| 171 | cmds.push(zeno::Command::MoveTo(to_v(p_in))); | ||
| 172 | } else { | ||
| 173 | cmds.push(zeno::Command::LineTo(to_v(p_in))); | ||
| 174 | } | ||
| 175 | cmds.push(zeno::Command::QuadTo(to_v(curr), to_v(p_out))); | ||
| 176 | } | ||
| 177 | } | ||
| 178 | cmds.push(zeno::Command::Close); | ||
| 179 | } | ||
| 180 | (cmds, true) | ||
| 181 | } | ||
| 182 | ShapePrimKind::Polygon { points, closed } => { | ||
| 183 | if points.len() < 2 { | ||
| 184 | return (cmds, *closed); | ||
| 185 | } | ||
| 186 | cmds.push(zeno::Command::MoveTo(to_v([points[0].x as f32, points[0].y as f32]))); | ||
| 187 | let segs = if *closed { points.len() } else { points.len() - 1 }; | ||
| 188 | for i in 0..segs { | ||
| 189 | let a = &points[i]; | ||
| 190 | let b = &points[(i + 1) % points.len()]; | ||
| 191 | let p_b = to_v([b.x as f32, b.y as f32]); | ||
| 192 | let is_linear = (a.linear && b.linear) | ||
| 193 | || (a.rx.abs() < 1e-9 && a.ry.abs() < 1e-9 && b.lx.abs() < 1e-9 && b.ly.abs() < 1e-9); | ||
| 194 | if is_linear { | ||
| 195 | cmds.push(zeno::Command::LineTo(p_b)); | ||
| 196 | } else { | ||
| 197 | let c1 = to_v([(a.x + a.rx) as f32, (a.y + a.ry) as f32]); | ||
| 198 | let c2 = to_v([(b.x + b.lx) as f32, (b.y + b.ly) as f32]); | ||
| 199 | cmds.push(zeno::Command::CurveTo(c1, c2, p_b)); | ||
| 200 | } | ||
| 201 | } | ||
| 202 | if *closed { | ||
| 203 | cmds.push(zeno::Command::Close); | ||
| 204 | } | ||
| 205 | (cmds, *closed) | ||
| 206 | } | ||
| 207 | } | ||
| 208 | } | ||
| 209 | |||
| 210 | /// Builds pixel-space `zeno::Command`s for a primitive after applying any inner-to-outer `PathModifier`s. | ||
| 211 | pub(super) fn build_primitive_commands_px( | ||
| 212 | kind: &ShapePrimKind, | ||
| 213 | xform: Affine2D, | ||
| 214 | mods: &[(PathModifier, Affine2D)], | ||
| 215 | shape_idx: u32, | ||
| 216 | dims: [u32; 2], | ||
| 217 | ) -> (Vec<zeno::Command>, bool) { | ||
| 218 | let (shape_cmds, closed) = build_primitive_commands_shape(kind, xform); | ||
| 219 | if shape_cmds.is_empty() { | ||
| 220 | return (Vec::new(), closed); | ||
| 221 | } | ||
| 222 | |||
| 223 | if mods.is_empty() { | ||
| 224 | let px_cmds = shape_cmds | ||
| 225 | .into_iter() | ||
| 226 | .map(|c| match c { | ||
| 227 | zeno::Command::MoveTo(p) => zeno::Command::MoveTo(shape_to_px([p.x, p.y], dims)), | ||
| 228 | zeno::Command::LineTo(p) => zeno::Command::LineTo(shape_to_px([p.x, p.y], dims)), | ||
| 229 | zeno::Command::QuadTo(a, p) => zeno::Command::QuadTo( | ||
| 230 | shape_to_px([a.x, a.y], dims), | ||
| 231 | shape_to_px([p.x, p.y], dims), | ||
| 232 | ), | ||
| 233 | zeno::Command::CurveTo(a, b, p) => zeno::Command::CurveTo( | ||
| 234 | shape_to_px([a.x, a.y], dims), | ||
| 235 | shape_to_px([b.x, b.y], dims), | ||
| 236 | shape_to_px([p.x, p.y], dims), | ||
| 237 | ), | ||
| 238 | zeno::Command::Close => zeno::Command::Close, | ||
| 239 | }) | ||
| 240 | .collect(); | ||
| 241 | return (px_cmds, closed); | ||
| 242 | } | ||
| 243 | |||
| 244 | let scale_hint = dims[0].max(dims[1]) as f32; | ||
| 245 | let pts = flatten_commands_to_poly_scaled(&shape_cmds, scale_hint); | ||
| 246 | let mut contour = Contour { points: dedup_contour_points(pts, closed), closed }; | ||
| 247 | |||
| 248 | for (mod_idx, &(op, post_xform)) in mods.iter().enumerate() { | ||
| 249 | if contour.points.len() < 2 { | ||
| 250 | return (Vec::new(), contour.closed); | ||
| 251 | } | ||
| 252 | contour = apply_path_modifier(contour, op, shape_idx, mod_idx as u32); | ||
| 253 | for p in &mut contour.points { | ||
| 254 | *p = post_xform.apply(*p); | ||
| 255 | } | ||
| 256 | } | ||
| 257 | |||
| 258 | if contour.points.len() < 2 || (contour.closed && contour.points.len() < 3) { | ||
| 259 | return (Vec::new(), contour.closed); | ||
| 260 | } | ||
| 261 | |||
| 262 | let mut px_cmds = Vec::with_capacity(contour.points.len() + 1); | ||
| 263 | for (i, &pt) in contour.points.iter().enumerate() { | ||
| 264 | let v = shape_to_px(pt, dims); | ||
| 265 | if i == 0 { | ||
| 266 | px_cmds.push(zeno::Command::MoveTo(v)); | ||
| 267 | } else { | ||
| 268 | px_cmds.push(zeno::Command::LineTo(v)); | ||
| 269 | } | ||
| 270 | } | ||
| 271 | if contour.closed { | ||
| 272 | px_cmds.push(zeno::Command::Close); | ||
| 273 | } | ||
| 274 | (px_cmds, contour.closed) | ||
| 275 | } | ||
| 276 | |||
| 277 | fn dedup_contour_points(pts: Vec<[f32; 2]>, closed: bool) -> Vec<[f32; 2]> { | ||
| 278 | let mut out: Vec<[f32; 2]> = Vec::with_capacity(pts.len()); | ||
| 279 | for p in pts { | ||
| 280 | if !p[0].is_finite() || !p[1].is_finite() { | ||
| 281 | continue; | ||
| 282 | } | ||
| 283 | if let Some(&prev) = out.last() { | ||
| 284 | if (p[0] - prev[0]).hypot(p[1] - prev[1]) <= 1e-6 { | ||
| 285 | continue; | ||
| 286 | } | ||
| 287 | } | ||
| 288 | out.push(p); | ||
| 289 | } | ||
| 290 | if closed && out.len() >= 2 { | ||
| 291 | if let (Some(&first), Some(&last)) = (out.first(), out.last()) { | ||
| 292 | if (last[0] - first[0]).hypot(last[1] - first[1]) <= 1e-6 { | ||
| 293 | out.pop(); | ||
| 294 | } | ||
| 295 | } | ||
| 296 | } | ||
| 297 | out | ||
| 298 | } | ||
| 299 | |||
| 300 | fn signed_area(pts: &[[f32; 2]]) -> f32 { | ||
| 301 | let n = pts.len(); | ||
| 302 | if n < 3 { | ||
| 303 | return 0.0; | ||
| 304 | } | ||
| 305 | let mut sum = 0.0_f64; | ||
| 306 | for i in 0..n { | ||
| 307 | let a = pts[i]; | ||
| 308 | let b = pts[(i + 1) % n]; | ||
| 309 | sum += (a[0] as f64) * (b[1] as f64) - (b[0] as f64) * (a[1] as f64); | ||
| 310 | } | ||
| 311 | (0.5 * sum) as f32 | ||
| 312 | } | ||
| 313 | |||
| 314 | fn apply_path_modifier(contour: Contour, op: PathModifier, shape_idx: u32, mod_idx: u32) -> Contour { | ||
| 315 | match op { | ||
| 316 | PathModifier::Expand { amount, join_style, miter_limit } => { | ||
| 317 | expand_contour(contour, amount, join_style, miter_limit) | ||
| 318 | } | ||
| 319 | PathModifier::Jitter { x_amount, y_amount, seed, smoothness, per_shape } => { | ||
| 320 | jitter_contour(contour, x_amount, y_amount, seed, smoothness, per_shape, shape_idx, mod_idx) | ||
| 321 | } | ||
| 322 | PathModifier::Offset { | ||
| 323 | offset_x, | ||
| 324 | offset_y, | ||
| 325 | contour_offset, | ||
| 326 | position, | ||
| 327 | join_style, | ||
| 328 | miter_limit, | ||
| 329 | } => { | ||
| 330 | let mut c = if contour_offset.abs() > 1e-6 { | ||
| 331 | expand_contour(contour, contour_offset, join_style, miter_limit) | ||
| 332 | } else { | ||
| 333 | contour | ||
| 334 | }; | ||
| 335 | if position.abs() > 1e-6 { | ||
| 336 | c = shift_contour_position(c, position); | ||
| 337 | } | ||
| 338 | if offset_x.abs() > 1e-6 || offset_y.abs() > 1e-6 { | ||
| 339 | for p in &mut c.points { | ||
| 340 | p[0] += offset_x; | ||
| 341 | p[1] += offset_y; | ||
| 342 | } | ||
| 343 | } | ||
| 344 | c | ||
| 345 | } | ||
| 346 | } | ||
| 347 | } | ||
| 348 | |||
| 349 | /// Offsets a contour outward (`amount > 0`) or inward (`amount < 0`) using miter/bevel/round joins. | ||
| 350 | fn expand_contour(contour: Contour, amount: f32, join_style: u8, miter_limit: f32) -> Contour { | ||
| 351 | if amount.abs() <= 1e-6 { | ||
| 352 | return contour; | ||
| 353 | } | ||
| 354 | let pts = dedup_contour_points(contour.points, contour.closed); | ||
| 355 | if !contour.closed { | ||
| 356 | if pts.len() < 2 { | ||
| 357 | return Contour { points: Vec::new(), closed: false }; | ||
| 358 | } | ||
| 359 | let n = pts.len(); | ||
| 360 | let mut out = Vec::with_capacity(n); | ||
| 361 | for i in 0..n { | ||
| 362 | let n0 = if i > 0 { | ||
| 363 | let dx = pts[i][0] - pts[i - 1][0]; | ||
| 364 | let dy = pts[i][1] - pts[i - 1][1]; | ||
| 365 | let l = dx.hypot(dy).max(1e-6); | ||
| 366 | [dy / l, -dx / l] | ||
| 367 | } else { | ||
| 368 | [0.0, 0.0] | ||
| 369 | }; | ||
| 370 | let n1 = if i + 1 < n { | ||
| 371 | let dx = pts[i + 1][0] - pts[i][0]; | ||
| 372 | let dy = pts[i + 1][1] - pts[i][1]; | ||
| 373 | let l = dx.hypot(dy).max(1e-6); | ||
| 374 | [dy / l, -dx / l] | ||
| 375 | } else { | ||
| 376 | [0.0, 0.0] | ||
| 377 | }; | ||
| 378 | let avg = if i == 0 { | ||
| 379 | n1 | ||
| 380 | } else if i + 1 == n { | ||
| 381 | n0 | ||
| 382 | } else { | ||
| 383 | let bx = n0[0] + n1[0]; | ||
| 384 | let by = n0[1] + n1[1]; | ||
| 385 | let denom = (1.0 + n0[0] * n1[0] + n0[1] * n1[1]).max(1e-4); | ||
| 386 | let scale = (1.0 / denom).min(miter_limit * 0.5); | ||
| 387 | [bx * scale, by * scale] | ||
| 388 | }; | ||
| 389 | out.push([pts[i][0] + avg[0] * amount, pts[i][1] + avg[1] * amount]); | ||
| 390 | } | ||
| 391 | return Contour { points: out, closed: false }; | ||
| 392 | } | ||
| 393 | |||
| 394 | let n = pts.len(); | ||
| 395 | if n < 3 { | ||
| 396 | return Contour { points: Vec::new(), closed: true }; | ||
| 397 | } | ||
| 398 | let orig_area = signed_area(&pts); | ||
| 399 | if orig_area.abs() <= 1e-10 { | ||
| 400 | return Contour { points: Vec::new(), closed: true }; | ||
| 401 | } | ||
| 402 | // For CCW (orig_area > 0) in Y-up shape space, outward normal of edge (dx, dy) is (dy, -dx)/len. | ||
| 403 | let orient = if orig_area > 0.0 { 1.0_f32 } else { -1.0_f32 }; | ||
| 404 | |||
| 405 | // Compute per-edge outward unit normals. | ||
| 406 | let mut normals = Vec::with_capacity(n); | ||
| 407 | for i in 0..n { | ||
| 408 | let a = pts[i]; | ||
| 409 | let b = pts[(i + 1) % n]; | ||
| 410 | let dx = b[0] - a[0]; | ||
| 411 | let dy = b[1] - a[1]; | ||
| 412 | let len = dx.hypot(dy).max(1e-6); | ||
| 413 | normals.push([orient * dy / len, -orient * dx / len]); | ||
| 414 | } | ||
| 415 | |||
| 416 | let mut out = Vec::with_capacity(n * 2); | ||
| 417 | for i in 0..n { | ||
| 418 | let n0 = normals[(i + n - 1) % n]; | ||
| 419 | let n1 = normals[i]; | ||
| 420 | let p = pts[i]; | ||
| 421 | |||
| 422 | let dot = (n0[0] * n1[0] + n0[1] * n1[1]).clamp(-1.0, 1.0); | ||
| 423 | let cross = n0[0] * n1[1] - n0[1] * n1[0]; | ||
| 424 | // When dot ~= 1, edges are collinear. | ||
| 425 | if dot > 1.0 - 1e-5 { | ||
| 426 | out.push([p[0] + n0[0] * amount, p[1] + n0[1] * amount]); | ||
| 427 | continue; | ||
| 428 | } | ||
| 429 | |||
| 430 | // Convex corner for CCW has cross > 0; outer join happens when expanding convex or shrinking reflex. | ||
| 431 | let is_outer = (cross * orient * amount) > 0.0; | ||
| 432 | let q0 = [p[0] + n0[0] * amount, p[1] + n0[1] * amount]; | ||
| 433 | let q1 = [p[0] + n1[0] * amount, p[1] + n1[1] * amount]; | ||
| 434 | let denom = 1.0 + dot; | ||
| 435 | |||
| 436 | if is_outer { | ||
| 437 | match join_style { | ||
| 438 | 0 => { | ||
| 439 | // Bevel | ||
| 440 | out.push(q0); | ||
| 441 | out.push(q1); | ||
| 442 | } | ||
| 443 | 1 => { | ||
| 444 | // Round arc from n0 to n1 | ||
| 445 | let a0 = (n0[1] * amount).atan2(n0[0] * amount); | ||
| 446 | let a1 = (n1[1] * amount).atan2(n1[0] * amount); | ||
| 447 | let mut delta = a1 - a0; | ||
| 448 | while delta > std::f32::consts::PI { | ||
| 449 | delta -= std::f32::consts::TAU; | ||
| 450 | } | ||
| 451 | while delta < -std::f32::consts::PI { | ||
| 452 | delta += std::f32::consts::TAU; | ||
| 453 | } | ||
| 454 | let steps = ((delta.abs() / 0.25).ceil() as usize).clamp(1, 16); | ||
| 455 | let rad = amount.abs(); | ||
| 456 | for s in 0..=steps { | ||
| 457 | let a = a0 + delta * (s as f32 / steps as f32); | ||
| 458 | out.push([p[0] + rad * a.cos(), p[1] + rad * a.sin()]); | ||
| 459 | } | ||
| 460 | } | ||
| 461 | _ => { | ||
| 462 | // Miter (with miter_limit fallback to bevel) | ||
| 463 | if denom > 1e-4 { | ||
| 464 | let miter_ratio = (2.0 / denom).sqrt(); | ||
| 465 | if miter_ratio <= miter_limit { | ||
| 466 | let inv = amount / denom; | ||
| 467 | out.push([p[0] + (n0[0] + n1[0]) * inv, p[1] + (n0[1] + n1[1]) * inv]); | ||
| 468 | } else { | ||
| 469 | out.push(q0); | ||
| 470 | out.push(q1); | ||
| 471 | } | ||
| 472 | } else { | ||
| 473 | out.push(q0); | ||
| 474 | out.push(q1); | ||
| 475 | } | ||
| 476 | } | ||
| 477 | } | ||
| 478 | } else { | ||
| 479 | // Inner corner (or convex corner when deflating): exact miter intersection clamped to miter_limit. | ||
| 480 | if denom > 1e-4 { | ||
| 481 | let miter_ratio = (2.0 / denom).sqrt(); | ||
| 482 | let clamped_inv = if miter_ratio <= miter_limit { | ||
| 483 | amount / denom | ||
| 484 | } else { | ||
| 485 | amount * (miter_limit / (2.0 * denom).sqrt().max(1e-4)) | ||
| 486 | }; | ||
| 487 | out.push([ | ||
| 488 | p[0] + (n0[0] + n1[0]) * clamped_inv, | ||
| 489 | p[1] + (n0[1] + n1[1]) * clamped_inv, | ||
| 490 | ]); | ||
| 491 | } else { | ||
| 492 | out.push([(q0[0] + q1[0]) * 0.5, (q0[1] + q1[1]) * 0.5]); | ||
| 493 | } | ||
| 494 | } | ||
| 495 | } | ||
| 496 | |||
| 497 | // If deflating (`amount < 0`), check for collapse / inverted winding. | ||
| 498 | if amount < 0.0 { | ||
| 499 | let mut min_x = f32::INFINITY; | ||
| 500 | let mut max_x = f32::NEG_INFINITY; | ||
| 501 | let mut min_y = f32::INFINITY; | ||
| 502 | let mut max_y = f32::NEG_INFINITY; | ||
| 503 | for &p in &pts { | ||
| 504 | min_x = min_x.min(p[0]); | ||
| 505 | max_x = max_x.max(p[0]); | ||
| 506 | min_y = min_y.min(p[1]); | ||
| 507 | max_y = max_y.max(p[1]); | ||
| 508 | } | ||
| 509 | let half_min = 0.5 * (max_x - min_x).min(max_y - min_y); | ||
| 510 | let new_area = signed_area(&out); | ||
| 511 | if (-amount) >= half_min - 1e-5 || new_area * orig_area <= 1e-10 { | ||
| 512 | return Contour { points: Vec::new(), closed: true }; | ||
| 513 | } | ||
| 514 | } | ||
| 515 | |||
| 516 | Contour { points: dedup_contour_points(out, true), closed: true } | ||
| 517 | } | ||
| 518 | |||
| 519 | /// Deterministic signed float in `[-1.0, 1.0]` from `(seed, shape_idx, mod_idx, vertex_idx, axis)`. | ||
| 520 | #[inline] | ||
| 521 | fn jitter_hash(seed: i64, shape_idx: u32, mod_idx: u32, vertex_idx: u32, axis: u32) -> f32 { | ||
| 522 | let mut h = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) | ||
| 523 | ^ (shape_idx as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9) | ||
| 524 | ^ (mod_idx as u64).wrapping_mul(0x94D0_49BB_1331_11EB) | ||
| 525 | ^ (vertex_idx as u64).wrapping_mul(0xD1B5_4A32_D192_ED03) | ||
| 526 | ^ (axis as u64).wrapping_mul(0x517C_C1B7_2722_0A95); | ||
| 527 | h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); | ||
| 528 | h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 529 | h ^= h >> 31; | ||
| 530 | let u = ((h >> 40) as f32) * (1.0 / ((1u32 << 24) as f32)); | ||
| 531 | u * 2.0 - 1.0 | ||
| 532 | } | ||
| 533 | |||
| 534 | /// Subdivides sparse contours so long straight edges (like rectangles) receive organic vertex jitter. | ||
| 535 | fn subdivide_for_jitter(pts: &[[f32; 2]], closed: bool) -> Vec<[f32; 2]> { | ||
| 536 | let n = pts.len(); | ||
| 537 | if n < 2 || n >= 48 { | ||
| 538 | return pts.to_vec(); | ||
| 539 | } | ||
| 540 | let seg_count = if closed { n } else { n - 1 }; | ||
| 541 | let mut total_len = 0.0_f32; | ||
| 542 | for i in 0..seg_count { | ||
| 543 | let a = pts[i]; | ||
| 544 | let b = pts[(i + 1) % n]; | ||
| 545 | total_len += (b[0] - a[0]).hypot(b[1] - a[1]); | ||
| 546 | } | ||
| 547 | if total_len <= 1e-6 { | ||
| 548 | return pts.to_vec(); | ||
| 549 | } | ||
| 550 | let target_step = (total_len / 48.0).max(1e-4); | ||
| 551 | let mut out = Vec::with_capacity(64); | ||
| 552 | for i in 0..seg_count { | ||
| 553 | let a = pts[i]; | ||
| 554 | let b = pts[(i + 1) % n]; | ||
| 555 | let len = (b[0] - a[0]).hypot(b[1] - a[1]); | ||
| 556 | let subs = ((len / target_step).ceil() as usize).clamp(1, 32); | ||
| 557 | for s in 0..subs { | ||
| 558 | let t = s as f32 / subs as f32; | ||
| 559 | out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); | ||
| 560 | } | ||
| 561 | } | ||
| 562 | if !closed { | ||
| 563 | out.push(pts[n - 1]); | ||
| 564 | } | ||
| 565 | out | ||
| 566 | } | ||
| 567 | |||
| 568 | /// Applies deterministic per-vertex or per-shape jitter with optional `smoothness` filtering. | ||
| 569 | #[allow(clippy::too_many_arguments)] | ||
| 570 | fn jitter_contour( | ||
| 571 | contour: Contour, | ||
| 572 | x_amount: f32, | ||
| 573 | y_amount: f32, | ||
| 574 | seed: i64, | ||
| 575 | smoothness: f32, | ||
| 576 | per_shape: bool, | ||
| 577 | shape_idx: u32, | ||
| 578 | mod_idx: u32, | ||
| 579 | ) -> Contour { | ||
| 580 | if per_shape { | ||
| 581 | let dx = jitter_hash(seed, shape_idx, mod_idx, 0, 0) * x_amount; | ||
| 582 | let dy = jitter_hash(seed, shape_idx, mod_idx, 0, 1) * y_amount; | ||
| 583 | let points = contour | ||
| 584 | .points | ||
| 585 | .into_iter() | ||
| 586 | .map(|p| [p[0] + dx, p[1] + dy]) | ||
| 587 | .collect(); | ||
| 588 | return Contour { points, closed: contour.closed }; | ||
| 589 | } | ||
| 590 | |||
| 591 | let pts = subdivide_for_jitter(&contour.points, contour.closed); | ||
| 592 | let n = pts.len(); | ||
| 593 | if n < 2 { | ||
| 594 | return Contour { points: pts, closed: contour.closed }; | ||
| 595 | } | ||
| 596 | |||
| 597 | let mut offsets: Vec<[f32; 2]> = (0..n) | ||
| 598 | .map(|i| { | ||
| 599 | [ | ||
| 600 | jitter_hash(seed, shape_idx, mod_idx, i as u32, 0) * x_amount, | ||
| 601 | jitter_hash(seed, shape_idx, mod_idx, i as u32, 1) * y_amount, | ||
| 602 | ] | ||
| 603 | }) | ||
| 604 | .collect(); | ||
| 605 | |||
| 606 | if smoothness > 1e-4 { | ||
| 607 | let sigma = (smoothness * 2.5).min((n as f32) * 0.5); | ||
| 608 | let radius = ((sigma * 2.5).ceil() as usize).clamp(1, n / 2); | ||
| 609 | let inv_two_sig_sq = 0.5 / (sigma * sigma).max(1e-4); | ||
| 610 | let mut smoothed = vec![[0.0_f32; 2]; n]; | ||
| 611 | for i in 0..n { | ||
| 612 | let mut sx = 0.0_f32; | ||
| 613 | let mut sy = 0.0_f32; | ||
| 614 | let mut wsum = 0.0_f32; | ||
| 615 | for d in -(radius as isize)..=(radius as isize) { | ||
| 616 | let w = (-((d * d) as f32) * inv_two_sig_sq).exp(); | ||
| 617 | let j = if contour.closed { | ||
| 618 | (i as isize + d).rem_euclid(n as isize) as usize | ||
| 619 | } else { | ||
| 620 | (i as isize + d).clamp(0, (n - 1) as isize) as usize | ||
| 621 | }; | ||
| 622 | sx += offsets[j][0] * w; | ||
| 623 | sy += offsets[j][1] * w; | ||
| 624 | wsum += w; | ||
| 625 | } | ||
| 626 | if wsum > 1e-6 { | ||
| 627 | smoothed[i] = [sx / wsum, sy / wsum]; | ||
| 628 | } | ||
| 629 | } | ||
| 630 | // Renormalize variance partially so smooth jitter stays visibly displaced rather than vanishing to 0. | ||
| 631 | let boost = (1.0 + sigma.sqrt()).min(3.0); | ||
| 632 | for s in &mut smoothed { | ||
| 633 | s[0] = (s[0] * boost).clamp(-x_amount.abs(), x_amount.abs()); | ||
| 634 | s[1] = (s[1] * boost).clamp(-y_amount.abs(), y_amount.abs()); | ||
| 635 | } | ||
| 636 | offsets = smoothed; | ||
| 637 | } | ||
| 638 | |||
| 639 | let points = pts | ||
| 640 | .into_iter() | ||
| 641 | .zip(offsets) | ||
| 642 | .map(|(p, o)| [p[0] + o[0], p[1] + o[1]]) | ||
| 643 | .collect(); | ||
| 644 | Contour { points, closed: contour.closed } | ||
| 645 | } | ||
| 646 | |||
| 647 | /// Shifts a contour's parametric origin along its arc length by `position` (in `[0, 1]` fractions). | ||
| 648 | fn shift_contour_position(contour: Contour, position: f32) -> Contour { | ||
| 649 | let pts = dedup_contour_points(contour.points, contour.closed); | ||
| 650 | let n = pts.len(); | ||
| 651 | if n < 2 { | ||
| 652 | return Contour { points: pts, closed: contour.closed }; | ||
| 653 | } | ||
| 654 | |||
| 655 | if !contour.closed { | ||
| 656 | // For an open path, translate along its unit start-to-end chord by `position * arc_len`. | ||
| 657 | let mut total = 0.0_f32; | ||
| 658 | for i in 0..n - 1 { | ||
| 659 | total += (pts[i + 1][0] - pts[i][0]).hypot(pts[i + 1][1] - pts[i][1]); | ||
| 660 | } | ||
| 661 | let cdx = pts[n - 1][0] - pts[0][0]; | ||
| 662 | let cdy = pts[n - 1][1] - pts[0][1]; | ||
| 663 | let clen = cdx.hypot(cdy); | ||
| 664 | if clen <= 1e-6 || total <= 1e-6 { | ||
| 665 | return Contour { points: pts, closed: false }; | ||
| 666 | } | ||
| 667 | let shift = position * total; | ||
| 668 | let tx = (cdx / clen) * shift; | ||
| 669 | let ty = (cdy / clen) * shift; | ||
| 670 | return Contour { | ||
| 671 | points: pts.into_iter().map(|p| [p[0] + tx, p[1] + ty]).collect(), | ||
| 672 | closed: false, | ||
| 673 | }; | ||
| 674 | } | ||
| 675 | |||
| 676 | let frac = position.rem_euclid(1.0); | ||
| 677 | if frac <= 1e-6 || frac >= 1.0 - 1e-6 { | ||
| 678 | return Contour { points: pts, closed: true }; | ||
| 679 | } | ||
| 680 | |||
| 681 | let mut seg_lens = Vec::with_capacity(n); | ||
| 682 | let mut total = 0.0_f32; | ||
| 683 | for i in 0..n { | ||
| 684 | let a = pts[i]; | ||
| 685 | let b = pts[(i + 1) % n]; | ||
| 686 | let l = (b[0] - a[0]).hypot(b[1] - a[1]); | ||
| 687 | seg_lens.push(l); | ||
| 688 | total += l; | ||
| 689 | } | ||
| 690 | if total <= 1e-6 { | ||
| 691 | return Contour { points: pts, closed: true }; | ||
| 692 | } | ||
| 693 | |||
| 694 | let target = frac * total; | ||
| 695 | let mut acc = 0.0_f32; | ||
| 696 | let mut split_idx = 0usize; | ||
| 697 | let mut split_t = 0.0_f32; | ||
| 698 | for (i, &l) in seg_lens.iter().enumerate() { | ||
| 699 | if acc + l >= target || i + 1 == n { | ||
| 700 | split_idx = i; | ||
| 701 | split_t = if l > 1e-6 { ((target - acc) / l).clamp(0.0, 1.0) } else { 0.0 }; | ||
| 702 | break; | ||
| 703 | } | ||
| 704 | acc += l; | ||
| 705 | } | ||
| 706 | |||
| 707 | let a = pts[split_idx]; | ||
| 708 | let b = pts[(split_idx + 1) % n]; | ||
| 709 | let start_pt = [a[0] + (b[0] - a[0]) * split_t, a[1] + (b[1] - a[1]) * split_t]; | ||
| 710 | let mut out = Vec::with_capacity(n + 1); | ||
| 711 | out.push(start_pt); | ||
| 712 | for k in 1..=n { | ||
| 713 | let idx = (split_idx + k) % n; | ||
| 714 | let p = pts[idx]; | ||
| 715 | if (p[0] - out.last().unwrap()[0]).hypot(p[1] - out.last().unwrap()[1]) > 1e-6 { | ||
| 716 | out.push(p); | ||
| 717 | } | ||
| 718 | } | ||
| 719 | Contour { points: dedup_contour_points(out, true), closed: true } | ||
| 720 | } | ||
| 721 | |||
| 722 | pub(super) fn flatten_commands_to_poly(cmds: &[zeno::Command]) -> Vec<[f32; 2]> { | ||
| 723 | flatten_commands_to_poly_scaled(cmds, 1.0) | ||
| 724 | } | ||
| 725 | |||
| 726 | fn flatten_commands_to_poly_scaled(cmds: &[zeno::Command], scale: f32) -> Vec<[f32; 2]> { | ||
| 727 | use zeno::Command::{CurveTo, LineTo, MoveTo, QuadTo}; | ||
| 728 | let mut poly: Vec<[f32; 2]> = Vec::new(); | ||
| 729 | for c in cmds { | ||
| 730 | match c { | ||
| 731 | MoveTo(p) | LineTo(p) => poly.push([p.x, p.y]), | ||
| 732 | QuadTo(a, p) => { | ||
| 733 | let p0 = poly.last().copied().unwrap_or([a.x, a.y]); | ||
| 734 | let len = ((a.x - p0[0]).hypot(a.y - p0[1]) + (p.x - a.x).hypot(p.y - a.y)) * scale; | ||
| 735 | let n = ((len.sqrt() * 1.5).ceil() as usize).clamp(8, 1024); | ||
| 736 | for i in 1..=n { | ||
| 737 | let t = i as f32 / n as f32; | ||
| 738 | let u = 1.0 - t; | ||
| 739 | poly.push([ | ||
| 740 | u * u * p0[0] + 2.0 * u * t * a.x + t * t * p.x, | ||
| 741 | u * u * p0[1] + 2.0 * u * t * a.y + t * t * p.y, | ||
| 742 | ]); | ||
| 743 | } | ||
| 744 | } | ||
| 745 | CurveTo(a, b, p) => { | ||
| 746 | let p0 = poly.last().copied().unwrap_or([a.x, a.y]); | ||
| 747 | let len = ((a.x - p0[0]).hypot(a.y - p0[1]) | ||
| 748 | + (b.x - a.x).hypot(b.y - a.y) | ||
| 749 | + (p.x - b.x).hypot(p.y - b.y)) | ||
| 750 | * scale; | ||
| 751 | let n = ((len.sqrt() * 1.5).ceil() as usize).clamp(16, 2048); | ||
| 752 | for i in 1..=n { | ||
| 753 | let t = i as f32 / n as f32; | ||
| 754 | let u = 1.0 - t; | ||
| 755 | let (c0, c1, c2, c3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); | ||
| 756 | poly.push([ | ||
| 757 | c0 * p0[0] + c1 * a.x + c2 * b.x + c3 * p.x, | ||
| 758 | c0 * p0[1] + c1 * a.y + c2 * b.y + c3 * p.y, | ||
| 759 | ]); | ||
| 760 | } | ||
| 761 | } | ||
| 762 | _ => {} | ||
| 763 | } | ||
| 764 | } | ||
| 765 | poly | ||
| 766 | } | ||
| 767 | |||
| 768 | /// Trims a command loop (closed or open) to arc-length fraction `[write_pos, write_pos + write_len]`. | ||
| 769 | pub(super) fn trim_path_commands( | ||
| 770 | cmds: Vec<zeno::Command>, | ||
| 771 | closed: bool, | ||
| 772 | write_pos: f32, | ||
| 773 | write_len: f32, | ||
| 774 | ) -> Vec<zeno::Command> { | ||
| 775 | if write_len <= 1e-5 { | ||
| 776 | return Vec::new(); | ||
| 777 | } | ||
| 778 | if write_len >= 1.0 - 1e-5 && (!closed || write_pos.rem_euclid(1.0) <= 1e-5) { | ||
| 779 | return cmds; | ||
| 780 | } | ||
| 781 | let poly = flatten_commands_to_poly(&cmds); | ||
| 782 | let n = poly.len(); | ||
| 783 | if n < 2 { | ||
| 784 | return Vec::new(); | ||
| 785 | } | ||
| 786 | let seg_count = if closed { n } else { n - 1 }; | ||
| 787 | let mut segs = Vec::with_capacity(seg_count); | ||
| 788 | let mut total = 0.0_f32; | ||
| 789 | for i in 0..seg_count { | ||
| 790 | let a = poly[i]; | ||
| 791 | let b = poly[(i + 1) % n]; | ||
| 792 | let len = (b[0] - a[0]).hypot(b[1] - a[1]); | ||
| 793 | segs.push((a, b, len)); | ||
| 794 | total += len; | ||
| 795 | } | ||
| 796 | if total <= 1e-5 { | ||
| 797 | return Vec::new(); | ||
| 798 | } | ||
| 799 | let s0 = if closed { | ||
| 800 | write_pos.rem_euclid(1.0) * total | ||
| 801 | } else { | ||
| 802 | write_pos.clamp(0.0, 1.0) * total | ||
| 803 | }; | ||
| 804 | let target = if closed { | ||
| 805 | write_len * total | ||
| 806 | } else { | ||
| 807 | (write_len * total).min((total - s0).max(0.0)) | ||
| 808 | }; | ||
| 809 | if target <= 1e-5 { | ||
| 810 | return Vec::new(); | ||
| 811 | } | ||
| 812 | let mut out = Vec::new(); | ||
| 813 | let mut acc = 0.0_f32; | ||
| 814 | let mut started = false; | ||
| 815 | let mut idx = 0usize; | ||
| 816 | let max_iters = if closed { seg_count * 2 + 2 } else { seg_count }; | ||
| 817 | while acc < s0 + target - 1e-5 && idx < max_iters { | ||
| 818 | let (a, b, len) = segs[idx % seg_count]; | ||
| 819 | idx += 1; | ||
| 820 | if len <= 1e-6 { | ||
| 821 | continue; | ||
| 822 | } | ||
| 823 | let seg_start = acc; | ||
| 824 | let seg_end = acc + len; | ||
| 825 | acc = seg_end; | ||
| 826 | if seg_end <= s0 { | ||
| 827 | continue; | ||
| 828 | } | ||
| 829 | let t0 = if !started { ((s0 - seg_start) / len).clamp(0.0, 1.0) } else { 0.0 }; | ||
| 830 | let t1 = ((s0 + target - seg_start) / len).clamp(0.0, 1.0); | ||
| 831 | if !started { | ||
| 832 | let p = [a[0] + t0 * (b[0] - a[0]), a[1] + t0 * (b[1] - a[1])]; | ||
| 833 | out.push(zeno::Command::MoveTo(zeno::Vector::new(p[0], p[1]))); | ||
| 834 | started = true; | ||
| 835 | } | ||
| 836 | let q = [a[0] + t1 * (b[0] - a[0]), a[1] + t1 * (b[1] - a[1])]; | ||
| 837 | out.push(zeno::Command::LineTo(zeno::Vector::new(q[0], q[1]))); | ||
| 838 | } | ||
| 839 | out | ||
| 840 | } | ||
| 841 | |||
| 842 | /// Flattens `cmds` and clips a closed polygon to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long. | ||
| 843 | pub(super) fn clip_to_viewport( | ||
| 844 | cmds: Vec<zeno::Command>, | ||
| 845 | closed: bool, | ||
| 846 | dims: [u32; 2], | ||
| 847 | margin: f32, | ||
| 848 | ) -> Vec<zeno::Command> { | ||
| 849 | use zeno::Command::{Close, CurveTo, LineTo, MoveTo}; | ||
| 850 | let [w, h] = [dims[0] as f32, dims[1] as f32]; | ||
| 851 | let limit = 4.0 * w.max(h); | ||
| 852 | let far = |v: &zeno::Vector| v.x.abs() > limit || v.y.abs() > limit; | ||
| 853 | let huge = cmds.iter().any(|c| match c { | ||
| 854 | MoveTo(p) | LineTo(p) => far(p), | ||
| 855 | zeno::Command::QuadTo(a, p) => far(a) || far(p), | ||
| 856 | CurveTo(a, b, p) => far(a) || far(b) || far(p), | ||
| 857 | _ => false, | ||
| 858 | }); | ||
| 859 | if !huge || !closed { | ||
| 860 | return cmds; | ||
| 861 | } | ||
| 862 | let mut poly = flatten_commands_to_poly(&cmds); | ||
| 863 | let edges: [(usize, f32, f32); 4] = [ | ||
| 864 | (0, 1.0, -margin), | ||
| 865 | (0, -1.0, w + margin), | ||
| 866 | (1, 1.0, -margin), | ||
| 867 | (1, -1.0, h + margin), | ||
| 868 | ]; | ||
| 869 | for (axis, sign, bound) in edges { | ||
| 870 | let inside = |p: [f32; 2]| sign * (p[axis] - bound) >= 0.0; | ||
| 871 | let input = std::mem::take(&mut poly); | ||
| 872 | for (i, &cur) in input.iter().enumerate() { | ||
| 873 | let prev = input[(i + input.len() - 1) % input.len()]; | ||
| 874 | if inside(cur) != inside(prev) { | ||
| 875 | let t = (bound - prev[axis]) / (cur[axis] - prev[axis]); | ||
| 876 | poly.push([prev[0] + t * (cur[0] - prev[0]), prev[1] + t * (cur[1] - prev[1])]); | ||
| 877 | } | ||
| 878 | if inside(cur) { | ||
| 879 | poly.push(cur); | ||
| 880 | } | ||
| 881 | } | ||
| 882 | } | ||
| 883 | let mut out = Vec::with_capacity(poly.len() + 1); | ||
| 884 | for (i, p) in poly.iter().enumerate() { | ||
| 885 | let v = zeno::Vector::new(p[0], p[1]); | ||
| 886 | out.push(if i == 0 { MoveTo(v) } else { LineTo(v) }); | ||
| 887 | } | ||
| 888 | if !out.is_empty() { | ||
| 889 | out.push(Close); | ||
| 890 | } | ||
| 891 | out | ||
| 892 | } | ||
crates/engine/src/eval/shapes/raster.rs created+191| ... | @@ -0,0 +1,191 @@ | ||
| 1 | //! CPU rasterizer for 2D vector `ShapeTree` hierarchies using `zeno`. | ||
| 2 | |||
| 3 | use super::geometry::{build_primitive_commands_px, clip_to_viewport, trim_path_commands}; | ||
| 4 | use super::{Affine2D, PathModifier, ShapeBoolOp, ShapeTree}; | ||
| 5 | |||
| 6 | fn composite_over(dst: &mut [f32], src: &[f32]) { | ||
| 7 | for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) { | ||
| 8 | let sa = s[3].clamp(0.0, 1.0); | ||
| 9 | if sa <= 1e-6 { | ||
| 10 | continue; | ||
| 11 | } | ||
| 12 | let inv = 1.0 - sa; | ||
| 13 | d[0] = s[0] + d[0] * inv; | ||
| 14 | d[1] = s[1] + d[1] * inv; | ||
| 15 | d[2] = s[2] + d[2] * inv; | ||
| 16 | d[3] = sa + d[3] * inv; | ||
| 17 | } | ||
| 18 | } | ||
| 19 | |||
| 20 | fn rasterize_shape_tree_f32( | ||
| 21 | tree: &ShapeTree, | ||
| 22 | dims: [u32; 2], | ||
| 23 | mods: &[(PathModifier, Affine2D)], | ||
| 24 | shape_counter: &mut u32, | ||
| 25 | dst: &mut [f32], | ||
| 26 | cov_buf: &mut [u8], | ||
| 27 | scratch: &mut zeno::Scratch, | ||
| 28 | ) { | ||
| 29 | let [w, h] = dims; | ||
| 30 | match tree { | ||
| 31 | ShapeTree::Primitive { | ||
| 32 | kind, | ||
| 33 | xform, | ||
| 34 | color, | ||
| 35 | solid, | ||
| 36 | border_width, | ||
| 37 | join_style, | ||
| 38 | cap_style, | ||
| 39 | miter_limit, | ||
| 40 | write_pos, | ||
| 41 | write_len, | ||
| 42 | } => { | ||
| 43 | let shape_idx = *shape_counter; | ||
| 44 | *shape_counter = shape_counter.wrapping_add(1); | ||
| 45 | |||
| 46 | let (cmds, closed) = build_primitive_commands_px(kind, *xform, mods, shape_idx, dims); | ||
| 47 | let finite = |v: &zeno::Vector| v.x.is_finite() && v.y.is_finite(); | ||
| 48 | let degenerate = cmds.iter().any(|c| match c { | ||
| 49 | zeno::Command::MoveTo(p) | zeno::Command::LineTo(p) => !finite(p), | ||
| 50 | zeno::Command::QuadTo(a, p) => !(finite(a) && finite(p)), | ||
| 51 | zeno::Command::CurveTo(a, b, p) => !(finite(a) && finite(b) && finite(p)), | ||
| 52 | _ => false, | ||
| 53 | }); | ||
| 54 | if cmds.is_empty() || degenerate { | ||
| 55 | return; | ||
| 56 | } | ||
| 57 | cov_buf.fill(0); | ||
| 58 | let reach = 4.0 * w.max(h) as f32; | ||
| 59 | let mut total_scale = xform.avg_scale(); | ||
| 60 | for (_, px) in mods { | ||
| 61 | total_scale *= px.avg_scale(); | ||
| 62 | } | ||
| 63 | let stroke_px = (*border_width * total_scale * (w as f32)).clamp(0.5, reach); | ||
| 64 | let cmds = clip_to_viewport( | ||
| 65 | cmds, | ||
| 66 | closed, | ||
| 67 | dims, | ||
| 68 | if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }, | ||
| 69 | ); | ||
| 70 | let cmds = if !*solid && (write_pos.abs() > 1e-5 || (*write_len - 1.0).abs() > 1e-5) { | ||
| 71 | trim_path_commands(cmds, closed, *write_pos, *write_len) | ||
| 72 | } else { | ||
| 73 | cmds | ||
| 74 | }; | ||
| 75 | if cmds.is_empty() { | ||
| 76 | return; | ||
| 77 | } | ||
| 78 | let style = if *solid && closed { | ||
| 79 | zeno::Style::Fill(zeno::Fill::NonZero) | ||
| 80 | } else { | ||
| 81 | let join = match *join_style { | ||
| 82 | 0 => zeno::Join::Bevel, | ||
| 83 | 1 => zeno::Join::Round, | ||
| 84 | _ => zeno::Join::Miter, | ||
| 85 | }; | ||
| 86 | let cap = match *cap_style { | ||
| 87 | 1 => zeno::Cap::Round, | ||
| 88 | 2 => zeno::Cap::Square, | ||
| 89 | _ => zeno::Cap::Butt, | ||
| 90 | }; | ||
| 91 | let mut st = zeno::Stroke::new(stroke_px); | ||
| 92 | st.join(join).cap(cap).miter_limit(*miter_limit); | ||
| 93 | zeno::Style::Stroke(st) | ||
| 94 | }; | ||
| 95 | let _ = zeno::Mask::with_scratch(&cmds, scratch) | ||
| 96 | .style(style) | ||
| 97 | .size(w, h) | ||
| 98 | .origin(zeno::Origin::TopLeft) | ||
| 99 | .render_into(cov_buf, None); | ||
| 100 | |||
| 101 | let ca = color[3].clamp(0.0, 1.0); | ||
| 102 | if ca <= 1e-6 { | ||
| 103 | return; | ||
| 104 | } | ||
| 105 | // Fusion keeps the colour unpremultiplied: Alpha scales coverage into alpha only, not RGB. | ||
| 106 | for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { | ||
| 107 | if cov == 0 { | ||
| 108 | continue; | ||
| 109 | } | ||
| 110 | let c = cov as f32 / 255.0; | ||
| 111 | let inv = 1.0 - c * ca; | ||
| 112 | px[0] = color[0] * c + px[0] * inv; | ||
| 113 | px[1] = color[1] * c + px[1] * inv; | ||
| 114 | px[2] = color[2] * c + px[2] * inv; | ||
| 115 | px[3] = c * ca + px[3] * inv; | ||
| 116 | } | ||
| 117 | } | ||
| 118 | ShapeTree::Group(children) => { | ||
| 119 | for ch in children { | ||
| 120 | rasterize_shape_tree_f32(ch, dims, mods, shape_counter, dst, cov_buf, scratch); | ||
| 121 | } | ||
| 122 | } | ||
| 123 | ShapeTree::Modify { op, post_xform, child } => { | ||
| 124 | let mut next_mods = Vec::with_capacity(mods.len() + 1); | ||
| 125 | next_mods.push((*op, *post_xform)); | ||
| 126 | next_mods.extend_from_slice(mods); | ||
| 127 | rasterize_shape_tree_f32(child, dims, &next_mods, shape_counter, dst, cov_buf, scratch); | ||
| 128 | } | ||
| 129 | ShapeTree::Boolean { op, color, opacity: _, keep_style, a, b } => { | ||
| 130 | let len = dst.len(); | ||
| 131 | let mut buf_a = vec![0.0f32; len]; | ||
| 132 | let mut buf_b = vec![0.0f32; len]; | ||
| 133 | rasterize_shape_tree_f32(a, dims, mods, shape_counter, &mut buf_a, cov_buf, scratch); | ||
| 134 | rasterize_shape_tree_f32(b, dims, mods, shape_counter, &mut buf_b, cov_buf, scratch); | ||
| 135 | let mut comb = vec![0.0f32; len]; | ||
| 136 | let ca = color[3].clamp(0.0, 1.0); | ||
| 137 | for ((ca_p, cb_p), out_p) in buf_a | ||
| 138 | .chunks_exact(4) | ||
| 139 | .zip(buf_b.chunks_exact(4)) | ||
| 140 | .zip(comb.chunks_exact_mut(4)) | ||
| 141 | { | ||
| 142 | let aa = ca_p[3].clamp(0.0, 1.0); | ||
| 143 | let ba = cb_p[3].clamp(0.0, 1.0); | ||
| 144 | let oa = match op { | ||
| 145 | ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0), | ||
| 146 | ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0), | ||
| 147 | ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0), | ||
| 148 | ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0), | ||
| 149 | }; | ||
| 150 | if *keep_style { | ||
| 151 | let s = if aa > 1e-6 { oa / aa } else { 0.0 }; | ||
| 152 | out_p[0] = ca_p[0] * s; | ||
| 153 | out_p[1] = ca_p[1] * s; | ||
| 154 | out_p[2] = ca_p[2] * s; | ||
| 155 | out_p[3] = oa; | ||
| 156 | } else { | ||
| 157 | // Opacity scales RGBA (baked into color); Alpha scales alpha only (not RGB). | ||
| 158 | out_p[0] = color[0] * oa; | ||
| 159 | out_p[1] = color[1] * oa; | ||
| 160 | out_p[2] = color[2] * oa; | ||
| 161 | out_p[3] = oa * ca; | ||
| 162 | } | ||
| 163 | } | ||
| 164 | composite_over(dst, &comb); | ||
| 165 | } | ||
| 166 | } | ||
| 167 | } | ||
| 168 | |||
| 169 | pub(super) fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec<u8> { | ||
| 170 | let px_count = (dims[0] as usize) * (dims[1] as usize); | ||
| 171 | let mut out = vec![0u8; px_count * 4]; | ||
| 172 | let Some(tree) = tree else { | ||
| 173 | return out; | ||
| 174 | }; | ||
| 175 | let b = blend.clamp(0.0, 1.0); | ||
| 176 | if b <= 1e-6 { | ||
| 177 | return out; | ||
| 178 | } | ||
| 179 | let mut accum = vec![0.0f32; px_count * 4]; | ||
| 180 | let mut cov_buf = vec![0u8; px_count]; | ||
| 181 | let mut scratch = zeno::Scratch::new(); | ||
| 182 | let mut shape_counter = 0u32; | ||
| 183 | rasterize_shape_tree_f32(tree, dims, &[], &mut shape_counter, &mut accum, &mut cov_buf, &mut scratch); | ||
| 184 | for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) { | ||
| 185 | dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 186 | dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 187 | dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 188 | dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8; | ||
| 189 | } | ||
| 190 | out | ||
| 191 | } | ||
crates/engine/src/eval/shapes/tests.rs created+746| ... | @@ -0,0 +1,746 @@ | ||
| 1 | use super::*; | ||
| 2 | use crate::Engine; | ||
| 3 | |||
| 4 | #[test] | ||
| 5 | fn test_s_render_ngon_transform_merge_and_boolean() { | ||
| 6 | let src = r#"Composition { | ||
| 7 | CurrentTime = 0, | ||
| 8 | RenderRange = { 0, 1 }, | ||
| 9 | GlobalRange = { 0, 1 }, | ||
| 10 | Tools = ordered() { | ||
| 11 | NGon1 = sNGon { | ||
| 12 | Inputs = { | ||
| 13 | Sides = Input { Value = 6, }, | ||
| 14 | Width = Input { Value = 0.4, }, | ||
| 15 | Red = Input { Value = 1.0, }, | ||
| 16 | Green = Input { Value = 0.0, }, | ||
| 17 | Blue = Input { Value = 0.0, }, | ||
| 18 | }, | ||
| 19 | }, | ||
| 20 | XF1 = sTransform { | ||
| 21 | Inputs = { | ||
| 22 | XOffset = Input { Value = -0.2, }, | ||
| 23 | YOffset = Input { Value = 0.0, }, | ||
| 24 | XSize = Input { Value = 1.0, }, | ||
| 25 | YSize = Input { Value = 1.0, }, | ||
| 26 | ZRotation = Input { Value = 15.0, }, | ||
| 27 | Input = Input { SourceOp = "NGon1", Source = "Output", }, | ||
| 28 | }, | ||
| 29 | }, | ||
| 30 | Rect1 = sRectangle { | ||
| 31 | Inputs = { | ||
| 32 | Width = Input { Value = 0.3, }, | ||
| 33 | Height = Input { Value = 0.3, }, | ||
| 34 | CornerRadius = Input { Value = 0.05, }, | ||
| 35 | Translate = Input { Value = { 0.0, 0.0 }, }, | ||
| 36 | ["Translate.X"] = Input { Value = 0.2, }, | ||
| 37 | Red = Input { Value = 0.0, }, | ||
| 38 | Green = Input { Value = 0.0, }, | ||
| 39 | Blue = Input { Value = 1.0, }, | ||
| 40 | }, | ||
| 41 | }, | ||
| 42 | Merge1 = sMerge { | ||
| 43 | Inputs = { | ||
| 44 | Input1 = Input { SourceOp = "XF1", Source = "Output", }, | ||
| 45 | Input2 = Input { SourceOp = "Rect1", Source = "Output", }, | ||
| 46 | }, | ||
| 47 | }, | ||
| 48 | Render1 = sRender { | ||
| 49 | Inputs = { | ||
| 50 | Width = Input { Value = 128, }, | ||
| 51 | Height = Input { Value = 128, }, | ||
| 52 | Input = Input { SourceOp = "Merge1", Source = "Output", }, | ||
| 53 | }, | ||
| 54 | }, | ||
| 55 | }, | ||
| 56 | }"#; | ||
| 57 | let comp = Comp::from_fusion_str(src).expect("parse sRender comp"); | ||
| 58 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 59 | return; | ||
| 60 | }; | ||
| 61 | let render_id = comp.find_node("Render1").unwrap(); | ||
| 62 | let (tex, stats) = eng.evaluate(&comp, render_id, 0.0); | ||
| 63 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | ||
| 64 | assert_eq!(tex.size, [128, 128]); | ||
| 65 | let px = eng.readback_rgba(&tex).expect("readback sRender"); | ||
| 66 | |||
| 67 | // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red | ||
| 68 | let left = (64 * 128 + 38) * 4; | ||
| 69 | assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]); | ||
| 70 | // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue | ||
| 71 | let right = (64 * 128 + 90) * 4; | ||
| 72 | assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]); | ||
| 73 | // Top-left corner (0, 0) should be transparent | ||
| 74 | assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent"); | ||
| 75 | } | ||
| 76 | |||
| 77 | #[test] | ||
| 78 | fn test_s_boolean_uses_own_color_and_subtract_xor() { | ||
| 79 | let src = r#"Composition { | ||
| 80 | CurrentTime = 0, | ||
| 81 | RenderRange = { 0, 1 }, | ||
| 82 | GlobalRange = { 0, 1 }, | ||
| 83 | Tools = ordered() { | ||
| 84 | NGon1 = sNGon { | ||
| 85 | Inputs = { | ||
| 86 | Sides = Input { Value = 5, }, | ||
| 87 | Width = Input { Value = 0.5, }, | ||
| 88 | Height = Input { Value = 0.5, }, | ||
| 89 | Red = Input { Value = 1.0, }, | ||
| 90 | Green = Input { Value = 0.0, }, | ||
| 91 | Blue = Input { Value = 0.0, }, | ||
| 92 | }, | ||
| 93 | }, | ||
| 94 | Rect1 = sRectangle { | ||
| 95 | Inputs = { | ||
| 96 | Width = Input { Value = 0.35, }, | ||
| 97 | Height = Input { Value = 0.35, }, | ||
| 98 | ["Translate.X"] = Input { Value = 0.18, }, | ||
| 99 | Red = Input { Value = 0.0, }, | ||
| 100 | Green = Input { Value = 1.0, }, | ||
| 101 | Blue = Input { Value = 0.0, }, | ||
| 102 | }, | ||
| 103 | }, | ||
| 104 | BoolSub = sBoolean { | ||
| 105 | Inputs = { | ||
| 106 | Operation = Input { Value = FuID { "Subtract" }, }, | ||
| 107 | Input1 = Input { SourceOp = "Rect1", Source = "Output", }, | ||
| 108 | Input2 = Input { SourceOp = "NGon1", Source = "Output", }, | ||
| 109 | }, | ||
| 110 | }, | ||
| 111 | BoolXor = sBoolean { | ||
| 112 | Inputs = { | ||
| 113 | Operation = Input { Value = FuID { "Xor" }, }, | ||
| 114 | Input1 = Input { SourceOp = "NGon1", Source = "Output", }, | ||
| 115 | Input2 = Input { SourceOp = "Rect1", Source = "Output", }, | ||
| 116 | }, | ||
| 117 | }, | ||
| 118 | RSub = sRender { | ||
| 119 | Inputs = { | ||
| 120 | Width = Input { Value = 128, }, | ||
| 121 | Height = Input { Value = 128, }, | ||
| 122 | Input = Input { SourceOp = "BoolSub", Source = "Output", }, | ||
| 123 | }, | ||
| 124 | }, | ||
| 125 | RXor = sRender { | ||
| 126 | Inputs = { | ||
| 127 | Width = Input { Value = 128, }, | ||
| 128 | Height = Input { Value = 128, }, | ||
| 129 | Input = Input { SourceOp = "BoolXor", Source = "Output", }, | ||
| 130 | }, | ||
| 131 | }, | ||
| 132 | }, | ||
| 133 | }"#; | ||
| 134 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 135 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 136 | return; | ||
| 137 | }; | ||
| 138 | let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0); | ||
| 139 | let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0); | ||
| 140 | let px_sub = eng.readback_rgba(&tex_sub).unwrap(); | ||
| 141 | let px_xor = eng.readback_rgba(&tex_xor).unwrap(); | ||
| 142 | |||
| 143 | // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white! | ||
| 144 | let rect_only = (64 * 128 + 102) * 4; | ||
| 145 | assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]); | ||
| 146 | assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]); | ||
| 147 | |||
| 148 | // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent! | ||
| 149 | let overlap = (64 * 128 + 77) * 4; | ||
| 150 | assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]); | ||
| 151 | assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]); | ||
| 152 | |||
| 153 | // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor! | ||
| 154 | let ngon_only = (64 * 128 + 54) * 4; | ||
| 155 | assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]); | ||
| 156 | } | ||
| 157 | |||
| 158 | #[test] | ||
| 159 | fn test_s_boolean_operation_names_and_missing_inputs() { | ||
| 160 | let boolean = |name: &str, op: &str, inputs: &str| { | ||
| 161 | format!( | ||
| 162 | r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }}, | ||
| 163 | R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }}, | ||
| 164 | Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"# | ||
| 165 | ) | ||
| 166 | }; | ||
| 167 | let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; | ||
| 168 | let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#; | ||
| 169 | let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; | ||
| 170 | let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#); | ||
| 171 | let src = format!( | ||
| 172 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ | ||
| 173 | Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }}, | ||
| 174 | Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }}, | ||
| 175 | Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }}, | ||
| 176 | {} {} {} {} {} {} | ||
| 177 | }} }}"#, | ||
| 178 | boolean("Inter", &fu("Intersection"), both), | ||
| 179 | boolean("Default", "", both), | ||
| 180 | boolean("Unknown", &fu("Intersect"), both), | ||
| 181 | boolean("SubFirst", &fu("Subtract"), first), | ||
| 182 | boolean("SubSecond", &fu("Subtract"), second), | ||
| 183 | boolean("UnionBoth", &fu("Union"), both), | ||
| 184 | ); | ||
| 185 | let comp = Comp::from_fusion_str(&src).unwrap(); | ||
| 186 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 187 | return; | ||
| 188 | }; | ||
| 189 | let mut px = |name: &str, x: usize| { | ||
| 190 | let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0); | ||
| 191 | let rgba = eng.readback_rgba(&tex).unwrap(); | ||
| 192 | let i = (64 * 128 + x) * 4; | ||
| 193 | [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] | ||
| 194 | }; | ||
| 195 | let white = [255; 4]; | ||
| 196 | let empty = [0; 4]; | ||
| 197 | // x=64 is inside both shapes, x=90 is inside only the rectangle. | ||
| 198 | assert_eq!(px("Inter", 64), white); | ||
| 199 | assert_eq!(px("Inter", 90), empty); | ||
| 200 | assert_eq!(px("Default", 64), white, "Operation defaults to Intersection"); | ||
| 201 | assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing"); | ||
| 202 | assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color"); | ||
| 203 | assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing"); | ||
| 204 | assert_eq!(px("UnionBoth", 90), white); | ||
| 205 | } | ||
| 206 | |||
| 207 | #[test] | ||
| 208 | fn test_s_grid() { | ||
| 209 | let src = r#"{ | ||
| 210 | Tools = ordered() { | ||
| 211 | El1 = sEllipse { | ||
| 212 | Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, | ||
| 213 | }, | ||
| 214 | Gr1 = sGrid { | ||
| 215 | Inputs = { | ||
| 216 | Input = Input { SourceOp = "El1", Source = "Output", }, | ||
| 217 | CellsX = Input { Value = 3, }, | ||
| 218 | CellsY = Input { Value = 3, }, | ||
| 219 | XOffset = Input { Value = 0.25, }, | ||
| 220 | YOffset = Input { Value = 0.25, }, | ||
| 221 | }, | ||
| 222 | }, | ||
| 223 | SR1 = sRender { | ||
| 224 | Inputs = { | ||
| 225 | Width = Input { Value = 64, }, | ||
| 226 | Height = Input { Value = 64, }, | ||
| 227 | Input = Input { SourceOp = "Gr1", Source = "Output", }, | ||
| 228 | }, | ||
| 229 | }, | ||
| 230 | }, | ||
| 231 | }"#; | ||
| 232 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 233 | let Ok(mut eng) = Engine::new_headless() else { return; }; | ||
| 234 | let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0); | ||
| 235 | let px_sr = eng.readback_rgba(&t_sr).unwrap(); | ||
| 236 | assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]); | ||
| 237 | assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]); | ||
| 238 | assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]); | ||
| 239 | } | ||
| 240 | |||
| 241 | #[test] | ||
| 242 | fn test_giant_rotated_shapes_clip_instead_of_hanging_and_alpha_stays_unpremultiplied() { | ||
| 243 | let src = r#"Composition { | ||
| 244 | CurrentTime = 0, | ||
| 245 | RenderRange = { 0, 1 }, | ||
| 246 | GlobalRange = { 0, 1 }, | ||
| 247 | Tools = ordered() { | ||
| 248 | NG = sNGon { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Alpha = Input { Value = 0.25, }, Opacity = Input { Value = 0.5, }, Blue = Input { Value = 0.5, }, }, }, | ||
| 249 | Rect = sRectangle { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Angle = Input { Value = 33, }, }, }, | ||
| 250 | SRN = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "NG", Source = "Output", }, }, }, | ||
| 251 | SRR = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, | ||
| 252 | }, | ||
| 253 | }"#; | ||
| 254 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 255 | let Ok(mut eng) = Engine::new_headless() else { return; }; | ||
| 256 | let (t, _) = eng.evaluate(&comp, comp.find_node("SRN").unwrap(), 0.0); | ||
| 257 | let px = eng.readback_rgba(&t).unwrap(); | ||
| 258 | let mid = (16 * 32 + 16) * 4; | ||
| 259 | assert_eq!(&px[mid..mid + 4], &[128, 128, 64, 32], "Opacity scales RGBA, Alpha scales alpha only"); | ||
| 260 | let (t, _) = eng.evaluate(&comp, comp.find_node("SRR").unwrap(), 0.0); | ||
| 261 | let px = eng.readback_rgba(&t).unwrap(); | ||
| 262 | assert_eq!(&px[mid..mid + 4], &[255, 255, 255, 255]); | ||
| 263 | assert_eq!(&px[0..4], &[255, 255, 255, 255], "giant rotated rectangle covers the corner"); | ||
| 264 | } | ||
| 265 | |||
| 266 | #[test] | ||
| 267 | fn s_outline_negative_thickness_s_boolean_keep_style_and_s_render_blend() { | ||
| 268 | let src = r#"Composition { | ||
| 269 | CurrentTime = 0, | ||
| 270 | RenderRange = { 0, 1 }, | ||
| 271 | GlobalRange = { 0, 1 }, | ||
| 272 | Tools = ordered() { | ||
| 273 | R1 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Red = Input { Value = 1.0, }, Green = Input { Value = 0.0, }, Blue = Input { Value = 0.0, }, }, }, | ||
| 274 | R2 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Blue = Input { Value = 1.0, }, }, }, | ||
| 275 | OutNeg = sOutline { Inputs = { Input = Input { SourceOp = "R1", Source = "Output", }, Thickness = Input { Value = -0.05, }, }, }, | ||
| 276 | SROutNeg = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "OutNeg", Source = "Output", }, }, }, | ||
| 277 | BoolKeep = sBoolean { Inputs = { | ||
| 278 | Input1 = Input { SourceOp = "R1", Source = "Output", }, | ||
| 279 | Input2 = Input { SourceOp = "R2", Source = "Output", }, | ||
| 280 | Operation = Input { Value = FuID { "Intersection" }, }, | ||
| 281 | StyleMode = Input { Value = FuID { "Keep" }, }, | ||
| 282 | Opacity = Input { Value = 0.2, }, | ||
| 283 | Green = Input { Value = 1.0, }, | ||
| 284 | }, }, | ||
| 285 | SRBool = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Blend = Input { Value = 0.2, }, Input = Input { SourceOp = "BoolKeep", Source = "Output", }, }, }, | ||
| 286 | }, | ||
| 287 | }"#; | ||
| 288 | let comp = Comp::from_fusion_str(src).unwrap(); | ||
| 289 | let Ok(mut eng) = Engine::new_headless() else { return; }; | ||
| 290 | let (t_out, _) = eng.evaluate(&comp, comp.find_node("SROutNeg").unwrap(), 0.0); | ||
| 291 | let px_out = eng.readback_rgba(&t_out).unwrap(); | ||
| 292 | assert!(px_out.iter().all(|&b| b == 0), "negative sOutline thickness should render empty"); | ||
| 293 | |||
| 294 | let (t_bool, _) = eng.evaluate(&comp, comp.find_node("SRBool").unwrap(), 0.0); | ||
| 295 | let px_bool = eng.readback_rgba(&t_bool).unwrap(); | ||
| 296 | let mid = (16 * 32 + 16) * 4; | ||
| 297 | assert_eq!(&px_bool[mid..mid + 4], &[255, 0, 0, 255], "sBoolean Keep preserves Input1 style ignoring Opacity, and sRender ignores Blend"); | ||
| 298 | } | ||
| 299 | |||
| 300 | #[test] | ||
| 301 | fn test_s_star_points_depth_rotation_and_outline() { | ||
| 302 | let src = r#"Composition { | ||
| 303 | CurrentTime = 0, | ||
| 304 | RenderRange = { 0, 1 }, | ||
| 305 | GlobalRange = { 0, 1 }, | ||
| 306 | Tools = ordered() { | ||
| 307 | Star5 = sStar { | ||
| 308 | Inputs = { | ||
| 309 | Points = Input { Value = 5, }, | ||
| 310 | Depth = Input { Value = 0.5, }, | ||
| 311 | Width = Input { Value = 0.6, }, | ||
| 312 | Height = Input { Value = 0.6, }, | ||
| 313 | Red = Input { Value = 1.0, }, | ||
| 314 | Green = Input { Value = 0.5, }, | ||
| 315 | Blue = Input { Value = 0.0, }, | ||
| 316 | }, | ||
| 317 | }, | ||
| 318 | StarOutline = sStar { | ||
| 319 | Inputs = { | ||
| 320 | NumberOfPoints = Input { Value = 6, }, | ||
| 321 | Depth = Input { Value = 0.4, }, | ||
| 322 | Width = Input { Value = 0.6, }, | ||
| 323 | Height = Input { Value = 0.6, }, | ||
| 324 | Solid = Input { Value = 0, }, | ||
| 325 | BorderWidth = Input { Value = 0.04, }, | ||
| 326 | CornerRadius = Input { Value = 0.02, }, | ||
| 327 | ZRotation = Input { Value = 30.0, }, | ||
| 328 | }, | ||
| 329 | }, | ||
| 330 | SRFill = sRender { | ||
| 331 | Inputs = { | ||
| 332 | Width = Input { Value = 64, }, | ||
| 333 | Height = Input { Value = 64, }, | ||
| 334 | Input = Input { SourceOp = "Star5", Source = "Output", }, | ||
| 335 | }, | ||
| 336 | }, | ||
| 337 | SROutline = sRender { | ||
| 338 | Inputs = { | ||
| 339 | Width = Input { Value = 64, }, | ||
| 340 | Height = Input { Value = 64, }, | ||
| 341 | Input = Input { SourceOp = "StarOutline", Source = "Output", }, | ||
| 342 | }, | ||
| 343 | }, | ||
| 344 | }, | ||
| 345 | }"#; | ||
| 346 | let comp = Comp::from_fusion_str(src).expect("parse sStar comp"); | ||
| 347 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 348 | |||
| 349 | let (tf, sf) = eng.evaluate(&comp, comp.find_node("SRFill").unwrap(), 0.0); | ||
| 350 | assert!(sf.unsupported_nodes.is_empty()); | ||
| 351 | let pf = eng.readback_rgba(&tf).unwrap(); | ||
| 352 | let px = |buf: &[u8], x: usize, y: usize| -> [u8; 4] { | ||
| 353 | let i = (y * 64 + x) * 4; | ||
| 354 | [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] | ||
| 355 | }; | ||
| 356 | // Center (32, 32) is solid orange. | ||
| 357 | let ctr = px(&pf, 32, 32); | ||
| 358 | assert!(ctr[0] > 240 && (ctr[1] as i32 - 128).abs() <= 4 && ctr[2] < 5 && ctr[3] == 255, "center={ctr:?}"); | ||
| 359 | // Rightmost outer tip at +X (r = 0.30 -> x ~ 50, y = 32) is covered! | ||
| 360 | assert!(px(&pf, 49, 32)[3] > 200, "outer tip at +X must be covered"); | ||
| 361 | // Opposite -X valley for odd 5-point star is at r = 0.15 (x ~ 22.4): x=24 inside, x=15 outside! | ||
| 362 | assert!(px(&pf, 24, 32)[3] > 200, "inner valley interior must be covered"); | ||
| 363 | assert_eq!(px(&pf, 15, 32)[3], 0, "outside -X inner valley must be empty"); | ||
| 364 | |||
| 365 | // Outline mode: hollow center, non-empty stroke ring. | ||
| 366 | let (to, _) = eng.evaluate(&comp, comp.find_node("SROutline").unwrap(), 0.0); | ||
| 367 | let po = eng.readback_rgba(&to).unwrap(); | ||
| 368 | assert_eq!(px(&po, 32, 32)[3], 0, "outline sStar center must be hollow"); | ||
| 369 | let lit_px = po.chunks_exact(4).filter(|c| c[3] > 127).count(); | ||
| 370 | assert!(lit_px > 50, "outline sStar should render visible stroke pixels, got {lit_px}"); | ||
| 371 | } | ||
| 372 | |||
| 373 | #[test] | ||
| 374 | fn test_s_duplicate_cumulative_transform_and_time_offset() { | ||
| 375 | let src = r#"Composition { | ||
| 376 | CurrentTime = 0, | ||
| 377 | RenderRange = { 0, 10 }, | ||
| 378 | GlobalRange = { 0, 10 }, | ||
| 379 | Tools = ordered() { | ||
| 380 | AnimRed = BezierSpline { | ||
| 381 | KeyFrames = { | ||
| 382 | [0] = { 0.0, Flags = { Linear = true } }, | ||
| 383 | [10] = { 1.0, Flags = { Linear = true } }, | ||
| 384 | }, | ||
| 385 | }, | ||
| 386 | Dot = sRectangle { | ||
| 387 | Inputs = { | ||
| 388 | Width = Input { Value = 0.1, }, | ||
| 389 | Height = Input { Value = 0.1, }, | ||
| 390 | Red = Input { SourceOp = "AnimRed", Source = "Value", }, | ||
| 391 | Green = Input { Value = 0.0, }, | ||
| 392 | Blue = Input { Value = 1.0, }, | ||
| 393 | }, | ||
| 394 | }, | ||
| 395 | Dup = sDuplicate { | ||
| 396 | Inputs = { | ||
| 397 | Input = Input { SourceOp = "Dot", Source = "Output", }, | ||
| 398 | Copies = Input { Value = 3, }, | ||
| 399 | XOffset = Input { Value = 0.2, }, | ||
| 400 | YOffset = Input { Value = 0.0, }, | ||
| 401 | XSize = Input { Value = 1.0, }, | ||
| 402 | YSize = Input { Value = 1.0, }, | ||
| 403 | ZRotation = Input { Value = 0.0, }, | ||
| 404 | TimeOffset = Input { Value = 5.0, }, | ||
| 405 | }, | ||
| 406 | }, | ||
| 407 | DupRot = sDuplicate { | ||
| 408 | Inputs = { | ||
| 409 | Input = Input { SourceOp = "Dot", Source = "Output", }, | ||
| 410 | Copies = Input { Value = 4, }, | ||
| 411 | ZRotation = Input { Value = 90.0, }, | ||
| 412 | XPivot = Input { Value = 0.2, }, | ||
| 413 | YPivot = Input { Value = 0.0, }, | ||
| 414 | }, | ||
| 415 | }, | ||
| 416 | SR = sRender { | ||
| 417 | Inputs = { | ||
| 418 | Width = Input { Value = 128, }, | ||
| 419 | Height = Input { Value = 128, }, | ||
| 420 | Input = Input { SourceOp = "Dup", Source = "Output", }, | ||
| 421 | }, | ||
| 422 | }, | ||
| 423 | SRRot = sRender { | ||
| 424 | Inputs = { | ||
| 425 | Width = Input { Value = 128, }, | ||
| 426 | Height = Input { Value = 128, }, | ||
| 427 | Input = Input { SourceOp = "DupRot", Source = "Output", }, | ||
| 428 | }, | ||
| 429 | }, | ||
| 430 | }, | ||
| 431 | }"#; | ||
| 432 | let comp = Comp::from_fusion_str(src).expect("parse sDuplicate comp"); | ||
| 433 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 434 | |||
| 435 | let (tex, stats) = eng.evaluate(&comp, comp.find_node("SR").unwrap(), 0.0); | ||
| 436 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | ||
| 437 | let buf = eng.readback_rgba(&tex).unwrap(); | ||
| 438 | let sample = |x: usize, y: usize| -> [u8; 4] { | ||
| 439 | let i = (y * 128 + x) * 4; | ||
| 440 | [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] | ||
| 441 | }; | ||
| 442 | // Copy 0 at x=0.0 -> px=64 (t=0 -> Red=0, Blue=255) | ||
| 443 | let c0 = sample(64, 64); | ||
| 444 | assert!(c0[0] < 5 && c0[2] > 250 && c0[3] == 255, "copy0={c0:?}"); | ||
| 445 | // Copy 1 at x=+0.2 -> px=90 (t=5 -> Red~128, Blue=255) | ||
| 446 | let c1 = sample(90, 64); | ||
| 447 | assert!((c1[0] as i32 - 128).abs() <= 4 && c1[2] > 250 && c1[3] == 255, "copy1={c1:?}"); | ||
| 448 | // Copy 2 at x=+0.4 -> px=115 (t=10 -> Red=255, Blue=255) | ||
| 449 | let c2 = sample(115, 64); | ||
| 450 | assert!(c2[0] > 250 && c2[2] > 250 && c2[3] == 255, "copy2={c2:?}"); | ||
| 451 | // Left side should remain transparent | ||
| 452 | assert_eq!(sample(20, 64)[3], 0); | ||
| 453 | |||
| 454 | // Pivot rotation check: copy 0 at (0,0), copy 1 rotated 90 deg CCW around (0.2, 0) -> (0.2, -0.2) -> px=(90, 90) | ||
| 455 | let (tex_r, _) = eng.evaluate(&comp, comp.find_node("SRRot").unwrap(), 0.0); | ||
| 456 | let buf_r = eng.readback_rgba(&tex_r).unwrap(); | ||
| 457 | assert_eq!(buf_r[(64 * 128 + 64) * 4 + 3], 255, "rot copy0 at origin"); | ||
| 458 | assert_eq!(buf_r[(90 * 128 + 90) * 4 + 3], 255, "rot copy1 at (0.2, -0.2)"); | ||
| 459 | assert_eq!(buf_r[(64 * 128 + 115) * 4 + 3], 255, "rot copy2 at (0.4, 0.0)"); | ||
| 460 | assert_eq!(buf_r[(38 * 128 + 90) * 4 + 3], 255, "rot copy3 at (0.2, +0.2)"); | ||
| 461 | } | ||
| 462 | |||
| 463 | #[test] | ||
| 464 | fn test_s_jitter_deterministic_seed_smoothness_and_per_shape() { | ||
| 465 | let src = r#"Composition { | ||
| 466 | CurrentTime = 0, | ||
| 467 | RenderRange = { 0, 1 }, | ||
| 468 | GlobalRange = { 0, 1 }, | ||
| 469 | Tools = ordered() { | ||
| 470 | Rect = sRectangle { | ||
| 471 | Inputs = { Width = Input { Value = 0.4, }, Height = Input { Value = 0.4, }, }, | ||
| 472 | }, | ||
| 473 | JitA = sJitter { | ||
| 474 | Inputs = { | ||
| 475 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 476 | XAmount = Input { Value = 0.08, }, | ||
| 477 | YAmount = Input { Value = 0.08, }, | ||
| 478 | Seed = Input { Value = 7, }, | ||
| 479 | Smoothness = Input { Value = 0.0, }, | ||
| 480 | }, | ||
| 481 | }, | ||
| 482 | JitB = sJitter { | ||
| 483 | Inputs = { | ||
| 484 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 485 | XAmount = Input { Value = 0.08, }, | ||
| 486 | YAmount = Input { Value = 0.08, }, | ||
| 487 | Seed = Input { Value = 99, }, | ||
| 488 | Smoothness = Input { Value = 0.0, }, | ||
| 489 | }, | ||
| 490 | }, | ||
| 491 | JitSmooth = sJitter { | ||
| 492 | Inputs = { | ||
| 493 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 494 | XAmount = Input { Value = 0.08, }, | ||
| 495 | YAmount = Input { Value = 0.08, }, | ||
| 496 | Seed = Input { Value = 7, }, | ||
| 497 | Smoothness = Input { Value = 2.0, }, | ||
| 498 | }, | ||
| 499 | }, | ||
| 500 | SRef = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, | ||
| 501 | SJA = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "JitA", Source = "Output", }, }, }, | ||
| 502 | SJB = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "JitB", Source = "Output", }, }, }, | ||
| 503 | SJS = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "JitSmooth", Source = "Output", }, }, }, | ||
| 504 | }, | ||
| 505 | }"#; | ||
| 506 | let comp = Comp::from_fusion_str(src).expect("parse sJitter comp"); | ||
| 507 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 508 | |||
| 509 | let (t_ref, _) = eng.evaluate(&comp, comp.find_node("SRef").unwrap(), 0.0); | ||
| 510 | let (t_a1, s_a) = eng.evaluate(&comp, comp.find_node("SJA").unwrap(), 0.0); | ||
| 511 | let (t_b, _) = eng.evaluate(&comp, comp.find_node("SJB").unwrap(), 0.0); | ||
| 512 | let (t_sm, _) = eng.evaluate(&comp, comp.find_node("SJS").unwrap(), 0.0); | ||
| 513 | assert!(s_a.unsupported_nodes.is_empty()); | ||
| 514 | |||
| 515 | let p_ref = eng.readback_rgba(&t_ref).unwrap(); | ||
| 516 | let p_a1 = eng.readback_rgba(&t_a1).unwrap(); | ||
| 517 | let p_b = eng.readback_rgba(&t_b).unwrap(); | ||
| 518 | let p_sm = eng.readback_rgba(&t_sm).unwrap(); | ||
| 519 | |||
| 520 | assert_ne!(p_ref, p_a1, "sJitter must deform the rectangle"); | ||
| 521 | assert_ne!(p_a1, p_b, "different Seed must produce different jitter"); | ||
| 522 | assert_ne!(p_a1, p_sm, "Smoothness > 0 must alter contour jitter"); | ||
| 523 | |||
| 524 | // Re-evaluating with a fresh engine must be bit-identical (deterministic). | ||
| 525 | let Ok(mut eng2) = Engine::new_headless() else { return }; | ||
| 526 | let (t_a2, _) = eng2.evaluate(&comp, comp.find_node("SJA").unwrap(), 0.0); | ||
| 527 | assert_eq!(p_a1, eng2.readback_rgba(&t_a2).unwrap()); | ||
| 528 | } | ||
| 529 | |||
| 530 | #[test] | ||
| 531 | fn test_s_expand_inflate_deflate_joins_and_collapse() { | ||
| 532 | let src = r#"Composition { | ||
| 533 | CurrentTime = 0, | ||
| 534 | RenderRange = { 0, 1 }, | ||
| 535 | GlobalRange = { 0, 1 }, | ||
| 536 | Tools = ordered() { | ||
| 537 | Rect = sRectangle { | ||
| 538 | Inputs = { Width = Input { Value = 0.3, }, Height = Input { Value = 0.3, }, }, | ||
| 539 | }, | ||
| 540 | ExpOut = sExpand { | ||
| 541 | Inputs = { | ||
| 542 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 543 | Amount = Input { Value = 0.1, }, | ||
| 544 | JoinStyle = Input { Value = 2, }, | ||
| 545 | }, | ||
| 546 | }, | ||
| 547 | ExpBevel = sExpand { | ||
| 548 | Inputs = { | ||
| 549 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 550 | Amount = Input { Value = 0.1, }, | ||
| 551 | JoinStyle = Input { Value = 0, }, | ||
| 552 | }, | ||
| 553 | }, | ||
| 554 | ExpIn = sExpand { | ||
| 555 | Inputs = { | ||
| 556 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 557 | Distance = Input { Value = -0.075, }, | ||
| 558 | }, | ||
| 559 | }, | ||
| 560 | ExpCollapse = sExpand { | ||
| 561 | Inputs = { | ||
| 562 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 563 | Amount = Input { Value = -0.25, }, | ||
| 564 | }, | ||
| 565 | }, | ||
| 566 | SRef = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, | ||
| 567 | SOut = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpOut", Source = "Output", }, }, }, | ||
| 568 | SBevel = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpBevel", Source = "Output", }, }, }, | ||
| 569 | SIn = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpIn", Source = "Output", }, }, }, | ||
| 570 | SCol = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpCollapse", Source = "Output", }, }, }, | ||
| 571 | }, | ||
| 572 | }"#; | ||
| 573 | let comp = Comp::from_fusion_str(src).expect("parse sExpand comp"); | ||
| 574 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 575 | |||
| 576 | let count_lit = |buf: &[u8]| buf.chunks_exact(4).filter(|c| c[3] > 127).count(); | ||
| 577 | let (t_ref, _) = eng.evaluate(&comp, comp.find_node("SRef").unwrap(), 0.0); | ||
| 578 | let (t_out, s_out) = eng.evaluate(&comp, comp.find_node("SOut").unwrap(), 0.0); | ||
| 579 | let (t_bev, _) = eng.evaluate(&comp, comp.find_node("SBevel").unwrap(), 0.0); | ||
| 580 | let (t_in, _) = eng.evaluate(&comp, comp.find_node("SIn").unwrap(), 0.0); | ||
| 581 | let (t_col, _) = eng.evaluate(&comp, comp.find_node("SCol").unwrap(), 0.0); | ||
| 582 | assert!(s_out.unsupported_nodes.is_empty()); | ||
| 583 | |||
| 584 | let lit_ref = count_lit(&eng.readback_rgba(&t_ref).unwrap()); // ~30x30 = 900 | ||
| 585 | let lit_out = count_lit(&eng.readback_rgba(&t_out).unwrap()); // ~50x50 = 2500 | ||
| 586 | let lit_bev = count_lit(&eng.readback_rgba(&t_bev).unwrap()); // ~2500 - 4*50 = 2300 | ||
| 587 | let lit_in = count_lit(&eng.readback_rgba(&t_in).unwrap()); // ~15x15 = 225 | ||
| 588 | let lit_col = count_lit(&eng.readback_rgba(&t_col).unwrap()); // 0 | ||
| 589 | |||
| 590 | assert!(lit_out > lit_ref * 2, "expanded area should exceed 2x original (ref={lit_ref}, out={lit_out})"); | ||
| 591 | assert!(lit_bev < lit_out && lit_bev > lit_ref * 2, "bevel join should trim miter corners (bev={lit_bev}, out={lit_out})"); | ||
| 592 | assert!(lit_in > 100 && lit_in < lit_ref / 2, "deflated area should shrink substantially (ref={lit_ref}, in={lit_in})"); | ||
| 593 | assert_eq!(lit_col, 0, "over-deflated shape must collapse cleanly to empty"); | ||
| 594 | } | ||
| 595 | |||
| 596 | #[test] | ||
| 597 | fn test_s_offset_translate_contour_and_path_position() { | ||
| 598 | let src = r#"Composition { | ||
| 599 | CurrentTime = 0, | ||
| 600 | RenderRange = { 0, 1 }, | ||
| 601 | GlobalRange = { 0, 1 }, | ||
| 602 | Tools = ordered() { | ||
| 603 | Rect = sRectangle { | ||
| 604 | Inputs = { Width = Input { Value = 0.2, }, Height = Input { Value = 0.2, }, }, | ||
| 605 | }, | ||
| 606 | OffXY = sOffset { | ||
| 607 | Inputs = { | ||
| 608 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 609 | XOffset = Input { Value = 0.25, }, | ||
| 610 | YOffset = Input { Value = -0.15, }, | ||
| 611 | }, | ||
| 612 | }, | ||
| 613 | OffContour = sOffset { | ||
| 614 | Inputs = { | ||
| 615 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 616 | Offset = Input { Value = 0.08, }, | ||
| 617 | }, | ||
| 618 | }, | ||
| 619 | OffPos = sOffset { | ||
| 620 | Inputs = { | ||
| 621 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 622 | Position = Input { Value = 0.5, }, | ||
| 623 | }, | ||
| 624 | }, | ||
| 625 | Out0 = sOutline { | ||
| 626 | Inputs = { | ||
| 627 | Input = Input { SourceOp = "Rect", Source = "Output", }, | ||
| 628 | Thickness = Input { Value = 0.04, }, | ||
| 629 | WriteLength = Input { Value = 0.25, }, | ||
| 630 | }, | ||
| 631 | }, | ||
| 632 | OutShifted = sOutline { | ||
| 633 | Inputs = { | ||
| 634 | Input = Input { SourceOp = "OffPos", Source = "Output", }, | ||
| 635 | Thickness = Input { Value = 0.04, }, | ||
| 636 | WriteLength = Input { Value = 0.25, }, | ||
| 637 | }, | ||
| 638 | }, | ||
| 639 | SXY = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "OffXY", Source = "Output", }, }, }, | ||
| 640 | SCtr = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "OffContour", Source = "Output", }, }, }, | ||
| 641 | SOut0 = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "Out0", Source = "Output", }, }, }, | ||
| 642 | SOutS = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "OutShifted", Source = "Output", }, }, }, | ||
| 643 | }, | ||
| 644 | }"#; | ||
| 645 | let comp = Comp::from_fusion_str(src).expect("parse sOffset comp"); | ||
| 646 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 647 | |||
| 648 | let (t_xy, s_xy) = eng.evaluate(&comp, comp.find_node("SXY").unwrap(), 0.0); | ||
| 649 | assert!(s_xy.unsupported_nodes.is_empty()); | ||
| 650 | let p_xy = eng.readback_rgba(&t_xy).unwrap(); | ||
| 651 | // Center shifted to (+0.25, -0.15) -> px = (75, 65); origin (50, 50) should be empty. | ||
| 652 | assert_eq!(p_xy[(65 * 100 + 75) * 4 + 3], 255, "translated rect center must be covered"); | ||
| 653 | assert_eq!(p_xy[(50 * 100 + 50) * 4 + 3], 0, "original center must be empty"); | ||
| 654 | |||
| 655 | // Scalar Offset inflates 0.2x0.2 -> 0.36x0.36 (~1296 px vs ~400 px). | ||
| 656 | let (t_ctr, _) = eng.evaluate(&comp, comp.find_node("SCtr").unwrap(), 0.0); | ||
| 657 | let lit_ctr = eng.readback_rgba(&t_ctr).unwrap().chunks_exact(4).filter(|c| c[3] > 127).count(); | ||
| 658 | assert!(lit_ctr > 900, "scalar sOffset should expand contour area, got {lit_ctr}"); | ||
| 659 | |||
| 660 | // Position=0.5 shifts the trimmed 25% outline stroke to the opposite side of the contour! | ||
| 661 | let (t_o0, _) = eng.evaluate(&comp, comp.find_node("SOut0").unwrap(), 0.0); | ||
| 662 | let (t_os, _) = eng.evaluate(&comp, comp.find_node("SOutS").unwrap(), 0.0); | ||
| 663 | let p_o0 = eng.readback_rgba(&t_o0).unwrap(); | ||
| 664 | let p_os = eng.readback_rgba(&t_os).unwrap(); | ||
| 665 | assert_ne!(p_o0, p_os, "sOffset Position must shift parametric stroke origin along the path"); | ||
| 666 | } | ||
| 667 | |||
| 668 | #[test] | ||
| 669 | fn test_s_polygon_closed_open_bezier_and_transform() { | ||
| 670 | let src = r#"Composition { | ||
| 671 | CurrentTime = 0, | ||
| 672 | RenderRange = { 0, 1 }, | ||
| 673 | GlobalRange = { 0, 1 }, | ||
| 674 | Tools = ordered() { | ||
| 675 | PolyClosed = sPolygon { | ||
| 676 | Inputs = { | ||
| 677 | Solid = Input { Value = 1, }, | ||
| 678 | Red = Input { Value = 0.0, }, | ||
| 679 | Green = Input { Value = 1.0, }, | ||
| 680 | Blue = Input { Value = 0.0, }, | ||
| 681 | Scale = Input { Value = 1.5, }, | ||
| 682 | ["Translate.X"] = Input { Value = 0.05, }, | ||
| 683 | Polyline = Input { | ||
| 684 | Value = Polyline { | ||
| 685 | Closed = true, | ||
| 686 | Points = { | ||
| 687 | { Linear = true, X = -0.2, Y = -0.2 }, | ||
| 688 | { Linear = true, X = 0.2, Y = -0.2 }, | ||
| 689 | { Linear = true, X = 0.0, Y = 0.2 }, | ||
| 690 | }, | ||
| 691 | }, | ||
| 692 | }, | ||
| 693 | }, | ||
| 694 | }, | ||
| 695 | PolyOpen = sPolygon { | ||
| 696 | Inputs = { | ||
| 697 | Solid = Input { Value = 0, }, | ||
| 698 | BorderWidth = Input { Value = 0.04, }, | ||
| 699 | Red = Input { Value = 1.0, }, | ||
| 700 | Green = Input { Value = 0.0, }, | ||
| 701 | Blue = Input { Value = 0.0, }, | ||
| 702 | Polyline = Input { | ||
| 703 | Value = Polyline { | ||
| 704 | Closed = false, | ||
| 705 | Points = { | ||
| 706 | { X = -0.35, Y = 0.0, RX = 0.1, RY = 0.2 }, | ||
| 707 | { X = 0.35, Y = 0.0, LX = -0.1, LY = 0.2 }, | ||
| 708 | }, | ||
| 709 | }, | ||
| 710 | }, | ||
| 711 | }, | ||
| 712 | }, | ||
| 713 | SRClosed = sRender { | ||
| 714 | Inputs = { | ||
| 715 | Width = Input { Value = 100, }, | ||
| 716 | Height = Input { Value = 100, }, | ||
| 717 | Input = Input { SourceOp = "PolyClosed", Source = "Output", }, | ||
| 718 | }, | ||
| 719 | }, | ||
| 720 | SROpen = sRender { | ||
| 721 | Inputs = { | ||
| 722 | Width = Input { Value = 100, }, | ||
| 723 | Height = Input { Value = 100, }, | ||
| 724 | Input = Input { SourceOp = "PolyOpen", Source = "Output", }, | ||
| 725 | }, | ||
| 726 | }, | ||
| 727 | }, | ||
| 728 | }"#; | ||
| 729 | let comp = Comp::from_fusion_str(src).expect("parse sPolygon comp"); | ||
| 730 | let Ok(mut eng) = Engine::new_headless() else { return }; | ||
| 731 | |||
| 732 | let (t_cl, s_cl) = eng.evaluate(&comp, comp.find_node("SRClosed").unwrap(), 0.0); | ||
| 733 | assert!(s_cl.unsupported_nodes.is_empty(), "unsupported: {:?}", s_cl.unsupported_nodes); | ||
| 734 | let p_cl = eng.readback_rgba(&t_cl).unwrap(); | ||
| 735 | // Triangle shifted by +0.05 -> interior at px=(55, 55) should be solid green. | ||
| 736 | let i_mid = (55 * 100 + 55) * 4; | ||
| 737 | assert_eq!(&p_cl[i_mid..i_mid + 4], &[0, 255, 0, 255]); | ||
| 738 | assert_eq!(&p_cl[0..4], &[0, 0, 0, 0]); | ||
| 739 | |||
| 740 | // Open Bezier arch arcs upward above y=0 (so y=50, x=50 is empty, while upper apex y~35, x=50 is red!). | ||
| 741 | let (t_op, _) = eng.evaluate(&comp, comp.find_node("SROpen").unwrap(), 0.0); | ||
| 742 | let p_op = eng.readback_rgba(&t_op).unwrap(); | ||
| 743 | assert_eq!(p_op[(50 * 100 + 50) * 4 + 3], 0, "open arch chord midpoint must remain hollow"); | ||
| 744 | let apex_hit = (25..45).any(|y| p_op[(y * 100 + 50) * 4] > 200 && p_op[(y * 100 + 50) * 4 + 3] > 200); | ||
| 745 | assert!(apex_hit, "open Bezier sPolygon arch apex must be stroked in red"); | ||
| 746 | } | ||
crates/engine/src/particles.rs+30-5| ... | @@ -1,8 +1,10 @@ | ... | @@ -1,8 +1,10 @@ |
| 1 | //! Fusion deterministic particle simulation & 2D rendering system. | 1 | //! Fusion deterministic particle simulation & 2D rendering system. |
| 2 | //! | 2 | //! |
| 3 | //! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`, | 3 | //! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`, |
| 4 | //! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode). | 4 | //! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pVortex`, `pFlock`, `pSpawn`, |
| 5 | //! `pChangeStyle`, `pGradientForce`, `pMerge`, and `pRender` (2D mode). | ||
| 5 | 6 | ||
| 7 | mod forces; | ||
| 6 | mod plan; | 8 | mod plan; |
| 7 | mod raster; | 9 | mod raster; |
| 8 | mod sim; | 10 | mod sim; |
| ... | @@ -11,10 +13,13 @@ mod tests; | ... | @@ -11,10 +13,13 @@ mod tests; |
| 11 | 13 | ||
| 12 | pub use plan::collect_bitmap_sources; | 14 | pub use plan::collect_bitmap_sources; |
| 13 | 15 | ||
| 16 | use std::collections::hash_map::DefaultHasher; | ||
| 14 | use std::collections::{BTreeMap, HashMap}; | 17 | use std::collections::{BTreeMap, HashMap}; |
| 18 | use std::hash::{Hash, Hasher}; | ||
| 15 | 19 | ||
| 16 | use model::{Comp, ExprEngine, NodeId}; | 20 | use model::{Comp, ExprEngine, NodeId}; |
| 17 | 21 | ||
| 22 | use forces::build_gradient_fields; | ||
| 18 | use plan::{build_particle_plan, particle_subgraph_hash}; | 23 | use plan::{build_particle_plan, particle_subgraph_hash}; |
| 19 | use raster::rasterize_particles; | 24 | use raster::rasterize_particles; |
| 20 | use sim::step_simulation; | 25 | use sim::step_simulation; |
| ... | @@ -95,6 +100,14 @@ struct SimState { | ... | @@ -95,6 +100,14 @@ struct SimState { |
| 95 | #[derive(Clone, Copy, Debug)] | 100 | #[derive(Clone, Copy, Debug)] |
| 96 | struct Particle { | 101 | struct Particle { |
| 97 | emitter_hash: u64, | 102 | emitter_hash: u64, |
| 103 | /// Particle set membership bitmask (bit 0 = Set1 .. bit 31 = Set32). | ||
| 104 | sets: u32, | ||
| 105 | /// Optional per-particle style override applied by `pChangeStyle` / `pSpawn`. | ||
| 106 | style_override: Option<ParticleStyleKind>, | ||
| 107 | /// Optional NGon sides override (0 = inherit from emitter). | ||
| 108 | ngon_sides_override: u8, | ||
| 109 | /// Optional bitmap sprite owner hash override (0 = use `emitter_hash`). | ||
| 110 | bitmap_owner_hash: u64, | ||
| 98 | pos: [f64; 3], | 111 | pos: [f64; 3], |
| 99 | vel: [f64; 3], | 112 | vel: [f64; 3], |
| 100 | rot_z: f64, | 113 | rot_z: f64, |
| ... | @@ -229,7 +242,19 @@ pub fn render_particles_2d( | ... | @@ -229,7 +242,19 @@ pub fn render_particles_2d( |
| 229 | .clamp(0.0, MAX_SIM_WINDOW as f64) as i64; | 242 | .clamp(0.0, MAX_SIM_WINDOW as f64) as i64; |
| 230 | let sim_origin = base_start.saturating_sub(pre_gen); | 243 | let sim_origin = base_start.saturating_sub(pre_gen); |
| 231 | 244 | ||
| 232 | let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); | 245 | let gradient_fields = build_gradient_fields(comp, &plan.modifiers, sprites); |
| 246 | let mut subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); | ||
| 247 | if !gradient_fields.is_empty() { | ||
| 248 | let mut h = DefaultHasher::new(); | ||
| 249 | subgraph_hash.hash(&mut h); | ||
| 250 | let mut gf_ids: Vec<NodeId> = gradient_fields.keys().copied().collect(); | ||
| 251 | gf_ids.sort_by_key(|id| id.0); | ||
| 252 | for id in gf_ids { | ||
| 253 | id.0.hash(&mut h); | ||
| 254 | gradient_fields[&id].content_hash.hash(&mut h); | ||
| 255 | } | ||
| 256 | subgraph_hash = h.finish(); | ||
| 257 | } | ||
| 233 | let key = (rnode.name.clone(), subgraph_hash); | 258 | let key = (rnode.name.clone(), subgraph_hash); |
| 234 | // Evict stale subgraph hashes for this render node while keeping other pRender entries. | 259 | // Evict stale subgraph hashes for this render node while keeping other pRender entries. |
| 235 | cache | 260 | cache |
| ... | @@ -245,7 +270,7 @@ pub fn render_particles_2d( | ... | @@ -245,7 +270,7 @@ pub fn render_particles_2d( |
| 245 | } else if target_frame > cached.current_frame { | 270 | } else if target_frame > cached.current_frame { |
| 246 | if i128::from(target_frame) - i128::from(cached.current_frame) <= i128::from(MAX_SIM_WINDOW) { | 271 | if i128::from(target_frame) - i128::from(cached.current_frame) <= i128::from(MAX_SIM_WINDOW) { |
| 247 | for f in cached.current_frame.saturating_add(1)..=target_frame { | 272 | for f in cached.current_frame.saturating_add(1)..=target_frame { |
| 248 | step_simulation(&mut cached.state, comp, &plan, f, expr); | 273 | step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); |
| 249 | maybe_record_snapshot(cached, f); | 274 | maybe_record_snapshot(cached, f); |
| 250 | } | 275 | } |
| 251 | cached.current_frame = target_frame; | 276 | cached.current_frame = target_frame; |
| ... | @@ -259,7 +284,7 @@ pub fn render_particles_2d( | ... | @@ -259,7 +284,7 @@ pub fn render_particles_2d( |
| 259 | cached.current_frame = snap_f; | 284 | cached.current_frame = snap_f; |
| 260 | if snap_f < target_frame { | 285 | if snap_f < target_frame { |
| 261 | for f in snap_f.saturating_add(1)..=target_frame { | 286 | for f in snap_f.saturating_add(1)..=target_frame { |
| 262 | step_simulation(&mut cached.state, comp, &plan, f, expr); | 287 | step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); |
| 263 | maybe_record_snapshot(cached, f); | 288 | maybe_record_snapshot(cached, f); |
| 264 | } | 289 | } |
| 265 | } | 290 | } |
| ... | @@ -284,7 +309,7 @@ pub fn render_particles_2d( | ... | @@ -284,7 +309,7 @@ pub fn render_particles_2d( |
| 284 | snapshots: BTreeMap::new(), | 309 | snapshots: BTreeMap::new(), |
| 285 | }; | 310 | }; |
| 286 | for f in sim_start..=target_frame { | 311 | for f in sim_start..=target_frame { |
| 287 | step_simulation(&mut sim.state, comp, &plan, f, expr); | 312 | step_simulation(&mut sim.state, comp, &plan, &gradient_fields, f, expr); |
| 288 | maybe_record_snapshot(&mut sim, f); | 313 | maybe_record_snapshot(&mut sim, f); |
| 289 | } | 314 | } |
| 290 | cache.entries.insert(key.clone(), sim); | 315 | cache.entries.insert(key.clone(), sim); |
crates/engine/src/particles/forces.rs created+814| ... | @@ -0,0 +1,814 @@ | ||
| 1 | //! Extended 2D particle modifiers & forces: | ||
| 2 | //! - `pVortex`: tangential swirl + radial inward/outward vortex force | ||
| 3 | //! - `pFlock`: O(N) spatial-hashed Boids cohesion, separation, and alignment steering | ||
| 4 | //! - `pSpawn`: child particle spawning from living parents (capped at `MAX_PARTICLES`) | ||
| 5 | //! - `pChangeStyle`: color/size/alpha/style modification over life or within a region | ||
| 6 | //! - `pGradientForce`: spatial luminance-gradient force from a pre-sampled 64x64 image grid | ||
| 7 | |||
| 8 | use std::collections::hash_map::DefaultHasher; | ||
| 9 | use std::collections::{HashMap, HashSet}; | ||
| 10 | use std::hash::{Hash, Hasher}; | ||
| 11 | |||
| 12 | use model::{Comp, ExprEngine, Node, NodeId}; | ||
| 13 | |||
| 14 | use super::sim::RegionSpec; | ||
| 15 | use super::{ | ||
| 16 | MAX_PARTICLES, Particle, ParticleStyleKind, SplitMix64, SpriteImage, VELOCITY_SCALE, | ||
| 17 | stable_name_hash, | ||
| 18 | }; | ||
| 19 | |||
| 20 | /// Resolution of the pre-sampled luminance gradient grid for `pGradientForce`. | ||
| 21 | const GRAD_GRID_DIM: usize = 64; | ||
| 22 | |||
| 23 | /// Maximum neighbors examined per particle in `pFlock` to guarantee O(N) worst-case runtime | ||
| 24 | /// even when all particles coincide at a single point. | ||
| 25 | const FLOCK_MAX_NEIGHBORS: usize = 32; | ||
| 26 | |||
| 27 | /// Force scale constant for `pVortex` (render widths per frame^2 at unit strength and distance). | ||
| 28 | const VORTEX_FORCE_SCALE: f64 = 1.0e-3; | ||
| 29 | |||
| 30 | /// Pre-sampled 2D spatial luminance gradient field `[dL/du, dL/dv]` in Y-up particle coordinates. | ||
| 31 | #[derive(Clone, Debug)] | ||
| 32 | pub(super) struct GradientField { | ||
| 33 | w: usize, | ||
| 34 | h: usize, | ||
| 35 | aspect: f64, | ||
| 36 | /// Interleaved `[gx, gy]` per grid cell (row 0 = top of image, row `h-1` = bottom). | ||
| 37 | grads: Vec<[f32; 2]>, | ||
| 38 | pub(super) content_hash: u64, | ||
| 39 | } | ||
| 40 | |||
| 41 | impl GradientField { | ||
| 42 | pub(super) fn from_sprite(sprite: &SpriteImage, channel: &str) -> Option<Self> { | ||
| 43 | let sw = sprite.size[0] as usize; | ||
| 44 | let sh = sprite.size[1] as usize; | ||
| 45 | if sw == 0 || sh == 0 || sprite.rgba.len() < sw.saturating_mul(sh).saturating_mul(4) { | ||
| 46 | return None; | ||
| 47 | } | ||
| 48 | let gw = sw.min(GRAD_GRID_DIM).max(2); | ||
| 49 | let gh = sh.min(GRAD_GRID_DIM).max(2); | ||
| 50 | |||
| 51 | let sample_scalar = |px: &[u8]| -> f32 { | ||
| 52 | let r = px[0] as f32 / 255.0; | ||
| 53 | let g = px[1] as f32 / 255.0; | ||
| 54 | let b = px[2] as f32 / 255.0; | ||
| 55 | let a = px[3] as f32 / 255.0; | ||
| 56 | match channel { | ||
| 57 | "Red" | "R" => r, | ||
| 58 | "Green" | "G" => g, | ||
| 59 | "Blue" | "B" => b, | ||
| 60 | "Alpha" | "A" => a, | ||
| 61 | _ => 0.2126 * r + 0.7152 * g + 0.0722 * b, | ||
| 62 | } | ||
| 63 | }; | ||
| 64 | |||
| 65 | // Downsample source image into `gw x gh` scalar luminance grid via box averaging. | ||
| 66 | let mut luma = vec![0.0_f32; gw * gh]; | ||
| 67 | for gy in 0..gh { | ||
| 68 | let y0 = gy * sh / gh; | ||
| 69 | let y1 = ((gy + 1) * sh / gh).max(y0 + 1).min(sh); | ||
| 70 | for gx in 0..gw { | ||
| 71 | let x0 = gx * sw / gw; | ||
| 72 | let x1 = ((gx + 1) * sw / gw).max(x0 + 1).min(sw); | ||
| 73 | let mut sum = 0.0_f32; | ||
| 74 | let mut cnt = 0u32; | ||
| 75 | // Sample up to a 4x4 stride inside each bin so huge 4K inputs stay instant. | ||
| 76 | let step_y = ((y1 - y0) / 4).max(1); | ||
| 77 | let step_x = ((x1 - x0) / 4).max(1); | ||
| 78 | let mut sy = y0; | ||
| 79 | while sy < y1 { | ||
| 80 | let row = sy * sw; | ||
| 81 | let mut sx = x0; | ||
| 82 | while sx < x1 { | ||
| 83 | let off = (row + sx) * 4; | ||
| 84 | sum += sample_scalar(&sprite.rgba[off..off + 4]); | ||
| 85 | cnt += 1; | ||
| 86 | sx += step_x; | ||
| 87 | } | ||
| 88 | sy += step_y; | ||
| 89 | } | ||
| 90 | luma[gy * gw + gx] = if cnt > 0 { sum / cnt as f32 } else { 0.0 }; | ||
| 91 | } | ||
| 92 | } | ||
| 93 | |||
| 94 | // Compute resolution-independent central differences: dL/du (+X right) and dL/dv (+Y up). | ||
| 95 | let mut grads = vec![[0.0_f32; 2]; gw * gh]; | ||
| 96 | let mut hasher = DefaultHasher::new(); | ||
| 97 | gw.hash(&mut hasher); | ||
| 98 | gh.hash(&mut hasher); | ||
| 99 | sw.hash(&mut hasher); | ||
| 100 | sh.hash(&mut hasher); | ||
| 101 | channel.hash(&mut hasher); | ||
| 102 | |||
| 103 | let scale_x = (gw.saturating_sub(1)) as f32; | ||
| 104 | let scale_y = (gh.saturating_sub(1)) as f32; | ||
| 105 | for gy in 0..gh { | ||
| 106 | let ym = gy.saturating_sub(1); | ||
| 107 | let yp = (gy + 1).min(gh - 1); | ||
| 108 | let dy_span = (yp - ym).max(1) as f32; | ||
| 109 | for gx in 0..gw { | ||
| 110 | let xm = gx.saturating_sub(1); | ||
| 111 | let xp = (gx + 1).min(gw - 1); | ||
| 112 | let dx_span = (xp - xm).max(1) as f32; | ||
| 113 | |||
| 114 | let dl_dx = (luma[gy * gw + xp] - luma[gy * gw + xm]) / dx_span * scale_x; | ||
| 115 | // Image row 0 is top (+Y in particle space), row gh-1 is bottom (-Y). | ||
| 116 | let dl_dy = (luma[ym * gw + gx] - luma[yp * gw + gx]) / dy_span * scale_y; | ||
| 117 | let g = [dl_dx, dl_dy]; | ||
| 118 | grads[gy * gw + gx] = g; | ||
| 119 | g[0].to_bits().hash(&mut hasher); | ||
| 120 | g[1].to_bits().hash(&mut hasher); | ||
| 121 | } | ||
| 122 | } | ||
| 123 | |||
| 124 | Some(Self { | ||
| 125 | w: gw, | ||
| 126 | h: gh, | ||
| 127 | aspect: sw as f64 / sh as f64, | ||
| 128 | grads, | ||
| 129 | content_hash: hasher.finish(), | ||
| 130 | }) | ||
| 131 | } | ||
| 132 | |||
| 133 | /// Bilinearly samples `[dL/du, dL/dv]` at particle world position `(px, py)`. | ||
| 134 | #[inline] | ||
| 135 | fn sample(&self, px: f64, py: f64) -> [f64; 2] { | ||
| 136 | let u = px + 0.5; | ||
| 137 | let v = 0.5 - py * self.aspect; | ||
| 138 | if !(-0.05..=1.05).contains(&u) || !(-0.05..=1.05).contains(&v) { | ||
| 139 | return [0.0, 0.0]; | ||
| 140 | } | ||
| 141 | let fx = u.clamp(0.0, 1.0) * (self.w - 1) as f64; | ||
| 142 | let fy = v.clamp(0.0, 1.0) * (self.h - 1) as f64; | ||
| 143 | let x0 = (fx.floor() as usize).min(self.w - 1); | ||
| 144 | let y0 = (fy.floor() as usize).min(self.h - 1); | ||
| 145 | let x1 = (x0 + 1).min(self.w - 1); | ||
| 146 | let y1 = (y0 + 1).min(self.h - 1); | ||
| 147 | let tx = fx - x0 as f64; | ||
| 148 | let ty = fy - y0 as f64; | ||
| 149 | |||
| 150 | let g00 = self.grads[y0 * self.w + x0]; | ||
| 151 | let g10 = self.grads[y0 * self.w + x1]; | ||
| 152 | let g01 = self.grads[y1 * self.w + x0]; | ||
| 153 | let g11 = self.grads[y1 * self.w + x1]; | ||
| 154 | |||
| 155 | let gx0 = g00[0] as f64 + (g10[0] as f64 - g00[0] as f64) * tx; | ||
| 156 | let gx1 = g01[0] as f64 + (g11[0] as f64 - g01[0] as f64) * tx; | ||
| 157 | let gy0 = g00[1] as f64 + (g10[1] as f64 - g00[1] as f64) * tx; | ||
| 158 | let gy1 = g01[1] as f64 + (g11[1] as f64 - g01[1] as f64) * tx; | ||
| 159 | [gx0 + (gx1 - gx0) * ty, gy0 + (gy1 - gy0) * ty] | ||
| 160 | } | ||
| 161 | } | ||
| 162 | |||
| 163 | pub(super) fn build_gradient_fields( | ||
| 164 | comp: &Comp, | ||
| 165 | modifiers: &[(NodeId, HashSet<u64>)], | ||
| 166 | sprites: &HashMap<NodeId, SpriteImage>, | ||
| 167 | ) -> HashMap<NodeId, GradientField> { | ||
| 168 | let mut fields = HashMap::new(); | ||
| 169 | for &(mod_id, _) in modifiers { | ||
| 170 | let Some(node) = comp.nodes.get(mod_id.0) else { | ||
| 171 | continue; | ||
| 172 | }; | ||
| 173 | if node.kind != "pGradientForce" { | ||
| 174 | continue; | ||
| 175 | } | ||
| 176 | let Some(sprite) = sprites.get(&mod_id) else { | ||
| 177 | continue; | ||
| 178 | }; | ||
| 179 | let channel = node.static_str("Channel").unwrap_or("Luma"); | ||
| 180 | if let Some(field) = GradientField::from_sprite(sprite, channel) { | ||
| 181 | fields.insert(mod_id, field); | ||
| 182 | } | ||
| 183 | } | ||
| 184 | fields | ||
| 185 | } | ||
| 186 | |||
| 187 | pub(super) fn parse_particle_style(s: &str) -> Option<ParticleStyleKind> { | ||
| 188 | match s { | ||
| 189 | "ParticleStylePoint" | "Point" => Some(ParticleStyleKind::Point), | ||
| 190 | "ParticleStyleBlob" | "Blob" => Some(ParticleStyleKind::Blob), | ||
| 191 | "ParticleStyleNGon" | "NGon" => Some(ParticleStyleKind::NGon), | ||
| 192 | "ParticleStyleBitmap" | "Bitmap" => Some(ParticleStyleKind::Bitmap), | ||
| 193 | "ParticleStyleBrush" | "Brush" => Some(ParticleStyleKind::Brush), | ||
| 194 | _ => None, | ||
| 195 | } | ||
| 196 | } | ||
| 197 | |||
| 198 | fn eval_first_num( | ||
| 199 | comp: &Comp, | ||
| 200 | node: &Node, | ||
| 201 | keys: &[&str], | ||
| 202 | t: f64, | ||
| 203 | default: f64, | ||
| 204 | expr: &ExprEngine, | ||
| 205 | ) -> f64 { | ||
| 206 | for &k in keys { | ||
| 207 | if node.inputs.contains_key(k) { | ||
| 208 | return comp.eval_number(node, k, t, default, expr); | ||
| 209 | } | ||
| 210 | } | ||
| 211 | default | ||
| 212 | } | ||
| 213 | |||
| 214 | /// Reads particle set bitmask from `Set1..=Set32` or integer `Set` (1..=32). | ||
| 215 | pub(super) fn read_sets_mask(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Option<u32> { | ||
| 216 | let mut mask = 0u32; | ||
| 217 | let mut any_key = false; | ||
| 218 | if node.inputs.contains_key("Set") { | ||
| 219 | any_key = true; | ||
| 220 | let idx = comp.eval_number(node, "Set", t, 1.0, expr).round() as i32; | ||
| 221 | if (1..=32).contains(&idx) { | ||
| 222 | mask |= 1u32 << (idx - 1); | ||
| 223 | } | ||
| 224 | } | ||
| 225 | for key in node.inputs.keys() { | ||
| 226 | if let Some(rest) = key.strip_prefix("Set") { | ||
| 227 | if let Ok(idx) = rest.parse::<u32>() { | ||
| 228 | if (1..=32).contains(&idx) { | ||
| 229 | any_key = true; | ||
| 230 | if comp.eval_number(node, key, t, 0.0, expr) > 0.5 { | ||
| 231 | mask |= 1u32 << (idx - 1); | ||
| 232 | } | ||
| 233 | } | ||
| 234 | } | ||
| 235 | } | ||
| 236 | } | ||
| 237 | any_key.then_some(mask) | ||
| 238 | } | ||
| 239 | |||
| 240 | struct ModifierFilter { | ||
| 241 | region: RegionSpec, | ||
| 242 | invert_region: bool, | ||
| 243 | probability: f64, | ||
| 244 | start_age: f64, | ||
| 245 | end_age: f64, | ||
| 246 | set_mask: Option<u32>, | ||
| 247 | dont_affect_sets: bool, | ||
| 248 | } | ||
| 249 | |||
| 250 | impl ModifierFilter { | ||
| 251 | fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { | ||
| 252 | let region = if node.static_str("Region").is_some() { | ||
| 253 | RegionSpec::from_node(comp, node, t, expr) | ||
| 254 | } else { | ||
| 255 | RegionSpec::All | ||
| 256 | }; | ||
| 257 | let invert_region = matches!(node.static_str("RegionMode"), Some("Outside" | "Leaving")); | ||
| 258 | let probability = comp.eval_number(node, "Probability", t, 1.0, expr).clamp(0.0, 1.0); | ||
| 259 | let start_age = comp.eval_number(node, "StartAge", t, 0.0, expr).clamp(0.0, 1.0); | ||
| 260 | let end_age = comp.eval_number(node, "EndAge", t, 1.0, expr).clamp(0.0, 1.0); | ||
| 261 | let set_mask = if node.kind == "pSpawn" && !node.inputs.contains_key("SetMode") { | ||
| 262 | None | ||
| 263 | } else { | ||
| 264 | read_sets_mask(comp, node, t, expr) | ||
| 265 | }; | ||
| 266 | let dont_affect_sets = matches!(node.static_str("SetMode"), Some("DontAffect" | "Don't Affect")); | ||
| 267 | Self { | ||
| 268 | region, | ||
| 269 | invert_region, | ||
| 270 | probability, | ||
| 271 | start_age, | ||
| 272 | end_age, | ||
| 273 | set_mask, | ||
| 274 | dont_affect_sets, | ||
| 275 | } | ||
| 276 | } | ||
| 277 | |||
| 278 | #[inline] | ||
| 279 | fn matches(&self, p: &Particle, scope: &HashSet<u64>, rng: &mut SplitMix64) -> bool { | ||
| 280 | if !p.alive || !scope.contains(&p.emitter_hash) { | ||
| 281 | return false; | ||
| 282 | } | ||
| 283 | let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); | ||
| 284 | if life_frac < self.start_age - 1e-9 || life_frac > self.end_age + 1e-9 { | ||
| 285 | return false; | ||
| 286 | } | ||
| 287 | if let Some(mask) = self.set_mask { | ||
| 288 | let hit = (p.sets & mask) != 0; | ||
| 289 | if (!self.dont_affect_sets && !hit) || (self.dont_affect_sets && hit) { | ||
| 290 | return false; | ||
| 291 | } | ||
| 292 | } | ||
| 293 | let inside = self.region.contains(p.pos); | ||
| 294 | if (!self.invert_region && !inside) || (self.invert_region && inside) { | ||
| 295 | return false; | ||
| 296 | } | ||
| 297 | if self.probability < 1.0 - 1e-9 && rng.next_f64() > self.probability { | ||
| 298 | return false; | ||
| 299 | } | ||
| 300 | true | ||
| 301 | } | ||
| 302 | } | ||
| 303 | |||
| 304 | /// Dispatches `pVortex`, `pFlock`, `pSpawn`, `pChangeStyle`, and `pGradientForce`. | ||
| 305 | #[allow(clippy::too_many_arguments)] | ||
| 306 | pub(super) fn apply_extended_modifier( | ||
| 307 | particles: &mut Vec<Particle>, | ||
| 308 | comp: &Comp, | ||
| 309 | node: &Node, | ||
| 310 | mod_id: NodeId, | ||
| 311 | scope: &HashSet<u64>, | ||
| 312 | emitter_nodes: &HashMap<u64, NodeId>, | ||
| 313 | gradient_fields: &HashMap<NodeId, GradientField>, | ||
| 314 | t: f64, | ||
| 315 | expr: &ExprEngine, | ||
| 316 | ) { | ||
| 317 | match node.kind.as_str() { | ||
| 318 | "pVortex" => apply_vortex(particles, comp, node, scope, t, expr), | ||
| 319 | "pFlock" => apply_flock(particles, comp, node, scope, t, expr), | ||
| 320 | "pSpawn" => apply_spawn(particles, comp, node, scope, emitter_nodes, t, expr), | ||
| 321 | "pChangeStyle" => apply_change_style(particles, comp, node, scope, t, expr), | ||
| 322 | "pGradientForce" => { | ||
| 323 | if let Some(field) = gradient_fields.get(&mod_id) { | ||
| 324 | apply_gradient_force(particles, comp, node, scope, field, t, expr); | ||
| 325 | } | ||
| 326 | } | ||
| 327 | _ => {} | ||
| 328 | } | ||
| 329 | } | ||
| 330 | |||
| 331 | /// `pVortex`: tangential swirl + radial spiral force around `Center` / `Translate`. | ||
| 332 | fn apply_vortex( | ||
| 333 | particles: &mut [Particle], | ||
| 334 | comp: &Comp, | ||
| 335 | node: &Node, | ||
| 336 | scope: &HashSet<u64>, | ||
| 337 | t: f64, | ||
| 338 | expr: &ExprEngine, | ||
| 339 | ) { | ||
| 340 | let strength = comp.eval_number(node, "Strength", t, 0.1, expr); | ||
| 341 | if strength.abs() < 1e-12 { | ||
| 342 | return; | ||
| 343 | } | ||
| 344 | let power = comp.eval_number(node, "Power", t, 2.0, expr); | ||
| 345 | let angle = comp.eval_number(node, "Angle", t, 0.0, expr).to_radians(); | ||
| 346 | let (sin_a, cos_a) = angle.sin_cos(); | ||
| 347 | |||
| 348 | let center_pt = if node.inputs.contains_key("Center") { | ||
| 349 | comp.eval_point(node, "Center", t, [0.0, 0.0], expr) | ||
| 350 | } else { | ||
| 351 | [0.0, 0.0] | ||
| 352 | }; | ||
| 353 | let cx = eval_first_num(comp, node, &["Translate.X", "Center.X"], t, center_pt[0], expr); | ||
| 354 | let cy = eval_first_num(comp, node, &["Translate.Y", "Center.Y"], t, center_pt[1], expr); | ||
| 355 | |||
| 356 | let filter = ModifierFilter::from_node(comp, node, t, expr); | ||
| 357 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | ||
| 358 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | ||
| 359 | |||
| 360 | for p in particles.iter_mut() { | ||
| 361 | if !filter.matches(p, scope, &mut rng) { | ||
| 362 | continue; | ||
| 363 | } | ||
| 364 | let rx = p.pos[0] - cx; | ||
| 365 | let ry = p.pos[1] - cy; | ||
| 366 | let dist = (rx * rx + ry * ry).sqrt(); | ||
| 367 | if dist < 1e-7 { | ||
| 368 | continue; | ||
| 369 | } | ||
| 370 | let inv_d = 1.0 / dist; | ||
| 371 | let r_hat_x = rx * inv_d; | ||
| 372 | let r_hat_y = ry * inv_d; | ||
| 373 | // CCW tangential unit vector around center. | ||
| 374 | let t_hat_x = -r_hat_y; | ||
| 375 | let t_hat_y = r_hat_x; | ||
| 376 | |||
| 377 | // Angle = 0 => pure tangential swirl; positive Angle spirals inward; negative spirals outward. | ||
| 378 | let fx = t_hat_x * cos_a - r_hat_x * sin_a; | ||
| 379 | let fy = t_hat_y * cos_a - r_hat_y * sin_a; | ||
| 380 | |||
| 381 | let falloff = dist.max(0.02).powf(power); | ||
| 382 | let mag = (strength * VORTEX_FORCE_SCALE / falloff).clamp(-0.2, 0.2); | ||
| 383 | p.vel[0] += fx * mag; | ||
| 384 | p.vel[1] += fy * mag; | ||
| 385 | } | ||
| 386 | } | ||
| 387 | |||
| 388 | /// `pFlock`: O(N) spatial-hashed Boids cohesion, separation, and alignment steering. | ||
| 389 | fn apply_flock( | ||
| 390 | particles: &mut [Particle], | ||
| 391 | comp: &Comp, | ||
| 392 | node: &Node, | ||
| 393 | scope: &HashSet<u64>, | ||
| 394 | t: f64, | ||
| 395 | expr: &ExprEngine, | ||
| 396 | ) { | ||
| 397 | let strength = comp.eval_number(node, "Strength", t, 1.0, expr); | ||
| 398 | if strength.abs() < 1e-12 { | ||
| 399 | return; | ||
| 400 | } | ||
| 401 | let cohesion = eval_first_num(comp, node, &["Cohesion", "AttractStrength", "CohesionStrength"], t, 0.1, expr); | ||
| 402 | let separation = eval_first_num(comp, node, &["Separation", "RepelStrength", "SeparationStrength"], t, 0.1, expr); | ||
| 403 | let alignment = eval_first_num(comp, node, &["Alignment", "AlignStrength", "AlignmentStrength"], t, 0.1, expr); | ||
| 404 | if cohesion.abs() < 1e-12 && separation.abs() < 1e-12 && alignment.abs() < 1e-12 { | ||
| 405 | return; | ||
| 406 | } | ||
| 407 | |||
| 408 | let radius = eval_first_num(comp, node, &["Radius", "InfluenceRadius", "Distance", "AttractDistance"], t, 0.15, expr) | ||
| 409 | .max(1e-4); | ||
| 410 | let sep_radius = eval_first_num(comp, node, &["RepelDistance", "SeparationRadius"], t, radius * 0.5, expr) | ||
| 411 | .clamp(1e-5, radius); | ||
| 412 | let radius_sq = radius * radius; | ||
| 413 | let inv_cell = 1.0 / radius.max(0.01); | ||
| 414 | |||
| 415 | let filter = ModifierFilter::from_node(comp, node, t, expr); | ||
| 416 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | ||
| 417 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | ||
| 418 | |||
| 419 | let mut active: Vec<usize> = Vec::new(); | ||
| 420 | let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new(); | ||
| 421 | |||
| 422 | for (idx, p) in particles.iter().enumerate() { | ||
| 423 | if !filter.matches(p, scope, &mut rng) { | ||
| 424 | continue; | ||
| 425 | } | ||
| 426 | active.push(idx); | ||
| 427 | let cx = (p.pos[0] * inv_cell).floor().clamp(-1e6, 1e6) as i32; | ||
| 428 | let cy = (p.pos[1] * inv_cell).floor().clamp(-1e6, 1e6) as i32; | ||
| 429 | grid.entry((cx, cy)).or_default().push(idx); | ||
| 430 | } | ||
| 431 | |||
| 432 | if active.len() < 2 { | ||
| 433 | return; | ||
| 434 | } | ||
| 435 | |||
| 436 | let mut deltas = vec![[0.0_f64; 3]; active.len()]; | ||
| 437 | for (slot, &i) in active.iter().enumerate() { | ||
| 438 | let pi = &particles[i]; | ||
| 439 | let cx = (pi.pos[0] * inv_cell).floor().clamp(-1e6, 1e6) as i32; | ||
| 440 | let cy = (pi.pos[1] * inv_cell).floor().clamp(-1e6, 1e6) as i32; | ||
| 441 | |||
| 442 | let mut sum_pos = [0.0_f64; 3]; | ||
| 443 | let mut sum_vel = [0.0_f64; 3]; | ||
| 444 | let mut sep_vec = [0.0_f64; 3]; | ||
| 445 | let mut n_count = 0usize; | ||
| 446 | let mut sep_count = 0usize; | ||
| 447 | let mut inspected = 0usize; | ||
| 448 | |||
| 449 | 'cells: for dy in -1..=1 { | ||
| 450 | for dx in -1..=1 { | ||
| 451 | let Some(bucket) = grid.get(&(cx + dx, cy + dy)) else { | ||
| 452 | continue; | ||
| 453 | }; | ||
| 454 | for &j in bucket { | ||
| 455 | if j == i { | ||
| 456 | continue; | ||
| 457 | } | ||
| 458 | inspected += 1; | ||
| 459 | if inspected > FLOCK_MAX_NEIGHBORS { | ||
| 460 | break 'cells; | ||
| 461 | } | ||
| 462 | let pj = &particles[j]; | ||
| 463 | let rx = pj.pos[0] - pi.pos[0]; | ||
| 464 | let ry = pj.pos[1] - pi.pos[1]; | ||
| 465 | let rz = pj.pos[2] - pi.pos[2]; | ||
| 466 | let d2 = rx * rx + ry * ry + rz * rz; | ||
| 467 | if d2 >= radius_sq || d2 <= 1e-12 { | ||
| 468 | continue; | ||
| 469 | } | ||
| 470 | n_count += 1; | ||
| 471 | sum_pos[0] += pj.pos[0]; | ||
| 472 | sum_pos[1] += pj.pos[1]; | ||
| 473 | sum_pos[2] += pj.pos[2]; | ||
| 474 | sum_vel[0] += pj.vel[0]; | ||
| 475 | sum_vel[1] += pj.vel[1]; | ||
| 476 | sum_vel[2] += pj.vel[2]; | ||
| 477 | |||
| 478 | let d = d2.sqrt(); | ||
| 479 | if d < sep_radius { | ||
| 480 | let weight = (1.0 - d / sep_radius) / d; | ||
| 481 | sep_vec[0] -= rx * weight; | ||
| 482 | sep_vec[1] -= ry * weight; | ||
| 483 | sep_vec[2] -= rz * weight; | ||
| 484 | sep_count += 1; | ||
| 485 | } | ||
| 486 | } | ||
| 487 | } | ||
| 488 | } | ||
| 489 | |||
| 490 | if n_count == 0 { | ||
| 491 | continue; | ||
| 492 | } | ||
| 493 | let inv_n = 1.0 / n_count as f64; | ||
| 494 | let mut acc = [0.0_f64; 3]; | ||
| 495 | for a in 0..3 { | ||
| 496 | let coh = (sum_pos[a] * inv_n - pi.pos[a]) * cohesion * strength * 0.05; | ||
| 497 | let align = (sum_vel[a] * inv_n - pi.vel[a]) * alignment * strength * 0.2; | ||
| 498 | let sep = if sep_count > 0 { | ||
| 499 | (sep_vec[a] / sep_count as f64) * separation * strength * 0.02 | ||
| 500 | } else { | ||
| 501 | 0.0 | ||
| 502 | }; | ||
| 503 | acc[a] = coh + align + sep; | ||
| 504 | } | ||
| 505 | let mag = (acc[0] * acc[0] + acc[1] * acc[1] + acc[2] * acc[2]).sqrt(); | ||
| 506 | const MAX_FLOCK_ACCEL: f64 = 0.05; | ||
| 507 | if mag > MAX_FLOCK_ACCEL { | ||
| 508 | let s = MAX_FLOCK_ACCEL / mag; | ||
| 509 | acc[0] *= s; | ||
| 510 | acc[1] *= s; | ||
| 511 | acc[2] *= s; | ||
| 512 | } | ||
| 513 | deltas[slot] = acc; | ||
| 514 | } | ||
| 515 | |||
| 516 | for (&i, acc) in active.iter().zip(deltas.iter()) { | ||
| 517 | particles[i].vel[0] += acc[0]; | ||
| 518 | particles[i].vel[1] += acc[1]; | ||
| 519 | particles[i].vel[2] += acc[2]; | ||
| 520 | } | ||
| 521 | } | ||
| 522 | |||
| 523 | /// `pSpawn`: spawns child particles from living parent particles, respecting `MAX_PARTICLES`. | ||
| 524 | fn apply_spawn( | ||
| 525 | particles: &mut Vec<Particle>, | ||
| 526 | comp: &Comp, | ||
| 527 | node: &Node, | ||
| 528 | scope: &HashSet<u64>, | ||
| 529 | emitter_nodes: &HashMap<u64, NodeId>, | ||
| 530 | t: f64, | ||
| 531 | expr: &ExprEngine, | ||
| 532 | ) { | ||
| 533 | if particles.len() >= MAX_PARTICLES { | ||
| 534 | return; | ||
| 535 | } | ||
| 536 | let number = comp.eval_number(node, "Number", t, 1.0, expr).max(0.0); | ||
| 537 | let number_var = comp.eval_number(node, "NumberVariance", t, 0.0, expr).max(0.0); | ||
| 538 | if number <= 1e-9 && number_var <= 1e-9 { | ||
| 539 | return; | ||
| 540 | } | ||
| 541 | |||
| 542 | let lifespan_base = comp.eval_number(node, "Lifespan", t, 50.0, expr).max(1.0); | ||
| 543 | let lifespan_var = comp.eval_number(node, "LifespanVariance", t, 0.0, expr).max(0.0); | ||
| 544 | let vel_transfer = eval_first_num(comp, node, &["VelocityTransfer", "InheritVelocity"], t, 1.0, expr); | ||
| 545 | let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr); | ||
| 546 | let vel_var = comp.eval_number(node, "VelocityVariance", t, 0.0, expr).max(0.0); | ||
| 547 | let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr); | ||
| 548 | let angle_var = comp.eval_number(node, "AngleVariance", t, 0.0, expr).max(0.0); | ||
| 549 | let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr); | ||
| 550 | let angle_z_var = comp.eval_number(node, "AngleZVariance", t, 0.0, expr).max(0.0); | ||
| 551 | let pos_var = comp.eval_number(node, "PositionVariance", t, 0.0, expr).max(0.0); | ||
| 552 | let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr); | ||
| 553 | let rot_z_var = comp.eval_number(node, "RotationZVariance", t, 0.0, expr).max(0.0); | ||
| 554 | let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr); | ||
| 555 | let spin_z_var = comp.eval_number(node, "SpinZVariance", t, 0.0, expr).max(0.0); | ||
| 556 | |||
| 557 | let has_size = node.inputs.contains_key("ParticleStyle.Size") || node.inputs.contains_key("Size"); | ||
| 558 | let size_base = eval_first_num(comp, node, &["ParticleStyle.Size", "Size"], t, 0.1, expr).max(0.0); | ||
| 559 | let size_var = eval_first_num(comp, node, &["ParticleStyle.SizeVariance", "SizeVariance"], t, 0.0, expr).max(0.0); | ||
| 560 | |||
| 561 | let has_r = node.inputs.contains_key("ParticleStyle.Red") || node.inputs.contains_key("Red"); | ||
| 562 | let has_g = node.inputs.contains_key("ParticleStyle.Green") || node.inputs.contains_key("Green"); | ||
| 563 | let has_b = node.inputs.contains_key("ParticleStyle.Blue") || node.inputs.contains_key("Blue"); | ||
| 564 | let has_a = node.inputs.contains_key("ParticleStyle.Alpha") || node.inputs.contains_key("Alpha"); | ||
| 565 | let col_r = eval_first_num(comp, node, &["ParticleStyle.Red", "Red"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 566 | let col_g = eval_first_num(comp, node, &["ParticleStyle.Green", "Green"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 567 | let col_b = eval_first_num(comp, node, &["ParticleStyle.Blue", "Blue"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 568 | let col_a = eval_first_num(comp, node, &["ParticleStyle.Alpha", "Alpha"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 569 | |||
| 570 | let explicit_style = node.static_str("Style").and_then(parse_particle_style); | ||
| 571 | let ngon_sides = if node.inputs.contains_key("ParticleStyleNGon.NGonSides") { | ||
| 572 | comp.eval_number(node, "ParticleStyleNGon.NGonSides", t, 5.0, expr) | ||
| 573 | .round() | ||
| 574 | .clamp(3.0, 64.0) as u8 | ||
| 575 | } else { | ||
| 576 | 0 | ||
| 577 | }; | ||
| 578 | let child_sets = read_sets_mask(comp, node, t, expr); | ||
| 579 | let spawn_hash = stable_name_hash(&node.name); | ||
| 580 | let has_spawn_bitmap = node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some(); | ||
| 581 | |||
| 582 | let filter = ModifierFilter::from_node(comp, node, t, expr); | ||
| 583 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | ||
| 584 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | ||
| 585 | |||
| 586 | let remaining_cap = MAX_PARTICLES.saturating_sub(particles.len()); | ||
| 587 | let mut spawned: Vec<Particle> = Vec::new(); | ||
| 588 | let parent_count = particles.len(); | ||
| 589 | |||
| 590 | for idx in 0..parent_count { | ||
| 591 | if spawned.len() >= remaining_cap { | ||
| 592 | break; | ||
| 593 | } | ||
| 594 | let parent = particles[idx]; | ||
| 595 | if !filter.matches(&parent, scope, &mut rng) { | ||
| 596 | continue; | ||
| 597 | } | ||
| 598 | |||
| 599 | let rate = (number + rng.signed() * number_var).max(0.0); | ||
| 600 | let whole = rate.floor() as usize; | ||
| 601 | let frac = rate - whole as f64; | ||
| 602 | let count = whole + usize::from(frac > 1e-9 && rng.next_f64() < frac); | ||
| 603 | if count == 0 { | ||
| 604 | continue; | ||
| 605 | } | ||
| 606 | |||
| 607 | // Inherit parent's visual style when `pSpawn` does not explicitly specify `Style`. | ||
| 608 | let child_style = explicit_style.or(parent.style_override).or_else(|| { | ||
| 609 | emitter_nodes | ||
| 610 | .get(&parent.emitter_hash) | ||
| 611 | .and_then(|id| comp.nodes.get(id.0)) | ||
| 612 | .and_then(|en| en.static_str("Style")) | ||
| 613 | .and_then(parse_particle_style) | ||
| 614 | }); | ||
| 615 | let child_bitmap_owner = if has_spawn_bitmap { | ||
| 616 | spawn_hash | ||
| 617 | } else if explicit_style.is_none() { | ||
| 618 | if parent.bitmap_owner_hash != 0 { | ||
| 619 | parent.bitmap_owner_hash | ||
| 620 | } else { | ||
| 621 | parent.emitter_hash | ||
| 622 | } | ||
| 623 | } else { | ||
| 624 | 0 | ||
| 625 | }; | ||
| 626 | |||
| 627 | for _ in 0..count { | ||
| 628 | if spawned.len() >= remaining_cap { | ||
| 629 | break; | ||
| 630 | } | ||
| 631 | let mut pos = parent.pos; | ||
| 632 | if pos_var > 0.0 { | ||
| 633 | pos[0] += rng.signed() * pos_var; | ||
| 634 | pos[1] += rng.signed() * pos_var; | ||
| 635 | pos[2] += rng.signed() * pos_var; | ||
| 636 | } | ||
| 637 | let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE; | ||
| 638 | let ang = (angle_base + rng.signed() * angle_var).to_radians(); | ||
| 639 | let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians(); | ||
| 640 | let cos_z = ang_z.cos(); | ||
| 641 | let vel = [ | ||
| 642 | parent.vel[0] * vel_transfer + speed * ang.cos() * cos_z, | ||
| 643 | parent.vel[1] * vel_transfer + speed * ang.sin() * cos_z, | ||
| 644 | parent.vel[2] * vel_transfer + speed * ang_z.sin(), | ||
| 645 | ]; | ||
| 646 | let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0); | ||
| 647 | let size = if has_size { | ||
| 648 | (size_base + rng.signed() * size_var).max(0.0) | ||
| 649 | } else { | ||
| 650 | parent.size | ||
| 651 | }; | ||
| 652 | let color = [ | ||
| 653 | if has_r { col_r } else { parent.color[0] }, | ||
| 654 | if has_g { col_g } else { parent.color[1] }, | ||
| 655 | if has_b { col_b } else { parent.color[2] }, | ||
| 656 | if has_a { col_a } else { parent.color[3] }, | ||
| 657 | ]; | ||
| 658 | spawned.push(Particle { | ||
| 659 | emitter_hash: spawn_hash, | ||
| 660 | sets: child_sets.unwrap_or(parent.sets), | ||
| 661 | style_override: child_style, | ||
| 662 | ngon_sides_override: if ngon_sides >= 3 { | ||
| 663 | ngon_sides | ||
| 664 | } else { | ||
| 665 | parent.ngon_sides_override | ||
| 666 | }, | ||
| 667 | bitmap_owner_hash: child_bitmap_owner, | ||
| 668 | pos, | ||
| 669 | vel, | ||
| 670 | rot_z: rot_z_base + rng.signed() * rot_z_var, | ||
| 671 | spin_z: spin_z_base + rng.signed() * spin_z_var, | ||
| 672 | age: 0.0, | ||
| 673 | lifespan, | ||
| 674 | size, | ||
| 675 | color, | ||
| 676 | alive: true, | ||
| 677 | }); | ||
| 678 | } | ||
| 679 | } | ||
| 680 | |||
| 681 | particles.extend(spawned); | ||
| 682 | } | ||
| 683 | |||
| 684 | /// `pChangeStyle`: modifies particle color, alpha, size, and style over life or inside a region. | ||
| 685 | fn apply_change_style( | ||
| 686 | particles: &mut [Particle], | ||
| 687 | comp: &Comp, | ||
| 688 | node: &Node, | ||
| 689 | scope: &HashSet<u64>, | ||
| 690 | t: f64, | ||
| 691 | expr: &ExprEngine, | ||
| 692 | ) { | ||
| 693 | let filter = ModifierFilter::from_node(comp, node, t, expr); | ||
| 694 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | ||
| 695 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | ||
| 696 | |||
| 697 | let has_r = node.inputs.contains_key("ParticleStyle.Red") | ||
| 698 | || node.inputs.contains_key("Red") | ||
| 699 | || node.inputs.contains_key("Color.R"); | ||
| 700 | let has_g = node.inputs.contains_key("ParticleStyle.Green") | ||
| 701 | || node.inputs.contains_key("Green") | ||
| 702 | || node.inputs.contains_key("Color.G"); | ||
| 703 | let has_b = node.inputs.contains_key("ParticleStyle.Blue") | ||
| 704 | || node.inputs.contains_key("Blue") | ||
| 705 | || node.inputs.contains_key("Color.B"); | ||
| 706 | let has_a = node.inputs.contains_key("ParticleStyle.Alpha") | ||
| 707 | || node.inputs.contains_key("Alpha") | ||
| 708 | || node.inputs.contains_key("Color.A"); | ||
| 709 | |||
| 710 | let new_r = eval_first_num(comp, node, &["ParticleStyle.Red", "Red", "Color.R"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 711 | let new_g = eval_first_num(comp, node, &["ParticleStyle.Green", "Green", "Color.G"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 712 | let new_b = eval_first_num(comp, node, &["ParticleStyle.Blue", "Blue", "Color.B"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 713 | let new_a = eval_first_num(comp, node, &["ParticleStyle.Alpha", "Alpha", "Color.A"], t, 1.0, expr).clamp(0.0, 1.0) as f32; | ||
| 714 | |||
| 715 | let color_grad = comp | ||
| 716 | .eval_gradient(node, "ParticleStyle.ColorOverLife", t) | ||
| 717 | .or_else(|| comp.eval_gradient(node, "Color", t)); | ||
| 718 | |||
| 719 | let has_size = node.inputs.contains_key("ParticleStyle.Size") || node.inputs.contains_key("Size"); | ||
| 720 | let new_size = eval_first_num(comp, node, &["ParticleStyle.Size", "Size"], t, 0.1, expr).max(0.0); | ||
| 721 | let size_var = eval_first_num(comp, node, &["ParticleStyle.SizeVariance", "SizeVariance"], t, 0.0, expr).max(0.0); | ||
| 722 | let size_over_life = node | ||
| 723 | .inputs | ||
| 724 | .get("ParticleStyle.SizeOverLife") | ||
| 725 | .and_then(|b| b.source_op.as_deref()) | ||
| 726 | .and_then(|src| comp.splines.get(src)); | ||
| 727 | |||
| 728 | let new_style = node.static_str("Style").and_then(parse_particle_style); | ||
| 729 | let new_ngon_sides = if node.inputs.contains_key("ParticleStyleNGon.NGonSides") { | ||
| 730 | comp.eval_number(node, "ParticleStyleNGon.NGonSides", t, 5.0, expr) | ||
| 731 | .round() | ||
| 732 | .clamp(3.0, 64.0) as u8 | ||
| 733 | } else { | ||
| 734 | 0 | ||
| 735 | }; | ||
| 736 | let bitmap_owner = if node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some() { | ||
| 737 | stable_name_hash(&node.name) | ||
| 738 | } else { | ||
| 739 | 0 | ||
| 740 | }; | ||
| 741 | |||
| 742 | for p in particles.iter_mut() { | ||
| 743 | if !filter.matches(p, scope, &mut rng) { | ||
| 744 | continue; | ||
| 745 | } | ||
| 746 | let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); | ||
| 747 | if has_r { | ||
| 748 | p.color[0] = new_r; | ||
| 749 | } | ||
| 750 | if has_g { | ||
| 751 | p.color[1] = new_g; | ||
| 752 | } | ||
| 753 | if has_b { | ||
| 754 | p.color[2] = new_b; | ||
| 755 | } | ||
| 756 | if has_a { | ||
| 757 | p.color[3] = new_a; | ||
| 758 | } | ||
| 759 | if let Some(ref grad) = color_grad { | ||
| 760 | let g = grad.sample(life_frac); | ||
| 761 | p.color[0] = g[0].clamp(0.0, 1.0); | ||
| 762 | p.color[1] = g[1].clamp(0.0, 1.0); | ||
| 763 | p.color[2] = g[2].clamp(0.0, 1.0); | ||
| 764 | p.color[3] = g[3].clamp(0.0, 1.0); | ||
| 765 | } | ||
| 766 | if has_size { | ||
| 767 | let mut s = (new_size + rng.signed() * size_var).max(0.0); | ||
| 768 | if let Some(sp) = size_over_life { | ||
| 769 | s *= (2.0 * sp.eval(life_frac)).max(0.0); | ||
| 770 | } | ||
| 771 | p.size = s; | ||
| 772 | } else if let Some(sp) = size_over_life { | ||
| 773 | p.size = (p.size * (2.0 * sp.eval(life_frac)).max(0.0)).max(0.0); | ||
| 774 | } | ||
| 775 | if let Some(st) = new_style { | ||
| 776 | p.style_override = Some(st); | ||
| 777 | if st == ParticleStyleKind::NGon && new_ngon_sides >= 3 { | ||
| 778 | p.ngon_sides_override = new_ngon_sides; | ||
| 779 | } | ||
| 780 | if st == ParticleStyleKind::Bitmap && bitmap_owner != 0 { | ||
| 781 | p.bitmap_owner_hash = bitmap_owner; | ||
| 782 | } | ||
| 783 | } | ||
| 784 | } | ||
| 785 | } | ||
| 786 | |||
| 787 | /// `pGradientForce`: accelerates particles along the spatial luminance gradient of its input image. | ||
| 788 | fn apply_gradient_force( | ||
| 789 | particles: &mut [Particle], | ||
| 790 | comp: &Comp, | ||
| 791 | node: &Node, | ||
| 792 | scope: &HashSet<u64>, | ||
| 793 | field: &GradientField, | ||
| 794 | t: f64, | ||
| 795 | expr: &ExprEngine, | ||
| 796 | ) { | ||
| 797 | let strength = comp.eval_number(node, "Strength", t, 0.1, expr); | ||
| 798 | if strength.abs() < 1e-12 { | ||
| 799 | return; | ||
| 800 | } | ||
| 801 | let scale = strength * VELOCITY_SCALE * VELOCITY_SCALE; | ||
| 802 | let filter = ModifierFilter::from_node(comp, node, t, expr); | ||
| 803 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | ||
| 804 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | ||
| 805 | |||
| 806 | for p in particles.iter_mut() { | ||
| 807 | if !filter.matches(p, scope, &mut rng) { | ||
| 808 | continue; | ||
| 809 | } | ||
| 810 | let [gx, gy] = field.sample(p.pos[0], p.pos[1]); | ||
| 811 | p.vel[0] += (gx * scale).clamp(-0.1, 0.1); | ||
| 812 | p.vel[1] += (gy * scale).clamp(-0.1, 0.1); | ||
| 813 | } | ||
| 814 | } | ||
crates/engine/src/particles/plan.rs+24-1| ... | @@ -89,12 +89,21 @@ fn collect_bitmap_sources_dfs( | ... | @@ -89,12 +89,21 @@ fn collect_bitmap_sources_dfs( |
| 89 | return; | 89 | return; |
| 90 | } | 90 | } |
| 91 | 91 | ||
| 92 | if node.kind == "pEmitter" { | 92 | if matches!(node.kind.as_str(), "pEmitter" | "pSpawn" | "pChangeStyle") { |
| 93 | if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") { | 93 | if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") { |
| 94 | if let Some(&src_id) = comp.node_by_name.get(src_name) { | 94 | if let Some(&src_id) = comp.node_by_name.get(src_name) { |
| 95 | out.push((node_id, src_id)); | 95 | out.push((node_id, src_id)); |
| 96 | } | 96 | } |
| 97 | } | 97 | } |
| 98 | } else if node.kind == "pGradientForce" { | ||
| 99 | for port in ["Image", "Bitmap", "BitmapInput", "GradientImage"] { | ||
| 100 | if let Some(src_name) = node.connected_node(port) { | ||
| 101 | if let Some(&src_id) = comp.node_by_name.get(src_name) { | ||
| 102 | out.push((node_id, src_id)); | ||
| 103 | break; | ||
| 104 | } | ||
| 105 | } | ||
| 106 | } | ||
| 98 | } | 107 | } |
| 99 | 108 | ||
| 100 | for up_id in particle_stream_inputs(comp, node) { | 109 | for up_id in particle_stream_inputs(comp, node) { |
| ... | @@ -179,6 +188,13 @@ fn build_plan_dfs( | ... | @@ -179,6 +188,13 @@ fn build_plan_dfs( |
| 179 | emitter_nodes.insert(emitter_hash, node_id); | 188 | emitter_nodes.insert(emitter_hash, node_id); |
| 180 | scope.insert(emitter_hash); | 189 | scope.insert(emitter_hash); |
| 181 | } | 190 | } |
| 191 | } else if !node.bypassed && node.kind == "pSpawn" { | ||
| 192 | // `pSpawn` reads only upstream particle scopes (preventing self-spawning loops), | ||
| 193 | // then adds its own hash so downstream forces and `pRender` include its children. | ||
| 194 | modifiers.push((node_id, scope.clone())); | ||
| 195 | let spawn_hash = stable_name_hash(&node.name); | ||
| 196 | emitter_nodes.insert(spawn_hash, node_id); | ||
| 197 | scope.insert(spawn_hash); | ||
| 182 | } else if !node.bypassed | 198 | } else if !node.bypassed |
| 183 | && matches!( | 199 | && matches!( |
| 184 | node.kind.as_str(), | 200 | node.kind.as_str(), |
| ... | @@ -189,8 +205,15 @@ fn build_plan_dfs( | ... | @@ -189,8 +205,15 @@ fn build_plan_dfs( |
| 189 | | "pFriction" | 205 | | "pFriction" |
| 190 | | "pKill" | 206 | | "pKill" |
| 191 | | "pBounce" | 207 | | "pBounce" |
| 208 | | "pVortex" | ||
| 209 | | "pFlock" | ||
| 210 | | "pChangeStyle" | ||
| 211 | | "pGradientForce" | ||
| 192 | ) | 212 | ) |
| 193 | { | 213 | { |
| 214 | if node.kind == "pChangeStyle" && node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some() { | ||
| 215 | emitter_nodes.insert(stable_name_hash(&node.name), node_id); | ||
| 216 | } | ||
| 194 | modifiers.push((node_id, scope.clone())); | 217 | modifiers.push((node_id, scope.clone())); |
| 195 | } | 218 | } |
| 196 | 219 |
crates/engine/src/particles/raster.rs+20-5| ... | @@ -285,8 +285,23 @@ pub(super) fn rasterize_particles( | ... | @@ -285,8 +285,23 @@ pub(super) fn rasterize_particles( |
| 285 | let cx = (p.pos[0] * depth_scale + 0.5) * w_f; | 285 | let cx = (p.pos[0] * depth_scale + 0.5) * w_f; |
| 286 | let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f; | 286 | let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f; |
| 287 | 287 | ||
| 288 | if props.style == ParticleStyleKind::Bitmap { | 288 | let eff_style = p.style_override.unwrap_or(props.style); |
| 289 | if let Some((_, nominal)) = props.resolved_sprite() { | 289 | let eff_ngon_sides = if p.ngon_sides_override >= 3 { |
| 290 | p.ngon_sides_override as f64 | ||
| 291 | } else { | ||
| 292 | props.ngon_sides | ||
| 293 | }; | ||
| 294 | |||
| 295 | if eff_style == ParticleStyleKind::Bitmap { | ||
| 296 | let bmp_idx = if p.bitmap_owner_hash != 0 { | ||
| 297 | props_list | ||
| 298 | .iter() | ||
| 299 | .position(|pr| pr.emitter_hash == p.bitmap_owner_hash) | ||
| 300 | .unwrap_or(props_idx) | ||
| 301 | } else { | ||
| 302 | props_idx | ||
| 303 | }; | ||
| 304 | if let Some((_, nominal)) = props_list[bmp_idx].resolved_sprite() { | ||
| 290 | let draw_w = size_world * nominal[0] * px_scale; | 305 | let draw_w = size_world * nominal[0] * px_scale; |
| 291 | let draw_h = size_world * nominal[1] * px_scale; | 306 | let draw_h = size_world * nominal[1] * px_scale; |
| 292 | if draw_w < 0.5 || draw_h < 0.5 { | 307 | if draw_w < 0.5 || draw_h < 0.5 { |
| ... | @@ -317,7 +332,7 @@ pub(super) fn rasterize_particles( | ... | @@ -317,7 +332,7 @@ pub(super) fn rasterize_particles( |
| 317 | max_y, | 332 | max_y, |
| 318 | color: [cr, cg, cb, ca], | 333 | color: [cr, cg, cb, ca], |
| 319 | shape: DrawShape::Bitmap { | 334 | shape: DrawShape::Bitmap { |
| 320 | emitter_idx: props_idx, | 335 | emitter_idx: bmp_idx, |
| 321 | cx, | 336 | cx, |
| 322 | cy, | 337 | cy, |
| 323 | draw_w, | 338 | draw_w, |
| ... | @@ -329,7 +344,7 @@ pub(super) fn rasterize_particles( | ... | @@ -329,7 +344,7 @@ pub(super) fn rasterize_particles( |
| 329 | } | 344 | } |
| 330 | } | 345 | } |
| 331 | 346 | ||
| 332 | match props.style { | 347 | match eff_style { |
| 333 | ParticleStyleKind::Point => { | 348 | ParticleStyleKind::Point => { |
| 334 | let ix = cx.floor() as isize; | 349 | let ix = cx.floor() as isize; |
| 335 | let iy = cy.floor() as isize; | 350 | let iy = cy.floor() as isize; |
| ... | @@ -390,7 +405,7 @@ pub(super) fn rasterize_particles( | ... | @@ -390,7 +405,7 @@ pub(super) fn rasterize_particles( |
| 390 | let Some((min_y, max_y)) = clip_bounds(cy - bound, cy + bound, h) else { | 405 | let Some((min_y, max_y)) = clip_bounds(cy - bound, cy + bound, h) else { |
| 391 | continue; | 406 | continue; |
| 392 | }; | 407 | }; |
| 393 | let sides = props.ngon_sides; | 408 | let sides = eff_ngon_sides; |
| 394 | let spike_period = std::f64::consts::TAU / sides; | 409 | let spike_period = std::f64::consts::TAU / sides; |
| 395 | let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians(); | 410 | let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians(); |
| 396 | let sharpness = 4.5 * (3.0 / sides).powf(2.8); | 411 | let sharpness = 4.5 * (3.0 / sides).powf(2.8); |
crates/engine/src/particles/sim.rs+27-5| ... | @@ -1,7 +1,8 @@ | ... | @@ -1,7 +1,8 @@ |
| 1 | use std::collections::HashSet; | 1 | use std::collections::{HashMap, HashSet}; |
| 2 | 2 | ||
| 3 | use model::{Comp, ExprEngine, Node}; | 3 | use model::{Comp, ExprEngine, Node, NodeId}; |
| 4 | 4 | ||
| 5 | use super::forces::{GradientField, apply_extended_modifier, read_sets_mask}; | ||
| 5 | use super::plan::ParticlePlan; | 6 | use super::plan::ParticlePlan; |
| 6 | use super::{ | 7 | use super::{ |
| 7 | MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, TURBULENCE_SCALE, | 8 | MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, TURBULENCE_SCALE, |
| ... | @@ -13,18 +14,34 @@ pub(super) fn step_simulation( | ... | @@ -13,18 +14,34 @@ pub(super) fn step_simulation( |
| 13 | state: &mut SimState, | 14 | state: &mut SimState, |
| 14 | comp: &Comp, | 15 | comp: &Comp, |
| 15 | plan: &ParticlePlan, | 16 | plan: &ParticlePlan, |
| 17 | gradient_fields: &HashMap<NodeId, GradientField>, | ||
| 16 | frame: i64, | 18 | frame: i64, |
| 17 | expr: &ExprEngine, | 19 | expr: &ExprEngine, |
| 18 | ) { | 20 | ) { |
| 19 | let t = frame as f64; | 21 | let t = frame as f64; |
| 20 | 22 | ||
| 21 | // 1. Apply forces & kills to existing live particles, then integrate motion and age. | 23 | // 1. Apply forces, spawns, style changes & kills to existing live particles, then integrate motion and age. |
| 22 | if !state.particles.is_empty() { | 24 | if !state.particles.is_empty() { |
| 23 | for (mod_id, scope) in &plan.modifiers { | 25 | for (mod_id, scope) in &plan.modifiers { |
| 24 | let Some(node) = comp.nodes.get(mod_id.0) else { | 26 | let Some(node) = comp.nodes.get(mod_id.0) else { |
| 25 | continue; | 27 | continue; |
| 26 | }; | 28 | }; |
| 27 | apply_modifier(&mut state.particles, comp, node, scope, t, expr); | 29 | match node.kind.as_str() { |
| 30 | "pVortex" | "pFlock" | "pSpawn" | "pChangeStyle" | "pGradientForce" => { | ||
| 31 | apply_extended_modifier( | ||
| 32 | &mut state.particles, | ||
| 33 | comp, | ||
| 34 | node, | ||
| 35 | *mod_id, | ||
| 36 | scope, | ||
| 37 | &plan.emitter_nodes, | ||
| 38 | gradient_fields, | ||
| 39 | t, | ||
| 40 | expr, | ||
| 41 | ); | ||
| 42 | } | ||
| 43 | _ => apply_modifier(&mut state.particles, comp, node, scope, t, expr), | ||
| 44 | } | ||
| 28 | } | 45 | } |
| 29 | 46 | ||
| 30 | for p in &mut state.particles { | 47 | for p in &mut state.particles { |
| ... | @@ -176,6 +193,7 @@ fn emit_particles( | ... | @@ -176,6 +193,7 @@ fn emit_particles( |
| 176 | .max(0.0); | 193 | .max(0.0); |
| 177 | 194 | ||
| 178 | let region = RegionSpec::from_node(comp, node, t, expr); | 195 | let region = RegionSpec::from_node(comp, node, t, expr); |
| 196 | let emitter_sets = read_sets_mask(comp, node, t, expr).unwrap_or(1u32); | ||
| 179 | state.particles.reserve(emit_count); | 197 | state.particles.reserve(emit_count); |
| 180 | 198 | ||
| 181 | for _ in 0..emit_count { | 199 | for _ in 0..emit_count { |
| ... | @@ -219,6 +237,10 @@ fn emit_particles( | ... | @@ -219,6 +237,10 @@ fn emit_particles( |
| 219 | 237 | ||
| 220 | state.particles.push(Particle { | 238 | state.particles.push(Particle { |
| 221 | emitter_hash, | 239 | emitter_hash, |
| 240 | sets: emitter_sets, | ||
| 241 | style_override: None, | ||
| 242 | ngon_sides_override: 0, | ||
| 243 | bitmap_owner_hash: 0, | ||
| 222 | pos, | 244 | pos, |
| 223 | vel, | 245 | vel, |
| 224 | rot_z, | 246 | rot_z, |
| ... | @@ -366,7 +388,7 @@ impl RegionSpec { | ... | @@ -366,7 +388,7 @@ impl RegionSpec { |
| 366 | } | 388 | } |
| 367 | } | 389 | } |
| 368 | 390 | ||
| 369 | fn contains(&self, p: [f64; 3]) -> bool { | 391 | pub(super) fn contains(&self, p: [f64; 3]) -> bool { |
| 370 | match *self { | 392 | match *self { |
| 371 | Self::All => true, | 393 | Self::All => true, |
| 372 | Self::Point { center } => { | 394 | Self::Point { center } => { |
crates/engine/src/particles/tests.rs+474-1| ... | @@ -263,8 +263,9 @@ Composition { | ... | @@ -263,8 +263,9 @@ Composition { |
| 263 | 263 | ||
| 264 | // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05) | 264 | // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05) |
| 265 | // crosses the floor at y=0.0 around frame 3. | 265 | // crosses the floor at y=0.0 around frame 3. |
| 266 | let empty_fields = HashMap::new(); | ||
| 266 | for f in 0..=4 { | 267 | for f in 0..=4 { |
| 267 | step_simulation(&mut state, &comp, &plan, f, &expr); | 268 | step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); |
| 268 | } | 269 | } |
| 269 | let first = state.particles.first().expect("particle emitted"); | 270 | let first = state.particles.first().expect("particle emitted"); |
| 270 | let init_vx = 0.1 * (-60.0_f64).to_radians().cos(); | 271 | let init_vx = 0.1 * (-60.0_f64).to_radians().cos(); |
| ... | @@ -629,3 +630,475 @@ Composition { | ... | @@ -629,3 +630,475 @@ Composition { |
| 629 | let img = render_particles_2d(&mut cache, &comp, pr, 5.0, [64, 64], &expr, &sprites); | 630 | let img = render_particles_2d(&mut cache, &comp, pr, 5.0, [64, 64], &expr, &sprites); |
| 630 | assert_eq!(img.len(), 64 * 64 * 4); | 631 | assert_eq!(img.len(), 64 * 64 * 4); |
| 631 | } | 632 | } |
| 633 | |||
| 634 | #[test] | ||
| 635 | fn test_p_vortex_swirl_and_spiral_angle() { | ||
| 636 | let make_comp = |angle: f64| { | ||
| 637 | format!( | ||
| 638 | r#"Composition {{ | ||
| 639 | GlobalRange = {{ 0, 20 }}, | ||
| 640 | RenderRange = {{ 0, 20 }}, | ||
| 641 | Tools = ordered() {{ | ||
| 642 | EN = BezierSpline {{ | ||
| 643 | KeyFrames = {{ | ||
| 644 | [0] = {{ 1, Flags = {{ Linear = true }} }}, | ||
| 645 | [1] = {{ 0, Flags = {{ Linear = true }} }}, | ||
| 646 | }}, | ||
| 647 | }}, | ||
| 648 | E = pEmitter {{ | ||
| 649 | Inputs = {{ | ||
| 650 | Number = Input {{ SourceOp = "EN", Source = "Value", }}, | ||
| 651 | Lifespan = Input {{ Value = 50, }}, | ||
| 652 | Region = Input {{ Value = FuID {{ "Point" }}, }}, | ||
| 653 | ["Point.Translate.X"] = Input {{ Value = 0.2, }}, | ||
| 654 | ["Point.Translate.Y"] = Input {{ Value = 0.0, }}, | ||
| 655 | Style = Input {{ Value = FuID {{ "ParticleStyleBlob" }}, }}, | ||
| 656 | ["ParticleStyle.Size"] = Input {{ Value = 0.5, }}, | ||
| 657 | }}, | ||
| 658 | }}, | ||
| 659 | V = pVortex {{ | ||
| 660 | Inputs = {{ | ||
| 661 | Input = Input {{ SourceOp = "E", Source = "Output", }}, | ||
| 662 | Strength = Input {{ Value = 1.0, }}, | ||
| 663 | Power = Input {{ Value = 1.0, }}, | ||
| 664 | Angle = Input {{ Value = {angle}, }}, | ||
| 665 | ["Translate.X"] = Input {{ Value = 0.0, }}, | ||
| 666 | ["Translate.Y"] = Input {{ Value = 0.0, }}, | ||
| 667 | }}, | ||
| 668 | }}, | ||
| 669 | R = pRender {{ | ||
| 670 | Inputs = {{ Input = Input {{ SourceOp = "V", Source = "Output", }}, }}, | ||
| 671 | }}, | ||
| 672 | }}, | ||
| 673 | }}"# | ||
| 674 | ) | ||
| 675 | }; | ||
| 676 | |||
| 677 | let expr = ExprEngine::new(); | ||
| 678 | let empty_fields = HashMap::new(); | ||
| 679 | |||
| 680 | // Angle = 0: pure CCW tangential swirl -> particle at (+0.2, 0) gains +Y velocity. | ||
| 681 | let comp_tan = Comp::from_fusion_str(&make_comp(0.0)).unwrap(); | ||
| 682 | let plan_tan = build_particle_plan(&comp_tan, comp_tan.node_by_name["R"]); | ||
| 683 | let mut state_tan = SimState::default(); | ||
| 684 | for f in 0..=4 { | ||
| 685 | step_simulation(&mut state_tan, &comp_tan, &plan_tan, &empty_fields, f, &expr); | ||
| 686 | } | ||
| 687 | let p_tan = state_tan.particles[0]; | ||
| 688 | assert!(p_tan.vel[1] > 0.01, "tangential vortex must swirl +Y at (+X,0), got {:?}", p_tan.vel); | ||
| 689 | |||
| 690 | // Angle = +60: inward spiral -> radius shrinks relative to initial 0.2. | ||
| 691 | let comp_in = Comp::from_fusion_str(&make_comp(60.0)).unwrap(); | ||
| 692 | let plan_in = build_particle_plan(&comp_in, comp_in.node_by_name["R"]); | ||
| 693 | let mut state_in = SimState::default(); | ||
| 694 | for f in 0..=5 { | ||
| 695 | step_simulation(&mut state_in, &comp_in, &plan_in, &empty_fields, f, &expr); | ||
| 696 | } | ||
| 697 | let r_in = state_in.particles[0].pos[0].hypot(state_in.particles[0].pos[1]); | ||
| 698 | assert!(r_in < 0.19, "positive Angle vortex should spiral inward, got r={r_in}"); | ||
| 699 | |||
| 700 | // Angle = -60: outward spiral -> radius grows relative to initial 0.2. | ||
| 701 | let comp_out = Comp::from_fusion_str(&make_comp(-60.0)).unwrap(); | ||
| 702 | let plan_out = build_particle_plan(&comp_out, comp_out.node_by_name["R"]); | ||
| 703 | let mut state_out = SimState::default(); | ||
| 704 | for f in 0..=5 { | ||
| 705 | step_simulation(&mut state_out, &comp_out, &plan_out, &empty_fields, f, &expr); | ||
| 706 | } | ||
| 707 | let r_out = state_out.particles[0].pos[0].hypot(state_out.particles[0].pos[1]); | ||
| 708 | assert!(r_out > 0.21, "negative Angle vortex should spiral outward, got r={r_out}"); | ||
| 709 | } | ||
| 710 | |||
| 711 | #[test] | ||
| 712 | fn test_p_flock_cohesion_separation_alignment_and_perf() { | ||
| 713 | let comp_src = r#"Composition { | ||
| 714 | GlobalRange = { 0, 20 }, | ||
| 715 | RenderRange = { 0, 20 }, | ||
| 716 | Tools = ordered() { | ||
| 717 | EN = BezierSpline { | ||
| 718 | KeyFrames = { | ||
| 719 | [0] = { 1, Flags = { Linear = true } }, | ||
| 720 | [1] = { 0, Flags = { Linear = true } }, | ||
| 721 | }, | ||
| 722 | }, | ||
| 723 | E1 = pEmitter { | ||
| 724 | Inputs = { | ||
| 725 | Number = Input { SourceOp = "EN", Source = "Value", }, | ||
| 726 | Lifespan = Input { Value = 50, }, | ||
| 727 | Region = Input { Value = FuID { "Point" }, }, | ||
| 728 | ["Point.Translate.X"] = Input { Value = -0.08, }, | ||
| 729 | Velocity = Input { Value = 0.0, }, | ||
| 730 | }, | ||
| 731 | }, | ||
| 732 | E2 = pEmitter { | ||
| 733 | Inputs = { | ||
| 734 | Number = Input { SourceOp = "EN", Source = "Value", }, | ||
| 735 | Lifespan = Input { Value = 50, }, | ||
| 736 | Region = Input { Value = FuID { "Point" }, }, | ||
| 737 | ["Point.Translate.X"] = Input { Value = 0.08, }, | ||
| 738 | Velocity = Input { Value = 0.2, }, | ||
| 739 | Angle = Input { Value = 90.0, }, | ||
| 740 | }, | ||
| 741 | }, | ||
| 742 | M = pMerge { | ||
| 743 | Inputs = { | ||
| 744 | Input1 = Input { SourceOp = "E1", Source = "Output", }, | ||
| 745 | Input2 = Input { SourceOp = "E2", Source = "Output", }, | ||
| 746 | }, | ||
| 747 | }, | ||
| 748 | FlockCoh = pFlock { | ||
| 749 | Inputs = { | ||
| 750 | Input = Input { SourceOp = "M", Source = "Output", }, | ||
| 751 | Cohesion = Input { Value = 1.0, }, | ||
| 752 | Separation = Input { Value = 0.0, }, | ||
| 753 | Alignment = Input { Value = 1.0, }, | ||
| 754 | Radius = Input { Value = 0.3, }, | ||
| 755 | Strength = Input { Value = 1.0, }, | ||
| 756 | }, | ||
| 757 | }, | ||
| 758 | FlockSep = pFlock { | ||
| 759 | Inputs = { | ||
| 760 | Input = Input { SourceOp = "M", Source = "Output", }, | ||
| 761 | Cohesion = Input { Value = 0.0, }, | ||
| 762 | Separation = Input { Value = 1.0, }, | ||
| 763 | Alignment = Input { Value = 0.0, }, | ||
| 764 | Radius = Input { Value = 0.4, }, | ||
| 765 | Strength = Input { Value = 1.0, }, | ||
| 766 | }, | ||
| 767 | }, | ||
| 768 | RCoh = pRender { Inputs = { Input = Input { SourceOp = "FlockCoh", Source = "Output", }, }, }, | ||
| 769 | RSep = pRender { Inputs = { Input = Input { SourceOp = "FlockSep", Source = "Output", }, }, }, | ||
| 770 | }, | ||
| 771 | }"#; | ||
| 772 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | ||
| 773 | let expr = ExprEngine::new(); | ||
| 774 | let empty_fields = HashMap::new(); | ||
| 775 | |||
| 776 | // Cohesion + Alignment: particles at x=-0.08 and x=+0.08 pull together and share +Y velocity. | ||
| 777 | let plan_coh = build_particle_plan(&comp, comp.node_by_name["RCoh"]); | ||
| 778 | let mut state_coh = SimState::default(); | ||
| 779 | for f in 0..=4 { | ||
| 780 | step_simulation(&mut state_coh, &comp, &plan_coh, &empty_fields, f, &expr); | ||
| 781 | } | ||
| 782 | let dx_coh = (state_coh.particles[1].pos[0] - state_coh.particles[0].pos[0]).abs(); | ||
| 783 | assert!(dx_coh < 0.155, "cohesion should pull particles closer than 0.16, got {dx_coh}"); | ||
| 784 | assert!(state_coh.particles[0].vel[1] > 0.002, "alignment should pull stationary particle toward neighbor +Y vel"); | ||
| 785 | |||
| 786 | // Separation: particles within repel radius push farther apart. | ||
| 787 | let plan_sep = build_particle_plan(&comp, comp.node_by_name["RSep"]); | ||
| 788 | let mut state_sep = SimState::default(); | ||
| 789 | for f in 0..=4 { | ||
| 790 | step_simulation(&mut state_sep, &comp, &plan_sep, &empty_fields, f, &expr); | ||
| 791 | } | ||
| 792 | let dx_sep = (state_sep.particles[1].pos[0] - state_sep.particles[0].pos[0]).abs(); | ||
| 793 | assert!(dx_sep > 0.165, "separation should push particles farther than 0.16, got {dx_sep}"); | ||
| 794 | |||
| 795 | // Stress check: 2,000 overlapping particles must step quickly without O(N^2) stall. | ||
| 796 | let heavy_src = r#"Composition { | ||
| 797 | GlobalRange = { 0, 5 }, | ||
| 798 | RenderRange = { 0, 5 }, | ||
| 799 | Tools = ordered() { | ||
| 800 | E = pEmitter { | ||
| 801 | Inputs = { | ||
| 802 | Number = Input { Value = 1000, }, | ||
| 803 | Lifespan = Input { Value = 20, }, | ||
| 804 | }, | ||
| 805 | }, | ||
| 806 | F = pFlock { | ||
| 807 | Inputs = { | ||
| 808 | Input = Input { SourceOp = "E", Source = "Output", }, | ||
| 809 | Radius = Input { Value = 0.2, }, | ||
| 810 | }, | ||
| 811 | }, | ||
| 812 | R = pRender { Inputs = { Input = Input { SourceOp = "F", Source = "Output", }, }, }, | ||
| 813 | }, | ||
| 814 | }"#; | ||
| 815 | let heavy_comp = Comp::from_fusion_str(heavy_src).unwrap(); | ||
| 816 | let heavy_plan = build_particle_plan(&heavy_comp, heavy_comp.node_by_name["R"]); | ||
| 817 | let mut heavy_state = SimState::default(); | ||
| 818 | let t0 = Instant::now(); | ||
| 819 | for f in 0..=2 { | ||
| 820 | step_simulation(&mut heavy_state, &heavy_comp, &heavy_plan, &empty_fields, f, &expr); | ||
| 821 | } | ||
| 822 | assert!(heavy_state.particles.len() >= 2000); | ||
| 823 | assert!( | ||
| 824 | t0.elapsed() < std::time::Duration::from_secs(2), | ||
| 825 | "pFlock on 2000+ overlapping particles took too long: {:?}", | ||
| 826 | t0.elapsed() | ||
| 827 | ); | ||
| 828 | } | ||
| 829 | |||
| 830 | #[test] | ||
| 831 | fn test_p_spawn_children_velocity_transfer_and_cap() { | ||
| 832 | let comp_src = r#"Composition { | ||
| 833 | GlobalRange = { 0, 20 }, | ||
| 834 | RenderRange = { 0, 20 }, | ||
| 835 | Tools = ordered() { | ||
| 836 | EN = BezierSpline { | ||
| 837 | KeyFrames = { | ||
| 838 | [0] = { 2, Flags = { Linear = true } }, | ||
| 839 | [1] = { 0, Flags = { Linear = true } }, | ||
| 840 | }, | ||
| 841 | }, | ||
| 842 | E = pEmitter { | ||
| 843 | Inputs = { | ||
| 844 | Number = Input { SourceOp = "EN", Source = "Value", }, | ||
| 845 | Lifespan = Input { Value = 20, }, | ||
| 846 | Velocity = Input { Value = 0.5, }, | ||
| 847 | Angle = Input { Value = 0.0, }, | ||
| 848 | Style = Input { Value = FuID { "ParticleStyleBlob" }, }, | ||
| 849 | ["ParticleStyle.Size"] = Input { Value = 0.6, }, | ||
| 850 | ["ParticleStyle.Red"] = Input { Value = 1.0, }, | ||
| 851 | ["ParticleStyle.Green"] = Input { Value = 0.0, }, | ||
| 852 | ["ParticleStyle.Blue"] = Input { Value = 0.0, }, | ||
| 853 | }, | ||
| 854 | }, | ||
| 855 | S = pSpawn { | ||
| 856 | Inputs = { | ||
| 857 | Input = Input { SourceOp = "E", Source = "Output", }, | ||
| 858 | Number = Input { Value = 3, }, | ||
| 859 | Lifespan = Input { Value = 10, }, | ||
| 860 | VelocityTransfer = Input { Value = 0.5, }, | ||
| 861 | Velocity = Input { Value = 0.2, }, | ||
| 862 | Angle = Input { Value = 90.0, }, | ||
| 863 | Set = Input { Value = 2, }, | ||
| 864 | Style = Input { Value = FuID { "ParticleStyleNGon" }, }, | ||
| 865 | ["ParticleStyle.Red"] = Input { Value = 0.0, }, | ||
| 866 | ["ParticleStyle.Green"] = Input { Value = 1.0, }, | ||
| 867 | ["ParticleStyle.Blue"] = Input { Value = 0.0, }, | ||
| 868 | }, | ||
| 869 | }, | ||
| 870 | R = pRender { | ||
| 871 | Inputs = { Input = Input { SourceOp = "S", Source = "Output", }, }, | ||
| 872 | }, | ||
| 873 | }, | ||
| 874 | }"#; | ||
| 875 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | ||
| 876 | let render_id = comp.node_by_name["R"]; | ||
| 877 | let plan = build_particle_plan(&comp, render_id); | ||
| 878 | let expr = ExprEngine::new(); | ||
| 879 | let empty_fields = HashMap::new(); | ||
| 880 | let mut state = SimState::default(); | ||
| 881 | |||
| 882 | // Frame 0: 2 parents emitted. Frame 1: each parent spawns 3 children => 2 + 6 = 8. | ||
| 883 | // Frame 2: only the 2 original parents spawn (NOT the 6 children!) => 2 + 6 + 6 = 14. | ||
| 884 | for f in 0..=2 { | ||
| 885 | step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); | ||
| 886 | } | ||
| 887 | assert_eq!(state.particles.len(), 14, "expected 2 parents + 12 non-recursive children"); | ||
| 888 | |||
| 889 | let spawn_hash = stable_name_hash("S"); | ||
| 890 | let children: Vec<_> = state.particles.iter().filter(|p| p.emitter_hash == spawn_hash).collect(); | ||
| 891 | assert_eq!(children.len(), 12); | ||
| 892 | for ch in &children { | ||
| 893 | assert_eq!(ch.sets, 1u32 << 1, "child should be assigned to Set 2"); | ||
| 894 | assert_eq!(ch.style_override, Some(ParticleStyleKind::NGon)); | ||
| 895 | assert!((ch.vel[0] - 0.025).abs() < 1e-6, "VelocityTransfer=0.5 of vx=0.05 -> 0.025, got {}", ch.vel[0]); | ||
| 896 | assert!((ch.vel[1] - 0.02).abs() < 1e-6, "Velocity=0.2 at Angle=90 -> vy=0.02, got {}", ch.vel[1]); | ||
| 897 | assert!((ch.color[1] - 1.0).abs() < 1e-5 && ch.color[0] < 1e-5); | ||
| 898 | } | ||
| 899 | |||
| 900 | // Verify rendering includes both parents and children. | ||
| 901 | let mut cache = ParticleCache::default(); | ||
| 902 | let img = render_particles_2d(&mut cache, &comp, render_id, 3.0, [128, 128], &expr, &HashMap::new()); | ||
| 903 | let green_px = img.chunks_exact(4).filter(|c| c[1] > 40 && c[0] < 10 && c[3] > 20).count(); | ||
| 904 | assert!(green_px > 10, "spawned green child particles must render visibly, got {green_px}"); | ||
| 905 | } | ||
| 906 | |||
| 907 | #[test] | ||
| 908 | fn test_p_change_style_color_size_style_and_region() { | ||
| 909 | let comp_src = r#"Composition { | ||
| 910 | GlobalRange = { 0, 10 }, | ||
| 911 | RenderRange = { 0, 10 }, | ||
| 912 | Tools = ordered() { | ||
| 913 | EN = BezierSpline { | ||
| 914 | KeyFrames = { | ||
| 915 | [0] = { 1, Flags = { Linear = true } }, | ||
| 916 | [1] = { 0, Flags = { Linear = true } }, | ||
| 917 | }, | ||
| 918 | }, | ||
| 919 | E_in = pEmitter { | ||
| 920 | Inputs = { | ||
| 921 | Number = Input { SourceOp = "EN", Source = "Value", }, | ||
| 922 | Lifespan = Input { Value = 20, }, | ||
| 923 | Region = Input { Value = FuID { "Point" }, }, | ||
| 924 | ["Point.Translate.X"] = Input { Value = -0.2, }, | ||
| 925 | Style = Input { Value = FuID { "ParticleStylePoint" }, }, | ||
| 926 | ["ParticleStyle.Size"] = Input { Value = 0.2, }, | ||
| 927 | ["ParticleStyle.Red"] = Input { Value = 1.0, }, | ||
| 928 | ["ParticleStyle.Green"] = Input { Value = 0.0, }, | ||
| 929 | ["ParticleStyle.Blue"] = Input { Value = 0.0, }, | ||
| 930 | }, | ||
| 931 | }, | ||
| 932 | E_out = pEmitter { | ||
| 933 | Inputs = { | ||
| 934 | Number = Input { SourceOp = "EN", Source = "Value", }, | ||
| 935 | Lifespan = Input { Value = 20, }, | ||
| 936 | Region = Input { Value = FuID { "Point" }, }, | ||
| 937 | ["Point.Translate.X"] = Input { Value = 0.25, }, | ||
| 938 | Style = Input { Value = FuID { "ParticleStylePoint" }, }, | ||
| 939 | ["ParticleStyle.Size"] = Input { Value = 0.2, }, | ||
| 940 | ["ParticleStyle.Red"] = Input { Value = 1.0, }, | ||
| 941 | ["ParticleStyle.Green"] = Input { Value = 0.0, }, | ||
| 942 | ["ParticleStyle.Blue"] = Input { Value = 0.0, }, | ||
| 943 | }, | ||
| 944 | }, | ||
| 945 | M = pMerge { | ||
| 946 | Inputs = { | ||
| 947 | Input1 = Input { SourceOp = "E_in", Source = "Output", }, | ||
| 948 | Input2 = Input { SourceOp = "E_out", Source = "Output", }, | ||
| 949 | }, | ||
| 950 | }, | ||
| 951 | CS = pChangeStyle { | ||
| 952 | Inputs = { | ||
| 953 | Input = Input { SourceOp = "M", Source = "Output", }, | ||
| 954 | Region = Input { Value = FuID { "SphereRgn" }, }, | ||
| 955 | ["SphereRgn.Translate.X"] = Input { Value = -0.2, }, | ||
| 956 | ["SphereRgn.Size"] = Input { Value = 0.2, }, | ||
| 957 | Style = Input { Value = FuID { "ParticleStyleBlob" }, }, | ||
| 958 | ["ParticleStyle.Size"] = Input { Value = 1.5, }, | ||
| 959 | ["ParticleStyle.Red"] = Input { Value = 0.0, }, | ||
| 960 | ["ParticleStyle.Green"] = Input { Value = 0.0, }, | ||
| 961 | ["ParticleStyle.Blue"] = Input { Value = 1.0, }, | ||
| 962 | Probability = Input { Value = 1.0, }, | ||
| 963 | }, | ||
| 964 | }, | ||
| 965 | R = pRender { | ||
| 966 | Inputs = { Input = Input { SourceOp = "CS", Source = "Output", }, }, | ||
| 967 | }, | ||
| 968 | }, | ||
| 969 | }"#; | ||
| 970 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | ||
| 971 | let render_id = comp.node_by_name["R"]; | ||
| 972 | let plan = build_particle_plan(&comp, render_id); | ||
| 973 | let expr = ExprEngine::new(); | ||
| 974 | let empty_fields = HashMap::new(); | ||
| 975 | let mut state = SimState::default(); | ||
| 976 | for f in 0..=2 { | ||
| 977 | step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); | ||
| 978 | } | ||
| 979 | let p_in = state.particles.iter().find(|p| p.pos[0] < 0.0).unwrap(); | ||
| 980 | let p_out = state.particles.iter().find(|p| p.pos[0] > 0.0).unwrap(); | ||
| 981 | |||
| 982 | assert_eq!(p_in.style_override, Some(ParticleStyleKind::Blob)); | ||
| 983 | assert!((p_in.size - 1.5).abs() < 1e-6); | ||
| 984 | assert!(p_in.color[2] > 0.99 && p_in.color[0] < 0.01); | ||
| 985 | |||
| 986 | assert_eq!(p_out.style_override, None, "particle outside Region must keep original style"); | ||
| 987 | assert!((p_out.size - 0.2).abs() < 1e-6); | ||
| 988 | assert!(p_out.color[0] > 0.99 && p_out.color[2] < 0.01); | ||
| 989 | |||
| 990 | // Rendered buffer must have a large blue blob on the left and a tiny red point on the right. | ||
| 991 | let mut cache = ParticleCache::default(); | ||
| 992 | let img = render_particles_2d(&mut cache, &comp, render_id, 2.0, [100, 100], &expr, &HashMap::new()); | ||
| 993 | let blue_px = img.chunks_exact(4).filter(|c| c[2] > 40 && c[0] < 10 && c[3] > 20).count(); | ||
| 994 | let red_px = img.chunks_exact(4).filter(|c| c[0] > 40 && c[2] < 10 && c[3] > 20).count(); | ||
| 995 | assert!(blue_px > 20, "changed particle must render as a large blue blob, got {blue_px}"); | ||
| 996 | assert_eq!(red_px, 1, "unchanged particle must remain a 1px red point, got {red_px}"); | ||
| 997 | } | ||
| 998 | |||
| 999 | #[test] | ||
| 1000 | fn test_p_gradient_force_luma_gradient_and_gpu_eval() { | ||
| 1001 | let comp_src = r#"Composition { | ||
| 1002 | GlobalRange = { 0, 10 }, | ||
| 1003 | RenderRange = { 0, 10 }, | ||
| 1004 | Tools = ordered() { | ||
| 1005 | RampBG = Background { | ||
| 1006 | Inputs = { | ||
| 1007 | Width = Input { Value = 64, }, | ||
| 1008 | Height = Input { Value = 64, }, | ||
| 1009 | Type = Input { Value = FuID { "Horizontal" }, }, | ||
| 1010 | TopLeftRed = Input { Value = 0.0, }, | ||
| 1011 | TopLeftGreen = Input { Value = 0.0, }, | ||
| 1012 | TopLeftBlue = Input { Value = 0.0, }, | ||
| 1013 | TopRightRed = Input { Value = 1.0, }, | ||
| 1014 | TopRightGreen = Input { Value = 1.0, }, | ||
| 1015 | TopRightBlue = Input { Value = 1.0, }, | ||
| 1016 | }, | ||
| 1017 | }, | ||
| 1018 | EN = BezierSpline { | ||
| 1019 | KeyFrames = { | ||
| 1020 | [0] = { 1, Flags = { Linear = true } }, | ||
| 1021 | [1] = { 0, Flags = { Linear = true } }, | ||
| 1022 | }, | ||
| 1023 | }, | ||
| 1024 | E = pEmitter { | ||
| 1025 | Inputs = { | ||
| 1026 | Number = Input { SourceOp = "EN", Source = "Value", }, | ||
| 1027 | Lifespan = Input { Value = 30, }, | ||
| 1028 | Region = Input { Value = FuID { "Point" }, }, | ||
| 1029 | ["Point.Translate.X"] = Input { Value = 0.0, }, | ||
| 1030 | ["Point.Translate.Y"] = Input { Value = 0.0, }, | ||
| 1031 | Style = Input { Value = FuID { "ParticleStyleBlob" }, }, | ||
| 1032 | ["ParticleStyle.Size"] = Input { Value = 1.0, }, | ||
| 1033 | }, | ||
| 1034 | }, | ||
| 1035 | GF = pGradientForce { | ||
| 1036 | Inputs = { | ||
| 1037 | Input = Input { SourceOp = "E", Source = "Output", }, | ||
| 1038 | Image = Input { SourceOp = "RampBG", Source = "Output", }, | ||
| 1039 | Strength = Input { Value = 1.0, }, | ||
| 1040 | }, | ||
| 1041 | }, | ||
| 1042 | R = pRender { | ||
| 1043 | Inputs = { | ||
| 1044 | Width = Input { Value = 64, }, | ||
| 1045 | Height = Input { Value = 64, }, | ||
| 1046 | Input = Input { SourceOp = "GF", Source = "Output", }, | ||
| 1047 | }, | ||
| 1048 | }, | ||
| 1049 | }, | ||
| 1050 | }"#; | ||
| 1051 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | ||
| 1052 | let render_id = comp.node_by_name["R"]; | ||
| 1053 | let gf_id = comp.node_by_name["GF"]; | ||
| 1054 | let bg_id = comp.node_by_name["RampBG"]; | ||
| 1055 | |||
| 1056 | // 1. Verify bitmap/image source discovery for pGradientForce. | ||
| 1057 | let sources = collect_bitmap_sources(&comp, render_id); | ||
| 1058 | assert_eq!(sources, vec![(gf_id, bg_id)]); | ||
| 1059 | |||
| 1060 | // 2. Build a synthetic left-to-right linear ramp sprite and verify rightward acceleration. | ||
| 1061 | let mut ramp_rgba = vec![0u8; 64 * 64 * 4]; | ||
| 1062 | for y in 0..64 { | ||
| 1063 | for x in 0..64 { | ||
| 1064 | let v = (x * 255 / 63) as u8; | ||
| 1065 | let off = (y * 64 + x) * 4; | ||
| 1066 | ramp_rgba[off] = v; | ||
| 1067 | ramp_rgba[off + 1] = v; | ||
| 1068 | ramp_rgba[off + 2] = v; | ||
| 1069 | ramp_rgba[off + 3] = 255; | ||
| 1070 | } | ||
| 1071 | } | ||
| 1072 | let mut sprites = HashMap::new(); | ||
| 1073 | sprites.insert(gf_id, SpriteImage { size: [64, 64], rgba: ramp_rgba }); | ||
| 1074 | |||
| 1075 | let plan = build_particle_plan(&comp, render_id); | ||
| 1076 | let fields = super::forces::build_gradient_fields(&comp, &plan.modifiers, &sprites); | ||
| 1077 | let expr = ExprEngine::new(); | ||
| 1078 | let mut state = SimState::default(); | ||
| 1079 | for f in 0..=4 { | ||
| 1080 | step_simulation(&mut state, &comp, &plan, &fields, f, &expr); | ||
| 1081 | } | ||
| 1082 | let p = state.particles[0]; | ||
| 1083 | assert!(p.vel[0] > 0.02, "left-to-right bright ramp must push particle +X, got {:?}", p.vel); | ||
| 1084 | assert!(p.vel[1].abs() < 1e-4, "horizontal ramp must have near-zero Y force, got {}", p.vel[1]); | ||
| 1085 | assert!(p.pos[0] > 0.05, "particle should move significantly right, got x={}", p.pos[0]); | ||
| 1086 | |||
| 1087 | // 3. End-to-end GPU evaluation of RampBG -> pGradientForce -> pRender. | ||
| 1088 | let Ok(mut eng) = crate::Engine::new_headless() else { return }; | ||
| 1089 | let (tex, stats) = eng.evaluate(&comp, render_id, 5.0); | ||
| 1090 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | ||
| 1091 | let px = eng.readback_rgba(&tex).unwrap(); | ||
| 1092 | let px_ref = px.as_slice(); | ||
| 1093 | // Particle started at x=32 and moved right into the right half (x > 36). | ||
| 1094 | let right_mass: u64 = (0..64) | ||
| 1095 | .flat_map(|y| (36..64).map(move |x| px_ref[(y * 64 + x) * 4 + 3] as u64)) | ||
| 1096 | .sum(); | ||
| 1097 | let left_mass: u64 = (0..64) | ||
| 1098 | .flat_map(|y| (0..28).map(move |x| px_ref[(y * 64 + x) * 4 + 3] as u64)) | ||
| 1099 | .sum(); | ||
| 1100 | assert!( | ||
| 1101 | right_mass > left_mass * 4 + 100, | ||
| 1102 | "GPU pGradientForce should push particle into right half (left={left_mass}, right={right_mass})" | ||
| 1103 | ); | ||
| 1104 | } |