| author | |
| committer | |
| log | 9704735b5b5d290cd87eee8e4bfaa93c26db239a |
| tree | f58ce335ae550ba8b1a38ae3d3191c7716d3ada2 |
| parent | 49156074669520737fc080e8bf1e2cbacdb4500d |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
19 files changed, 4663 insertions(+), 960 deletions(-)
crates/engine/src/eval/mod.rs+9| ... | ... | @@ -1069,6 +1069,9 @@ impl Engine { |
| 1069 | 1069 | | "sEllipse" |
| 1070 | 1070 | | "sStar" |
| 1071 | 1071 | | "sPolygon" |
| 1072 | | "sBSpline" | |
| 1073 | | "sChangeStyle" | |
| 1074 | | "sText" | |
| 1072 | 1075 | | "sGrid" |
| 1073 | 1076 | | "sMerge" |
| 1074 | 1077 | | "sTransform" |
| ... | ... | @@ -1107,6 +1110,12 @@ impl Engine { |
| 1107 | 1110 | | "pBounce" |
| 1108 | 1111 | | "pVortex" |
| 1109 | 1112 | | "pFlock" |
| 1113 | | "pAvoid" | |
| 1114 | | "pFollow" | |
| 1115 | | "pTangentForce" | |
| 1116 | | "pCustom" | |
| 1117 | | "pCustomForce" | |
| 1118 | | "pImageEmitter" | |
| 1110 | 1119 | | "pSpawn" |
| 1111 | 1120 | | "pChangeStyle" |
| 1112 | 1121 | | "pGradientForce" => self.dummy.clone(), |
crates/engine/src/eval/shapes.rs+125-17| ... | ... | @@ -1,15 +1,19 @@ |
| 1 | 1 | //! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sStar`, `sPolygon`, |
| 2 | //! `sGrid`, `sMerge`, `sTransform`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, `sBoolean`, `sOutline`). | |
| 2 | //! `sBSpline`, `sText`, `sChangeStyle`, `sGrid`, `sMerge`, `sTransform`, `sDuplicate`, `sJitter`, | |
| 3 | //! `sExpand`, `sOffset`, `sBoolean`, `sOutline`). | |
| 3 | 4 | |
| 4 | 5 | mod collect; |
| 6 | mod collect_prims; | |
| 5 | 7 | mod geometry; |
| 8 | mod modifiers; | |
| 6 | 9 | mod raster; |
| 7 | 10 | #[cfg(test)] |
| 8 | 11 | mod tests; |
| 9 | 12 | |
| 13 | use super::warps_masks::bspline::BSplinePoint; | |
| 10 | 14 | use super::*; |
| 11 | 15 | |
| 12 | use collect::collect_shape_tree; | |
| 16 | use collect::collect_shape_tree_by_name; | |
| 13 | 17 | use raster::rasterize_shape_tree_rgba8; |
| 14 | 18 | |
| 15 | 19 | /// Safety cap on total collected leaf primitives so nested `sDuplicate`/`sGrid` cannot blow up memory. |
| ... | ... | @@ -75,6 +79,49 @@ impl Affine2D { |
| 75 | 79 | } |
| 76 | 80 | } |
| 77 | 81 | |
| 82 | #[derive(Clone, Copy, Debug)] | |
| 83 | enum ShapeCmd { | |
| 84 | MoveTo([f32; 2]), | |
| 85 | LineTo([f32; 2]), | |
| 86 | QuadTo([f32; 2], [f32; 2]), | |
| 87 | CurveTo([f32; 2], [f32; 2], [f32; 2]), | |
| 88 | Close, | |
| 89 | } | |
| 90 | ||
| 91 | impl ShapeCmd { | |
| 92 | fn hash_into(self, h: &mut DefaultHasher) { | |
| 93 | match self { | |
| 94 | Self::MoveTo(p) => { | |
| 95 | 0u8.hash(h); | |
| 96 | p[0].to_bits().hash(h); | |
| 97 | p[1].to_bits().hash(h); | |
| 98 | } | |
| 99 | Self::LineTo(p) => { | |
| 100 | 1u8.hash(h); | |
| 101 | p[0].to_bits().hash(h); | |
| 102 | p[1].to_bits().hash(h); | |
| 103 | } | |
| 104 | Self::QuadTo(a, p) => { | |
| 105 | 2u8.hash(h); | |
| 106 | a[0].to_bits().hash(h); | |
| 107 | a[1].to_bits().hash(h); | |
| 108 | p[0].to_bits().hash(h); | |
| 109 | p[1].to_bits().hash(h); | |
| 110 | } | |
| 111 | Self::CurveTo(a, b, p) => { | |
| 112 | 3u8.hash(h); | |
| 113 | a[0].to_bits().hash(h); | |
| 114 | a[1].to_bits().hash(h); | |
| 115 | b[0].to_bits().hash(h); | |
| 116 | b[1].to_bits().hash(h); | |
| 117 | p[0].to_bits().hash(h); | |
| 118 | p[1].to_bits().hash(h); | |
| 119 | } | |
| 120 | Self::Close => 4u8.hash(h), | |
| 121 | } | |
| 122 | } | |
| 123 | } | |
| 124 | ||
| 78 | 125 | #[derive(Clone, Debug)] |
| 79 | 126 | enum ShapePrimKind { |
| 80 | 127 | NGon { sides: u32, width: f32, height: f32 }, |
| ... | ... | @@ -82,6 +129,8 @@ enum ShapePrimKind { |
| 82 | 129 | Ellipse { width: f32, height: f32 }, |
| 83 | 130 | Star { points: u32, depth: f32, width: f32, height: f32, corner_radius: f32 }, |
| 84 | 131 | Polygon { points: Vec<model::PolyPoint>, closed: bool }, |
| 132 | BSpline { points: Vec<BSplinePoint>, closed: bool, tessellation: f32 }, | |
| 133 | Text { cmds: Vec<ShapeCmd> }, | |
| 85 | 134 | } |
| 86 | 135 | |
| 87 | 136 | #[derive(Clone, Copy, Debug)] |
| ... | ... | @@ -102,6 +151,35 @@ struct OutlineStyle { |
| 102 | 151 | write_len: f32, |
| 103 | 152 | } |
| 104 | 153 | |
| 154 | #[derive(Clone, Copy, Debug, Default)] | |
| 155 | struct StyleOverride { | |
| 156 | color: Option<[f32; 4]>, | |
| 157 | solid: Option<bool>, | |
| 158 | border_width: Option<f32>, | |
| 159 | join_style: Option<u8>, | |
| 160 | cap_style: Option<u8>, | |
| 161 | line_type: Option<u8>, | |
| 162 | } | |
| 163 | ||
| 164 | impl StyleOverride { | |
| 165 | /// Combines an inner override with an outer override (outer takes precedence per field). | |
| 166 | fn merge_outer(inner: Option<Self>, outer: Option<Self>) -> Option<Self> { | |
| 167 | match (inner, outer) { | |
| 168 | (None, None) => None, | |
| 169 | (Some(a), None) => Some(a), | |
| 170 | (None, Some(b)) => Some(b), | |
| 171 | (Some(a), Some(b)) => Some(Self { | |
| 172 | color: b.color.or(a.color), | |
| 173 | solid: b.solid.or(a.solid), | |
| 174 | border_width: b.border_width.or(a.border_width), | |
| 175 | join_style: b.join_style.or(a.join_style), | |
| 176 | cap_style: b.cap_style.or(a.cap_style), | |
| 177 | line_type: b.line_type.or(a.line_type), | |
| 178 | }), | |
| 179 | } | |
| 180 | } | |
| 181 | } | |
| 182 | ||
| 105 | 183 | #[derive(Clone, Copy, Debug)] |
| 106 | 184 | enum PathModifier { |
| 107 | 185 | Expand { |
| ... | ... | @@ -176,8 +254,11 @@ enum ShapeTree { |
| 176 | 254 | miter_limit: f32, |
| 177 | 255 | write_pos: f32, |
| 178 | 256 | write_len: f32, |
| 257 | fill_even_odd: bool, | |
| 258 | line_type: u8, | |
| 179 | 259 | }, |
| 180 | 260 | Group(Vec<ShapeTree>), |
| 261 | CombineGroup(Vec<ShapeTree>), | |
| 181 | 262 | Boolean { |
| 182 | 263 | op: ShapeBoolOp, |
| 183 | 264 | color: [f32; 4], |
| ... | ... | @@ -207,6 +288,8 @@ impl ShapeTree { |
| 207 | 288 | miter_limit, |
| 208 | 289 | write_pos, |
| 209 | 290 | write_len, |
| 291 | fill_even_odd, | |
| 292 | line_type, | |
| 210 | 293 | } => { |
| 211 | 294 | 0u8.hash(h); |
| 212 | 295 | match kind { |
| ... | ... | @@ -249,6 +332,24 @@ impl ShapeTree { |
| 249 | 332 | pt.linear.hash(h); |
| 250 | 333 | } |
| 251 | 334 | } |
| 335 | ShapePrimKind::BSpline { points, closed, tessellation } => { | |
| 336 | 6u8.hash(h); | |
| 337 | closed.hash(h); | |
| 338 | tessellation.to_bits().hash(h); | |
| 339 | points.len().hash(h); | |
| 340 | for pt in points { | |
| 341 | pt.x.to_bits().hash(h); | |
| 342 | pt.y.to_bits().hash(h); | |
| 343 | pt.w.to_bits().hash(h); | |
| 344 | } | |
| 345 | } | |
| 346 | ShapePrimKind::Text { cmds } => { | |
| 347 | 7u8.hash(h); | |
| 348 | cmds.len().hash(h); | |
| 349 | for cmd in cmds { | |
| 350 | cmd.hash_into(h); | |
| 351 | } | |
| 352 | } | |
| 252 | 353 | } |
| 253 | 354 | xform.hash_into(h); |
| 254 | 355 | for c in color { |
| ... | ... | @@ -261,6 +362,8 @@ impl ShapeTree { |
| 261 | 362 | miter_limit.to_bits().hash(h); |
| 262 | 363 | write_pos.to_bits().hash(h); |
| 263 | 364 | write_len.to_bits().hash(h); |
| 365 | fill_even_odd.hash(h); | |
| 366 | line_type.hash(h); | |
| 264 | 367 | } |
| 265 | 368 | ShapeTree::Group(children) => { |
| 266 | 369 | 1u8.hash(h); |
| ... | ... | @@ -269,6 +372,13 @@ impl ShapeTree { |
| 269 | 372 | ch.hash_into(h); |
| 270 | 373 | } |
| 271 | 374 | } |
| 375 | ShapeTree::CombineGroup(children) => { | |
| 376 | 4u8.hash(h); | |
| 377 | children.len().hash(h); | |
| 378 | for ch in children { | |
| 379 | ch.hash_into(h); | |
| 380 | } | |
| 381 | } | |
| 272 | 382 | ShapeTree::Boolean { op, color, opacity, keep_style, a, b } => { |
| 273 | 383 | 2u8.hash(h); |
| 274 | 384 | (*op as u8).hash(h); |
| ... | ... | @@ -311,21 +421,19 @@ impl Engine { |
| 311 | 421 | let blend = 1.0_f32; |
| 312 | 422 | |
| 313 | 423 | let mut prim_budget = MAX_SHAPE_PRIMITIVES; |
| 314 | let shape_tree = node | |
| 315 | .connected_node("Input") | |
| 316 | .and_then(|s| comp.find_node(s)) | |
| 317 | .and_then(|src_id| { | |
| 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 | ) | |
| 328 | }); | |
| 424 | let shape_tree = node.connected_node("Input").and_then(|src_name| { | |
| 425 | collect_shape_tree_by_name( | |
| 426 | comp, | |
| 427 | src_name, | |
| 428 | time, | |
| 429 | &self.expr, | |
| 430 | Affine2D::identity(), | |
| 431 | None, | |
| 432 | None, | |
| 433 | 0, | |
| 434 | &mut prim_budget, | |
| 435 | ) | |
| 436 | }); | |
| 329 | 437 | |
| 330 | 438 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); |
| 331 | 439 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
crates/engine/src/eval/shapes/collect.rs+187-266| ... | ... | @@ -1,61 +1,53 @@ |
| 1 | 1 | //! Graph collection for 2D vector shape nodes (`sNGon`, `sRectangle`, `sEllipse`, `sStar`, |
| 2 | //! `sPolygon`, `sTransform`, `sMerge`, `sGrid`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, | |
| 3 | //! `sOutline`, `sBoolean`). | |
| 2 | //! `sPolygon`, `sBSpline`, `sText`, `sChangeStyle`, `sTransform`, `sMerge`, `sGrid`, | |
| 3 | //! `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, `sOutline`, `sBoolean`). | |
| 4 | 4 | |
| 5 | use model::{Comp, ExprEngine, Node, NodeId, ParamValue}; | |
| 5 | use model::{Comp, ExprEngine, Node, NodeId}; | |
| 6 | 6 | |
| 7 | use super::{Affine2D, OutlineStyle, PathModifier, ShapeBoolOp, ShapePrimKind, ShapeTree}; | |
| 7 | use super::collect_prims::{ | |
| 8 | collect_basic_primitive, collect_raw_bspline_by_name, collect_s_change_style, collect_s_text, | |
| 9 | eval_first_num, eval_xy_or_point, is_point_binding, | |
| 10 | }; | |
| 11 | use super::{Affine2D, OutlineStyle, PathModifier, ShapeBoolOp, ShapeTree, StyleOverride}; | |
| 8 | 12 | |
| 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( | |
| 13 | #[allow(clippy::too_many_arguments)] | |
| 14 | pub(super) fn collect_shape_tree_by_name( | |
| 26 | 15 | comp: &Comp, |
| 27 | node: &Node, | |
| 28 | x_keys: &[&str], | |
| 29 | y_keys: &[&str], | |
| 30 | point_key: &str, | |
| 16 | name: &str, | |
| 31 | 17 | time: f64, |
| 32 | default: [f32; 2], | |
| 33 | 18 | 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; | |
| 19 | parent_xform: Affine2D, | |
| 20 | outline_override: Option<OutlineStyle>, | |
| 21 | style_override: Option<StyleOverride>, | |
| 22 | depth: usize, | |
| 23 | prim_budget: &mut usize, | |
| 24 | ) -> Option<ShapeTree> { | |
| 25 | if depth > 32 || *prim_budget == 0 { | |
| 26 | return None; | |
| 52 | 27 | } |
| 53 | if let Some(src) = &binding.source_op { | |
| 54 | if comp.poly_paths.contains_key(src) { | |
| 55 | return true; | |
| 56 | } | |
| 28 | if let Some(id) = comp.find_node(name) { | |
| 29 | return collect_shape_tree( | |
| 30 | comp, | |
| 31 | id, | |
| 32 | time, | |
| 33 | expr, | |
| 34 | parent_xform, | |
| 35 | outline_override, | |
| 36 | style_override, | |
| 37 | depth, | |
| 38 | prim_budget, | |
| 39 | ); | |
| 57 | 40 | } |
| 58 | false | |
| 41 | collect_raw_bspline_by_name( | |
| 42 | comp, | |
| 43 | name, | |
| 44 | time, | |
| 45 | expr, | |
| 46 | parent_xform, | |
| 47 | outline_override, | |
| 48 | style_override, | |
| 49 | prim_budget, | |
| 50 | ) | |
| 59 | 51 | } |
| 60 | 52 | |
| 61 | 53 | /// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. |
| ... | ... | @@ -72,45 +64,6 @@ fn parse_bool_op(node: &Node) -> Option<ShapeBoolOp> { |
| 72 | 64 | } |
| 73 | 65 | } |
| 74 | 66 | |
| 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 | 67 | #[allow(clippy::too_many_arguments)] |
| 115 | 68 | pub(super) fn collect_shape_tree( |
| 116 | 69 | comp: &Comp, |
| ... | ... | @@ -119,6 +72,7 @@ pub(super) fn collect_shape_tree( |
| 119 | 72 | expr: &ExprEngine, |
| 120 | 73 | parent_xform: Affine2D, |
| 121 | 74 | outline_override: Option<OutlineStyle>, |
| 75 | style_override: Option<StyleOverride>, | |
| 122 | 76 | depth: usize, |
| 123 | 77 | prim_budget: &mut usize, |
| 124 | 78 | ) -> Option<ShapeTree> { |
| ... | ... | @@ -130,15 +84,15 @@ pub(super) fn collect_shape_tree( |
| 130 | 84 | return node |
| 131 | 85 | .connected_node("Input") |
| 132 | 86 | .or_else(|| node.connected_node("Input1")) |
| 133 | .and_then(|s| comp.find_node(s)) | |
| 134 | .and_then(|id| { | |
| 135 | collect_shape_tree( | |
| 87 | .and_then(|s| { | |
| 88 | collect_shape_tree_by_name( | |
| 136 | 89 | comp, |
| 137 | id, | |
| 90 | s, | |
| 138 | 91 | time, |
| 139 | 92 | expr, |
| 140 | 93 | parent_xform, |
| 141 | 94 | outline_override, |
| 95 | style_override, | |
| 142 | 96 | depth + 1, |
| 143 | 97 | prim_budget, |
| 144 | 98 | ) |
| ... | ... | @@ -146,122 +100,43 @@ pub(super) fn collect_shape_tree( |
| 146 | 100 | } |
| 147 | 101 | |
| 148 | 102 | 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( | |
| 103 | "sNGon" | "sRectangle" | "sEllipse" | "sStar" | "sPolygon" | "sBSpline" => { | |
| 104 | collect_basic_primitive( | |
| 162 | 105 | comp, |
| 163 | 106 | node, |
| 164 | &["XPivot", "Pivot.X"], | |
| 165 | &["YPivot", "Pivot.Y"], | |
| 166 | "Pivot", | |
| 167 | 107 | time, |
| 168 | [0.0, 0.0], | |
| 169 | 108 | 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 | }) | |
| 109 | parent_xform, | |
| 110 | outline_override, | |
| 111 | style_override, | |
| 112 | prim_budget, | |
| 113 | ) | |
| 259 | 114 | } |
| 115 | "sText" => collect_s_text( | |
| 116 | comp, | |
| 117 | node, | |
| 118 | time, | |
| 119 | expr, | |
| 120 | parent_xform, | |
| 121 | outline_override, | |
| 122 | style_override, | |
| 123 | prim_budget, | |
| 124 | ), | |
| 125 | "sChangeStyle" => collect_s_change_style( | |
| 126 | comp, | |
| 127 | node, | |
| 128 | time, | |
| 129 | expr, | |
| 130 | parent_xform, | |
| 131 | outline_override, | |
| 132 | style_override, | |
| 133 | depth, | |
| 134 | prim_budget, | |
| 135 | ), | |
| 260 | 136 | "sTransform" => { |
| 261 | let src_id = node | |
| 137 | let src_name = node | |
| 262 | 138 | .connected_node("Input") |
| 263 | .or_else(|| node.connected_node("Input1")) | |
| 264 | .and_then(|s| comp.find_node(s))?; | |
| 139 | .or_else(|| node.connected_node("Input1"))?; | |
| 265 | 140 | let [ox, oy] = eval_xy_or_point( |
| 266 | 141 | comp, |
| 267 | 142 | node, |
| ... | ... | @@ -292,13 +167,22 @@ pub(super) fn collect_shape_tree( |
| 292 | 167 | .mul(Affine2D::scale(sx, sy)) |
| 293 | 168 | .mul(Affine2D::translate(-px, -py)); |
| 294 | 169 | let combined = parent_xform.mul(local); |
| 295 | collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1, prim_budget) | |
| 170 | collect_shape_tree_by_name( | |
| 171 | comp, | |
| 172 | src_name, | |
| 173 | time, | |
| 174 | expr, | |
| 175 | combined, | |
| 176 | outline_override, | |
| 177 | style_override, | |
| 178 | depth + 1, | |
| 179 | prim_budget, | |
| 180 | ) | |
| 296 | 181 | } |
| 297 | 182 | "sDuplicate" => { |
| 298 | let src_id = node | |
| 183 | let src_name = node | |
| 299 | 184 | .connected_node("Input") |
| 300 | .or_else(|| node.connected_node("Input1")) | |
| 301 | .and_then(|s| comp.find_node(s))?; | |
| 185 | .or_else(|| node.connected_node("Input1"))?; | |
| 302 | 186 | let copies = comp.eval_number(node, "Copies", time, 2.0, expr).round().clamp(0.0, 256.0) as usize; |
| 303 | 187 | if copies == 0 { |
| 304 | 188 | return None; |
| ... | ... | @@ -349,13 +233,14 @@ pub(super) fn collect_shape_tree( |
| 349 | 233 | } |
| 350 | 234 | let copy_time = time + (i as f64) * time_offset; |
| 351 | 235 | let copy_xf = parent_xform.mul(cum_xf); |
| 352 | if let Some(tree) = collect_shape_tree( | |
| 236 | if let Some(tree) = collect_shape_tree_by_name( | |
| 353 | 237 | comp, |
| 354 | src_id, | |
| 238 | src_name, | |
| 355 | 239 | copy_time, |
| 356 | 240 | expr, |
| 357 | 241 | copy_xf, |
| 358 | 242 | outline_override, |
| 243 | style_override, | |
| 359 | 244 | depth + 1, |
| 360 | 245 | prim_budget, |
| 361 | 246 | ) { |
| ... | ... | @@ -370,10 +255,9 @@ pub(super) fn collect_shape_tree( |
| 370 | 255 | } |
| 371 | 256 | } |
| 372 | 257 | "sJitter" => { |
| 373 | let src_id = node | |
| 258 | let src_name = node | |
| 374 | 259 | .connected_node("Input") |
| 375 | .or_else(|| node.connected_node("Input1")) | |
| 376 | .and_then(|s| comp.find_node(s))?; | |
| 260 | .or_else(|| node.connected_node("Input1"))?; | |
| 377 | 261 | |
| 378 | 262 | let has_x = node.inputs.contains_key("XAmount") |
| 379 | 263 | || node.inputs.contains_key("PositionX") |
| ... | ... | @@ -408,13 +292,14 @@ pub(super) fn collect_shape_tree( |
| 408 | 292 | let per_shape = matches!(node.static_str("Mode").or_else(|| node.static_str("JitterMode")), Some("Shape" | "PerShape")) |
| 409 | 293 | || comp.eval_number(node, "PerShape", time, 0.0, expr) > 0.5; |
| 410 | 294 | |
| 411 | let child = collect_shape_tree( | |
| 295 | let child = collect_shape_tree_by_name( | |
| 412 | 296 | comp, |
| 413 | src_id, | |
| 297 | src_name, | |
| 414 | 298 | time, |
| 415 | 299 | expr, |
| 416 | 300 | Affine2D::identity(), |
| 417 | 301 | outline_override, |
| 302 | style_override, | |
| 418 | 303 | depth + 1, |
| 419 | 304 | prim_budget, |
| 420 | 305 | )?; |
| ... | ... | @@ -447,34 +332,35 @@ pub(super) fn collect_shape_tree( |
| 447 | 332 | }) |
| 448 | 333 | } |
| 449 | 334 | "sExpand" => { |
| 450 | let src_id = node | |
| 335 | let src_name = node | |
| 451 | 336 | .connected_node("Input") |
| 452 | .or_else(|| node.connected_node("Input1")) | |
| 453 | .and_then(|s| comp.find_node(s))?; | |
| 337 | .or_else(|| node.connected_node("Input1"))?; | |
| 454 | 338 | let amount = eval_first_num(comp, node, &["Amount", "Distance", "Expand", "Offset"], time, 0.0, expr) as f32; |
| 455 | 339 | let join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; |
| 456 | 340 | let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; |
| 457 | 341 | |
| 458 | 342 | if amount.abs() <= 1e-6 { |
| 459 | return collect_shape_tree( | |
| 343 | return collect_shape_tree_by_name( | |
| 460 | 344 | comp, |
| 461 | src_id, | |
| 345 | src_name, | |
| 462 | 346 | time, |
| 463 | 347 | expr, |
| 464 | 348 | parent_xform, |
| 465 | 349 | outline_override, |
| 350 | style_override, | |
| 466 | 351 | depth + 1, |
| 467 | 352 | prim_budget, |
| 468 | 353 | ); |
| 469 | 354 | } |
| 470 | 355 | |
| 471 | let child = collect_shape_tree( | |
| 356 | let child = collect_shape_tree_by_name( | |
| 472 | 357 | comp, |
| 473 | src_id, | |
| 358 | src_name, | |
| 474 | 359 | time, |
| 475 | 360 | expr, |
| 476 | 361 | Affine2D::identity(), |
| 477 | 362 | outline_override, |
| 363 | style_override, | |
| 478 | 364 | depth + 1, |
| 479 | 365 | prim_budget, |
| 480 | 366 | )?; |
| ... | ... | @@ -489,10 +375,9 @@ pub(super) fn collect_shape_tree( |
| 489 | 375 | }) |
| 490 | 376 | } |
| 491 | 377 | "sOffset" => { |
| 492 | let src_id = node | |
| 378 | let src_name = node | |
| 493 | 379 | .connected_node("Input") |
| 494 | .or_else(|| node.connected_node("Input1")) | |
| 495 | .and_then(|s| comp.find_node(s))?; | |
| 380 | .or_else(|| node.connected_node("Input1"))?; | |
| 496 | 381 | |
| 497 | 382 | let mut offset_x = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; |
| 498 | 383 | let mut offset_y = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; |
| ... | ... | @@ -513,25 +398,27 @@ pub(super) fn collect_shape_tree( |
| 513 | 398 | // Fast path: pure 2D translation with no contour normal offset or path position shift. |
| 514 | 399 | if contour_offset.abs() <= 1e-6 && position.abs() <= 1e-6 { |
| 515 | 400 | let combined = parent_xform.mul(Affine2D::translate(offset_x, offset_y)); |
| 516 | return collect_shape_tree( | |
| 401 | return collect_shape_tree_by_name( | |
| 517 | 402 | comp, |
| 518 | src_id, | |
| 403 | src_name, | |
| 519 | 404 | time, |
| 520 | 405 | expr, |
| 521 | 406 | combined, |
| 522 | 407 | outline_override, |
| 408 | style_override, | |
| 523 | 409 | depth + 1, |
| 524 | 410 | prim_budget, |
| 525 | 411 | ); |
| 526 | 412 | } |
| 527 | 413 | |
| 528 | let child = collect_shape_tree( | |
| 414 | let child = collect_shape_tree_by_name( | |
| 529 | 415 | comp, |
| 530 | src_id, | |
| 416 | src_name, | |
| 531 | 417 | time, |
| 532 | 418 | expr, |
| 533 | 419 | Affine2D::identity(), |
| 534 | 420 | outline_override, |
| 421 | style_override, | |
| 535 | 422 | depth + 1, |
| 536 | 423 | prim_budget, |
| 537 | 424 | )?; |
| ... | ... | @@ -561,14 +448,15 @@ pub(super) fn collect_shape_tree( |
| 561 | 448 | ports.sort_by_key(|&(idx, _)| idx); |
| 562 | 449 | let mut children = Vec::new(); |
| 563 | 450 | 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( | |
| 451 | if let Some(src_name) = node.connected_node(port) { | |
| 452 | if let Some(tree) = collect_shape_tree_by_name( | |
| 566 | 453 | comp, |
| 567 | src_id, | |
| 454 | src_name, | |
| 568 | 455 | time, |
| 569 | 456 | expr, |
| 570 | 457 | parent_xform, |
| 571 | 458 | outline_override, |
| 459 | style_override, | |
| 572 | 460 | depth + 1, |
| 573 | 461 | prim_budget, |
| 574 | 462 | ) { |
| ... | ... | @@ -583,10 +471,9 @@ pub(super) fn collect_shape_tree( |
| 583 | 471 | } |
| 584 | 472 | } |
| 585 | 473 | "sGrid" => { |
| 586 | let src_id = node | |
| 474 | let src_name = node | |
| 587 | 475 | .connected_node("Input") |
| 588 | .or_else(|| node.connected_node("Input1")) | |
| 589 | .and_then(|s| comp.find_node(s))?; | |
| 476 | .or_else(|| node.connected_node("Input1"))?; | |
| 590 | 477 | let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; |
| 591 | 478 | let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; |
| 592 | 479 | let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32; |
| ... | ... | @@ -600,13 +487,14 @@ pub(super) fn collect_shape_tree( |
| 600 | 487 | } |
| 601 | 488 | let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off; |
| 602 | 489 | let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty)); |
| 603 | if let Some(tree) = collect_shape_tree( | |
| 490 | if let Some(tree) = collect_shape_tree_by_name( | |
| 604 | 491 | comp, |
| 605 | src_id, | |
| 492 | src_name, | |
| 606 | 493 | time, |
| 607 | 494 | expr, |
| 608 | 495 | cell_xf, |
| 609 | 496 | outline_override, |
| 497 | style_override, | |
| 610 | 498 | depth + 1, |
| 611 | 499 | prim_budget, |
| 612 | 500 | ) { |
| ... | ... | @@ -617,25 +505,34 @@ pub(super) fn collect_shape_tree( |
| 617 | 505 | if children.is_empty() { |
| 618 | 506 | None |
| 619 | 507 | } else { |
| 620 | Some(ShapeTree::Group(children)) | |
| 508 | Some(ShapeTree::CombineGroup(children)) | |
| 621 | 509 | } |
| 622 | 510 | } |
| 623 | 511 | "sOutline" => { |
| 624 | let src_id = node | |
| 512 | let src_name = node | |
| 625 | 513 | .connected_node("Input") |
| 626 | .or_else(|| node.connected_node("Input1")) | |
| 627 | .and_then(|s| comp.find_node(s))?; | |
| 514 | .or_else(|| node.connected_node("Input1"))?; | |
| 628 | 515 | let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr) as f32; |
| 629 | 516 | if thickness <= 0.0 { |
| 630 | 517 | return None; |
| 631 | 518 | } |
| 632 | 519 | 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; | |
| 520 | let cap = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; | |
| 634 | 521 | let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; |
| 635 | 522 | let write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; |
| 636 | 523 | let write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; |
| 637 | 524 | 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) | |
| 525 | collect_shape_tree_by_name( | |
| 526 | comp, | |
| 527 | src_name, | |
| 528 | time, | |
| 529 | expr, | |
| 530 | parent_xform, | |
| 531 | Some(style), | |
| 532 | style_override, | |
| 533 | depth + 1, | |
| 534 | prim_budget, | |
| 535 | ) | |
| 639 | 536 | } |
| 640 | 537 | "sBoolean" => { |
| 641 | 538 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; |
| ... | ... | @@ -643,39 +540,44 @@ pub(super) fn collect_shape_tree( |
| 643 | 540 | let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; |
| 644 | 541 | let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; |
| 645 | 542 | 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]; | |
| 543 | let mut keep_style = node.static_str("StyleMode").unwrap_or("Replace") == "Keep"; | |
| 544 | let mut color = [r * opacity, g * opacity, b_col * opacity, a_col * opacity]; | |
| 545 | if let Some(sv) = style_override { | |
| 546 | if let Some(c) = sv.color { | |
| 547 | color = c; | |
| 548 | keep_style = false; | |
| 549 | } | |
| 550 | } | |
| 551 | let child_sv = if keep_style { style_override } else { None }; | |
| 648 | 552 | let a = node |
| 649 | 553 | .connected_node("Input1") |
| 650 | 554 | .or_else(|| node.connected_node("Input")) |
| 651 | .and_then(|s| comp.find_node(s)) | |
| 652 | .and_then(|id| { | |
| 653 | collect_shape_tree( | |
| 555 | .and_then(|s| { | |
| 556 | collect_shape_tree_by_name( | |
| 654 | 557 | comp, |
| 655 | id, | |
| 558 | s, | |
| 656 | 559 | time, |
| 657 | 560 | expr, |
| 658 | 561 | parent_xform, |
| 659 | 562 | outline_override, |
| 563 | child_sv, | |
| 660 | 564 | depth + 1, |
| 661 | 565 | prim_budget, |
| 662 | 566 | ) |
| 663 | 567 | })?; |
| 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 | }); | |
| 568 | let b_opt = node.connected_node("Input2").and_then(|s| { | |
| 569 | collect_shape_tree_by_name( | |
| 570 | comp, | |
| 571 | s, | |
| 572 | time, | |
| 573 | expr, | |
| 574 | parent_xform, | |
| 575 | outline_override, | |
| 576 | child_sv, | |
| 577 | depth + 1, | |
| 578 | prim_budget, | |
| 579 | ) | |
| 580 | }); | |
| 679 | 581 | // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty. |
| 680 | 582 | let (op, b) = match (parse_bool_op(node), b_opt) { |
| 681 | 583 | (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())), |
| ... | ... | @@ -692,15 +594,34 @@ pub(super) fn collect_shape_tree( |
| 692 | 594 | }) |
| 693 | 595 | } |
| 694 | 596 | "PipeRouter" | "Fuse.Wireless" => { |
| 695 | let src_id = node | |
| 597 | let src_name = node | |
| 696 | 598 | .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) | |
| 599 | .or_else(|| node.connected_node("Input1"))?; | |
| 600 | collect_shape_tree_by_name( | |
| 601 | comp, | |
| 602 | src_name, | |
| 603 | time, | |
| 604 | expr, | |
| 605 | parent_xform, | |
| 606 | outline_override, | |
| 607 | style_override, | |
| 608 | depth + 1, | |
| 609 | prim_budget, | |
| 610 | ) | |
| 700 | 611 | } |
| 701 | 612 | "MacroOperator" | "GroupOperator" => { |
| 702 | 613 | let out_id = node.macro_output?; |
| 703 | collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1, prim_budget) | |
| 614 | collect_shape_tree( | |
| 615 | comp, | |
| 616 | out_id, | |
| 617 | time, | |
| 618 | expr, | |
| 619 | parent_xform, | |
| 620 | outline_override, | |
| 621 | style_override, | |
| 622 | depth + 1, | |
| 623 | prim_budget, | |
| 624 | ) | |
| 704 | 625 | } |
| 705 | 626 | _ => None, |
| 706 | 627 | } |
crates/engine/src/eval/shapes/collect_prims.rs created+684| ... | ... | @@ -0,0 +1,684 @@ |
| 1 | //! Collection helpers for leaf 2D shape primitives (`sNGon`, `sRectangle`, `sEllipse`, | |
| 2 | //! `sStar`, `sPolygon`, `sBSpline`, `sText`) and `sChangeStyle`. | |
| 3 | ||
| 4 | use model::{Comp, ExprEngine, InputBinding, LuaKey, Node, NodeId, ParamValue}; | |
| 5 | ||
| 6 | use super::super::warps_masks::bspline::{eval_bspline_shape, find_tool_table_in_tools}; | |
| 7 | use super::collect::collect_shape_tree_by_name; | |
| 8 | use super::{ | |
| 9 | Affine2D, OutlineStyle, ShapeCmd, ShapePrimKind, ShapeTree, StyleOverride, | |
| 10 | }; | |
| 11 | ||
| 12 | pub(super) fn eval_first_num( | |
| 13 | comp: &Comp, | |
| 14 | node: &Node, | |
| 15 | keys: &[&str], | |
| 16 | time: f64, | |
| 17 | default: f64, | |
| 18 | expr: &ExprEngine, | |
| 19 | ) -> f64 { | |
| 20 | for &k in keys { | |
| 21 | if node.inputs.contains_key(k) { | |
| 22 | return comp.eval_number(node, k, time, default, expr); | |
| 23 | } | |
| 24 | } | |
| 25 | default | |
| 26 | } | |
| 27 | ||
| 28 | pub(super) fn eval_xy_or_point( | |
| 29 | comp: &Comp, | |
| 30 | node: &Node, | |
| 31 | x_keys: &[&str], | |
| 32 | y_keys: &[&str], | |
| 33 | point_key: &str, | |
| 34 | time: f64, | |
| 35 | default: [f32; 2], | |
| 36 | expr: &ExprEngine, | |
| 37 | ) -> [f32; 2] { | |
| 38 | eval_xy_or_point_keys(comp, node, x_keys, y_keys, &[point_key], time, default, expr) | |
| 39 | } | |
| 40 | ||
| 41 | fn eval_xy_or_point_keys( | |
| 42 | comp: &Comp, | |
| 43 | node: &Node, | |
| 44 | x_keys: &[&str], | |
| 45 | y_keys: &[&str], | |
| 46 | point_keys: &[&str], | |
| 47 | time: f64, | |
| 48 | default: [f32; 2], | |
| 49 | expr: &ExprEngine, | |
| 50 | ) -> [f32; 2] { | |
| 51 | let mut pt = default; | |
| 52 | for &pk in point_keys { | |
| 53 | if node.inputs.contains_key(pk) { | |
| 54 | let p = comp.eval_point(node, pk, time, [default[0] as f64, default[1] as f64], expr); | |
| 55 | pt = [p[0] as f32, p[1] as f32]; | |
| 56 | break; | |
| 57 | } | |
| 58 | } | |
| 59 | let x = eval_first_num(comp, node, x_keys, time, pt[0] as f64, expr) as f32; | |
| 60 | let y = eval_first_num(comp, node, y_keys, time, pt[1] as f64, expr) as f32; | |
| 61 | [x, y] | |
| 62 | } | |
| 63 | ||
| 64 | pub(super) fn is_point_binding(comp: &Comp, node: &Node, key: &str) -> bool { | |
| 65 | let Some(binding) = node.inputs.get(key) else { | |
| 66 | return false; | |
| 67 | }; | |
| 68 | if matches!(binding.value, Some(ParamValue::Point(_))) { | |
| 69 | return true; | |
| 70 | } | |
| 71 | if let Some(src) = &binding.source_op { | |
| 72 | if comp.poly_paths.contains_key(src) { | |
| 73 | return true; | |
| 74 | } | |
| 75 | } | |
| 76 | false | |
| 77 | } | |
| 78 | ||
| 79 | fn eval_text_anchor_h(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { | |
| 80 | if node.inputs.contains_key("HorizontalLeftCenterRight") { | |
| 81 | return comp.eval_number(node, "HorizontalLeftCenterRight", time, 0.0, expr) as f32; | |
| 82 | } | |
| 83 | if let Some(s) = node.static_str("HAnchor") { | |
| 84 | return match s { | |
| 85 | "Left" => -1.0, | |
| 86 | "Right" => 1.0, | |
| 87 | _ => 0.0, | |
| 88 | }; | |
| 89 | } | |
| 90 | if node.inputs.contains_key("HAnchor") { | |
| 91 | return comp.eval_number(node, "HAnchor", time, 0.0, expr) as f32; | |
| 92 | } | |
| 93 | if comp.eval_number(node, "HorizontalJustificationLeft", time, 0.0, expr) > 0.5 { | |
| 94 | return -1.0; | |
| 95 | } | |
| 96 | if comp.eval_number(node, "HorizontalJustificationRight", time, 0.0, expr) > 0.5 { | |
| 97 | return 1.0; | |
| 98 | } | |
| 99 | if comp.eval_number(node, "HorizontalJustificationCenter", time, 0.0, expr) > 0.5 { | |
| 100 | return 0.0; | |
| 101 | } | |
| 102 | let jnew = comp.eval_number(node, "HorizontalJustificationNew", time, -1.0, expr).round() as i32; | |
| 103 | match jnew { | |
| 104 | 0 => -1.0, | |
| 105 | 2 => 1.0, | |
| 106 | _ => 0.0, | |
| 107 | } | |
| 108 | } | |
| 109 | ||
| 110 | fn eval_text_anchor_v(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { | |
| 111 | if node.inputs.contains_key("VerticalTopCenterBottom") { | |
| 112 | return comp.eval_number(node, "VerticalTopCenterBottom", time, 0.0, expr) as f32; | |
| 113 | } | |
| 114 | if let Some(s) = node.static_str("VAnchor") { | |
| 115 | return match s { | |
| 116 | "Top" => -1.0, | |
| 117 | "Bottom" => 1.0, | |
| 118 | _ => 0.0, | |
| 119 | }; | |
| 120 | } | |
| 121 | if node.inputs.contains_key("VAnchor") { | |
| 122 | return comp.eval_number(node, "VAnchor", time, 0.0, expr) as f32; | |
| 123 | } | |
| 124 | if comp.eval_number(node, "VerticalJustificationTop", time, 0.0, expr) > 0.5 { | |
| 125 | return -1.0; | |
| 126 | } | |
| 127 | if comp.eval_number(node, "VerticalJustificationBottom", time, 0.0, expr) > 0.5 { | |
| 128 | return 1.0; | |
| 129 | } | |
| 130 | if comp.eval_number(node, "VerticalJustificationCenter", time, 0.0, expr) > 0.5 { | |
| 131 | return 0.0; | |
| 132 | } | |
| 133 | let jnew = comp.eval_number(node, "VerticalJustificationNew", time, -1.0, expr).round() as i32; | |
| 134 | match jnew { | |
| 135 | 0 => -1.0, | |
| 136 | 2 => 1.0, | |
| 137 | _ => 0.0, | |
| 138 | } | |
| 139 | } | |
| 140 | ||
| 141 | fn parse_line_type(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> u8 { | |
| 142 | for key in ["LineType", "LineStyle"] { | |
| 143 | if let Some(s) = node.static_str(key) { | |
| 144 | return match s { | |
| 145 | "Dash" => 1, | |
| 146 | "Dot" => 2, | |
| 147 | "DashDot" | "Dash Dot" => 3, | |
| 148 | "DashDotDot" | "Dash Dot Dot" => 4, | |
| 149 | _ => 0, | |
| 150 | }; | |
| 151 | } | |
| 152 | if node.inputs.contains_key(key) { | |
| 153 | return comp.eval_number(node, key, time, 0.0, expr).round().clamp(0.0, 4.0) as u8; | |
| 154 | } | |
| 155 | } | |
| 156 | 0 | |
| 157 | } | |
| 158 | ||
| 159 | fn extract_polygon_polyline( | |
| 160 | comp: &Comp, | |
| 161 | node: &Node, | |
| 162 | time: f64, | |
| 163 | solid: bool, | |
| 164 | expr: &ExprEngine, | |
| 165 | ) -> (Vec<model::PolyPoint>, bool) { | |
| 166 | let explicit_closed = if node.inputs.contains_key("Closed") { | |
| 167 | Some(comp.eval_number(node, "Closed", time, if solid { 1.0 } else { 0.0 }, expr) > 0.5) | |
| 168 | } else { | |
| 169 | None | |
| 170 | }; | |
| 171 | ||
| 172 | if let Some(src) = node.connected_node("Polyline").or_else(|| node.connected_node("PolyLine")) { | |
| 173 | if let Some(pts) = comp.eval_polyline_spline(src, time) { | |
| 174 | return (pts, explicit_closed.unwrap_or(true)); | |
| 175 | } | |
| 176 | if let Some(pp) = comp.poly_paths.get(src) { | |
| 177 | return (pp.points.clone(), explicit_closed.unwrap_or(pp.closed || solid)); | |
| 178 | } | |
| 179 | } | |
| 180 | ||
| 181 | if let Some(tbl) = node | |
| 182 | .raw | |
| 183 | .get_table("Inputs") | |
| 184 | .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine"))) | |
| 185 | .and_then(|p| p.get_table("Value")) | |
| 186 | { | |
| 187 | let has_closed_key = tbl.get_bool("Closed").is_some(); | |
| 188 | let (parsed_closed, pts) = model::PolyPath::parse_polyline_table(tbl); | |
| 189 | let closed = explicit_closed.unwrap_or(if has_closed_key { parsed_closed } else { solid }); | |
| 190 | return (pts, closed); | |
| 191 | } | |
| 192 | ||
| 193 | (Vec::new(), explicit_closed.unwrap_or(solid)) | |
| 194 | } | |
| 195 | ||
| 196 | #[allow(clippy::too_many_arguments)] | |
| 197 | pub(super) fn collect_basic_primitive( | |
| 198 | comp: &Comp, | |
| 199 | node: &Node, | |
| 200 | time: f64, | |
| 201 | expr: &ExprEngine, | |
| 202 | parent_xform: Affine2D, | |
| 203 | outline_override: Option<OutlineStyle>, | |
| 204 | style_override: Option<StyleOverride>, | |
| 205 | prim_budget: &mut usize, | |
| 206 | ) -> Option<ShapeTree> { | |
| 207 | *prim_budget = prim_budget.saturating_sub(1); | |
| 208 | let is_bspline = node.kind == "sBSpline"; | |
| 209 | let [tx, ty] = eval_xy_or_point_keys( | |
| 210 | comp, | |
| 211 | node, | |
| 212 | &["Translate.X", "Center.X", "XOffset"], | |
| 213 | &["Translate.Y", "Center.Y", "YOffset"], | |
| 214 | &["Translate", "Center"], | |
| 215 | time, | |
| 216 | [0.0, 0.0], | |
| 217 | expr, | |
| 218 | ); | |
| 219 | let [px, py] = eval_xy_or_point( | |
| 220 | comp, | |
| 221 | node, | |
| 222 | &["XPivot", "Pivot.X"], | |
| 223 | &["YPivot", "Pivot.Y"], | |
| 224 | "Pivot", | |
| 225 | time, | |
| 226 | [0.0, 0.0], | |
| 227 | expr, | |
| 228 | ); | |
| 229 | let base_scale = eval_first_num(comp, node, &["Scale", "Size"], time, 1.0, expr); | |
| 230 | let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; | |
| 231 | let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; | |
| 232 | let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; | |
| 233 | ||
| 234 | let local = if (sx - 1.0).abs() > 1e-6 || (sy - 1.0).abs() > 1e-6 || px.abs() > 1e-6 || py.abs() > 1e-6 { | |
| 235 | Affine2D::translate(tx + px, ty + py) | |
| 236 | .mul(Affine2D::rotate_deg(angle)) | |
| 237 | .mul(Affine2D::scale(sx, sy)) | |
| 238 | .mul(Affine2D::translate(-px, -py)) | |
| 239 | } else { | |
| 240 | Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)) | |
| 241 | }; | |
| 242 | let xform = parent_xform.mul(local); | |
| 243 | ||
| 244 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | |
| 245 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | |
| 246 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | |
| 247 | let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; | |
| 248 | let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; | |
| 249 | ||
| 250 | let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; | |
| 251 | let default_bw = if is_bspline { 0.0 } else { 0.01 }; | |
| 252 | let mut border_width = comp.eval_number(node, "BorderWidth", time, default_bw, expr).abs() as f32; | |
| 253 | let mut join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; | |
| 254 | let mut cap_style = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; | |
| 255 | let mut miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; | |
| 256 | let mut write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; | |
| 257 | let mut write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; | |
| 258 | let fill_even_odd = if is_bspline || node.inputs.contains_key("FillMethod") { | |
| 259 | comp.eval_number(node, "FillMethod", time, 1.0, expr) < 0.5 | |
| 260 | } else { | |
| 261 | false | |
| 262 | }; | |
| 263 | let mut line_type = parse_line_type(node, comp, time, expr); | |
| 264 | let mut color = [r * opacity, g * opacity, b * opacity, a * opacity]; | |
| 265 | ||
| 266 | if let Some(sv) = style_override { | |
| 267 | if let Some(c) = sv.color { | |
| 268 | color = c; | |
| 269 | } | |
| 270 | if let Some(s) = sv.solid { | |
| 271 | solid = s; | |
| 272 | } | |
| 273 | if let Some(bw) = sv.border_width { | |
| 274 | border_width = bw; | |
| 275 | } | |
| 276 | if let Some(js) = sv.join_style { | |
| 277 | join_style = js; | |
| 278 | } | |
| 279 | if let Some(cs) = sv.cap_style { | |
| 280 | cap_style = cs; | |
| 281 | } | |
| 282 | if let Some(lt) = sv.line_type { | |
| 283 | line_type = lt; | |
| 284 | } | |
| 285 | } | |
| 286 | ||
| 287 | if let Some(ov) = outline_override { | |
| 288 | solid = false; | |
| 289 | border_width = ov.thickness; | |
| 290 | join_style = ov.join; | |
| 291 | cap_style = ov.cap; | |
| 292 | miter_limit = ov.miter_limit; | |
| 293 | write_pos = ov.write_pos; | |
| 294 | write_len = ov.write_len; | |
| 295 | } | |
| 296 | ||
| 297 | let kind = match node.kind.as_str() { | |
| 298 | "sNGon" => { | |
| 299 | let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; | |
| 300 | let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; | |
| 301 | let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; | |
| 302 | ShapePrimKind::NGon { sides, width, height } | |
| 303 | } | |
| 304 | "sRectangle" => { | |
| 305 | let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; | |
| 306 | let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; | |
| 307 | let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; | |
| 308 | ShapePrimKind::Rectangle { width, height, corner_radius } | |
| 309 | } | |
| 310 | "sStar" => { | |
| 311 | let points = eval_first_num(comp, node, &["Points", "NumberOfPoints"], time, 6.0, expr) | |
| 312 | .round() | |
| 313 | .clamp(3.0, 256.0) as u32; | |
| 314 | let depth = comp.eval_number(node, "Depth", time, 0.5, expr).clamp(0.0, 2.0) as f32; | |
| 315 | let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; | |
| 316 | let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; | |
| 317 | let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; | |
| 318 | ShapePrimKind::Star { points, depth, width, height, corner_radius } | |
| 319 | } | |
| 320 | "sPolygon" => { | |
| 321 | let (points, closed) = extract_polygon_polyline(comp, node, time, solid, expr); | |
| 322 | if points.len() < 2 { | |
| 323 | return None; | |
| 324 | } | |
| 325 | ShapePrimKind::Polygon { points, closed } | |
| 326 | } | |
| 327 | "sBSpline" => { | |
| 328 | let bs = eval_bspline_shape(comp, node, time); | |
| 329 | let closed = if node.inputs.contains_key("Closed") { | |
| 330 | comp.eval_number(node, "Closed", time, if bs.closed { 1.0 } else { 0.0 }, expr) > 0.5 | |
| 331 | } else { | |
| 332 | bs.closed | |
| 333 | }; | |
| 334 | if (closed && bs.points.len() < 3) || (!closed && bs.points.len() < 2) { | |
| 335 | return None; | |
| 336 | } | |
| 337 | if !solid && border_width <= 1e-6 { | |
| 338 | return None; | |
| 339 | } | |
| 340 | let tessellation = comp.eval_number(node, "Tessellation", time, 2.0, expr) as f32; | |
| 341 | ShapePrimKind::BSpline { points: bs.points, closed, tessellation } | |
| 342 | } | |
| 343 | _ => { | |
| 344 | let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; | |
| 345 | let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; | |
| 346 | ShapePrimKind::Ellipse { width, height } | |
| 347 | } | |
| 348 | }; | |
| 349 | ||
| 350 | Some(ShapeTree::Primitive { | |
| 351 | kind, | |
| 352 | xform, | |
| 353 | color, | |
| 354 | solid, | |
| 355 | border_width, | |
| 356 | join_style, | |
| 357 | cap_style, | |
| 358 | miter_limit, | |
| 359 | write_pos, | |
| 360 | write_len, | |
| 361 | fill_even_odd, | |
| 362 | line_type, | |
| 363 | }) | |
| 364 | } | |
| 365 | ||
| 366 | #[allow(clippy::too_many_arguments)] | |
| 367 | pub(super) fn collect_s_text( | |
| 368 | comp: &Comp, | |
| 369 | node: &Node, | |
| 370 | time: f64, | |
| 371 | expr: &ExprEngine, | |
| 372 | parent_xform: Affine2D, | |
| 373 | outline_override: Option<OutlineStyle>, | |
| 374 | style_override: Option<StyleOverride>, | |
| 375 | prim_budget: &mut usize, | |
| 376 | ) -> Option<ShapeTree> { | |
| 377 | *prim_budget = prim_budget.saturating_sub(1); | |
| 378 | let enabled1 = comp.eval_number(node, "Enabled1", time, 1.0, expr) > 0.5; | |
| 379 | if !enabled1 && outline_override.is_none() { | |
| 380 | return None; | |
| 381 | } | |
| 382 | let text_str = comp.eval_text(node, "StyledText", time, "", expr); | |
| 383 | if text_str.is_empty() { | |
| 384 | return None; | |
| 385 | } | |
| 386 | let font_family = node.static_str("Font").unwrap_or("Open Sans"); | |
| 387 | let font_style = node.static_str("Style").unwrap_or("Bold"); | |
| 388 | let size_norm = comp.eval_number(node, "Size", time, 0.08, expr) as f32; | |
| 389 | let tracking = eval_first_num( | |
| 390 | comp, | |
| 391 | node, | |
| 392 | &["CharacterSpacing", "CharacterSpacingClone", "Tracking"], | |
| 393 | time, | |
| 394 | 1.0, | |
| 395 | expr, | |
| 396 | ) as f32; | |
| 397 | let line_spacing = eval_first_num( | |
| 398 | comp, | |
| 399 | node, | |
| 400 | &["LineSpacing", "LineSpacingClone"], | |
| 401 | time, | |
| 402 | 1.0, | |
| 403 | expr, | |
| 404 | ) as f32; | |
| 405 | let h_lcr = eval_text_anchor_h(comp, node, time, expr); | |
| 406 | let v_tcb = eval_text_anchor_v(comp, node, time, expr); | |
| 407 | let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, expr) as f32; | |
| 408 | let write_on_start = comp.eval_number(node, "Start", time, 0.0, expr) as f32; | |
| 409 | let write_on_end = comp.eval_number(node, "End", time, 1.0, expr) as f32; | |
| 410 | let char_size_x = comp.eval_number(node, "CharacterSizeX", time, 1.0, expr).max(0.0) as f32; | |
| 411 | let char_size_y = comp.eval_number(node, "CharacterSizeY", time, 1.0, expr).max(0.0) as f32; | |
| 412 | ||
| 413 | let raw_cmds = crate::text_engine::layout_text_shape_commands(&crate::text_engine::TextShapeParams { | |
| 414 | text: &text_str, | |
| 415 | font_family, | |
| 416 | font_style, | |
| 417 | size_norm, | |
| 418 | tracking, | |
| 419 | line_spacing, | |
| 420 | h_lcr, | |
| 421 | v_tcb, | |
| 422 | shear_x, | |
| 423 | write_on_start, | |
| 424 | write_on_end, | |
| 425 | char_size_x, | |
| 426 | char_size_y, | |
| 427 | }); | |
| 428 | if raw_cmds.is_empty() { | |
| 429 | return None; | |
| 430 | } | |
| 431 | let cmds: Vec<ShapeCmd> = raw_cmds | |
| 432 | .into_iter() | |
| 433 | .map(|c| match c { | |
| 434 | zeno::Command::MoveTo(p) => ShapeCmd::MoveTo([p.x, p.y]), | |
| 435 | zeno::Command::LineTo(p) => ShapeCmd::LineTo([p.x, p.y]), | |
| 436 | zeno::Command::QuadTo(a, p) => ShapeCmd::QuadTo([a.x, a.y], [p.x, p.y]), | |
| 437 | zeno::Command::CurveTo(a, b, p) => ShapeCmd::CurveTo([a.x, a.y], [b.x, b.y], [p.x, p.y]), | |
| 438 | zeno::Command::Close => ShapeCmd::Close, | |
| 439 | }) | |
| 440 | .collect(); | |
| 441 | ||
| 442 | let [tx, ty] = eval_xy_or_point_keys( | |
| 443 | comp, | |
| 444 | node, | |
| 445 | &["Center.X", "Translate.X", "XOffset"], | |
| 446 | &["Center.Y", "Translate.Y", "YOffset"], | |
| 447 | &["Center", "Translate"], | |
| 448 | time, | |
| 449 | [0.0, 0.0], | |
| 450 | expr, | |
| 451 | ); | |
| 452 | let [px, py] = eval_xy_or_point( | |
| 453 | comp, | |
| 454 | node, | |
| 455 | &["XPivot", "Pivot.X"], | |
| 456 | &["YPivot", "Pivot.Y"], | |
| 457 | "Pivot", | |
| 458 | time, | |
| 459 | [0.0, 0.0], | |
| 460 | expr, | |
| 461 | ); | |
| 462 | let base_scale = eval_first_num(comp, node, &["LayoutSize", "Scale"], time, 1.0, expr); | |
| 463 | let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; | |
| 464 | let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; | |
| 465 | let angle = eval_first_num(comp, node, &["AngleZ", "ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; | |
| 466 | let local = if (sx - 1.0).abs() > 1e-6 || (sy - 1.0).abs() > 1e-6 || px.abs() > 1e-6 || py.abs() > 1e-6 { | |
| 467 | Affine2D::translate(tx + px, ty + py) | |
| 468 | .mul(Affine2D::rotate_deg(angle)) | |
| 469 | .mul(Affine2D::scale(sx, sy)) | |
| 470 | .mul(Affine2D::translate(-px, -py)) | |
| 471 | } else { | |
| 472 | Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)) | |
| 473 | }; | |
| 474 | let xform = parent_xform.mul(local); | |
| 475 | ||
| 476 | let r = eval_first_num(comp, node, &["Red1", "Red", "Red1Clone"], time, 1.0, expr) as f32; | |
| 477 | let g = eval_first_num(comp, node, &["Green1", "Green", "Green1Clone"], time, 1.0, expr) as f32; | |
| 478 | let b = eval_first_num(comp, node, &["Blue1", "Blue", "Blue1Clone"], time, 1.0, expr) as f32; | |
| 479 | let a = eval_first_num(comp, node, &["Alpha1", "Alpha", "Alpha1Clone"], time, 1.0, expr) as f32; | |
| 480 | let opacity = eval_first_num(comp, node, &["Opacity1", "Opacity"], time, 1.0, expr) as f32; | |
| 481 | let mut color = [r * opacity, g * opacity, b * opacity, a * opacity]; | |
| 482 | ||
| 483 | let elem_shape = comp.eval_number(node, "ElementShape1", time, 0.0, expr).round() as i32; | |
| 484 | let mut solid = if node.inputs.contains_key("Solid") { | |
| 485 | comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5 | |
| 486 | } else { | |
| 487 | elem_shape != 1 | |
| 488 | }; | |
| 489 | let mut border_width = if node.inputs.contains_key("BorderWidth") { | |
| 490 | comp.eval_number(node, "BorderWidth", time, 0.02, expr).abs() as f32 | |
| 491 | } else { | |
| 492 | (comp.eval_number(node, "Thickness1", time, 0.02, expr).abs() as f32) * size_norm.max(1e-4) | |
| 493 | }; | |
| 494 | let mut join_style = eval_first_num(comp, node, &["JoinStyle1", "JoinStyle"], time, 1.0, expr).round().clamp(0.0, 3.0) as u8; | |
| 495 | let mut cap_style = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; | |
| 496 | let mut miter_limit = eval_first_num(comp, node, &["MiterLimit1", "MiterLimit"], time, 10.0, expr).max(1.0) as f32; | |
| 497 | let mut write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; | |
| 498 | let mut write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; | |
| 499 | let mut line_type = parse_line_type(node, comp, time, expr); | |
| 500 | ||
| 501 | if let Some(sv) = style_override { | |
| 502 | if let Some(c) = sv.color { | |
| 503 | color = c; | |
| 504 | } | |
| 505 | if let Some(s) = sv.solid { | |
| 506 | solid = s; | |
| 507 | } | |
| 508 | if let Some(bw) = sv.border_width { | |
| 509 | border_width = bw; | |
| 510 | } | |
| 511 | if let Some(js) = sv.join_style { | |
| 512 | join_style = js; | |
| 513 | } | |
| 514 | if let Some(cs) = sv.cap_style { | |
| 515 | cap_style = cs; | |
| 516 | } | |
| 517 | if let Some(lt) = sv.line_type { | |
| 518 | line_type = lt; | |
| 519 | } | |
| 520 | } | |
| 521 | if let Some(ov) = outline_override { | |
| 522 | solid = false; | |
| 523 | border_width = ov.thickness; | |
| 524 | join_style = ov.join; | |
| 525 | cap_style = ov.cap; | |
| 526 | miter_limit = ov.miter_limit; | |
| 527 | write_pos = ov.write_pos; | |
| 528 | write_len = ov.write_len; | |
| 529 | } | |
| 530 | ||
| 531 | Some(ShapeTree::Primitive { | |
| 532 | kind: ShapePrimKind::Text { cmds }, | |
| 533 | xform, | |
| 534 | color, | |
| 535 | solid, | |
| 536 | border_width, | |
| 537 | join_style, | |
| 538 | cap_style, | |
| 539 | miter_limit, | |
| 540 | write_pos, | |
| 541 | write_len, | |
| 542 | fill_even_odd: false, | |
| 543 | line_type, | |
| 544 | }) | |
| 545 | } | |
| 546 | ||
| 547 | #[allow(clippy::too_many_arguments)] | |
| 548 | pub(super) fn collect_s_change_style( | |
| 549 | comp: &Comp, | |
| 550 | node: &Node, | |
| 551 | time: f64, | |
| 552 | expr: &ExprEngine, | |
| 553 | parent_xform: Affine2D, | |
| 554 | outline_override: Option<OutlineStyle>, | |
| 555 | style_override: Option<StyleOverride>, | |
| 556 | depth: usize, | |
| 557 | prim_budget: &mut usize, | |
| 558 | ) -> Option<ShapeTree> { | |
| 559 | let src_name = node | |
| 560 | .connected_node("Input") | |
| 561 | .or_else(|| node.connected_node("Input1"))?; | |
| 562 | let keep_mode = node.static_str("StyleMode").unwrap_or("Replace") == "Keep"; | |
| 563 | let override_color = if node.inputs.contains_key("OverrideColor") { | |
| 564 | comp.eval_number(node, "OverrideColor", time, 1.0, expr) > 0.5 | |
| 565 | } else { | |
| 566 | !keep_mode | |
| 567 | }; | |
| 568 | let color = if override_color { | |
| 569 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | |
| 570 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | |
| 571 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | |
| 572 | let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; | |
| 573 | let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; | |
| 574 | Some([r * opacity, g * opacity, b * opacity, a * opacity]) | |
| 575 | } else { | |
| 576 | None | |
| 577 | }; | |
| 578 | let check_opt = |flag: &str, key: &str| -> bool { | |
| 579 | node.inputs.contains_key(key) | |
| 580 | && (!node.inputs.contains_key(flag) | |
| 581 | || comp.eval_number(node, flag, time, 1.0, expr) > 0.5) | |
| 582 | }; | |
| 583 | let solid = check_opt("OverrideSolid", "Solid") | |
| 584 | .then(|| comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5); | |
| 585 | let border_width = check_opt("OverrideBorderWidth", "BorderWidth") | |
| 586 | .then(|| comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32); | |
| 587 | let join_style = check_opt("OverrideJoinStyle", "JoinStyle") | |
| 588 | .then(|| comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8); | |
| 589 | let cap_style = check_opt("OverrideCapStyle", "CapStyle") | |
| 590 | .then(|| comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8); | |
| 591 | let lt = parse_line_type(node, comp, time, expr); | |
| 592 | let line_type = (check_opt("OverrideLineType", "LineType") | |
| 593 | || check_opt("OverrideLineType", "LineStyle")) | |
| 594 | .then_some(lt); | |
| 595 | ||
| 596 | let local_sv = StyleOverride { color, solid, border_width, join_style, cap_style, line_type }; | |
| 597 | let merged_sv = StyleOverride::merge_outer(Some(local_sv), style_override); | |
| 598 | collect_shape_tree_by_name( | |
| 599 | comp, | |
| 600 | src_name, | |
| 601 | time, | |
| 602 | expr, | |
| 603 | parent_xform, | |
| 604 | outline_override, | |
| 605 | merged_sv, | |
| 606 | depth + 1, | |
| 607 | prim_budget, | |
| 608 | ) | |
| 609 | } | |
| 610 | ||
| 611 | /// Fallback collection for `sBSpline` when `model::is_modifier_type("sBSpline")` omits it from | |
| 612 | /// `comp.nodes`; builds a transient `Node` from `comp.raw_root.Tools` and reuses `collect_basic_primitive`. | |
| 613 | #[allow(clippy::too_many_arguments)] | |
| 614 | pub(super) fn collect_raw_bspline_by_name( | |
| 615 | comp: &Comp, | |
| 616 | name: &str, | |
| 617 | time: f64, | |
| 618 | expr: &ExprEngine, | |
| 619 | parent_xform: Affine2D, | |
| 620 | outline_override: Option<OutlineStyle>, | |
| 621 | style_override: Option<StyleOverride>, | |
| 622 | prim_budget: &mut usize, | |
| 623 | ) -> Option<ShapeTree> { | |
| 624 | let tools = comp.raw_root.as_ref()?.get_table("Tools")?; | |
| 625 | let tbl = find_tool_table_in_tools(tools, name)?; | |
| 626 | if tbl.tag.as_deref() != Some("sBSpline") { | |
| 627 | return None; | |
| 628 | } | |
| 629 | if tbl.get_bool("PassThrough").unwrap_or(false) { | |
| 630 | return None; | |
| 631 | } | |
| 632 | let mut inputs = std::collections::HashMap::new(); | |
| 633 | if let Some(in_tbl) = tbl.get_table("Inputs") { | |
| 634 | for (k, v) in &in_tbl.entries { | |
| 635 | let LuaKey::Str(in_name) = k else { continue }; | |
| 636 | let Some(it) = v.as_table() else { continue }; | |
| 637 | let source_op = it.get_str("SourceOp").map(str::to_owned); | |
| 638 | let source_output = it.get_str("Source").map(str::to_owned); | |
| 639 | let expression = it.get_str("Expression").map(str::to_owned); | |
| 640 | let value = it.get("Value").and_then(|val| { | |
| 641 | if let Some(n) = val.as_f64() { | |
| 642 | Some(ParamValue::Number(n)) | |
| 643 | } else if let Some(s) = val.as_str() { | |
| 644 | Some(ParamValue::Text(s.to_owned())) | |
| 645 | } else if let Some(pt) = val.as_table() { | |
| 646 | let mut vals = pt.positional_values(); | |
| 647 | if let (Some(x), Some(y)) = (vals.next().and_then(|v| v.as_f64()), vals.next().and_then(|v| v.as_f64())) { | |
| 648 | Some(ParamValue::Point([x, y])) | |
| 649 | } else { | |
| 650 | None | |
| 651 | } | |
| 652 | } else { | |
| 653 | None | |
| 654 | } | |
| 655 | }); | |
| 656 | inputs.insert( | |
| 657 | in_name.clone(), | |
| 658 | InputBinding { value, source_op, source_output, expression }, | |
| 659 | ); | |
| 660 | } | |
| 661 | } | |
| 662 | let tmp = Node { | |
| 663 | id: NodeId(usize::MAX), | |
| 664 | name: name.to_owned(), | |
| 665 | kind: "sBSpline".to_owned(), | |
| 666 | inputs, | |
| 667 | clips: Vec::new(), | |
| 668 | raw: tbl.clone(), | |
| 669 | bypassed: false, | |
| 670 | internal: false, | |
| 671 | macro_output: None, | |
| 672 | pos: [0.0, 0.0], | |
| 673 | }; | |
| 674 | collect_basic_primitive( | |
| 675 | comp, | |
| 676 | &tmp, | |
| 677 | time, | |
| 678 | expr, | |
| 679 | parent_xform, | |
| 680 | outline_override, | |
| 681 | style_override, | |
| 682 | prim_budget, | |
| 683 | ) | |
| 684 | } |
crates/engine/src/eval/shapes/geometry.rs+275-536| ... | ... | @@ -1,13 +1,11 @@ |
| 1 | //! 2D vector shape command generation, contour flattening, path modifiers | |
| 2 | //! (`sExpand`, `sJitter`, `sOffset`), path trimming, and viewport clipping. | |
| 1 | //! 2D vector shape command generation, adaptive curve flattening, path trimming, | |
| 2 | //! and viewport clipping. | |
| 3 | 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 | } | |
| 4 | use super::super::warps_masks::bspline::eval_rational_cubic_bspline_2d; | |
| 5 | use super::modifiers::{ | |
| 6 | Contour, apply_path_modifier_contours, dash_contours, dedup_contour_points, expand_contour, | |
| 7 | }; | |
| 8 | use super::{Affine2D, PathModifier, ShapeCmd, ShapePrimKind}; | |
| 11 | 9 | |
| 12 | 10 | #[inline] |
| 13 | 11 | fn shape_to_px(wpt: [f32; 2], dims: [u32; 2]) -> zeno::Vector { |
| ... | ... | @@ -204,9 +202,175 @@ fn build_primitive_commands_shape(kind: &ShapePrimKind, xform: Affine2D) -> (Vec |
| 204 | 202 | } |
| 205 | 203 | (cmds, *closed) |
| 206 | 204 | } |
| 205 | ShapePrimKind::BSpline { points, closed, tessellation } => { | |
| 206 | let min_steps = (12.0 + tessellation.clamp(0.0, 9.0) * 4.0).round() as usize; | |
| 207 | let xf_pts: Vec<([f32; 2], f32)> = points | |
| 208 | .iter() | |
| 209 | .map(|p| (xform.apply([p.x as f32, p.y as f32]), p.w as f32)) | |
| 210 | .collect(); | |
| 211 | let poly = eval_rational_cubic_bspline_2d(&xf_pts, *closed, |chord| { | |
| 212 | ((chord * 128.0).ceil() as usize).clamp(min_steps, 96) | |
| 213 | }); | |
| 214 | for (i, &pt) in poly.iter().enumerate() { | |
| 215 | let v = zeno::Vector::new(pt[0], pt[1]); | |
| 216 | if i == 0 { | |
| 217 | cmds.push(zeno::Command::MoveTo(v)); | |
| 218 | } else { | |
| 219 | cmds.push(zeno::Command::LineTo(v)); | |
| 220 | } | |
| 221 | } | |
| 222 | if *closed && !cmds.is_empty() { | |
| 223 | cmds.push(zeno::Command::Close); | |
| 224 | } | |
| 225 | (cmds, *closed) | |
| 226 | } | |
| 227 | ShapePrimKind::Text { cmds: text_cmds } => { | |
| 228 | cmds.reserve(text_cmds.len()); | |
| 229 | for &c in text_cmds { | |
| 230 | cmds.push(match c { | |
| 231 | ShapeCmd::MoveTo(p) => zeno::Command::MoveTo(to_v(p)), | |
| 232 | ShapeCmd::LineTo(p) => zeno::Command::LineTo(to_v(p)), | |
| 233 | ShapeCmd::QuadTo(a, p) => zeno::Command::QuadTo(to_v(a), to_v(p)), | |
| 234 | ShapeCmd::CurveTo(a, b, p) => zeno::Command::CurveTo(to_v(a), to_v(b), to_v(p)), | |
| 235 | ShapeCmd::Close => zeno::Command::Close, | |
| 236 | }); | |
| 237 | } | |
| 238 | (cmds, true) | |
| 239 | } | |
| 207 | 240 | } |
| 208 | 241 | } |
| 209 | 242 | |
| 243 | /// Flattens `CurveTo` and `QuadTo` segments adaptively in pixel space to sub-0.02px accuracy | |
| 244 | /// so smooth curves (like `sEllipse`, `sText`, rounded corners) avoid coarse polygon facets. | |
| 245 | fn flatten_quad_adaptive( | |
| 246 | p0: [f32; 2], | |
| 247 | c: [f32; 2], | |
| 248 | p1: [f32; 2], | |
| 249 | tol_sq: f32, | |
| 250 | depth: u8, | |
| 251 | out: &mut Vec<[f32; 2]>, | |
| 252 | ) { | |
| 253 | let mx = 0.5 * (p0[0] + p1[0]); | |
| 254 | let my = 0.5 * (p0[1] + p1[1]); | |
| 255 | let dx = c[0] - mx; | |
| 256 | let dy = c[1] - my; | |
| 257 | if depth >= 9 || (dx * dx + dy * dy) <= 16.0 * tol_sq { | |
| 258 | out.push(p1); | |
| 259 | return; | |
| 260 | } | |
| 261 | let q0 = [0.5 * (p0[0] + c[0]), 0.5 * (p0[1] + c[1])]; | |
| 262 | let q1 = [0.5 * (c[0] + p1[0]), 0.5 * (c[1] + p1[1])]; | |
| 263 | let mid = [0.5 * (q0[0] + q1[0]), 0.5 * (q0[1] + q1[1])]; | |
| 264 | flatten_quad_adaptive(p0, q0, mid, tol_sq, depth + 1, out); | |
| 265 | flatten_quad_adaptive(mid, q1, p1, tol_sq, depth + 1, out); | |
| 266 | } | |
| 267 | ||
| 268 | fn flatten_cubic_adaptive( | |
| 269 | p0: [f32; 2], | |
| 270 | c1: [f32; 2], | |
| 271 | c2: [f32; 2], | |
| 272 | p1: [f32; 2], | |
| 273 | tol_sq: f32, | |
| 274 | depth: u8, | |
| 275 | out: &mut Vec<[f32; 2]>, | |
| 276 | ) { | |
| 277 | let dx = p1[0] - p0[0]; | |
| 278 | let dy = p1[1] - p0[1]; | |
| 279 | let len_sq = dx * dx + dy * dy; | |
| 280 | let d1 = (c1[0] - p1[0]) * dy - (c1[1] - p1[1]) * dx; | |
| 281 | let d2 = (c2[0] - p1[0]) * dy - (c2[1] - p1[1]) * dx; | |
| 282 | let d_max = d1.abs().max(d2.abs()); | |
| 283 | let flat_ok = if len_sq > 1e-8 { | |
| 284 | (d_max * d_max) <= (16.0 / 9.0) * tol_sq * len_sq | |
| 285 | } else { | |
| 286 | (c1[0] - p0[0]).hypot(c1[1] - p0[1]).max((c2[0] - p0[0]).hypot(c2[1] - p0[1])) <= 0.1 | |
| 287 | }; | |
| 288 | if depth >= 9 || (flat_ok && depth >= 2) { | |
| 289 | out.push(p1); | |
| 290 | return; | |
| 291 | } | |
| 292 | let p01 = [0.5 * (p0[0] + c1[0]), 0.5 * (p0[1] + c1[1])]; | |
| 293 | let p12 = [0.5 * (c1[0] + c2[0]), 0.5 * (c1[1] + c2[1])]; | |
| 294 | let p23 = [0.5 * (c2[0] + p1[0]), 0.5 * (c2[1] + p1[1])]; | |
| 295 | let p012 = [0.5 * (p01[0] + p12[0]), 0.5 * (p01[1] + p12[1])]; | |
| 296 | let p123 = [0.5 * (p12[0] + p23[0]), 0.5 * (p12[1] + p23[1])]; | |
| 297 | let mid = [0.5 * (p012[0] + p123[0]), 0.5 * (p012[1] + p123[1])]; | |
| 298 | flatten_cubic_adaptive(p0, p01, p012, mid, tol_sq, depth + 1, out); | |
| 299 | flatten_cubic_adaptive(mid, p123, p23, p1, tol_sq, depth + 1, out); | |
| 300 | } | |
| 301 | ||
| 302 | /// Splits `cmds` into per-subpath `Contour`s, adaptively flattening curves in `tol_px` units. | |
| 303 | pub(super) fn flatten_commands_to_contours( | |
| 304 | cmds: &[zeno::Command], | |
| 305 | default_closed: bool, | |
| 306 | tol_px: f32, | |
| 307 | ) -> Vec<Contour> { | |
| 308 | use zeno::Command::{Close, CurveTo, LineTo, MoveTo, QuadTo}; | |
| 309 | let tol_sq = tol_px * tol_px; | |
| 310 | let mut contours: Vec<Contour> = Vec::new(); | |
| 311 | let mut cur: Vec<[f32; 2]> = Vec::new(); | |
| 312 | let mut cur_closed = false; | |
| 313 | ||
| 314 | let flush = |cur: &mut Vec<[f32; 2]>, closed: bool, out: &mut Vec<Contour>| { | |
| 315 | let pts = dedup_contour_points(std::mem::take(cur), closed); | |
| 316 | if pts.len() >= 2 && (!closed || pts.len() >= 3) { | |
| 317 | out.push(Contour { points: pts, closed }); | |
| 318 | } | |
| 319 | }; | |
| 320 | ||
| 321 | for c in cmds { | |
| 322 | match *c { | |
| 323 | MoveTo(p) => { | |
| 324 | if !cur.is_empty() { | |
| 325 | flush(&mut cur, cur_closed || default_closed, &mut contours); | |
| 326 | } | |
| 327 | cur_closed = false; | |
| 328 | cur.push([p.x, p.y]); | |
| 329 | } | |
| 330 | LineTo(p) => { | |
| 331 | cur.push([p.x, p.y]); | |
| 332 | } | |
| 333 | QuadTo(a, p) => { | |
| 334 | let p0 = cur.last().copied().unwrap_or([a.x, a.y]); | |
| 335 | flatten_quad_adaptive(p0, [a.x, a.y], [p.x, p.y], tol_sq, 0, &mut cur); | |
| 336 | } | |
| 337 | CurveTo(a, b, p) => { | |
| 338 | let p0 = cur.last().copied().unwrap_or([a.x, a.y]); | |
| 339 | flatten_cubic_adaptive(p0, [a.x, a.y], [b.x, b.y], [p.x, p.y], tol_sq, 0, &mut cur); | |
| 340 | } | |
| 341 | Close => { | |
| 342 | cur_closed = true; | |
| 343 | flush(&mut cur, true, &mut contours); | |
| 344 | } | |
| 345 | } | |
| 346 | } | |
| 347 | if !cur.is_empty() { | |
| 348 | flush(&mut cur, cur_closed || default_closed, &mut contours); | |
| 349 | } | |
| 350 | contours | |
| 351 | } | |
| 352 | ||
| 353 | pub(super) fn contours_to_commands(contours: &[Contour]) -> Vec<zeno::Command> { | |
| 354 | let mut cmds = Vec::new(); | |
| 355 | for c in contours { | |
| 356 | if c.points.len() < 2 || (c.closed && c.points.len() < 3) { | |
| 357 | continue; | |
| 358 | } | |
| 359 | for (i, &pt) in c.points.iter().enumerate() { | |
| 360 | let v = zeno::Vector::new(pt[0], pt[1]); | |
| 361 | if i == 0 { | |
| 362 | cmds.push(zeno::Command::MoveTo(v)); | |
| 363 | } else { | |
| 364 | cmds.push(zeno::Command::LineTo(v)); | |
| 365 | } | |
| 366 | } | |
| 367 | if c.closed { | |
| 368 | cmds.push(zeno::Command::Close); | |
| 369 | } | |
| 370 | } | |
| 371 | cmds | |
| 372 | } | |
| 373 | ||
| 210 | 374 | /// Builds pixel-space `zeno::Command`s for a primitive after applying any inner-to-outer `PathModifier`s. |
| 211 | 375 | pub(super) fn build_primitive_commands_px( |
| 212 | 376 | kind: &ShapePrimKind, |
| ... | ... | @@ -221,7 +385,7 @@ pub(super) fn build_primitive_commands_px( |
| 221 | 385 | } |
| 222 | 386 | |
| 223 | 387 | if mods.is_empty() { |
| 224 | let px_cmds = shape_cmds | |
| 388 | let px_cmds: Vec<zeno::Command> = shape_cmds | |
| 225 | 389 | .into_iter() |
| 226 | 390 | .map(|c| match c { |
| 227 | 391 | zeno::Command::MoveTo(p) => zeno::Command::MoveTo(shape_to_px([p.x, p.y], dims)), |
| ... | ... | @@ -238,534 +402,93 @@ pub(super) fn build_primitive_commands_px( |
| 238 | 402 | zeno::Command::Close => zeno::Command::Close, |
| 239 | 403 | }) |
| 240 | 404 | .collect(); |
| 405 | let has_curves = px_cmds | |
| 406 | .iter() | |
| 407 | .any(|c| matches!(c, zeno::Command::QuadTo(..) | zeno::Command::CurveTo(..))); | |
| 408 | if has_curves { | |
| 409 | let contours = flatten_commands_to_contours(&px_cmds, closed, 0.015); | |
| 410 | return (contours_to_commands(&contours), closed); | |
| 411 | } | |
| 241 | 412 | return (px_cmds, closed); |
| 242 | 413 | } |
| 243 | 414 | |
| 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 }; | |
| 415 | let tol_shape = 0.02 / (dims[0].max(dims[1]).max(1) as f32); | |
| 416 | let mut contours = flatten_commands_to_contours(&shape_cmds, closed, tol_shape); | |
| 247 | 417 | |
| 248 | 418 | for (mod_idx, &(op, post_xform)) in mods.iter().enumerate() { |
| 249 | if contour.points.len() < 2 { | |
| 250 | return (Vec::new(), contour.closed); | |
| 419 | if contours.is_empty() { | |
| 420 | return (Vec::new(), closed); | |
| 251 | 421 | } |
| 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; | |
| 422 | contours = apply_path_modifier_contours(contours, op, shape_idx, mod_idx as u32); | |
| 423 | for c in &mut contours { | |
| 424 | for p in &mut c.points { | |
| 425 | *p = post_xform.apply(*p); | |
| 286 | 426 | } |
| 287 | 427 | } |
| 288 | out.push(p); | |
| 289 | 428 | } |
| 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 | 429 | |
| 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]); | |
| 430 | let eff_closed = contours.first().is_some_and(|c| c.closed); | |
| 431 | let mut px_cmds = Vec::new(); | |
| 432 | for c in &contours { | |
| 433 | if c.points.len() < 2 || (c.closed && c.points.len() < 3) { | |
| 427 | 434 | continue; |
| 428 | 435 | } |
| 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 | ]); | |
| 436 | for (i, &pt) in c.points.iter().enumerate() { | |
| 437 | let v = shape_to_px(pt, dims); | |
| 438 | if i == 0 { | |
| 439 | px_cmds.push(zeno::Command::MoveTo(v)); | |
| 491 | 440 | } else { |
| 492 | out.push([(q0[0] + q1[0]) * 0.5, (q0[1] + q1[1]) * 0.5]); | |
| 441 | px_cmds.push(zeno::Command::LineTo(v)); | |
| 493 | 442 | } |
| 494 | 443 | } |
| 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 }; | |
| 444 | if c.closed { | |
| 445 | px_cmds.push(zeno::Command::Close); | |
| 666 | 446 | } |
| 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 | 447 | } |
| 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 } | |
| 448 | (px_cmds, eff_closed) | |
| 720 | 449 | } |
| 721 | 450 | |
| 722 | pub(super) fn flatten_commands_to_poly(cmds: &[zeno::Command]) -> Vec<[f32; 2]> { | |
| 723 | flatten_commands_to_poly_scaled(cmds, 1.0) | |
| 451 | /// Builds a closed-ring fill path (`outer` + reversed `inner`) for thick single-contour outlines, | |
| 452 | /// avoiding `zeno::Stroke`'s inner-corner self-overlap artifact. | |
| 453 | pub(super) fn closed_outline_fill_commands( | |
| 454 | cmds: &[zeno::Command], | |
| 455 | stroke_px: f32, | |
| 456 | join_style: u8, | |
| 457 | miter_limit: f32, | |
| 458 | ) -> Option<Vec<zeno::Command>> { | |
| 459 | let contours = flatten_commands_to_contours(cmds, true, 0.02); | |
| 460 | if contours.len() != 1 || !contours[0].closed || contours[0].points.len() < 3 { | |
| 461 | return None; | |
| 462 | } | |
| 463 | let half = stroke_px * 0.5; | |
| 464 | let outer = expand_contour(contours[0].clone(), half, join_style, miter_limit, None); | |
| 465 | if outer.points.len() < 3 { | |
| 466 | return None; | |
| 467 | } | |
| 468 | let mut inner = expand_contour(contours[0].clone(), -half, join_style, miter_limit, None); | |
| 469 | let mut out = contours_to_commands(&[outer]); | |
| 470 | if inner.points.len() >= 3 { | |
| 471 | inner.points.reverse(); | |
| 472 | out.extend(contours_to_commands(&[inner])); | |
| 473 | } | |
| 474 | Some(out) | |
| 724 | 475 | } |
| 725 | 476 | |
| 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 | } | |
| 477 | /// Applies `line_type` dashing (`1..=4`) to pixel-space `cmds`. | |
| 478 | pub(super) fn dash_path_commands( | |
| 479 | cmds: Vec<zeno::Command>, | |
| 480 | closed: bool, | |
| 481 | line_type: u8, | |
| 482 | stroke_px: f32, | |
| 483 | ) -> Vec<zeno::Command> { | |
| 484 | if line_type == 0 { | |
| 485 | return cmds; | |
| 764 | 486 | } |
| 765 | poly | |
| 487 | let contours = flatten_commands_to_contours(&cmds, closed, 0.05); | |
| 488 | dash_contours(&contours, line_type, stroke_px) | |
| 766 | 489 | } |
| 767 | 490 | |
| 768 | /// Trims a command loop (closed or open) to arc-length fraction `[write_pos, write_pos + write_len]`. | |
| 491 | /// Trims each contour in `cmds` to arc-length fraction `[write_pos, write_pos + write_len]`. | |
| 769 | 492 | pub(super) fn trim_path_commands( |
| 770 | 493 | cmds: Vec<zeno::Command>, |
| 771 | 494 | closed: bool, |
| ... | ... | @@ -778,7 +501,20 @@ pub(super) fn trim_path_commands( |
| 778 | 501 | if write_len >= 1.0 - 1e-5 && (!closed || write_pos.rem_euclid(1.0) <= 1e-5) { |
| 779 | 502 | return cmds; |
| 780 | 503 | } |
| 781 | let poly = flatten_commands_to_poly(&cmds); | |
| 504 | let contours = flatten_commands_to_contours(&cmds, closed, 0.02); | |
| 505 | let mut out = Vec::new(); | |
| 506 | for c in contours { | |
| 507 | out.extend(trim_single_contour(&c.points, c.closed, write_pos, write_len)); | |
| 508 | } | |
| 509 | out | |
| 510 | } | |
| 511 | ||
| 512 | fn trim_single_contour( | |
| 513 | poly: &[[f32; 2]], | |
| 514 | closed: bool, | |
| 515 | write_pos: f32, | |
| 516 | write_len: f32, | |
| 517 | ) -> Vec<zeno::Command> { | |
| 782 | 518 | let n = poly.len(); |
| 783 | 519 | if n < 2 { |
| 784 | 520 | return Vec::new(); |
| ... | ... | @@ -839,7 +575,7 @@ pub(super) fn trim_path_commands( |
| 839 | 575 | out |
| 840 | 576 | } |
| 841 | 577 | |
| 842 | /// Flattens `cmds` and clips a closed polygon to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long. | |
| 578 | /// Flattens `cmds` and clips closed polygons to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long. | |
| 843 | 579 | pub(super) fn clip_to_viewport( |
| 844 | 580 | cmds: Vec<zeno::Command>, |
| 845 | 581 | closed: bool, |
| ... | ... | @@ -859,34 +595,37 @@ pub(super) fn clip_to_viewport( |
| 859 | 595 | if !huge || !closed { |
| 860 | 596 | return cmds; |
| 861 | 597 | } |
| 862 | let mut poly = flatten_commands_to_poly(&cmds); | |
| 598 | let contours = flatten_commands_to_contours(&cmds, closed, 0.05); | |
| 863 | 599 | let edges: [(usize, f32, f32); 4] = [ |
| 864 | 600 | (0, 1.0, -margin), |
| 865 | 601 | (0, -1.0, w + margin), |
| 866 | 602 | (1, 1.0, -margin), |
| 867 | 603 | (1, -1.0, h + margin), |
| 868 | 604 | ]; |
| 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); | |
| 605 | let mut out = Vec::new(); | |
| 606 | for contour in contours { | |
| 607 | let mut poly = contour.points; | |
| 608 | for (axis, sign, bound) in edges { | |
| 609 | let inside = |p: [f32; 2]| sign * (p[axis] - bound) >= 0.0; | |
| 610 | let input = std::mem::take(&mut poly); | |
| 611 | for (i, &cur) in input.iter().enumerate() { | |
| 612 | let prev = input[(i + input.len() - 1) % input.len()]; | |
| 613 | if inside(cur) != inside(prev) { | |
| 614 | let t = (bound - prev[axis]) / (cur[axis] - prev[axis]); | |
| 615 | poly.push([prev[0] + t * (cur[0] - prev[0]), prev[1] + t * (cur[1] - prev[1])]); | |
| 616 | } | |
| 617 | if inside(cur) { | |
| 618 | poly.push(cur); | |
| 619 | } | |
| 880 | 620 | } |
| 881 | 621 | } |
| 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); | |
| 622 | for (i, p) in poly.iter().enumerate() { | |
| 623 | let v = zeno::Vector::new(p[0], p[1]); | |
| 624 | out.push(if i == 0 { MoveTo(v) } else { LineTo(v) }); | |
| 625 | } | |
| 626 | if !poly.is_empty() { | |
| 627 | out.push(Close); | |
| 628 | } | |
| 890 | 629 | } |
| 891 | 630 | out |
| 892 | 631 | } |
crates/engine/src/eval/shapes/modifiers.rs created+581| ... | ... | @@ -0,0 +1,581 @@ |
| 1 | //! Multi-contour path modifiers (`sExpand`, `sJitter`, `sOffset`, `LineType` dashing) | |
| 2 | //! and shared contour offset/orientation utilities. | |
| 3 | ||
| 4 | use super::PathModifier; | |
| 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 | pub(super) fn dedup_contour_points(pts: Vec<[f32; 2]>, closed: bool) -> Vec<[f32; 2]> { | |
| 13 | let mut out: Vec<[f32; 2]> = Vec::with_capacity(pts.len()); | |
| 14 | for p in pts { | |
| 15 | if !p[0].is_finite() || !p[1].is_finite() { | |
| 16 | continue; | |
| 17 | } | |
| 18 | if let Some(&prev) = out.last() { | |
| 19 | if (p[0] - prev[0]).hypot(p[1] - prev[1]) <= 1e-6 { | |
| 20 | continue; | |
| 21 | } | |
| 22 | } | |
| 23 | out.push(p); | |
| 24 | } | |
| 25 | if closed && out.len() >= 2 { | |
| 26 | if let (Some(&first), Some(&last)) = (out.first(), out.last()) { | |
| 27 | if (last[0] - first[0]).hypot(last[1] - first[1]) <= 1e-6 { | |
| 28 | out.pop(); | |
| 29 | } | |
| 30 | } | |
| 31 | } | |
| 32 | out | |
| 33 | } | |
| 34 | ||
| 35 | pub(super) fn signed_area(pts: &[[f32; 2]]) -> f32 { | |
| 36 | let n = pts.len(); | |
| 37 | if n < 3 { | |
| 38 | return 0.0; | |
| 39 | } | |
| 40 | let mut sum = 0.0_f64; | |
| 41 | for i in 0..n { | |
| 42 | let a = pts[i]; | |
| 43 | let b = pts[(i + 1) % n]; | |
| 44 | sum += (a[0] as f64) * (b[1] as f64) - (b[0] as f64) * (a[1] as f64); | |
| 45 | } | |
| 46 | (0.5 * sum) as f32 | |
| 47 | } | |
| 48 | ||
| 49 | pub(super) fn apply_path_modifier_contours( | |
| 50 | contours: Vec<Contour>, | |
| 51 | op: PathModifier, | |
| 52 | shape_idx: u32, | |
| 53 | mod_idx: u32, | |
| 54 | ) -> Vec<Contour> { | |
| 55 | match op { | |
| 56 | PathModifier::Expand { amount, join_style, miter_limit } => { | |
| 57 | expand_contours(contours, amount, join_style, miter_limit) | |
| 58 | } | |
| 59 | PathModifier::Jitter { x_amount, y_amount, seed, smoothness, per_shape } => { | |
| 60 | if per_shape { | |
| 61 | let dx = jitter_hash(seed, shape_idx, mod_idx, 0, 0) * x_amount; | |
| 62 | let dy = jitter_hash(seed, shape_idx, mod_idx, 0, 1) * y_amount; | |
| 63 | return contours | |
| 64 | .into_iter() | |
| 65 | .map(|c| Contour { | |
| 66 | points: c.points.into_iter().map(|p| [p[0] + dx, p[1] + dy]).collect(), | |
| 67 | closed: c.closed, | |
| 68 | }) | |
| 69 | .collect(); | |
| 70 | } | |
| 71 | contours | |
| 72 | .into_iter() | |
| 73 | .enumerate() | |
| 74 | .map(|(ci, c)| { | |
| 75 | jitter_contour( | |
| 76 | c, | |
| 77 | x_amount, | |
| 78 | y_amount, | |
| 79 | seed, | |
| 80 | smoothness, | |
| 81 | false, | |
| 82 | shape_idx.wrapping_mul(131).wrapping_add(ci as u32), | |
| 83 | mod_idx, | |
| 84 | ) | |
| 85 | }) | |
| 86 | .collect() | |
| 87 | } | |
| 88 | PathModifier::Offset { | |
| 89 | offset_x, | |
| 90 | offset_y, | |
| 91 | contour_offset, | |
| 92 | position, | |
| 93 | join_style, | |
| 94 | miter_limit, | |
| 95 | } => { | |
| 96 | let mut cs = if contour_offset.abs() > 1e-6 { | |
| 97 | expand_contours(contours, contour_offset, join_style, miter_limit) | |
| 98 | } else { | |
| 99 | contours | |
| 100 | }; | |
| 101 | if position.abs() > 1e-6 { | |
| 102 | cs = cs.into_iter().map(|c| shift_contour_position(c, position)).collect(); | |
| 103 | } | |
| 104 | if offset_x.abs() > 1e-6 || offset_y.abs() > 1e-6 { | |
| 105 | for c in &mut cs { | |
| 106 | for p in &mut c.points { | |
| 107 | p[0] += offset_x; | |
| 108 | p[1] += offset_y; | |
| 109 | } | |
| 110 | } | |
| 111 | } | |
| 112 | cs | |
| 113 | } | |
| 114 | } | |
| 115 | } | |
| 116 | ||
| 117 | fn expand_contours( | |
| 118 | contours: Vec<Contour>, | |
| 119 | amount: f32, | |
| 120 | join_style: u8, | |
| 121 | miter_limit: f32, | |
| 122 | ) -> Vec<Contour> { | |
| 123 | if amount.abs() <= 1e-6 { | |
| 124 | return contours; | |
| 125 | } | |
| 126 | // Determine dominant orientation from the largest closed contour so outer boundaries | |
| 127 | // and opposite-winding holes offset consistently (e.g., `sText` glyphs). | |
| 128 | let mut best_abs = 0.0_f32; | |
| 129 | let mut dom_sign = 0.0_f32; | |
| 130 | for c in &contours { | |
| 131 | if c.closed && c.points.len() >= 3 { | |
| 132 | let a = signed_area(&c.points); | |
| 133 | if a.abs() > best_abs { | |
| 134 | best_abs = a.abs(); | |
| 135 | dom_sign = if a > 0.0 { 1.0 } else { -1.0 }; | |
| 136 | } | |
| 137 | } | |
| 138 | } | |
| 139 | let dom = (best_abs > 1e-10).then_some(dom_sign); | |
| 140 | contours | |
| 141 | .into_iter() | |
| 142 | .filter_map(|c| { | |
| 143 | let out = expand_contour(c, amount, join_style, miter_limit, dom); | |
| 144 | if out.points.len() >= 2 && (!out.closed || out.points.len() >= 3) { | |
| 145 | Some(out) | |
| 146 | } else { | |
| 147 | None | |
| 148 | } | |
| 149 | }) | |
| 150 | .collect() | |
| 151 | } | |
| 152 | ||
| 153 | /// Offsets a contour outward (`amount > 0`) or inward (`amount < 0`) using miter/bevel/round joins. | |
| 154 | pub(super) fn expand_contour( | |
| 155 | contour: Contour, | |
| 156 | amount: f32, | |
| 157 | join_style: u8, | |
| 158 | miter_limit: f32, | |
| 159 | orient_override: Option<f32>, | |
| 160 | ) -> Contour { | |
| 161 | if amount.abs() <= 1e-6 { | |
| 162 | return contour; | |
| 163 | } | |
| 164 | let pts = dedup_contour_points(contour.points, contour.closed); | |
| 165 | if !contour.closed { | |
| 166 | if pts.len() < 2 { | |
| 167 | return Contour { points: Vec::new(), closed: false }; | |
| 168 | } | |
| 169 | let n = pts.len(); | |
| 170 | let mut out = Vec::with_capacity(n); | |
| 171 | for i in 0..n { | |
| 172 | let n0 = if i > 0 { | |
| 173 | let dx = pts[i][0] - pts[i - 1][0]; | |
| 174 | let dy = pts[i][1] - pts[i - 1][1]; | |
| 175 | let l = dx.hypot(dy).max(1e-6); | |
| 176 | [dy / l, -dx / l] | |
| 177 | } else { | |
| 178 | [0.0, 0.0] | |
| 179 | }; | |
| 180 | let n1 = if i + 1 < n { | |
| 181 | let dx = pts[i + 1][0] - pts[i][0]; | |
| 182 | let dy = pts[i + 1][1] - pts[i][1]; | |
| 183 | let l = dx.hypot(dy).max(1e-6); | |
| 184 | [dy / l, -dx / l] | |
| 185 | } else { | |
| 186 | [0.0, 0.0] | |
| 187 | }; | |
| 188 | let avg = if i == 0 { | |
| 189 | n1 | |
| 190 | } else if i + 1 == n { | |
| 191 | n0 | |
| 192 | } else { | |
| 193 | let bx = n0[0] + n1[0]; | |
| 194 | let by = n0[1] + n1[1]; | |
| 195 | let denom = (1.0 + n0[0] * n1[0] + n0[1] * n1[1]).max(1e-4); | |
| 196 | let scale = (1.0 / denom).min(miter_limit * 0.5); | |
| 197 | [bx * scale, by * scale] | |
| 198 | }; | |
| 199 | out.push([pts[i][0] + avg[0] * amount, pts[i][1] + avg[1] * amount]); | |
| 200 | } | |
| 201 | return Contour { points: out, closed: false }; | |
| 202 | } | |
| 203 | ||
| 204 | let n = pts.len(); | |
| 205 | if n < 3 { | |
| 206 | return Contour { points: Vec::new(), closed: true }; | |
| 207 | } | |
| 208 | let orig_area = signed_area(&pts); | |
| 209 | if orig_area.abs() <= 1e-10 { | |
| 210 | return Contour { points: Vec::new(), closed: true }; | |
| 211 | } | |
| 212 | // For CCW (orig_area > 0) in Y-up shape space, outward normal of edge (dx, dy) is (dy, -dx)/len. | |
| 213 | let self_orient = if orig_area > 0.0 { 1.0_f32 } else { -1.0_f32 }; | |
| 214 | let orient = orient_override.unwrap_or(self_orient); | |
| 215 | let eff_amount = amount * (self_orient * orient); | |
| 216 | ||
| 217 | // Compute per-edge outward unit normals relative to the contour's own winding, | |
| 218 | // and let `eff_amount` flip inward for opposite-winding holes. | |
| 219 | let mut normals = Vec::with_capacity(n); | |
| 220 | for i in 0..n { | |
| 221 | let a = pts[i]; | |
| 222 | let b = pts[(i + 1) % n]; | |
| 223 | let dx = b[0] - a[0]; | |
| 224 | let dy = b[1] - a[1]; | |
| 225 | let len = dx.hypot(dy).max(1e-6); | |
| 226 | normals.push([self_orient * dy / len, -self_orient * dx / len]); | |
| 227 | } | |
| 228 | ||
| 229 | let mut out = Vec::with_capacity(n * 2); | |
| 230 | for i in 0..n { | |
| 231 | let n0 = normals[(i + n - 1) % n]; | |
| 232 | let n1 = normals[i]; | |
| 233 | let p = pts[i]; | |
| 234 | ||
| 235 | let dot = (n0[0] * n1[0] + n0[1] * n1[1]).clamp(-1.0, 1.0); | |
| 236 | let cross = n0[0] * n1[1] - n0[1] * n1[0]; | |
| 237 | if dot > 1.0 - 1e-5 { | |
| 238 | out.push([p[0] + n0[0] * eff_amount, p[1] + n0[1] * eff_amount]); | |
| 239 | continue; | |
| 240 | } | |
| 241 | ||
| 242 | let is_outer = (cross * self_orient * eff_amount) > 0.0; | |
| 243 | let q0 = [p[0] + n0[0] * eff_amount, p[1] + n0[1] * eff_amount]; | |
| 244 | let q1 = [p[0] + n1[0] * eff_amount, p[1] + n1[1] * eff_amount]; | |
| 245 | let denom = 1.0 + dot; | |
| 246 | ||
| 247 | if is_outer { | |
| 248 | match join_style { | |
| 249 | 0 => { | |
| 250 | out.push(q0); | |
| 251 | out.push(q1); | |
| 252 | } | |
| 253 | 1 => { | |
| 254 | let a0 = (n0[1] * eff_amount).atan2(n0[0] * eff_amount); | |
| 255 | let a1 = (n1[1] * eff_amount).atan2(n1[0] * eff_amount); | |
| 256 | let mut delta = a1 - a0; | |
| 257 | while delta > std::f32::consts::PI { | |
| 258 | delta -= std::f32::consts::TAU; | |
| 259 | } | |
| 260 | while delta < -std::f32::consts::PI { | |
| 261 | delta += std::f32::consts::TAU; | |
| 262 | } | |
| 263 | let steps = ((delta.abs() / 0.25).ceil() as usize).clamp(1, 16); | |
| 264 | let rad = eff_amount.abs(); | |
| 265 | for s in 0..=steps { | |
| 266 | let a = a0 + delta * (s as f32 / steps as f32); | |
| 267 | out.push([p[0] + rad * a.cos(), p[1] + rad * a.sin()]); | |
| 268 | } | |
| 269 | } | |
| 270 | _ => { | |
| 271 | if denom > 1e-4 { | |
| 272 | let miter_ratio = (2.0 / denom).sqrt(); | |
| 273 | if miter_ratio <= miter_limit { | |
| 274 | let inv = eff_amount / denom; | |
| 275 | out.push([p[0] + (n0[0] + n1[0]) * inv, p[1] + (n0[1] + n1[1]) * inv]); | |
| 276 | } else { | |
| 277 | out.push(q0); | |
| 278 | out.push(q1); | |
| 279 | } | |
| 280 | } else { | |
| 281 | out.push(q0); | |
| 282 | out.push(q1); | |
| 283 | } | |
| 284 | } | |
| 285 | } | |
| 286 | } else if denom > 1e-4 { | |
| 287 | let miter_ratio = (2.0 / denom).sqrt(); | |
| 288 | let clamped_inv = if miter_ratio <= miter_limit { | |
| 289 | eff_amount / denom | |
| 290 | } else { | |
| 291 | eff_amount * (miter_limit / (2.0 * denom).sqrt().max(1e-4)) | |
| 292 | }; | |
| 293 | out.push([ | |
| 294 | p[0] + (n0[0] + n1[0]) * clamped_inv, | |
| 295 | p[1] + (n0[1] + n1[1]) * clamped_inv, | |
| 296 | ]); | |
| 297 | } else { | |
| 298 | out.push([(q0[0] + q1[0]) * 0.5, (q0[1] + q1[1]) * 0.5]); | |
| 299 | } | |
| 300 | } | |
| 301 | ||
| 302 | if eff_amount < 0.0 { | |
| 303 | let mut min_x = f32::INFINITY; | |
| 304 | let mut max_x = f32::NEG_INFINITY; | |
| 305 | let mut min_y = f32::INFINITY; | |
| 306 | let mut max_y = f32::NEG_INFINITY; | |
| 307 | for &p in &pts { | |
| 308 | min_x = min_x.min(p[0]); | |
| 309 | max_x = max_x.max(p[0]); | |
| 310 | min_y = min_y.min(p[1]); | |
| 311 | max_y = max_y.max(p[1]); | |
| 312 | } | |
| 313 | let half_min = 0.5 * (max_x - min_x).min(max_y - min_y); | |
| 314 | let new_area = signed_area(&out); | |
| 315 | if (-eff_amount) >= half_min - 1e-5 || new_area * orig_area <= 1e-10 { | |
| 316 | return Contour { points: Vec::new(), closed: true }; | |
| 317 | } | |
| 318 | } | |
| 319 | ||
| 320 | Contour { points: dedup_contour_points(out, true), closed: true } | |
| 321 | } | |
| 322 | ||
| 323 | /// Deterministic signed float in `[-1.0, 1.0]` from `(seed, shape_idx, mod_idx, vertex_idx, axis)`. | |
| 324 | #[inline] | |
| 325 | fn jitter_hash(seed: i64, shape_idx: u32, mod_idx: u32, vertex_idx: u32, axis: u32) -> f32 { | |
| 326 | let mut h = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) | |
| 327 | ^ (shape_idx as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9) | |
| 328 | ^ (mod_idx as u64).wrapping_mul(0x94D0_49BB_1331_11EB) | |
| 329 | ^ (vertex_idx as u64).wrapping_mul(0xD1B5_4A32_D192_ED03) | |
| 330 | ^ (axis as u64).wrapping_mul(0x517C_C1B7_2722_0A95); | |
| 331 | h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); | |
| 332 | h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); | |
| 333 | h ^= h >> 31; | |
| 334 | let u = ((h >> 40) as f32) * (1.0 / ((1u32 << 24) as f32)); | |
| 335 | u * 2.0 - 1.0 | |
| 336 | } | |
| 337 | ||
| 338 | fn subdivide_for_jitter(pts: &[[f32; 2]], closed: bool) -> Vec<[f32; 2]> { | |
| 339 | let n = pts.len(); | |
| 340 | if n < 2 || n >= 48 { | |
| 341 | return pts.to_vec(); | |
| 342 | } | |
| 343 | let seg_count = if closed { n } else { n - 1 }; | |
| 344 | let mut total_len = 0.0_f32; | |
| 345 | for i in 0..seg_count { | |
| 346 | let a = pts[i]; | |
| 347 | let b = pts[(i + 1) % n]; | |
| 348 | total_len += (b[0] - a[0]).hypot(b[1] - a[1]); | |
| 349 | } | |
| 350 | if total_len <= 1e-6 { | |
| 351 | return pts.to_vec(); | |
| 352 | } | |
| 353 | let target_step = (total_len / 48.0).max(1e-4); | |
| 354 | let mut out = Vec::with_capacity(64); | |
| 355 | for i in 0..seg_count { | |
| 356 | let a = pts[i]; | |
| 357 | let b = pts[(i + 1) % n]; | |
| 358 | let len = (b[0] - a[0]).hypot(b[1] - a[1]); | |
| 359 | let subs = ((len / target_step).ceil() as usize).clamp(1, 32); | |
| 360 | for s in 0..subs { | |
| 361 | let t = s as f32 / subs as f32; | |
| 362 | out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); | |
| 363 | } | |
| 364 | } | |
| 365 | if !closed { | |
| 366 | out.push(pts[n - 1]); | |
| 367 | } | |
| 368 | out | |
| 369 | } | |
| 370 | ||
| 371 | #[allow(clippy::too_many_arguments)] | |
| 372 | fn jitter_contour( | |
| 373 | contour: Contour, | |
| 374 | x_amount: f32, | |
| 375 | y_amount: f32, | |
| 376 | seed: i64, | |
| 377 | smoothness: f32, | |
| 378 | per_shape: bool, | |
| 379 | shape_idx: u32, | |
| 380 | mod_idx: u32, | |
| 381 | ) -> Contour { | |
| 382 | if per_shape { | |
| 383 | let dx = jitter_hash(seed, shape_idx, mod_idx, 0, 0) * x_amount; | |
| 384 | let dy = jitter_hash(seed, shape_idx, mod_idx, 0, 1) * y_amount; | |
| 385 | let points = contour.points.into_iter().map(|p| [p[0] + dx, p[1] + dy]).collect(); | |
| 386 | return Contour { points, closed: contour.closed }; | |
| 387 | } | |
| 388 | ||
| 389 | let pts = subdivide_for_jitter(&contour.points, contour.closed); | |
| 390 | let n = pts.len(); | |
| 391 | if n < 2 { | |
| 392 | return Contour { points: pts, closed: contour.closed }; | |
| 393 | } | |
| 394 | ||
| 395 | let mut offsets: Vec<[f32; 2]> = (0..n) | |
| 396 | .map(|i| { | |
| 397 | [ | |
| 398 | jitter_hash(seed, shape_idx, mod_idx, i as u32, 0) * x_amount, | |
| 399 | jitter_hash(seed, shape_idx, mod_idx, i as u32, 1) * y_amount, | |
| 400 | ] | |
| 401 | }) | |
| 402 | .collect(); | |
| 403 | ||
| 404 | if smoothness > 1e-4 { | |
| 405 | let sigma = (smoothness * 2.5).min((n as f32) * 0.5); | |
| 406 | let radius = ((sigma * 2.5).ceil() as usize).clamp(1, n / 2); | |
| 407 | let inv_two_sig_sq = 0.5 / (sigma * sigma).max(1e-4); | |
| 408 | let mut smoothed = vec![[0.0_f32; 2]; n]; | |
| 409 | for i in 0..n { | |
| 410 | let mut sx = 0.0_f32; | |
| 411 | let mut sy = 0.0_f32; | |
| 412 | let mut wsum = 0.0_f32; | |
| 413 | for d in -(radius as isize)..=(radius as isize) { | |
| 414 | let w = (-((d * d) as f32) * inv_two_sig_sq).exp(); | |
| 415 | let j = if contour.closed { | |
| 416 | (i as isize + d).rem_euclid(n as isize) as usize | |
| 417 | } else { | |
| 418 | (i as isize + d).clamp(0, (n - 1) as isize) as usize | |
| 419 | }; | |
| 420 | sx += offsets[j][0] * w; | |
| 421 | sy += offsets[j][1] * w; | |
| 422 | wsum += w; | |
| 423 | } | |
| 424 | if wsum > 1e-6 { | |
| 425 | smoothed[i] = [sx / wsum, sy / wsum]; | |
| 426 | } | |
| 427 | } | |
| 428 | let boost = (1.0 + sigma.sqrt()).min(3.0); | |
| 429 | for s in &mut smoothed { | |
| 430 | s[0] = (s[0] * boost).clamp(-x_amount.abs(), x_amount.abs()); | |
| 431 | s[1] = (s[1] * boost).clamp(-y_amount.abs(), y_amount.abs()); | |
| 432 | } | |
| 433 | offsets = smoothed; | |
| 434 | } | |
| 435 | ||
| 436 | let points = pts | |
| 437 | .into_iter() | |
| 438 | .zip(offsets) | |
| 439 | .map(|(p, o)| [p[0] + o[0], p[1] + o[1]]) | |
| 440 | .collect(); | |
| 441 | Contour { points, closed: contour.closed } | |
| 442 | } | |
| 443 | ||
| 444 | fn shift_contour_position(contour: Contour, position: f32) -> Contour { | |
| 445 | let pts = dedup_contour_points(contour.points, contour.closed); | |
| 446 | let n = pts.len(); | |
| 447 | if n < 2 { | |
| 448 | return Contour { points: pts, closed: contour.closed }; | |
| 449 | } | |
| 450 | ||
| 451 | if !contour.closed { | |
| 452 | let mut total = 0.0_f32; | |
| 453 | for i in 0..n - 1 { | |
| 454 | total += (pts[i + 1][0] - pts[i][0]).hypot(pts[i + 1][1] - pts[i][1]); | |
| 455 | } | |
| 456 | let cdx = pts[n - 1][0] - pts[0][0]; | |
| 457 | let cdy = pts[n - 1][1] - pts[0][1]; | |
| 458 | let clen = cdx.hypot(cdy); | |
| 459 | if clen <= 1e-6 || total <= 1e-6 { | |
| 460 | return Contour { points: pts, closed: false }; | |
| 461 | } | |
| 462 | let shift = position * total; | |
| 463 | let tx = (cdx / clen) * shift; | |
| 464 | let ty = (cdy / clen) * shift; | |
| 465 | return Contour { | |
| 466 | points: pts.into_iter().map(|p| [p[0] + tx, p[1] + ty]).collect(), | |
| 467 | closed: false, | |
| 468 | }; | |
| 469 | } | |
| 470 | ||
| 471 | let frac = position.rem_euclid(1.0); | |
| 472 | if frac <= 1e-6 || frac >= 1.0 - 1e-6 { | |
| 473 | return Contour { points: pts, closed: true }; | |
| 474 | } | |
| 475 | ||
| 476 | let mut seg_lens = Vec::with_capacity(n); | |
| 477 | let mut total = 0.0_f32; | |
| 478 | for i in 0..n { | |
| 479 | let a = pts[i]; | |
| 480 | let b = pts[(i + 1) % n]; | |
| 481 | let l = (b[0] - a[0]).hypot(b[1] - a[1]); | |
| 482 | seg_lens.push(l); | |
| 483 | total += l; | |
| 484 | } | |
| 485 | if total <= 1e-6 { | |
| 486 | return Contour { points: pts, closed: true }; | |
| 487 | } | |
| 488 | ||
| 489 | let target = frac * total; | |
| 490 | let mut acc = 0.0_f32; | |
| 491 | let mut split_idx = 0usize; | |
| 492 | let mut split_t = 0.0_f32; | |
| 493 | for (i, &l) in seg_lens.iter().enumerate() { | |
| 494 | if acc + l >= target || i + 1 == n { | |
| 495 | split_idx = i; | |
| 496 | split_t = if l > 1e-6 { ((target - acc) / l).clamp(0.0, 1.0) } else { 0.0 }; | |
| 497 | break; | |
| 498 | } | |
| 499 | acc += l; | |
| 500 | } | |
| 501 | ||
| 502 | let a = pts[split_idx]; | |
| 503 | let b = pts[(split_idx + 1) % n]; | |
| 504 | let start_pt = [a[0] + (b[0] - a[0]) * split_t, a[1] + (b[1] - a[1]) * split_t]; | |
| 505 | let mut out = Vec::with_capacity(n + 1); | |
| 506 | out.push(start_pt); | |
| 507 | for k in 1..=n { | |
| 508 | let idx = (split_idx + k) % n; | |
| 509 | let p = pts[idx]; | |
| 510 | if (p[0] - out.last().unwrap()[0]).hypot(p[1] - out.last().unwrap()[1]) > 1e-6 { | |
| 511 | out.push(p); | |
| 512 | } | |
| 513 | } | |
| 514 | Contour { points: dedup_contour_points(out, true), closed: true } | |
| 515 | } | |
| 516 | ||
| 517 | /// Splits pixel-space `contours` into dash/gap open `zeno::Command` segments for `line_type > 0`. | |
| 518 | pub(super) fn dash_contours( | |
| 519 | contours: &[Contour], | |
| 520 | line_type: u8, | |
| 521 | stroke_px: f32, | |
| 522 | ) -> Vec<zeno::Command> { | |
| 523 | let w = stroke_px.max(1.0); | |
| 524 | let pattern: &[f32] = match line_type { | |
| 525 | 1 => &[3.0 * w, 2.0 * w], // Dash | |
| 526 | 2 => &[0.5 * w, 1.5 * w], // Dot | |
| 527 | 3 => &[3.0 * w, 1.5 * w, 0.5 * w, 1.5 * w], // DashDot | |
| 528 | 4 => &[3.0 * w, 1.5 * w, 0.5 * w, 1.5 * w, 0.5 * w, 1.5 * w], // DashDotDot | |
| 529 | _ => return Vec::new(), | |
| 530 | }; | |
| 531 | let mut out = Vec::new(); | |
| 532 | for c in contours { | |
| 533 | let n = c.points.len(); | |
| 534 | if n < 2 { | |
| 535 | continue; | |
| 536 | } | |
| 537 | let seg_count = if c.closed { n } else { n - 1 }; | |
| 538 | let mut pat_idx = 0usize; | |
| 539 | let mut pat_rem = pattern[0]; | |
| 540 | let mut draw_on = true; | |
| 541 | let mut pen_active = false; | |
| 542 | for s in 0..seg_count { | |
| 543 | let a = c.points[s]; | |
| 544 | let b = c.points[(s + 1) % n]; | |
| 545 | let dx = b[0] - a[0]; | |
| 546 | let dy = b[1] - a[1]; | |
| 547 | let len = dx.hypot(dy); | |
| 548 | if len <= 1e-6 { | |
| 549 | continue; | |
| 550 | } | |
| 551 | let mut pos = 0.0_f32; | |
| 552 | while pos < len - 1e-5 { | |
| 553 | let step = pat_rem.min(len - pos); | |
| 554 | let t0 = pos / len; | |
| 555 | let t1 = (pos + step) / len; | |
| 556 | let p0 = [a[0] + dx * t0, a[1] + dy * t0]; | |
| 557 | let p1 = [a[0] + dx * t1, a[1] + dy * t1]; | |
| 558 | if draw_on { | |
| 559 | if !pen_active { | |
| 560 | out.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1]))); | |
| 561 | pen_active = true; | |
| 562 | } | |
| 563 | out.push(zeno::Command::LineTo(zeno::Vector::new(p1[0], p1[1]))); | |
| 564 | } else { | |
| 565 | pen_active = false; | |
| 566 | } | |
| 567 | pos += step; | |
| 568 | pat_rem -= step; | |
| 569 | if pat_rem <= 1e-5 { | |
| 570 | pat_idx = (pat_idx + 1) % pattern.len(); | |
| 571 | pat_rem = pattern[pat_idx]; | |
| 572 | draw_on = pat_idx % 2 == 0; | |
| 573 | if !draw_on { | |
| 574 | pen_active = false; | |
| 575 | } | |
| 576 | } | |
| 577 | } | |
| 578 | } | |
| 579 | } | |
| 580 | out | |
| 581 | } |
crates/engine/src/eval/shapes/raster.rs+307-75| ... | ... | @@ -1,6 +1,9 @@ |
| 1 | 1 | //! CPU rasterizer for 2D vector `ShapeTree` hierarchies using `zeno`. |
| 2 | 2 | |
| 3 | use super::geometry::{build_primitive_commands_px, clip_to_viewport, trim_path_commands}; | |
| 3 | use super::geometry::{ | |
| 4 | build_primitive_commands_px, clip_to_viewport, closed_outline_fill_commands, | |
| 5 | dash_path_commands, trim_path_commands, | |
| 6 | }; | |
| 4 | 7 | use super::{Affine2D, PathModifier, ShapeBoolOp, ShapeTree}; |
| 5 | 8 | |
| 6 | 9 | fn composite_over(dst: &mut [f32], src: &[f32]) { |
| ... | ... | @@ -17,6 +20,239 @@ fn composite_over(dst: &mut [f32], src: &[f32]) { |
| 17 | 20 | } |
| 18 | 21 | } |
| 19 | 22 | |
| 23 | struct PreparedPrim { | |
| 24 | cmds: Vec<zeno::Command>, | |
| 25 | closed: bool, | |
| 26 | stroke_px: f32, | |
| 27 | use_even_odd_ring: bool, | |
| 28 | } | |
| 29 | ||
| 30 | #[allow(clippy::too_many_arguments)] | |
| 31 | fn prepare_primitive_cmds( | |
| 32 | tree: &ShapeTree, | |
| 33 | dims: [u32; 2], | |
| 34 | mods: &[(PathModifier, Affine2D)], | |
| 35 | shape_idx: u32, | |
| 36 | ) -> Option<PreparedPrim> { | |
| 37 | let ShapeTree::Primitive { | |
| 38 | kind, | |
| 39 | xform, | |
| 40 | solid, | |
| 41 | border_width, | |
| 42 | join_style, | |
| 43 | cap_style: _, | |
| 44 | miter_limit, | |
| 45 | write_pos, | |
| 46 | write_len, | |
| 47 | fill_even_odd: _, | |
| 48 | line_type, | |
| 49 | .. | |
| 50 | } = tree | |
| 51 | else { | |
| 52 | return None; | |
| 53 | }; | |
| 54 | let [w, h] = dims; | |
| 55 | let (cmds, closed) = build_primitive_commands_px(kind, *xform, mods, shape_idx, dims); | |
| 56 | let finite = |v: &zeno::Vector| v.x.is_finite() && v.y.is_finite(); | |
| 57 | let degenerate = cmds.iter().any(|c| match c { | |
| 58 | zeno::Command::MoveTo(p) | zeno::Command::LineTo(p) => !finite(p), | |
| 59 | zeno::Command::QuadTo(a, p) => !(finite(a) && finite(p)), | |
| 60 | zeno::Command::CurveTo(a, b, p) => !(finite(a) && finite(b) && finite(p)), | |
| 61 | _ => false, | |
| 62 | }); | |
| 63 | if cmds.is_empty() || degenerate { | |
| 64 | return None; | |
| 65 | } | |
| 66 | let reach = 4.0 * w.max(h) as f32; | |
| 67 | let mut total_scale = xform.avg_scale(); | |
| 68 | for (_, px) in mods { | |
| 69 | total_scale *= px.avg_scale(); | |
| 70 | } | |
| 71 | let stroke_px = (*border_width * total_scale * (w as f32)).clamp(0.5, reach); | |
| 72 | let cmds = clip_to_viewport( | |
| 73 | cmds, | |
| 74 | closed, | |
| 75 | dims, | |
| 76 | if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }, | |
| 77 | ); | |
| 78 | let is_trimmed = !*solid && (write_pos.abs() > 1e-5 || (*write_len - 1.0).abs() > 1e-5); | |
| 79 | let cmds = if is_trimmed { | |
| 80 | trim_path_commands(cmds, closed, *write_pos, *write_len) | |
| 81 | } else { | |
| 82 | cmds | |
| 83 | }; | |
| 84 | let eff_closed = closed && (!is_trimmed || *write_len >= 1.0 - 1e-5); | |
| 85 | let cmds = if !*solid && *line_type > 0 { | |
| 86 | dash_path_commands(cmds, eff_closed, *line_type, stroke_px) | |
| 87 | } else { | |
| 88 | cmds | |
| 89 | }; | |
| 90 | if cmds.is_empty() { | |
| 91 | return None; | |
| 92 | } | |
| 93 | ||
| 94 | let mut use_even_odd_ring = false; | |
| 95 | let cmds = if !*solid && eff_closed && *line_type == 0 && stroke_px > 3.0 { | |
| 96 | if let Some(ring_cmds) = closed_outline_fill_commands(&cmds, stroke_px, *join_style, *miter_limit) { | |
| 97 | use_even_odd_ring = true; | |
| 98 | ring_cmds | |
| 99 | } else { | |
| 100 | cmds | |
| 101 | } | |
| 102 | } else { | |
| 103 | cmds | |
| 104 | }; | |
| 105 | ||
| 106 | Some(PreparedPrim { | |
| 107 | cmds, | |
| 108 | closed: eff_closed, | |
| 109 | stroke_px, | |
| 110 | use_even_odd_ring, | |
| 111 | }) | |
| 112 | } | |
| 113 | ||
| 114 | #[derive(Clone, Copy, PartialEq)] | |
| 115 | struct PrimStyleKey { | |
| 116 | color: [u32; 4], | |
| 117 | solid: bool, | |
| 118 | border_width: u32, | |
| 119 | join_style: u8, | |
| 120 | cap_style: u8, | |
| 121 | miter_limit: u32, | |
| 122 | fill_even_odd: bool, | |
| 123 | line_type: u8, | |
| 124 | } | |
| 125 | ||
| 126 | fn prim_style_key(tree: &ShapeTree) -> Option<PrimStyleKey> { | |
| 127 | let ShapeTree::Primitive { | |
| 128 | color, | |
| 129 | solid, | |
| 130 | border_width, | |
| 131 | join_style, | |
| 132 | cap_style, | |
| 133 | miter_limit, | |
| 134 | fill_even_odd, | |
| 135 | line_type, | |
| 136 | .. | |
| 137 | } = tree | |
| 138 | else { | |
| 139 | return None; | |
| 140 | }; | |
| 141 | Some(PrimStyleKey { | |
| 142 | color: color.map(f32::to_bits), | |
| 143 | solid: *solid, | |
| 144 | border_width: border_width.to_bits(), | |
| 145 | join_style: *join_style, | |
| 146 | cap_style: *cap_style, | |
| 147 | miter_limit: miter_limit.to_bits(), | |
| 148 | fill_even_odd: *fill_even_odd, | |
| 149 | line_type: *line_type, | |
| 150 | }) | |
| 151 | } | |
| 152 | ||
| 153 | #[allow(clippy::too_many_arguments)] | |
| 154 | fn rasterize_cmds_cov( | |
| 155 | cmds: &[zeno::Command], | |
| 156 | closed: bool, | |
| 157 | solid: bool, | |
| 158 | stroke_px: f32, | |
| 159 | join_style: u8, | |
| 160 | cap_style: u8, | |
| 161 | miter_limit: f32, | |
| 162 | fill_even_odd: bool, | |
| 163 | use_even_odd_ring: bool, | |
| 164 | dims: [u32; 2], | |
| 165 | cov_buf: &mut [u8], | |
| 166 | scratch: &mut zeno::Scratch, | |
| 167 | ) { | |
| 168 | let [w, h] = dims; | |
| 169 | cov_buf.fill(0); | |
| 170 | if cmds.is_empty() { | |
| 171 | return; | |
| 172 | } | |
| 173 | let style = if use_even_odd_ring { | |
| 174 | zeno::Style::Fill(zeno::Fill::EvenOdd) | |
| 175 | } else if solid && closed { | |
| 176 | zeno::Style::Fill(if fill_even_odd { zeno::Fill::EvenOdd } else { zeno::Fill::NonZero }) | |
| 177 | } else { | |
| 178 | let join = match join_style { | |
| 179 | 0 => zeno::Join::Bevel, | |
| 180 | 1 => zeno::Join::Round, | |
| 181 | _ => zeno::Join::Miter, | |
| 182 | }; | |
| 183 | let cap = match cap_style { | |
| 184 | 1 => zeno::Cap::Round, | |
| 185 | 2 => zeno::Cap::Square, | |
| 186 | _ => zeno::Cap::Butt, | |
| 187 | }; | |
| 188 | let mut st = zeno::Stroke::new(stroke_px); | |
| 189 | st.join(join).cap(cap).miter_limit(miter_limit); | |
| 190 | zeno::Style::Stroke(st) | |
| 191 | }; | |
| 192 | let _ = zeno::Mask::with_scratch(cmds, scratch) | |
| 193 | .style(style) | |
| 194 | .size(w, h) | |
| 195 | .origin(zeno::Origin::TopLeft) | |
| 196 | .render_into(cov_buf, None); | |
| 197 | } | |
| 198 | ||
| 199 | fn blend_cov_into_dst(color: [f32; 4], cov_buf: &[u8], dst: &mut [f32]) { | |
| 200 | let ca = color[3].clamp(0.0, 1.0); | |
| 201 | if ca <= 1e-6 { | |
| 202 | return; | |
| 203 | } | |
| 204 | // Fusion keeps the colour unpremultiplied: Alpha scales coverage into alpha only, not RGB. | |
| 205 | for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { | |
| 206 | if cov == 0 { | |
| 207 | continue; | |
| 208 | } | |
| 209 | let c = cov as f32 / 255.0; | |
| 210 | let inv = 1.0 - c * ca; | |
| 211 | px[0] = color[0] * c + px[0] * inv; | |
| 212 | px[1] = color[1] * c + px[1] * inv; | |
| 213 | px[2] = color[2] * c + px[2] * inv; | |
| 214 | px[3] = c * ca + px[3] * inv; | |
| 215 | } | |
| 216 | } | |
| 217 | ||
| 218 | #[allow(clippy::too_many_arguments)] | |
| 219 | fn render_cmds_into_dst( | |
| 220 | cmds: &[zeno::Command], | |
| 221 | closed: bool, | |
| 222 | color: [f32; 4], | |
| 223 | solid: bool, | |
| 224 | stroke_px: f32, | |
| 225 | join_style: u8, | |
| 226 | cap_style: u8, | |
| 227 | miter_limit: f32, | |
| 228 | fill_even_odd: bool, | |
| 229 | use_even_odd_ring: bool, | |
| 230 | dims: [u32; 2], | |
| 231 | dst: &mut [f32], | |
| 232 | cov_buf: &mut [u8], | |
| 233 | scratch: &mut zeno::Scratch, | |
| 234 | ) { | |
| 235 | let ca = color[3].clamp(0.0, 1.0); | |
| 236 | if ca <= 1e-6 || cmds.is_empty() { | |
| 237 | return; | |
| 238 | } | |
| 239 | rasterize_cmds_cov( | |
| 240 | cmds, | |
| 241 | closed, | |
| 242 | solid, | |
| 243 | stroke_px, | |
| 244 | join_style, | |
| 245 | cap_style, | |
| 246 | miter_limit, | |
| 247 | fill_even_odd, | |
| 248 | use_even_odd_ring, | |
| 249 | dims, | |
| 250 | cov_buf, | |
| 251 | scratch, | |
| 252 | ); | |
| 253 | blend_cov_into_dst(color, cov_buf, dst); | |
| 254 | } | |
| 255 | ||
| 20 | 256 | fn rasterize_shape_tree_f32( |
| 21 | 257 | tree: &ShapeTree, |
| 22 | 258 | dims: [u32; 2], |
| ... | ... | @@ -26,96 +262,92 @@ fn rasterize_shape_tree_f32( |
| 26 | 262 | cov_buf: &mut [u8], |
| 27 | 263 | scratch: &mut zeno::Scratch, |
| 28 | 264 | ) { |
| 29 | let [w, h] = dims; | |
| 30 | 265 | match tree { |
| 31 | 266 | ShapeTree::Primitive { |
| 32 | kind, | |
| 33 | xform, | |
| 34 | 267 | color, |
| 35 | 268 | solid, |
| 36 | border_width, | |
| 37 | 269 | join_style, |
| 38 | 270 | cap_style, |
| 39 | 271 | miter_limit, |
| 40 | write_pos, | |
| 41 | write_len, | |
| 272 | fill_even_odd, | |
| 273 | .. | |
| 42 | 274 | } => { |
| 43 | 275 | let shape_idx = *shape_counter; |
| 44 | 276 | *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 { | |
| 277 | let Some(prep) = prepare_primitive_cmds(tree, dims, mods, shape_idx) else { | |
| 55 | 278 | 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, | |
| 279 | }; | |
| 280 | render_cmds_into_dst( | |
| 281 | &prep.cmds, | |
| 282 | prep.closed, | |
| 283 | *color, | |
| 284 | *solid, | |
| 285 | prep.stroke_px, | |
| 286 | *join_style, | |
| 287 | *cap_style, | |
| 288 | *miter_limit, | |
| 289 | *fill_even_odd, | |
| 290 | prep.use_even_odd_ring, | |
| 67 | 291 | dims, |
| 68 | if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }, | |
| 292 | dst, | |
| 293 | cov_buf, | |
| 294 | scratch, | |
| 69 | 295 | ); |
| 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; | |
| 296 | } | |
| 297 | ShapeTree::Group(children) => { | |
| 298 | for ch in children { | |
| 299 | rasterize_shape_tree_f32(ch, dims, mods, shape_counter, dst, cov_buf, scratch); | |
| 104 | 300 | } |
| 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; | |
| 301 | } | |
| 302 | ShapeTree::CombineGroup(children) => { | |
| 303 | if let Some(first) = children.first() { | |
| 304 | if let Some(first_key) = prim_style_key(first) { | |
| 305 | if children.iter().all(|c| prim_style_key(c) == Some(first_key)) { | |
| 306 | let ShapeTree::Primitive { | |
| 307 | color, | |
| 308 | solid, | |
| 309 | join_style, | |
| 310 | cap_style, | |
| 311 | miter_limit, | |
| 312 | fill_even_odd, | |
| 313 | .. | |
| 314 | } = first | |
| 315 | else { | |
| 316 | unreachable!(); | |
| 317 | }; | |
| 318 | let mut union_cov = vec![0u8; cov_buf.len()]; | |
| 319 | let mut any_hit = false; | |
| 320 | for ch in children { | |
| 321 | let shape_idx = *shape_counter; | |
| 322 | *shape_counter = shape_counter.wrapping_add(1); | |
| 323 | if let Some(prep) = prepare_primitive_cmds(ch, dims, mods, shape_idx) { | |
| 324 | rasterize_cmds_cov( | |
| 325 | &prep.cmds, | |
| 326 | prep.closed, | |
| 327 | *solid, | |
| 328 | prep.stroke_px, | |
| 329 | *join_style, | |
| 330 | *cap_style, | |
| 331 | *miter_limit, | |
| 332 | *fill_even_odd, | |
| 333 | prep.use_even_odd_ring, | |
| 334 | dims, | |
| 335 | cov_buf, | |
| 336 | scratch, | |
| 337 | ); | |
| 338 | any_hit = true; | |
| 339 | for (u, &c) in union_cov.iter_mut().zip(cov_buf.iter()) { | |
| 340 | *u = (*u).max(c); | |
| 341 | } | |
| 342 | } | |
| 343 | } | |
| 344 | if any_hit { | |
| 345 | blend_cov_into_dst(*color, &union_cov, dst); | |
| 346 | } | |
| 347 | return; | |
| 348 | } | |
| 109 | 349 | } |
| 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 | 350 | } |
| 117 | } | |
| 118 | ShapeTree::Group(children) => { | |
| 119 | 351 | for ch in children { |
| 120 | 352 | rasterize_shape_tree_f32(ch, dims, mods, shape_counter, dst, cov_buf, scratch); |
| 121 | 353 | } |
crates/engine/src/eval/shapes/tests.rs+185| ... | ... | @@ -744,3 +744,188 @@ fn test_s_polygon_closed_open_bezier_and_transform() { |
| 744 | 744 | let apex_hit = (25..45).any(|y| p_op[(y * 100 + 50) * 4] > 200 && p_op[(y * 100 + 50) * 4 + 3] > 200); |
| 745 | 745 | assert!(apex_hit, "open Bezier sPolygon arch apex must be stroked in red"); |
| 746 | 746 | } |
| 747 | ||
| 748 | #[test] | |
| 749 | fn test_s_bspline_closed_and_open() { | |
| 750 | let src = r#"Composition { | |
| 751 | CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, | |
| 752 | Tools = ordered() { | |
| 753 | BS1 = sBSpline { | |
| 754 | Inputs = { | |
| 755 | Red = Input { Value = 1, }, Green = Input { Value = 0, }, Blue = Input { Value = 0, }, | |
| 756 | Polyline = Input { | |
| 757 | Value = BSplinePolyline { | |
| 758 | Closed = true, | |
| 759 | Points = { | |
| 760 | { X = -0.2, Y = -0.2, W = 1 }, | |
| 761 | { X = 0.2, Y = -0.2, W = 1 }, | |
| 762 | { X = 0.2, Y = 0.2, W = 1 }, | |
| 763 | { X = -0.2, Y = 0.2, W = 1 }, | |
| 764 | }, | |
| 765 | }, | |
| 766 | }, | |
| 767 | }, | |
| 768 | }, | |
| 769 | R = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "BS1", Source = "Output", }, }, }, | |
| 770 | }, | |
| 771 | }"#; | |
| 772 | let comp = Comp::from_fusion_str(src).unwrap(); | |
| 773 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 774 | let (tex, stats) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); | |
| 775 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | |
| 776 | let rgba = eng.readback_rgba(&tex).unwrap(); | |
| 777 | let mid = (32 * 64 + 32) * 4; | |
| 778 | assert_eq!(&rgba[mid..mid + 4], &[255, 0, 0, 255]); | |
| 779 | assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); | |
| 780 | ||
| 781 | // Open stroked sBSpline: center (32, 32) must remain transparent, while curve stroke along y=0 (32) near x=32 is red. | |
| 782 | let open_src = r#"Composition { | |
| 783 | CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, | |
| 784 | Tools = ordered() { | |
| 785 | BSOpen = sBSpline { | |
| 786 | Inputs = { | |
| 787 | Solid = Input { Value = 0, }, | |
| 788 | BorderWidth = Input { Value = 0.06, }, | |
| 789 | Red = Input { Value = 0, }, Green = Input { Value = 1, }, Blue = Input { Value = 0, }, | |
| 790 | Polyline = Input { | |
| 791 | Value = BSplinePolyline { | |
| 792 | Closed = false, | |
| 793 | Points = { | |
| 794 | { X = -0.35, Y = -0.2, W = 1 }, | |
| 795 | { X = 0.0, Y = 0.2, W = 1 }, | |
| 796 | { X = 0.35, Y = -0.2, W = 1 }, | |
| 797 | }, | |
| 798 | }, | |
| 799 | }, | |
| 800 | }, | |
| 801 | }, | |
| 802 | R = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "BSOpen", Source = "Output", }, }, }, | |
| 803 | }, | |
| 804 | }"#; | |
| 805 | let open_comp = Comp::from_fusion_str(open_src).unwrap(); | |
| 806 | let (tex_o, _) = eng.evaluate(&open_comp, open_comp.find_node("R").unwrap(), 0.0); | |
| 807 | let po = eng.readback_rgba(&tex_o).unwrap(); | |
| 808 | let stroke_hits = (0..64) | |
| 809 | .flat_map(|y| (0..64).map(move |x| (y * 64 + x) * 4)) | |
| 810 | .filter(|&i| po[i + 1] > 150 && po[i] < 20 && po[i + 3] > 150) | |
| 811 | .count(); | |
| 812 | assert!(stroke_hits > 30, "open stroked sBSpline should render green curve, hits={stroke_hits}"); | |
| 813 | assert_eq!(po[(56 * 64 + 32) * 4 + 3], 0, "open sBSpline bottom background stays hollow"); | |
| 814 | } | |
| 815 | ||
| 816 | #[test] | |
| 817 | fn test_s_change_style_color_opacity_and_stroke_override() { | |
| 818 | let src = r#"Composition { | |
| 819 | CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, | |
| 820 | Tools = ordered() { | |
| 821 | RectA = sRectangle { | |
| 822 | Inputs = { | |
| 823 | Width = Input { Value = 0.5, }, | |
| 824 | Height = Input { Value = 0.5, }, | |
| 825 | Red = Input { Value = 1, }, Green = Input { Value = 0, }, Blue = Input { Value = 0, }, | |
| 826 | }, | |
| 827 | }, | |
| 828 | CSColor = sChangeStyle { | |
| 829 | Inputs = { | |
| 830 | Input = Input { SourceOp = "RectA", Source = "Output", }, | |
| 831 | Red = Input { Value = 0, }, Green = Input { Value = 1, }, Blue = Input { Value = 0.5, }, | |
| 832 | Alpha = Input { Value = 0.5, }, Opacity = Input { Value = 0.5, }, | |
| 833 | }, | |
| 834 | }, | |
| 835 | RColor = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "CSColor", Source = "Output", }, }, }, | |
| 836 | CSOutline = sChangeStyle { | |
| 837 | Inputs = { | |
| 838 | Input = Input { SourceOp = "RectA", Source = "Output", }, | |
| 839 | Red = Input { Value = 0, }, Green = Input { Value = 0, }, Blue = Input { Value = 1, }, | |
| 840 | Solid = Input { Value = 0, }, | |
| 841 | BorderWidth = Input { Value = 0.05, }, | |
| 842 | }, | |
| 843 | }, | |
| 844 | ROutline = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "CSOutline", Source = "Output", }, }, }, | |
| 845 | }, | |
| 846 | }"#; | |
| 847 | let comp = Comp::from_fusion_str(src).unwrap(); | |
| 848 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 849 | ||
| 850 | let (t1, s1) = eng.evaluate(&comp, comp.find_node("RColor").unwrap(), 0.0); | |
| 851 | assert!(s1.unsupported_nodes.is_empty()); | |
| 852 | let p1 = eng.readback_rgba(&t1).unwrap(); | |
| 853 | let mid = (32 * 64 + 32) * 4; | |
| 854 | // Alpha = 0.5 * 0.5 = 0.25 -> [0, 128, 64, 64] in straight RGBA output (matching Fusion GT). | |
| 855 | assert_eq!(p1[mid], 0); | |
| 856 | assert!(p1[mid + 1] > 115 && p1[mid + 1] < 140, "expected green ~128, got {:?}", &p1[mid..mid + 4]); | |
| 857 | assert!(p1[mid + 2] > 55 && p1[mid + 2] < 75, "expected blue ~64, got {:?}", &p1[mid..mid + 4]); | |
| 858 | assert!(p1[mid + 3] > 55 && p1[mid + 3] < 75, "expected alpha ~64, got {}", p1[mid + 3]); | |
| 859 | ||
| 860 | let (t2, s2) = eng.evaluate(&comp, comp.find_node("ROutline").unwrap(), 0.0); | |
| 861 | assert!(s2.unsupported_nodes.is_empty()); | |
| 862 | let p2 = eng.readback_rgba(&t2).unwrap(); | |
| 863 | assert_eq!(p2[mid + 3], 0, "Solid=0 override must hollow out rectangle interior"); | |
| 864 | let border_hits = (0..64) | |
| 865 | .flat_map(|y| (0..64).map(move |x| (y * 64 + x) * 4)) | |
| 866 | .filter(|&i| p2[i + 2] > 180 && p2[i + 3] > 180) | |
| 867 | .count(); | |
| 868 | assert!(border_hits > 60, "blue stroke override must render border, hits={border_hits}"); | |
| 869 | } | |
| 870 | ||
| 871 | #[test] | |
| 872 | fn test_s_text_contours_and_composition() { | |
| 873 | let src = r#"Composition { | |
| 874 | CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, | |
| 875 | Tools = ordered() { | |
| 876 | Txt = sText { | |
| 877 | Inputs = { | |
| 878 | StyledText = Input { Value = "HI", }, | |
| 879 | Font = Input { Value = "Open Sans", }, | |
| 880 | Style = Input { Value = "Bold", }, | |
| 881 | Size = Input { Value = 0.35, }, | |
| 882 | Red1 = Input { Value = 1, }, Green1 = Input { Value = 0.5, }, Blue1 = Input { Value = 0, }, | |
| 883 | }, | |
| 884 | }, | |
| 885 | Out = sOutline { | |
| 886 | Inputs = { | |
| 887 | Input = Input { SourceOp = "Txt", Source = "Output", }, | |
| 888 | Thickness = Input { Value = 0.02, }, | |
| 889 | }, | |
| 890 | }, | |
| 891 | Exp = sExpand { | |
| 892 | Inputs = { | |
| 893 | Input = Input { SourceOp = "Txt", Source = "Output", }, | |
| 894 | Expand = Input { Value = 0.015, }, | |
| 895 | }, | |
| 896 | }, | |
| 897 | Cut = sRectangle { | |
| 898 | Inputs = { | |
| 899 | Width = Input { Value = 0.12, }, Height = Input { Value = 0.12, }, | |
| 900 | Red = Input { Value = 0, }, Green = Input { Value = 0, }, Blue = Input { Value = 1, }, | |
| 901 | }, | |
| 902 | }, | |
| 903 | Bool = sBoolean { | |
| 904 | Inputs = { | |
| 905 | Operation = Input { Value = FuID { "Union" }, }, | |
| 906 | Input1 = Input { SourceOp = "Txt", Source = "Output", }, | |
| 907 | Input2 = Input { SourceOp = "Cut", Source = "Output", }, | |
| 908 | }, | |
| 909 | }, | |
| 910 | Xform = sTransform { | |
| 911 | Inputs = { | |
| 912 | Input = Input { SourceOp = "Bool", Source = "Output", }, | |
| 913 | XOffset = Input { Value = 0.05, }, | |
| 914 | }, | |
| 915 | }, | |
| 916 | RTxt = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Txt", Source = "Output", }, }, }, | |
| 917 | ROut = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Out", Source = "Output", }, }, }, | |
| 918 | RExp = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Exp", Source = "Output", }, }, }, | |
| 919 | RXform = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Xform", Source = "Output", }, }, }, | |
| 920 | }, | |
| 921 | }"#; | |
| 922 | let comp = Comp::from_fusion_str(src).unwrap(); | |
| 923 | let Ok(mut eng) = Engine::new_headless() else { return }; | |
| 924 | for name in ["RTxt", "ROut", "RExp", "RXform"] { | |
| 925 | let (tex, stats) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); | |
| 926 | assert!(stats.unsupported_nodes.is_empty(), "{name} unsupported: {:?}", stats.unsupported_nodes); | |
| 927 | let px = eng.readback_rgba(&tex).unwrap(); | |
| 928 | let lit = px.chunks_exact(4).filter(|c| c[3] > 20).count(); | |
| 929 | assert!(lit > 50, "{name} must rasterize visible glyph pixels, lit={lit}"); | |
| 930 | } | |
| 931 | } |
crates/engine/src/eval/warps_masks/bspline.rs+54-36| ... | ... | @@ -38,7 +38,7 @@ pub(in crate::eval) fn parse_bspline_table(tbl: &LuaTable) -> BSplineShape { |
| 38 | 38 | BSplineShape { closed, points } |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | fn find_tool_table_in_tools<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a LuaTable> { | |
| 41 | pub(in crate::eval) fn find_tool_table_in_tools<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a LuaTable> { | |
| 42 | 42 | if let Some(t) = tools.get_table(name) { |
| 43 | 43 | return Some(t); |
| 44 | 44 | } |
| ... | ... | @@ -54,7 +54,7 @@ fn find_tool_table_in_tools<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a L |
| 54 | 54 | None |
| 55 | 55 | } |
| 56 | 56 | |
| 57 | fn parse_bspline_keyframes(spline_tbl: &LuaTable) -> Option<Vec<(f64, BSplineShape)>> { | |
| 57 | pub(in crate::eval) fn parse_bspline_keyframes(spline_tbl: &LuaTable) -> Option<Vec<(f64, BSplineShape)>> { | |
| 58 | 58 | let kfs = spline_tbl.get_table("KeyFrames")?; |
| 59 | 59 | let mut out = Vec::with_capacity(kfs.entries.len()); |
| 60 | 60 | for (k, v) in &kfs.entries { |
| ... | ... | @@ -76,7 +76,7 @@ fn parse_bspline_keyframes(spline_tbl: &LuaTable) -> Option<Vec<(f64, BSplineSha |
| 76 | 76 | Some(out) |
| 77 | 77 | } |
| 78 | 78 | |
| 79 | fn interp_bspline_kfs( | |
| 79 | pub(in crate::eval) fn interp_bspline_kfs( | |
| 80 | 80 | comp: &Comp, |
| 81 | 81 | spline_name: &str, |
| 82 | 82 | kfs: &[(f64, BSplineShape)], |
| ... | ... | @@ -134,7 +134,7 @@ fn interp_bspline_kfs( |
| 134 | 134 | } |
| 135 | 135 | } |
| 136 | 136 | |
| 137 | fn eval_bspline_shape(comp: &Comp, node: &Node, time: f64) -> BSplineShape { | |
| 137 | pub(in crate::eval) fn eval_bspline_shape(comp: &Comp, node: &Node, time: f64) -> BSplineShape { | |
| 138 | 138 | for port in ["Polyline", "PolyLine", "Polyline2"] { |
| 139 | 139 | if let Some(src_name) = node.connected_node(port) { |
| 140 | 140 | if let Some(root) = comp.raw_root.as_ref() { |
| ... | ... | @@ -178,43 +178,29 @@ fn eval_bspline_shape(comp: &Comp, node: &Node, time: f64) -> BSplineShape { |
| 178 | 178 | BSplineShape { closed: false, points: Vec::new() } |
| 179 | 179 | } |
| 180 | 180 | |
| 181 | /// Evaluates a uniform rational cubic B-spline into pixel-space polygon vertices. | |
| 182 | pub(in crate::eval) fn evaluate_bspline_polygon( | |
| 183 | shape: &BSplineShape, | |
| 184 | size: [u32; 2], | |
| 185 | center: [f32; 2], | |
| 186 | scale: f32, | |
| 187 | angle_deg: f32, | |
| 181 | /// Evaluates a uniform rational cubic B-spline over already-transformed 2D control points. | |
| 182 | pub(in crate::eval) fn eval_rational_cubic_bspline_2d( | |
| 183 | points: &[([f32; 2], f32)], | |
| 184 | closed: bool, | |
| 185 | steps_for_chord: impl Fn(f32) -> usize, | |
| 188 | 186 | ) -> Vec<[f32; 2]> { |
| 189 | let n = shape.points.len(); | |
| 190 | if (shape.closed && n < 3) || (!shape.closed && n < 2) || size[0] == 0 || size[1] == 0 { | |
| 187 | let n = points.len(); | |
| 188 | if (closed && n < 3) || (!closed && n < 2) { | |
| 191 | 189 | return Vec::new(); |
| 192 | 190 | } |
| 193 | let [w, h] = size; | |
| 194 | let aspect = w as f32 / (h as f32).max(1.0); | |
| 195 | let (s, c) = angle_deg.to_radians().sin_cos(); | |
| 196 | let to_px = |x: f64, y: f64| -> [f32; 2] { | |
| 197 | let sx = x as f32 * scale; | |
| 198 | let sy = (y as f32 * scale) / aspect; | |
| 199 | let rx = sx * c - sy * s; | |
| 200 | let ry = (sx * s + sy * c) * aspect; | |
| 201 | [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32] | |
| 202 | }; | |
| 203 | ||
| 204 | 191 | let mut ctrl: Vec<([f32; 2], f32)> = Vec::with_capacity(n + 6); |
| 205 | if shape.closed { | |
| 206 | for p in &shape.points { | |
| 207 | ctrl.push((to_px(p.x, p.y), p.w.max(0.0) as f32)); | |
| 192 | if closed { | |
| 193 | for &(pt, w) in points { | |
| 194 | ctrl.push((pt, w.max(0.0))); | |
| 208 | 195 | } |
| 209 | 196 | } else { |
| 210 | 197 | // Clamped open cubic B-spline: repeat endpoints twice so curve interpolates P0 and P_{n-1}. |
| 211 | let first = (to_px(shape.points[0].x, shape.points[0].y), shape.points[0].w.max(0.0) as f32); | |
| 212 | let last_p = shape.points[n - 1]; | |
| 213 | let last = (to_px(last_p.x, last_p.y), last_p.w.max(0.0) as f32); | |
| 198 | let first = (points[0].0, points[0].1.max(0.0)); | |
| 199 | let last = (points[n - 1].0, points[n - 1].1.max(0.0)); | |
| 214 | 200 | ctrl.push(first); |
| 215 | 201 | ctrl.push(first); |
| 216 | for p in &shape.points { | |
| 217 | ctrl.push((to_px(p.x, p.y), p.w.max(0.0) as f32)); | |
| 202 | for &(pt, w) in points { | |
| 203 | ctrl.push((pt, w.max(0.0))); | |
| 218 | 204 | } |
| 219 | 205 | ctrl.push(last); |
| 220 | 206 | ctrl.push(last); |
| ... | ... | @@ -243,17 +229,17 @@ pub(in crate::eval) fn evaluate_bspline_polygon( |
| 243 | 229 | ]) |
| 244 | 230 | }; |
| 245 | 231 | |
| 246 | let seg_count = if shape.closed { n } else { ctrl.len().saturating_sub(3) }; | |
| 232 | let seg_count = if closed { n } else { ctrl.len().saturating_sub(3) }; | |
| 247 | 233 | let mut poly = Vec::with_capacity(seg_count * 20); |
| 248 | 234 | for seg in 0..seg_count { |
| 249 | let (p0, p1, p2, p3) = if shape.closed { | |
| 235 | let (p0, p1, p2, p3) = if closed { | |
| 250 | 236 | (ctrl[(seg + n - 1) % n], ctrl[seg], ctrl[(seg + 1) % n], ctrl[(seg + 2) % n]) |
| 251 | 237 | } else { |
| 252 | 238 | (ctrl[seg], ctrl[seg + 1], ctrl[seg + 2], ctrl[seg + 3]) |
| 253 | 239 | }; |
| 254 | 240 | let chord = (p2.0[0] - p1.0[0]).hypot(p2.0[1] - p1.0[1]); |
| 255 | let steps = ((chord * 0.25).ceil() as usize).clamp(16, 48); | |
| 256 | let end = if !shape.closed && seg + 1 == seg_count { steps } else { steps - 1 }; | |
| 241 | let steps = steps_for_chord(chord).max(1); | |
| 242 | let end = if !closed && seg + 1 == seg_count { steps } else { steps - 1 }; | |
| 257 | 243 | for st in 0..=end { |
| 258 | 244 | let t = st as f32 / steps as f32; |
| 259 | 245 | if let Some(pt) = eval_seg(p0, p1, p2, p3, t) { |
| ... | ... | @@ -266,6 +252,38 @@ pub(in crate::eval) fn evaluate_bspline_polygon( |
| 266 | 252 | poly |
| 267 | 253 | } |
| 268 | 254 | |
| 255 | /// Evaluates a uniform rational cubic B-spline into pixel-space polygon vertices. | |
| 256 | pub(in crate::eval) fn evaluate_bspline_polygon( | |
| 257 | shape: &BSplineShape, | |
| 258 | size: [u32; 2], | |
| 259 | center: [f32; 2], | |
| 260 | scale: f32, | |
| 261 | angle_deg: f32, | |
| 262 | ) -> Vec<[f32; 2]> { | |
| 263 | let n = shape.points.len(); | |
| 264 | if (shape.closed && n < 3) || (!shape.closed && n < 2) || size[0] == 0 || size[1] == 0 { | |
| 265 | return Vec::new(); | |
| 266 | } | |
| 267 | let [w, h] = size; | |
| 268 | let aspect = w as f32 / (h as f32).max(1.0); | |
| 269 | let (s, c) = angle_deg.to_radians().sin_cos(); | |
| 270 | let to_px = |x: f64, y: f64| -> [f32; 2] { | |
| 271 | let sx = x as f32 * scale; | |
| 272 | let sy = (y as f32 * scale) / aspect; | |
| 273 | let rx = sx * c - sy * s; | |
| 274 | let ry = (sx * s + sy * c) * aspect; | |
| 275 | [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32] | |
| 276 | }; | |
| 277 | let pts: Vec<([f32; 2], f32)> = shape | |
| 278 | .points | |
| 279 | .iter() | |
| 280 | .map(|p| (to_px(p.x, p.y), p.w as f32)) | |
| 281 | .collect(); | |
| 282 | eval_rational_cubic_bspline_2d(&pts, shape.closed, |chord| { | |
| 283 | ((chord * 0.25).ceil() as usize).clamp(16, 48) | |
| 284 | }) | |
| 285 | } | |
| 286 | ||
| 269 | 287 | fn trim_poly_arc(poly: &[[f32; 2]], closed: bool, write_pos: f32, write_len: f32) -> Vec<[f32; 2]> { |
| 270 | 288 | let write_pos = if write_pos.is_finite() { write_pos } else { 0.0 }; |
| 271 | 289 | let write_len = if write_len.is_finite() { write_len.clamp(0.0, 1.0) } else { 1.0 }; |
crates/engine/src/particles.rs+66-5| ... | ... | @@ -4,11 +4,16 @@ |
| 4 | 4 | //! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pVortex`, `pFlock`, `pSpawn`, |
| 5 | 5 | //! `pChangeStyle`, `pGradientForce`, `pMerge`, and `pRender` (2D mode). |
| 6 | 6 | |
| 7 | mod custom; | |
| 8 | mod custom_eval; | |
| 9 | mod extra_forces; | |
| 7 | 10 | mod forces; |
| 8 | 11 | mod plan; |
| 9 | 12 | mod raster; |
| 10 | 13 | mod sim; |
| 11 | 14 | #[cfg(test)] |
| 15 | mod extra_tests; | |
| 16 | #[cfg(test)] | |
| 12 | 17 | mod tests; |
| 13 | 18 | |
| 14 | 19 | pub use plan::collect_bitmap_sources; |
| ... | ... | @@ -90,16 +95,29 @@ struct CachedSim { |
| 90 | 95 | snapshots: BTreeMap<i64, SimState>, |
| 91 | 96 | } |
| 92 | 97 | |
| 93 | #[derive(Clone, Default)] | |
| 98 | #[derive(Clone)] | |
| 94 | 99 | struct SimState { |
| 95 | 100 | particles: Vec<Particle>, |
| 96 | 101 | /// Fractional emission accumulator per `pEmitter` stable name hash. |
| 97 | 102 | emit_accum: HashMap<u64, f64>, |
| 103 | /// Monotonically increasing particle ID counter for `id` in `pCustom` / `pAvoid`. | |
| 104 | next_id: u32, | |
| 105 | } | |
| 106 | ||
| 107 | impl Default for SimState { | |
| 108 | fn default() -> Self { | |
| 109 | Self { | |
| 110 | particles: Vec::new(), | |
| 111 | emit_accum: HashMap::new(), | |
| 112 | next_id: 1, | |
| 113 | } | |
| 114 | } | |
| 98 | 115 | } |
| 99 | 116 | |
| 100 | 117 | #[derive(Clone, Copy, Debug)] |
| 101 | 118 | struct Particle { |
| 102 | 119 | emitter_hash: u64, |
| 120 | id: u32, | |
| 103 | 121 | /// Particle set membership bitmask (bit 0 = Set1 .. bit 31 = Set32). |
| 104 | 122 | sets: u32, |
| 105 | 123 | /// Optional per-particle style override applied by `pChangeStyle` / `pSpawn`. |
| ... | ... | @@ -110,11 +128,15 @@ struct Particle { |
| 110 | 128 | bitmap_owner_hash: u64, |
| 111 | 129 | pos: [f64; 3], |
| 112 | 130 | vel: [f64; 3], |
| 131 | rot_xy: [f64; 2], | |
| 113 | 132 | rot_z: f64, |
| 133 | spin_xy: [f64; 2], | |
| 114 | 134 | spin_z: f64, |
| 115 | 135 | age: f64, |
| 116 | 136 | lifespan: f64, |
| 117 | 137 | size: f64, |
| 138 | mass: f64, | |
| 139 | user: f64, | |
| 118 | 140 | color: [f32; 4], |
| 119 | 141 | alive: bool, |
| 120 | 142 | } |
| ... | ... | @@ -244,7 +266,7 @@ pub fn render_particles_2d( |
| 244 | 266 | |
| 245 | 267 | let gradient_fields = build_gradient_fields(comp, &plan.modifiers, sprites); |
| 246 | 268 | let mut subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); |
| 247 | if !gradient_fields.is_empty() { | |
| 269 | if !gradient_fields.is_empty() || !sprites.is_empty() { | |
| 248 | 270 | let mut h = DefaultHasher::new(); |
| 249 | 271 | subgraph_hash.hash(&mut h); |
| 250 | 272 | let mut gf_ids: Vec<NodeId> = gradient_fields.keys().copied().collect(); |
| ... | ... | @@ -253,6 +275,18 @@ pub fn render_particles_2d( |
| 253 | 275 | id.0.hash(&mut h); |
| 254 | 276 | gradient_fields[&id].content_hash.hash(&mut h); |
| 255 | 277 | } |
| 278 | let mut spr_ids: Vec<NodeId> = sprites.keys().copied().collect(); | |
| 279 | spr_ids.sort_by_key(|id| id.0); | |
| 280 | for id in spr_ids { | |
| 281 | let sp = &sprites[&id]; | |
| 282 | id.0.hash(&mut h); | |
| 283 | sp.size.hash(&mut h); | |
| 284 | sp.rgba.len().hash(&mut h); | |
| 285 | let step = (sp.rgba.len() / 256).max(1); | |
| 286 | for b in sp.rgba.iter().step_by(step) { | |
| 287 | b.hash(&mut h); | |
| 288 | } | |
| 289 | } | |
| 256 | 290 | subgraph_hash = h.finish(); |
| 257 | 291 | } |
| 258 | 292 | let key = (rnode.name.clone(), subgraph_hash); |
| ... | ... | @@ -270,7 +304,16 @@ pub fn render_particles_2d( |
| 270 | 304 | } else if target_frame > cached.current_frame { |
| 271 | 305 | if i128::from(target_frame) - i128::from(cached.current_frame) <= i128::from(MAX_SIM_WINDOW) { |
| 272 | 306 | for f in cached.current_frame.saturating_add(1)..=target_frame { |
| 273 | step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); | |
| 307 | step_simulation( | |
| 308 | &mut cached.state, | |
| 309 | comp, | |
| 310 | &plan, | |
| 311 | &gradient_fields, | |
| 312 | sprites, | |
| 313 | f, | |
| 314 | sim_origin, | |
| 315 | expr, | |
| 316 | ); | |
| 274 | 317 | maybe_record_snapshot(cached, f); |
| 275 | 318 | } |
| 276 | 319 | cached.current_frame = target_frame; |
| ... | ... | @@ -284,7 +327,16 @@ pub fn render_particles_2d( |
| 284 | 327 | cached.current_frame = snap_f; |
| 285 | 328 | if snap_f < target_frame { |
| 286 | 329 | for f in snap_f.saturating_add(1)..=target_frame { |
| 287 | step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); | |
| 330 | step_simulation( | |
| 331 | &mut cached.state, | |
| 332 | comp, | |
| 333 | &plan, | |
| 334 | &gradient_fields, | |
| 335 | sprites, | |
| 336 | f, | |
| 337 | sim_origin, | |
| 338 | expr, | |
| 339 | ); | |
| 288 | 340 | maybe_record_snapshot(cached, f); |
| 289 | 341 | } |
| 290 | 342 | } |
| ... | ... | @@ -309,7 +361,16 @@ pub fn render_particles_2d( |
| 309 | 361 | snapshots: BTreeMap::new(), |
| 310 | 362 | }; |
| 311 | 363 | for f in sim_start..=target_frame { |
| 312 | step_simulation(&mut sim.state, comp, &plan, &gradient_fields, f, expr); | |
| 364 | step_simulation( | |
| 365 | &mut sim.state, | |
| 366 | comp, | |
| 367 | &plan, | |
| 368 | &gradient_fields, | |
| 369 | sprites, | |
| 370 | f, | |
| 371 | sim_start, | |
| 372 | expr, | |
| 373 | ); | |
| 313 | 374 | maybe_record_snapshot(&mut sim, f); |
| 314 | 375 | } |
| 315 | 376 | cache.entries.insert(key.clone(), sim); |
crates/engine/src/particles/custom.rs created+494| ... | ... | @@ -0,0 +1,494 @@ |
| 1 | //! Pure-Rust per-particle expression parser & evaluator for `pCustom` and `pCustomForce`. | |
| 2 | //! | |
| 3 | //! Supports Fusion particle expressions (`px/py/pz`, `vx/vy/vz`, `rx/ry/rz`, `sx/sy/sz`, | |
| 4 | //! `r/g/b/a`, `size`, `age`, `lifespan`/`life`, `id`, `mass`, `user`, `time`, `n1..n8`, | |
| 5 | //! `p1x/p1y/p1z..p4x/p4y/p4z`, `s1..s4`, `i1..i8`, `getr1/g1/b1/a1`, degree trig + radian | |
| 6 | //! `sinr/cosr/...`, `abs/sqrt/pow/exp/log/floor/ceil/round/clamp/min/max/if/iif/mix/step/smoothstep/rand/rands/noise`). | |
| 7 | ||
| 8 | ||
| 9 | #[derive(Clone, Debug, PartialEq)] | |
| 10 | enum Tok { | |
| 11 | Num(f64), | |
| 12 | Ident(String), | |
| 13 | Plus, | |
| 14 | Minus, | |
| 15 | Star, | |
| 16 | Slash, | |
| 17 | Percent, | |
| 18 | Caret, | |
| 19 | LParen, | |
| 20 | RParen, | |
| 21 | Comma, | |
| 22 | Lt, | |
| 23 | Le, | |
| 24 | Gt, | |
| 25 | Ge, | |
| 26 | Eq, | |
| 27 | Ne, | |
| 28 | And, | |
| 29 | Or, | |
| 30 | Bang, | |
| 31 | } | |
| 32 | ||
| 33 | fn tokenize(src: &str) -> Result<Vec<Tok>, ()> { | |
| 34 | let b = src.as_bytes(); | |
| 35 | let mut out = Vec::new(); | |
| 36 | let mut i = 0; | |
| 37 | while i < b.len() { | |
| 38 | let c = b[i]; | |
| 39 | if c.is_ascii_whitespace() { | |
| 40 | i += 1; | |
| 41 | continue; | |
| 42 | } | |
| 43 | if c == b'/' && b.get(i + 1) == Some(&b'/') { | |
| 44 | i += 2; | |
| 45 | while i < b.len() && b[i] != b'\n' { | |
| 46 | i += 1; | |
| 47 | } | |
| 48 | continue; | |
| 49 | } | |
| 50 | if c == b'/' && b.get(i + 1) == Some(&b'*') { | |
| 51 | i += 2; | |
| 52 | while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') { | |
| 53 | i += 1; | |
| 54 | } | |
| 55 | i = (i + 2).min(b.len()); | |
| 56 | continue; | |
| 57 | } | |
| 58 | if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) { | |
| 59 | let start = i; | |
| 60 | while i < b.len() && b[i].is_ascii_digit() { | |
| 61 | i += 1; | |
| 62 | } | |
| 63 | if b.get(i) == Some(&b'.') { | |
| 64 | i += 1; | |
| 65 | while i < b.len() && b[i].is_ascii_digit() { | |
| 66 | i += 1; | |
| 67 | } | |
| 68 | } | |
| 69 | if matches!(b.get(i), Some(b'e' | b'E')) { | |
| 70 | let exp_pos = i; | |
| 71 | i += 1; | |
| 72 | if matches!(b.get(i), Some(b'+' | b'-')) { | |
| 73 | i += 1; | |
| 74 | } | |
| 75 | let dig_start = i; | |
| 76 | while i < b.len() && b[i].is_ascii_digit() { | |
| 77 | i += 1; | |
| 78 | } | |
| 79 | if i == dig_start { | |
| 80 | i = exp_pos; | |
| 81 | } | |
| 82 | } | |
| 83 | let v: f64 = src[start..i].parse().map_err(|_| ())?; | |
| 84 | out.push(Tok::Num(v)); | |
| 85 | continue; | |
| 86 | } | |
| 87 | if c.is_ascii_alphabetic() || c == b'_' { | |
| 88 | let start = i; | |
| 89 | while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { | |
| 90 | i += 1; | |
| 91 | } | |
| 92 | out.push(Tok::Ident(src[start..i].to_owned())); | |
| 93 | continue; | |
| 94 | } | |
| 95 | let next = b.get(i + 1).copied(); | |
| 96 | match (c, next) { | |
| 97 | (b'<', Some(b'=')) => { out.push(Tok::Le); i += 2; } | |
| 98 | (b'>', Some(b'=')) => { out.push(Tok::Ge); i += 2; } | |
| 99 | (b'=', Some(b'=')) => { out.push(Tok::Eq); i += 2; } | |
| 100 | (b'!', Some(b'=')) | (b'~', Some(b'=')) | (b'<', Some(b'>')) => { out.push(Tok::Ne); i += 2; } | |
| 101 | (b'&', Some(b'&')) => { out.push(Tok::And); i += 2; } | |
| 102 | (b'|', Some(b'|')) => { out.push(Tok::Or); i += 2; } | |
| 103 | (b'+', _) => { out.push(Tok::Plus); i += 1; } | |
| 104 | (b'-', _) => { out.push(Tok::Minus); i += 1; } | |
| 105 | (b'*', _) => { out.push(Tok::Star); i += 1; } | |
| 106 | (b'/', _) => { out.push(Tok::Slash); i += 1; } | |
| 107 | (b'%', _) => { out.push(Tok::Percent); i += 1; } | |
| 108 | (b'^', _) => { out.push(Tok::Caret); i += 1; } | |
| 109 | (b'(', _) => { out.push(Tok::LParen); i += 1; } | |
| 110 | (b')', _) => { out.push(Tok::RParen); i += 1; } | |
| 111 | (b',', _) => { out.push(Tok::Comma); i += 1; } | |
| 112 | (b'<', _) => { out.push(Tok::Lt); i += 1; } | |
| 113 | (b'>', _) => { out.push(Tok::Gt); i += 1; } | |
| 114 | (b'=', _) => { out.push(Tok::Eq); i += 1; } | |
| 115 | (b'&', _) => { out.push(Tok::And); i += 1; } | |
| 116 | (b'|', _) => { out.push(Tok::Or); i += 1; } | |
| 117 | (b'!', _) => { out.push(Tok::Bang); i += 1; } | |
| 118 | _ => return Err(()), | |
| 119 | } | |
| 120 | } | |
| 121 | Ok(out) | |
| 122 | } | |
| 123 | ||
| 124 | #[derive(Clone, Copy, Debug)] | |
| 125 | pub(super) enum Var { | |
| 126 | Px, Py, Pz, | |
| 127 | Vx, Vy, Vz, | |
| 128 | Rx, Ry, Rz, | |
| 129 | Sx, Sy, Sz, | |
| 130 | R, G, B, A, | |
| 131 | Size, Age, Lifespan, Id, Mass, User, Time, Pi, E, | |
| 132 | Num(u8), | |
| 133 | Pt(u8, u8), | |
| 134 | Setup(u8), | |
| 135 | Inter(u8), | |
| 136 | } | |
| 137 | ||
| 138 | #[derive(Clone, Copy, Debug)] | |
| 139 | pub(super) enum BinOp { | |
| 140 | Add, Sub, Mul, Div, Mod, Pow, | |
| 141 | Lt, Le, Gt, Ge, Eq, Ne, | |
| 142 | And, Or, | |
| 143 | } | |
| 144 | ||
| 145 | #[derive(Clone, Copy, Debug)] | |
| 146 | pub(super) enum Func { | |
| 147 | Sin, Cos, Tan, Asin, Acos, Atan, Atan2, | |
| 148 | Sinr, Cosr, Tanr, Asinr, Acosr, Atanr, Atan2r, | |
| 149 | Sinh, Cosh, Tanh, Deg, Rad, | |
| 150 | Abs, Sqrt, Pow, Exp, Log, Log10, Log2, | |
| 151 | Floor, Ceil, Round, Trunc, Fract, Sign, | |
| 152 | Min, Max, Clamp, Mod, If, Dist, Hypot, Mix, Step, Smoothstep, | |
| 153 | Rand, Rands, Noise1, Noise2, Noise3, | |
| 154 | SampleImg(u8, u8), // (channel 0..4, edge_mode 0..2) | |
| 155 | } | |
| 156 | ||
| 157 | #[derive(Clone, Debug)] | |
| 158 | pub(super) enum Ast { | |
| 159 | Const(f64), | |
| 160 | Var(Var), | |
| 161 | Neg(Box<Ast>), | |
| 162 | Not(Box<Ast>), | |
| 163 | Bin(BinOp, Box<Ast>, Box<Ast>), | |
| 164 | Call(Func, Vec<Ast>), | |
| 165 | } | |
| 166 | ||
| 167 | struct Parser<'a> { | |
| 168 | toks: &'a [Tok], | |
| 169 | pos: usize, | |
| 170 | depth: usize, | |
| 171 | } | |
| 172 | ||
| 173 | impl<'a> Parser<'a> { | |
| 174 | fn peek(&self) -> Option<&Tok> { | |
| 175 | self.toks.get(self.pos) | |
| 176 | } | |
| 177 | ||
| 178 | fn eat(&mut self, t: &Tok) -> bool { | |
| 179 | if self.peek() == Some(t) { | |
| 180 | self.pos += 1; | |
| 181 | true | |
| 182 | } else { | |
| 183 | false | |
| 184 | } | |
| 185 | } | |
| 186 | ||
| 187 | fn parse(&mut self) -> Result<Ast, ()> { | |
| 188 | if self.toks.is_empty() { | |
| 189 | return Ok(Ast::Const(0.0)); | |
| 190 | } | |
| 191 | let e = self.parse_or()?; | |
| 192 | if self.pos != self.toks.len() { | |
| 193 | return Err(()); | |
| 194 | } | |
| 195 | Ok(e) | |
| 196 | } | |
| 197 | ||
| 198 | fn with_depth(&mut self, f: impl FnOnce(&mut Self) -> Result<Ast, ()>) -> Result<Ast, ()> { | |
| 199 | if self.depth >= 64 { | |
| 200 | return Err(()); | |
| 201 | } | |
| 202 | self.depth += 1; | |
| 203 | let r = f(self); | |
| 204 | self.depth -= 1; | |
| 205 | r | |
| 206 | } | |
| 207 | ||
| 208 | fn parse_or(&mut self) -> Result<Ast, ()> { | |
| 209 | let mut lhs = self.parse_and()?; | |
| 210 | while self.eat(&Tok::Or) { | |
| 211 | let rhs = self.parse_and()?; | |
| 212 | lhs = Ast::Bin(BinOp::Or, Box::new(lhs), Box::new(rhs)); | |
| 213 | } | |
| 214 | Ok(lhs) | |
| 215 | } | |
| 216 | ||
| 217 | fn parse_and(&mut self) -> Result<Ast, ()> { | |
| 218 | let mut lhs = self.parse_cmp()?; | |
| 219 | while self.eat(&Tok::And) { | |
| 220 | let rhs = self.parse_cmp()?; | |
| 221 | lhs = Ast::Bin(BinOp::And, Box::new(lhs), Box::new(rhs)); | |
| 222 | } | |
| 223 | Ok(lhs) | |
| 224 | } | |
| 225 | ||
| 226 | fn parse_cmp(&mut self) -> Result<Ast, ()> { | |
| 227 | let mut lhs = self.parse_add()?; | |
| 228 | loop { | |
| 229 | let op = match self.peek() { | |
| 230 | Some(Tok::Lt) => BinOp::Lt, | |
| 231 | Some(Tok::Le) => BinOp::Le, | |
| 232 | Some(Tok::Gt) => BinOp::Gt, | |
| 233 | Some(Tok::Ge) => BinOp::Ge, | |
| 234 | Some(Tok::Eq) => BinOp::Eq, | |
| 235 | Some(Tok::Ne) => BinOp::Ne, | |
| 236 | _ => break, | |
| 237 | }; | |
| 238 | self.pos += 1; | |
| 239 | let rhs = self.parse_add()?; | |
| 240 | lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs)); | |
| 241 | } | |
| 242 | Ok(lhs) | |
| 243 | } | |
| 244 | ||
| 245 | fn parse_add(&mut self) -> Result<Ast, ()> { | |
| 246 | let mut lhs = self.parse_mul()?; | |
| 247 | loop { | |
| 248 | if self.eat(&Tok::Plus) { | |
| 249 | let rhs = self.parse_mul()?; | |
| 250 | lhs = Ast::Bin(BinOp::Add, Box::new(lhs), Box::new(rhs)); | |
| 251 | } else if self.eat(&Tok::Minus) { | |
| 252 | let rhs = self.parse_mul()?; | |
| 253 | lhs = Ast::Bin(BinOp::Sub, Box::new(lhs), Box::new(rhs)); | |
| 254 | } else { | |
| 255 | break; | |
| 256 | } | |
| 257 | } | |
| 258 | Ok(lhs) | |
| 259 | } | |
| 260 | ||
| 261 | fn parse_mul(&mut self) -> Result<Ast, ()> { | |
| 262 | let mut lhs = self.parse_pow()?; | |
| 263 | loop { | |
| 264 | if self.eat(&Tok::Star) { | |
| 265 | let rhs = self.parse_pow()?; | |
| 266 | lhs = Ast::Bin(BinOp::Mul, Box::new(lhs), Box::new(rhs)); | |
| 267 | } else if self.eat(&Tok::Slash) { | |
| 268 | let rhs = self.parse_pow()?; | |
| 269 | lhs = Ast::Bin(BinOp::Div, Box::new(lhs), Box::new(rhs)); | |
| 270 | } else if self.eat(&Tok::Percent) { | |
| 271 | let rhs = self.parse_pow()?; | |
| 272 | lhs = Ast::Bin(BinOp::Mod, Box::new(lhs), Box::new(rhs)); | |
| 273 | } else { | |
| 274 | break; | |
| 275 | } | |
| 276 | } | |
| 277 | Ok(lhs) | |
| 278 | } | |
| 279 | ||
| 280 | fn parse_pow(&mut self) -> Result<Ast, ()> { | |
| 281 | let base = self.parse_unary()?; | |
| 282 | if self.eat(&Tok::Caret) { | |
| 283 | let exp = self.with_depth(Self::parse_pow)?; | |
| 284 | Ok(Ast::Bin(BinOp::Pow, Box::new(base), Box::new(exp))) | |
| 285 | } else { | |
| 286 | Ok(base) | |
| 287 | } | |
| 288 | } | |
| 289 | ||
| 290 | fn parse_unary(&mut self) -> Result<Ast, ()> { | |
| 291 | if self.eat(&Tok::Minus) { | |
| 292 | let inner = self.with_depth(Self::parse_unary)?; | |
| 293 | Ok(Ast::Neg(Box::new(inner))) | |
| 294 | } else if self.eat(&Tok::Plus) { | |
| 295 | self.with_depth(Self::parse_unary) | |
| 296 | } else if self.eat(&Tok::Bang) { | |
| 297 | let inner = self.with_depth(Self::parse_unary)?; | |
| 298 | Ok(Ast::Not(Box::new(inner))) | |
| 299 | } else { | |
| 300 | self.parse_primary() | |
| 301 | } | |
| 302 | } | |
| 303 | ||
| 304 | fn parse_primary(&mut self) -> Result<Ast, ()> { | |
| 305 | match self.peek().cloned() { | |
| 306 | Some(Tok::LParen) => { | |
| 307 | self.pos += 1; | |
| 308 | let inner = self.with_depth(Self::parse_or)?; | |
| 309 | if !self.eat(&Tok::RParen) { | |
| 310 | return Err(()); | |
| 311 | } | |
| 312 | Ok(inner) | |
| 313 | } | |
| 314 | Some(Tok::Num(v)) => { | |
| 315 | self.pos += 1; | |
| 316 | Ok(Ast::Const(v)) | |
| 317 | } | |
| 318 | Some(Tok::Ident(name)) => { | |
| 319 | self.pos += 1; | |
| 320 | if self.eat(&Tok::LParen) { | |
| 321 | let mut args = Vec::new(); | |
| 322 | if self.peek() != Some(&Tok::RParen) { | |
| 323 | loop { | |
| 324 | args.push(self.with_depth(Self::parse_or)?); | |
| 325 | if !self.eat(&Tok::Comma) { | |
| 326 | break; | |
| 327 | } | |
| 328 | } | |
| 329 | } | |
| 330 | if !self.eat(&Tok::RParen) { | |
| 331 | return Err(()); | |
| 332 | } | |
| 333 | Ok(Ast::Call(resolve_func(&name, args.len())?, args)) | |
| 334 | } else { | |
| 335 | Ok(Ast::Var(resolve_var(&name)?)) | |
| 336 | } | |
| 337 | } | |
| 338 | _ => Err(()), | |
| 339 | } | |
| 340 | } | |
| 341 | } | |
| 342 | ||
| 343 | fn resolve_var(name: &str) -> Result<Var, ()> { | |
| 344 | match name { | |
| 345 | "px" => Ok(Var::Px), | |
| 346 | "py" => Ok(Var::Py), | |
| 347 | "pz" => Ok(Var::Pz), | |
| 348 | "vx" => Ok(Var::Vx), | |
| 349 | "vy" => Ok(Var::Vy), | |
| 350 | "vz" => Ok(Var::Vz), | |
| 351 | "rx" => Ok(Var::Rx), | |
| 352 | "ry" => Ok(Var::Ry), | |
| 353 | "rz" => Ok(Var::Rz), | |
| 354 | "sx" => Ok(Var::Sx), | |
| 355 | "sy" => Ok(Var::Sy), | |
| 356 | "sz" => Ok(Var::Sz), | |
| 357 | "r" => Ok(Var::R), | |
| 358 | "g" => Ok(Var::G), | |
| 359 | "b" => Ok(Var::B), | |
| 360 | "a" => Ok(Var::A), | |
| 361 | "size" => Ok(Var::Size), | |
| 362 | "age" => Ok(Var::Age), | |
| 363 | "lifespan" | "life" => Ok(Var::Lifespan), | |
| 364 | "id" => Ok(Var::Id), | |
| 365 | "mass" => Ok(Var::Mass), | |
| 366 | "user" => Ok(Var::User), | |
| 367 | "time" => Ok(Var::Time), | |
| 368 | "pi" => Ok(Var::Pi), | |
| 369 | "e" => Ok(Var::E), | |
| 370 | "n1" => Ok(Var::Num(0)), | |
| 371 | "n2" => Ok(Var::Num(1)), | |
| 372 | "n3" => Ok(Var::Num(2)), | |
| 373 | "n4" => Ok(Var::Num(3)), | |
| 374 | "n5" => Ok(Var::Num(4)), | |
| 375 | "n6" => Ok(Var::Num(5)), | |
| 376 | "n7" => Ok(Var::Num(6)), | |
| 377 | "n8" => Ok(Var::Num(7)), | |
| 378 | "p1x" => Ok(Var::Pt(0, 0)), | |
| 379 | "p1y" => Ok(Var::Pt(0, 1)), | |
| 380 | "p1z" => Ok(Var::Pt(0, 2)), | |
| 381 | "p2x" => Ok(Var::Pt(1, 0)), | |
| 382 | "p2y" => Ok(Var::Pt(1, 1)), | |
| 383 | "p2z" => Ok(Var::Pt(1, 2)), | |
| 384 | "p3x" => Ok(Var::Pt(2, 0)), | |
| 385 | "p3y" => Ok(Var::Pt(2, 1)), | |
| 386 | "p3z" => Ok(Var::Pt(2, 2)), | |
| 387 | "p4x" => Ok(Var::Pt(3, 0)), | |
| 388 | "p4y" => Ok(Var::Pt(3, 1)), | |
| 389 | "p4z" => Ok(Var::Pt(3, 2)), | |
| 390 | "s1" => Ok(Var::Setup(0)), | |
| 391 | "s2" => Ok(Var::Setup(1)), | |
| 392 | "s3" => Ok(Var::Setup(2)), | |
| 393 | "s4" => Ok(Var::Setup(3)), | |
| 394 | "i1" => Ok(Var::Inter(0)), | |
| 395 | "i2" => Ok(Var::Inter(1)), | |
| 396 | "i3" => Ok(Var::Inter(2)), | |
| 397 | "i4" => Ok(Var::Inter(3)), | |
| 398 | "i5" => Ok(Var::Inter(4)), | |
| 399 | "i6" => Ok(Var::Inter(5)), | |
| 400 | "i7" => Ok(Var::Inter(6)), | |
| 401 | "i8" => Ok(Var::Inter(7)), | |
| 402 | _ => Err(()), | |
| 403 | } | |
| 404 | } | |
| 405 | ||
| 406 | fn resolve_func(name: &str, argc: usize) -> Result<Func, ()> { | |
| 407 | if let Some(rest) = name.strip_prefix("get") { | |
| 408 | let bytes = rest.as_bytes(); | |
| 409 | if (2..=3).contains(&bytes.len()) && argc == 2 { | |
| 410 | let ch = match bytes[0] { | |
| 411 | b'r' => Some(0), | |
| 412 | b'g' => Some(1), | |
| 413 | b'b' => Some(2), | |
| 414 | b'a' => Some(3), | |
| 415 | b'c' => Some(4), | |
| 416 | _ => None, | |
| 417 | }; | |
| 418 | let edge = match bytes.get(2) { | |
| 419 | None | Some(b'b') => Some(0), | |
| 420 | Some(b'w') => Some(1), | |
| 421 | Some(b'd') => Some(2), | |
| 422 | _ => None, | |
| 423 | }; | |
| 424 | if let (Some(ch), Some(edge)) = (ch, edge) { | |
| 425 | if bytes[1] == b'1' || bytes[1] == b'2' { | |
| 426 | return Ok(Func::SampleImg(ch, edge)); | |
| 427 | } | |
| 428 | } | |
| 429 | } | |
| 430 | } | |
| 431 | let f = match (name, argc) { | |
| 432 | ("sin", 1) => Func::Sin, | |
| 433 | ("cos", 1) => Func::Cos, | |
| 434 | ("tan", 1) => Func::Tan, | |
| 435 | ("asin", 1) => Func::Asin, | |
| 436 | ("acos", 1) => Func::Acos, | |
| 437 | ("atan", 1) => Func::Atan, | |
| 438 | ("atan2", 2) => Func::Atan2, | |
| 439 | ("sinr", 1) => Func::Sinr, | |
| 440 | ("cosr", 1) => Func::Cosr, | |
| 441 | ("tanr", 1) => Func::Tanr, | |
| 442 | ("asinr", 1) => Func::Asinr, | |
| 443 | ("acosr", 1) => Func::Acosr, | |
| 444 | ("atanr", 1) => Func::Atanr, | |
| 445 | ("atan2r", 2) => Func::Atan2r, | |
| 446 | ("sinh", 1) => Func::Sinh, | |
| 447 | ("cosh", 1) => Func::Cosh, | |
| 448 | ("tanh", 1) => Func::Tanh, | |
| 449 | ("deg", 1) => Func::Deg, | |
| 450 | ("rad", 1) => Func::Rad, | |
| 451 | ("abs", 1) => Func::Abs, | |
| 452 | ("sqrt", 1) => Func::Sqrt, | |
| 453 | ("pow", 2) => Func::Pow, | |
| 454 | ("exp", 1) => Func::Exp, | |
| 455 | ("log" | "ln", 1) => Func::Log, | |
| 456 | ("log10", 1) => Func::Log10, | |
| 457 | ("log2", 1) => Func::Log2, | |
| 458 | ("floor" | "int", 1) => Func::Floor, | |
| 459 | ("ceil", 1) => Func::Ceil, | |
| 460 | ("round", 1) => Func::Round, | |
| 461 | ("trunc", 1) => Func::Trunc, | |
| 462 | ("fract", 1) => Func::Fract, | |
| 463 | ("sign", 1) => Func::Sign, | |
| 464 | ("min", n) if n >= 2 => Func::Min, | |
| 465 | ("max", n) if n >= 2 => Func::Max, | |
| 466 | ("clamp", 3) => Func::Clamp, | |
| 467 | ("mod", 2) => Func::Mod, | |
| 468 | ("if" | "iif", 3) => Func::If, | |
| 469 | ("dist", 4) => Func::Dist, | |
| 470 | ("hypot", 2) => Func::Hypot, | |
| 471 | ("mix" | "lerp", 3) => Func::Mix, | |
| 472 | ("step", 2) => Func::Step, | |
| 473 | ("smoothstep", 3) => Func::Smoothstep, | |
| 474 | ("rand", 2) => Func::Rand, | |
| 475 | ("rands", 3) => Func::Rands, | |
| 476 | ("noise", 1) => Func::Noise1, | |
| 477 | ("noise2", 2) => Func::Noise2, | |
| 478 | ("noise3", 3) => Func::Noise3, | |
| 479 | _ => return Err(()), | |
| 480 | }; | |
| 481 | Ok(f) | |
| 482 | } | |
| 483 | ||
| 484 | pub(super) fn compile_expr(src: &str) -> Option<Ast> { | |
| 485 | let trimmed = src.trim(); | |
| 486 | if trimmed.is_empty() { | |
| 487 | return None; | |
| 488 | } | |
| 489 | let toks = tokenize(trimmed).ok()?; | |
| 490 | let mut p = Parser { toks: &toks, pos: 0, depth: 0 }; | |
| 491 | p.parse().ok() | |
| 492 | } | |
| 493 | ||
| 494 | pub(super) use super::custom_eval::{apply_custom, apply_custom_force}; |
crates/engine/src/particles/custom_eval.rs created+467| ... | ... | @@ -0,0 +1,467 @@ |
| 1 | //! Evaluator & per-particle executors for `pCustom` and `pCustomForce`. | |
| 2 | ||
| 3 | use std::collections::HashSet; | |
| 4 | ||
| 5 | use model::{Comp, ExprEngine, Node}; | |
| 6 | ||
| 7 | use super::custom::{Ast, BinOp, Func, Var, compile_expr}; | |
| 8 | use super::forces::ModifierFilter; | |
| 9 | use super::sim::value_noise_3d; | |
| 10 | use super::{Particle, SplitMix64, SpriteImage, VELOCITY_SCALE}; | |
| 11 | ||
| 12 | struct EvalCtx<'a> { | |
| 13 | p: &'a Particle, | |
| 14 | time: f64, | |
| 15 | seed: i64, | |
| 16 | n: [f64; 8], | |
| 17 | pt: [[f64; 3]; 4], | |
| 18 | s: [f64; 4], | |
| 19 | i: [f64; 8], | |
| 20 | img: Option<&'a SpriteImage>, | |
| 21 | } | |
| 22 | ||
| 23 | fn sample_sprite(img: Option<&SpriteImage>, x: f64, y: f64, ch: u8, edge: u8) -> f64 { | |
| 24 | let Some(sp) = img else { | |
| 25 | return 0.0; | |
| 26 | }; | |
| 27 | let w = sp.size[0] as isize; | |
| 28 | let h = sp.size[1] as isize; | |
| 29 | if w <= 0 || h <= 0 || sp.rgba.len() < (w as usize) * (h as usize) * 4 { | |
| 30 | return 0.0; | |
| 31 | } | |
| 32 | // Fusion normalized image coords: (0,0) bottom-left, (1,1) top-right. | |
| 33 | let mut u = x; | |
| 34 | let mut v = 1.0 - y; | |
| 35 | match edge { | |
| 36 | 1 => { | |
| 37 | u = u.rem_euclid(1.0); | |
| 38 | v = v.rem_euclid(1.0); | |
| 39 | } | |
| 40 | 2 => { | |
| 41 | u = u.clamp(0.0, 1.0); | |
| 42 | v = v.clamp(0.0, 1.0); | |
| 43 | } | |
| 44 | _ => { | |
| 45 | if !(0.0..=1.0).contains(&u) || !(0.0..=1.0).contains(&v) { | |
| 46 | return 0.0; | |
| 47 | } | |
| 48 | } | |
| 49 | } | |
| 50 | let ix = ((u * w as f64).floor() as isize).clamp(0, w - 1) as usize; | |
| 51 | let iy = ((v * h as f64).floor() as isize).clamp(0, h - 1) as usize; | |
| 52 | let off = (iy * w as usize + ix) * 4; | |
| 53 | let px = &sp.rgba[off..off + 4]; | |
| 54 | match ch { | |
| 55 | 0 => px[0] as f64 / 255.0, | |
| 56 | 1 => px[1] as f64 / 255.0, | |
| 57 | 2 => px[2] as f64 / 255.0, | |
| 58 | 3 => px[3] as f64 / 255.0, | |
| 59 | _ => (0.2126 * px[0] as f64 + 0.7152 * px[1] as f64 + 0.0722 * px[2] as f64) / 255.0, | |
| 60 | } | |
| 61 | } | |
| 62 | ||
| 63 | fn eval_ast(ast: &Ast, ctx: &EvalCtx<'_>) -> f64 { | |
| 64 | let v = match ast { | |
| 65 | Ast::Const(c) => *c, | |
| 66 | Ast::Var(var) => match *var { | |
| 67 | Var::Px => ctx.p.pos[0], | |
| 68 | Var::Py => ctx.p.pos[1], | |
| 69 | Var::Pz => ctx.p.pos[2], | |
| 70 | Var::Vx => ctx.p.vel[0], | |
| 71 | Var::Vy => ctx.p.vel[1], | |
| 72 | Var::Vz => ctx.p.vel[2], | |
| 73 | Var::Rx => ctx.p.rot_xy[0], | |
| 74 | Var::Ry => ctx.p.rot_xy[1], | |
| 75 | Var::Rz => ctx.p.rot_z, | |
| 76 | Var::Sx => ctx.p.spin_xy[0], | |
| 77 | Var::Sy => ctx.p.spin_xy[1], | |
| 78 | Var::Sz => ctx.p.spin_z, | |
| 79 | Var::R => ctx.p.color[0] as f64, | |
| 80 | Var::G => ctx.p.color[1] as f64, | |
| 81 | Var::B => ctx.p.color[2] as f64, | |
| 82 | Var::A => ctx.p.color[3] as f64, | |
| 83 | Var::Size => ctx.p.size, | |
| 84 | Var::Age => ctx.p.age / ctx.p.lifespan.max(1.0), | |
| 85 | Var::Lifespan => ctx.p.lifespan, | |
| 86 | Var::Id => ctx.p.id as f64, | |
| 87 | Var::Mass => ctx.p.mass, | |
| 88 | Var::User => ctx.p.user, | |
| 89 | Var::Time => ctx.time, | |
| 90 | Var::Pi => std::f64::consts::PI, | |
| 91 | Var::E => std::f64::consts::E, | |
| 92 | Var::Num(idx) => ctx.n[idx as usize], | |
| 93 | Var::Pt(idx, axis) => ctx.pt[idx as usize][axis as usize], | |
| 94 | Var::Setup(idx) => ctx.s[idx as usize], | |
| 95 | Var::Inter(idx) => ctx.i[idx as usize], | |
| 96 | }, | |
| 97 | Ast::Neg(x) => -eval_ast(x, ctx), | |
| 98 | Ast::Not(x) => if eval_ast(x, ctx) == 0.0 { 1.0 } else { 0.0 }, | |
| 99 | Ast::Bin(op, a, b) => { | |
| 100 | let x = eval_ast(a, ctx); | |
| 101 | let y = eval_ast(b, ctx); | |
| 102 | match op { | |
| 103 | BinOp::Add => x + y, | |
| 104 | BinOp::Sub => x - y, | |
| 105 | BinOp::Mul => x * y, | |
| 106 | BinOp::Div => if y.abs() < 1e-12 { 0.0 } else { x / y }, | |
| 107 | BinOp::Mod => if y.abs() < 1e-12 { 0.0 } else { x % y }, | |
| 108 | BinOp::Pow => x.powf(y), | |
| 109 | BinOp::Lt => if x < y { 1.0 } else { 0.0 }, | |
| 110 | BinOp::Le => if x <= y { 1.0 } else { 0.0 }, | |
| 111 | BinOp::Gt => if x > y { 1.0 } else { 0.0 }, | |
| 112 | BinOp::Ge => if x >= y { 1.0 } else { 0.0 }, | |
| 113 | BinOp::Eq => if (x - y).abs() < 1e-12 { 1.0 } else { 0.0 }, | |
| 114 | BinOp::Ne => if (x - y).abs() >= 1e-12 { 1.0 } else { 0.0 }, | |
| 115 | BinOp::And => if x != 0.0 && y != 0.0 { 1.0 } else { 0.0 }, | |
| 116 | BinOp::Or => if x != 0.0 || y != 0.0 { 1.0 } else { 0.0 }, | |
| 117 | } | |
| 118 | } | |
| 119 | Ast::Call(func, args) => match *func { | |
| 120 | Func::Sin => eval_ast(&args[0], ctx).to_radians().sin(), | |
| 121 | Func::Cos => eval_ast(&args[0], ctx).to_radians().cos(), | |
| 122 | Func::Tan => eval_ast(&args[0], ctx).to_radians().tan(), | |
| 123 | Func::Asin => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).asin().to_degrees(), | |
| 124 | Func::Acos => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).acos().to_degrees(), | |
| 125 | Func::Atan => eval_ast(&args[0], ctx).atan().to_degrees(), | |
| 126 | Func::Atan2 => eval_ast(&args[0], ctx).atan2(eval_ast(&args[1], ctx)).to_degrees(), | |
| 127 | Func::Sinr => eval_ast(&args[0], ctx).sin(), | |
| 128 | Func::Cosr => eval_ast(&args[0], ctx).cos(), | |
| 129 | Func::Tanr => eval_ast(&args[0], ctx).tan(), | |
| 130 | Func::Asinr => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).asin(), | |
| 131 | Func::Acosr => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).acos(), | |
| 132 | Func::Atanr => eval_ast(&args[0], ctx).atan(), | |
| 133 | Func::Atan2r => eval_ast(&args[0], ctx).atan2(eval_ast(&args[1], ctx)), | |
| 134 | Func::Sinh => eval_ast(&args[0], ctx).sinh(), | |
| 135 | Func::Cosh => eval_ast(&args[0], ctx).cosh(), | |
| 136 | Func::Tanh => eval_ast(&args[0], ctx).tanh(), | |
| 137 | Func::Deg => eval_ast(&args[0], ctx).to_degrees(), | |
| 138 | Func::Rad => eval_ast(&args[0], ctx).to_radians(), | |
| 139 | Func::Abs => eval_ast(&args[0], ctx).abs(), | |
| 140 | Func::Sqrt => eval_ast(&args[0], ctx).max(0.0).sqrt(), | |
| 141 | Func::Pow => eval_ast(&args[0], ctx).powf(eval_ast(&args[1], ctx)), | |
| 142 | Func::Exp => eval_ast(&args[0], ctx).exp(), | |
| 143 | Func::Log => eval_ast(&args[0], ctx).max(1e-12).ln(), | |
| 144 | Func::Log10 => eval_ast(&args[0], ctx).max(1e-12).log10(), | |
| 145 | Func::Log2 => eval_ast(&args[0], ctx).max(1e-12).log2(), | |
| 146 | Func::Floor => eval_ast(&args[0], ctx).floor(), | |
| 147 | Func::Ceil => eval_ast(&args[0], ctx).ceil(), | |
| 148 | Func::Round => eval_ast(&args[0], ctx).round(), | |
| 149 | Func::Trunc => eval_ast(&args[0], ctx).trunc(), | |
| 150 | Func::Fract => eval_ast(&args[0], ctx).fract(), | |
| 151 | Func::Sign => { | |
| 152 | let x = eval_ast(&args[0], ctx); | |
| 153 | if x > 0.0 { 1.0 } else if x < 0.0 { -1.0 } else { 0.0 } | |
| 154 | } | |
| 155 | Func::Min => args.iter().map(|a| eval_ast(a, ctx)).fold(f64::INFINITY, f64::min), | |
| 156 | Func::Max => args.iter().map(|a| eval_ast(a, ctx)).fold(f64::NEG_INFINITY, f64::max), | |
| 157 | Func::Clamp => { | |
| 158 | let x = eval_ast(&args[0], ctx); | |
| 159 | let lo = eval_ast(&args[1], ctx); | |
| 160 | let hi = eval_ast(&args[2], ctx); | |
| 161 | if lo <= hi { x.clamp(lo, hi) } else { x.clamp(hi, lo) } | |
| 162 | } | |
| 163 | Func::Mod => { | |
| 164 | let x = eval_ast(&args[0], ctx); | |
| 165 | let y = eval_ast(&args[1], ctx); | |
| 166 | if y.abs() < 1e-12 { 0.0 } else { x % y } | |
| 167 | } | |
| 168 | Func::If => { | |
| 169 | if eval_ast(&args[0], ctx) != 0.0 { | |
| 170 | eval_ast(&args[1], ctx) | |
| 171 | } else { | |
| 172 | eval_ast(&args[2], ctx) | |
| 173 | } | |
| 174 | } | |
| 175 | Func::Dist => { | |
| 176 | let x1 = eval_ast(&args[0], ctx); | |
| 177 | let y1 = eval_ast(&args[1], ctx); | |
| 178 | let x2 = eval_ast(&args[2], ctx); | |
| 179 | let y2 = eval_ast(&args[3], ctx); | |
| 180 | (x2 - x1).hypot(y2 - y1) | |
| 181 | } | |
| 182 | Func::Hypot => eval_ast(&args[0], ctx).hypot(eval_ast(&args[1], ctx)), | |
| 183 | Func::Mix => { | |
| 184 | let a = eval_ast(&args[0], ctx); | |
| 185 | let b = eval_ast(&args[1], ctx); | |
| 186 | let u = eval_ast(&args[2], ctx); | |
| 187 | a + (b - a) * u | |
| 188 | } | |
| 189 | Func::Step => { | |
| 190 | if eval_ast(&args[1], ctx) < eval_ast(&args[0], ctx) { 0.0 } else { 1.0 } | |
| 191 | } | |
| 192 | Func::Smoothstep => { | |
| 193 | let e0 = eval_ast(&args[0], ctx); | |
| 194 | let e1 = eval_ast(&args[1], ctx); | |
| 195 | let x = eval_ast(&args[2], ctx); | |
| 196 | let u = if (e1 - e0).abs() < 1e-12 { 0.0 } else { ((x - e0) / (e1 - e0)).clamp(0.0, 1.0) }; | |
| 197 | u * u * (3.0 - 2.0 * u) | |
| 198 | } | |
| 199 | Func::Rand => { | |
| 200 | let lo = eval_ast(&args[0], ctx); | |
| 201 | let hi = eval_ast(&args[1], ctx); | |
| 202 | let mut rng = SplitMix64::from_parts(ctx.seed ^ i64::from(ctx.p.id), ctx.time.round() as i64, "pCustomRand"); | |
| 203 | rng.range(lo, hi) | |
| 204 | } | |
| 205 | Func::Rands => { | |
| 206 | let lo = eval_ast(&args[0], ctx); | |
| 207 | let hi = eval_ast(&args[1], ctx); | |
| 208 | let s = eval_ast(&args[2], ctx).to_bits() as i64; | |
| 209 | let mut rng = SplitMix64::from_parts(ctx.seed ^ s ^ i64::from(ctx.p.id), 0, "pCustomRands"); | |
| 210 | rng.range(lo, hi) | |
| 211 | } | |
| 212 | Func::Noise1 => value_noise_3d(eval_ast(&args[0], ctx), 0.0, 0.0, ctx.seed as u64), | |
| 213 | Func::Noise2 => value_noise_3d(eval_ast(&args[0], ctx), eval_ast(&args[1], ctx), 0.0, ctx.seed as u64), | |
| 214 | Func::Noise3 => value_noise_3d( | |
| 215 | eval_ast(&args[0], ctx), | |
| 216 | eval_ast(&args[1], ctx), | |
| 217 | eval_ast(&args[2], ctx), | |
| 218 | ctx.seed as u64, | |
| 219 | ), | |
| 220 | Func::SampleImg(ch, edge) => { | |
| 221 | let x = eval_ast(&args[0], ctx); | |
| 222 | let y = eval_ast(&args[1], ctx); | |
| 223 | sample_sprite(ctx.img, x, y, ch, edge) | |
| 224 | } | |
| 225 | }, | |
| 226 | }; | |
| 227 | if v.is_finite() { v } else { 0.0 } | |
| 228 | } | |
| 229 | ||
| 230 | fn read_common_inputs(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> ([f64; 8], [[f64; 3]; 4], [Option<Ast>; 4], [Option<Ast>; 8]) { | |
| 231 | let n = std::array::from_fn(|idx| { | |
| 232 | let key = format!("NumberIn{}", idx + 1); | |
| 233 | comp.eval_number(node, &key, t, 0.0, expr) | |
| 234 | }); | |
| 235 | let pt = std::array::from_fn(|idx| { | |
| 236 | let i = idx + 1; | |
| 237 | let pin_key = format!("PointIn{i}"); | |
| 238 | let def_pt = if node.inputs.contains_key(&pin_key) { | |
| 239 | comp.eval_point(node, &pin_key, t, [0.0, 0.0], expr) | |
| 240 | } else { | |
| 241 | [0.0, 0.0] | |
| 242 | }; | |
| 243 | [ | |
| 244 | comp.eval_number(node, &format!("Position{i}.X"), t, def_pt[0], expr), | |
| 245 | comp.eval_number(node, &format!("Position{i}.Y"), t, def_pt[1], expr), | |
| 246 | comp.eval_number(node, &format!("Position{i}.Z"), t, 0.0, expr), | |
| 247 | ] | |
| 248 | }); | |
| 249 | let setups = std::array::from_fn(|idx| { | |
| 250 | let key = format!("Setup{}", idx + 1); | |
| 251 | compile_expr(&comp.eval_text(node, &key, t, "", expr)) | |
| 252 | }); | |
| 253 | let inters = std::array::from_fn(|idx| { | |
| 254 | let key = format!("Intermediate{}", idx + 1); | |
| 255 | let alias = format!("Inter{}", idx + 1); | |
| 256 | let txt = if node.inputs.contains_key(&key) { | |
| 257 | comp.eval_text(node, &key, t, "", expr) | |
| 258 | } else if node.inputs.contains_key(&alias) { | |
| 259 | comp.eval_text(node, &alias, t, "", expr) | |
| 260 | } else { | |
| 261 | String::new() | |
| 262 | }; | |
| 263 | compile_expr(&txt) | |
| 264 | }); | |
| 265 | (n, pt, setups, inters) | |
| 266 | } | |
| 267 | ||
| 268 | fn compile_channel_expr( | |
| 269 | comp: &Comp, | |
| 270 | node: &Node, | |
| 271 | keys: &[&str], | |
| 272 | identity_var: &str, | |
| 273 | t: f64, | |
| 274 | expr: &ExprEngine, | |
| 275 | ) -> Option<Ast> { | |
| 276 | for &k in keys { | |
| 277 | if node.inputs.contains_key(k) { | |
| 278 | let txt = comp.eval_text(node, k, t, identity_var, expr); | |
| 279 | let trimmed = txt.trim(); | |
| 280 | if trimmed.is_empty() || trimmed == identity_var { | |
| 281 | return None; | |
| 282 | } | |
| 283 | return compile_expr(trimmed); | |
| 284 | } | |
| 285 | } | |
| 286 | None | |
| 287 | } | |
| 288 | ||
| 289 | /// Applies `pCustom` per-particle expression overrides to matching live particles. | |
| 290 | pub(super) fn apply_custom( | |
| 291 | particles: &mut [Particle], | |
| 292 | comp: &Comp, | |
| 293 | node: &Node, | |
| 294 | scope: &HashSet<u64>, | |
| 295 | img: Option<&SpriteImage>, | |
| 296 | t: f64, | |
| 297 | expr: &ExprEngine, | |
| 298 | ) { | |
| 299 | let px_ast = compile_channel_expr(comp, node, &["PositionXExpression"], "px", t, expr); | |
| 300 | let py_ast = compile_channel_expr(comp, node, &["PositionYExpression"], "py", t, expr); | |
| 301 | let pz_ast = compile_channel_expr(comp, node, &["PositionZExpression"], "pz", t, expr); | |
| 302 | let vx_ast = compile_channel_expr(comp, node, &["VelocityXExpression"], "vx", t, expr); | |
| 303 | let vy_ast = compile_channel_expr(comp, node, &["VelocityYExpression"], "vy", t, expr); | |
| 304 | let vz_ast = compile_channel_expr(comp, node, &["VelocityZExpression"], "vz", t, expr); | |
| 305 | let rx_ast = compile_channel_expr(comp, node, &["RotationXExpression"], "rx", t, expr); | |
| 306 | let ry_ast = compile_channel_expr(comp, node, &["RotationYExpression"], "ry", t, expr); | |
| 307 | let rz_ast = compile_channel_expr(comp, node, &["RotationZExpression"], "rz", t, expr); | |
| 308 | let sx_ast = compile_channel_expr(comp, node, &["SpinXExpression"], "sx", t, expr); | |
| 309 | let sy_ast = compile_channel_expr(comp, node, &["SpinYExpression"], "sy", t, expr); | |
| 310 | let sz_ast = compile_channel_expr(comp, node, &["SpinZExpression"], "sz", t, expr); | |
| 311 | let r_ast = compile_channel_expr(comp, node, &["RedExpression"], "r", t, expr); | |
| 312 | let g_ast = compile_channel_expr(comp, node, &["GreenExpression"], "g", t, expr); | |
| 313 | let b_ast = compile_channel_expr(comp, node, &["BlueExpression"], "b", t, expr); | |
| 314 | let a_ast = compile_channel_expr(comp, node, &["AlphaExpression"], "a", t, expr); | |
| 315 | let size_ast = compile_channel_expr(comp, node, &["SizeExpression"], "size", t, expr); | |
| 316 | let life_ast = compile_channel_expr(comp, node, &["LifeSpanExpression", "LifespanExpression"], "lifespan", t, expr); | |
| 317 | let mass_ast = compile_channel_expr(comp, node, &["MassExpression"], "mass", t, expr); | |
| 318 | let user_ast = compile_channel_expr(comp, node, &["UserExpression"], "user", t, expr); | |
| 319 | let kill_ast = compile_channel_expr(comp, node, &["KillExpressionKillIf10", "KillExpression"], "0", t, expr); | |
| 320 | ||
| 321 | if [ | |
| 322 | &px_ast, &py_ast, &pz_ast, &vx_ast, &vy_ast, &vz_ast, &rx_ast, &ry_ast, &rz_ast, | |
| 323 | &sx_ast, &sy_ast, &sz_ast, &r_ast, &g_ast, &b_ast, &a_ast, &size_ast, &life_ast, | |
| 324 | &mass_ast, &user_ast, &kill_ast, | |
| 325 | ] | |
| 326 | .iter() | |
| 327 | .all(|o| o.is_none()) | |
| 328 | { | |
| 329 | return; | |
| 330 | } | |
| 331 | ||
| 332 | let (n, pt, setups, inters) = read_common_inputs(comp, node, t, expr); | |
| 333 | let filter = ModifierFilter::from_node(comp, node, t, expr); | |
| 334 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | |
| 335 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | |
| 336 | ||
| 337 | for p in particles.iter_mut() { | |
| 338 | if !filter.matches(p, scope, &mut rng) { | |
| 339 | continue; | |
| 340 | } | |
| 341 | let mut ctx = EvalCtx { | |
| 342 | p, | |
| 343 | time: t, | |
| 344 | seed, | |
| 345 | n, | |
| 346 | pt, | |
| 347 | s: [0.0; 4], | |
| 348 | i: [0.0; 8], | |
| 349 | img, | |
| 350 | }; | |
| 351 | for idx in 0..4 { | |
| 352 | if let Some(ref ast) = setups[idx] { | |
| 353 | ctx.s[idx] = eval_ast(ast, &ctx); | |
| 354 | } | |
| 355 | } | |
| 356 | for idx in 0..8 { | |
| 357 | if let Some(ref ast) = inters[idx] { | |
| 358 | ctx.i[idx] = eval_ast(ast, &ctx); | |
| 359 | } | |
| 360 | } | |
| 361 | let new_px = px_ast.as_ref().map_or(p.pos[0], |e| eval_ast(e, &ctx)); | |
| 362 | let new_py = py_ast.as_ref().map_or(p.pos[1], |e| eval_ast(e, &ctx)); | |
| 363 | let new_pz = pz_ast.as_ref().map_or(p.pos[2], |e| eval_ast(e, &ctx)); | |
| 364 | let new_vx = vx_ast.as_ref().map_or(p.vel[0], |e| eval_ast(e, &ctx)); | |
| 365 | let new_vy = vy_ast.as_ref().map_or(p.vel[1], |e| eval_ast(e, &ctx)); | |
| 366 | let new_vz = vz_ast.as_ref().map_or(p.vel[2], |e| eval_ast(e, &ctx)); | |
| 367 | let new_rx = rx_ast.as_ref().map_or(p.rot_xy[0], |e| eval_ast(e, &ctx)); | |
| 368 | let new_ry = ry_ast.as_ref().map_or(p.rot_xy[1], |e| eval_ast(e, &ctx)); | |
| 369 | let new_rz = rz_ast.as_ref().map_or(p.rot_z, |e| eval_ast(e, &ctx)); | |
| 370 | let new_sx = sx_ast.as_ref().map_or(p.spin_xy[0], |e| eval_ast(e, &ctx)); | |
| 371 | let new_sy = sy_ast.as_ref().map_or(p.spin_xy[1], |e| eval_ast(e, &ctx)); | |
| 372 | let new_sz = sz_ast.as_ref().map_or(p.spin_z, |e| eval_ast(e, &ctx)); | |
| 373 | let new_r = r_ast.as_ref().map_or(p.color[0], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); | |
| 374 | let new_g = g_ast.as_ref().map_or(p.color[1], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); | |
| 375 | let new_b = b_ast.as_ref().map_or(p.color[2], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); | |
| 376 | let new_a = a_ast.as_ref().map_or(p.color[3], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); | |
| 377 | let new_size = size_ast.as_ref().map_or(p.size, |e| eval_ast(e, &ctx).max(0.0)); | |
| 378 | let new_life = life_ast.as_ref().map_or(p.lifespan, |e| eval_ast(e, &ctx).max(1.0)); | |
| 379 | let new_mass = mass_ast.as_ref().map_or(p.mass, |e| eval_ast(e, &ctx)); | |
| 380 | let new_user = user_ast.as_ref().map_or(p.user, |e| eval_ast(e, &ctx)); | |
| 381 | let kill = kill_ast.as_ref().is_some_and(|e| eval_ast(e, &ctx) > 0.5); | |
| 382 | ||
| 383 | p.pos = [new_px, new_py, new_pz]; | |
| 384 | p.vel = [new_vx, new_vy, new_vz]; | |
| 385 | p.rot_xy = [new_rx, new_ry]; | |
| 386 | p.rot_z = new_rz; | |
| 387 | p.spin_xy = [new_sx, new_sy]; | |
| 388 | p.spin_z = new_sz; | |
| 389 | p.color = [new_r, new_g, new_b, new_a]; | |
| 390 | p.size = new_size; | |
| 391 | p.lifespan = new_life; | |
| 392 | p.mass = new_mass; | |
| 393 | p.user = new_user; | |
| 394 | if kill { | |
| 395 | p.alive = false; | |
| 396 | } | |
| 397 | } | |
| 398 | } | |
| 399 | ||
| 400 | /// Applies `pCustomForce` per-particle acceleration/torque expressions each substep. | |
| 401 | pub(super) fn apply_custom_force( | |
| 402 | particles: &mut [Particle], | |
| 403 | comp: &Comp, | |
| 404 | node: &Node, | |
| 405 | scope: &HashSet<u64>, | |
| 406 | img: Option<&SpriteImage>, | |
| 407 | t: f64, | |
| 408 | expr: &ExprEngine, | |
| 409 | ) { | |
| 410 | let fx_ast = compile_channel_expr(comp, node, &["ForceXExpression"], "0", t, expr); | |
| 411 | let fy_ast = compile_channel_expr(comp, node, &["ForceYExpression"], "0", t, expr); | |
| 412 | let fz_ast = compile_channel_expr(comp, node, &["ForceZExpression"], "0", t, expr); | |
| 413 | let tx_ast = compile_channel_expr(comp, node, &["TorqueXExpression"], "0", t, expr); | |
| 414 | let ty_ast = compile_channel_expr(comp, node, &["TorqueYExpression"], "0", t, expr); | |
| 415 | let tz_ast = compile_channel_expr(comp, node, &["TorqueZExpression"], "0", t, expr); | |
| 416 | if [&fx_ast, &fy_ast, &fz_ast, &tx_ast, &ty_ast, &tz_ast] | |
| 417 | .iter() | |
| 418 | .all(|o| o.is_none()) | |
| 419 | { | |
| 420 | return; | |
| 421 | } | |
| 422 | ||
| 423 | let (n, pt, setups, inters) = read_common_inputs(comp, node, t, expr); | |
| 424 | let filter = ModifierFilter::from_node(comp, node, t, expr); | |
| 425 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | |
| 426 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | |
| 427 | let force_scale = VELOCITY_SCALE * VELOCITY_SCALE; | |
| 428 | ||
| 429 | for p in particles.iter_mut() { | |
| 430 | if !filter.matches(p, scope, &mut rng) { | |
| 431 | continue; | |
| 432 | } | |
| 433 | let mut ctx = EvalCtx { | |
| 434 | p, | |
| 435 | time: t, | |
| 436 | seed, | |
| 437 | n, | |
| 438 | pt, | |
| 439 | s: [0.0; 4], | |
| 440 | i: [0.0; 8], | |
| 441 | img, | |
| 442 | }; | |
| 443 | for idx in 0..4 { | |
| 444 | if let Some(ref ast) = setups[idx] { | |
| 445 | ctx.s[idx] = eval_ast(ast, &ctx); | |
| 446 | } | |
| 447 | } | |
| 448 | for idx in 0..8 { | |
| 449 | if let Some(ref ast) = inters[idx] { | |
| 450 | ctx.i[idx] = eval_ast(ast, &ctx); | |
| 451 | } | |
| 452 | } | |
| 453 | let inv_m = if p.mass.abs() > 1e-6 { 1.0 / p.mass } else { 1.0 }; | |
| 454 | let dfx = fx_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * force_scale * inv_m); | |
| 455 | let dfy = fy_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * force_scale * inv_m); | |
| 456 | let dfz = fz_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * force_scale * inv_m); | |
| 457 | let dtx = tx_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * inv_m); | |
| 458 | let dty = ty_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * inv_m); | |
| 459 | let dtz = tz_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * inv_m); | |
| 460 | p.vel[0] += dfx; | |
| 461 | p.vel[1] += dfy; | |
| 462 | p.vel[2] += dfz; | |
| 463 | p.spin_xy[0] += dtx; | |
| 464 | p.spin_xy[1] += dty; | |
| 465 | p.spin_z += dtz; | |
| 466 | } | |
| 467 | } |
crates/engine/src/particles/extra_forces.rs created+595| ... | ... | @@ -0,0 +1,595 @@ |
| 1 | //! Additional Fusion particle operators: | |
| 2 | //! - `pAvoid`: repulsive obstacle-avoidance steering force around a region surface | |
| 3 | //! - `pFollow`: spring-damper target follow and boids leader-follower steering | |
| 4 | //! - `pTangentForce`: orbital tangential cross-product force (`S x (p - center)`) | |
| 5 | //! - `pImageEmitter`: emits particles sampled from an input image's RGBA pixels | |
| 6 | ||
| 7 | use std::collections::{HashMap, HashSet}; | |
| 8 | ||
| 9 | use model::{Comp, ExprEngine, Node, NodeId}; | |
| 10 | ||
| 11 | use super::forces::{ModifierFilter, eval_first_num, read_sets_mask}; | |
| 12 | use super::sim::RegionSpec; | |
| 13 | use super::{ | |
| 14 | MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, SpriteImage, VELOCITY_SCALE, | |
| 15 | }; | |
| 16 | ||
| 17 | /// `pAvoid`: repels particles smoothly away from the obstacle `Region` within `Distance`. | |
| 18 | pub(super) fn apply_avoid( | |
| 19 | particles: &mut [Particle], | |
| 20 | comp: &Comp, | |
| 21 | node: &Node, | |
| 22 | scope: &HashSet<u64>, | |
| 23 | t: f64, | |
| 24 | expr: &ExprEngine, | |
| 25 | ) { | |
| 26 | let strength = comp.eval_number(node, "Strength", t, 0.1, expr); | |
| 27 | let dist_limit = comp.eval_number(node, "Distance", t, 0.1, expr).max(0.0); | |
| 28 | if strength.abs() < 1e-12 || dist_limit <= 1e-9 { | |
| 29 | return; | |
| 30 | } | |
| 31 | ||
| 32 | let filter = ModifierFilter::from_node_ignore_region(comp, node, t, expr); | |
| 33 | // Fusion's pAvoid defaults Region to LineRgn ((0,0,0)..(0,0,0)). | |
| 34 | let obstacle = RegionSpec::from_node_with_default(comp, node, t, expr, "LineRgn"); | |
| 35 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | |
| 36 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | |
| 37 | let force_mag = strength * VELOCITY_SCALE * VELOCITY_SCALE; | |
| 38 | ||
| 39 | for p in particles.iter_mut() { | |
| 40 | if !filter.matches(p, scope, &mut rng) { | |
| 41 | continue; | |
| 42 | } | |
| 43 | let Some((dist, dir)) = avoid_surface_vector(&obstacle, p.pos, p.id) else { | |
| 44 | continue; | |
| 45 | }; | |
| 46 | if dist >= dist_limit { | |
| 47 | continue; | |
| 48 | } | |
| 49 | let falloff = if dist <= 0.0 { | |
| 50 | 1.0 | |
| 51 | } else { | |
| 52 | 1.0 - dist / dist_limit | |
| 53 | }; | |
| 54 | let push = force_mag * falloff; | |
| 55 | p.vel[0] += dir[0] * push; | |
| 56 | p.vel[1] += dir[1] * push; | |
| 57 | p.vel[2] += dir[2] * push; | |
| 58 | } | |
| 59 | } | |
| 60 | ||
| 61 | fn avoid_surface_vector(region: &RegionSpec, p: [f64; 3], id: u32) -> Option<(f64, [f64; 3])> { | |
| 62 | let normalize_or_fallback = |dx: f64, dy: f64, dz: f64| -> (f64, [f64; 3]) { | |
| 63 | let len = (dx * dx + dy * dy + dz * dz).sqrt(); | |
| 64 | if len > 1e-9 { | |
| 65 | (len, [dx / len, dy / len, dz / len]) | |
| 66 | } else { | |
| 67 | let ang = (id as f64) * 2.399963229728653; | |
| 68 | (0.0, [ang.cos(), ang.sin(), 0.0]) | |
| 69 | } | |
| 70 | }; | |
| 71 | ||
| 72 | match *region { | |
| 73 | RegionSpec::Point { center } => { | |
| 74 | Some(normalize_or_fallback(p[0] - center[0], p[1] - center[1], p[2] - center[2])) | |
| 75 | } | |
| 76 | RegionSpec::Sphere { center, radius } => { | |
| 77 | let (d, dir) = | |
| 78 | normalize_or_fallback(p[0] - center[0], p[1] - center[1], p[2] - center[2]); | |
| 79 | Some(((d - radius).max(0.0), dir)) | |
| 80 | } | |
| 81 | RegionSpec::Line { start, end } => { | |
| 82 | let abx = end[0] - start[0]; | |
| 83 | let aby = end[1] - start[1]; | |
| 84 | let abz = end[2] - start[2]; | |
| 85 | let ab2 = abx * abx + aby * aby + abz * abz; | |
| 86 | let s = if ab2 > 1e-12 { | |
| 87 | (((p[0] - start[0]) * abx + (p[1] - start[1]) * aby + (p[2] - start[2]) * abz) | |
| 88 | / ab2) | |
| 89 | .clamp(0.0, 1.0) | |
| 90 | } else { | |
| 91 | 0.0 | |
| 92 | }; | |
| 93 | let qx = start[0] + abx * s; | |
| 94 | let qy = start[1] + aby * s; | |
| 95 | let qz = start[2] + abz * s; | |
| 96 | Some(normalize_or_fallback(p[0] - qx, p[1] - qy, p[2] - qz)) | |
| 97 | } | |
| 98 | RegionSpec::Rect { | |
| 99 | center, | |
| 100 | width, | |
| 101 | height, | |
| 102 | } => { | |
| 103 | let hw = width * 0.5; | |
| 104 | let hh = height * 0.5; | |
| 105 | let rx = p[0] - center[0]; | |
| 106 | let ry = p[1] - center[1]; | |
| 107 | let dx = (rx.abs() - hw).max(0.0) * rx.signum(); | |
| 108 | let dy = (ry.abs() - hh).max(0.0) * ry.signum(); | |
| 109 | let dz = p[2] - center[2]; | |
| 110 | if dx.abs() > 1e-9 || dy.abs() > 1e-9 || dz.abs() > 1e-9 { | |
| 111 | Some(normalize_or_fallback(dx, dy, dz)) | |
| 112 | } else { | |
| 113 | let px = hw - rx.abs(); | |
| 114 | let py = hh - ry.abs(); | |
| 115 | if px <= py { | |
| 116 | Some((0.0, [if rx >= 0.0 { 1.0 } else { -1.0 }, 0.0, 0.0])) | |
| 117 | } else { | |
| 118 | Some((0.0, [0.0, if ry >= 0.0 { 1.0 } else { -1.0 }, 0.0])) | |
| 119 | } | |
| 120 | } | |
| 121 | } | |
| 122 | RegionSpec::Cube { | |
| 123 | center, | |
| 124 | width, | |
| 125 | height, | |
| 126 | depth, | |
| 127 | } => { | |
| 128 | let hw = width * 0.5; | |
| 129 | let hh = height * 0.5; | |
| 130 | let hd = depth * 0.5; | |
| 131 | let rx = p[0] - center[0]; | |
| 132 | let ry = p[1] - center[1]; | |
| 133 | let rz = p[2] - center[2]; | |
| 134 | let dx = (rx.abs() - hw).max(0.0) * rx.signum(); | |
| 135 | let dy = (ry.abs() - hh).max(0.0) * ry.signum(); | |
| 136 | let dz = (rz.abs() - hd).max(0.0) * rz.signum(); | |
| 137 | if dx.abs() > 1e-9 || dy.abs() > 1e-9 || dz.abs() > 1e-9 { | |
| 138 | Some(normalize_or_fallback(dx, dy, dz)) | |
| 139 | } else { | |
| 140 | let px = hw - rx.abs(); | |
| 141 | let py = hh - ry.abs(); | |
| 142 | let pz = hd - rz.abs(); | |
| 143 | if px <= py && px <= pz { | |
| 144 | Some((0.0, [if rx >= 0.0 { 1.0 } else { -1.0 }, 0.0, 0.0])) | |
| 145 | } else if py <= pz { | |
| 146 | Some((0.0, [0.0, if ry >= 0.0 { 1.0 } else { -1.0 }, 0.0])) | |
| 147 | } else { | |
| 148 | Some((0.0, [0.0, 0.0, if rz >= 0.0 { 1.0 } else { -1.0 }])) | |
| 149 | } | |
| 150 | } | |
| 151 | } | |
| 152 | RegionSpec::All => None, | |
| 153 | } | |
| 154 | } | |
| 155 | ||
| 156 | /// `pFollow`: supports Fusion's spring-damper target follow (`Position` + `Spring` + `Damping`) | |
| 157 | /// and leader/neighbor follower steering (`FollowSet` / `AffectSet` / `Strength` / `Distance`). | |
| 158 | pub(super) fn apply_follow( | |
| 159 | particles: &mut [Particle], | |
| 160 | comp: &Comp, | |
| 161 | node: &Node, | |
| 162 | scope: &HashSet<u64>, | |
| 163 | t: f64, | |
| 164 | expr: &ExprEngine, | |
| 165 | ) { | |
| 166 | let has_neighbor_inputs = node.inputs.contains_key("FollowSet") | |
| 167 | || node.inputs.contains_key("AffectSet") | |
| 168 | || (node.inputs.contains_key("Strength") && !node.inputs.contains_key("Spring")); | |
| 169 | ||
| 170 | if has_neighbor_inputs { | |
| 171 | apply_follow_neighbors(particles, comp, node, scope, t, expr); | |
| 172 | } else { | |
| 173 | apply_follow_spring(particles, comp, node, scope, t, expr); | |
| 174 | } | |
| 175 | } | |
| 176 | ||
| 177 | fn apply_follow_spring( | |
| 178 | particles: &mut [Particle], | |
| 179 | comp: &Comp, | |
| 180 | node: &Node, | |
| 181 | scope: &HashSet<u64>, | |
| 182 | t: f64, | |
| 183 | expr: &ExprEngine, | |
| 184 | ) { | |
| 185 | let spring = comp.eval_number(node, "Spring", t, 1.0, expr); | |
| 186 | let damping = comp.eval_number(node, "Damping", t, 0.1, expr).max(0.0); | |
| 187 | if spring.abs() < 1e-12 && damping.abs() < 1e-12 { | |
| 188 | return; | |
| 189 | } | |
| 190 | ||
| 191 | let pos_pt = if node.inputs.contains_key("Position") { | |
| 192 | comp.eval_point(node, "Position", t, [0.0, 0.0], expr) | |
| 193 | } else { | |
| 194 | [0.0, 0.0] | |
| 195 | }; | |
| 196 | let tx = eval_first_num(comp, node, &["Position.X", "Center.X"], t, pos_pt[0], expr); | |
| 197 | let ty = eval_first_num(comp, node, &["Position.Y", "Center.Y"], t, pos_pt[1], expr); | |
| 198 | let tz = eval_first_num(comp, node, &["Position.Z", "Center.Z"], t, 0.0, expr); | |
| 199 | ||
| 200 | let filter = ModifierFilter::from_node(comp, node, t, expr); | |
| 201 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | |
| 202 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | |
| 203 | let k = spring * VELOCITY_SCALE * VELOCITY_SCALE; | |
| 204 | let damp_factor = (1.0 - (damping * 0.1).clamp(0.0, 0.99)).clamp(0.01, 1.0); | |
| 205 | ||
| 206 | for p in particles.iter_mut() { | |
| 207 | if !filter.matches(p, scope, &mut rng) { | |
| 208 | continue; | |
| 209 | } | |
| 210 | p.vel[0] = p.vel[0] * damp_factor + (tx - p.pos[0]) * k; | |
| 211 | p.vel[1] = p.vel[1] * damp_factor + (ty - p.pos[1]) * k; | |
| 212 | p.vel[2] = p.vel[2] * damp_factor + (tz - p.pos[2]) * k; | |
| 213 | } | |
| 214 | } | |
| 215 | ||
| 216 | fn parse_set_arg(comp: &Comp, node: &Node, key: &str, t: f64, expr: &ExprEngine) -> Option<u32> { | |
| 217 | if let Some(s) = node.static_str(key) { | |
| 218 | if let Some(rest) = s.strip_prefix("Set") { | |
| 219 | if let Ok(idx) = rest.parse::<u32>() { | |
| 220 | if (1..=32).contains(&idx) { | |
| 221 | return Some(1u32 << (idx - 1)); | |
| 222 | } | |
| 223 | } | |
| 224 | } | |
| 225 | } | |
| 226 | if node.inputs.contains_key(key) { | |
| 227 | let idx = comp.eval_number(node, key, t, 1.0, expr).round() as i32; | |
| 228 | if (1..=32).contains(&idx) { | |
| 229 | return Some(1u32 << (idx - 1)); | |
| 230 | } | |
| 231 | } | |
| 232 | None | |
| 233 | } | |
| 234 | ||
| 235 | fn apply_follow_neighbors( | |
| 236 | particles: &mut [Particle], | |
| 237 | comp: &Comp, | |
| 238 | node: &Node, | |
| 239 | scope: &HashSet<u64>, | |
| 240 | t: f64, | |
| 241 | expr: &ExprEngine, | |
| 242 | ) { | |
| 243 | let strength = comp.eval_number(node, "Strength", t, 0.5, expr); | |
| 244 | if strength.abs() < 1e-12 || particles.is_empty() { | |
| 245 | return; | |
| 246 | } | |
| 247 | let distance = comp.eval_number(node, "Distance", t, 0.25, expr).max(0.0); | |
| 248 | let follow_mask = parse_set_arg(comp, node, "FollowSet", t, expr); | |
| 249 | let affect_mask = parse_set_arg(comp, node, "AffectSet", t, expr); | |
| 250 | ||
| 251 | let filter = ModifierFilter::from_node(comp, node, t, expr); | |
| 252 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | |
| 253 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | |
| 254 | ||
| 255 | let leaders: Vec<([f64; 3], [f64; 3])> = particles | |
| 256 | .iter() | |
| 257 | .filter(|p| { | |
| 258 | p.alive | |
| 259 | && scope.contains(&p.emitter_hash) | |
| 260 | && follow_mask.is_none_or(|m| (p.sets & m) != 0) | |
| 261 | }) | |
| 262 | .map(|p| (p.pos, p.vel)) | |
| 263 | .collect(); | |
| 264 | if leaders.is_empty() { | |
| 265 | return; | |
| 266 | } | |
| 267 | ||
| 268 | let dist_sq = if distance > 1e-9 { | |
| 269 | distance * distance | |
| 270 | } else { | |
| 271 | f64::INFINITY | |
| 272 | }; | |
| 273 | let accel = strength * VELOCITY_SCALE * VELOCITY_SCALE; | |
| 274 | ||
| 275 | let mut deltas = vec![[0.0_f64; 3]; particles.len()]; | |
| 276 | for (idx, p) in particles.iter().enumerate() { | |
| 277 | if !filter.matches(p, scope, &mut rng) { | |
| 278 | continue; | |
| 279 | } | |
| 280 | if let Some(m) = affect_mask { | |
| 281 | if (p.sets & m) == 0 { | |
| 282 | continue; | |
| 283 | } | |
| 284 | } | |
| 285 | let mut sum_pos = [0.0_f64; 3]; | |
| 286 | let mut sum_vel = [0.0_f64; 3]; | |
| 287 | let mut count = 0usize; | |
| 288 | for &(lp, lv) in &leaders { | |
| 289 | let dx = lp[0] - p.pos[0]; | |
| 290 | let dy = lp[1] - p.pos[1]; | |
| 291 | let dz = lp[2] - p.pos[2]; | |
| 292 | let d2 = dx * dx + dy * dy + dz * dz; | |
| 293 | if d2 <= 1e-12 || d2 > dist_sq { | |
| 294 | continue; | |
| 295 | } | |
| 296 | sum_pos[0] += dx; | |
| 297 | sum_pos[1] += dy; | |
| 298 | sum_pos[2] += dz; | |
| 299 | sum_vel[0] += lv[0] - p.vel[0]; | |
| 300 | sum_vel[1] += lv[1] - p.vel[1]; | |
| 301 | sum_vel[2] += lv[2] - p.vel[2]; | |
| 302 | count += 1; | |
| 303 | } | |
| 304 | if count > 0 { | |
| 305 | let inv = 1.0 / count as f64; | |
| 306 | deltas[idx] = [ | |
| 307 | sum_pos[0] * inv * accel + sum_vel[0] * inv * (accel * 2.0).min(0.25), | |
| 308 | sum_pos[1] * inv * accel + sum_vel[1] * inv * (accel * 2.0).min(0.25), | |
| 309 | sum_pos[2] * inv * accel + sum_vel[2] * inv * (accel * 2.0).min(0.25), | |
| 310 | ]; | |
| 311 | } | |
| 312 | } | |
| 313 | ||
| 314 | for (p, dv) in particles.iter_mut().zip(deltas) { | |
| 315 | p.vel[0] += dv[0]; | |
| 316 | p.vel[1] += dv[1]; | |
| 317 | p.vel[2] += dv[2]; | |
| 318 | } | |
| 319 | } | |
| 320 | ||
| 321 | /// `pTangentForce`: orbital tangential force around `Translate` / `Center` via `S x (p - center)`. | |
| 322 | pub(super) fn apply_tangent_force( | |
| 323 | particles: &mut [Particle], | |
| 324 | comp: &Comp, | |
| 325 | node: &Node, | |
| 326 | scope: &HashSet<u64>, | |
| 327 | t: f64, | |
| 328 | expr: &ExprEngine, | |
| 329 | ) { | |
| 330 | let center_pt = if node.inputs.contains_key("Center") { | |
| 331 | comp.eval_point(node, "Center", t, [0.0, 0.0], expr) | |
| 332 | } else { | |
| 333 | [0.0, 0.0] | |
| 334 | }; | |
| 335 | let cx = eval_first_num(comp, node, &["Translate.X", "Center.X"], t, center_pt[0], expr); | |
| 336 | let cy = eval_first_num(comp, node, &["Translate.Y", "Center.Y"], t, center_pt[1], expr); | |
| 337 | let cz = eval_first_num(comp, node, &["Translate.Z", "Center.Z"], t, 0.0, expr); | |
| 338 | ||
| 339 | let (sx, sy, sz) = if node.inputs.contains_key("XStrength") | |
| 340 | || node.inputs.contains_key("YStrength") | |
| 341 | || node.inputs.contains_key("ZStrength") | |
| 342 | { | |
| 343 | ( | |
| 344 | comp.eval_number(node, "XStrength", t, 0.0, expr), | |
| 345 | comp.eval_number(node, "YStrength", t, 0.0, expr), | |
| 346 | comp.eval_number(node, "ZStrength", t, 0.1, expr), | |
| 347 | ) | |
| 348 | } else if node.inputs.contains_key("Strength") || node.inputs.contains_key("Axis") { | |
| 349 | let s = comp.eval_number(node, "Strength", t, 0.1, expr); | |
| 350 | let axis_idx = match node.static_str("Axis") { | |
| 351 | Some("X" | "x") => 0, | |
| 352 | Some("Y" | "y") => 1, | |
| 353 | Some("Z" | "z") => 2, | |
| 354 | _ => comp.eval_number(node, "Axis", t, 2.0, expr).round() as i32, | |
| 355 | }; | |
| 356 | match axis_idx { | |
| 357 | 0 => (s, 0.0, 0.0), | |
| 358 | 1 => (0.0, s, 0.0), | |
| 359 | _ => (0.0, 0.0, s), | |
| 360 | } | |
| 361 | } else { | |
| 362 | (0.0, 0.0, 0.1) | |
| 363 | }; | |
| 364 | ||
| 365 | if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 { | |
| 366 | return; | |
| 367 | } | |
| 368 | ||
| 369 | let filter = ModifierFilter::from_node(comp, node, t, expr); | |
| 370 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | |
| 371 | let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); | |
| 372 | let scale = POINT_FORCE_SCALE.max(VELOCITY_SCALE * VELOCITY_SCALE * 0.2); | |
| 373 | ||
| 374 | for p in particles.iter_mut() { | |
| 375 | if !filter.matches(p, scope, &mut rng) { | |
| 376 | continue; | |
| 377 | } | |
| 378 | let rx = p.pos[0] - cx; | |
| 379 | let ry = p.pos[1] - cy; | |
| 380 | let rz = p.pos[2] - cz; | |
| 381 | // Cross product S x r gives orbital tangent acceleration around center. | |
| 382 | let fx = (sy * rz - sz * ry) * scale; | |
| 383 | let fy = (sz * rx - sx * rz) * scale; | |
| 384 | let fz = (sx * ry - sy * rx) * scale; | |
| 385 | p.vel[0] += fx; | |
| 386 | p.vel[1] += fy; | |
| 387 | p.vel[2] += fz; | |
| 388 | } | |
| 389 | } | |
| 390 | ||
| 391 | /// `pImageEmitter`: emits particles distributed across the sampled RGBA pixels of its `Input` image. | |
| 392 | #[allow(clippy::too_many_arguments)] | |
| 393 | pub(super) fn emit_image_particles( | |
| 394 | state: &mut SimState, | |
| 395 | comp: &Comp, | |
| 396 | node: &Node, | |
| 397 | emitter_id: NodeId, | |
| 398 | emitter_hash: u64, | |
| 399 | sprites: &HashMap<NodeId, SpriteImage>, | |
| 400 | frame: i64, | |
| 401 | sim_start: i64, | |
| 402 | t: f64, | |
| 403 | expr: &ExprEngine, | |
| 404 | ) { | |
| 405 | let every_frame = comp.eval_number(node, "CreateParticlesEveryFrame", t, 0.0, expr) > 0.5; | |
| 406 | if !every_frame && frame != sim_start { | |
| 407 | return; | |
| 408 | } | |
| 409 | let Some(sprite) = sprites.get(&emitter_id) else { | |
| 410 | return; | |
| 411 | }; | |
| 412 | let sw = sprite.size[0] as usize; | |
| 413 | let sh = sprite.size[1] as usize; | |
| 414 | if sw == 0 || sh == 0 || sprite.rgba.len() < sw.saturating_mul(sh).saturating_mul(4) { | |
| 415 | return; | |
| 416 | } | |
| 417 | ||
| 418 | let x_density = comp.eval_number(node, "XDensity", t, 1.0, expr).clamp(0.0, 8.0); | |
| 419 | let y_density = comp.eval_number(node, "YDensity", t, 1.0, expr).clamp(0.0, 8.0); | |
| 420 | if x_density <= 1e-6 || y_density <= 1e-6 { | |
| 421 | return; | |
| 422 | } | |
| 423 | let alpha_thresh = comp.eval_number(node, "AlphaThreshold", t, 0.0, expr).clamp(0.0, 1.0); | |
| 424 | let use_style_color = matches!(node.static_str("ColorMode"), Some("UseStyle" | "Style")) | |
| 425 | || (node.inputs.contains_key("ColorMode") | |
| 426 | && comp.eval_number(node, "ColorMode", t, 0.0, expr).round() as i32 == 1); | |
| 427 | ||
| 428 | let remaining = MAX_PARTICLES.saturating_sub(state.particles.len()); | |
| 429 | if remaining == 0 { | |
| 430 | return; | |
| 431 | } | |
| 432 | ||
| 433 | let mut nx = ((sw as f64) * x_density).round().max(1.0) as usize; | |
| 434 | let mut ny = ((sh as f64) * y_density).round().max(1.0) as usize; | |
| 435 | if nx.saturating_mul(ny) > remaining { | |
| 436 | let scale = (remaining as f64 / (nx * ny) as f64).sqrt(); | |
| 437 | nx = ((nx as f64) * scale).floor().max(1.0) as usize; | |
| 438 | ny = (remaining / nx).max(1); | |
| 439 | } | |
| 440 | ||
| 441 | let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; | |
| 442 | let mut rng = SplitMix64::from_parts(seed, frame, &node.name); | |
| 443 | ||
| 444 | let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0); | |
| 445 | let lifespan_var = comp | |
| 446 | .eval_number(node, "LifespanVariance", t, 0.0, expr) | |
| 447 | .max(0.0); | |
| 448 | let pos_var = comp | |
| 449 | .eval_number(node, "PositionVariance", t, 0.0, expr) | |
| 450 | .max(0.0); | |
| 451 | let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr); | |
| 452 | let vel_var = comp | |
| 453 | .eval_number(node, "VelocityVariance", t, 0.0, expr) | |
| 454 | .max(0.0); | |
| 455 | let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr); | |
| 456 | let angle_var = comp | |
| 457 | .eval_number(node, "AngleVariance", t, 0.0, expr) | |
| 458 | .max(0.0); | |
| 459 | let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr); | |
| 460 | let angle_z_var = comp | |
| 461 | .eval_number(node, "AngleZVariance", t, 0.0, expr) | |
| 462 | .max(0.0); | |
| 463 | ||
| 464 | let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr); | |
| 465 | let rot_z_var = comp | |
| 466 | .eval_number(node, "RotationZVariance", t, 0.0, expr) | |
| 467 | .max(0.0); | |
| 468 | let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr); | |
| 469 | let spin_z_var = comp | |
| 470 | .eval_number(node, "SpinZVariance", t, 0.0, expr) | |
| 471 | .max(0.0); | |
| 472 | ||
| 473 | let style_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr) as f32; | |
| 474 | let style_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr) as f32; | |
| 475 | let style_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr) as f32; | |
| 476 | let style_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr) as f32; | |
| 477 | let size_base = comp | |
| 478 | .eval_number(node, "ParticleStyle.Size", t, 0.1, expr) | |
| 479 | .max(0.0); | |
| 480 | let size_var = comp | |
| 481 | .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr) | |
| 482 | .max(0.0); | |
| 483 | ||
| 484 | let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr); | |
| 485 | let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr); | |
| 486 | let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr); | |
| 487 | let sx = comp.eval_number(node, "Transform3DOp.Scale.X", t, 1.0, expr); | |
| 488 | let sy = if comp.eval_number(node, "Transform3DOp.ScaleLock", t, 1.0, expr) > 0.5 | |
| 489 | && !node.inputs.contains_key("Transform3DOp.Scale.Y") | |
| 490 | { | |
| 491 | sx | |
| 492 | } else { | |
| 493 | comp.eval_number(node, "Transform3DOp.Scale.Y", t, 1.0, expr) | |
| 494 | }; | |
| 495 | let rz_deg = comp.eval_number(node, "Transform3DOp.Rotate.Z", t, 0.0, expr); | |
| 496 | let (sin_rz, cos_rz) = rz_deg.to_radians().sin_cos(); | |
| 497 | ||
| 498 | let region = if node.static_str("Region").is_some() { | |
| 499 | RegionSpec::from_node(comp, node, t, expr) | |
| 500 | } else { | |
| 501 | RegionSpec::All | |
| 502 | }; | |
| 503 | let emitter_sets = read_sets_mask(comp, node, t, expr).unwrap_or(1u32); | |
| 504 | let aspect = sw as f64 / (sh as f64).max(1.0); | |
| 505 | ||
| 506 | for iy in 0..ny { | |
| 507 | let v = (iy as f64 + 0.5) / ny as f64; | |
| 508 | let py = ((v * sh as f64).floor() as usize).min(sh - 1); | |
| 509 | for ix in 0..nx { | |
| 510 | if state.particles.len() >= MAX_PARTICLES { | |
| 511 | return; | |
| 512 | } | |
| 513 | let u = (ix as f64 + 0.5) / nx as f64; | |
| 514 | let px = ((u * sw as f64).floor() as usize).min(sw - 1); | |
| 515 | let off = (py * sw + px) * 4; | |
| 516 | let pa = sprite.rgba[off + 3] as f64 / 255.0; | |
| 517 | if pa <= alpha_thresh.max(1e-6) { | |
| 518 | continue; | |
| 519 | } | |
| 520 | ||
| 521 | let lx = (u - 0.5) * sx; | |
| 522 | let ly = ((0.5 - v) / aspect) * sy; | |
| 523 | let mut pos = [ | |
| 524 | tx + lx * cos_rz - ly * sin_rz, | |
| 525 | ty + lx * sin_rz + ly * cos_rz, | |
| 526 | tz, | |
| 527 | ]; | |
| 528 | if !region.contains(pos) { | |
| 529 | continue; | |
| 530 | } | |
| 531 | if pos_var > 0.0 { | |
| 532 | pos[0] += rng.signed() * pos_var; | |
| 533 | pos[1] += rng.signed() * pos_var; | |
| 534 | pos[2] += rng.signed() * pos_var; | |
| 535 | } | |
| 536 | ||
| 537 | let color = if use_style_color { | |
| 538 | [ | |
| 539 | style_r.clamp(0.0, 1.0), | |
| 540 | style_g.clamp(0.0, 1.0), | |
| 541 | style_b.clamp(0.0, 1.0), | |
| 542 | style_a.clamp(0.0, 1.0), | |
| 543 | ] | |
| 544 | } else { | |
| 545 | // Sprite readback is premultiplied RGBA8; unpremultiply RGB so particle rasterizer | |
| 546 | // can apply its own FadeIn/FadeOut and ColorOverLife cleanly. | |
| 547 | let inv_a = 1.0 / pa as f32; | |
| 548 | let pr = ((sprite.rgba[off] as f32 / 255.0) * inv_a).clamp(0.0, 1.0); | |
| 549 | let pg = ((sprite.rgba[off + 1] as f32 / 255.0) * inv_a).clamp(0.0, 1.0); | |
| 550 | let pb = ((sprite.rgba[off + 2] as f32 / 255.0) * inv_a).clamp(0.0, 1.0); | |
| 551 | [ | |
| 552 | (pr * style_r).clamp(0.0, 1.0), | |
| 553 | (pg * style_g).clamp(0.0, 1.0), | |
| 554 | (pb * style_b).clamp(0.0, 1.0), | |
| 555 | (pa as f32 * style_a).clamp(0.0, 1.0), | |
| 556 | ] | |
| 557 | }; | |
| 558 | ||
| 559 | let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE; | |
| 560 | let ang = (angle_base + rng.signed() * angle_var).to_radians(); | |
| 561 | let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians(); | |
| 562 | let cos_z = ang_z.cos(); | |
| 563 | let vel = [ | |
| 564 | speed * ang.cos() * cos_z, | |
| 565 | speed * ang.sin() * cos_z, | |
| 566 | speed * ang_z.sin(), | |
| 567 | ]; | |
| 568 | ||
| 569 | let pid = state.next_id; | |
| 570 | state.next_id = state.next_id.wrapping_add(1).max(1); | |
| 571 | ||
| 572 | state.particles.push(Particle { | |
| 573 | emitter_hash, | |
| 574 | id: pid, | |
| 575 | sets: emitter_sets, | |
| 576 | style_override: None, | |
| 577 | ngon_sides_override: 0, | |
| 578 | bitmap_owner_hash: 0, | |
| 579 | pos, | |
| 580 | vel, | |
| 581 | rot_xy: [0.0, 0.0], | |
| 582 | rot_z: rot_z_base + rng.signed() * rot_z_var, | |
| 583 | spin_xy: [0.0, 0.0], | |
| 584 | spin_z: spin_z_base + rng.signed() * spin_z_var, | |
| 585 | age: 0.0, | |
| 586 | lifespan: (lifespan_base + rng.signed() * lifespan_var).max(1.0), | |
| 587 | size: (size_base + rng.signed() * size_var).max(0.0), | |
| 588 | mass: 1.0, | |
| 589 | user: 0.0, | |
| 590 | color, | |
| 591 | alive: true, | |
| 592 | }); | |
| 593 | } | |
| 594 | } | |
| 595 | } |
crates/engine/src/particles/extra_tests.rs created+342| ... | ... | @@ -0,0 +1,342 @@ |
| 1 | //! Unit & end-to-end GPU tests for `pAvoid`, `pCustom`, `pCustomForce`, `pFollow`, | |
| 2 | //! `pImageEmitter`, and `pTangentForce`. | |
| 3 | ||
| 4 | use super::plan::build_particle_plan; | |
| 5 | use super::sim::step_simulation; | |
| 6 | use super::*; | |
| 7 | ||
| 8 | #[test] | |
| 9 | fn test_p_avoid_repels_from_obstacle_region() { | |
| 10 | let comp_src = r#"Composition { | |
| 11 | GlobalRange = { 0, 10 }, | |
| 12 | RenderRange = { 0, 10 }, | |
| 13 | Tools = ordered() { | |
| 14 | EN = BezierSpline { | |
| 15 | KeyFrames = { | |
| 16 | [0] = { 1, Flags = { Linear = true } }, | |
| 17 | [1] = { 0, Flags = { Linear = true } }, | |
| 18 | }, | |
| 19 | }, | |
| 20 | ENear = pEmitter { | |
| 21 | Inputs = { | |
| 22 | Number = Input { SourceOp = "EN", Source = "Value", }, | |
| 23 | Lifespan = Input { Value = 50, }, | |
| 24 | Region = Input { Value = FuID { "Point" }, }, | |
| 25 | ["Point.Translate.X"] = Input { Value = 0.05, }, | |
| 26 | }, | |
| 27 | }, | |
| 28 | EFar = pEmitter { | |
| 29 | Inputs = { | |
| 30 | Number = Input { SourceOp = "EN", Source = "Value", }, | |
| 31 | Lifespan = Input { Value = 50, }, | |
| 32 | Region = Input { Value = FuID { "Point" }, }, | |
| 33 | ["Point.Translate.X"] = Input { Value = 0.40, }, | |
| 34 | }, | |
| 35 | }, | |
| 36 | M = pMerge { | |
| 37 | Inputs = { | |
| 38 | Input1 = Input { SourceOp = "ENear", Source = "Output", }, | |
| 39 | Input2 = Input { SourceOp = "EFar", Source = "Output", }, | |
| 40 | }, | |
| 41 | }, | |
| 42 | Av = pAvoid { | |
| 43 | Inputs = { | |
| 44 | Input = Input { SourceOp = "M", Source = "Output", }, | |
| 45 | Region = Input { Value = FuID { "SphereRgn" }, }, | |
| 46 | ["SphereRgn.Translate.X"] = Input { Value = 0.0, }, | |
| 47 | ["SphereRgn.Size"] = Input { Value = 0.02, }, | |
| 48 | Distance = Input { Value = 0.15, }, | |
| 49 | Strength = Input { Value = 2.0, }, | |
| 50 | }, | |
| 51 | }, | |
| 52 | R = pRender { Inputs = { Input = Input { SourceOp = "Av", Source = "Output", }, }, }, | |
| 53 | }, | |
| 54 | }"#; | |
| 55 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | |
| 56 | let render_id = comp.node_by_name["R"]; | |
| 57 | let plan = build_particle_plan(&comp, render_id); | |
| 58 | let expr = ExprEngine::new(); | |
| 59 | let empty_fields = HashMap::new(); | |
| 60 | let no_sprites = HashMap::new(); | |
| 61 | let mut state = SimState::default(); | |
| 62 | for f in 0..=4 { | |
| 63 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 64 | } | |
| 65 | assert_eq!(state.particles.len(), 2); | |
| 66 | let near = &state.particles[0]; | |
| 67 | let far = &state.particles[1]; | |
| 68 | assert!(near.vel[0] > 0.01 && near.pos[0] > 0.07, "near particle should be repelled +X: {:?}", near); | |
| 69 | assert!(far.vel[0].abs() < 1e-9 && (far.pos[0] - 0.40).abs() < 1e-9, "far particle outside Distance must remain unaffected: {:?}", far); | |
| 70 | } | |
| 71 | ||
| 72 | #[test] | |
| 73 | fn test_p_tangent_force_orbital_velocity() { | |
| 74 | let comp_src = r#"Composition { | |
| 75 | GlobalRange = { 0, 10 }, | |
| 76 | RenderRange = { 0, 10 }, | |
| 77 | Tools = ordered() { | |
| 78 | EN = BezierSpline { | |
| 79 | KeyFrames = { | |
| 80 | [0] = { 1, Flags = { Linear = true } }, | |
| 81 | [1] = { 0, Flags = { Linear = true } }, | |
| 82 | }, | |
| 83 | }, | |
| 84 | E = pEmitter { | |
| 85 | Inputs = { | |
| 86 | Number = Input { SourceOp = "EN", Source = "Value", }, | |
| 87 | Lifespan = Input { Value = 50, }, | |
| 88 | Region = Input { Value = FuID { "Point" }, }, | |
| 89 | ["Point.Translate.X"] = Input { Value = 0.25, }, | |
| 90 | ["Point.Translate.Y"] = Input { Value = 0.0, }, | |
| 91 | }, | |
| 92 | }, | |
| 93 | TF = pTangentForce { | |
| 94 | Inputs = { | |
| 95 | Input = Input { SourceOp = "E", Source = "Output", }, | |
| 96 | ["Translate.X"] = Input { Value = 0.0, }, | |
| 97 | ["Translate.Y"] = Input { Value = 0.0, }, | |
| 98 | ZStrength = Input { Value = 1.0, }, | |
| 99 | }, | |
| 100 | }, | |
| 101 | R = pRender { Inputs = { Input = Input { SourceOp = "TF", Source = "Output", }, }, }, | |
| 102 | }, | |
| 103 | }"#; | |
| 104 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | |
| 105 | let render_id = comp.node_by_name["R"]; | |
| 106 | let plan = build_particle_plan(&comp, render_id); | |
| 107 | let expr = ExprEngine::new(); | |
| 108 | let empty_fields = HashMap::new(); | |
| 109 | let no_sprites = HashMap::new(); | |
| 110 | let mut state = SimState::default(); | |
| 111 | for f in 0..=1 { | |
| 112 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 113 | } | |
| 114 | let p1 = state.particles[0]; | |
| 115 | assert!(p1.vel[1] > 1e-4, "ZStrength > 0 at (+X,0) should produce +Y orbital velocity, got {:?}", p1.vel); | |
| 116 | assert!(p1.vel[0].abs() < 1e-9, "radial X force should be 0 on first tangent impulse, got {}", p1.vel[0]); | |
| 117 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, 2, 0, &expr); | |
| 118 | let p2 = state.particles[0]; | |
| 119 | assert!(p2.vel[0] < 0.0, "second step after moving +Y should deflect velocity inward toward -X, got {:?}", p2.vel); | |
| 120 | } | |
| 121 | ||
| 122 | #[test] | |
| 123 | fn test_p_follow_spring_target_and_leader_sets() { | |
| 124 | // 1. Native Fusion spring-damper follow toward Position. | |
| 125 | let spring_src = r#"Composition { | |
| 126 | GlobalRange = { 0, 10 }, | |
| 127 | RenderRange = { 0, 10 }, | |
| 128 | Tools = ordered() { | |
| 129 | EN = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } }, [1] = { 0, Flags = { Linear = true } } } }, | |
| 130 | E = pEmitter { | |
| 131 | Inputs = { | |
| 132 | Number = Input { SourceOp = "EN", Source = "Value", }, | |
| 133 | Lifespan = Input { Value = 50, }, | |
| 134 | Region = Input { Value = FuID { "Point" }, }, | |
| 135 | ["Point.Translate.X"] = Input { Value = -0.3, }, | |
| 136 | }, | |
| 137 | }, | |
| 138 | Fol = pFollow { | |
| 139 | Inputs = { | |
| 140 | Input = Input { SourceOp = "E", Source = "Output", }, | |
| 141 | ["Position.X"] = Input { Value = 0.3, }, | |
| 142 | ["Position.Y"] = Input { Value = 0.2, }, | |
| 143 | Spring = Input { Value = 2.0, }, | |
| 144 | Damping = Input { Value = 0.2, }, | |
| 145 | }, | |
| 146 | }, | |
| 147 | R = pRender { Inputs = { Input = Input { SourceOp = "Fol", Source = "Output", }, }, }, | |
| 148 | }, | |
| 149 | }"#; | |
| 150 | let comp = Comp::from_fusion_str(spring_src).unwrap(); | |
| 151 | let plan = build_particle_plan(&comp, comp.node_by_name["R"]); | |
| 152 | let expr = ExprEngine::new(); | |
| 153 | let empty_fields = HashMap::new(); | |
| 154 | let no_sprites = HashMap::new(); | |
| 155 | let mut state = SimState::default(); | |
| 156 | for f in 0..=4 { | |
| 157 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 158 | } | |
| 159 | let p = state.particles[0]; | |
| 160 | assert!(p.vel[0] > 0.01 && p.vel[1] > 0.005, "spring target must pull particle toward (0.3, 0.2), got {:?}", p.vel); | |
| 161 | ||
| 162 | // 2. Boids leader-follower mode using FollowSet / AffectSet / Strength / Distance. | |
| 163 | let boids_src = r#"Composition { | |
| 164 | GlobalRange = { 0, 10 }, | |
| 165 | RenderRange = { 0, 10 }, | |
| 166 | Tools = ordered() { | |
| 167 | EN = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } }, [1] = { 0, Flags = { Linear = true } } } }, | |
| 168 | Leader = pEmitter { | |
| 169 | Inputs = { | |
| 170 | Number = Input { SourceOp = "EN", Source = "Value", }, | |
| 171 | Lifespan = Input { Value = 50, }, | |
| 172 | Set1 = Input { Value = 1, }, | |
| 173 | Region = Input { Value = FuID { "Point" }, }, | |
| 174 | ["Point.Translate.X"] = Input { Value = 0.2, }, | |
| 175 | Velocity = Input { Value = 0.0, }, | |
| 176 | }, | |
| 177 | }, | |
| 178 | Follower = pEmitter { | |
| 179 | Inputs = { | |
| 180 | Number = Input { SourceOp = "EN", Source = "Value", }, | |
| 181 | Lifespan = Input { Value = 50, }, | |
| 182 | Set2 = Input { Value = 1, }, | |
| 183 | Region = Input { Value = FuID { "Point" }, }, | |
| 184 | ["Point.Translate.X"] = Input { Value = -0.1, }, | |
| 185 | Velocity = Input { Value = 0.0, }, | |
| 186 | }, | |
| 187 | }, | |
| 188 | M = pMerge { | |
| 189 | Inputs = { | |
| 190 | Input1 = Input { SourceOp = "Leader", Source = "Output", }, | |
| 191 | Input2 = Input { SourceOp = "Follower", Source = "Output", }, | |
| 192 | }, | |
| 193 | }, | |
| 194 | Fol = pFollow { | |
| 195 | Inputs = { | |
| 196 | Input = Input { SourceOp = "M", Source = "Output", }, | |
| 197 | FollowSet = Input { Value = FuID { "Set1" }, }, | |
| 198 | AffectSet = Input { Value = FuID { "Set2" }, }, | |
| 199 | Strength = Input { Value = 3.0, }, | |
| 200 | Distance = Input { Value = 0.5, }, | |
| 201 | }, | |
| 202 | }, | |
| 203 | R = pRender { Inputs = { Input = Input { SourceOp = "Fol", Source = "Output", }, }, }, | |
| 204 | }, | |
| 205 | }"#; | |
| 206 | let bcomp = Comp::from_fusion_str(boids_src).unwrap(); | |
| 207 | let bplan = build_particle_plan(&bcomp, bcomp.node_by_name["R"]); | |
| 208 | let mut bstate = SimState::default(); | |
| 209 | for f in 0..=4 { | |
| 210 | step_simulation(&mut bstate, &bcomp, &bplan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 211 | } | |
| 212 | let leader = bstate.particles.iter().find(|x| (x.sets & 1) != 0).unwrap(); | |
| 213 | let follower = bstate.particles.iter().find(|x| (x.sets & 2) != 0).unwrap(); | |
| 214 | assert!(leader.vel[0].abs() < 1e-9, "leader in Set1 not in AffectSet must stay still"); | |
| 215 | assert!(follower.vel[0] > 0.01 && follower.pos[0] > -0.1, "follower in Set2 must steer toward leader in Set1"); | |
| 216 | } | |
| 217 | ||
| 218 | #[test] | |
| 219 | fn test_p_custom_and_p_custom_force_expressions_and_gpu() { | |
| 220 | let comp_src = r#"Composition { | |
| 221 | GlobalRange = { 0, 10 }, | |
| 222 | RenderRange = { 0, 10 }, | |
| 223 | Tools = ordered() { | |
| 224 | EN = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } }, [1] = { 0, Flags = { Linear = true } } } }, | |
| 225 | E = pEmitter { | |
| 226 | Inputs = { | |
| 227 | Number = Input { SourceOp = "EN", Source = "Value", }, | |
| 228 | Lifespan = Input { Value = 50, }, | |
| 229 | Style = Input { Value = FuID { "ParticleStyleBlob" }, }, | |
| 230 | ["ParticleStyle.Size"] = Input { Value = 0.4, }, | |
| 231 | }, | |
| 232 | }, | |
| 233 | Cust = pCustom { | |
| 234 | Inputs = { | |
| 235 | Input = Input { SourceOp = "E", Source = "Output", }, | |
| 236 | NumberIn1 = Input { Value = 0.25, }, | |
| 237 | ["Position1.X"] = Input { Value = -0.1, }, | |
| 238 | ["Position1.Y"] = Input { Value = 0.05, }, | |
| 239 | Setup1 = Input { Value = "sin(90)", }, | |
| 240 | Intermediate1 = Input { Value = "s1 * n1", }, | |
| 241 | PositionXExpression = Input { Value = "if(id > 1, i1, p1x)", }, | |
| 242 | PositionYExpression = Input { Value = "p1y", }, | |
| 243 | RedExpression = Input { Value = "clamp(n1 * 4, 0, 1)", }, | |
| 244 | GreenExpression = Input { Value = "0", }, | |
| 245 | BlueExpression = Input { Value = "0", }, | |
| 246 | KillExpressionKillIf10 = Input { Value = "if(id == 1 && age >= 0.04, 1, 0)", }, | |
| 247 | }, | |
| 248 | }, | |
| 249 | CF = pCustomForce { | |
| 250 | Inputs = { | |
| 251 | Input = Input { SourceOp = "Cust", Source = "Output", }, | |
| 252 | ForceYExpression = Input { Value = "2.0", }, | |
| 253 | TorqueZExpression = Input { Value = "1.5", }, | |
| 254 | }, | |
| 255 | }, | |
| 256 | R = pRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "CF", Source = "Output", }, }, }, | |
| 257 | }, | |
| 258 | }"#; | |
| 259 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | |
| 260 | let render_id = comp.node_by_name["R"]; | |
| 261 | let plan = build_particle_plan(&comp, render_id); | |
| 262 | let expr = ExprEngine::new(); | |
| 263 | let empty_fields = HashMap::new(); | |
| 264 | let no_sprites = HashMap::new(); | |
| 265 | let mut state = SimState::default(); | |
| 266 | for f in 0..=4 { | |
| 267 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 268 | } | |
| 269 | // Particle id=1 was killed at age>=2; particle id=2 survived at x=0.25 with +Y acceleration from pCustomForce. | |
| 270 | assert_eq!(state.particles.len(), 1, "id=1 must be killed leaving id=2, got {:?}", state.particles); | |
| 271 | let p = state.particles[0]; | |
| 272 | assert_eq!(p.id, 2); | |
| 273 | assert!((p.pos[0] - 0.25).abs() < 1e-6); | |
| 274 | assert!(p.vel[1] > 0.02, "ForceYExpression='2.0' must accelerate +Y: {}", p.vel[1]); | |
| 275 | assert!(p.rot_z > 1.0, "TorqueZExpression='1.5' must integrate spin_z into rot_z: {}", p.rot_z); | |
| 276 | assert!(p.color[0] > 0.99 && p.color[1] < 0.01); | |
| 277 | ||
| 278 | let Ok(mut eng) = crate::Engine::new_headless() else { return }; | |
| 279 | let (tex, stats) = eng.evaluate(&comp, render_id, 4.0); | |
| 280 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | |
| 281 | let px = eng.readback_rgba(&tex).unwrap(); | |
| 282 | let nonzero = px.chunks_exact(4).filter(|c| c[3] > 0).count(); | |
| 283 | assert!(nonzero > 5); | |
| 284 | } | |
| 285 | ||
| 286 | #[test] | |
| 287 | fn test_p_image_emitter_samples_rgba_and_alpha_threshold_and_gpu() { | |
| 288 | // 32x32 image whose left half is opaque red and right half is fully transparent, | |
| 289 | // driving pImageEmitter -> pRender on GPU. | |
| 290 | let comp_src = r#"Composition { | |
| 291 | GlobalRange = { 0, 5 }, | |
| 292 | RenderRange = { 0, 5 }, | |
| 293 | Tools = ordered() { | |
| 294 | MaskLeft = RectangleMask { | |
| 295 | Inputs = { | |
| 296 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 32, }, | |
| 297 | Center = Input { Value = { 0.25, 0.5 }, }, | |
| 298 | Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, | |
| 299 | }, | |
| 300 | }, | |
| 301 | RedHalf = Background { | |
| 302 | Inputs = { | |
| 303 | Width = Input { Value = 32, }, Height = Input { Value = 32, }, | |
| 304 | TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, | |
| 305 | EffectMask = Input { SourceOp = "MaskLeft", Source = "Mask", }, | |
| 306 | }, | |
| 307 | }, | |
| 308 | IE = pImageEmitter { | |
| 309 | Inputs = { | |
| 310 | Input = Input { SourceOp = "RedHalf", Source = "Output", }, | |
| 311 | XDensity = Input { Value = 0.5, }, | |
| 312 | YDensity = Input { Value = 0.5, }, | |
| 313 | AlphaThreshold = Input { Value = 0.5, }, | |
| 314 | Style = Input { Value = FuID { "ParticleStyleBlob" }, }, | |
| 315 | ["ParticleStyle.Size"] = Input { Value = 0.25, }, | |
| 316 | }, | |
| 317 | }, | |
| 318 | R = pRender { | |
| 319 | Inputs = { | |
| 320 | Width = Input { Value = 64, }, Height = Input { Value = 64, }, | |
| 321 | Input = Input { SourceOp = "IE", Source = "Output", }, | |
| 322 | }, | |
| 323 | }, | |
| 324 | }, | |
| 325 | }"#; | |
| 326 | let comp = Comp::from_fusion_str(comp_src).unwrap(); | |
| 327 | let render_id = comp.node_by_name["R"]; | |
| 328 | let Ok(mut eng) = crate::Engine::new_headless() else { return }; | |
| 329 | let (tex, stats) = eng.evaluate(&comp, render_id, 2.0); | |
| 330 | assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); | |
| 331 | let px = eng.readback_rgba(&tex).unwrap(); | |
| 332 | let px_ref = px.as_slice(); | |
| 333 | ||
| 334 | let left_red: u64 = (0..64) | |
| 335 | .flat_map(|y| (0..28).map(move |x| px_ref[(y * 64 + x) * 4] as u64)) | |
| 336 | .sum(); | |
| 337 | let right_alpha: u64 = (0..64) | |
| 338 | .flat_map(|y| (42..64).map(move |x| px_ref[(y * 64 + x) * 4 + 3] as u64)) | |
| 339 | .sum(); | |
| 340 | assert!(left_red > 1000, "pImageEmitter must emit bright red particles over left half (left_red={left_red})"); | |
| 341 | assert_eq!(right_alpha, 0, "right transparent half above AlphaThreshold must emit no particles (right_alpha={right_alpha})"); | |
| 342 | } |
crates/engine/src/particles/forces.rs+47-6| ... | ... | @@ -195,7 +195,7 @@ pub(super) fn parse_particle_style(s: &str) -> Option<ParticleStyleKind> { |
| 195 | 195 | } |
| 196 | 196 | } |
| 197 | 197 | |
| 198 | fn eval_first_num( | |
| 198 | pub(super) fn eval_first_num( | |
| 199 | 199 | comp: &Comp, |
| 200 | 200 | node: &Node, |
| 201 | 201 | keys: &[&str], |
| ... | ... | @@ -237,7 +237,7 @@ pub(super) fn read_sets_mask(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine |
| 237 | 237 | any_key.then_some(mask) |
| 238 | 238 | } |
| 239 | 239 | |
| 240 | struct ModifierFilter { | |
| 240 | pub(super) struct ModifierFilter { | |
| 241 | 241 | region: RegionSpec, |
| 242 | 242 | invert_region: bool, |
| 243 | 243 | probability: f64, |
| ... | ... | @@ -248,8 +248,21 @@ struct ModifierFilter { |
| 248 | 248 | } |
| 249 | 249 | |
| 250 | 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() { | |
| 251 | pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { | |
| 252 | Self::build(comp, node, t, expr, false) | |
| 253 | } | |
| 254 | ||
| 255 | pub(super) fn from_node_ignore_region( | |
| 256 | comp: &Comp, | |
| 257 | node: &Node, | |
| 258 | t: f64, | |
| 259 | expr: &ExprEngine, | |
| 260 | ) -> Self { | |
| 261 | Self::build(comp, node, t, expr, true) | |
| 262 | } | |
| 263 | ||
| 264 | fn build(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine, ignore_region: bool) -> Self { | |
| 265 | let region = if !ignore_region && node.static_str("Region").is_some() { | |
| 253 | 266 | RegionSpec::from_node(comp, node, t, expr) |
| 254 | 267 | } else { |
| 255 | 268 | RegionSpec::All |
| ... | ... | @@ -276,7 +289,7 @@ impl ModifierFilter { |
| 276 | 289 | } |
| 277 | 290 | |
| 278 | 291 | #[inline] |
| 279 | fn matches(&self, p: &Particle, scope: &HashSet<u64>, rng: &mut SplitMix64) -> bool { | |
| 292 | pub(super) fn matches(&self, p: &Particle, scope: &HashSet<u64>, rng: &mut SplitMix64) -> bool { | |
| 280 | 293 | if !p.alive || !scope.contains(&p.emitter_hash) { |
| 281 | 294 | return false; |
| 282 | 295 | } |
| ... | ... | @@ -305,19 +318,38 @@ impl ModifierFilter { |
| 305 | 318 | #[allow(clippy::too_many_arguments)] |
| 306 | 319 | pub(super) fn apply_extended_modifier( |
| 307 | 320 | particles: &mut Vec<Particle>, |
| 321 | next_id: &mut u32, | |
| 308 | 322 | comp: &Comp, |
| 309 | 323 | node: &Node, |
| 310 | 324 | mod_id: NodeId, |
| 311 | 325 | scope: &HashSet<u64>, |
| 312 | 326 | emitter_nodes: &HashMap<u64, NodeId>, |
| 313 | 327 | gradient_fields: &HashMap<NodeId, GradientField>, |
| 328 | sprites: &HashMap<NodeId, SpriteImage>, | |
| 314 | 329 | t: f64, |
| 315 | 330 | expr: &ExprEngine, |
| 316 | 331 | ) { |
| 317 | 332 | match node.kind.as_str() { |
| 318 | 333 | "pVortex" => apply_vortex(particles, comp, node, scope, t, expr), |
| 319 | 334 | "pFlock" => apply_flock(particles, comp, node, scope, t, expr), |
| 320 | "pSpawn" => apply_spawn(particles, comp, node, scope, emitter_nodes, t, expr), | |
| 335 | "pAvoid" => super::extra_forces::apply_avoid(particles, comp, node, scope, t, expr), | |
| 336 | "pFollow" => super::extra_forces::apply_follow(particles, comp, node, scope, t, expr), | |
| 337 | "pTangentForce" => { | |
| 338 | super::extra_forces::apply_tangent_force(particles, comp, node, scope, t, expr) | |
| 339 | } | |
| 340 | "pCustom" => { | |
| 341 | super::custom::apply_custom(particles, comp, node, scope, sprites.get(&mod_id), t, expr) | |
| 342 | } | |
| 343 | "pCustomForce" => super::custom::apply_custom_force( | |
| 344 | particles, | |
| 345 | comp, | |
| 346 | node, | |
| 347 | scope, | |
| 348 | sprites.get(&mod_id), | |
| 349 | t, | |
| 350 | expr, | |
| 351 | ), | |
| 352 | "pSpawn" => apply_spawn(particles, next_id, comp, node, scope, emitter_nodes, t, expr), | |
| 321 | 353 | "pChangeStyle" => apply_change_style(particles, comp, node, scope, t, expr), |
| 322 | 354 | "pGradientForce" => { |
| 323 | 355 | if let Some(field) = gradient_fields.get(&mod_id) { |
| ... | ... | @@ -521,8 +553,10 @@ fn apply_flock( |
| 521 | 553 | } |
| 522 | 554 | |
| 523 | 555 | /// `pSpawn`: spawns child particles from living parent particles, respecting `MAX_PARTICLES`. |
| 556 | #[allow(clippy::too_many_arguments)] | |
| 524 | 557 | fn apply_spawn( |
| 525 | 558 | particles: &mut Vec<Particle>, |
| 559 | next_id: &mut u32, | |
| 526 | 560 | comp: &Comp, |
| 527 | 561 | node: &Node, |
| 528 | 562 | scope: &HashSet<u64>, |
| ... | ... | @@ -655,8 +689,11 @@ fn apply_spawn( |
| 655 | 689 | if has_b { col_b } else { parent.color[2] }, |
| 656 | 690 | if has_a { col_a } else { parent.color[3] }, |
| 657 | 691 | ]; |
| 692 | let pid = *next_id; | |
| 693 | *next_id = (*next_id).wrapping_add(1).max(1); | |
| 658 | 694 | spawned.push(Particle { |
| 659 | 695 | emitter_hash: spawn_hash, |
| 696 | id: pid, | |
| 660 | 697 | sets: child_sets.unwrap_or(parent.sets), |
| 661 | 698 | style_override: child_style, |
| 662 | 699 | ngon_sides_override: if ngon_sides >= 3 { |
| ... | ... | @@ -667,11 +704,15 @@ fn apply_spawn( |
| 667 | 704 | bitmap_owner_hash: child_bitmap_owner, |
| 668 | 705 | pos, |
| 669 | 706 | vel, |
| 707 | rot_xy: [0.0, 0.0], | |
| 670 | 708 | rot_z: rot_z_base + rng.signed() * rot_z_var, |
| 709 | spin_xy: [0.0, 0.0], | |
| 671 | 710 | spin_z: spin_z_base + rng.signed() * spin_z_var, |
| 672 | 711 | age: 0.0, |
| 673 | 712 | lifespan, |
| 674 | 713 | size, |
| 714 | mass: parent.mass, | |
| 715 | user: parent.user, | |
| 675 | 716 | color, |
| 676 | 717 | alive: true, |
| 677 | 718 | }); |
crates/engine/src/particles/plan.rs+25-3| ... | ... | @@ -95,6 +95,21 @@ fn collect_bitmap_sources_dfs( |
| 95 | 95 | out.push((node_id, src_id)); |
| 96 | 96 | } |
| 97 | 97 | } |
| 98 | } else if node.kind == "pImageEmitter" { | |
| 99 | if let Some(src_name) = node.connected_node("Input") { | |
| 100 | if let Some(&src_id) = comp.node_by_name.get(src_name) { | |
| 101 | out.push((node_id, src_id)); | |
| 102 | } | |
| 103 | } | |
| 104 | } else if matches!(node.kind.as_str(), "pCustom" | "pCustomForce") { | |
| 105 | for port in ["Image1", "Image", "Bitmap", "BitmapInput"] { | |
| 106 | if let Some(src_name) = node.connected_node(port) { | |
| 107 | if let Some(&src_id) = comp.node_by_name.get(src_name) { | |
| 108 | out.push((node_id, src_id)); | |
| 109 | break; | |
| 110 | } | |
| 111 | } | |
| 112 | } | |
| 98 | 113 | } else if node.kind == "pGradientForce" { |
| 99 | 114 | for port in ["Image", "Bitmap", "BitmapInput", "GradientImage"] { |
| 100 | 115 | if let Some(src_name) = node.connected_node(port) { |
| ... | ... | @@ -106,8 +121,10 @@ fn collect_bitmap_sources_dfs( |
| 106 | 121 | } |
| 107 | 122 | } |
| 108 | 123 | |
| 109 | for up_id in particle_stream_inputs(comp, node) { | |
| 110 | collect_bitmap_sources_dfs(comp, up_id, visited, out); | |
| 124 | if node.kind != "pImageEmitter" { | |
| 125 | for up_id in particle_stream_inputs(comp, node) { | |
| 126 | collect_bitmap_sources_dfs(comp, up_id, visited, out); | |
| 127 | } | |
| 111 | 128 | } |
| 112 | 129 | } |
| 113 | 130 | |
| ... | ... | @@ -181,7 +198,7 @@ fn build_plan_dfs( |
| 181 | 198 | scope.extend(up_set); |
| 182 | 199 | } |
| 183 | 200 | |
| 184 | if node.kind == "pEmitter" { | |
| 201 | if matches!(node.kind.as_str(), "pEmitter" | "pImageEmitter") { | |
| 185 | 202 | if !node.bypassed { |
| 186 | 203 | let emitter_hash = stable_name_hash(&node.name); |
| 187 | 204 | emitters.push((node_id, emitter_hash)); |
| ... | ... | @@ -207,6 +224,11 @@ fn build_plan_dfs( |
| 207 | 224 | | "pBounce" |
| 208 | 225 | | "pVortex" |
| 209 | 226 | | "pFlock" |
| 227 | | "pAvoid" | |
| 228 | | "pFollow" | |
| 229 | | "pTangentForce" | |
| 230 | | "pCustom" | |
| 231 | | "pCustomForce" | |
| 210 | 232 | | "pChangeStyle" |
| 211 | 233 | | "pGradientForce" |
| 212 | 234 | ) |
crates/engine/src/particles/sim.rs+56-6| ... | ... | @@ -5,17 +5,20 @@ use model::{Comp, ExprEngine, Node, NodeId}; |
| 5 | 5 | use super::forces::{GradientField, apply_extended_modifier, read_sets_mask}; |
| 6 | 6 | use super::plan::ParticlePlan; |
| 7 | 7 | use super::{ |
| 8 | MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, TURBULENCE_SCALE, | |
| 9 | VELOCITY_SCALE, | |
| 8 | MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, SpriteImage, | |
| 9 | TURBULENCE_SCALE, VELOCITY_SCALE, | |
| 10 | 10 | }; |
| 11 | 11 | |
| 12 | 12 | /// Advances the particle simulation by a single integer frame `frame`. |
| 13 | #[allow(clippy::too_many_arguments)] | |
| 13 | 14 | pub(super) fn step_simulation( |
| 14 | 15 | state: &mut SimState, |
| 15 | 16 | comp: &Comp, |
| 16 | 17 | plan: &ParticlePlan, |
| 17 | 18 | gradient_fields: &HashMap<NodeId, GradientField>, |
| 19 | sprites: &HashMap<NodeId, SpriteImage>, | |
| 18 | 20 | frame: i64, |
| 21 | sim_start: i64, | |
| 19 | 22 | expr: &ExprEngine, |
| 20 | 23 | ) { |
| 21 | 24 | let t = frame as f64; |
| ... | ... | @@ -27,15 +30,26 @@ pub(super) fn step_simulation( |
| 27 | 30 | continue; |
| 28 | 31 | }; |
| 29 | 32 | match node.kind.as_str() { |
| 30 | "pVortex" | "pFlock" | "pSpawn" | "pChangeStyle" | "pGradientForce" => { | |
| 33 | "pVortex" | |
| 34 | | "pFlock" | |
| 35 | | "pAvoid" | |
| 36 | | "pFollow" | |
| 37 | | "pTangentForce" | |
| 38 | | "pCustom" | |
| 39 | | "pCustomForce" | |
| 40 | | "pSpawn" | |
| 41 | | "pChangeStyle" | |
| 42 | | "pGradientForce" => { | |
| 31 | 43 | apply_extended_modifier( |
| 32 | 44 | &mut state.particles, |
| 45 | &mut state.next_id, | |
| 33 | 46 | comp, |
| 34 | 47 | node, |
| 35 | 48 | *mod_id, |
| 36 | 49 | scope, |
| 37 | 50 | &plan.emitter_nodes, |
| 38 | 51 | gradient_fields, |
| 52 | sprites, | |
| 39 | 53 | t, |
| 40 | 54 | expr, |
| 41 | 55 | ); |
| ... | ... | @@ -51,6 +65,8 @@ pub(super) fn step_simulation( |
| 51 | 65 | p.pos[0] += p.vel[0]; |
| 52 | 66 | p.pos[1] += p.vel[1]; |
| 53 | 67 | p.pos[2] += p.vel[2]; |
| 68 | p.rot_xy[0] += p.spin_xy[0]; | |
| 69 | p.rot_xy[1] += p.spin_xy[1]; | |
| 54 | 70 | p.rot_z += p.spin_z; |
| 55 | 71 | p.age += 1.0; |
| 56 | 72 | if p.age >= p.lifespan { |
| ... | ... | @@ -69,7 +85,22 @@ pub(super) fn step_simulation( |
| 69 | 85 | let Some(node) = comp.nodes.get(emitter_id.0) else { |
| 70 | 86 | continue; |
| 71 | 87 | }; |
| 72 | emit_particles(state, comp, node, emitter_hash, frame, t, expr); | |
| 88 | if node.kind == "pImageEmitter" { | |
| 89 | super::extra_forces::emit_image_particles( | |
| 90 | state, | |
| 91 | comp, | |
| 92 | node, | |
| 93 | emitter_id, | |
| 94 | emitter_hash, | |
| 95 | sprites, | |
| 96 | frame, | |
| 97 | sim_start, | |
| 98 | t, | |
| 99 | expr, | |
| 100 | ); | |
| 101 | } else { | |
| 102 | emit_particles(state, comp, node, emitter_hash, frame, t, expr); | |
| 103 | } | |
| 73 | 104 | } |
| 74 | 105 | |
| 75 | 106 | // A newborn is damped by friction and then integrated once on its birth frame; other forces |
| ... | ... | @@ -86,6 +117,8 @@ pub(super) fn step_simulation( |
| 86 | 117 | for axis in 0..3 { |
| 87 | 118 | p.pos[axis] += p.vel[axis]; |
| 88 | 119 | } |
| 120 | p.rot_xy[0] += p.spin_xy[0]; | |
| 121 | p.rot_xy[1] += p.spin_xy[1]; | |
| 89 | 122 | p.rot_z += p.spin_z; |
| 90 | 123 | } |
| 91 | 124 | } |
| ... | ... | @@ -235,19 +268,26 @@ fn emit_particles( |
| 235 | 268 | ] |
| 236 | 269 | }; |
| 237 | 270 | |
| 271 | let pid = state.next_id; | |
| 272 | state.next_id = state.next_id.wrapping_add(1).max(1); | |
| 238 | 273 | state.particles.push(Particle { |
| 239 | 274 | emitter_hash, |
| 275 | id: pid, | |
| 240 | 276 | sets: emitter_sets, |
| 241 | 277 | style_override: None, |
| 242 | 278 | ngon_sides_override: 0, |
| 243 | 279 | bitmap_owner_hash: 0, |
| 244 | 280 | pos, |
| 245 | 281 | vel, |
| 282 | rot_xy: [0.0, 0.0], | |
| 246 | 283 | rot_z, |
| 284 | spin_xy: [0.0, 0.0], | |
| 247 | 285 | spin_z, |
| 248 | 286 | age: 0.0, |
| 249 | 287 | lifespan, |
| 250 | 288 | size, |
| 289 | mass: 1.0, | |
| 290 | user: 0.0, | |
| 251 | 291 | color, |
| 252 | 292 | alive: true, |
| 253 | 293 | }); |
| ... | ... | @@ -283,7 +323,17 @@ pub(super) enum RegionSpec { |
| 283 | 323 | |
| 284 | 324 | impl RegionSpec { |
| 285 | 325 | pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { |
| 286 | let region_name = node.static_str("Region").unwrap_or("SphereRgn"); | |
| 326 | Self::from_node_with_default(comp, node, t, expr, "SphereRgn") | |
| 327 | } | |
| 328 | ||
| 329 | pub(super) fn from_node_with_default( | |
| 330 | comp: &Comp, | |
| 331 | node: &Node, | |
| 332 | t: f64, | |
| 333 | expr: &ExprEngine, | |
| 334 | default_region: &str, | |
| 335 | ) -> Self { | |
| 336 | let region_name = node.static_str("Region").unwrap_or(default_region); | |
| 287 | 337 | match region_name { |
| 288 | 338 | "RectRgn" => Self::Rect { |
| 289 | 339 | center: [ |
| ... | ... | @@ -904,7 +954,7 @@ fn apply_modifier( |
| 904 | 954 | } |
| 905 | 955 | |
| 906 | 956 | /// Smooth deterministic 3D value noise in `[-1.0, 1.0]`. |
| 907 | fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { | |
| 957 | pub(super) fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { | |
| 908 | 958 | let xi = x.floor() as i64; |
| 909 | 959 | let yi = y.floor() as i64; |
| 910 | 960 | let zi = z.floor() as i64; |
crates/engine/src/particles/tests.rs+15-10| ... | ... | @@ -264,8 +264,9 @@ Composition { |
| 264 | 264 | // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05) |
| 265 | 265 | // crosses the floor at y=0.0 around frame 3. |
| 266 | 266 | let empty_fields = HashMap::new(); |
| 267 | let no_sprites = HashMap::new(); | |
| 267 | 268 | for f in 0..=4 { |
| 268 | step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); | |
| 269 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 269 | 270 | } |
| 270 | 271 | let first = state.particles.first().expect("particle emitted"); |
| 271 | 272 | let init_vx = 0.1 * (-60.0_f64).to_radians().cos(); |
| ... | ... | @@ -677,12 +678,13 @@ fn test_p_vortex_swirl_and_spiral_angle() { |
| 677 | 678 | let expr = ExprEngine::new(); |
| 678 | 679 | let empty_fields = HashMap::new(); |
| 679 | 680 | |
| 681 | let no_sprites = HashMap::new(); | |
| 680 | 682 | // Angle = 0: pure CCW tangential swirl -> particle at (+0.2, 0) gains +Y velocity. |
| 681 | 683 | let comp_tan = Comp::from_fusion_str(&make_comp(0.0)).unwrap(); |
| 682 | 684 | let plan_tan = build_particle_plan(&comp_tan, comp_tan.node_by_name["R"]); |
| 683 | 685 | let mut state_tan = SimState::default(); |
| 684 | 686 | for f in 0..=4 { |
| 685 | step_simulation(&mut state_tan, &comp_tan, &plan_tan, &empty_fields, f, &expr); | |
| 687 | step_simulation(&mut state_tan, &comp_tan, &plan_tan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 686 | 688 | } |
| 687 | 689 | let p_tan = state_tan.particles[0]; |
| 688 | 690 | assert!(p_tan.vel[1] > 0.01, "tangential vortex must swirl +Y at (+X,0), got {:?}", p_tan.vel); |
| ... | ... | @@ -692,7 +694,7 @@ fn test_p_vortex_swirl_and_spiral_angle() { |
| 692 | 694 | let plan_in = build_particle_plan(&comp_in, comp_in.node_by_name["R"]); |
| 693 | 695 | let mut state_in = SimState::default(); |
| 694 | 696 | for f in 0..=5 { |
| 695 | step_simulation(&mut state_in, &comp_in, &plan_in, &empty_fields, f, &expr); | |
| 697 | step_simulation(&mut state_in, &comp_in, &plan_in, &empty_fields, &no_sprites, f, 0, &expr); | |
| 696 | 698 | } |
| 697 | 699 | let r_in = state_in.particles[0].pos[0].hypot(state_in.particles[0].pos[1]); |
| 698 | 700 | assert!(r_in < 0.19, "positive Angle vortex should spiral inward, got r={r_in}"); |
| ... | ... | @@ -702,7 +704,7 @@ fn test_p_vortex_swirl_and_spiral_angle() { |
| 702 | 704 | let plan_out = build_particle_plan(&comp_out, comp_out.node_by_name["R"]); |
| 703 | 705 | let mut state_out = SimState::default(); |
| 704 | 706 | for f in 0..=5 { |
| 705 | step_simulation(&mut state_out, &comp_out, &plan_out, &empty_fields, f, &expr); | |
| 707 | step_simulation(&mut state_out, &comp_out, &plan_out, &empty_fields, &no_sprites, f, 0, &expr); | |
| 706 | 708 | } |
| 707 | 709 | let r_out = state_out.particles[0].pos[0].hypot(state_out.particles[0].pos[1]); |
| 708 | 710 | assert!(r_out > 0.21, "negative Angle vortex should spiral outward, got r={r_out}"); |
| ... | ... | @@ -773,11 +775,12 @@ fn test_p_flock_cohesion_separation_alignment_and_perf() { |
| 773 | 775 | let expr = ExprEngine::new(); |
| 774 | 776 | let empty_fields = HashMap::new(); |
| 775 | 777 | |
| 778 | let no_sprites = HashMap::new(); | |
| 776 | 779 | // Cohesion + Alignment: particles at x=-0.08 and x=+0.08 pull together and share +Y velocity. |
| 777 | 780 | let plan_coh = build_particle_plan(&comp, comp.node_by_name["RCoh"]); |
| 778 | 781 | let mut state_coh = SimState::default(); |
| 779 | 782 | for f in 0..=4 { |
| 780 | step_simulation(&mut state_coh, &comp, &plan_coh, &empty_fields, f, &expr); | |
| 783 | step_simulation(&mut state_coh, &comp, &plan_coh, &empty_fields, &no_sprites, f, 0, &expr); | |
| 781 | 784 | } |
| 782 | 785 | let dx_coh = (state_coh.particles[1].pos[0] - state_coh.particles[0].pos[0]).abs(); |
| 783 | 786 | assert!(dx_coh < 0.155, "cohesion should pull particles closer than 0.16, got {dx_coh}"); |
| ... | ... | @@ -787,7 +790,7 @@ fn test_p_flock_cohesion_separation_alignment_and_perf() { |
| 787 | 790 | let plan_sep = build_particle_plan(&comp, comp.node_by_name["RSep"]); |
| 788 | 791 | let mut state_sep = SimState::default(); |
| 789 | 792 | for f in 0..=4 { |
| 790 | step_simulation(&mut state_sep, &comp, &plan_sep, &empty_fields, f, &expr); | |
| 793 | step_simulation(&mut state_sep, &comp, &plan_sep, &empty_fields, &no_sprites, f, 0, &expr); | |
| 791 | 794 | } |
| 792 | 795 | let dx_sep = (state_sep.particles[1].pos[0] - state_sep.particles[0].pos[0]).abs(); |
| 793 | 796 | assert!(dx_sep > 0.165, "separation should push particles farther than 0.16, got {dx_sep}"); |
| ... | ... | @@ -817,7 +820,7 @@ fn test_p_flock_cohesion_separation_alignment_and_perf() { |
| 817 | 820 | let mut heavy_state = SimState::default(); |
| 818 | 821 | let t0 = Instant::now(); |
| 819 | 822 | for f in 0..=2 { |
| 820 | step_simulation(&mut heavy_state, &heavy_comp, &heavy_plan, &empty_fields, f, &expr); | |
| 823 | step_simulation(&mut heavy_state, &heavy_comp, &heavy_plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 821 | 824 | } |
| 822 | 825 | assert!(heavy_state.particles.len() >= 2000); |
| 823 | 826 | assert!( |
| ... | ... | @@ -881,8 +884,9 @@ fn test_p_spawn_children_velocity_transfer_and_cap() { |
| 881 | 884 | |
| 882 | 885 | // Frame 0: 2 parents emitted. Frame 1: each parent spawns 3 children => 2 + 6 = 8. |
| 883 | 886 | // Frame 2: only the 2 original parents spawn (NOT the 6 children!) => 2 + 6 + 6 = 14. |
| 887 | let no_sprites = HashMap::new(); | |
| 884 | 888 | for f in 0..=2 { |
| 885 | step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); | |
| 889 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 886 | 890 | } |
| 887 | 891 | assert_eq!(state.particles.len(), 14, "expected 2 parents + 12 non-recursive children"); |
| 888 | 892 | |
| ... | ... | @@ -972,9 +976,10 @@ fn test_p_change_style_color_size_style_and_region() { |
| 972 | 976 | let plan = build_particle_plan(&comp, render_id); |
| 973 | 977 | let expr = ExprEngine::new(); |
| 974 | 978 | let empty_fields = HashMap::new(); |
| 979 | let no_sprites = HashMap::new(); | |
| 975 | 980 | let mut state = SimState::default(); |
| 976 | 981 | for f in 0..=2 { |
| 977 | step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); | |
| 982 | step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); | |
| 978 | 983 | } |
| 979 | 984 | let p_in = state.particles.iter().find(|p| p.pos[0] < 0.0).unwrap(); |
| 980 | 985 | let p_out = state.particles.iter().find(|p| p.pos[0] > 0.0).unwrap(); |
| ... | ... | @@ -1077,7 +1082,7 @@ fn test_p_gradient_force_luma_gradient_and_gpu_eval() { |
| 1077 | 1082 | let expr = ExprEngine::new(); |
| 1078 | 1083 | let mut state = SimState::default(); |
| 1079 | 1084 | for f in 0..=4 { |
| 1080 | step_simulation(&mut state, &comp, &plan, &fields, f, &expr); | |
| 1085 | step_simulation(&mut state, &comp, &plan, &fields, &sprites, f, 0, &expr); | |
| 1081 | 1086 | } |
| 1082 | 1087 | let p = state.particles[0]; |
| 1083 | 1088 | assert!(p.vel[0] > 0.02, "left-to-right bright ramp must push particle +X, got {:?}", p.vel); |
crates/engine/src/text_engine.rs+149| ... | ... | @@ -987,6 +987,155 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec |
| 987 | 987 | Some((out, total_chars)) |
| 988 | 988 | } |
| 989 | 989 | |
| 990 | /// Parameters for extracting vector `zeno::Command` contours for `sText` in Y-up shape space. | |
| 991 | pub struct TextShapeParams<'a> { | |
| 992 | pub text: &'a str, | |
| 993 | pub font_family: &'a str, | |
| 994 | pub font_style: &'a str, | |
| 995 | pub size_norm: f32, | |
| 996 | pub tracking: f32, | |
| 997 | pub line_spacing: f32, | |
| 998 | pub h_lcr: f32, | |
| 999 | pub v_tcb: f32, | |
| 1000 | pub shear_x: f32, | |
| 1001 | pub write_on_start: f32, | |
| 1002 | pub write_on_end: f32, | |
| 1003 | pub char_size_x: f32, | |
| 1004 | pub char_size_y: f32, | |
| 1005 | } | |
| 1006 | ||
| 1007 | struct ShapePathBuilder { | |
| 1008 | commands: Vec<Command>, | |
| 1009 | scale_x: f32, | |
| 1010 | scale_y: f32, | |
| 1011 | origin: [f32; 2], | |
| 1012 | lean: f32, | |
| 1013 | } | |
| 1014 | ||
| 1015 | impl ShapePathBuilder { | |
| 1016 | fn point(&self, x: f32, y: f32) -> Vector { | |
| 1017 | let px = x * self.scale_x; | |
| 1018 | let py = y * self.scale_y; | |
| 1019 | Vector::new(self.origin[0] + px + py * self.lean, self.origin[1] + py) | |
| 1020 | } | |
| 1021 | } | |
| 1022 | ||
| 1023 | impl OutlineBuilder for ShapePathBuilder { | |
| 1024 | fn move_to(&mut self, x: f32, y: f32) { | |
| 1025 | let p = self.point(x, y); | |
| 1026 | self.commands.push(Command::MoveTo(p)); | |
| 1027 | } | |
| 1028 | fn line_to(&mut self, x: f32, y: f32) { | |
| 1029 | let p = self.point(x, y); | |
| 1030 | self.commands.push(Command::LineTo(p)); | |
| 1031 | } | |
| 1032 | fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { | |
| 1033 | let (c, p) = (self.point(x1, y1), self.point(x, y)); | |
| 1034 | self.commands.push(Command::QuadTo(c, p)); | |
| 1035 | } | |
| 1036 | fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { | |
| 1037 | let (c1, c2, p) = (self.point(x1, y1), self.point(x2, y2), self.point(x, y)); | |
| 1038 | self.commands.push(Command::CurveTo(c1, c2, p)); | |
| 1039 | } | |
| 1040 | fn close(&mut self) { | |
| 1041 | self.commands.push(Command::Close); | |
| 1042 | } | |
| 1043 | } | |
| 1044 | ||
| 1045 | /// Extracts Y-up shape-space vector `zeno::Command` contours for `sText` using `rustybuzz` + `ttf-parser`. | |
| 1046 | pub fn layout_text_shape_commands(params: &TextShapeParams<'_>) -> Vec<Command> { | |
| 1047 | let total_chars = params.text.chars().count(); | |
| 1048 | if total_chars == 0 || !params.size_norm.is_finite() || params.size_norm <= 1e-4 { | |
| 1049 | return Vec::new(); | |
| 1050 | } | |
| 1051 | let c_start = (params.write_on_start.clamp(0.0, 1.0) * total_chars as f32).floor() as usize; | |
| 1052 | let c_end = (params.write_on_end.clamp(0.0, 1.0) * total_chars as f32).ceil() as usize; | |
| 1053 | if c_start >= c_end || c_start >= total_chars { | |
| 1054 | return Vec::new(); | |
| 1055 | } | |
| 1056 | let Some(font) = Font::find(params.font_family, params.font_style) else { | |
| 1057 | return Vec::new(); | |
| 1058 | }; | |
| 1059 | let face = font.face(); | |
| 1060 | let upem = face.units_per_em() as f32; | |
| 1061 | if upem <= 0.0 { | |
| 1062 | return Vec::new(); | |
| 1063 | } | |
| 1064 | ||
| 1065 | // Use a large reference scale (1000.0) for `shape_line` so integer glyph advance/kerning | |
| 1066 | // stays exact, then rescale back to normalized shape units (width = 1.0). | |
| 1067 | let ref_w = 1000.0_f32; | |
| 1068 | let (font_px, asc, desc) = size_metrics(&face, params.size_norm, ref_w); | |
| 1069 | let top_anchor = (font_px - desc).max(0.0) / ref_w; | |
| 1070 | let asc = asc / ref_w; | |
| 1071 | let desc = desc / ref_w; | |
| 1072 | let font_em = font_px / ref_w; | |
| 1073 | let extra_track = (params.tracking - 1.0) * params.size_norm; | |
| 1074 | ||
| 1075 | struct ShapeLine { | |
| 1076 | glyphs: Vec<(GlyphId, f32, f32)>, | |
| 1077 | width: f32, | |
| 1078 | } | |
| 1079 | let mut lines: Vec<ShapeLine> = Vec::new(); | |
| 1080 | let mut char_cursor = 0usize; | |
| 1081 | for raw_line in params.text.split('\n') { | |
| 1082 | let raw_char_len = raw_line.chars().count(); | |
| 1083 | let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line); | |
| 1084 | let mut glyphs = Vec::new(); | |
| 1085 | let width = if line_str.is_empty() { | |
| 1086 | 0.0 | |
| 1087 | } else { | |
| 1088 | let shaped = shape_line(&face, line_str, font_px, extra_track * ref_w); | |
| 1089 | for g in &shaped.glyphs { | |
| 1090 | let idx = char_cursor + g.char_index; | |
| 1091 | if idx < c_start || idx >= c_end { | |
| 1092 | continue; | |
| 1093 | } | |
| 1094 | glyphs.push((g.id, g.x / ref_w * params.char_size_x, g.y / ref_w * params.char_size_y)); | |
| 1095 | } | |
| 1096 | shaped.width / ref_w * params.char_size_x | |
| 1097 | }; | |
| 1098 | lines.push(ShapeLine { glyphs, width }); | |
| 1099 | char_cursor += raw_char_len + 1; | |
| 1100 | } | |
| 1101 | ||
| 1102 | let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; | |
| 1103 | let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5; | |
| 1104 | let ls = params.line_spacing.max(0.05); | |
| 1105 | let line_step = (desc + asc) * ls; | |
| 1106 | let mut baselines = Vec::with_capacity(lines.len()); | |
| 1107 | let mut y_acc = 0.0_f32; | |
| 1108 | for i in 0..lines.len() { | |
| 1109 | baselines.push(y_acc); | |
| 1110 | if i + 1 < lines.len() { | |
| 1111 | y_acc += line_step; | |
| 1112 | } | |
| 1113 | } | |
| 1114 | let block_h = y_acc + top_anchor; | |
| 1115 | let baseline_0 = v_frac * block_h - top_anchor; | |
| 1116 | ||
| 1117 | let mut commands = Vec::new(); | |
| 1118 | let scale_x = (font_em / upem) * params.char_size_x; | |
| 1119 | let scale_y = (font_em / upem) * params.char_size_y; | |
| 1120 | let lean = font.lean - params.shear_x; | |
| 1121 | for (li, line) in lines.into_iter().enumerate() { | |
| 1122 | let start_x = -line.width * h_frac; | |
| 1123 | let base_y = baseline_0 - baselines[li]; | |
| 1124 | for (gid, gx, gy) in line.glyphs { | |
| 1125 | let mut builder = ShapePathBuilder { | |
| 1126 | commands: Vec::new(), | |
| 1127 | scale_x, | |
| 1128 | scale_y, | |
| 1129 | origin: [start_x + gx, base_y + gy], | |
| 1130 | lean, | |
| 1131 | }; | |
| 1132 | face.outline_glyph(gid, &mut builder); | |
| 1133 | commands.extend(builder.commands); | |
| 1134 | } | |
| 1135 | } | |
| 1136 | commands | |
| 1137 | } | |
| 1138 | ||
| 990 | 1139 | const GLYPH_BASELINE_ANCHOR: f32 = 256.0; |
| 991 | 1140 | const GLYPH_BASELINE_ANCHOR_I32: i32 = 256; |
| 992 | 1141 | const MAX_GLYPH_CACHE_ENTRIES: usize = 4096; |