authoravatarclover caruso<git@paperclover.net>2026-12-01 02:57:14-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 03:50:24-08:00
loge425cbbc6a0f2456b92ab401b458ae1f44826f6f
tree188140097e2899d35a7cdc3287312a8e624fd899
parentaea6a860813d536eb3354f2f47cb47412200739e
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

engine: native SwitchElse, CheckerPieceGenerator, AlphaWeightedNoise, Crystallize fuses

Ports Clover's four custom Fuses with GPU compute shaders (archive_fx.wgsl), CheckerPieceGenerator's ExtraScale output resolved in Comp::eval_number, catalog entries, and GPU/model unit tests. Assisted-by: claude-sonnet-5.5

7 files changed, 614 insertions(+), 8 deletions(-)

crates/app/src/add_tool.rs+5
......@@ -68,11 +68,13 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[
6868 ToolEntry { kind: "TextPlus", display: "Text+", aliases: "textplus title font", category: ToolCategory::Generator, is_generator: true },
6969 ToolEntry { kind: "Loader", display: "Loader", aliases: "ld read media footage image", category: ToolCategory::Generator, is_generator: true },
7070 ToolEntry { kind: "DaySky", display: "Day Sky", aliases: "sky sun atmosphere preetham hdri", category: ToolCategory::Generator, is_generator: true },
71 ToolEntry { kind: "Fuse.CheckerPieceGenerator", display: "Checker Piece", aliases: "checkerboard checker tile squares", category: ToolCategory::Generator, is_generator: true },
7172 // Composite
7273 ToolEntry { kind: "Merge", display: "Merge", aliases: "mrg over blend comp", category: ToolCategory::Composite, is_generator: false },
7374 ToolEntry { kind: "Dissolve", display: "Dissolve", aliases: "dx mix crossfade", category: ToolCategory::Composite, is_generator: false },
7475 ToolEntry { kind: "ChannelBoolean", display: "Channel Booleans", aliases: "cb channel matte", category: ToolCategory::Composite, is_generator: false },
7576 ToolEntry { kind: "Switch", display: "Switch", aliases: "sw select", category: ToolCategory::Composite, is_generator: false },
77 ToolEntry { kind: "Fuse.SwitchElse", display: "Switch Else", aliases: "sw select fallback default", category: ToolCategory::Composite, is_generator: false },
7678 ToolEntry { kind: "Shadow", display: "Shadow", aliases: "drop shadow", category: ToolCategory::Composite, is_generator: false },
7779 ToolEntry { kind: "Paint", display: "Paint", aliases: "brush stroke clone retouch", category: ToolCategory::Composite, is_generator: false },
7880 // Color
......@@ -86,6 +88,7 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[
8688 ToolEntry { kind: "FilmGrain", display: "Film Grain", aliases: "grain noise", category: ToolCategory::Color, is_generator: false },
8789 ToolEntry { kind: "Fuse.Colorize", display: "Colorize", aliases: "tint duotone", category: ToolCategory::Color, is_generator: false },
8890 ToolEntry { kind: "Fuse.Outline", display: "Outline", aliases: "stroke edge", category: ToolCategory::Color, is_generator: false },
91 ToolEntry { kind: "Fuse.AlphaWeightedNoise", display: "Alpha Weighted Noise", aliases: "awn dither stipple random alpha", category: ToolCategory::Color, is_generator: false },
8992 // Keyer
9093 ToolEntry { kind: "UltraKeyer", display: "Ultra Keyer", aliases: "uk chroma green blue screen", category: ToolCategory::Keyer, is_generator: false },
9194 ToolEntry { kind: "LumaKeyer", display: "Luma Keyer", aliases: "lk luminance key", category: ToolCategory::Keyer, is_generator: false },
......@@ -117,6 +120,7 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[
117120 ToolEntry { kind: "Dent", display: "Dent", aliases: "pinch punch bulge lens", category: ToolCategory::TransformWarp, is_generator: false },
118121 ToolEntry { kind: "Fuse.Duplicate", display: "Duplicate", aliases: "copies repeat array clone", category: ToolCategory::TransformWarp, is_generator: false },
119122 ToolEntry { kind: "Fuse.KScope", display: "Kaleidoscope", aliases: "kscope mirror slices", category: ToolCategory::TransformWarp, is_generator: false },
123 ToolEntry { kind: "Fuse.Crystallize", display: "Crystallize", aliases: "facet voronoi cells shards", category: ToolCategory::TransformWarp, is_generator: false },
120124 // Mask
121125 ToolEntry { kind: "EllipseMask", display: "Ellipse Mask", aliases: "el circle oval", category: ToolCategory::Mask, is_generator: true },
122126 ToolEntry { kind: "RectangleMask", display: "Rectangle Mask", aliases: "rect box square", category: ToolCategory::Mask, is_generator: true },
......@@ -606,6 +610,7 @@ mod tests {
606610 "MtlPhong", "MtlCookTorrance", "LightPoint", "LightSpot", "WandMask",
607611 "Fuse.Duplicate", "Fuse.KScope", "Fuse.Wireless", "Fuse.Cryptomatte",
608612 "Dimension.OpticalFlow", "Dimension.CopyAux", "pBounce", "Custom", "Switch",
613 "Fuse.SwitchElse", "Fuse.CheckerPieceGenerator", "Fuse.AlphaWeightedNoise", "Fuse.Crystallize",
609614 ] {
610615 assert!(seen.contains(kind), "catalog is missing {kind}");
611616 }
crates/engine/src/eval/fuses.rs created+432
......@@ -0,0 +1,432 @@
1//! Native ports of Clover's custom Fuses: `SwitchElse`, `CheckerPieceGenerator`,
2//! `AlphaWeightedNoise`, and `Crystallize`.
3
4use super::*;
5
6impl Engine {
7 pub(super) fn eval_switch_else(
8 &mut self,
9 comp: &Comp,
10 node: &Node,
11 time: f64,
12 enc: &mut wgpu::CommandEncoder,
13 visiting: &mut HashSet<(NodeId, i64)>,
14 stats: &mut EvalStats,
15 ) -> CachedTexture {
16 let index = |name: &str, default: f64| comp.eval_number(node, name, time, default, &self.expr).round().max(1.0) as usize;
17 let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| {
18 node.connected_node(&format!("Input{i}")).and_then(|s| comp.find_node(s))
19 });
20 match picked {
21 Some(id) => self.eval_node(comp, id, time, enc, visiting, stats),
22 None => self.dummy.clone(),
23 }
24 }
25
26 pub(super) fn eval_checker_piece(
27 &mut self,
28 comp: &Comp,
29 node: &Node,
30 time: f64,
31 frame_i: i64,
32 enc: &mut wgpu::CommandEncoder,
33 stats: &mut EvalStats,
34 ) -> CachedTexture {
35 let (full_size, _) = comp.checker_piece_metrics(node, time, &self.expr);
36 let edge = (full_size / self.proxy_scale.max(1)).max(1);
37 let flip = comp.eval_number(node, "Flip", time, 0.0, &self.expr) > 0.5;
38 let color = |suffix: &str, default: [f64; 3]| {
39 [
40 comp.eval_number(node, &format!("R{suffix}"), time, default[0], &self.expr) as f32,
41 comp.eval_number(node, &format!("G{suffix}"), time, default[1], &self.expr) as f32,
42 comp.eval_number(node, &format!("B{suffix}"), time, default[2], &self.expr) as f32,
43 comp.eval_number(node, &format!("A{suffix}"), time, 1.0, &self.expr) as f32,
44 ]
45 };
46 let (a, b) = (color("1", [0.0; 3]), color("2", [1.0; 3]));
47
48 let mut u = UniformParams::default();
49 (u.p[0], u.p[1]) = if flip { (b, a) } else { (a, b) };
50 let depth = self.node_depth(comp, node, time, None);
51 let size = [edge, edge];
52 let key = self.make_key(node, "CheckerPiece", size, &[depth as u64], bytemuck::cast_slice(&u.p[..2]));
53 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
54 stats.cache_hits += 1;
55 return hit;
56 }
57 stats.cache_misses += 1;
58 stats.nodes_evaluated += 1;
59 let dst = self.alloc_tex(size, depth, key);
60 self.dispatch_op(enc, ShaderOp::CheckerPiece, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u);
61 self.cache.insert(key, dst.clone(), node.id, frame_i);
62 dst
63 }
64
65 pub(super) fn eval_alpha_weighted_noise(
66 &mut self,
67 comp: &Comp,
68 node: &Node,
69 time: f64,
70 frame_i: i64,
71 enc: &mut wgpu::CommandEncoder,
72 visiting: &mut HashSet<(NodeId, i64)>,
73 stats: &mut EvalStats,
74 ) -> CachedTexture {
75 let Some(src_id) = node
76 .connected_node("Image")
77 .or_else(|| node.connected_node("Input"))
78 .and_then(|s| comp.find_node(s))
79 else {
80 return self.dummy.clone();
81 };
82 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
83 let mut u = UniformParams::default();
84 u.p[0] = [
85 comp.eval_number(node, "RandomSeed", time, 0.0, &self.expr).round().max(0.0) as f32,
86 comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32,
87 comp.eval_number(node, "Lift", time, 0.0, &self.expr) as f32,
88 0.0,
89 ];
90 let key = self.make_key(node, "AlphaWeightedNoise", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1]));
91 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
92 stats.cache_hits += 1;
93 return hit;
94 }
95 stats.cache_misses += 1;
96 stats.nodes_evaluated += 1;
97 let dst = self.alloc_tex_like(&src, src.depth, key);
98 self.dispatch_op(enc, ShaderOp::AlphaWeightedNoise, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u);
99 self.cache.insert(key, dst.clone(), node.id, frame_i);
100 dst
101 }
102
103 pub(super) fn eval_crystallize(
104 &mut self,
105 comp: &Comp,
106 node: &Node,
107 time: f64,
108 frame_i: i64,
109 enc: &mut wgpu::CommandEncoder,
110 visiting: &mut HashSet<(NodeId, i64)>,
111 stats: &mut EvalStats,
112 ) -> CachedTexture {
113 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
114 return self.dummy.clone();
115 };
116 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
117 let num = |name: &str, default: f64| comp.eval_number(node, name, time, default, &self.expr);
118 let size = num("Size", 0.025).max(0.001);
119 let smooth = num("Smooth", 1.0) >= 0.5;
120 let width = src.canvas_size[0] as f32;
121
122 let mut u = UniformParams::default();
123 u.p[0] = [
124 size as f32 * width,
125 (num("Feathering", 0.0).max(0.0) * 0.2).max(1e-4) as f32,
126 (num("Seethe", 0.0) + num("SeetheRate", 0.02) * time) as f32,
127 num("RandomSeed", 0.0) as f32,
128 ];
129 u.p[1] = [
130 num("Jitter", 1.0).clamp(0.0, 1.0) as f32,
131 num("Blades", 2.0).round().clamp(1.0, 3.0) as f32,
132 src.origin[0] as f32,
133 src.origin[1] as f32,
134 ];
135 u.p[2] = [src.canvas_size[1] as f32, if smooth { 1.0 } else { 0.0 }, 0.0, 0.0];
136
137 let key = self.make_key(node, "Crystallize", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p[..3]));
138 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
139 stats.cache_hits += 1;
140 return hit;
141 }
142 stats.cache_misses += 1;
143 stats.nodes_evaluated += 1;
144
145 let blurred;
146 let facet_src = if smooth {
147 // Box about one facet wide, standing in for the facet's average.
148 let radius = 0.35 * u.p[0][0];
149 let tmp = self.alloc_tex_like(&src, src.depth, 0);
150 blurred = self.alloc_tex_like(&src, src.depth, 0);
151 for (dir, from, to) in [([1.0, 0.0], &src, &tmp), ([0.0, 1.0], &tmp, &blurred)] {
152 let mut ub = UniformParams::default();
153 ub.p[0] = [dir[0], dir[1], radius, 1.0];
154 ub.p[1] = [1.0, 0.0, 0.0, 1.0];
155 self.dispatch_op(enc, ShaderOp::Blur, &from.view, &self.dummy.view, &self.dummy.view, to, &ub);
156 }
157 &blurred
158 } else {
159 &src
160 };
161
162 let dst = self.alloc_tex_like(&src, src.depth, key);
163 self.dispatch_op(enc, ShaderOp::Crystallize, &facet_src.view, &self.dummy.view, &self.dummy.view, &dst, &u);
164 self.cache.insert(key, dst.clone(), node.id, frame_i);
165 dst
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn comp(tools: &str) -> Comp {
174 let src = format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ {tools} }} }}");
175 Comp::from_fusion_str(&src).expect("parse comp")
176 }
177
178 fn bg(name: &str, w: u32, inputs: &str) -> String {
179 format!("{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {w}, }}, {inputs} }}, }},")
180 }
181
182 /// Renders `name` and returns `(size, rgba8 rows top-down)`; `None` without a GPU adapter.
183 fn render(comp: &Comp, name: &str, time: f64) -> Option<([u32; 2], Vec<u8>)> {
184 let mut eng = Engine::new_headless().ok()?;
185 let (tex, _) = eng.evaluate(comp, comp.find_node(name).unwrap(), time);
186 Some((tex.size, eng.readback_rgba(&tex).unwrap()))
187 }
188
189 fn px(img: &(Vec<u8>, u32), x: u32, y: u32) -> [u8; 4] {
190 let i = ((y * img.1 + x) * 4) as usize;
191 img.0[i..i + 4].try_into().unwrap()
192 }
193
194 #[test]
195 fn switch_else_prefers_switch_input_then_else_then_dummy() {
196 let tools = [
197 bg("Red", 16, "TopLeftRed = Input { Value = 1, },"),
198 bg("Green", 16, "TopLeftGreen = Input { Value = 1, },"),
199 r#"Both = Fuse.SwitchElse { Inputs = {
200 Input1 = Input { SourceOp = "Red", Source = "Output", },
201 Input2 = Input { SourceOp = "Green", Source = "Output", },
202 }, },
203 ElseOnly = Fuse.SwitchElse { Inputs = {
204 Input2 = Input { SourceOp = "Green", Source = "Output", },
205 }, },
206 Swapped = Fuse.SwitchElse { Inputs = {
207 Switch = Input { Value = 2, },
208 Else = Input { Value = 1, },
209 Input1 = Input { SourceOp = "Red", Source = "Output", },
210 Input2 = Input { SourceOp = "Green", Source = "Output", },
211 }, },
212 SwappedElse = Fuse.SwitchElse { Inputs = {
213 Switch = Input { Value = 2, },
214 Else = Input { Value = 1, },
215 Input1 = Input { SourceOp = "Red", Source = "Output", },
216 }, },
217 Dangling = Fuse.SwitchElse { Inputs = {
218 Input1 = Input { SourceOp = "Missing", Source = "Output", },
219 Input2 = Input { SourceOp = "Green", Source = "Output", },
220 }, },
221 Empty = Fuse.SwitchElse { },"#
222 .to_string(),
223 ]
224 .concat();
225 let c = comp(&tools);
226 let color = |name| render(&c, name, 0.0).map(|(size, p)| (size, [p[0], p[1], p[2]]));
227 let Some(both) = color("Both") else { return };
228 assert_eq!(both, ([16, 16], [255, 0, 0]));
229 assert_eq!(color("ElseOnly").unwrap(), ([16, 16], [0, 255, 0]));
230 assert_eq!(color("Swapped").unwrap(), ([16, 16], [0, 255, 0]));
231 assert_eq!(color("SwappedElse").unwrap(), ([16, 16], [255, 0, 0]));
232 assert_eq!(color("Dangling").unwrap(), ([16, 16], [0, 255, 0]));
233 assert_eq!(color("Empty").unwrap().0, [1, 1]);
234 }
235
236 #[test]
237 fn checker_piece_is_y_up_nearest_2x2_with_flip_and_colors() {
238 let c = comp(
239 r#"Plain = Fuse.CheckerPieceGenerator { Inputs = {
240 Width = Input { Value = 40, },
241 Repeat = Input { Value = 5, },
242 }, },
243 Flipped = Fuse.CheckerPieceGenerator { Inputs = {
244 Width = Input { Value = 40, },
245 Repeat = Input { Value = 5, },
246 Flip = Input { Value = 1, },
247 R1 = Input { Value = 1, }, G1 = Input { Value = 0, }, B1 = Input { Value = 0, }, A1 = Input { Value = 1, },
248 R2 = Input { Value = 0, }, G2 = Input { Value = 0, }, B2 = Input { Value = 1, }, A2 = Input { Value = 0.5, },
249 }, },
250 Odd = Fuse.CheckerPieceGenerator { Inputs = {
251 Width = Input { Value = 100, },
252 Repeat = Input { Value = 3, },
253 }, },
254 Floor = Fuse.CheckerPieceGenerator { Inputs = {
255 Width = Input { Value = 4, },
256 Repeat = Input { Value = 10, },
257 }, },"#,
258 );
259 let Some((size, rgba)) = render(&c, "Plain", 0.0) else { return };
260 // 40 / 5 = 8 px tiles; A = black bottom-left & top-right, B = white top-left & bottom-right.
261 assert_eq!(size, [8, 8]);
262 let img = (rgba, 8);
263 let [top_left, top_right, bottom_left, bottom_right] =
264 [(0, 0), (7, 0), (0, 7), (7, 7)].map(|(x, y)| px(&img, x, y));
265 assert_eq!([top_left, bottom_right], [[255; 4]; 2]);
266 assert_eq!([top_right, bottom_left], [[0, 0, 0, 255]; 2]);
267 // Nearest-neighbor: the quadrant seams sit exactly at the midlines.
268 assert_eq!([px(&img, 3, 3), px(&img, 4, 3), px(&img, 3, 4), px(&img, 4, 4)], [top_left, top_right, bottom_left, bottom_right]);
269
270 let (_, rgba) = render(&c, "Flipped", 0.0).unwrap();
271 let img = (rgba, 8);
272 // Flip swaps A and B: B (blue, half alpha) now bottom-left & top-right, A (red) top-left & bottom-right.
273 assert_eq!(px(&img, 0, 0), [255, 0, 0, 255]);
274 assert_eq!(px(&img, 7, 7), [255, 0, 0, 255]);
275 assert_eq!(px(&img, 7, 0), [0, 0, 255, 128]);
276 assert_eq!(px(&img, 0, 7), [0, 0, 255, 128]);
277
278 assert_eq!(render(&c, "Odd", 0.0).unwrap().0, [32, 32]);
279 assert_eq!(render(&c, "Floor", 0.0).unwrap().0, [2, 2]);
280 }
281
282 #[test]
283 fn alpha_weighted_noise_thresholds_alpha_and_unpremultiplies_without_nan() {
284 let tools = [
285 bg("Clear", 64, "TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0, },"),
286 bg("Solid", 64, "TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 1, },"),
287 bg("Half", 64, "TopLeftRed = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 0.5, },"),
288 r#"ClearNoise = Fuse.AlphaWeightedNoise { Inputs = {
289 Image = Input { SourceOp = "Clear", Source = "Output", },
290 Lift = Input { Value = 1, },
291 }, },
292 SolidNoise = Fuse.AlphaWeightedNoise { Inputs = { Image = Input { SourceOp = "Solid", Source = "Output", }, }, },
293 SolidGone = Fuse.AlphaWeightedNoise { Inputs = {
294 Image = Input { SourceOp = "Solid", Source = "Output", },
295 Gain = Input { Value = 0, },
296 }, },
297 HalfA = Fuse.AlphaWeightedNoise { Inputs = { Image = Input { SourceOp = "Half", Source = "Output", }, }, },
298 HalfAgain = Fuse.AlphaWeightedNoise { Inputs = { Input = Input { SourceOp = "Half", Source = "Output", }, }, },
299 HalfB = Fuse.AlphaWeightedNoise { Inputs = {
300 Image = Input { SourceOp = "Half", Source = "Output", },
301 RandomSeed = Input { Value = 7, },
302 }, },
303 HalfBright = Fuse.AlphaWeightedNoise { Inputs = {
304 Image = Input { SourceOp = "Half", Source = "Output", },
305 Lift = Input { Value = 0.25, },
306 }, },
307 NoInput = Fuse.AlphaWeightedNoise { },"#
308 .to_string(),
309 ]
310 .concat();
311 let c = comp(&tools);
312 let Some((_, clear)) = render(&c, "ClearNoise", 0.0) else { return };
313 assert!(clear.chunks(4).all(|p| p == [0, 0, 0, 255]), "alpha 0 -> 1 has no color to recover, so rgb is 0 rather than NaN");
314 assert!(render(&c, "SolidNoise", 0.0).unwrap().1.chunks(4).all(|p| p == [128, 0, 0, 255]));
315 assert!(render(&c, "SolidGone", 0.0).unwrap().1.chunks(4).all(|p| p == [0, 0, 0, 0]));
316
317 let coverage = |name| {
318 let (_, px) = render(&c, name, 0.0).unwrap();
319 let opaque = px.chunks(4).filter(|p| p[3] == 255).count();
320 assert!(px.chunks(4).all(|p| p == [0, 0, 0, 0] || p[3] == 255), "{name}: alpha is binary");
321 assert!(px.chunks(4).filter(|p| p[3] == 255).all(|p| p[0] == 128), "{name}: rgb / alpha restored");
322 opaque as f32 / 4096.0
323 };
324 assert!((coverage("HalfA") - 0.5).abs() < 0.05);
325 assert!((coverage("HalfBright") - 0.75).abs() < 0.05);
326 let a = render(&c, "HalfA", 0.0).unwrap().1;
327 assert_eq!(a, render(&c, "HalfA", 1.0).unwrap().1, "deterministic");
328 assert_eq!(a, render(&c, "HalfAgain", 0.0).unwrap().1, "`Input` is the fallback main port");
329 assert_ne!(a, render(&c, "HalfB", 0.0).unwrap().1, "seed changes the pattern");
330 assert_eq!(render(&c, "NoInput", 0.0).unwrap().0, [1, 1]);
331 }
332
333 fn crystallize_comp(input: &str, crystal: &str) -> Comp {
334 comp(&format!(
335 r#"{} Crystal = Fuse.Crystallize {{ Inputs = {{
336 Input = Input {{ SourceOp = "Src", Source = "Output", }},
337 Size = Input {{ Value = 0.125, }},
338 Smooth = Input {{ Value = 0, }},
339 Feathering = Input {{ Value = 0, }},
340 Jitter = Input {{ Value = 0, }},
341 Blades = Input {{ Value = 1, }},
342 {crystal}
343 }}, }},"#,
344 bg("Src", 64, input)
345 ))
346 }
347
348 const H_RAMP: &str = "Type = Input { Value = \"Horizontal\", }, TopRightRed = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, },";
349 const V_RAMP: &str = "Type = Input { Value = \"Vertical\", }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, },";
350
351 #[test]
352 fn crystallize_samples_facet_homes_in_fusion_y_up_pixels() {
353 // 8 px cells, jitter 0: every pixel takes the ramp value at the center of a nearby cell.
354 for (ramp, horizontal) in [(H_RAMP, true), (V_RAMP, false)] {
355 let c = crystallize_comp(ramp, "");
356 let Some((size, rgba)) = render(&c, "Crystal", 0.0) else { return };
357 assert_eq!(size, [64, 64]);
358 let img = (rgba, 64);
359 let mut input = std::collections::HashSet::new();
360 for y in 12..52 {
361 for x in 12..52 {
362 let r = f32::from(px(&img, x, y)[0]) / 255.0;
363 // Fusion y is up: the vertical ramp is 1 at the top row.
364 let ramp_at = if horizontal { (x as f32 + 0.5) / 64.0 } else { 1.0 - (y as f32 + 0.5) / 64.0 };
365 assert!((r - ramp_at).abs() < 0.2, "({x},{y}) {r} vs {ramp_at}");
366 let cell_center = r * 8.0 - 0.5;
367 assert!((cell_center - cell_center.round()).abs() < 0.05, "({x},{y}) {r} is not a cell center");
368 input.insert((r * 255.0).round() as u8);
369 }
370 }
371 assert!(input.len() > 3 && input.len() <= 8, "{} distinct facets", input.len());
372 }
373 }
374
375 #[test]
376 fn crystallize_seed_seethe_and_blades_change_the_facets() {
377 let render_with = |extra: &str, time: f64| {
378 let c = crystallize_comp(H_RAMP, &format!("Jitter = Input {{ Value = 1, }}, SeetheRate = Input {{ Value = 0, }}, {extra}"));
379 render(&c, "Crystal", time).map(|r| r.1)
380 };
381 let Some(base) = render_with("", 0.0) else { return };
382 assert_eq!(base, render_with("", 5.0).unwrap(), "SeetheRate 0 ignores time");
383 assert_ne!(base, render_with("RandomSeed = Input { Value = 3, },", 0.0).unwrap());
384 assert_ne!(base, render_with("Seethe = Input { Value = 0.3, },", 0.0).unwrap());
385 assert_ne!(base, render_with("Blades = Input { Value = 3, },", 0.0).unwrap());
386
387 let c = crystallize_comp(H_RAMP, "SeetheRate = Input { Value = 0.1, },");
388 assert_ne!(render(&c, "Crystal", 0.0).unwrap().1, render(&c, "Crystal", 5.0).unwrap().1, "phase = seethe + rate * time");
389 }
390
391 #[test]
392 fn crystallize_feathering_blends_neighbouring_facets_and_smooth_averages_the_source() {
393 let c = crystallize_comp(H_RAMP, "");
394 let hard = render(&c, "Crystal", 0.0).unwrap().1;
395 let c = crystallize_comp(H_RAMP, "Feathering = Input { Value = 1, },");
396 let feathered = render(&c, "Crystal", 0.0).unwrap().1;
397 let distinct = |p: &[u8]| p.chunks(4).map(|p| p[0]).collect::<std::collections::HashSet<_>>().len();
398 assert!(distinct(&feathered) > distinct(&hard) * 2, "feathering mixes facet colors");
399
400 // Per-pixel alpha noise: facets sampling one texel stay binary-ish, Smooth averages a facet's worth.
401 let noisy = |smooth| {
402 comp(&format!(
403 r#"{}
404 Noise = Fuse.AlphaWeightedNoise {{ Inputs = {{ Image = Input {{ SourceOp = "Half", Source = "Output", }}, }}, }},
405 Crystal = Fuse.Crystallize {{ Inputs = {{
406 Input = Input {{ SourceOp = "Noise", Source = "Output", }},
407 Size = Input {{ Value = 0.125, }},
408 Smooth = Input {{ Value = {smooth}, }},
409 }}, }},"#,
410 bg("Half", 64, "TopLeftAlpha = Input { Value = 0.5, },")
411 ))
412 };
413 let spread = |smooth| {
414 let a: Vec<f32> = render(&noisy(smooth), "Crystal", 0.0).unwrap().1.chunks(4).map(|p| f32::from(p[3]) / 255.0).collect();
415 let mean = a.iter().sum::<f32>() / a.len() as f32;
416 a.iter().map(|v| (v - mean).powi(2)).sum::<f32>() / a.len() as f32
417 };
418 assert!(spread(1) * 3.0 < spread(0), "smooth {} vs raw {}", spread(1), spread(0));
419 }
420
421 #[test]
422 fn crystallize_preserves_flat_images_and_requires_an_input() {
423 let c = comp(&format!(
424 r#"{} Crystal = Fuse.Crystallize {{ Inputs = {{ Input = Input {{ SourceOp = "Src", Source = "Output", }}, }}, }}, Bare = Fuse.Crystallize {{ }},"#,
425 bg("Src", 32, "TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 1, },")
426 ));
427 let Some((size, rgba)) = render(&c, "Crystal", 2.0) else { return };
428 assert_eq!(size, [32, 32]);
429 assert!(rgba.chunks(4).all(|p| p == [128, 64, 0, 255]), "default Smooth/Feathering keep a flat field flat");
430 assert_eq!(render(&c, "Bare", 0.0).unwrap().0, [1, 1]);
431 }
432}
crates/engine/src/eval/mod.rs+9-3
......@@ -15,6 +15,7 @@ mod composite;
1515mod transform;
1616mod color;
1717mod blur_glow;
18mod fuses;
1819mod keyers;
1920mod masks;
2021mod paint;
......@@ -589,6 +590,10 @@ impl Engine {
589590 "GridWarp" => self.eval_grid_warp(comp, node, time, frame_i, enc, visiting, stats),
590591 "Fuse.Duplicate" => self.eval_duplicate(comp, node, time, frame_i, enc, visiting, stats),
591592 "Fuse.KScope" => self.eval_kscope(comp, node, time, frame_i, enc, visiting, stats),
593 "Fuse.SwitchElse" => self.eval_switch_else(comp, node, time, enc, visiting, stats),
594 "Fuse.CheckerPieceGenerator" => self.eval_checker_piece(comp, node, time, frame_i, enc, stats),
595 "Fuse.AlphaWeightedNoise" => self.eval_alpha_weighted_noise(comp, node, time, frame_i, enc, visiting, stats),
596 "Fuse.Crystallize" => self.eval_crystallize(comp, node, time, frame_i, enc, visiting, stats),
592597 "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
593598 "sNGon"
594599 | "sRectangle"
......@@ -709,7 +714,8 @@ mod lazy_shader_verify {
709714 ShaderOp::UltraKeyer, ShaderOp::Dissolve, ShaderOp::Homography, ShaderOp::ShadowComp,
710715 ShaderOp::Plasma, ShaderOp::FilmGrain, ShaderOp::SetDomain, ShaderOp::ChangeDepth,
711716 ShaderOp::Vortex, ShaderOp::KScope, ShaderOp::Drip, ShaderOp::Dent,
712 ShaderOp::PerspectivePos, ShaderOp::DaySky, ShaderOp::GridWarp,
717 ShaderOp::PerspectivePos, ShaderOp::DaySky, ShaderOp::GridWarp, ShaderOp::CheckerPiece,
718 ShaderOp::AlphaWeightedNoise, ShaderOp::Crystallize,
713719 ];
714720 // Verify starts completely empty (lazy!)
715721 assert_eq!(eng.pipelines.borrow().modules.len(), 0);
......@@ -719,9 +725,9 @@ mod lazy_shader_verify {
719725 eng.pipelines_for(BitDepth::Float16).borrow_mut().ensure_pipeline(&eng.device, op);
720726 }
721727 assert_eq!(eng.pipelines.borrow().modules.len(), 7);
722 assert_eq!(eng.pipelines.borrow().pipelines.len(), 47);
728 assert_eq!(eng.pipelines.borrow().pipelines.len(), 50);
723729 assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().modules.len(), 7);
724 assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 47);
730 assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 50);
725731 }
726732
727733 #[test]
crates/engine/src/eval/registry.rs+14-3
......@@ -89,6 +89,9 @@ pub(super) enum ShaderOp {
8989 PerspectivePos,
9090 DaySky,
9191 GridWarp,
92 CheckerPiece,
93 AlphaWeightedNoise,
94 Crystallize,
9295}
9396
9497impl ShaderOp {
......@@ -142,9 +145,14 @@ impl ShaderOp {
142145 | Self::UltraKeyer
143146 | Self::Plasma => ShaderDomain::KeyersGen,
144147
145 Self::Drip | Self::Dent | Self::PerspectivePos | Self::DaySky | Self::GridWarp => {
146 ShaderDomain::ArchiveFx
147 }
148 Self::Drip
149 | Self::Dent
150 | Self::PerspectivePos
151 | Self::DaySky
152 | Self::GridWarp
153 | Self::CheckerPiece
154 | Self::AlphaWeightedNoise
155 | Self::Crystallize => ShaderDomain::ArchiveFx,
148156 }
149157 }
150158
......@@ -197,6 +205,9 @@ impl ShaderOp {
197205 Self::PerspectivePos => "perspective_pos_op",
198206 Self::DaySky => "day_sky_op",
199207 Self::GridWarp => "grid_warp_op",
208 Self::CheckerPiece => "checker_piece_op",
209 Self::AlphaWeightedNoise => "alpha_weighted_noise_op",
210 Self::Crystallize => "crystallize_op",
200211 }
201212 }
202213}
crates/engine/src/shaders/archive_fx.wgsl+95
......@@ -228,3 +228,98 @@ fn grid_warp_op(@builtin(global_invocation_id) gid: vec3<u32>) {
228228 let m = read_mask(gid.xy, dims, u.p[0].y, u.p[0].z) * u.p[0].x;
229229 store_dst(vec2<i32>(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0)));
230230}
231
232// ============================================================================
233// Fuses: CheckerPieceGenerator, AlphaWeightedNoise, Crystallize
234// ============================================================================
235
236// 6. CheckerPieceGenerator: nearest-neighbor 2x2 board, color A at bottom-left & top-right.
237// p[0] = color A (rgba), p[1] = color B (rgba); Flip is pre-applied by swapping A/B.
238@compute @workgroup_size(8, 8)
239fn checker_piece_op(@builtin(global_invocation_id) gid: vec3<u32>) {
240 let dims = textureDimensions(dst_tex);
241 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
242 let right = gid.x * 2u >= dims.x;
243 let bottom = gid.y * 2u >= dims.y; // texture row 0 is the top
244 store_dst(vec2<i32>(gid.xy), select(u.p[1], u.p[0], right != bottom));
245}
246
247fn pcg_hash(v: u32) -> u32 {
248 let s = v * 747796405u + 2891336453u;
249 let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
250 return (w >> 22u) ^ w;
251}
252
253// 7. AlphaWeightedNoise: alpha becomes 0 or 1 with probability `a * gain + lift`.
254// p[0] = (seed, gain, lift, 0)
255@compute @workgroup_size(8, 8)
256fn alpha_weighted_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {
257 let dims = textureDimensions(dst_tex);
258 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
259 let src = textureLoad(src_a, vec2<i32>(gid.xy), 0);
260 let rnd = f32(pcg_hash(gid.x + pcg_hash(gid.y + pcg_hash(u32(u.p[0].x)))) >> 8u) / 16777216.0;
261 let new_a = select(0.0, 1.0, rnd < src.a * u.p[0].y + u.p[0].z);
262 let rgb = select(vec3<f32>(0.0), src.rgb / src.a * new_a, src.a > 1e-6 && new_a > 0.5);
263 store_dst(vec2<i32>(gid.xy), vec4<f32>(rgb, new_a));
264}
265
266fn crystal_hash(c: vec2<f32>, n: f32) -> f32 {
267 let h = sin(c.x * 127.1 + c.y * 311.7 + n * 74.7) * 43758.5453;
268 return h - floor(h);
269}
270
271// A facet is the union of the Voronoi regions of `blades` seeds spun rigidly about a fixed home.
272fn crystal_facet_distance(p: vec2<f32>, c: vec2<f32>, home: vec2<f32>, phase: f32, n: f32, blades: i32) -> f32 {
273 let a = 6.2831853 * (crystal_hash(c, n + 2.0) + phase) / f32(blades);
274 let r = 0.12 + 0.13 * crystal_hash(c, n + 3.0);
275 var d = 1e9;
276 for (var k = 0; k < blades; k = k + 1) {
277 let ak = a + 6.2831853 * f32(k) / f32(blades);
278 let v = home + r * vec2<f32>(cos(ak), sin(ak)) - p;
279 d = min(d, length(v));
280 }
281 return d;
282}
283
284// 8. Crystallize (port of Crystallize.fuse's CrystallizeKernel; Fusion pixel coords are bottom-up).
285// p[0] = (size_px, feather, phase, seed)
286// p[1] = (jitter, blades, dod_origin_x, dod_origin_y) origin is top-down canvas pixels
287// p[2].x = canvas height
288@compute @workgroup_size(8, 8)
289fn crystallize_op(@builtin(global_invocation_id) gid: vec3<u32>) {
290 let dims = textureDimensions(dst_tex);
291 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
292 let size = u.p[0].x;
293 let feather = u.p[0].y;
294 let phase = u.p[0].z;
295 let seed = u.p[0].w;
296 let jitter = u.p[1].x;
297 let blades = i32(u.p[1].y);
298 let fdims = vec2<f32>(dims);
299 let origin = vec2<f32>(u.p[1].z, u.p[2].x - u.p[1].w - fdims.y);
300 let px = vec2<f32>(f32(gid.x), fdims.y - 1.0 - f32(gid.y));
301 let p = (px + origin + 0.5) / size;
302 let cell = floor(p);
303
304 var homes: array<vec2<f32>, 25>;
305 var dist: array<f32, 25>;
306 var dmin = 1e9;
307 for (var i = 0; i < 25; i = i + 1) {
308 let c = cell + vec2<f32>(f32(i % 5 - 2), f32(i / 5 - 2));
309 homes[i] = c + 0.5 + jitter * (vec2<f32>(crystal_hash(c, seed), crystal_hash(c, seed + 1.0)) - 0.5);
310 dist[i] = crystal_facet_distance(p, c, homes[i], phase, seed, blades);
311 dmin = min(dmin, dist[i]);
312 }
313
314 var acc = vec4<f32>(0.0);
315 var total = 0.0;
316 for (var i = 0; i < 25; i = i + 1) {
317 let w = exp((dmin - dist[i]) / feather);
318 if (w > 0.001) {
319 let uv = (homes[i] * size - origin) / fdims;
320 acc = acc + w * textureSampleLevel(src_a, samp_lin, vec2<f32>(uv.x, 1.0 - uv.y), 0.0);
321 total = total + w;
322 }
323 }
324 store_dst(vec2<i32>(gid.xy), acc / total);
325}
crates/model/src/comp.rs+6-2
......@@ -89,6 +89,7 @@ pub fn is_supported_tool(kind: &str) -> bool {
8989 | "TimeSpeed"
9090 | "Switch"
9191 | "Fuse.Switch"
92 | "Fuse.SwitchElse"
9293 | "Note"
9394 | "Underlay"
9495 | "StickyNote"
......@@ -138,6 +139,9 @@ pub fn is_supported_tool(kind: &str) -> bool {
138139 | "GridWarp"
139140 | "Fuse.Duplicate"
140141 | "Fuse.KScope"
142 | "Fuse.AlphaWeightedNoise"
143 | "Fuse.CheckerPieceGenerator"
144 | "Fuse.Crystallize"
141145 // 2D vector shape pipeline
142146 | "sRender"
143147 | "sNGon"
......@@ -606,12 +610,12 @@ pub fn default_main_input_port(kind: &str) -> &'static str {
606610 "Merge" | "Dissolve" | "ChannelBoolean" => "Background",
607611 "BitmapMask" => "Image",
608612 "Switch" => "Input0",
609 "Fuse.Switch" => "Input1",
613 "Fuse.Switch" | "Fuse.SwitchElse" => "Input1",
610614 "Merge3D" => "SceneInput1",
611615 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D"
612616 | "Displace3D" | "Duplicate3D" => "SceneInput",
613617 "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput",
614 "Fuse.Colorize" | "Fuse.Outline" => "Image",
618 "Fuse.Colorize" | "Fuse.Outline" | "Fuse.AlphaWeightedNoise" => "Image",
615619 "Custom" => "Image1",
616620 "MacroOperator" | "GroupOperator" => "MainInput1",
617621 _ => "Input",
crates/model/src/comp/eval.rs+53
......@@ -142,6 +142,12 @@ impl Comp {
142142 if let Some(sp) = self.splines.get(src) {
143143 return sp.eval(time);
144144 }
145 if binding.source_output.as_deref() == Some("ExtraScale") {
146 let checker = self.find_node(src).map(|id| self.node(id));
147 if let Some(checker) = checker.filter(|n| n.kind == "Fuse.CheckerPieceGenerator") {
148 return self.checker_piece_metrics_at(checker, time, expr_engine, depth + 1).1;
149 }
150 }
145151 if let Some(sh) = self.shakes.get(src) {
146152 let axis = match binding.source_output.as_deref() {
147153 Some("Y") => 1,
......@@ -170,6 +176,20 @@ impl Comp {
170176 .unwrap_or(default)
171177 }
172178
179 /// `(size, extra_scale)` of a `Fuse.CheckerPieceGenerator`: the even tile edge in pixels and the
180 /// factor that scales it back to the exact `Width / Repeat` (its `ExtraScale` output).
181 pub fn checker_piece_metrics(&self, node: &Node, time: f64, expr_engine: &ExprEngine) -> (u32, f64) {
182 self.checker_piece_metrics_at(node, time, expr_engine, 0)
183 }
184
185 fn checker_piece_metrics_at(&self, node: &Node, time: f64, expr_engine: &ExprEngine, depth: usize) -> (u32, f64) {
186 let width = self.eval_number_at(node, "Width", time, f64::from(self.width), expr_engine, depth);
187 let repeats = self.eval_number_at(node, "Repeat", time, 10.0, expr_engine, depth).max(1.0);
188 let precise = width / repeats;
189 let size = ((precise / 2.0).floor() * 2.0).max(2.0);
190 (size as u32, precise / size)
191 }
192
173193 /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`.
174194 pub fn eval_point(
175195 &self,
......@@ -825,4 +845,37 @@ mod tests {
825845 let echo = comp.node(comp.find_node("Echo").unwrap());
826846 assert_eq!(comp.eval_number(echo, "Width", 0.0, -1.0, &engine), 13.0);
827847 }
848 #[test]
849 fn checker_piece_extra_scale_output_feeds_number_inputs() {
850 let src = r#"Composition {
851 Tools = ordered() {
852 Checker = Fuse.CheckerPieceGenerator { Inputs = {
853 Width = Input { Value = 100, },
854 Repeat = Input { Value = 3, },
855 }, },
856 Default = Fuse.CheckerPieceGenerator { },
857 Tiny = Fuse.CheckerPieceGenerator { Inputs = {
858 Width = Input { Value = 4, },
859 Repeat = Input { Value = 10, },
860 }, },
861 M = Merge { Inputs = {
862 Size = Input { SourceOp = "Checker", Source = "ExtraScale", },
863 Blend = Input { SourceOp = "Default", Source = "ExtraScale", },
864 Angle = Input { SourceOp = "Tiny", Source = "Output", },
865 }, },
866 }
867 }"#;
868 let mut comp = Comp::from_fusion_str(src).unwrap();
869 comp.width = 1920;
870 let engine = ExprEngine::new();
871 let m = comp.node(comp.find_node("M").unwrap());
872 let node = |n| comp.node(comp.find_node(n).unwrap());
873
874 assert_eq!(comp.checker_piece_metrics(node("Checker"), 0.0, &engine).0, 32);
875 assert!((comp.eval_number(m, "Size", 0.0, 1.0, &engine) - 100.0 / 3.0 / 32.0).abs() < 1e-12);
876 assert_eq!(comp.checker_piece_metrics(node("Default"), 0.0, &engine), (192, 1.0));
877 assert_eq!(comp.eval_number(m, "Blend", 0.0, 0.0, &engine), 1.0);
878 assert_eq!(comp.checker_piece_metrics(node("Tiny"), 0.0, &engine), (2, 0.2));
879 assert_eq!(comp.eval_number(m, "Angle", 0.0, 7.0, &engine), 7.0, "non-ExtraScale outputs stay unresolved");
880 }
828881}