Skip to main content

blockworx_editor/presentation/
route.rs

1//! Solved wire geometry: what the router produced for one route — its
2//! edge polyline, resolved endpoints, and crossing hops. Authored route
3//! state (anchors, waypoints, labels, name, role) stays on the document's
4//! own [`Route`](blockworx_doc::block_model::Route); everything here is
5//! recomputable and never persisted.
6
7use blockworx_doc::geometry::{FracVal, GridPoint};
8use blockworx_geom::{Pos2, Vec2};
9
10use crate::grid::LINE_RADIUS;
11use crate::grid::px_point;
12use crate::presentation::store::{EdgeId, IdMap, IdMapExt};
13use crate::widget::edge::RouteEdgeExt;
14
15/// The orientation of a route segment. Pure data.
16#[derive(Clone, PartialEq, Eq, Hash, Copy, Debug, PartialOrd, Ord)]
17pub enum RouteDirection {
18    Horizontal,
19    Vertical,
20}
21
22/// A single straight (horizontal or vertical) segment of a route, in grid space.
23/// Pure data; the pixel-space helpers (`length`, `distance`) live in the
24/// `RouteEdgeExt` trait in [`crate::widget::edge`].
25#[derive(Clone, PartialEq, Debug)]
26pub struct RouteEdge {
27    pub start: GridPoint,
28    pub end: GridPoint,
29}
30
31impl RouteEdge {
32    /// Whether this segment runs more horizontally or vertically. Pure grid
33    /// arithmetic, so it stays on the data type.
34    pub fn direction(&self) -> RouteDirection {
35        if (self.end.x - self.start.x).abs() > (self.end.y - self.start.y).abs() {
36            RouteDirection::Horizontal
37        } else {
38            RouteDirection::Vertical
39        }
40    }
41}
42
43/// A purely visual decoration marking where this route crosses *over* another
44/// route. The crossing route gets a small semicircular "hop" drawn at `pos`;
45/// `orientation` is the direction of this route's own segment at the crossing
46/// (the bump bulges perpendicular to it). Every route crossing a given point in
47/// the point's chosen orientation carries a matching `Crossing`, so they all hop
48/// identically there. Computed where the wires are drawn
49/// ([`crate::widget::auto_route::route_hops`]), never stored with them.
50#[derive(Clone, Copy, PartialEq, Debug)]
51pub struct Crossing {
52    pub pos: GridPoint,
53    pub orientation: RouteDirection,
54}
55
56/// Where a point on the route sits and which way the wire runs there.
57#[derive(Clone, Copy, Debug)]
58pub struct LocAndDirection {
59    pub location: Pos2,
60    pub direction: RouteDirection,
61}
62
63#[derive(Default, Debug, Clone, PartialEq)]
64pub struct RouteGeometry {
65    pub edges: IdMap<EdgeId, RouteEdge>,
66    pub start_pos: GridPoint,
67    pub end_pos: GridPoint,
68}
69
70impl RouteGeometry {
71    pub fn edge(&self, edge_index: EdgeId) -> Option<&RouteEdge> {
72        self.edges.get(&edge_index)
73    }
74
75    pub fn iter_edges(&self) -> impl Iterator<Item = (EdgeId, &RouteEdge)> {
76        self.edges.iter().map(|(&k, v)| (k, v))
77    }
78
79    pub fn start_pos(&self) -> Pos2 {
80        px_point(self.start_pos)
81    }
82
83    pub fn end_pos(&self) -> Pos2 {
84        px_point(self.end_pos)
85    }
86
87    /// The polyline's corner sequence: the resolved start, then each
88    /// edge's end (no duplicated interior points).
89    pub fn points(&self) -> Vec<Pos2> {
90        let mut points: Vec<Pos2> = Vec::new();
91        points.push(px_point(self.start_pos));
92        for (_, edge) in self.iter_edges() {
93            points.push(px_point(edge.end));
94        }
95        points
96    }
97
98    pub fn hovered_corner(&self, hover_pos: Pos2) -> Option<(EdgeId, EdgeId)> {
99        self.edges.windows(2).find_map(|edges| {
100            let (edge_id1, edge1) = edges[0];
101            let (edge_id2, edge2) = edges[1];
102            if px_point(edge1.end).distance(hover_pos) <= LINE_RADIUS
103                && edge1.direction() != edge2.direction()
104            {
105                Some((edge_id1, edge_id2))
106            } else {
107                None
108            }
109        })
110    }
111
112    pub fn hovered_edge(&self, hover_pos: Pos2) -> Option<EdgeId> {
113        self.iter_edges().find_map(|(eid, edge)| {
114            if edge.distance(hover_pos).1 <= LINE_RADIUS
115                && px_point(edge.start).distance(hover_pos) > LINE_RADIUS
116                && px_point(edge.end).distance(hover_pos) > LINE_RADIUS
117            {
118                Some(eid)
119            } else {
120                None
121            }
122        })
123    }
124
125    /// Perpendicular distance from `hover_pos` to the nearest point on the
126    /// route, or `None` if the point isn't within the hit radius (or sits
127    /// on a terminal endpoint, which is left to the pin under it). Unlike
128    /// [`hovered_edge`](Self::hovered_edge) this keeps interior corners
129    /// hoverable. Lets a caller pick the *closest* route among several in
130    /// range.
131    pub fn hovered_edge_distance(&self, hover_pos: Pos2) -> Option<f32> {
132        // Only the route's two terminal endpoints are excluded, so a hover near a
133        // pin falls through to it. Interior corners are NOT excluded: the segment
134        // distance already clamps to the bend, so a corner stays hoverable instead
135        // of sitting in a dead zone where both adjacent edges reject it.
136        if self.start_pos().distance(hover_pos) <= LINE_RADIUS
137            || self.end_pos().distance(hover_pos) <= LINE_RADIUS
138        {
139            return None;
140        }
141        self.iter_edges()
142            .filter_map(|(_, edge)| {
143                let perp = edge.distance(hover_pos).1;
144                (perp <= LINE_RADIUS).then_some(perp)
145            })
146            .min_by(f32::total_cmp)
147    }
148
149    // Convert a distance along the route to a point on the route. This is
150    // the inverse of `distance_along`. If the distance is out of range,
151    // take the end anchor.
152    pub fn map_linear_distance_to_position(&self, linear_distance: FracVal) -> LocAndDirection {
153        let mut distance: f32 = linear_distance.into();
154        for (_, edge) in self.iter_edges() {
155            if edge.length() < distance {
156                distance -= edge.length();
157            } else {
158                let frac = distance / edge.length();
159                let start: Pos2 = px_point(edge.start);
160                let end: Pos2 = px_point(edge.end);
161                return LocAndDirection {
162                    location: start + frac * (end - start),
163                    direction: edge.direction(),
164                };
165            }
166        }
167        LocAndDirection {
168            location: px_point(self.end_pos),
169            direction: RouteDirection::Horizontal,
170        }
171    }
172
173    /// Slide an arc-length position along the route by a screen-space delta:
174    /// map to world, offset, re-project onto the nearest point of the wire.
175    pub fn slide_along(&self, from: FracVal, delta: Vec2) -> FracVal {
176        let anchor = self.map_linear_distance_to_position(from).location;
177        self.distance_along(anchor + delta)
178    }
179
180    /// The arc length along the route of the nearest point to `pos`.
181    pub fn distance_along(&self, pos: Pos2) -> FracVal {
182        let mut min_distance = f32::INFINITY;
183        let mut accum_distance: f32 = 0.0;
184        let mut min_distance_along: f32 = 0.0;
185        for (_, edge) in self.iter_edges() {
186            let (distance_along_edge, distance_to_point) = edge.distance(pos);
187            if distance_to_point < min_distance {
188                min_distance = distance_to_point;
189                min_distance_along = accum_distance + distance_along_edge;
190            }
191            accum_distance += edge.length();
192        }
193        FracVal::from(min_distance_along)
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use crate::grid::GRID_SIZE;
201    use blockworx_geom::vec2;
202
203    /// One straight horizontal run, ten cells long.
204    fn horizontal_wire() -> RouteGeometry {
205        let start = GridPoint { x: 0, y: 0 };
206        let end = GridPoint { x: 10, y: 0 };
207        let mut edges: IdMap<EdgeId, RouteEdge> = IdMap::default();
208        edges.insert_value(RouteEdge { start, end });
209        RouteGeometry {
210            edges,
211            start_pos: start,
212            end_pos: end,
213        }
214    }
215
216    #[test]
217    fn sliding_along_the_wire_advances_by_the_delta() {
218        let wire = horizontal_wire();
219        assert_eq!(wire.iter_edges().count(), 1, "one segment to slide along");
220        assert_eq!(
221            wire.start_pos().y,
222            wire.end_pos().y,
223            "the segment is horizontal"
224        );
225        let span = wire.end_pos().x - wire.start_pos().x;
226        assert!(
227            span > 5.0 * GRID_SIZE,
228            "long enough to slide two cells from three cells in without clamping: {span}"
229        );
230
231        let from = FracVal::from(3.0 * GRID_SIZE);
232        let slid = wire.slide_along(from, vec2(2.0 * GRID_SIZE, 0.0));
233
234        assert!(
235            (f32::from(slid) - 5.0 * GRID_SIZE).abs() < 0.01,
236            "sliding {} advanced to {}, expected {}",
237            2.0 * GRID_SIZE,
238            f32::from(slid),
239            5.0 * GRID_SIZE
240        );
241    }
242
243    #[test]
244    fn a_perpendicular_slide_reprojects_onto_the_wire() {
245        let wire = horizontal_wire();
246        let from = FracVal::from(3.0 * GRID_SIZE);
247        let anchor = wire.map_linear_distance_to_position(from).location;
248        assert!(
249            (anchor.y - wire.start_pos().y).abs() < 0.01,
250            "the starting anchor sits on the wire"
251        );
252
253        let slid = wire.slide_along(from, vec2(0.0, 4.0 * GRID_SIZE));
254        let landed = wire.map_linear_distance_to_position(slid).location;
255
256        assert!(
257            (landed.y - wire.start_pos().y).abs() < 0.01,
258            "an off-wire delta re-projects back onto the wire: {landed:?}"
259        );
260        assert!(
261            (landed.x - anchor.x).abs() < 0.01,
262            "and does not move along it: {} -> {}",
263            anchor.x,
264            landed.x
265        );
266    }
267}