1//! Fusion-style node handles: a square output on every node's right edge and role-coloured
2//! input triangles that rotate onto whichever edge faces their upstream node.
3
4use super::*;
5use model::Node;
6
7/// Below this zoom handles are neither drawn nor hit.
8pub(crate) const HANDLE_MIN_ZOOM: f32 = 0.36;
9const HIT_IN: f32 = 9.0;
10const HIT_OUT: f32 = 10.0;
11/// Pointer this deep inside a node border grabs the node, never a handle.
12const BODY_INSET: f32 = 3.0;
13/// A wire dropped this close to a node body lands on its auto-picked port.
14const DROP_MARGIN: f32 = 6.0;
15const STUB: f32 = 6.0;
16
17const YELLOW: [f32; 4] = [0.91, 0.77, 0.23, 1.0];
18const GREEN: [f32; 4] = [0.42, 0.75, 0.23, 1.0];
19const BLUE: [f32; 4] = [0.23, 0.63, 0.91, 1.0];
20pub(crate) const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0];
21const PURPLE: [f32; 4] = [0.72, 0.50, 0.92, 1.0];
22
23static SCENE_INPUTS: [&str; 32] = [
24 "SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4", "SceneInput5", "SceneInput6", "SceneInput7", "SceneInput8",
25 "SceneInput9", "SceneInput10", "SceneInput11", "SceneInput12", "SceneInput13", "SceneInput14", "SceneInput15", "SceneInput16",
26 "SceneInput17", "SceneInput18", "SceneInput19", "SceneInput20", "SceneInput21", "SceneInput22", "SceneInput23", "SceneInput24",
27 "SceneInput25", "SceneInput26", "SceneInput27", "SceneInput28", "SceneInput29", "SceneInput30", "SceneInput31", "SceneInput32",
28];
29
30static INPUTS: [&str; 33] = [
31 "Input0", "Input1", "Input2", "Input3", "Input4", "Input5", "Input6", "Input7", "Input8", "Input9", "Input10", "Input11",
32 "Input12", "Input13", "Input14", "Input15", "Input16", "Input17", "Input18", "Input19", "Input20", "Input21", "Input22",
33 "Input23", "Input24", "Input25", "Input26", "Input27", "Input28", "Input29", "Input30", "Input31", "Input32",
34];
35
36/// Screen-pixel handle sizes; two steps so they stay crisp while the node bars scale.
37#[derive(Clone, Copy)]
38pub(crate) struct Metrics {
39 pub tri_len: f32,
40 pub tri_half: f32,
41 pub out_half: f32,
42 out_gap: f32,
43}
44
45impl Metrics {
46 pub(crate) fn at(zoom: f32) -> Self {
47 if zoom >= 0.72 {
48 Self { tri_len: 6.5, tri_half: 3.6, out_half: 2.8, out_gap: 2.2 }
49 } else {
50 Self { tri_len: 4.5, tri_half: 2.6, out_half: 2.0, out_gap: 1.5 }
51 }
52 }
53
54 pub(crate) fn large(zoom: f32) -> bool {
55 zoom >= 0.72
56 }
57
58 pub(crate) fn output_center(self, r: [f32; 4]) -> [f32; 2] {
59 [r[2] + self.out_gap + self.out_half, (r[1] + r[3]) * 0.5]
60 }
61
62 /// Where a wire leaves the output square.
63 pub(crate) fn output_tip(self, r: [f32; 4]) -> [f32; 2] {
64 let c = self.output_center(r);
65 [c[0] + self.out_half, c[1]]
66 }
67}
68
69/// One input triangle of a node, in canvas-local pixels.
70#[derive(Clone, Copy, Debug)]
71pub(crate) struct Slot<'a> {
72 pub port: &'a str,
73 pub color: [f32; 4],
74 pub edge: Edge,
75 /// Triangle tip, flush on the node border.
76 pub tip: [f32; 2],
77 pub src: Option<NodeId>,
78}
79
80impl Slot<'_> {
81 /// Centre of the triangle's base, where the wire attaches.
82 pub(crate) fn base(&self, m: Metrics) -> [f32; 2] {
83 let n = self.edge.normal();
84 [self.tip[0] + n[0] * m.tri_len, self.tip[1] + n[1] * m.tri_len]
85 }
86
87 pub(crate) fn center(&self, m: Metrics) -> [f32; 2] {
88 let n = self.edge.normal();
89 let d = m.tri_len * 0.45;
90 [self.tip[0] + n[0] * d, self.tip[1] + n[1] * d]
91 }
92}
93
94#[derive(Clone, Copy, PartialEq, Eq)]
95enum Class {
96 Generator,
97 TwoInput,
98 Single,
99}
100
101#[derive(Clone, Copy)]
102enum Table {
103 Fixed(&'static [&'static str]),
104 /// Connected ports plus the first free one.
105 Grow(&'static [&'static str]),
106 /// One main input and an `EffectMask`.
107 Masked(&'static str),
108}
109
110fn zero_indexed(n: &Node) -> bool {
111 n.inputs.contains_key("Source") || n.inputs.contains_key("Input0") || !n.inputs.contains_key("Which")
112}
113
114fn table(n: &Node) -> (Table, Class) {
115 use Class::*;
116 match n.kind.as_str() {
117 "Merge" | "Dissolve" | "ChannelBoolean" => (Table::Fixed(&["Background", "Foreground", "EffectMask"]), TwoInput),
118 "Displace" => (Table::Fixed(&["Input", "Foreground", "EffectMask"]), TwoInput),
119 "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask"
120 | "Fuse.CheckerPieceGenerator" => (Table::Fixed(&["EffectMask"]), Generator),
121 "Fuse.SwitchElse" => (Table::Fixed(&["Input1", "Input2", "EffectMask"]), Single),
122 "DeltaKeyer" => (Table::Fixed(&["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]), Single),
123 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => {
124 (Table::Fixed(&["SceneInput"]), Single)
125 }
126 "Merge3D" => (Table::Grow(&SCENE_INPUTS), Single),
127 "sMerge" | "pMerge" | "Fuse.Switch" => (Table::Grow(&INPUTS[1..]), Single),
128 "sBoolean" => (Table::Grow(&INPUTS[1..=2]), Single),
129 "Switch" => (Table::Grow(if zero_indexed(n) { &INPUTS[..] } else { &INPUTS[1..] }), Single),
130 "BitmapMask" => (Table::Fixed(&["Image"]), Single),
131 "ImagePlane3D" | "TextureTransformOperator" => (Table::Fixed(&["MaterialInput"]), Single),
132 "Saver" | "PipeRouter" => (Table::Fixed(&["Input"]), Single),
133 "MacroOperator" | "GroupOperator" => (Table::Fixed(&["MainInput1"]), Single),
134 kind => (Table::Masked(default_main_input_port(kind)), Single),
135 }
136}
137
138/// Port a wire dropped on `n`'s body lands on: the first open main port.
139pub(crate) fn drop_port(n: &Node) -> &'static str {
140 let (table, class) = table(n);
141 let free = |p: &&'static str| n.inputs.get(*p).is_none_or(|b| b.source_op.is_none());
142 match table {
143 Table::Masked(main) => main,
144 Table::Fixed(l) if class == Class::TwoInput => l[..2].iter().find(|p| free(p)).copied().unwrap_or(l[0]),
145 Table::Fixed(l) => l[0],
146 Table::Grow(l) => l.iter().find(|p| free(p)).copied().unwrap_or(l[l.len() - 1]),
147 }
148}
149
150/// Calls `f` for every input port to show on `n`: the declared ports, then any other connected ones.
151fn each_port<'a>(n: &'a Node, table: Table, mut f: impl FnMut(&'a str)) {
152 let connected = |p: &str| n.inputs.get(p).is_some_and(|b| b.source_op.is_some());
153 match table {
154 Table::Fixed(l) => l.iter().for_each(|p| f(p)),
155 Table::Grow(l) => {
156 let mut free_shown = false;
157 for p in l {
158 if connected(p) {
159 f(p);
160 } else if !free_shown {
161 free_shown = true;
162 f(p);
163 }
164 }
165 }
166 Table::Masked(main) => {
167 f(main);
168 f("EffectMask");
169 }
170 }
171 let declared = |p: &str| match table {
172 Table::Fixed(l) | Table::Grow(l) => l.contains(&p),
173 Table::Masked(main) => p == main || p == "EffectMask",
174 };
175 let mut extras: Vec<&str> = n
176 .inputs
177 .iter()
178 .filter(|(p, b)| b.source_op.is_some() && !declared(p))
179 .map(|(p, _)| p.as_str())
180 .collect();
181 extras.sort_unstable();
182 extras.into_iter().for_each(f);
183}
184
185fn port_color(n: &Node, port: &str) -> [f32; 4] {
186 match port {
187 "Input0" | "MaterialInput" => YELLOW,
188 "Input1" if n.kind == "Switch" && zero_indexed(n) => GREEN,
189 "Input1" => YELLOW,
190 "Input2" | "SceneInput2" => GREEN,
191 "GarbageMatte" | "SolidMatte" | "Garbage.Matte" | "Solid.Matte" => GRAY,
192 _ => match PortRole::from_input_name(port) {
193 PortRole::Background => YELLOW,
194 PortRole::Foreground => GREEN,
195 PortRole::Mask => BLUE,
196 PortRole::Scene3D if port == "SceneInput" || port == "SceneInput1" => YELLOW,
197 PortRole::Scene3D => PURPLE,
198 PortRole::Aux => GRAY,
199 },
200 }
201}
202
203/// Fusion's resting side for an input that has no upstream to face.
204fn default_edge(class: Class, role: PortRole) -> Edge {
205 match (class, role) {
206 (Class::TwoInput, PortRole::Foreground) | (Class::Single, PortRole::Mask) => Edge::Top,
207 (Class::TwoInput, PortRole::Mask) => Edge::Bottom,
208 _ => Edge::Left,
209 }
210}
211
212/// Picks the node edge facing vector `(dx, dy)`, biased for the bar's wide aspect.
213pub(crate) fn closest_edge(dx: f32, dy: f32) -> Edge {
214 if dx.abs() * 0.58 >= dy.abs() {
215 if dx >= 0.0 { Edge::Right } else { Edge::Left }
216 } else if dy >= 0.0 {
217 Edge::Bottom
218 } else {
219 Edge::Top
220 }
221}
222
223/// Polyline a wire follows from an output square to an input triangle.
224#[derive(Clone, Copy, Debug)]
225pub(crate) struct Route {
226 pts: [[f32; 2]; 6],
227 len: usize,
228}
229
230impl Route {
231 pub(crate) fn points(&self) -> &[[f32; 2]] {
232 &self.pts[..self.len]
233 }
234}
235
236fn within(p: [f32; 2], r: [f32; 4], margin: f32) -> bool {
237 p[0] >= r[0] - margin && p[0] <= r[2] + margin && p[1] >= r[1] - margin && p[1] <= r[3] + margin
238}
239
240fn dist2(a: [f32; 2], b: [f32; 2]) -> f32 {
241 (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)
242}
243
244/// Liang–Barsky segment/rect overlap.
245pub(crate) fn segment_hits_rect(a: [f32; 2], b: [f32; 2], r: [f32; 4]) -> bool {
246 let d = [b[0] - a[0], b[1] - a[1]];
247 let (mut t0, mut t1) = (0.0_f32, 1.0_f32);
248 for (p, q) in [(-d[0], a[0] - r[0]), (d[0], r[2] - a[0]), (-d[1], a[1] - r[1]), (d[1], r[3] - a[1])] {
249 if p == 0.0 {
250 if q < 0.0 {
251 return false;
252 }
253 } else {
254 let t = q / p;
255 if p < 0.0 { t0 = t0.max(t) } else { t1 = t1.min(t) }
256 if t0 > t1 {
257 return false;
258 }
259 }
260 }
261 true
262}
263
264impl FlowView {
265 pub(crate) fn upstream_of(&self, comp: &Comp, n: &Node, port: &str) -> Option<NodeId> {
266 let src = n.inputs.get(port)?.source_op.as_deref()?;
267 self.scope.resolve(comp, src)
268 }
269
270 /// Calls `f` for each input triangle of `n`, placed on the edge facing its upstream node
271 /// (or Fusion's default side when open) and spread along that edge so none overlap.
272 pub(crate) fn for_each_input<'a>(&self, comp: &Comp, n: &'a Node, mut f: impl FnMut(Slot<'a>)) {
273 let (table, class) = table(n);
274 let m = Metrics::at(self.zoom);
275 let r = self.node_rect_local(n.pos);
276 let (cx, cy) = ((r[0] + r[2]) * 0.5, (r[1] + r[3]) * 0.5);
277
278 // The two right-edge lanes flank the output square; a third crowds onto top/bottom instead.
279 let place = |port: &str, lanes: &mut [bool; 2]| -> (Option<NodeId>, Edge, usize) {
280 let Some(src) = self.upstream_of(comp, n, port) else {
281 return (None, default_edge(class, PortRole::from_input_name(port)), 0);
282 };
283 let sp = comp.node(src).pos;
284 let (dx, dy) = (sp[0] - n.pos[0], sp[1] - n.pos[1]);
285 match closest_edge(dx, dy) {
286 Edge::Right => {
287 let want = usize::from(dy >= 0.0);
288 match [want, 1 - want].into_iter().find(|&l| !lanes[l]) {
289 Some(lane) => {
290 lanes[lane] = true;
291 (Some(src), Edge::Right, lane)
292 }
293 None => (Some(src), if want == 1 { Edge::Bottom } else { Edge::Top }, 0),
294 }
295 }
296 edge => (Some(src), edge, 0),
297 }
298 };
299
300 let mut counts = [0_usize; 4];
301 let mut lanes = [false; 2];
302 each_port(n, table, |port| counts[place(port, &mut lanes).1 as usize] += 1);
303
304 let along = |center: f32, span: f32, i: usize, count: usize| {
305 let pitch = (span / count as f32).max(2.0 * m.tri_half + 1.0);
306 center + (i as f32 - (count as f32 - 1.0) * 0.5) * pitch
307 };
308 let lane_offset = m.out_half + m.tri_half + 1.0;
309 let mut seen = [0_usize; 4];
310 let mut lanes = [false; 2];
311 each_port(n, table, |port| {
312 let (src, edge, lane) = place(port, &mut lanes);
313 let (i, count) = (seen[edge as usize], counts[edge as usize]);
314 seen[edge as usize] += 1;
315 let tip = match edge {
316 Edge::Left => [r[0], along(cy, r[3] - r[1], i, count)],
317 Edge::Top => [along(cx, r[2] - r[0], i, count), r[1]],
318 Edge::Bottom => [along(cx, r[2] - r[0], i, count), r[3]],
319 Edge::Right => [r[2], cy + if lane == 1 { lane_offset } else { -lane_offset }],
320 };
321 f(Slot { port, color: port_color(n, port), edge, tip, src });
322 });
323 }
324
325 pub(crate) fn input_slot<'a>(&self, comp: &Comp, n: &'a Node, port: &str) -> Option<Slot<'a>> {
326 let mut found = None;
327 self.for_each_input(comp, n, |s| {
328 if s.port == port {
329 found = Some(s);
330 }
331 });
332 found
333 }
334
335 /// Straight from output square to input triangle; otherwise an elbow, otherwise a loop over or
336 /// under both nodes, so a wire never cuts through either body.
337 pub(crate) fn wire_route(&self, src_rect: [f32; 4], dst_rect: [f32; 4], slot: &Slot) -> Route {
338 let m = Metrics::at(self.zoom);
339 let p0 = m.output_tip(src_rect);
340 let q0 = slot.base(m);
341 let n = slot.edge.normal();
342 let p1 = [p0[0] + STUB, p0[1]];
343 let q1 = [q0[0] + n[0] * STUB, q0[1] + n[1] * STUB];
344 let inset = |r: [f32; 4]| [r[0] + 1.0, r[1] + 1.0, r[2] - 1.0, r[3] - 1.0];
345 let (sr, dr) = (inset(src_rect), inset(dst_rect));
346 let clear = |r: &Route| r.points().windows(2).all(|s| !segment_hits_rect(s[0], s[1], sr) && !segment_hits_rect(s[0], s[1], dr));
347
348 let straight = Route { pts: [p0, q0, q0, q0, q0, q0], len: 2 };
349 if clear(&straight) {
350 return straight;
351 }
352 let elbow = Route { pts: [p0, p1, [p1[0], q1[1]], q1, q0, q0], len: 5 };
353 if clear(&elbow) {
354 return elbow;
355 }
356 let dcy = (dst_rect[1] + dst_rect[3]) * 0.5;
357 let up = slot.edge == Edge::Top || (slot.edge != Edge::Bottom && slot.tip[1] <= dcy);
358 let margin = m.tri_len + STUB + 3.0;
359 let y = if up { src_rect[1].min(dst_rect[1]) - margin } else { src_rect[3].max(dst_rect[3]) + margin };
360 Route { pts: [p0, p1, [p1[0], y], [q1[0], y], q1, q0], len: 6 }
361 }
362
363 /// Extra pixels around a node's rect that its handles can reach.
364 fn handle_reach(&self, n: &Node) -> f32 {
365 let m = Metrics::at(self.zoom);
366 let r = self.node_rect_local(n.pos);
367 let mut ports = 0_usize;
368 each_port(n, table(n).0, |_| ports += 1);
369 // One edge carrying every port spreads them past the node's shorter side.
370 let spread = (ports.saturating_sub(1) as f32 * (2.0 * m.tri_half + 1.0) - (r[2] - r[0]).min(r[3] - r[1])) * 0.5;
371 HIT_IN + m.tri_len + 4.0 + spread.max(0.0)
372 }
373
374 /// Output square (`None` port) or input triangle under `local`. A node body always wins.
375 pub(crate) fn hit_handle<'a>(&self, comp: &'a Comp, local: [f32; 2]) -> Option<(NodeId, Option<&'a str>)> {
376 if self.zoom < HANDLE_MIN_ZOOM {
377 return None;
378 }
379 let m = Metrics::at(self.zoom);
380 for n in comp.nodes.iter().rev().filter(|n| self.scope.shows(n)) {
381 let r = self.node_rect_local(n.pos);
382 if !within(local, r, self.handle_reach(n).max(HIT_OUT)) {
383 continue;
384 }
385 if within(local, r, -BODY_INSET) {
386 return None;
387 }
388 let d = dist2(local, m.output_center(r));
389 let mut best = (d <= HIT_OUT * HIT_OUT).then_some((d, None));
390 self.for_each_input(comp, n, |s| {
391 let d = dist2(local, s.center(m));
392 if d <= HIT_IN * HIT_IN && best.is_none_or(|(b, _)| d < b) {
393 best = Some((d, Some(s.port)));
394 }
395 });
396 if let Some((_, port)) = best {
397 return Some((n.id, port));
398 }
399 }
400 None
401 }
402
403 /// Port a wire released at `local` lands on: an input triangle, else the auto-picked port of
404 /// the node body underneath.
405 pub(crate) fn hit_drop_target<'a>(&self, comp: &'a Comp, local: [f32; 2]) -> Option<(NodeId, &'a str)> {
406 let m = Metrics::at(self.zoom);
407 for n in comp.nodes.iter().rev().filter(|n| self.scope.shows(n)) {
408 let r = self.node_rect_local(n.pos);
409 if self.zoom >= HANDLE_MIN_ZOOM && within(local, r, self.handle_reach(n)) {
410 let mut best: Option<(f32, &str)> = None;
411 self.for_each_input(comp, n, |s| {
412 let d = dist2(local, s.center(m));
413 if d <= HIT_IN * HIT_IN && best.is_none_or(|(b, _)| d < b) {
414 best = Some((d, s.port));
415 }
416 });
417 if let Some((_, port)) = best {
418 return Some((n.id, port));
419 }
420 }
421 if within(local, r, DROP_MARGIN) {
422 return Some((n.id, drop_port(n)));
423 }
424 }
425 None
426 }
427}
428
429#[cfg(test)]
430mod tests {
431 use super::*;
432
433 fn comp(src: &str) -> Comp {
434 Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ {src} }} }}")).expect("parse comp")
435 }
436
437 fn port(comp: &Comp, name: &str) -> &'static str {
438 drop_port(comp.node(comp.find_node(name).unwrap()))
439 }
440
441 fn view() -> FlowView {
442 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
443 flow.size = [800.0, 600.0];
444 flow
445 }
446
447 fn slots(flow: &FlowView, comp: &Comp, name: &str) -> Vec<(String, Edge, [f32; 2], Option<NodeId>)> {
448 let mut out = Vec::new();
449 flow.for_each_input(comp, comp.node(comp.find_node(name).unwrap()), |s| out.push((s.port.to_owned(), s.edge, s.tip, s.src)));
450 out
451 }
452
453 fn edge_of(slots: &[(String, Edge, [f32; 2], Option<NodeId>)], port: &str) -> Edge {
454 slots.iter().find(|s| s.0 == port).unwrap_or_else(|| panic!("no slot {port}")).1
455 }
456
457 /// Bounding box of the triangle on `edge` with its tip at `tip`.
458 fn tri_box(m: Metrics, edge: Edge, tip: [f32; 2]) -> [f32; 4] {
459 let b = Slot { port: "", color: YELLOW, edge, tip, src: None }.base(m);
460 let (lo, hi) = ([tip[0].min(b[0]), tip[1].min(b[1])], [tip[0].max(b[0]), tip[1].max(b[1])]);
461 if edge.normal()[0] == 0.0 {
462 [lo[0] - m.tri_half, lo[1], hi[0] + m.tri_half, hi[1]]
463 } else {
464 [lo[0], lo[1] - m.tri_half, hi[0], hi[1] + m.tri_half]
465 }
466 }
467
468 fn overlaps(a: [f32; 4], b: [f32; 4]) -> bool {
469 a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]
470 }
471
472 #[test]
473 fn single_input_kinds_use_engine_port_names() {
474 let c = comp(
475 "R = Renderer3D { }, D = Displace { }, CB = ChannelBoolean { }, Dis = Dissolve { },
476 BM = BitmapMask { }, T = Transform3D { }, Plane = ImagePlane3D { }, G = Background { }",
477 );
478 assert_eq!(port(&c, "R"), "SceneInput");
479 assert_eq!(port(&c, "D"), "Input");
480 assert_eq!(port(&c, "CB"), "Background");
481 assert_eq!(port(&c, "Dis"), "Background");
482 assert_eq!(port(&c, "BM"), "Image");
483 assert_eq!(port(&c, "T"), "SceneInput");
484 assert_eq!(port(&c, "Plane"), "MaterialInput");
485 assert_eq!(port(&c, "G"), "EffectMask");
486 }
487
488 #[test]
489 fn body_drops_take_the_first_open_main_port() {
490 let c = comp(
491 r#"A = Background { },
492 M = Merge { Inputs = { Background = Input { SourceOp = "A", Source = "Output" } } },
493 Full = Merge { Inputs = { Background = Input { SourceOp = "A", Source = "Output" },
494 Foreground = Input { SourceOp = "A", Source = "Output" } } },
495 D = Displace { Inputs = { Input = Input { SourceOp = "A", Source = "Output" } } }"#,
496 );
497 assert_eq!(port(&c, "M"), "Foreground");
498 assert_eq!(port(&c, "Full"), "Background");
499 assert_eq!(port(&c, "D"), "Foreground");
500 }
501
502 #[test]
503 fn multi_input_kinds_pick_next_free_port() {
504 let c = comp(
505 r#"A = Background { }, B = Background { },
506 M3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output" } } },
507 M3b = Merge3D { },
508 S = Switch { Inputs = { Input0 = Input { SourceOp = "A", Source = "Output" } } },
509 SW = Switch { Inputs = { Which = Input { Value = 1 } } },
510 SB = sBoolean { Inputs = { Input1 = Input { SourceOp = "A", Source = "Output" } } },
511 SB0 = sBoolean { },
512 FS = Fuse.Switch { }"#,
513 );
514 assert_eq!(port(&c, "M3b"), "SceneInput1");
515 assert_eq!(port(&c, "M3"), "SceneInput2");
516 assert_eq!(port(&c, "S"), "Input1");
517 assert_eq!(port(&c, "SW"), "Input1");
518 assert_eq!(port(&c, "SB"), "Input2");
519 assert_eq!(port(&c, "SB0"), "Input1");
520 assert_eq!(port(&c, "FS"), "Input1");
521 }
522
523 #[test]
524 fn native_switch_without_which_starts_at_input0() {
525 let c = comp("S = Switch { }");
526 assert_eq!(port(&c, "S"), "Input0");
527 }
528
529 #[test]
530 fn unconnected_inputs_rest_on_fusion_sides() {
531 let c = comp("Blur1 = Blur { }, Merge1 = Merge { }, Gen = FastNoise { }, Sv = Saver { }");
532 let flow = view();
533
534 let blur = slots(&flow, &c, "Blur1");
535 assert_eq!(blur.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["Input", "EffectMask"]);
536 assert_eq!((edge_of(&blur, "Input"), edge_of(&blur, "EffectMask")), (Edge::Left, Edge::Top));
537
538 let merge = slots(&flow, &c, "Merge1");
539 assert_eq!(edge_of(&merge, "Background"), Edge::Left);
540 assert_eq!(edge_of(&merge, "Foreground"), Edge::Top);
541 assert_eq!(edge_of(&merge, "EffectMask"), Edge::Bottom);
542
543 assert_eq!(slots(&flow, &c, "Gen").iter().map(|s| (s.0.as_str(), s.1)).collect::<Vec<_>>(), [("EffectMask", Edge::Left)]);
544 assert_eq!(slots(&flow, &c, "Sv").len(), 1);
545 }
546
547 #[test]
548 fn roles_map_to_fusion_colors() {
549 let c = comp(
550 r#"M = Merge { }, S = Switch { }, SB = sBoolean { }, M3 = Merge3D { },
551 B = Blur { Inputs = { GarbageMatte = Input { SourceOp = "M", Source = "Output" } } }"#,
552 );
553 let color = |name: &str, p: &str| port_color(c.node(c.find_node(name).unwrap()), p);
554 assert_eq!(color("M", "Background"), YELLOW);
555 assert_eq!(color("M", "Foreground"), GREEN);
556 assert_eq!(color("M", "EffectMask"), BLUE);
557 assert_eq!((color("S", "Input0"), color("S", "Input1")), (YELLOW, GREEN));
558 assert_eq!((color("SB", "Input1"), color("SB", "Input2")), (YELLOW, GREEN));
559 assert_eq!((color("M3", "SceneInput1"), color("M3", "SceneInput2"), color("M3", "SceneInput3")), (YELLOW, GREEN, PURPLE));
560 assert_eq!(color("B", "GarbageMatte"), GRAY);
561 }
562
563 #[test]
564 fn connected_inputs_face_their_upstream_across_all_quadrants() {
565 let flow = view();
566 // (upstream offset from the Blur, expected edge)
567 let cases: [([f32; 2], Edge); 8] = [
568 ([-110.0, 0.0], Edge::Left),
569 ([-110.0, -55.0], Edge::Left),
570 ([-40.0, -80.0], Edge::Top),
571 ([0.0, -60.0], Edge::Top),
572 ([40.0, 80.0], Edge::Bottom),
573 ([0.0, 60.0], Edge::Bottom),
574 ([110.0, -20.0], Edge::Right),
575 ([110.0, 20.0], Edge::Right),
576 ];
577 for (off, expected) in cases {
578 let c = comp(&format!(
579 r#"Up = Background {{ ViewInfo = OperatorInfo {{ Pos = {{ {}, {} }} }} }},
580 Blur1 = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "Up", Source = "Output" }} }},
581 ViewInfo = OperatorInfo {{ Pos = {{ 0, 0 }} }} }}"#,
582 off[0], off[1]
583 ));
584 let s = slots(&flow, &c, "Blur1");
585 assert_eq!(edge_of(&s, "Input"), expected, "upstream at {off:?}");
586
587 let (up, blur) = (c.find_node("Up").unwrap(), c.find_node("Blur1").unwrap());
588 let (sr, dr) = (flow.node_rect_local(c.node(up).pos), flow.node_rect_local(c.node(blur).pos));
589 let m = Metrics::at(flow.zoom);
590 let slot = flow.input_slot(&c, c.node(blur), "Input").unwrap();
591 let route = flow.wire_route(sr, dr, &slot);
592 let shrink = |r: [f32; 4]| [r[0] + 1.5, r[1] + 1.5, r[2] - 1.5, r[3] - 1.5];
593 for seg in route.points().windows(2) {
594 assert!(!segment_hits_rect(seg[0], seg[1], shrink(sr)), "wire cuts the source body, upstream at {off:?}");
595 assert!(!segment_hits_rect(seg[0], seg[1], shrink(dr)), "wire cuts the consumer body, upstream at {off:?}");
596 }
597
598 let square = {
599 let c = m.output_center(dr);
600 [c[0] - m.out_half, c[1] - m.out_half, c[0] + m.out_half, c[1] + m.out_half]
601 };
602 for (_, edge, tip, _) in &s {
603 assert!(!overlaps(tri_box(m, *edge, *tip), square), "handle on {edge:?} hits the output square, upstream at {off:?}");
604 }
605 }
606 }
607
608 #[test]
609 fn crowded_edges_spread_without_overlap() {
610 let flow = view();
611 let c = comp(
612 r#"A = Background { ViewInfo = OperatorInfo { Pos = { -110, -30 } } },
613 B = Background { ViewInfo = OperatorInfo { Pos = { -110, 0 } } },
614 C = Background { ViewInfo = OperatorInfo { Pos = { -110, 30 } } },
615 R1 = Background { ViewInfo = OperatorInfo { Pos = { 110, 200 } } },
616 R2 = Background { ViewInfo = OperatorInfo { Pos = { 110, 210 } } },
617 R3 = Background { ViewInfo = OperatorInfo { Pos = { 110, 190 } } },
618 M3 = Merge3D {
619 Inputs = {
620 SceneInput1 = Input { SourceOp = "A", Source = "Output" },
621 SceneInput2 = Input { SourceOp = "B", Source = "Output" },
622 SceneInput3 = Input { SourceOp = "C", Source = "Output" },
623 },
624 ViewInfo = OperatorInfo { Pos = { 0, 0 } },
625 },
626 Back = Merge {
627 Inputs = {
628 Background = Input { SourceOp = "R1", Source = "Output" },
629 Foreground = Input { SourceOp = "R2", Source = "Output" },
630 EffectMask = Input { SourceOp = "R3", Source = "Output" },
631 },
632 ViewInfo = OperatorInfo { Pos = { 0, 200 } },
633 }"#,
634 );
635 let m = Metrics::at(flow.zoom);
636 for name in ["M3", "Back"] {
637 let s = slots(&flow, &c, name);
638 for (i, a) in s.iter().enumerate() {
639 for b in &s[i + 1..] {
640 assert!(!overlaps(tri_box(m, a.1, a.2), tri_box(m, b.1, b.2)), "{name}: {} overlaps {}", a.0, b.0);
641 }
642 }
643 }
644 // Three upstreams plus the next free port all stack down the left edge.
645 let m3 = slots(&flow, &c, "M3");
646 assert_eq!(m3.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4"]);
647 assert!(m3.iter().all(|s| s.1 == Edge::Left));
648 assert!(m3.windows(2).all(|w| w[0].2[1] < w[1].2[1]));
649 // A third source on the right spills to top/bottom instead of crowding the output square.
650 let back = slots(&flow, &c, "Back");
651 assert_eq!(back.iter().filter(|s| s.1 == Edge::Right).count(), 2);
652 }
653
654 #[test]
655 fn hit_handle_finds_output_square_and_input_triangles() {
656 let flow = view();
657 let c = comp(
658 r#"Up = Background { ViewInfo = OperatorInfo { Pos = { -110, 0 } } },
659 M = Merge { Inputs = { Background = Input { SourceOp = "Up", Source = "Output" } },
660 ViewInfo = OperatorInfo { Pos = { 0, 0 } } }"#,
661 );
662 let (up, merge) = (c.find_node("Up").unwrap(), c.find_node("M").unwrap());
663 let m = Metrics::at(flow.zoom);
664 let ur = flow.node_rect_local(c.node(up).pos);
665 let mr = flow.node_rect_local(c.node(merge).pos);
666
667 assert_eq!(flow.hit_handle(&c, m.output_center(ur)), Some((up, None)));
668 for (p, want) in [("Background", Edge::Left), ("Foreground", Edge::Top), ("EffectMask", Edge::Bottom)] {
669 let s = flow.input_slot(&c, c.node(merge), p).unwrap();
670 assert_eq!(s.edge, want);
671 assert_eq!(flow.hit_handle(&c, s.center(m)), Some((merge, Some(p))), "{p}");
672 }
673 // A few pixels off the tip still grabs it; deep inside the body never does.
674 let bg = flow.input_slot(&c, c.node(merge), "Background").unwrap();
675 assert_eq!(flow.hit_handle(&c, [bg.tip[0] - 7.0, bg.tip[1] + 2.0]), Some((merge, Some("Background"))));
676 assert_eq!(flow.hit_handle(&c, [(mr[0] + mr[2]) * 0.5, (mr[1] + mr[3]) * 0.5]), None);
677 assert_eq!(flow.hit_handle(&c, [mr[0] + 6.0, (mr[1] + mr[3]) * 0.5]), None);
678 assert_eq!(flow.hit_handle(&c, [0.0, 0.0]), None);
679 }
680}