Skip to main content

connector_routing/
graph.rs

1//! The [`RoutingGraph`]: a partial grid whose vertices have at most one neighbour per
2//! [`Direction`].
3//!
4//! The orthogonal visibility graph is one; the searches, congestion, ordering and
5//! nudging rely only on the partial-grid structure, so other builders can plug in.
6
7use alloc::collections::BTreeMap;
8use alloc::vec::Vec;
9
10use crate::geom::{Direction, Point};
11
12/// A vertex of a [`RoutingGraph`].
13///
14/// Ids are slots: they stay valid while other vertices are added or removed, and the
15/// slot of a removed vertex is reused later. Use [`RoutingGraph::capacity`] to size
16/// per-vertex arrays.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct VertexId(pub(crate) u32);
19
20impl VertexId {
21    /// The slot index, below [`RoutingGraph::capacity`].
22    #[must_use]
23    pub const fn index(self) -> usize {
24        self.0 as usize
25    }
26}
27
28/// The marker for "no neighbour" in [`Slot::neighbors`].
29const NONE: u32 = u32::MAX;
30
31/// One vertex slot.
32#[derive(Debug, Clone)]
33struct Slot {
34    /// The vertex position. Meaningless for a free slot.
35    point: Point,
36    /// The neighbour in each direction, indexed by [`Direction::index`], or [`NONE`].
37    neighbors: [u32; 4],
38    /// Whether the slot holds a vertex.
39    alive: bool,
40}
41
42/// A partial grid: points joined by axis-parallel, obstacle-free edges.
43///
44/// Every vertex has at most one neighbour in each direction, and the edge to it is the
45/// segment between the two points. Edges are undirected: `b` is the right neighbour of
46/// `a` exactly when `a` is the left neighbour of `b`.
47#[derive(Debug, Clone, Default)]
48pub struct RoutingGraph {
49    /// Vertex slots, live and free.
50    slots: Vec<Slot>,
51    /// Free slot indices, reused last in, first out.
52    free: Vec<u32>,
53    /// The vertex at each point.
54    by_point: BTreeMap<Point, VertexId>,
55}
56
57impl RoutingGraph {
58    /// Creates an empty graph.
59    #[must_use]
60    pub fn new() -> Self {
61        Self::default()
62    }
63
64    /// The number of vertices.
65    #[must_use]
66    pub fn len(&self) -> usize {
67        self.by_point.len()
68    }
69
70    /// Whether the graph has no vertices.
71    #[must_use]
72    pub fn is_empty(&self) -> bool {
73        self.by_point.is_empty()
74    }
75
76    /// One more than the largest slot index ever used; the size for per-vertex arrays.
77    #[must_use]
78    pub fn capacity(&self) -> usize {
79        self.slots.len()
80    }
81
82    /// The vertex at `point`, if any.
83    #[must_use]
84    pub fn vertex_at(&self, point: Point) -> Option<VertexId> {
85        self.by_point.get(&point).copied()
86    }
87
88    /// The position of vertex `v`.
89    ///
90    /// # Panics
91    ///
92    /// Panics if `v` is not a vertex of this graph.
93    #[must_use]
94    pub fn point(&self, v: VertexId) -> Point {
95        let slot = &self.slots[v.index()];
96        assert!(slot.alive, "vertex {v:?} is not in the graph");
97
98        slot.point
99    }
100
101    /// Whether `v` is a live vertex of this graph.
102    #[must_use]
103    pub fn contains(&self, v: VertexId) -> bool {
104        self.slots.get(v.index()).is_some_and(|slot| slot.alive)
105    }
106
107    /// The neighbour of `v` in direction `dir`, if any.
108    #[must_use]
109    pub fn neighbor(&self, v: VertexId, dir: Direction) -> Option<VertexId> {
110        let id = self.slots[v.index()].neighbors[dir.index()];
111
112        (id != NONE).then_some(VertexId(id))
113    }
114
115    /// Every vertex, in increasing point order.
116    pub fn vertices(&self) -> impl Iterator<Item = VertexId> + '_ {
117        self.by_point.values().copied()
118    }
119
120    /// Every edge once, as `(a, b)` with `b` to the right of or above `a`, in increasing
121    /// point order of `a`.
122    pub fn edges(&self) -> impl Iterator<Item = (VertexId, VertexId)> + '_ {
123        self.vertices().flat_map(move |v| {
124            [Direction::Right, Direction::Up]
125                .into_iter()
126                .filter_map(move |dir| self.neighbor(v, dir).map(|w| (v, w)))
127        })
128    }
129
130    /// The graph as sorted point and edge lists, independent of vertex ids.
131    ///
132    /// Two graphs are the same geometric graph exactly when their canonical forms are
133    /// equal.
134    #[must_use]
135    pub fn canonical(&self) -> (Vec<Point>, Vec<(Point, Point)>) {
136        let points = self.by_point.keys().copied().collect();
137        let edges = self
138            .edges()
139            .map(|(a, b)| (self.point(a), self.point(b)))
140            .collect();
141
142        (points, edges)
143    }
144
145    /// Adds an unconnected vertex at `point`, which must not hold a vertex yet.
146    pub(crate) fn insert(&mut self, point: Point) -> VertexId {
147        debug_assert!(!self.by_point.contains_key(&point), "duplicate vertex");
148        let slot = Slot {
149            point,
150            neighbors: [NONE; 4],
151            alive: true,
152        };
153        let id = if let Some(index) = self.free.pop() {
154            self.slots[index as usize] = slot;
155            index
156        } else {
157            let index = u32::try_from(self.slots.len()).expect("fewer than 2^32 vertices");
158            self.slots.push(slot);
159            index
160        };
161
162        let v = VertexId(id);
163        self.by_point.insert(point, v);
164
165        v
166    }
167
168    /// Makes `b` the neighbour of `a` in direction `dir` (and `a` that of `b` in the
169    /// reverse direction), replacing earlier links of both in those directions.
170    pub(crate) fn link(&mut self, a: VertexId, dir: Direction, b: VertexId) {
171        self.slots[a.index()].neighbors[dir.index()] = b.0;
172        self.slots[b.index()].neighbors[dir.reverse().index()] = a.0;
173    }
174
175    /// Clears the link of `a` in direction `dir` (and its counterpart).
176    pub(crate) fn unlink(&mut self, a: VertexId, dir: Direction) {
177        if let Some(b) = self.neighbor(a, dir) {
178            self.slots[b.index()].neighbors[dir.reverse().index()] = NONE;
179        }
180
181        self.slots[a.index()].neighbors[dir.index()] = NONE;
182    }
183
184    /// Removes vertex `v`, joining its left and right (and its lower and upper)
185    /// neighbours directly, as removing a point from the middle of a segment does.
186    pub(crate) fn remove(&mut self, v: VertexId) {
187        for (back, forward) in [
188            (Direction::Left, Direction::Right),
189            (Direction::Down, Direction::Up),
190        ] {
191            match (self.neighbor(v, back), self.neighbor(v, forward)) {
192                (Some(a), Some(b)) => self.link(a, forward, b),
193                (Some(_), None) => self.unlink(v, back),
194                (None, Some(_)) => self.unlink(v, forward),
195                (None, None) => {}
196            }
197        }
198
199        let slot = &mut self.slots[v.index()];
200        slot.alive = false;
201        slot.neighbors = [NONE; 4];
202        self.by_point.remove(&slot.point);
203        self.free.push(v.0);
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    //! Unit tests for linking and removal.
210
211    use super::*;
212
213    /// Removing a middle vertex joins its neighbours; slots are reused.
214    #[test]
215    fn remove_joins_neighbours() {
216        let mut graph = RoutingGraph::new();
217        let a = graph.insert(Point::new(0, 0));
218        let b = graph.insert(Point::new(5, 0));
219        let c = graph.insert(Point::new(9, 0));
220        graph.link(a, Direction::Right, b);
221        graph.link(b, Direction::Right, c);
222
223        graph.remove(b);
224        assert_eq!(graph.neighbor(a, Direction::Right), Some(c));
225        assert_eq!(graph.neighbor(c, Direction::Left), Some(a));
226        assert_eq!(graph.len(), 2);
227
228        let d = graph.insert(Point::new(1, 1));
229        assert_eq!(d, b);
230        assert_eq!(graph.canonical().1, [(Point::new(0, 0), Point::new(9, 0))]);
231    }
232}