diff --git a/crates/flow/src/hit.rs b/crates/flow/src/hit.rs index 2f61e29cc7a12ef112327c030535e5c7d3a2e05f..3eaf0e283e43b36df8703782e47c6834a4975093 100644 --- a/crates/flow/src/hit.rs +++ b/crates/flow/src/hit.rs @@ -22,51 +22,6 @@ impl FlowView { [c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh] } - /// Computes auto-wrapped port geometry for a wire `src -> dst` so ports snap to the - /// closest facing sides of each node (Fusion's signature clean multi-directional routing!). - pub(crate) fn wire_endpoints(&self, comp: &Comp, src: NodeId, dst: NodeId, role: PortRole) -> ([f32; 2], Edge, [f32; 2], Edge) { - let sp = comp.node(src).pos; - let dp = comp.node(dst).pos; - let sr = self.node_rect_local(sp); - let dr = self.node_rect_local(dp); - - let dx = dp[0] - sp[0]; - let dy = dp[1] - sp[1]; - // Weight Y slightly more because nodes are wider than tall (~5:1 aspect)! - let out_edge = closest_edge(dx, dy); - let in_edge = closest_edge_for_input(-dx, -dy, role); - - let a = out_edge.point_on_rect(sr, 0.5); - let b = in_edge.point_on_rect(dr, 0.5); - (a, out_edge, b, in_edge) - } - - /// Computes a node's resting output port edge (average direction of its consumers, defaulting to Right). - pub(crate) fn node_output_edge(&self, comp: &Comp, id: NodeId) -> Edge { - let name = &comp.node(id).name; - let sp = comp.node(id).pos; - let mut sx = 0.0_f32; - let mut sy = 0.0_f32; - let mut count = 0; - for other in comp.nodes.iter().filter(|n| self.scope.shows(n)) { - for binding in other.inputs.values() { - if binding.source_op.as_deref() == Some(name.as_str()) { - let dx = other.pos[0] - sp[0]; - let dy = other.pos[1] - sp[1]; - let len = (dx * dx + dy * dy).sqrt().max(1.0); - sx += dx / len; - sy += dy / len; - count += 1; - } - } - } - if count == 0 { - Edge::Right - } else { - closest_edge(sx, sy) - } - } - pub(crate) fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option { for n in comp.nodes.iter().rev() { if !self.scope.shows(n) { continue; } @@ -78,186 +33,26 @@ impl FlowView { None } - pub(crate) fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option { - for n in comp.nodes.iter().rev() { - if !self.scope.shows(n) { continue; } - let r = self.node_rect_local(n.pos); - let edge = self.node_output_edge(comp, n.id); - let nrm = edge.normal(); - let p0 = edge.point_on_rect(r, 0.5); - let p = [p0[0] + nrm[0] * 5.0, p0[1] + nrm[1] * 5.0]; - let dx = local[0] - p[0]; - let dy = local[1] - p[1]; - if dx * dx + dy * dy <= 10.0 * 10.0 { - return Some(n.id); - } - } - None - } - - pub(crate) fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> { - for n in comp.nodes.iter().rev() { - if !self.scope.shows(n) { continue; } - let r = self.node_rect_local(n.pos); - if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 { - return Some((n.id, drop_port(n, local[1] < r[1] + 2.0, local[1] > r[3] - 2.0))); - } - } - None - } - - /// Hit-tests already-connected input port triangles so the user can drag an input off to disconnect/rewire. - pub(crate) fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> { - let hit_r2 = 10.5_f32 * 10.5_f32; - for dst in comp.nodes.iter().rev() { - if !self.scope.shows(dst) { continue; } - for (port, binding) in &dst.inputs { - let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; - let role = PortRole::from_input_name(port); - let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); - let bn = be.normal(); - let center = [b[0] + bn[0] * 4.0, b[1] + bn[1] * 4.0]; - let dx = local[0] - center[0]; - let dy = local[1] - center[1]; - if dx * dx + dy * dy <= hit_r2 { - return Some((dst.id, port.clone(), src_id)); - } - } - } - None - } - pub(crate) fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option) -> Option { let mut best: Option<(f32, WireRef)> = None; for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { if Some(dst.id) == ignore_node { continue; } - for (port, binding) in &dst.inputs { - let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; - if Some(src_id) == ignore_node { - continue; - } - let role = PortRole::from_input_name(port); - let (a, ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); - let d = dist_to_straight_wire(local, a, ae, b, be, self.zoom); + let dr = self.node_rect_local(dst.pos); + self.for_each_input(comp, dst, |slot| { + let Some(src) = slot.src.filter(|&s| Some(s) != ignore_node) else { return }; + let route = self.wire_route(self.node_rect_local(comp.node(src).pos), dr, &slot); + let d = route.points().windows(2).map(|s| dist_to_seg(local, s[0], s[1])).fold(f32::INFINITY, f32::min); if d < 10.0 && best.as_ref().is_none_or(|(bd, _)| d < *bd) { - best = Some(( - d, - WireRef { - src: src_id, - dst: dst.id, - port: port.clone(), - }, - )); + best = Some((d, WireRef { src, dst: dst.id, port: slot.port.to_owned() })); } - } + }); } best.map(|(_, w)| w) } } -const SCENE_INPUTS: [&str; 32] = [ - "SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4", "SceneInput5", "SceneInput6", "SceneInput7", "SceneInput8", - "SceneInput9", "SceneInput10", "SceneInput11", "SceneInput12", "SceneInput13", "SceneInput14", "SceneInput15", "SceneInput16", - "SceneInput17", "SceneInput18", "SceneInput19", "SceneInput20", "SceneInput21", "SceneInput22", "SceneInput23", "SceneInput24", - "SceneInput25", "SceneInput26", "SceneInput27", "SceneInput28", "SceneInput29", "SceneInput30", "SceneInput31", "SceneInput32", -]; - -const INPUTS: [&str; 33] = [ - "Input0", "Input1", "Input2", "Input3", "Input4", "Input5", "Input6", "Input7", "Input8", "Input9", "Input10", "Input11", - "Input12", "Input13", "Input14", "Input15", "Input16", "Input17", "Input18", "Input19", "Input20", "Input21", "Input22", - "Input23", "Input24", "Input25", "Input26", "Input27", "Input28", "Input29", "Input30", "Input31", "Input32", -]; - -/// Port a wire dropped on `n` lands on; `top`/`bottom` are the node's mask/foreground approach bands. -fn drop_port(n: &model::Node, top: bool, bottom: bool) -> &'static str { - let free = |names: &[&'static str]| { - names - .iter() - .copied() - .find(|p| n.inputs.get(*p).is_none_or(|b| b.source_op.is_none())) - .unwrap_or(names[names.len() - 1]) - }; - match n.kind.as_str() { - "Merge" | "Dissolve" | "ChannelBoolean" => { - if top { - "Foreground" - } else if bottom { - "EffectMask" - } else { - "Background" - } - } - "Displace" => { - if top { - "Foreground" - } else if bottom { - "EffectMask" - } else { - "Input" - } - } - "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => { - "SceneInput" - } - "Merge3D" => free(&SCENE_INPUTS), - "sMerge" | "pMerge" => free(&INPUTS[1..]), - "sBoolean" => free(&INPUTS[1..=2]), - "Fuse.Switch" => free(&INPUTS[1..]), - "Switch" => { - let zero_indexed = n.inputs.contains_key("Source") || n.inputs.contains_key("Input0") || !n.inputs.contains_key("Which"); - free(if zero_indexed { &INPUTS[..] } else { &INPUTS[1..] }) - } - "BitmapMask" => "Image", - "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput", - kind if bottom && kind != "PipeRouter" => "EffectMask", - kind => default_main_input_port(kind), - } -} - -/// Picks the closest node edge facing vector `(dx, dy)` accounting for thin rectangular bar aspect. -fn closest_edge(dx: f32, dy: f32) -> Edge { - // Nodes are 84x21 (4:1 aspect), so require a balanced X bias so horizontal rows snap Left/Right - // while vertical stacks naturally snap Top/Bottom! - if dx.abs() * 0.58 >= dy.abs() { - if dx >= 0.0 { Edge::Right } else { Edge::Left } - } else if dy >= 0.0 { - Edge::Bottom - } else { - Edge::Top - } -} - -/// Auto-wraps input port to the closest side facing the producer, gently nudging Mask/FG when needed. -fn closest_edge_for_input(dx_to_src: f32, dy_to_src: f32, role: PortRole) -> Edge { - let primary = closest_edge(dx_to_src, dy_to_src); - match role { - PortRole::Mask => { - // Masks prefer Top/Bottom unless directly horizontal - if dy_to_src.abs() >= dx_to_src.abs() * 0.35 { - if dy_to_src >= 0.0 { Edge::Bottom } else { Edge::Top } - } else { - primary - } - } - _ => primary, - } -} - -fn dist_to_straight_wire(pt: [f32; 2], a: [f32; 2], ae: Edge, b: [f32; 2], be: Edge, zoom: f32) -> f32 { - let stub = (8.0 * zoom).clamp(4.0, 11.0); - let an = ae.normal(); - let bn = be.normal(); - let a_out = [a[0] + an[0] * stub, a[1] + an[1] * stub]; - let b_out = [b[0] + bn[0] * stub, b[1] + bn[1] * stub]; - dist_to_seg(pt, a, a_out) - .min(dist_to_seg(pt, a_out, b_out)) - .min(dist_to_seg(pt, b_out, b)) -} - pub(crate) fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { let ab = [b[0] - a[0], b[1] - a[1]]; let len2 = ab[0] * ab[0] + ab[1] * ab[1]; @@ -269,63 +64,3 @@ pub(crate) fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { let q = [a[0] + ab[0] * t, a[1] + ab[1] * t]; ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() } - -#[cfg(test)] -mod tests { - use super::*; - - fn port(comp: &Comp, name: &str) -> &'static str { - drop_port(comp.node(comp.find_node(name).unwrap()), false, false) - } - - fn comp(src: &str) -> Comp { - Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ {src} }} }}")).expect("parse comp") - } - - #[test] - fn single_input_kinds_use_engine_port_names() { - let c = comp( - "R = Renderer3D { }, D = Displace { }, CB = ChannelBoolean { }, Dis = Dissolve { }, - BM = BitmapMask { }, T = Transform3D { }, Plane = ImagePlane3D { }", - ); - assert_eq!(port(&c, "R"), "SceneInput"); - assert_eq!(port(&c, "D"), "Input"); - assert_eq!(port(&c, "CB"), "Background"); - assert_eq!(port(&c, "Dis"), "Background"); - assert_eq!(port(&c, "BM"), "Image"); - assert_eq!(port(&c, "T"), "SceneInput"); - assert_eq!(port(&c, "Plane"), "MaterialInput"); - let d = c.node(c.find_node("D").unwrap()); - assert_eq!(drop_port(d, true, false), "Foreground"); - assert_eq!(drop_port(d, false, true), "EffectMask"); - let cb = c.node(c.find_node("CB").unwrap()); - assert_eq!(drop_port(cb, true, false), "Foreground"); - } - - #[test] - fn multi_input_kinds_pick_next_free_port() { - let c = comp( - r#"A = Background { }, B = Background { }, - M3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output" } } }, - M3b = Merge3D { }, - S = Switch { Inputs = { Input0 = Input { SourceOp = "A", Source = "Output" } } }, - SW = Switch { Inputs = { Which = Input { Value = 1 } } }, - SB = sBoolean { Inputs = { Input1 = Input { SourceOp = "A", Source = "Output" } } }, - SB0 = sBoolean { }, - FS = Fuse.Switch { }"#, - ); - assert_eq!(port(&c, "M3b"), "SceneInput1"); - assert_eq!(port(&c, "M3"), "SceneInput2"); - assert_eq!(port(&c, "S"), "Input1"); - assert_eq!(port(&c, "SW"), "Input1"); - assert_eq!(port(&c, "SB"), "Input2"); - assert_eq!(port(&c, "SB0"), "Input1"); - assert_eq!(port(&c, "FS"), "Input1"); - } - - #[test] - fn native_switch_without_which_starts_at_input0() { - let c = comp("S = Switch { }"); - assert_eq!(port(&c, "S"), "Input0"); - } -} diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 596b7a0d2215e005b2b23cf25fe85d62a2ca2f30..2927d7e6ebb70e63b00f329f9b584d390d4ebbe8 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -1,6 +1,7 @@ //! Node Flow canvas built on `draw` + `ui`: //! - Sleek thin Fusion-style node bars with colored bottom stripe -//! - Auto-wrapping output/input ports that snap to whichever side faces connected nodes +//! - Fusion handles: output square on the right edge, role-coloured input triangles that rotate toward their upstream node +//! - Drag output -> input triangle (or node body) to wire, drag a connected triangle off to rewire or disconnect //! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal) //! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks //! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert. @@ -8,6 +9,7 @@ mod hit; mod paint; +mod ports; mod scope; use draw::{Glyphs, PathStyle, Primitive}; @@ -61,15 +63,6 @@ impl Edge { Edge::Bottom => [0.0, 1.0], } } - - fn point_on_rect(self, r: [f32; 4], t: f32) -> [f32; 2] { - match self { - Edge::Left => [r[0], r[1] + (r[3] - r[1]) * t], - Edge::Right => [r[2], r[1] + (r[3] - r[1]) * t], - Edge::Top => [r[0] + (r[2] - r[0]) * t, r[1]], - Edge::Bottom => [r[0] + (r[2] - r[0]) * t, r[3]], - } - } } #[derive(Clone, Debug)] @@ -85,12 +78,25 @@ struct ModalTransform { struct WireDrag { src: NodeId, cursor_local: [f32; 2], - /// If hovering a target input port, `(dst, port, creates_cycle)`. - target: Option<(NodeId, &'static str, bool)>, - /// True when dragging an existing connected input off to disconnect/rewire. + target: Option, + /// Set when dragging an existing connected input off to disconnect/rewire. detached_from: Option<(NodeId, String)>, } +#[derive(Clone, Debug)] +struct DropTarget { + node: NodeId, + port: String, + cycle: bool, +} + +/// Handle under the pointer: a node's output square (`port: None`) or one of its input triangles. +#[derive(Clone, Debug, PartialEq, Eq)] +struct HandleId { + node: NodeId, + port: Option, +} + #[derive(Clone, Debug)] struct BoxSelect { start_local: [f32; 2], @@ -172,6 +178,7 @@ pub struct FlowView { pub viewed_nodes: [Option; 2], pub palette: FlowPalette, hovered_node: Option, + hovered_handle: Option, hovered_wire: Option, modal: Option, wire_drag: Option, @@ -197,6 +204,7 @@ impl FlowView { viewed_nodes: [None, None], palette: FlowPalette::from_ui(theme), hovered_node: None, + hovered_handle: None, hovered_wire: None, modal: None, wire_drag: None, @@ -225,6 +233,7 @@ impl FlowView { self.selected.clear(); self.primary = None; self.hovered_node = None; + self.hovered_handle = None; self.hovered_wire = None; self.modal = None; self.wire_drag = None; @@ -271,6 +280,7 @@ impl FlowView { self.selected.extend(select); self.primary = select; self.hovered_node = None; + self.hovered_handle = None; self.hovered_wire = None; self.modal = None; self.wire_drag = None; @@ -298,6 +308,7 @@ impl FlowView { if self.hovered_node.is_some_and(|id| id.0 >= len) { self.hovered_node = None; } + self.hovered_handle = None; self.hovered_wire = None; self.modal = None; self.wire_drag = None; @@ -699,15 +710,17 @@ impl FlowView { ]; } else if self.modal.is_some() { self.apply_modal(comp, modifiers.shift_key()); - } else if let Some(wd) = &mut self.wire_drag { - wd.cursor_local = self.pointer_local; - let src = wd.src; - let target = self.hit_input_port(comp, self.pointer_local).map(|(dst, port)| { - let cycle = comp.would_create_cycle(src, dst); - (dst, port, cycle) - }); - if let Some(wd_mut) = &mut self.wire_drag { - wd_mut.target = target; + } else if self.wire_drag.is_some() { + let hit = self.hit_drop_target(comp, self.pointer_local); + if let Some(wd) = &mut self.wire_drag { + wd.cursor_local = self.pointer_local; + if wd.target.as_ref().map(|t| (t.node, t.port.as_str())) != hit { + wd.target = hit.map(|(node, port)| DropTarget { + node, + port: port.to_owned(), + cycle: comp.would_create_cycle(wd.src, node), + }); + } } } else if let Some(bs) = &mut self.box_select { bs.cur_local = self.pointer_local; @@ -726,7 +739,11 @@ impl FlowView { } } else { self.hovered_node = self.hit_node(comp, self.pointer_local); - self.hovered_wire = if self.hovered_node.is_none() { + let handle = self.hit_handle(comp, self.pointer_local); + if self.hovered_handle.as_ref().map(|h| (h.node, h.port.as_deref())) != handle { + self.hovered_handle = handle.map(|(node, port)| HandleId { node, port: port.map(str::to_owned) }); + } + self.hovered_wire = if self.hovered_node.is_none() && handle.is_none() { self.hit_wire(comp, self.pointer_local, None) } else { None @@ -765,17 +782,23 @@ impl FlowView { } } else if button == MouseButton::Left { if pressed { + let handle = self.hit_handle(comp, self.pointer_local).filter(|_| self.scope.is_root()); if self.modal.is_some() { self.confirm_modal(comp, history, &mut actions); - } else if let Some(src) = self.hit_output_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) { + } else if let Some((src, None)) = handle { self.wire_drag = Some(WireDrag { src, cursor_local: self.pointer_local, target: None, detached_from: None, }); - } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) { - // Dragging an existing input port detaches it so user can drop to disconnect or rewire! + } else if let Some((dst, Some(port), src)) = handle.and_then(|(dst, port)| { + let port = port?; + let src = self.upstream_of(comp, comp.node(dst), port)?; + Some((dst, Some(port.to_owned()), src)) + }) { + // Dragging a connected triangle detaches it: drop on another triangle to move + // the wire, or on empty canvas to disconnect. history.begin_group(comp, "Rewire"); comp.disconnect(dst, &port); actions.push(FlowAction::GraphMutated(Some(dst))); @@ -830,25 +853,28 @@ impl FlowView { } if let Some(wd) = self.wire_drag.take() { let detached = wd.detached_from.is_some(); - if let Some((dst, port)) = self.hit_input_port(comp, self.pointer_local) { - if !detached { - history.begin_group(comp, "Connect"); - } - let result = if comp.would_create_cycle(wd.src, dst) { - Err("Cycle rejected: cannot connect downstream to upstream".to_owned()) - } else { - comp.connect_output(wd.src, "Output", dst, port) - }; - match result { - Ok(()) => { - history.commit_group(comp); + let target = self.hit_drop_target(comp, self.pointer_local).map(|(node, port)| (node, port.to_owned())); + if let Some((dst, port)) = target { + if wd.detached_from.as_ref() == Some(&(dst, port.clone())) { + // Dropped back where it started: nothing changed, leave no undo entry. + if history.cancel_group(comp) { actions.push(FlowAction::GraphMutated(Some(dst))); } - Err(e) => { - if history.cancel_group(comp) && detached { - actions.push(FlowAction::GraphMutated(None)); + } else { + if !detached { + history.begin_group(comp, "Connect"); + } + match comp.connect_output(wd.src, "Output", dst, &port) { + Ok(()) => { + history.commit_group(comp); + actions.push(FlowAction::GraphMutated(Some(dst))); + } + Err(e) => { + if history.cancel_group(comp) && detached { + actions.push(FlowAction::GraphMutated(None)); + } + actions.push(FlowAction::StatusNotice(e)); } - actions.push(FlowAction::StatusNotice(e)); } } } else if let Some((dst, port)) = wd.detached_from { @@ -918,13 +944,13 @@ fn read_only_notice(actions: &mut Vec) { actions.push(FlowAction::StatusNotice("Group contents are read-only; press Esc to leave the group".to_owned())); } -/// Samples a smooth cubic Bezier preview wire leaving `a` along `out_normal` and arriving at `b`. -pub fn sample_preview_bezier(a: [f32; 2], out_normal: [f32; 2], b: [f32; 2], steps: usize) -> Vec<[f32; 2]> { +/// Samples a cubic Bezier wire leaving `a` along `a_normal` and arriving at `b` from the side `b_normal` faces. +pub fn sample_wire_bezier(a: [f32; 2], a_normal: [f32; 2], b: [f32; 2], b_normal: [f32; 2], steps: usize) -> Vec<[f32; 2]> { let steps = steps.max(2); let dist = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt(); let handle = (dist * 0.42).clamp(24.0, 140.0); - let c1 = [a[0] + out_normal[0] * handle, a[1] + out_normal[1] * handle]; - let c2 = [b[0] - out_normal[0] * handle * 0.65, b[1] - out_normal[1] * handle * 0.65]; + let c1 = [a[0] + a_normal[0] * handle, a[1] + a_normal[1] * handle]; + let c2 = [b[0] + b_normal[0] * handle * 0.65, b[1] + b_normal[1] * handle * 0.65]; let mut pts = Vec::with_capacity(steps + 1); for i in 0..=steps { let t = i as f32 / steps as f32; @@ -962,7 +988,7 @@ mod tests { #[test] fn bezier_preview_endpoints_match() { - let pts = sample_preview_bezier([10.0, 20.0], [1.0, 0.0], [210.0, 80.0], 16); + let pts = sample_wire_bezier([10.0, 20.0], [1.0, 0.0], [210.0, 80.0], [-1.0, 0.0], 16); assert_eq!(pts.len(), 17); assert!((pts[0][0] - 10.0).abs() < 1e-4); assert!((pts[0][1] - 20.0).abs() < 1e-4); @@ -994,11 +1020,14 @@ mod tests { let merge_local = flow.world_to_local(comp.node(merge).pos); assert_eq!(flow.hit_node(&comp, merge_local), Some(merge)); - // Top of Merge hits Foreground; bottom hits EffectMask; middle hits Background - let mr = flow.node_rect_local(comp.node(merge).pos); - assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[1] - 2.0]), Some((merge, "Foreground"))); - assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[3] + 2.0]), Some((merge, "EffectMask"))); - assert_eq!(flow.hit_input_port(&comp, merge_local), Some((merge, "Background"))); + // Each triangle drops on its own port; the body picks the first open main port. + let m = ports::Metrics::at(flow.zoom); + for port in ["Background", "Foreground", "EffectMask"] { + let slot = flow.input_slot(&comp, comp.node(merge), port).unwrap(); + assert_eq!(flow.hit_drop_target(&comp, slot.center(m)), Some((merge, port))); + } + assert_eq!(flow.hit_drop_target(&comp, merge_local), Some((merge, "Foreground"))); + assert_eq!(flow.hit_drop_target(&comp, [0.0, 0.0]), None); } #[test] @@ -1243,10 +1272,9 @@ mod tests { flow.size = [800.0, 600.0]; flow.pan = [80.0, 0.0]; flow.zoom = 1.0; - let (bg, merge) = (id(&comp, "BG1"), id(&comp, "Merge1")); - let (_, _, b, be) = flow.wire_endpoints(&comp, bg, merge, PortRole::Background); - let n = be.normal(); - let port = [b[0] + n[0] * 4.0, b[1] + n[1] * 4.0]; + let merge = id(&comp, "Merge1"); + let m = ports::Metrics::at(flow.zoom); + let port = flow.input_slot(&comp, comp.node(merge), "Background").unwrap().center(m); let rect = [0.0, 0.0, 800.0, 600.0]; flow.input( @@ -1267,6 +1295,152 @@ mod tests { assert!(!history.can_undo() && !history.in_group()); } + const WIRE_COMP: &str = r#"Composition { + Tools = ordered() { + BG1 = Background { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, }, + BG2 = Background { ViewInfo = OperatorInfo { Pos = { 0, 80 } }, }, + Merge1 = Merge { + Inputs = { Background = Input { SourceOp = "BG1", Source = "Output" }, }, + ViewInfo = OperatorInfo { Pos = { 160, 0 } }, + }, + Blur1 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 120 } }, }, + }, + }"#; + + fn wire_flow() -> (Comp, FlowView, CompHistory) { + let comp = Comp::from_fusion_str(WIRE_COMP).expect("parse comp"); + let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true)); + flow.size = [800.0, 600.0]; + flow.pan = [80.0, 60.0]; + flow.zoom = 1.0; + (comp, flow, CompHistory::new()) + } + + fn send(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, event: ui::Event, at: [f32; 2]) -> Vec { + flow.input(comp, history, event, [0.0, 0.0, 800.0, 600.0], at, ModifiersState::empty()) + } + + fn drag(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, from: [f32; 2], to: [f32; 2]) -> Vec { + let button = |pressed| ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() }; + send(flow, comp, history, ui::Event::PointerMoved(from), from); + send(flow, comp, history, button(true), from); + send(flow, comp, history, ui::Event::PointerMoved(to), to); + send(flow, comp, history, button(false), to) + } + + fn output_center(flow: &FlowView, comp: &Comp, node: NodeId) -> [f32; 2] { + ports::Metrics::at(flow.zoom).output_center(flow.node_rect_local(comp.node(node).pos)) + } + + fn input_center(flow: &FlowView, comp: &Comp, node: NodeId, port: &str) -> [f32; 2] { + flow.input_slot(comp, comp.node(node), port).unwrap().center(ports::Metrics::at(flow.zoom)) + } + + fn source(comp: &Comp, node: NodeId, port: &str) -> Option { + comp.node(node).inputs.get(port).and_then(|b| b.source_op.clone()) + } + + #[test] + fn dragging_an_output_onto_an_input_triangle_wires_that_exact_port() { + let (mut comp, mut flow, mut history) = wire_flow(); + let (bg2, merge) = (id(&comp, "BG2"), id(&comp, "Merge1")); + let (from, to) = (output_center(&flow, &comp, bg2), input_center(&flow, &comp, merge, "EffectMask")); + + let acts = drag(&mut flow, &mut comp, &mut history, from, to); + assert_eq!(source(&comp, merge, "EffectMask").as_deref(), Some("BG2")); + assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1")); + assert!(acts.iter().any(|a| matches!(a, FlowAction::GraphMutated(Some(n)) if *n == merge))); + assert!(flow.wire_drag.is_none()); + assert!(history.undo(&mut comp)); + assert_eq!(source(&comp, merge, "EffectMask"), None); + } + + #[test] + fn dropping_on_a_body_auto_picks_and_highlights_the_open_port() { + let (mut comp, mut flow, mut history) = wire_flow(); + let (bg2, merge, blur) = (id(&comp, "BG2"), id(&comp, "Merge1"), id(&comp, "Blur1")); + let from = output_center(&flow, &comp, bg2); + let body = flow.world_to_local(comp.node(merge).pos); + + let button = |pressed| ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() }; + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(from), from); + send(&mut flow, &mut comp, &mut history, button(true), from); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(body), body); + let target = flow.wire_drag.as_ref().and_then(|wd| wd.target.as_ref()).expect("hover target"); + assert_eq!((target.node, target.port.as_str(), target.cycle), (merge, "Foreground", false)); + send(&mut flow, &mut comp, &mut history, button(false), body); + assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG2")); + + // Single-input tools take their main input. + let (from, body) = (output_center(&flow, &comp, bg2), flow.world_to_local(comp.node(blur).pos)); + drag(&mut flow, &mut comp, &mut history, from, body); + assert_eq!(source(&comp, blur, "Input").as_deref(), Some("BG2")); + } + + #[test] + fn dropping_a_downstream_wire_upstream_is_flagged_as_a_cycle() { + let (mut comp, mut flow, mut history) = wire_flow(); + let (bg1, merge) = (id(&comp, "BG1"), id(&comp, "Merge1")); + let from = output_center(&flow, &comp, merge); + let to = input_center(&flow, &comp, bg1, "EffectMask"); + let acts = drag(&mut flow, &mut comp, &mut history, from, to); + assert!(acts.iter().any(|a| matches!(a, FlowAction::StatusNotice(_)))); + assert_eq!(source(&comp, bg1, "EffectMask"), None); + assert!(!history.can_undo() && !history.in_group()); + } + + #[test] + fn dragging_a_connected_triangle_off_rewires_or_disconnects() { + let (mut comp, mut flow, mut history) = wire_flow(); + let merge = id(&comp, "Merge1"); + let bg_tri = input_center(&flow, &comp, merge, "Background"); + + // Onto another triangle: the wire moves. + let fg_tri = input_center(&flow, &comp, merge, "Foreground"); + drag(&mut flow, &mut comp, &mut history, bg_tri, fg_tri); + assert_eq!(source(&comp, merge, "Background"), None); + assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG1")); + assert_eq!(history.undo_len(), 1); + + // Dragging the moved triangle off onto empty canvas disconnects it. + let fg_tri = input_center(&flow, &comp, merge, "Foreground"); + let acts = drag(&mut flow, &mut comp, &mut history, fg_tri, [700.0, 500.0]); + assert_eq!(source(&comp, merge, "Foreground"), None); + assert!(acts.iter().any(|a| matches!(a, FlowAction::StatusNotice(m) if m.starts_with("Disconnected")))); + assert_eq!(history.undo_len(), 2); + assert!(history.undo(&mut comp)); + assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG1")); + } + + #[test] + fn dropping_a_detached_wire_back_where_it_started_leaves_no_undo_entry() { + let (mut comp, mut flow, mut history) = wire_flow(); + let merge = id(&comp, "Merge1"); + let tri = input_center(&flow, &comp, merge, "Background"); + drag(&mut flow, &mut comp, &mut history, tri, tri); + assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1")); + assert!(!history.can_undo() && !history.in_group()); + } + + #[test] + fn handle_hover_tracks_the_pointer_and_body_clicks_still_select() { + let (mut comp, mut flow, mut history) = wire_flow(); + let (bg1, merge) = (id(&comp, "BG1"), id(&comp, "Merge1")); + let out = output_center(&flow, &comp, bg1); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(out), out); + assert_eq!(flow.hovered_handle, Some(HandleId { node: bg1, port: None })); + let tri = input_center(&flow, &comp, merge, "EffectMask"); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(tri), tri); + assert_eq!(flow.hovered_handle, Some(HandleId { node: merge, port: Some("EffectMask".to_owned()) })); + let body = flow.world_to_local(comp.node(merge).pos); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(body), body); + assert_eq!(flow.hovered_handle, None); + + press(&mut flow, &mut comp, &mut history, Instant::now(), merge); + assert_eq!(flow.primary, Some(merge)); + assert!(flow.wire_drag.is_none()); + } + #[test] fn letter_shortcuts_ignore_ctrl_and_alt() { let (mut comp, mut flow) = group_flow(); diff --git a/crates/flow/src/paint.rs b/crates/flow/src/paint.rs index ded993039627920a6685c2ea8d21e8f96f92c7f7..7020eb9a8359b5d6ca442bc234568a3f7e4d4f81 100644 --- a/crates/flow/src/paint.rs +++ b/crates/flow/src/paint.rs @@ -20,6 +20,12 @@ impl FlowView { weight: 600, italic: false, }; + let port_font = text::Font { + families: Arc::from([text::Family::Sans]), + size: 9.0, + weight: 500, + italic: false, + }; let make_layout = |s: &str, font: &text::Font| { let styles = [text::Style::new(font.clone())]; text::Paragraph { @@ -47,6 +53,15 @@ impl FlowView { self.badge_cache .entry("cycle!".to_owned()) .or_insert_with(|| make_layout("cycle!", &tiny_font)); + let wanted = [ + self.hovered_handle.as_ref().map(|h| h.port.as_deref().unwrap_or("Output")), + self.wire_drag.as_ref().and_then(|wd| wd.target.as_ref()).map(|t| t.port.as_str()), + ]; + for name in wanted.into_iter().flatten() { + if !self.badge_cache.contains_key(name) { + self.badge_cache.insert(name.to_owned(), make_layout(name, &port_font)); + } + } for key in [ HUD_ROOT, HUD_GROUP, @@ -103,122 +118,94 @@ impl FlowView { } } - // 3. Straight Fusion wires + crisp white output squares (□) + inward-pointing colored input arrows (▶)! - let large_ports = self.zoom >= 0.72; - let tri_len = if large_ports { 6.5 } else { 4.5 }; - let out_half = if large_ports { 2.8 } else { 2.0 }; - let out_gap = if large_ports { 2.2 } else { 1.5 }; - let port_outline = [0.04, 0.04, 0.06, 0.92]; + // 3. Output squares (idle gray; wires overpaint connected ones white), straight Fusion wires + // and role-coloured input triangles. + let handles = self.zoom >= ports::HANDLE_MIN_ZOOM; + let m = ports::Metrics::at(self.zoom); + let large = ports::Metrics::large(self.zoom); + let on_screen = |r: [f32; 4]| r[2] >= -24.0 && r[0] <= w + 24.0 && r[3] >= -24.0 && r[1] <= h + 24.0; + let out_hot = |id: NodeId| { + self.wire_drag.as_ref().is_some_and(|wd| wd.src == id) + || self.hovered_handle.as_ref().is_some_and(|hh| hh.node == id && hh.port.is_none()) + }; + let out_fill = |id: NodeId, connected: bool| { + if out_hot(id) { + [0.98, 0.84, 0.30, 1.0] + } else if connected { + [0.96, 0.97, 1.0, 1.0] + } else { + [0.42, 0.44, 0.50, 1.0] + } + }; + if handles { + for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) { + let r = self.node_rect_local(n.pos); + if on_screen(r) { + push_square(&mut out, m.output_center(r), m.out_half, out_fill(n.id, false)); + } + } + } for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { - // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping - let mut used_edges: HashMap = HashMap::new(); - let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect(); - sorted_ports.sort_by_key(|(p, _)| match PortRole::from_input_name(p) { - PortRole::Background => 0u8, - PortRole::Foreground => 1, - PortRole::Mask => 2, - PortRole::Scene3D => 3, - PortRole::Aux => 4, - }); - for (port, binding) in sorted_ports { - let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; - let role = PortRole::from_input_name(port); - let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role); - let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 }; - let count = used_edges.entry(ekey(be)).or_insert(0); - if *count > 0 { - // Spread horizontal top/bottom ports (e.g. FG + Mask) like Fusion's ColorCorrector / Merge - let dr = self.node_rect_local(dst.pos); - if matches!(be, Edge::Top | Edge::Bottom) { - let t = if *count == 1 { 0.25 } else { 0.75 }; - b = be.point_on_rect(dr, t); - } else if role == PortRole::Mask { - be = Edge::Bottom; - b = be.point_on_rect(dr, 0.5); - } else { - let t = if *count == 1 { 0.30 } else { 0.70 }; - b = be.point_on_rect(dr, t); + let dr = self.node_rect_local(dst.pos); + let dst_vis = on_screen(dr); + self.for_each_input(comp, dst, |slot| { + if let Some(src) = slot.src { + let sr = self.node_rect_local(comp.node(src).pos); + let (x0, x1) = (sr[0].min(dr[0]), sr[2].max(dr[2])); + let (y0, y1) = (sr[1].min(dr[1]), sr[3].max(dr[3])); + if x1 >= 0.0 && x0 <= w && y1 >= 0.0 && y0 <= h { + let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src && hw.dst == dst.id && hw.port == slot.port); + let is_sel = self.selected.contains(&src) || self.selected.contains(&dst.id); + let (color, width) = if is_hot { + ([0.98, 0.82, 0.24, 1.0], 2.4) + } else if is_sel { + ([0.92, 0.94, 0.98, 0.96], 1.6) + } else { + ([0.64, 0.66, 0.72, 0.76], 1.1) + }; + for seg in self.wire_route(sr, dr, &slot).points().windows(2) { + out.push(Primitive::Segment { from: seg[0], to: seg[1], width, color }); + } + if handles { + push_square(&mut out, m.output_center(sr), m.out_half, out_fill(src, true)); + } } } - *count += 1; - - let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src_id && hw.dst == dst.id && hw.port == *port); - let is_sel = self.selected.contains(&src_id) || self.selected.contains(&dst.id); - - let wire_col = if is_hot { - [0.98, 0.82, 0.24, 1.0] - } else if is_sel { - [0.92, 0.94, 0.98, 0.96] - } else { - [0.64, 0.66, 0.72, 0.76] - }; - let width = if is_hot { 2.4 } else if is_sel { 1.6 } else { 1.1 }; - let an = ae.normal(); - let bn = be.normal(); - let op = [a[0] + an[0] * (out_gap + out_half), a[1] + an[1] * (out_gap + out_half)]; - let ip_base = [b[0] + bn[0] * tri_len, b[1] + bn[1] * tri_len]; - - // Straight wire directly from output square center to input triangle base (exact Fusion look!) - out.push(Primitive::Segment { from: op, to: ip_base, width, color: wire_col }); - - if self.zoom >= 0.36 { - // Output port: crisp Fusion white square `□` with thin dark outline - out.push(Primitive::RoundedRect { - rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], - radius: 0.6, - stroke: None, - color: [0.94, 0.95, 0.98, 0.98], - }); - out.push(Primitive::RoundedRect { - rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half], - radius: 0.6, - stroke: Some(0.9), - color: port_outline, - }); - - // Input port: crisp Fusion colored triangle pointing INTO `dst`! - let pcol = port_color(role); - let tri = input_arrow_svg(be, large_ports); - out.push(Primitive::Path { - data: tri, - origin: b, - style: PathStyle::Fill, - color: pcol, - }); - out.push(Primitive::Path { - data: tri, - origin: b, - style: PathStyle::Stroke(0.9), - color: port_outline, - }); + if handles && dst_vis { + let target = self.wire_drag.as_ref().and_then(|wd| wd.target.as_ref()).filter(|t| t.node == dst.id && t.port == slot.port); + let hot = target.is_some() || self.hovered_handle.as_ref().is_some_and(|hh| hh.node == dst.id && hh.port.as_deref() == Some(slot.port)); + let tri = input_arrow_svg(slot.edge, large); + let fill = if slot.src.is_some() || hot { slot.color } else { [slot.color[0], slot.color[1], slot.color[2], 0.78] }; + out.push(Primitive::Path { data: tri, origin: slot.tip, style: PathStyle::Fill, color: fill }); + let (outline, outline_w) = match target { + Some(t) if t.cycle => ([0.96, 0.30, 0.34, 1.0], 1.6), + _ if hot => ([1.0, 1.0, 1.0, 1.0], 1.4), + _ => ([0.04, 0.04, 0.06, 0.92], 0.9), + }; + out.push(Primitive::Path { data: tri, origin: slot.tip, style: PathStyle::Stroke(outline_w), color: outline }); } - } + }); } - // Active wire drag preview (smooth cubic bezier + cycle rejection feedback) + // Rubber-band wire from the output square, tinted by the hovered input's role if let Some(wd) = &self.wire_drag { if wd.src.0 < comp.nodes.len() { - let sr = self.node_rect_local(comp.node(wd.src).pos); - let edge = self.node_output_edge(comp, wd.src); - let a = edge.point_on_rect(sr, 0.5); - let (end, is_cycle, target_role) = match wd.target { - Some((dst, port, cycle)) if dst.0 < comp.nodes.len() => { - let role = PortRole::from_input_name(port); - let (_, _, b, _) = self.wire_endpoints(comp, wd.src, dst, role); - (b, cycle, Some(role)) - } - _ => (wd.cursor_local, false, None), + let a = m.output_tip(self.node_rect_local(comp.node(wd.src).pos)); + let slot = wd.target.as_ref().filter(|t| t.node.0 < comp.nodes.len()).and_then(|t| { + self.input_slot(comp, comp.node(t.node), &t.port) + }); + let is_cycle = wd.target.as_ref().is_some_and(|t| t.cycle); + let (end, end_normal) = match &slot { + Some(s) => (s.base(m), s.edge.normal()), + None => (wd.cursor_local, [-1.0, 0.0]), }; - let wire_col = if is_cycle { - [0.96, 0.30, 0.34, 1.0] - } else if let Some(role) = target_role { - port_color(role) - } else { - [0.98, 0.84, 0.30, 1.0] + let wire_col = match &slot { + _ if is_cycle => [0.96, 0.30, 0.34, 1.0], + Some(s) => s.color, + None => [0.98, 0.84, 0.30, 1.0], }; - let pts = sample_preview_bezier(a, edge.normal(), end, 16); + let pts = sample_wire_bezier(a, [1.0, 0.0], end, end_normal, 16); for seg in pts.windows(2) { out.push(Primitive::Segment { from: seg[0], @@ -372,32 +359,23 @@ impl FlowView { } } - // Fusion-style tiny viewer indicator pill underneath bottom-left (`● ○` for Viewer 1 / Viewer 2!) + // Fusion's viewer pill tucked under the bottom-left: left dot = Viewer 1, right dot = Viewer 2. if v1 || v2 { - let pw = 22.0; - let ph = 9.0; - let px = r[0] + 4.0; - let py = r[3] + 1.5; + let (px, py) = (r[0] + 4.0, r[3] + 1.0); out.push(Primitive::RoundedRect { - rect: [px, py, px + pw, py + ph], + rect: [px, py, px + 22.0, py + 9.0], radius: 3.0, stroke: None, color: [0.02, 0.02, 0.03, 0.92], }); - let d1 = if v1 { [0.24, 0.90, 0.82, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; - let d2 = if v2 { [0.98, 0.68, 0.28, 1.0] } else { [0.26, 0.28, 0.34, 0.6] }; - out.push(Primitive::RoundedRect { - rect: [px + 3.5, py + 2.0, px + 8.5, py + 7.0], - radius: 2.5, - stroke: None, - color: d1, - }); - out.push(Primitive::RoundedRect { - rect: [px + 13.0, py + 2.0, px + 18.0, py + 7.0], - radius: 2.5, - stroke: None, - color: d2, - }); + for (dot, lit, color) in [(px + 3.5, v1, [0.24, 0.90, 0.82, 1.0]), (px + 13.0, v2, [0.98, 0.68, 0.28, 1.0])] { + let rect = [dot, py + 2.0, dot + 5.0, py + 7.0]; + if lit { + out.push(Primitive::RoundedRect { rect, radius: 2.5, stroke: None, color }); + } else { + out.push(Primitive::RoundedRect { rect, radius: 2.5, stroke: Some(1.0), color: [0.46, 0.48, 0.55, 0.9] }); + } + } } if n.bypassed { @@ -411,6 +389,36 @@ impl FlowView { } } + // Port-name label for the hovered handle or wire-drop target + let label = match (&self.wire_drag, &self.hovered_handle) { + (Some(wd), _) => wd.target.as_ref().filter(|t| t.node.0 < comp.nodes.len()).and_then(|t| { + self.input_slot(comp, comp.node(t.node), &t.port).map(|s| (t.port.as_str(), s.base(m), s.edge.normal())) + }), + (None, Some(hh)) if hh.node.0 < comp.nodes.len() && handles => match &hh.port { + None => Some(("Output", m.output_tip(self.node_rect_local(comp.node(hh.node).pos)), [1.0, 0.0])), + Some(port) => self + .input_slot(comp, comp.node(hh.node), port) + .map(|s| (port.as_str(), s.base(m), s.edge.normal())), + }, + _ => None, + }; + if let Some((name, at, normal)) = label { + if let Some(layout) = self.badge_cache.get(name) { + let (pw, ph, gap) = (layout.width() + 10.0, 14.0, 3.0); + let x0 = if normal[0] < 0.0 { at[0] - gap - pw } else if normal[0] > 0.0 { at[0] + gap } else { at[0] - pw * 0.5 }; + let y0 = if normal[1] < 0.0 { at[1] - gap - ph } else if normal[1] > 0.0 { at[1] + gap } else { at[1] - ph * 0.5 }; + let rect = [x0, y0, x0 + pw, y0 + ph]; + out.push(Primitive::RoundedRect { rect, radius: 3.0, stroke: None, color: [0.02, 0.02, 0.03, 0.94] }); + out.push(Primitive::RoundedRect { rect, radius: 3.0, stroke: Some(0.8), color: [0.46, 0.48, 0.55, 0.9] }); + out.push(Primitive::Text { + text: layout as &dyn Glyphs, + origin: [x0 + 5.0, y0 + (ph - layout.height()) * 0.5], + clip: Some(rect), + ink: [0.94, 0.95, 0.98, 1.0], + }); + } + } + // 5. Box select marquee if let Some(bs) = &self.box_select { let x0 = bs.start_local[0].min(bs.cur_local[0]); @@ -473,14 +481,10 @@ fn input_arrow_svg(edge: Edge, large: bool) -> &'static str { } } -fn port_color(role: PortRole) -> [f32; 4] { - match role { - PortRole::Background => [0.94, 0.76, 0.26, 1.0], // Fusion gold - PortRole::Foreground => [0.34, 0.86, 0.46, 1.0], // Fusion green - PortRole::Mask => [0.32, 0.64, 0.98, 1.0], // Fusion blue - PortRole::Scene3D => [0.30, 0.86, 0.90, 1.0], // Cyan - PortRole::Aux => [0.74, 0.58, 0.90, 1.0], // Violet - } +fn push_square(out: &mut Vec>, c: [f32; 2], half: f32, fill: [f32; 4]) { + let rect = [c[0] - half, c[1] - half, c[0] + half, c[1] + half]; + out.push(Primitive::RoundedRect { rect, radius: 0.6, stroke: None, color: fill }); + out.push(Primitive::RoundedRect { rect, radius: 0.6, stroke: Some(0.9), color: [0.04, 0.04, 0.06, 0.92] }); } fn node_accent(kind: &str) -> [f32; 4] { diff --git a/crates/flow/src/ports.rs b/crates/flow/src/ports.rs new file mode 100644 index 0000000000000000000000000000000000000000..a6990617945cb0c82034d966221fe8f89c43d87b --- /dev/null +++ b/crates/flow/src/ports.rs @@ -0,0 +1,675 @@ +//! Fusion-style node handles: a square output on every node's right edge and role-coloured +//! input triangles that rotate onto whichever edge faces their upstream node. + +use super::*; +use model::Node; + +/// Below this zoom handles are neither drawn nor hit. +pub(crate) const HANDLE_MIN_ZOOM: f32 = 0.36; +const HIT_IN: f32 = 9.0; +const HIT_OUT: f32 = 10.0; +/// Pointer this deep inside a node border grabs the node, never a handle. +const BODY_INSET: f32 = 3.0; +/// A wire dropped this close to a node body lands on its auto-picked port. +const DROP_MARGIN: f32 = 6.0; +const STUB: f32 = 6.0; + +const YELLOW: [f32; 4] = [0.91, 0.77, 0.23, 1.0]; +const GREEN: [f32; 4] = [0.42, 0.75, 0.23, 1.0]; +const BLUE: [f32; 4] = [0.23, 0.63, 0.91, 1.0]; +const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0]; +const PURPLE: [f32; 4] = [0.72, 0.50, 0.92, 1.0]; + +static SCENE_INPUTS: [&str; 32] = [ + "SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4", "SceneInput5", "SceneInput6", "SceneInput7", "SceneInput8", + "SceneInput9", "SceneInput10", "SceneInput11", "SceneInput12", "SceneInput13", "SceneInput14", "SceneInput15", "SceneInput16", + "SceneInput17", "SceneInput18", "SceneInput19", "SceneInput20", "SceneInput21", "SceneInput22", "SceneInput23", "SceneInput24", + "SceneInput25", "SceneInput26", "SceneInput27", "SceneInput28", "SceneInput29", "SceneInput30", "SceneInput31", "SceneInput32", +]; + +static INPUTS: [&str; 33] = [ + "Input0", "Input1", "Input2", "Input3", "Input4", "Input5", "Input6", "Input7", "Input8", "Input9", "Input10", "Input11", + "Input12", "Input13", "Input14", "Input15", "Input16", "Input17", "Input18", "Input19", "Input20", "Input21", "Input22", + "Input23", "Input24", "Input25", "Input26", "Input27", "Input28", "Input29", "Input30", "Input31", "Input32", +]; + +/// Screen-pixel handle sizes; two steps so they stay crisp while the node bars scale. +#[derive(Clone, Copy)] +pub(crate) struct Metrics { + pub tri_len: f32, + pub tri_half: f32, + pub out_half: f32, + out_gap: f32, +} + +impl Metrics { + pub(crate) fn at(zoom: f32) -> Self { + if zoom >= 0.72 { + Self { tri_len: 6.5, tri_half: 3.6, out_half: 2.8, out_gap: 2.2 } + } else { + Self { tri_len: 4.5, tri_half: 2.6, out_half: 2.0, out_gap: 1.5 } + } + } + + pub(crate) fn large(zoom: f32) -> bool { + zoom >= 0.72 + } + + pub(crate) fn output_center(self, r: [f32; 4]) -> [f32; 2] { + [r[2] + self.out_gap + self.out_half, (r[1] + r[3]) * 0.5] + } + + /// Where a wire leaves the output square. + pub(crate) fn output_tip(self, r: [f32; 4]) -> [f32; 2] { + let c = self.output_center(r); + [c[0] + self.out_half, c[1]] + } +} + +/// One input triangle of a node, in canvas-local pixels. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Slot<'a> { + pub port: &'a str, + pub color: [f32; 4], + pub edge: Edge, + /// Triangle tip, flush on the node border. + pub tip: [f32; 2], + pub src: Option, +} + +impl Slot<'_> { + /// Centre of the triangle's base, where the wire attaches. + pub(crate) fn base(&self, m: Metrics) -> [f32; 2] { + let n = self.edge.normal(); + [self.tip[0] + n[0] * m.tri_len, self.tip[1] + n[1] * m.tri_len] + } + + pub(crate) fn center(&self, m: Metrics) -> [f32; 2] { + let n = self.edge.normal(); + let d = m.tri_len * 0.45; + [self.tip[0] + n[0] * d, self.tip[1] + n[1] * d] + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Class { + Generator, + TwoInput, + Single, +} + +#[derive(Clone, Copy)] +enum Table { + Fixed(&'static [&'static str]), + /// Connected ports plus the first free one. + Grow(&'static [&'static str]), + /// One main input and an `EffectMask`. + Masked(&'static str), +} + +fn zero_indexed(n: &Node) -> bool { + n.inputs.contains_key("Source") || n.inputs.contains_key("Input0") || !n.inputs.contains_key("Which") +} + +fn table(n: &Node) -> (Table, Class) { + use Class::*; + match n.kind.as_str() { + "Merge" | "Dissolve" | "ChannelBoolean" => (Table::Fixed(&["Background", "Foreground", "EffectMask"]), TwoInput), + "Displace" => (Table::Fixed(&["Input", "Foreground", "EffectMask"]), TwoInput), + "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask" => { + (Table::Fixed(&["EffectMask"]), Generator) + } + "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => { + (Table::Fixed(&["SceneInput"]), Single) + } + "Merge3D" => (Table::Grow(&SCENE_INPUTS), Single), + "sMerge" | "pMerge" | "Fuse.Switch" => (Table::Grow(&INPUTS[1..]), Single), + "sBoolean" => (Table::Grow(&INPUTS[1..=2]), Single), + "Switch" => (Table::Grow(if zero_indexed(n) { &INPUTS[..] } else { &INPUTS[1..] }), Single), + "BitmapMask" => (Table::Fixed(&["Image"]), Single), + "ImagePlane3D" | "TextureTransformOperator" => (Table::Fixed(&["MaterialInput"]), Single), + "Saver" | "PipeRouter" => (Table::Fixed(&["Input"]), Single), + "MacroOperator" | "GroupOperator" => (Table::Fixed(&["MainInput1"]), Single), + kind => (Table::Masked(default_main_input_port(kind)), Single), + } +} + +/// Port a wire dropped on `n`'s body lands on: the first open main port. +pub(crate) fn drop_port(n: &Node) -> &'static str { + let (table, class) = table(n); + let free = |p: &&'static str| n.inputs.get(*p).is_none_or(|b| b.source_op.is_none()); + match table { + Table::Masked(main) => main, + Table::Fixed(l) if class == Class::TwoInput => l[..2].iter().find(|p| free(p)).copied().unwrap_or(l[0]), + Table::Fixed(l) => l[0], + Table::Grow(l) => l.iter().find(|p| free(p)).copied().unwrap_or(l[l.len() - 1]), + } +} + +/// Calls `f` for every input port to show on `n`: the declared ports, then any other connected ones. +fn each_port<'a>(n: &'a Node, table: Table, mut f: impl FnMut(&'a str)) { + let connected = |p: &str| n.inputs.get(p).is_some_and(|b| b.source_op.is_some()); + match table { + Table::Fixed(l) => l.iter().for_each(|p| f(p)), + Table::Grow(l) => { + let mut free_shown = false; + for p in l { + if connected(p) { + f(p); + } else if !free_shown { + free_shown = true; + f(p); + } + } + } + Table::Masked(main) => { + f(main); + f("EffectMask"); + } + } + let declared = |p: &str| match table { + Table::Fixed(l) | Table::Grow(l) => l.contains(&p), + Table::Masked(main) => p == main || p == "EffectMask", + }; + let mut extras: Vec<&str> = n + .inputs + .iter() + .filter(|(p, b)| b.source_op.is_some() && !declared(p)) + .map(|(p, _)| p.as_str()) + .collect(); + extras.sort_unstable(); + extras.into_iter().for_each(f); +} + +fn port_color(n: &Node, port: &str) -> [f32; 4] { + match port { + "Input0" | "MaterialInput" => YELLOW, + "Input1" if n.kind == "Switch" && zero_indexed(n) => GREEN, + "Input1" => YELLOW, + "Input2" | "SceneInput2" => GREEN, + "GarbageMatte" | "SolidMatte" => GRAY, + _ => match PortRole::from_input_name(port) { + PortRole::Background => YELLOW, + PortRole::Foreground => GREEN, + PortRole::Mask => BLUE, + PortRole::Scene3D if port == "SceneInput" || port == "SceneInput1" => YELLOW, + PortRole::Scene3D => PURPLE, + PortRole::Aux => GRAY, + }, + } +} + +/// Fusion's resting side for an input that has no upstream to face. +fn default_edge(class: Class, role: PortRole) -> Edge { + match (class, role) { + (Class::TwoInput, PortRole::Foreground) | (Class::Single, PortRole::Mask) => Edge::Top, + (Class::TwoInput, PortRole::Mask) => Edge::Bottom, + _ => Edge::Left, + } +} + +/// Picks the node edge facing vector `(dx, dy)`, biased for the bar's wide aspect. +pub(crate) fn closest_edge(dx: f32, dy: f32) -> Edge { + if dx.abs() * 0.58 >= dy.abs() { + if dx >= 0.0 { Edge::Right } else { Edge::Left } + } else if dy >= 0.0 { + Edge::Bottom + } else { + Edge::Top + } +} + +/// Polyline a wire follows from an output square to an input triangle. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Route { + pts: [[f32; 2]; 6], + len: usize, +} + +impl Route { + pub(crate) fn points(&self) -> &[[f32; 2]] { + &self.pts[..self.len] + } +} + +fn within(p: [f32; 2], r: [f32; 4], margin: f32) -> bool { + p[0] >= r[0] - margin && p[0] <= r[2] + margin && p[1] >= r[1] - margin && p[1] <= r[3] + margin +} + +fn dist2(a: [f32; 2], b: [f32; 2]) -> f32 { + (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) +} + +/// Liang–Barsky segment/rect overlap. +pub(crate) fn segment_hits_rect(a: [f32; 2], b: [f32; 2], r: [f32; 4]) -> bool { + let d = [b[0] - a[0], b[1] - a[1]]; + let (mut t0, mut t1) = (0.0_f32, 1.0_f32); + 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])] { + if p == 0.0 { + if q < 0.0 { + return false; + } + } else { + let t = q / p; + if p < 0.0 { t0 = t0.max(t) } else { t1 = t1.min(t) } + if t0 > t1 { + return false; + } + } + } + true +} + +impl FlowView { + pub(crate) fn upstream_of(&self, comp: &Comp, n: &Node, port: &str) -> Option { + let src = n.inputs.get(port)?.source_op.as_deref()?; + self.scope.resolve(comp, src) + } + + /// Calls `f` for each input triangle of `n`, placed on the edge facing its upstream node + /// (or Fusion's default side when open) and spread along that edge so none overlap. + pub(crate) fn for_each_input<'a>(&self, comp: &Comp, n: &'a Node, mut f: impl FnMut(Slot<'a>)) { + let (table, class) = table(n); + let m = Metrics::at(self.zoom); + let r = self.node_rect_local(n.pos); + let (cx, cy) = ((r[0] + r[2]) * 0.5, (r[1] + r[3]) * 0.5); + + // The two right-edge lanes flank the output square; a third crowds onto top/bottom instead. + let place = |port: &str, lanes: &mut [bool; 2]| -> (Option, Edge, usize) { + let Some(src) = self.upstream_of(comp, n, port) else { + return (None, default_edge(class, PortRole::from_input_name(port)), 0); + }; + let sp = comp.node(src).pos; + let (dx, dy) = (sp[0] - n.pos[0], sp[1] - n.pos[1]); + match closest_edge(dx, dy) { + Edge::Right => { + let want = usize::from(dy >= 0.0); + match [want, 1 - want].into_iter().find(|&l| !lanes[l]) { + Some(lane) => { + lanes[lane] = true; + (Some(src), Edge::Right, lane) + } + None => (Some(src), if want == 1 { Edge::Bottom } else { Edge::Top }, 0), + } + } + edge => (Some(src), edge, 0), + } + }; + + let mut counts = [0_usize; 4]; + let mut lanes = [false; 2]; + each_port(n, table, |port| counts[place(port, &mut lanes).1 as usize] += 1); + + let along = |center: f32, span: f32, i: usize, count: usize| { + let pitch = (span / count as f32).max(2.0 * m.tri_half + 1.0); + center + (i as f32 - (count as f32 - 1.0) * 0.5) * pitch + }; + let lane_offset = m.out_half + m.tri_half + 1.0; + let mut seen = [0_usize; 4]; + let mut lanes = [false; 2]; + each_port(n, table, |port| { + let (src, edge, lane) = place(port, &mut lanes); + let (i, count) = (seen[edge as usize], counts[edge as usize]); + seen[edge as usize] += 1; + let tip = match edge { + Edge::Left => [r[0], along(cy, r[3] - r[1], i, count)], + Edge::Top => [along(cx, r[2] - r[0], i, count), r[1]], + Edge::Bottom => [along(cx, r[2] - r[0], i, count), r[3]], + Edge::Right => [r[2], cy + if lane == 1 { lane_offset } else { -lane_offset }], + }; + f(Slot { port, color: port_color(n, port), edge, tip, src }); + }); + } + + pub(crate) fn input_slot<'a>(&self, comp: &Comp, n: &'a Node, port: &str) -> Option> { + let mut found = None; + self.for_each_input(comp, n, |s| { + if s.port == port { + found = Some(s); + } + }); + found + } + + /// Straight from output square to input triangle; otherwise an elbow, otherwise a loop over or + /// under both nodes, so a wire never cuts through either body. + pub(crate) fn wire_route(&self, src_rect: [f32; 4], dst_rect: [f32; 4], slot: &Slot) -> Route { + let m = Metrics::at(self.zoom); + let p0 = m.output_tip(src_rect); + let q0 = slot.base(m); + let n = slot.edge.normal(); + let p1 = [p0[0] + STUB, p0[1]]; + let q1 = [q0[0] + n[0] * STUB, q0[1] + n[1] * STUB]; + let inset = |r: [f32; 4]| [r[0] + 1.0, r[1] + 1.0, r[2] - 1.0, r[3] - 1.0]; + let (sr, dr) = (inset(src_rect), inset(dst_rect)); + 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)); + + let straight = Route { pts: [p0, q0, q0, q0, q0, q0], len: 2 }; + if clear(&straight) { + return straight; + } + let elbow = Route { pts: [p0, p1, [p1[0], q1[1]], q1, q0, q0], len: 5 }; + if clear(&elbow) { + return elbow; + } + let dcy = (dst_rect[1] + dst_rect[3]) * 0.5; + let up = slot.edge == Edge::Top || (slot.edge != Edge::Bottom && slot.tip[1] <= dcy); + let margin = m.tri_len + STUB + 3.0; + let y = if up { src_rect[1].min(dst_rect[1]) - margin } else { src_rect[3].max(dst_rect[3]) + margin }; + Route { pts: [p0, p1, [p1[0], y], [q1[0], y], q1, q0], len: 6 } + } + + /// Extra pixels around a node's rect that its handles can reach. + fn handle_reach(&self, n: &Node) -> f32 { + let m = Metrics::at(self.zoom); + let grow = if matches!(table(n).0, Table::Grow(_)) { n.inputs.len() as f32 * 4.5 } else { 0.0 }; + HIT_IN + m.tri_len + 4.0 + grow + } + + /// Output square (`None` port) or input triangle under `local`. A node body always wins. + pub(crate) fn hit_handle<'a>(&self, comp: &'a Comp, local: [f32; 2]) -> Option<(NodeId, Option<&'a str>)> { + if self.zoom < HANDLE_MIN_ZOOM { + return None; + } + let m = Metrics::at(self.zoom); + for n in comp.nodes.iter().rev().filter(|n| self.scope.shows(n)) { + let r = self.node_rect_local(n.pos); + if !within(local, r, self.handle_reach(n).max(HIT_OUT)) { + continue; + } + if within(local, r, -BODY_INSET) { + return None; + } + let d = dist2(local, m.output_center(r)); + let mut best = (d <= HIT_OUT * HIT_OUT).then_some((d, None)); + self.for_each_input(comp, n, |s| { + let d = dist2(local, s.center(m)); + if d <= HIT_IN * HIT_IN && best.is_none_or(|(b, _)| d < b) { + best = Some((d, Some(s.port))); + } + }); + if let Some((_, port)) = best { + return Some((n.id, port)); + } + } + None + } + + /// Port a wire released at `local` lands on: an input triangle, else the auto-picked port of + /// the node body underneath. + pub(crate) fn hit_drop_target<'a>(&self, comp: &'a Comp, local: [f32; 2]) -> Option<(NodeId, &'a str)> { + let m = Metrics::at(self.zoom); + for n in comp.nodes.iter().rev().filter(|n| self.scope.shows(n)) { + let r = self.node_rect_local(n.pos); + if self.zoom >= HANDLE_MIN_ZOOM && within(local, r, self.handle_reach(n)) { + let mut best: Option<(f32, &str)> = None; + self.for_each_input(comp, n, |s| { + let d = dist2(local, s.center(m)); + if d <= HIT_IN * HIT_IN && best.is_none_or(|(b, _)| d < b) { + best = Some((d, s.port)); + } + }); + if let Some((_, port)) = best { + return Some((n.id, port)); + } + } + if within(local, r, DROP_MARGIN) { + return Some((n.id, drop_port(n))); + } + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn comp(src: &str) -> Comp { + Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ {src} }} }}")).expect("parse comp") + } + + fn port(comp: &Comp, name: &str) -> &'static str { + drop_port(comp.node(comp.find_node(name).unwrap())) + } + + fn view() -> FlowView { + let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true)); + flow.size = [800.0, 600.0]; + flow + } + + fn slots(flow: &FlowView, comp: &Comp, name: &str) -> Vec<(String, Edge, [f32; 2], Option)> { + let mut out = Vec::new(); + 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))); + out + } + + fn edge_of(slots: &[(String, Edge, [f32; 2], Option)], port: &str) -> Edge { + slots.iter().find(|s| s.0 == port).unwrap_or_else(|| panic!("no slot {port}")).1 + } + + /// Bounding box of the triangle on `edge` with its tip at `tip`. + fn tri_box(m: Metrics, edge: Edge, tip: [f32; 2]) -> [f32; 4] { + let b = Slot { port: "", color: YELLOW, edge, tip, src: None }.base(m); + let (lo, hi) = ([tip[0].min(b[0]), tip[1].min(b[1])], [tip[0].max(b[0]), tip[1].max(b[1])]); + if edge.normal()[0] == 0.0 { + [lo[0] - m.tri_half, lo[1], hi[0] + m.tri_half, hi[1]] + } else { + [lo[0], lo[1] - m.tri_half, hi[0], hi[1] + m.tri_half] + } + } + + fn overlaps(a: [f32; 4], b: [f32; 4]) -> bool { + a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1] + } + + #[test] + fn single_input_kinds_use_engine_port_names() { + let c = comp( + "R = Renderer3D { }, D = Displace { }, CB = ChannelBoolean { }, Dis = Dissolve { }, + BM = BitmapMask { }, T = Transform3D { }, Plane = ImagePlane3D { }, G = Background { }", + ); + assert_eq!(port(&c, "R"), "SceneInput"); + assert_eq!(port(&c, "D"), "Input"); + assert_eq!(port(&c, "CB"), "Background"); + assert_eq!(port(&c, "Dis"), "Background"); + assert_eq!(port(&c, "BM"), "Image"); + assert_eq!(port(&c, "T"), "SceneInput"); + assert_eq!(port(&c, "Plane"), "MaterialInput"); + assert_eq!(port(&c, "G"), "EffectMask"); + } + + #[test] + fn body_drops_take_the_first_open_main_port() { + let c = comp( + r#"A = Background { }, + M = Merge { Inputs = { Background = Input { SourceOp = "A", Source = "Output" } } }, + Full = Merge { Inputs = { Background = Input { SourceOp = "A", Source = "Output" }, + Foreground = Input { SourceOp = "A", Source = "Output" } } }, + D = Displace { Inputs = { Input = Input { SourceOp = "A", Source = "Output" } } }"#, + ); + assert_eq!(port(&c, "M"), "Foreground"); + assert_eq!(port(&c, "Full"), "Background"); + assert_eq!(port(&c, "D"), "Foreground"); + } + + #[test] + fn multi_input_kinds_pick_next_free_port() { + let c = comp( + r#"A = Background { }, B = Background { }, + M3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output" } } }, + M3b = Merge3D { }, + S = Switch { Inputs = { Input0 = Input { SourceOp = "A", Source = "Output" } } }, + SW = Switch { Inputs = { Which = Input { Value = 1 } } }, + SB = sBoolean { Inputs = { Input1 = Input { SourceOp = "A", Source = "Output" } } }, + SB0 = sBoolean { }, + FS = Fuse.Switch { }"#, + ); + assert_eq!(port(&c, "M3b"), "SceneInput1"); + assert_eq!(port(&c, "M3"), "SceneInput2"); + assert_eq!(port(&c, "S"), "Input1"); + assert_eq!(port(&c, "SW"), "Input1"); + assert_eq!(port(&c, "SB"), "Input2"); + assert_eq!(port(&c, "SB0"), "Input1"); + assert_eq!(port(&c, "FS"), "Input1"); + } + + #[test] + fn native_switch_without_which_starts_at_input0() { + let c = comp("S = Switch { }"); + assert_eq!(port(&c, "S"), "Input0"); + } + + #[test] + fn unconnected_inputs_rest_on_fusion_sides() { + let c = comp("Blur1 = Blur { }, Merge1 = Merge { }, Gen = FastNoise { }, Sv = Saver { }"); + let flow = view(); + + let blur = slots(&flow, &c, "Blur1"); + assert_eq!(blur.iter().map(|s| s.0.as_str()).collect::>(), ["Input", "EffectMask"]); + assert_eq!((edge_of(&blur, "Input"), edge_of(&blur, "EffectMask")), (Edge::Left, Edge::Top)); + + let merge = slots(&flow, &c, "Merge1"); + assert_eq!(edge_of(&merge, "Background"), Edge::Left); + assert_eq!(edge_of(&merge, "Foreground"), Edge::Top); + assert_eq!(edge_of(&merge, "EffectMask"), Edge::Bottom); + + assert_eq!(slots(&flow, &c, "Gen").iter().map(|s| (s.0.as_str(), s.1)).collect::>(), [("EffectMask", Edge::Left)]); + assert_eq!(slots(&flow, &c, "Sv").len(), 1); + } + + #[test] + fn roles_map_to_fusion_colors() { + let c = comp( + r#"M = Merge { }, S = Switch { }, SB = sBoolean { }, M3 = Merge3D { }, + B = Blur { Inputs = { GarbageMatte = Input { SourceOp = "M", Source = "Output" } } }"#, + ); + let color = |name: &str, p: &str| port_color(c.node(c.find_node(name).unwrap()), p); + assert_eq!(color("M", "Background"), YELLOW); + assert_eq!(color("M", "Foreground"), GREEN); + assert_eq!(color("M", "EffectMask"), BLUE); + assert_eq!((color("S", "Input0"), color("S", "Input1")), (YELLOW, GREEN)); + assert_eq!((color("SB", "Input1"), color("SB", "Input2")), (YELLOW, GREEN)); + assert_eq!((color("M3", "SceneInput1"), color("M3", "SceneInput2"), color("M3", "SceneInput3")), (YELLOW, GREEN, PURPLE)); + assert_eq!(color("B", "GarbageMatte"), GRAY); + } + + #[test] + fn connected_inputs_face_their_upstream_across_all_quadrants() { + let flow = view(); + // (upstream offset from the Blur, expected edge) + let cases: [([f32; 2], Edge); 8] = [ + ([-110.0, 0.0], Edge::Left), + ([-110.0, -55.0], Edge::Left), + ([-40.0, -80.0], Edge::Top), + ([0.0, -60.0], Edge::Top), + ([40.0, 80.0], Edge::Bottom), + ([0.0, 60.0], Edge::Bottom), + ([110.0, -20.0], Edge::Right), + ([110.0, 20.0], Edge::Right), + ]; + for (off, expected) in cases { + let c = comp(&format!( + r#"Up = Background {{ ViewInfo = OperatorInfo {{ Pos = {{ {}, {} }} }} }}, + Blur1 = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "Up", Source = "Output" }} }}, + ViewInfo = OperatorInfo {{ Pos = {{ 0, 0 }} }} }}"#, + off[0], off[1] + )); + let s = slots(&flow, &c, "Blur1"); + assert_eq!(edge_of(&s, "Input"), expected, "upstream at {off:?}"); + + let (up, blur) = (c.find_node("Up").unwrap(), c.find_node("Blur1").unwrap()); + let (sr, dr) = (flow.node_rect_local(c.node(up).pos), flow.node_rect_local(c.node(blur).pos)); + let m = Metrics::at(flow.zoom); + let slot = flow.input_slot(&c, c.node(blur), "Input").unwrap(); + let route = flow.wire_route(sr, dr, &slot); + let shrink = |r: [f32; 4]| [r[0] + 1.5, r[1] + 1.5, r[2] - 1.5, r[3] - 1.5]; + for seg in route.points().windows(2) { + assert!(!segment_hits_rect(seg[0], seg[1], shrink(sr)), "wire cuts the source body, upstream at {off:?}"); + assert!(!segment_hits_rect(seg[0], seg[1], shrink(dr)), "wire cuts the consumer body, upstream at {off:?}"); + } + + let square = { + let c = m.output_center(dr); + [c[0] - m.out_half, c[1] - m.out_half, c[0] + m.out_half, c[1] + m.out_half] + }; + for (_, edge, tip, _) in &s { + assert!(!overlaps(tri_box(m, *edge, *tip), square), "handle on {edge:?} hits the output square, upstream at {off:?}"); + } + } + } + + #[test] + fn crowded_edges_spread_without_overlap() { + let flow = view(); + let c = comp( + r#"A = Background { ViewInfo = OperatorInfo { Pos = { -110, -30 } } }, + B = Background { ViewInfo = OperatorInfo { Pos = { -110, 0 } } }, + C = Background { ViewInfo = OperatorInfo { Pos = { -110, 30 } } }, + R1 = Background { ViewInfo = OperatorInfo { Pos = { 110, 200 } } }, + R2 = Background { ViewInfo = OperatorInfo { Pos = { 110, 210 } } }, + R3 = Background { ViewInfo = OperatorInfo { Pos = { 110, 190 } } }, + M3 = Merge3D { + Inputs = { + SceneInput1 = Input { SourceOp = "A", Source = "Output" }, + SceneInput2 = Input { SourceOp = "B", Source = "Output" }, + SceneInput3 = Input { SourceOp = "C", Source = "Output" }, + }, + ViewInfo = OperatorInfo { Pos = { 0, 0 } }, + }, + Back = Merge { + Inputs = { + Background = Input { SourceOp = "R1", Source = "Output" }, + Foreground = Input { SourceOp = "R2", Source = "Output" }, + EffectMask = Input { SourceOp = "R3", Source = "Output" }, + }, + ViewInfo = OperatorInfo { Pos = { 0, 200 } }, + }"#, + ); + let m = Metrics::at(flow.zoom); + for name in ["M3", "Back"] { + let s = slots(&flow, &c, name); + for (i, a) in s.iter().enumerate() { + for b in &s[i + 1..] { + assert!(!overlaps(tri_box(m, a.1, a.2), tri_box(m, b.1, b.2)), "{name}: {} overlaps {}", a.0, b.0); + } + } + } + // Three upstreams plus the next free port all stack down the left edge. + let m3 = slots(&flow, &c, "M3"); + assert_eq!(m3.iter().map(|s| s.0.as_str()).collect::>(), ["SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4"]); + assert!(m3.iter().all(|s| s.1 == Edge::Left)); + assert!(m3.windows(2).all(|w| w[0].2[1] < w[1].2[1])); + // A third source on the right spills to top/bottom instead of crowding the output square. + let back = slots(&flow, &c, "Back"); + assert_eq!(back.iter().filter(|s| s.1 == Edge::Right).count(), 2); + } + + #[test] + fn hit_handle_finds_output_square_and_input_triangles() { + let flow = view(); + let c = comp( + r#"Up = Background { ViewInfo = OperatorInfo { Pos = { -110, 0 } } }, + M = Merge { Inputs = { Background = Input { SourceOp = "Up", Source = "Output" } }, + ViewInfo = OperatorInfo { Pos = { 0, 0 } } }"#, + ); + let (up, merge) = (c.find_node("Up").unwrap(), c.find_node("M").unwrap()); + let m = Metrics::at(flow.zoom); + let ur = flow.node_rect_local(c.node(up).pos); + let mr = flow.node_rect_local(c.node(merge).pos); + + assert_eq!(flow.hit_handle(&c, m.output_center(ur)), Some((up, None))); + for (p, want) in [("Background", Edge::Left), ("Foreground", Edge::Top), ("EffectMask", Edge::Bottom)] { + let s = flow.input_slot(&c, c.node(merge), p).unwrap(); + assert_eq!(s.edge, want); + assert_eq!(flow.hit_handle(&c, s.center(m)), Some((merge, Some(p))), "{p}"); + } + // A few pixels off the tip still grabs it; deep inside the body never does. + let bg = flow.input_slot(&c, c.node(merge), "Background").unwrap(); + assert_eq!(flow.hit_handle(&c, [bg.tip[0] - 7.0, bg.tip[1] + 2.0]), Some((merge, Some("Background")))); + assert_eq!(flow.hit_handle(&c, [(mr[0] + mr[2]) * 0.5, (mr[1] + mr[3]) * 0.5]), None); + assert_eq!(flow.hit_handle(&c, [mr[0] + 6.0, (mr[1] + mr[3]) * 0.5]), None); + assert_eq!(flow.hit_handle(&c, [0.0, 0.0]), None); + } +}