| 1 | use super::*; |
| 2 | |
| 3 | impl FlowView { |
| 4 | pub(crate) fn world_to_local(&self, w: [f32; 2]) -> [f32; 2] { |
| 5 | [ |
| 6 | (w[0] - self.pan[0]) * self.zoom + self.size[0] * 0.5, |
| 7 | (w[1] - self.pan[1]) * self.zoom + self.size[1] * 0.5, |
| 8 | ] |
| 9 | } |
| 10 | |
| 11 | pub(crate) fn local_to_world(&self, l: [f32; 2]) -> [f32; 2] { |
| 12 | [ |
| 13 | (l[0] - self.size[0] * 0.5) / self.zoom + self.pan[0], |
| 14 | (l[1] - self.size[1] * 0.5) / self.zoom + self.pan[1], |
| 15 | ] |
| 16 | } |
| 17 | |
| 18 | pub(crate) fn node_rect_local(&self, pos: [f32; 2]) -> [f32; 4] { |
| 19 | let c = self.world_to_local(pos); |
| 20 | let hw = NODE_W * 0.5 * self.zoom; |
| 21 | let hh = NODE_H * 0.5 * self.zoom; |
| 22 | [c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh] |
| 23 | } |
| 24 | |
| 25 | pub(crate) fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> { |
| 26 | for n in comp.nodes.iter().rev() { |
| 27 | if !self.scope.shows(n) { continue; } |
| 28 | let r = self.node_rect_local(n.pos); |
| 29 | if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] { |
| 30 | return Some(n.id); |
| 31 | } |
| 32 | } |
| 33 | None |
| 34 | } |
| 35 | |
| 36 | pub(crate) fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option<NodeId>) -> Option<WireRef> { |
| 37 | let mut best: Option<(f32, WireRef)> = None; |
| 38 | for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { |
| 39 | if Some(dst.id) == ignore_node { |
| 40 | continue; |
| 41 | } |
| 42 | let dr = self.node_rect_local(dst.pos); |
| 43 | self.for_each_input(comp, dst, |slot| { |
| 44 | let Some(src) = slot.src.filter(|&s| Some(s) != ignore_node) else { return }; |
| 45 | let route = self.wire_route(self.node_rect_local(comp.node(src).pos), dr, &slot); |
| 46 | let d = route.points().windows(2).map(|s| dist_to_seg(local, s[0], s[1])).fold(f32::INFINITY, f32::min); |
| 47 | if d < 10.0 && best.as_ref().is_none_or(|(bd, _)| d < *bd) { |
| 48 | best = Some((d, WireRef { src, dst: dst.id, port: slot.port.to_owned() })); |
| 49 | } |
| 50 | }); |
| 51 | } |
| 52 | best.map(|(_, w)| w) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | pub(crate) fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { |
| 57 | let ab = [b[0] - a[0], b[1] - a[1]]; |
| 58 | let len2 = ab[0] * ab[0] + ab[1] * ab[1]; |
| 59 | let t = if len2 < 1e-6 { |
| 60 | 0.0 |
| 61 | } else { |
| 62 | (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / len2).clamp(0.0, 1.0) |
| 63 | }; |
| 64 | let q = [a[0] + ab[0] * t, a[1] + ab[1] * t]; |
| 65 | ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() |
| 66 | } |