Skip to main content

connector_routing/
nets.rs

1//! Routed nets as edge sets of a routing graph: the common input of ordering and
2//! nudging, for two-terminal connectors and hyperedge trees alike.
3
4use alloc::collections::BTreeMap;
5use alloc::vec::Vec;
6
7use crate::geom::{DirSet, Direction};
8use crate::graph::{RoutingGraph, VertexId};
9use crate::route::Route;
10
11/// One routed net: the graph edges it uses and its terminals.
12#[derive(Debug, Clone, Default, PartialEq, Eq)]
13pub struct Net {
14    /// For each vertex the net touches, the directions of its edges there.
15    pub(crate) arms: BTreeMap<VertexId, DirSet>,
16    /// The terminal vertices (ports). Segments through a terminal are fixed.
17    pub(crate) terminals: Vec<VertexId>,
18}
19
20impl Net {
21    /// The net of a connector route.
22    #[must_use]
23    pub fn from_route(graph: &RoutingGraph, route: &Route) -> Self {
24        let mut net = Self::default();
25        net.add_path(graph, &route.vertices);
26        if let (Some(&first), Some(&last)) = (route.vertices.first(), route.vertices.last()) {
27            net.terminals.push(first);
28            if last != first {
29                net.terminals.push(last);
30            }
31        }
32
33        net
34    }
35
36    /// Adds the edges of a vertex path.
37    pub(crate) fn add_path(&mut self, graph: &RoutingGraph, path: &[VertexId]) {
38        if let [only] = path {
39            self.arms.entry(*only).or_default();
40        }
41
42        for pair in path.windows(2) {
43            let dir = Direction::between(graph.point(pair[0]), graph.point(pair[1]))
44                .expect("consecutive route vertices are aligned");
45            *self.arms.entry(pair[0]).or_default() |= DirSet::only(dir);
46            *self.arms.entry(pair[1]).or_default() |= DirSet::only(dir.reverse());
47        }
48    }
49
50    /// The directions of the net's edges at `v`.
51    #[must_use]
52    pub(crate) fn arms_at(&self, v: VertexId) -> DirSet {
53        self.arms.get(&v).copied().unwrap_or_default()
54    }
55
56    /// Whether the net uses the edge leaving `v` in direction `dir`.
57    #[must_use]
58    pub(crate) fn has_edge(&self, v: VertexId, dir: Direction) -> bool {
59        self.arms_at(v).contains(dir)
60    }
61
62    /// Every edge once, as `(v, dir)` with `dir` either [`Direction::Right`] or
63    /// [`Direction::Up`].
64    pub(crate) fn edges(&self) -> impl Iterator<Item = (VertexId, Direction)> + '_ {
65        self.arms.iter().flat_map(|(&v, &arms)| {
66            [Direction::Right, Direction::Up]
67                .into_iter()
68                .filter(move |&d| arms.contains(d))
69                .map(move |d| (v, d))
70        })
71    }
72}