Skip to main content

brep_ecad_core/
autoroute.rs

1//! Grid-based autorouter.
2//!
3//! Each net is routed island to island (a Prim-style tree) with A* over a uniform
4//! grid on every copper layer, using 45° moves and through vias.
5//!
6//! Clearance is exact, not approximated by the grid. Every copper obstacle is convex
7//! (rectangles, capsules, discs, outline edges). If both ends of a move of length `L`
8//! lie at least `T` from a convex shape, every point of the move lies at least
9//! `√(T² − L²/4)` from it: a chord that dips closer would be shorter than `L`. Nodes
10//! are therefore legal only at `T = √(Q² + pitch²/2)`, with `Q = clearance + width/2`,
11//! which guarantees `Q` along every straight or diagonal move, so routed copper passes
12//! the exact-geometry DRC while the extra margin stays a few micrometres.
13//!
14//! Net classes. Each net is routed at its class's track width and via
15//! ([`crate::board::DesignRules::width_for`], [`crate::board::DesignRules::via_for`]),
16//! and the `clearance` above is PER PAIR: between the net being routed and each
17//! obstacle it is [`crate::board::DesignRules::clearance_between_classes`] of their
18//! two classes, the larger of the two, which is the rule DRC checks. The grid keeps
19//! one set of maps per `Profile` (a track width or via diameter, and the class of
20//! the net using it), and grows each obstacle on a map by the pair's clearance; a
21//! board with no classes has exactly the maps, and routes exactly as, before
22//! classes existed. A net that is blocked by earlier routes is retried with those routes allowed
23//! at a high cost; the nets it crosses are ripped up and queued again, with bounded
24//! attempts. Work is split into [`RouteJob::step`] calls, measured in node
25//! expansions rather than wall time, so interactive and WebAssembly hosts stay
26//! responsive.
27//!
28//! Vias follow the board's [`ViaPolicy`]. `Avoid` routes exactly as `Allow` does, so
29//! it connects every net `Allow` would, and then removes vias: each net that has any
30//! is rerouted against the finished board, first searching for a route with no via
31//! at all, and keeps the new copper only if it connects everything with fewer vias.
32//! Routing with vias priced out from the start was tried and rejected: long
33//! single-layer detours fill the board early and later nets fail to route.
34use crate::board::{
35    Board, Connectivity, CopperItem, CopperRef, DesignRules, NetClass, Shape, Track, Via, ViaPolicy,
36};
37use crate::{Document, Netlist, Point, Uuid};
38use std::cmp::Reverse;
39use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
40
41/// Pad entry points for one net.
42#[derive(Default)]
43struct Stubs {
44    /// Per seed node, the stub from the pad centre up to (not including) the node.
45    paths: HashMap<u32, Vec<Point>>,
46    /// Seed nodes inside large pads, such as exposed thermal pads, where a via fits.
47    vias: HashSet<u32>,
48}
49
50/// Claim owner for copper that no routed net may touch.
51const BLOCKED: u32 = u32::MAX;
52/// Upper bound on grid cells per layer; the pitch is coarsened to stay below it.
53const MAX_CELLS: usize = 1_500_000;
54const DIRECTIONS: [(i64, i64); 8] = [
55    (1, 0),
56    (1, 1),
57    (0, 1),
58    (-1, 1),
59    (-1, 0),
60    (-1, -1),
61    (0, -1),
62    (1, -1),
63];
64const NO_DIRECTION: u8 = 8;
65const NO_PARENT: u32 = u32::MAX;
66/// Width of the band around routed pads that other nets are discouraged from using.
67const APPROACH: i32 = 800;
68/// Rip-up retries a single net may initiate.
69const MAX_ATTEMPTS: u32 = 4;
70/// Rerouting passes over nets with vias; another pass runs only if one improved.
71const MAX_CLEANUP_PASSES: u32 = 3;
72
73#[derive(Clone, Copy, Debug)]
74struct Grid {
75    origin: Point,
76    pitch: i32,
77    width: usize,
78    height: usize,
79    layers: usize,
80}
81impl Grid {
82    fn cells(&self) -> usize {
83        self.width * self.height
84    }
85    fn centre(&self, cell: usize) -> Point {
86        Point::new(
87            self.origin.x + (cell % self.width) as i32 * self.pitch,
88            self.origin.y + (cell / self.width) as i32 * self.pitch,
89        )
90    }
91    /// Inclusive cell rectangle whose centres lie within the world bounds.
92    fn span(&self, min: Point, max: Point) -> Option<(usize, usize, usize, usize)> {
93        let pitch = i64::from(self.pitch);
94        let low = |v: i32, o: i32| (i64::from(v) - i64::from(o)).div_euclid(pitch) + 1;
95        let high = |v: i32, o: i32| (i64::from(v) - i64::from(o)).div_euclid(pitch);
96        let x0 = (low(min.x - 1, self.origin.x)).max(0);
97        let y0 = (low(min.y - 1, self.origin.y)).max(0);
98        let x1 = high(max.x, self.origin.x).min(self.width as i64 - 1);
99        let y1 = high(max.y, self.origin.y).min(self.height as i64 - 1);
100        (x0 <= x1 && y0 <= y1).then_some((x0 as usize, x1 as usize, y0 as usize, y1 as usize))
101    }
102}
103
104/// Whether a disc lies entirely within a shape.
105fn disc_inside(shape: &Shape, at: Point, radius: i32) -> bool {
106    match shape.clone() {
107        Shape::Rect { min, max } => {
108            at.x - radius >= min.x
109                && at.x + radius <= max.x
110                && at.y - radius >= min.y
111                && at.y + radius <= max.y
112        }
113        Shape::Capsule { a, b, radius: r } => {
114            crate::board::point_segment_distance(at, a, b) + f64::from(radius) <= f64::from(r)
115        }
116        // A disc at least as round as the corners fits as in the plain box; a
117        // smaller one must keep within the corner arcs, i.e. within `r - radius`
118        // of the core rectangle.
119        Shape::RoundRect { min, max, radius: r } if radius >= r => {
120            disc_inside(&Shape::Rect { min, max }, at, radius)
121        }
122        Shape::RoundRect { min, max, radius: r } => {
123            let core = Shape::Rect {
124                min: Point::new(min.x + r, min.y + r),
125                max: Point::new(max.x - r, max.y - r),
126            };
127            core.distance_to_point(at) + f64::from(radius) <= f64::from(r)
128        }
129        // The disc fits where its centre lies at least its radius deep.
130        Shape::Polygon { .. } => shape.depth(at) >= f64::from(radius),
131    }
132}
133
134/// Visit cells whose centres are closer than `radius` to the shape.
135fn for_cells_near(grid: &Grid, shape: &Shape, radius: f64, mut visit: impl FnMut(usize)) {
136    let (min, max) = shape.bounds();
137    let reach = radius.ceil() as i32 + 1;
138    let Some((x0, x1, y0, y1)) = grid.span(
139        Point::new(min.x.saturating_sub(reach), min.y.saturating_sub(reach)),
140        Point::new(max.x.saturating_add(reach), max.y.saturating_add(reach)),
141    ) else {
142        return;
143    };
144    for y in y0..=y1 {
145        for x in x0..=x1 {
146            let cell = y * grid.width + x;
147            if shape.distance_to_point(grid.centre(cell)) < radius {
148                visit(cell);
149            }
150        }
151    }
152}
153
154/// Per-cell claims by copper owners. Each owner claims a cell at most once, so a
155/// cell is usable by net `n` when unclaimed or claimed only by `n`.
156#[derive(Clone)]
157struct Claims {
158    count: Vec<u16>,
159    sum: Vec<u32>,
160}
161impl Claims {
162    fn new(cells: usize) -> Self {
163        Self {
164            count: vec![0; cells],
165            sum: vec![0; cells],
166        }
167    }
168    fn free(&self, cell: usize, net: u32) -> bool {
169        let count = self.count[cell];
170        count == 0 || (count == 1 && self.sum[cell] == net)
171    }
172    fn add(&mut self, cell: usize, owner: u32) {
173        self.count[cell] = self.count[cell].saturating_add(1);
174        self.sum[cell] = self.sum[cell].wrapping_add(owner);
175    }
176    fn remove(&mut self, cell: usize, owner: u32) {
177        self.count[cell] -= 1;
178        self.sum[cell] = self.sum[cell].wrapping_sub(owner);
179    }
180}
181
182/// What one set of grid maps is inflated for: copper `size` across (a track width
183/// or a via diameter) of a net in class `class`, an index into
184/// [`RouteJob::gaps`]. Obstacle `o` is kept `gaps[class][o's class]` from it.
185#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
186struct Profile {
187    size: i32,
188    class: usize,
189}
190
191struct RouteNet {
192    name: String,
193    width: i32,
194    /// The net's class, an index into [`RouteJob::gaps`].
195    class: usize,
196    /// Its via diameter and drill, its class's.
197    via: (i32, i32),
198    /// The [`Profile`]s its tracks and its vias are searched on.
199    profile: usize,
200    via_profile: usize,
201    /// Copper item indices of each island carrying the net.
202    islands: Vec<Vec<usize>>,
203    span: i64,
204}
205
206#[derive(Default)]
207struct NetState {
208    tracks: Vec<Track>,
209    vias: Vec<Via>,
210    /// Route claims as `map * cells + cell`.
211    claimed: HashSet<u64>,
212    /// Island connections that could not be made in the last attempt.
213    missing: usize,
214    routed: bool,
215}
216
217#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
218pub struct Progress {
219    pub total_nets: usize,
220    pub completed_nets: usize,
221    pub failed_nets: usize,
222    pub rip_ups: usize,
223    /// Every net is routed and nets with vias are being rerouted to drop them.
224    pub removing_vias: bool,
225    pub done: bool,
226}
227
228#[derive(Clone, Debug, Default, PartialEq)]
229pub struct RouteOutcome {
230    pub tracks: Vec<Track>,
231    pub vias: Vec<Via>,
232    /// Nets left with unrouted connections.
233    pub unrouted: Vec<String>,
234    /// Grid pitch actually used, after any coarsening for large boards.
235    pub pitch: i32,
236}
237impl RouteOutcome {
238    /// Add the routed copper to the board. Existing copper is kept.
239    pub fn apply(self, board: &mut Board) {
240        board.tracks.extend(self.tracks);
241        board.vias.extend(self.vias);
242    }
243}
244
245/// A resumable routing run over a snapshot of the board.
246pub struct RouteJob {
247    grid: Grid,
248    /// The track profiles of routed nets, then their via profiles; one set of
249    /// maps each.
250    profiles: Vec<Profile>,
251    /// The clearance between copper of two classes, by class index: filled once
252    /// from [`crate::board::DesignRules::clearance_between_classes`], the one
253    /// lookup DRC and the zone fill use, and the only clearance this router reads.
254    /// Class 0 is the class of copper on no net, Default.
255    gaps: Vec<Vec<i32>>,
256    /// The largest entry of `gaps`, for bounding-box prefilters.
257    max_gap: i32,
258    items: Vec<CopperItem>,
259    /// The class of each static item: that of the nets its island carries.
260    item_class: Vec<usize>,
261    /// Claim owner of each static item: a routed net index or `BLOCKED`.
262    owners: Vec<u32>,
263    outline: Vec<Point>,
264    /// The board's cutouts, holes in the outline a route keeps the edge
265    /// clearance from as it does from the outline.
266    cutouts: Vec<Vec<Point>>,
267    edge_clearance: i32,
268    static_claims: Vec<Claims>,
269    route_claims: Vec<Claims>,
270    /// Per layer, the approaches to routed nets' pads. Other nets pay to pass
271    /// through them, which leaves room for fan-out from fine-pitch parts.
272    approaches: Vec<Claims>,
273    nets: Vec<RouteNet>,
274    states: Vec<NetState>,
275    queue: VecDeque<usize>,
276    attempts: Vec<u32>,
277    rip_ups: usize,
278    rip_up_limit: usize,
279    expansions: u64,
280    cost: Vec<u32>,
281    parent: Vec<u32>,
282    direction: Vec<u8>,
283    stamp: Vec<u32>,
284    generation: u32,
285    /// How often each node has been contested; raises its cost for every net.
286    history: Vec<u16>,
287    /// Cells where a via would touch a pad; through vias span every layer.
288    no_via: Vec<bool>,
289    vias: ViaPolicy,
290    /// Nets still to reroute in the current via clean-up pass; `None` until routing
291    /// has finished and the first pass begins.
292    cleanup: Option<VecDeque<usize>>,
293    cleanup_passes: u32,
294    /// Where copper given up by nets that lost vias this pass sat, grown by the
295    /// search margin. Only nets near it can gain from another pass.
296    cleanup_freed: Vec<(Point, Point)>,
297}
298
299impl RouteJob {
300    /// Prepare to connect every unrouted connection. Existing copper is kept and
301    /// treated as part of its net, or as an obstacle.
302    pub fn new(board: &Board, netlist: &Netlist) -> Self {
303        let conn = board.connectivity(netlist);
304        let rules = &board.rules;
305        // Every class in play, Default first, so netless copper is class 0.
306        let mut classes: Vec<NetClass> = vec![rules.default_class()];
307        let mut class_index = |class: NetClass| {
308            classes
309                .iter()
310                .position(|c| c.name == class.name)
311                .unwrap_or_else(|| {
312                    classes.push(class);
313                    classes.len() - 1
314                })
315        };
316        let island_class: Vec<usize> = conn
317            .island_nets
318            .iter()
319            .map(|nets| class_index(rules.class_of_nets(nets.iter().map(String::as_str))))
320            .collect();
321        let item_class: Vec<usize> = conn.islands.iter().map(|&i| island_class[i]).collect();
322        let mut island_items = vec![vec![]; conn.island_count];
323        for (i, island) in conn.islands.iter().enumerate() {
324            island_items[*island].push(i);
325        }
326        let mut net_islands: BTreeMap<&str, BTreeSet<usize>> = BTreeMap::new();
327        for (i, net) in conn.item_nets.iter().enumerate() {
328            if let Some(net) = net {
329                net_islands.entry(net).or_default().insert(conn.islands[i]);
330            }
331        }
332        let mut nets: Vec<RouteNet> = net_islands
333            .into_iter()
334            .filter(|(_, islands)| islands.len() > 1)
335            .map(|(name, islands)| {
336                let centres: Vec<Point> = islands
337                    .iter()
338                    .flat_map(|&s| island_items[s].iter())
339                    .map(|&i| conn.items[i].shape.center())
340                    .collect();
341                let (x0, x1) = centres
342                    .iter()
343                    .fold((i32::MAX, i32::MIN), |(a, b), p| (a.min(p.x), b.max(p.x)));
344                let (y0, y1) = centres
345                    .iter()
346                    .fold((i32::MAX, i32::MIN), |(a, b), p| (a.min(p.y), b.max(p.y)));
347                let class = rules.class_of(Some(name));
348                RouteNet {
349                    name: name.to_owned(),
350                    width: rules.width_for(name),
351                    via: (class.via_diameter, class.via_drill),
352                    class: class_index(class),
353                    profile: 0,
354                    via_profile: 0,
355                    islands: islands.iter().map(|&s| island_items[s].clone()).collect(),
356                    span: i64::from(x1) - i64::from(x0) + i64::from(y1) - i64::from(y0),
357                }
358            })
359            .collect();
360        nets.sort_by(|a, b| a.span.cmp(&b.span).then_with(|| a.name.cmp(&b.name)));
361        let gaps: Vec<Vec<i32>> = classes
362            .iter()
363            .map(|a| {
364                classes
365                    .iter()
366                    .map(|b| DesignRules::clearance_between_classes(a, b).0)
367                    .collect()
368            })
369            .collect();
370        let max_gap = gaps.iter().flatten().copied().max().unwrap_or(0);
371        let tracks: Vec<Profile> = nets
372            .iter()
373            .map(|n| Profile {
374                size: n.width,
375                class: n.class,
376            })
377            .collect::<BTreeSet<_>>()
378            .into_iter()
379            .collect();
380        let vias: Vec<Profile> = nets
381            .iter()
382            .map(|n| Profile {
383                size: n.via.0,
384                class: n.class,
385            })
386            .collect::<BTreeSet<_>>()
387            .into_iter()
388            .collect();
389        for net in &mut nets {
390            let (track, via) = (
391                Profile {
392                    size: net.width,
393                    class: net.class,
394                },
395                Profile {
396                    size: net.via.0,
397                    class: net.class,
398                },
399            );
400            net.profile = tracks.binary_search(&track).unwrap_or(0);
401            net.via_profile = tracks.len() + vias.binary_search(&via).unwrap_or(0);
402        }
403        let thinnest = tracks
404            .iter()
405            .map(|p| &p.size)
406            .chain(board.tracks.iter().map(|t| &t.width))
407            .min()
408            .copied()
409            .unwrap_or(rules.track_width);
410        let profiles: Vec<Profile> = tracks.into_iter().chain(vias).collect();
411        let (min, max) = board.outline_bounds();
412        let dims = |pitch: i32| {
413            (
414                ((i64::from(max.x) - i64::from(min.x)) / i64::from(pitch) + 1) as usize,
415                ((i64::from(max.y) - i64::from(min.y)) / i64::from(pitch) + 1) as usize,
416            )
417        };
418        let mut pitch = rules.routing_grid.min(thinnest * 7 / 10).max(10);
419        while {
420            let (w, h) = dims(pitch);
421            w * h > MAX_CELLS
422        } {
423            pitch += pitch / 4 + 1;
424        }
425        let (width, height) = dims(pitch);
426        let grid = Grid {
427            origin: min,
428            pitch,
429            width,
430            height,
431            layers: usize::from(board.layer_count.max(1)),
432        };
433        let cells = grid.cells();
434        let nodes = cells * grid.layers;
435        let maps = profiles.len() * grid.layers;
436        let count = nets.len();
437        let mut job = Self {
438            grid,
439            gaps,
440            max_gap,
441            items: vec![],
442            item_class,
443            owners: vec![],
444            outline: board.outline.clone(),
445            cutouts: board.cutouts.iter().map(|c| c.points.clone()).collect(),
446            edge_clearance: rules.edge_clearance,
447            static_claims: vec![Claims::new(cells); maps],
448            route_claims: vec![Claims::new(cells); maps],
449            approaches: vec![Claims::new(cells); grid.layers],
450            states: (0..count).map(|_| NetState::default()).collect(),
451            queue: (0..count).collect(),
452            attempts: vec![0; count],
453            rip_ups: 0,
454            rip_up_limit: count * MAX_ATTEMPTS as usize + 16,
455            expansions: 0,
456            cost: vec![0; nodes],
457            parent: vec![NO_PARENT; nodes],
458            direction: vec![NO_DIRECTION; nodes],
459            stamp: vec![0; nodes],
460            generation: 0,
461            history: vec![0; nodes],
462            no_via: vec![false; cells],
463            vias: rules.autoroute_vias,
464            cleanup: None,
465            cleanup_passes: 0,
466            cleanup_freed: vec![],
467            profiles,
468            nets,
469        };
470        job.paint_static(board, &conn);
471        job.items = conn.items;
472        job
473    }
474
475    /// Distance from a node to an obstacle below which the node is unusable for a
476    /// profile, so that moves between usable nodes keep `gap` (see the module docs).
477    fn keep_out(&self, gap: i32, profile: usize) -> f64 {
478        let q = f64::from(gap) + f64::from(self.profiles[profile].size) / 2.;
479        let pitch = f64::from(self.grid.pitch);
480        (q * q + pitch * pitch / 2.).sqrt() + 1.
481    }
482
483    fn next_generation(&mut self) -> u32 {
484        if self.generation == u32::MAX {
485            self.stamp.fill(0);
486            self.generation = 0;
487        }
488        self.generation += 1;
489        self.generation
490    }
491
492    fn paint_static(&mut self, board: &Board, conn: &Connectivity) {
493        let index: BTreeMap<&str, u32> = self
494            .nets
495            .iter()
496            .enumerate()
497            .map(|(i, n)| (n.name.as_str(), i as u32))
498            .collect();
499        self.owners = conn
500            .islands
501            .iter()
502            .map(|island| {
503                conn.island_net(*island)
504                    .and_then(|net| index.get(net))
505                    .copied()
506                    .unwrap_or(BLOCKED)
507            })
508            .collect();
509        let mut owners: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
510        for (i, owner) in self.owners.iter().enumerate() {
511            owners.entry(*owner).or_default().push(i);
512        }
513        let grid = self.grid;
514        let cells = grid.cells();
515        // Vias stay off pads, including pads of their own net: a via in a solder
516        // land wicks solder. Large thermal pads opt back in through `Stubs::vias`.
517        // One map serves every net, so it is sized for the largest via and its
518        // class's own clearance; other nets' pads also keep their pair clearance
519        // through the static claims.
520        let via_reach = self
521            .profiles
522            .iter()
523            .filter(|p| {
524                self.nets
525                    .iter()
526                    .any(|n| self.profiles[n.via_profile] == **p)
527            })
528            .map(|p| f64::from(p.size / 2 + self.gaps[p.class][p.class] / 2))
529            .fold(0., f64::max);
530        for item in conn
531            .items
532            .iter()
533            .filter(|i| matches!(i.owner, CopperRef::Pad { .. }))
534        {
535            let no_via = &mut self.no_via;
536            for_cells_near(&grid, &item.shape, via_reach, |cell| no_via[cell] = true);
537        }
538        let outside: Vec<bool> = (0..cells)
539            .map(|cell| !board.outline_contains(grid.centre(cell)))
540            .collect();
541        // The approach band around routed pads: as wide as the widest track keeps
542        // from copper of its own class, plus `APPROACH`.
543        let approach = (0..self.profiles.len())
544            .filter(|&p| self.nets.iter().any(|n| n.profile == p))
545            .map(|p| self.keep_out(self.gaps[self.profiles[p].class][self.profiles[p].class], p))
546            .fold(0., f64::max)
547            + f64::from(APPROACH);
548        for class in 0..self.profiles.len() {
549            let routing = self.profiles[class].class;
550            for (&owner, members) in &owners {
551                let generation = self.next_generation();
552                for &i in members {
553                    let item = &conn.items[i];
554                    let radius = self.keep_out(self.gaps[routing][self.item_class[i]], class);
555                    for layer in item.layers.0..=item.layers.1 {
556                        let layer = usize::from(layer);
557                        let claims = &mut self.static_claims[class * grid.layers + layer];
558                        let stamp = &mut self.stamp;
559                        for_cells_near(&grid, &item.shape, radius, |cell| {
560                            let node = layer * cells + cell;
561                            if stamp[node] != generation {
562                                stamp[node] = generation;
563                                claims.add(cell, owner);
564                            }
565                        });
566                    }
567                }
568            }
569            if class == 0 {
570                let radius = approach;
571                for (&owner, members) in owners.iter().filter(|(o, _)| **o != BLOCKED) {
572                    let generation = self.next_generation();
573                    for &i in members {
574                        let item = &conn.items[i];
575                        if !matches!(item.owner, CopperRef::Pad { .. }) {
576                            continue;
577                        }
578                        for layer in item.layers.0..=item.layers.1 {
579                            let layer = usize::from(layer);
580                            let claims = &mut self.approaches[layer];
581                            let stamp = &mut self.stamp;
582                            for_cells_near(&grid, &item.shape, radius, |cell| {
583                                let node = layer * cells + cell;
584                                if stamp[node] != generation {
585                                    stamp[node] = generation;
586                                    claims.add(cell, owner);
587                                }
588                            });
589                        }
590                    }
591                }
592            }
593            let edge_radius = self.keep_out(board.rules.edge_clearance, class);
594            for layer in 0..grid.layers {
595                let claims = &mut self.static_claims[class * grid.layers + layer];
596                for (cell, out) in outside.iter().enumerate() {
597                    if *out {
598                        claims.add(cell, BLOCKED);
599                    }
600                }
601                for (a, b) in board.outline_edges() {
602                    for_cells_near(&grid, &Shape::segment(a, b, 0), edge_radius, |cell| {
603                        claims.add(cell, BLOCKED)
604                    });
605                }
606            }
607        }
608    }
609
610    fn map(&self, class: usize, node: usize) -> (usize, usize) {
611        let cells = self.grid.cells();
612        (class * self.grid.layers + node / cells, node % cells)
613    }
614    /// Whether a node may carry the net's track, and whether that uses another
615    /// net's route (only permitted in soft mode).
616    fn legal(&self, net: usize, node: usize, soft: bool) -> Option<bool> {
617        let (map, cell) = self.map(self.nets[net].profile, node);
618        if !self.static_claims[map].free(cell, net as u32) {
619            return None;
620        }
621        let conflict = !self.route_claims[map].free(cell, net as u32);
622        (!conflict || soft).then_some(conflict)
623    }
624    fn via_legal(&self, net: usize, cell: usize, soft: bool) -> Option<bool> {
625        let class = self.nets[net].via_profile;
626        let mut conflict = false;
627        for layer in 0..self.grid.layers {
628            let map = class * self.grid.layers + layer;
629            if !self.static_claims[map].free(cell, net as u32) {
630                return None;
631            }
632            conflict |= !self.route_claims[map].free(cell, net as u32);
633        }
634        (!conflict || soft).then_some(conflict)
635    }
636
637    /// Statically legal nodes inside an island's copper. Pads record the stub back to
638    /// their centre; a pad with no usable interior node escapes to nearby grid nodes.
639    fn seeds(&self, net: usize, island: usize, stubs: &mut Stubs) -> Vec<u32> {
640        let cells = self.grid.cells();
641        let class = self.nets[net].profile;
642        let usable = |node: u32| {
643            let (map, cell) = self.map(class, node as usize);
644            self.static_claims[map].free(cell, net as u32)
645        };
646        let mut seeds = vec![];
647        for &i in &self.nets[net].islands[island] {
648            let item = &self.items[i];
649            let is_pad = matches!(item.owner, CopperRef::Pad { .. });
650            for layer in item.layers.0..=item.layers.1 {
651                let base = usize::from(layer) * cells;
652                let mut inside = vec![];
653                for_cells_near(&self.grid, &item.shape, 0.5, |cell| {
654                    let node = (base + cell) as u32;
655                    if usable(node) {
656                        inside.push(node);
657                    }
658                });
659                if is_pad {
660                    if inside.is_empty() {
661                        for (node, stub) in self.escapes(net, item, layer) {
662                            stubs.paths.entry(node).or_insert(stub);
663                            inside.push(node);
664                        }
665                    } else {
666                        let (min, max) = item.shape.bounds();
667                        let diameter = self.nets[net].via.0;
668                        let radius = diameter / 2;
669                        let large = (max.x - min.x).min(max.y - min.y) >= 3 * diameter;
670                        for node in &inside {
671                            stubs
672                                .paths
673                                .entry(*node)
674                                .or_insert_with(|| vec![item.shape.center()]);
675                            let at = self.grid.centre(*node as usize % cells);
676                            if large && disc_inside(&item.shape, at, radius) {
677                                stubs.vias.insert(*node);
678                            }
679                        }
680                    }
681                }
682                seeds.extend(inside);
683            }
684        }
685        seeds.sort_unstable();
686        seeds.dedup();
687        seeds
688    }
689
690    /// Fan-out from a pad whose interior is too tight for the grid: leave the pad
691    /// centre along each axis to a grid line past the pad, then jog onto the nearest
692    /// grid node. Each stub is checked against exact copper geometry.
693    fn escapes(&self, net: usize, pad: &CopperItem, layer: u8) -> Vec<(u32, Vec<Point>)> {
694        let grid = self.grid;
695        let pitch = i64::from(grid.pitch);
696        let width = self.nets[net].width;
697        let centre = pad.shape.center();
698        let (min, max) = pad.shape.bounds();
699        let column = |v: i32, o: i32| (i64::from(v) - i64::from(o)) as f64 / pitch as f64;
700        let mut escapes = vec![];
701        for (dx, dy) in [(1i64, 0i64), (-1, 0), (0, 1), (0, -1)] {
702            for k in 0..6 {
703                let (gx, gy) = if dx != 0 {
704                    let edge = column(if dx > 0 { max.x } else { min.x }, grid.origin.x);
705                    let gx = if dx > 0 {
706                        edge.floor() as i64 + 1 + k
707                    } else {
708                        edge.ceil() as i64 - 1 - k
709                    };
710                    (gx, column(centre.y, grid.origin.y).round() as i64)
711                } else {
712                    let edge = column(if dy > 0 { max.y } else { min.y }, grid.origin.y);
713                    let gy = if dy > 0 {
714                        edge.floor() as i64 + 1 + k
715                    } else {
716                        edge.ceil() as i64 - 1 - k
717                    };
718                    (column(centre.x, grid.origin.x).round() as i64, gy)
719                };
720                if gx < 0 || gy < 0 || gx >= grid.width as i64 || gy >= grid.height as i64 {
721                    break;
722                }
723                let cell = gy as usize * grid.width + gx as usize;
724                let node = (usize::from(layer) * grid.cells() + cell) as u32;
725                let target = grid.centre(cell);
726                let jog = if dx != 0 {
727                    Point::new(target.x, centre.y)
728                } else {
729                    Point::new(centre.x, target.y)
730                };
731                let (map, _) = self.map(self.nets[net].profile, node as usize);
732                if !self.static_claims[map].free(cell, net as u32) {
733                    continue;
734                }
735                let path = crate::board::simplify_path(vec![centre, jog, target]);
736                if path
737                    .windows(2)
738                    .all(|s| self.clear(net, &Shape::segment(s[0], s[1], width), layer))
739                {
740                    let mut stub = path;
741                    stub.pop();
742                    escapes.push((node, stub));
743                    break;
744                }
745            }
746        }
747        escapes
748    }
749
750    /// Exact clearance of new copper against the board edge, other owners' static
751    /// copper, and other nets' routes.
752    fn clear(&self, net: usize, shape: &Shape, layer: u8) -> bool {
753        let gaps = &self.gaps[self.nets[net].class];
754        let (min, max) = shape.bounds();
755        let near = |other: &Shape| {
756            let (a, b) = other.bounds();
757            a.x <= max.x.saturating_add(self.max_gap)
758                && b.x >= min.x.saturating_sub(self.max_gap)
759                && a.y <= max.y.saturating_add(self.max_gap)
760                && b.y >= min.y.saturating_sub(self.max_gap)
761        };
762        let statics = self
763            .items
764            .iter()
765            .zip(&self.owners)
766            .zip(&self.item_class)
767            .all(|((item, owner), class)| {
768                *owner == net as u32
769                    || layer < item.layers.0
770                    || layer > item.layers.1
771                    || !near(&item.shape)
772                    || shape.distance(&item.shape) >= f64::from(gaps[*class])
773            });
774        let inside = crate::board::polygon_contains(&self.outline, shape.center())
775            && !self.cutouts.iter().any(|c| crate::board::polygon_contains(c, shape.center()))
776            && self.outline_edges().all(|(a, b)| {
777                // Copper ON an edge is never clear, even with no edge clearance:
778                // the mill would cut it.
779                let gap = shape.distance(&Shape::segment(a, b, 0));
780                gap >= f64::from(self.edge_clearance) && gap > 0.
781            });
782        let routes = self.states.iter().enumerate().all(|(j, state)| {
783            let clearance = f64::from(gaps[self.nets[j].class]);
784            j == net
785                || (state
786                    .tracks
787                    .iter()
788                    .filter(|t| t.layer == layer)
789                    .flat_map(|t| t.segments())
790                    .all(|other| !near(&other) || shape.distance(&other) >= clearance)
791                    && state.vias.iter().all(|v| {
792                        let other = Shape::circle(v.at, v.diameter / 2);
793                        !near(&other) || shape.distance(&other) >= clearance
794                    }))
795        });
796        statics && inside && routes
797    }
798    fn outline_edges(&self) -> impl Iterator<Item = (Point, Point)> + '_ {
799        std::iter::once(&self.outline).chain(&self.cutouts).flat_map(|ring| {
800            let n = ring.len();
801            (0..n).map(move |i| (ring[i], ring[(i + 1) % n]))
802        })
803    }
804
805    fn cell_box(&self, nodes: impl Iterator<Item = u32>) -> Option<(i64, i64, i64, i64)> {
806        let cells = self.grid.cells();
807        nodes.fold(None, |b, node| {
808            let cell = node as usize % cells;
809            let (x, y) = (
810                (cell % self.grid.width) as i64,
811                (cell / self.grid.width) as i64,
812            );
813            Some(match b {
814                None => (x, x, y, y),
815                Some((x0, x1, y0, y1)) => (x0.min(x), x1.max(x), y0.min(y), y1.max(y)),
816            })
817        })
818    }
819
820    #[allow(clippy::too_many_arguments)]
821    fn search(
822        &mut self,
823        net: usize,
824        sources: &[u32],
825        targets: &HashMap<u32, usize>,
826        boxes: &[(i64, i64, i64, i64)],
827        window: Option<(i64, i64, i64, i64)>,
828        soft: bool,
829        stubs: &Stubs,
830        via_cost: Option<u32>,
831    ) -> Option<Vec<u32>> {
832        let generation = self.next_generation();
833        let grid = self.grid;
834        let cells = grid.cells();
835        let pitch = u32::try_from(grid.pitch).unwrap_or(1);
836        let straight = pitch;
837        let diagonal = (f64::from(pitch) * std::f64::consts::SQRT_2 * 1.15).round() as u32;
838        let diagonal_floor = (f64::from(pitch) * std::f64::consts::SQRT_2).floor() as u32;
839        let cross_grain = pitch / 2;
840        let bends = [0, pitch, 3 * pitch];
841        // Sharing is cheap on the first retry, so a blocked net takes its natural path
842        // and displaces the other net; repeated retries make sharing progressively
843        // dearer so contested nets settle instead of trading places.
844        let conflict_cost = pitch * (1 + 2 * self.attempts[net]);
845        let history_cost = pitch.div_ceil(2);
846        let approach_cost = 3 * pitch;
847        // Paths start and end near pad centres, so stubs stay short and square.
848        let stub = |node: usize| {
849            stubs.paths.get(&(node as u32)).map_or(0, |points| {
850                let mut length = 0.;
851                let mut last = grid.centre(node % cells);
852                for p in points.iter().rev() {
853                    length += f64::from(last.x - p.x).hypot(f64::from(last.y - p.y));
854                    last = *p;
855                }
856                length.round() as u32
857            })
858        };
859        let (x0, x1, y0, y1) =
860            window.unwrap_or((0, grid.width as i64 - 1, 0, grid.height as i64 - 1));
861        let heuristic = |node: usize| -> u32 {
862            let cell = node % cells;
863            let (x, y) = ((cell % grid.width) as i64, (cell / grid.width) as i64);
864            boxes
865                .iter()
866                .map(|&(bx0, bx1, by0, by1)| {
867                    let dx = (bx0 - x).max(x - bx1).max(0) as u32;
868                    let dy = (by0 - y).max(y - by1).max(0) as u32;
869                    straight
870                        .saturating_mul(dx.max(dy) - dx.min(dy))
871                        .saturating_add(diagonal_floor.saturating_mul(dx.min(dy)))
872                })
873                .min()
874                .unwrap_or(0)
875        };
876        let mut heap = BinaryHeap::new();
877        for &source in sources {
878            let node = source as usize;
879            if self.legal(net, node, soft).is_none() {
880                continue;
881            }
882            let start = stub(node);
883            self.stamp[node] = generation;
884            self.cost[node] = start;
885            self.parent[node] = NO_PARENT;
886            self.direction[node] = NO_DIRECTION;
887            heap.push(Reverse((start + heuristic(node), start, source)));
888        }
889        while let Some(Reverse((_, g, node))) = heap.pop() {
890            let node = node as usize;
891            if g != self.cost[node] {
892                continue;
893            }
894            self.expansions += 1;
895            if targets.contains_key(&(node as u32)) {
896                let mut path = vec![node as u32];
897                while let Some(&last) = path.last() {
898                    let parent = self.parent[last as usize];
899                    if parent == NO_PARENT {
900                        break;
901                    }
902                    path.push(parent);
903                }
904                path.reverse();
905                return Some(path);
906            }
907            let (layer, cell) = (node / cells, node % cells);
908            let (x, y) = ((cell % grid.width) as i64, (cell / grid.width) as i64);
909            let came = self.direction[node];
910            let mut relax = |job: &mut Self, next: usize, cost: u32, direction: u8| {
911                if job.stamp[next] != generation || cost < job.cost[next] {
912                    job.stamp[next] = generation;
913                    job.cost[next] = cost;
914                    job.parent[next] = node as u32;
915                    job.direction[next] = direction;
916                    heap.push(Reverse((
917                        cost.saturating_add(heuristic(next)),
918                        cost,
919                        next as u32,
920                    )));
921                }
922            };
923            for (d, (dx, dy)) in DIRECTIONS.iter().enumerate() {
924                let (nx, ny) = (x + dx, y + dy);
925                if nx < x0 || nx > x1 || ny < y0 || ny > y1 {
926                    continue;
927                }
928                let turn = if came == NO_DIRECTION {
929                    0
930                } else {
931                    let t = (d as i64 - i64::from(came)).rem_euclid(8);
932                    t.min(8 - t) as usize
933                };
934                if turn > 2 {
935                    continue;
936                }
937                let next = layer * cells + ny as usize * grid.width + nx as usize;
938                let Some(conflict) = self.legal(net, next, soft) else {
939                    continue;
940                };
941                let mut step = if d % 2 == 1 {
942                    diagonal
943                } else if grid.layers > 1 && (d % 4 == 0) != (layer % 2 == 0) {
944                    straight + cross_grain
945                } else {
946                    straight
947                };
948                step += bends[turn] + u32::from(self.history[next]) * history_cost;
949                if !self.approaches[layer].free(next % cells, net as u32) {
950                    step += approach_cost;
951                }
952                if conflict {
953                    step += conflict_cost;
954                }
955                if targets.contains_key(&(next as u32)) {
956                    step += stub(next);
957                }
958                relax(self, next, g.saturating_add(step), d as u8);
959            }
960            if grid.layers > 1
961                && let Some(via_cost) = via_cost
962                && (stubs.vias.contains(&(node as u32))
963                    || (!stubs.paths.contains_key(&(node as u32)) && !self.no_via[cell]))
964                && let Some(via_conflict) = self.via_legal(net, cell, soft)
965            {
966                for other in (0..grid.layers).filter(|l| *l != layer) {
967                    let next = other * cells + cell;
968                    let Some(conflict) = self.legal(net, next, soft) else {
969                        continue;
970                    };
971                    let mut step =
972                        via_cost.saturating_add(u32::from(self.history[next]) * history_cost);
973                    if conflict || via_conflict {
974                        step = step.saturating_add(conflict_cost);
975                    }
976                    relax(self, next, g.saturating_add(step), NO_DIRECTION);
977                }
978            }
979        }
980        None
981    }
982
983    /// Nets whose route claims a soft path overlaps.
984    fn blockers(&self, net: usize, path: &[u32]) -> BTreeSet<usize> {
985        let cells = self.grid.cells();
986        let via_class = self.nets[net].via_profile;
987        let mut keys = vec![];
988        for (i, &node) in path.iter().enumerate() {
989            let (map, cell) = self.map(self.nets[net].profile, node as usize);
990            keys.push((map * cells + cell) as u64);
991            if i > 0 && path[i - 1] as usize % cells == cell {
992                for layer in 0..self.grid.layers {
993                    keys.push(((via_class * self.grid.layers + layer) * cells + cell) as u64);
994                }
995            }
996        }
997        self.states
998            .iter()
999            .enumerate()
1000            .filter(|(j, state)| *j != net && keys.iter().any(|k| state.claimed.contains(k)))
1001            .map(|(j, _)| j)
1002            .collect()
1003    }
1004
1005    fn rip_up(&mut self, net: usize) {
1006        let cells = self.grid.cells();
1007        let state = std::mem::take(&mut self.states[net]);
1008        for key in state.claimed {
1009            let key = key as usize;
1010            self.route_claims[key / cells].remove(key % cells, net as u32);
1011        }
1012        self.rip_ups += 1;
1013        self.queue.push_back(net);
1014    }
1015
1016    fn claim(&mut self, net: usize, shape: &Shape, layers: (usize, usize)) {
1017        let grid = self.grid;
1018        let cells = grid.cells();
1019        for class in 0..self.profiles.len() {
1020            let gap = self.gaps[self.profiles[class].class][self.nets[net].class];
1021            let radius = self.keep_out(gap, class);
1022            for layer in layers.0..=layers.1 {
1023                let map = class * grid.layers + layer;
1024                let claims = &mut self.route_claims[map];
1025                let claimed = &mut self.states[net].claimed;
1026                for_cells_near(&grid, shape, radius, |cell| {
1027                    if claimed.insert((map * cells + cell) as u64) {
1028                        claims.add(cell, net as u32);
1029                    }
1030                });
1031            }
1032        }
1033    }
1034
1035    /// Turn a grid path into tracks and vias and claim their clearance zones.
1036    fn commit(&mut self, net: usize, path: &[u32], stubs: &Stubs) {
1037        let cells = self.grid.cells();
1038        let width = self.nets[net].width;
1039        let mut runs = vec![];
1040        let mut vias = vec![];
1041        let mut points = vec![];
1042        points.extend(stubs.paths.get(&path[0]).into_iter().flatten().copied());
1043        for (i, &node) in path.iter().enumerate() {
1044            let (layer, cell) = (node as usize / cells, node as usize % cells);
1045            if i > 0 && path[i - 1] as usize % cells == cell {
1046                runs.push((path[i - 1] as usize / cells, std::mem::take(&mut points)));
1047                vias.push(self.grid.centre(cell));
1048            }
1049            points.push(self.grid.centre(cell));
1050            if i + 1 == path.len() {
1051                points.extend(stubs.paths.get(&node).into_iter().flatten().rev().copied());
1052                runs.push((layer, std::mem::take(&mut points)));
1053            }
1054        }
1055        let last_layer = self.grid.layers - 1;
1056        for (layer, points) in runs {
1057            let track = Track::new(layer as u8, width, points);
1058            if track.points.len() < 2 {
1059                continue;
1060            }
1061            let segments: Vec<Shape> = track.segments().collect();
1062            for segment in &segments {
1063                self.claim(net, segment, (layer, layer));
1064            }
1065            self.states[net].tracks.push(track);
1066        }
1067        let (diameter, drill) = self.nets[net].via;
1068        for at in vias {
1069            self.claim(net, &Shape::circle(at, diameter / 2), (0, last_layer));
1070            self.states[net].vias.push(Via {
1071                id: Uuid::new_v4(),
1072                at,
1073                diameter,
1074                drill,
1075                span: None,
1076            });
1077        }
1078    }
1079
1080    /// What a via costs when one may be placed.
1081    fn via_cost(&self) -> u32 {
1082        (20 * u32::try_from(self.grid.pitch).unwrap_or(1)).max(2000)
1083    }
1084
1085    /// Route one net. `cleanup` reroutes a finished net for fewer vias; it never rips
1086    /// up another net.
1087    fn route_net(&mut self, net: usize, cleanup: bool) {
1088        self.states[net].missing = 0;
1089        self.states[net].routed = true;
1090        let islands = self.nets[net].islands.len();
1091        let mut stubs = Stubs::default();
1092        let seeds: Vec<Vec<u32>> = (0..islands)
1093            .map(|i| self.seeds(net, i, &mut stubs))
1094            .collect();
1095        let mut connected = vec![false; islands];
1096        connected[0] = true;
1097        let mut tree = seeds[0].clone();
1098        for remaining in (1..islands).rev() {
1099            let mut targets = HashMap::new();
1100            let mut boxes = vec![];
1101            for (island, nodes) in seeds.iter().enumerate().filter(|(i, _)| !connected[*i]) {
1102                boxes.extend(self.cell_box(nodes.iter().copied()));
1103                for &node in nodes {
1104                    targets.insert(node, island);
1105                }
1106            }
1107            if boxes.len() > 16
1108                && let Some(all) = self.cell_box(targets.keys().copied())
1109            {
1110                boxes = vec![all];
1111            }
1112            let window = self
1113                .cell_box(tree.iter().chain(targets.keys()).copied())
1114                .map(|(x0, x1, y0, y1)| {
1115                    let pad = 40.max((x1 - x0).max(y1 - y0) / 3);
1116                    (x0 - pad, x1 + pad, y0 - pad, y1 + pad)
1117                });
1118            // Via costs to try in order; `None` searches without vias. A clean-up
1119            // reroute looks for a route with no via before accepting one.
1120            let allow = Some(self.via_cost());
1121            let stages = match self.vias {
1122                ViaPolicy::Never => vec![None],
1123                ViaPolicy::Avoid if cleanup => vec![None, allow],
1124                ViaPolicy::Allow | ViaPolicy::Avoid => vec![allow],
1125            };
1126            let mut path = None;
1127            for &vias in &stages {
1128                path = self.search(net, &tree, &targets, &boxes, window, false, &stubs, vias);
1129                if path.is_none() {
1130                    path = self.search(net, &tree, &targets, &boxes, None, false, &stubs, vias);
1131                }
1132                if path.is_some() {
1133                    break;
1134                }
1135            }
1136            let soft_vias = *stages.last().unwrap();
1137            if path.is_none()
1138                && !cleanup
1139                && self.attempts[net] < MAX_ATTEMPTS
1140                && self.rip_ups < self.rip_up_limit
1141                && let Some(soft) =
1142                    self.search(net, &tree, &targets, &boxes, None, true, &stubs, soft_vias)
1143            {
1144                self.attempts[net] += 1;
1145                for &node in &soft {
1146                    if self.legal(net, node as usize, false).is_none() {
1147                        let h = &mut self.history[node as usize];
1148                        *h = h.saturating_add(1);
1149                    }
1150                }
1151                for blocker in self.blockers(net, &soft) {
1152                    self.rip_up(blocker);
1153                }
1154                path = Some(soft);
1155            }
1156            let Some(path) = path else {
1157                self.states[net].missing = remaining;
1158                return;
1159            };
1160            let reached = targets[path.last().unwrap()];
1161            self.commit(net, &path, &stubs);
1162            connected[reached] = true;
1163            tree.extend(path);
1164            tree.extend(seeds[reached].iter().copied());
1165        }
1166    }
1167
1168    /// Reroute a finished net against the board as it now stands. The new copper is
1169    /// kept only if it still connects every island with fewer vias; otherwise the
1170    /// old copper and its claims are put back exactly.
1171    fn reduce_vias(&mut self, net: usize) {
1172        let before = self.states[net].vias.len();
1173        if before == 0 || self.states[net].missing > 0 {
1174            return;
1175        }
1176        let cells = self.grid.cells();
1177        let old = std::mem::take(&mut self.states[net]);
1178        for &key in &old.claimed {
1179            let key = key as usize;
1180            self.route_claims[key / cells].remove(key % cells, net as u32);
1181        }
1182        self.route_net(net, true);
1183        let new = &self.states[net];
1184        if new.missing == 0 && new.vias.len() < before {
1185            if let Some(region) = self.copper_region(&old) {
1186                self.cleanup_freed.push(region);
1187            }
1188            return;
1189        }
1190        let new = std::mem::replace(&mut self.states[net], old);
1191        for key in new.claimed {
1192            let key = key as usize;
1193            self.route_claims[key / cells].remove(key % cells, net as u32);
1194        }
1195        for &key in &self.states[net].claimed {
1196            let key = key as usize;
1197            self.route_claims[key / cells].add(key % cells, net as u32);
1198        }
1199    }
1200
1201    /// Bounds of a net's routed copper, grown by the margin a search window adds.
1202    fn copper_region(&self, state: &NetState) -> Option<(Point, Point)> {
1203        let points = state
1204            .tracks
1205            .iter()
1206            .flat_map(|t| t.points.iter().copied())
1207            .chain(state.vias.iter().map(|v| v.at));
1208        let (min, max) = points.fold(None, |b: Option<(Point, Point)>, p| {
1209            Some(b.map_or((p, p), |(a, b)| {
1210                (
1211                    Point::new(a.x.min(p.x), a.y.min(p.y)),
1212                    Point::new(b.x.max(p.x), b.y.max(p.y)),
1213                )
1214            }))
1215        })?;
1216        let margin = 40 * self.grid.pitch + (max.x - min.x).max(max.y - min.y) / 3;
1217        Some((
1218            Point::new(min.x - margin, min.y - margin),
1219            Point::new(max.x + margin, max.y + margin),
1220        ))
1221    }
1222
1223    /// Whether the via clean-up that follows routing under Avoid has more to do.
1224    fn cleanup_pending(&self) -> bool {
1225        self.vias == ViaPolicy::Avoid
1226            && match &self.cleanup {
1227                None => true,
1228                Some(queue) => {
1229                    !queue.is_empty()
1230                        || (!self.cleanup_freed.is_empty()
1231                            && self.cleanup_passes < MAX_CLEANUP_PASSES)
1232                }
1233            }
1234    }
1235
1236    /// The next net to reroute for fewer vias, starting a pass when one is due.
1237    fn next_cleanup(&mut self) -> Option<usize> {
1238        if !self.cleanup_pending() {
1239            return None;
1240        }
1241        if self.cleanup.as_ref().is_none_or(VecDeque::is_empty) {
1242            self.cleanup_passes += 1;
1243            let freed = std::mem::take(&mut self.cleanup_freed);
1244            let first = self.cleanup.is_none();
1245            let near = |region: Option<(Point, Point)>| {
1246                region.is_some_and(|(a, b)| {
1247                    freed
1248                        .iter()
1249                        .any(|(c, d)| a.x <= d.x && c.x <= b.x && a.y <= d.y && c.y <= b.y)
1250                })
1251            };
1252            self.cleanup = Some(
1253                (0..self.nets.len())
1254                    .filter(|&i| !self.states[i].vias.is_empty() && self.states[i].missing == 0)
1255                    .filter(|&i| first || near(self.copper_region(&self.states[i])))
1256                    .collect(),
1257            );
1258        }
1259        self.cleanup.as_mut()?.pop_front()
1260    }
1261
1262    /// Route queued nets until roughly `budget` grid nodes have been expanded.
1263    pub fn step(&mut self, budget: u64) -> Progress {
1264        let stop = self.expansions.saturating_add(budget);
1265        while self.expansions < stop {
1266            if let Some(net) = self.queue.pop_front() {
1267                self.route_net(net, false);
1268            } else if let Some(net) = self.next_cleanup() {
1269                self.reduce_vias(net);
1270            } else {
1271                break;
1272            }
1273        }
1274        self.progress()
1275    }
1276    pub fn progress(&self) -> Progress {
1277        let queued: BTreeSet<usize> = self.queue.iter().copied().collect();
1278        let settled = |i: &usize| !queued.contains(i) && self.states[*i].routed;
1279        Progress {
1280            total_nets: self.nets.len(),
1281            completed_nets: (0..self.nets.len())
1282                .filter(|i| settled(i) && self.states[*i].missing == 0)
1283                .count(),
1284            failed_nets: (0..self.nets.len())
1285                .filter(|i| settled(i) && self.states[*i].missing > 0)
1286                .count(),
1287            rip_ups: self.rip_ups,
1288            removing_vias: self.queue.is_empty()
1289                && self.cleanup.is_some()
1290                && self.cleanup_pending(),
1291            done: self.queue.is_empty() && !self.cleanup_pending(),
1292        }
1293    }
1294    /// Copper routed so far, for previews.
1295    pub fn routed(&self) -> impl Iterator<Item = (&[Track], &[Via])> {
1296        self.states
1297            .iter()
1298            .map(|s| (s.tracks.as_slice(), s.vias.as_slice()))
1299    }
1300    pub fn pitch(&self) -> i32 {
1301        self.grid.pitch
1302    }
1303    pub fn run(mut self) -> RouteOutcome {
1304        while !self.step(u64::MAX).done {}
1305        self.outcome()
1306    }
1307    pub fn outcome(&self) -> RouteOutcome {
1308        let queued: BTreeSet<usize> = self.queue.iter().copied().collect();
1309        RouteOutcome {
1310            tracks: self.states.iter().flat_map(|s| s.tracks.clone()).collect(),
1311            vias: self.states.iter().flat_map(|s| s.vias.clone()).collect(),
1312            unrouted: self
1313                .nets
1314                .iter()
1315                .enumerate()
1316                .filter(|(i, _)| queued.contains(i) || self.states[*i].missing > 0)
1317                .map(|(_, n)| n.name.clone())
1318                .collect(),
1319            pitch: self.grid.pitch,
1320        }
1321    }
1322}
1323
1324impl Document {
1325    /// Route every unrouted connection and add the copper to the board.
1326    pub fn autoroute(&mut self) -> RouteOutcome {
1327        let outcome = RouteJob::new(&self.board, &self.netlist()).run();
1328        outcome.clone().apply(&mut self.board);
1329        outcome
1330    }
1331}
1332