aboutsummaryrefslogtreecommitdiff
path: root/tools/router/src
diff options
context:
space:
mode:
authorLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
committerLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
commita59e8e99243a895197a30d6cd6dd8d744dd606de (patch)
tree8910cc7476ff1317932257dfc8497a0f9ffc29f7 /tools/router/src
parent6f2bbe1f94e4321c329f92ec3420f6d32fd7b26d (diff)
downloadhw-toolchain-main.tar.gz
Keep only the current router: drop the Python router, router-rs -> routerHEADmain
The sequential Python/C router (pcbroute.py, pipeline.py, astar.c) is gone. The Rust crate takes its place at tools/router/, next to the KiCad I/O scripts it uses (dump_board.py, write_board.py, plot_routes.py). knowledge/tooling/router.md is now the Rust router's reference; the small Python venv for plots and 3D checks moves to tools/.venv (tools/requirements.txt). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/router/src')
-rw-r--r--tools/router/src/astar.rs320
-rw-r--r--tools/router/src/board.rs847
-rw-r--r--tools/router/src/cleanup.rs408
-rw-r--r--tools/router/src/config.rs389
-rw-r--r--tools/router/src/geom.rs281
-rw-r--r--tools/router/src/io.rs145
-rw-r--r--tools/router/src/lib.rs15
-rw-r--r--tools/router/src/main.rs107
-rw-r--r--tools/router/src/placement.rs99
-rw-r--r--tools/router/src/pour.rs224
-rw-r--r--tools/router/src/router.rs1268
-rw-r--r--tools/router/src/run.rs451
12 files changed, 4554 insertions, 0 deletions
diff --git a/tools/router/src/astar.rs b/tools/router/src/astar.rs
new file mode 100644
index 0000000..0a91f7a
--- /dev/null
+++ b/tools/router/src/astar.rs
@@ -0,0 +1,320 @@
+//! Grid A* core, 2 layers (port of an earlier C core with the same arithmetic in f32;
+//! a radix heap replaces the binary heap, so ties break differently).
+//!
+//! States are cell * 2 + layer, so both layers of a cell share a cache line. Foreign distance for net X: n1 == X ? d2 : d1.
+
+use crate::board::Field;
+
+/// A step "runs alongside" copper within this distance (mm) beyond its clearance.
+const HUG_BAND: f32 = 0.15;
+
+/// A via's conflicts and history weigh like this many track steps.
+const VIA_SOFT: f32 = 8.0;
+
+const DX: [i32; 8] = [1, 1, 0, -1, -1, -1, 0, 1];
+const DY: [i32; 8] = [0, 1, 1, 1, 0, -1, -1, -1];
+
+pub struct SearchArgs<'a> {
+ pub nx: usize,
+ pub n: usize,
+ pub f: &'a [Field],
+ pub padd: &'a [f32],
+ /// per cell distance to the nearest drill edge; a via needs r_hole
+ pub hole: &'a [f32],
+ pub r_hole: f32,
+ /// steps a path needs between two of its own vias
+ pub via_gap: u16,
+ pub cost: &'a [f32],
+ /// negotiation: a step onto other nets' soft copper costs (base + hist) * (1 + pres)
+ /// (INFINITY: not allowed); elsewhere base + hist
+ pub soft: Option<&'a [Field]>,
+ pub hist: &'a [f32],
+ pub pres: f32,
+ pub net: i32,
+ pub src: &'a [i32],
+ pub tgt: &'a [u8],
+ pub goal_layer1: bool,
+ pub hx: i32,
+ pub hy: i32,
+ pub r_nom: f32,
+ pub r_neck: f32,
+ pub r_via: f32,
+ pub r_vpad: f32,
+ pub r_diag: f32,
+ pub neckbox: &'a [[i32; 4]],
+ pub via_cost: f32,
+ pub via_cmult: f32,
+ pub bmult: f32,
+ pub turn_cost: f32,
+ pub allow_via: bool,
+ pub max_expand: i64,
+ pub layer_mask: u8,
+ /// heuristic weight: 1 is exact A*, more trades path cost for fewer expansions
+ pub hweight: f32,
+ /// extra cost per step farther than HUG_BAND from other copper
+ pub hug: f32,
+ /// per state distance to the copper of the net's bundle partners (pair, bus), and the
+ /// extra cost per step farther than HUG_BAND from it
+ pub attract: Option<&'a [f32]>,
+ pub attract_cost: f32,
+ /// a necked step costs 0.3 plus this much per mm of width given up
+ pub neck: f32,
+ /// cell window [x0, y0, x1, y1] (inclusive) the search stays in
+ pub window: [i32; 4],
+}
+
+/// Per-state search data, packed so that one state is one cache access.
+#[derive(Clone, Copy, Default)]
+struct Node {
+ g: f32,
+ par: i32,
+ stamp: u32,
+ dir: u8,
+ closed: bool,
+ /// steps since the path's last via (its own vias are not in the hole field yet)
+ since: u16,
+}
+
+/// Radix heap on the f32 bit patterns of non-negative keys. A* pops keys in non-decreasing
+/// order (the octile heuristic is consistent: every step costs at least its length), which
+/// is all a radix heap needs; push and pop are O(1) amortised instead of a binary heap's
+/// cache-missing O(log n).
+struct RadixHeap {
+ last: u32,
+ len: usize,
+ buckets: Vec<Vec<(u32, i32)>>,
+}
+
+impl RadixHeap {
+ fn new() -> RadixHeap {
+ RadixHeap { last: 0, len: 0, buckets: (0..33).map(|_| Vec::new()).collect() }
+ }
+
+ fn clear(&mut self) {
+ self.buckets.iter_mut().for_each(Vec::clear);
+ self.last = 0;
+ self.len = 0;
+ }
+
+ fn bucket(&self, k: u32) -> usize {
+ (32 - (k ^ self.last).leading_zeros()) as usize
+ }
+
+ fn push(&mut self, f: f32, i: i32) {
+ let k = f.max(0.0).to_bits().max(self.last); // a key below the last pop would break the order
+ let b = self.bucket(k);
+ self.buckets[b].push((k, i));
+ self.len += 1;
+ }
+
+ fn pop(&mut self) -> i32 {
+ if self.buckets[0].is_empty() {
+ let b = (1..33).find(|&b| !self.buckets[b].is_empty()).unwrap();
+ let items = std::mem::take(&mut self.buckets[b]);
+ self.last = items.iter().map(|e| e.0).min().unwrap();
+ for &(k, i) in &items {
+ let nb = self.bucket(k);
+ self.buckets[nb].push((k, i));
+ }
+ let mut v = items;
+ v.clear();
+ self.buckets[b] = v;
+ }
+ self.len -= 1;
+ self.buckets[0].pop().unwrap().1
+ }
+
+ fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+}
+
+pub struct Search {
+ node: Vec<Node>,
+ call: u32,
+ heap: RadixHeap,
+}
+
+#[inline]
+fn heur(x: i32, y: i32, hx: i32, hy: i32) -> f32 {
+ let (ax, ay) = ((x - hx).abs(), (y - hy).abs());
+ ax.max(ay) as f32 + 0.414_213_56f32 * ax.min(ay) as f32
+}
+
+impl Search {
+ pub fn new(states: usize) -> Search {
+ Search { node: vec![Node::default(); states], call: 0, heap: RadixHeap::new() }
+ }
+
+ fn push(&mut self, f: f32, i: i32) {
+ self.heap.push(f, i);
+ }
+
+ fn pop(&mut self) -> i32 {
+ self.heap.pop()
+ }
+
+ /// Path (target back to source) with neck flags, or None.
+ pub fn route(&mut self, a: &SearchArgs) -> Option<(Vec<i32>, Vec<u8>)> {
+ let nx = a.nx as i32;
+ let fdist = |s: usize| a.f[s].fdist(a.net);
+ self.call = self.call.wrapping_add(1);
+ if self.call == 0 {
+ self.node.iter_mut().for_each(|v| v.stamp = 0);
+ self.call = 1;
+ }
+ let call = self.call;
+ self.heap.clear();
+ let neck_cost = 0.3 + a.neck * 2.0 * (a.r_nom - a.r_neck).max(0.0);
+ for &s in a.src {
+ let s = s as usize;
+ let l = s & 1;
+ if (a.layer_mask >> l) & 1 == 0 {
+ continue;
+ }
+ if fdist(s) < if a.r_neck > 0.0 { a.r_neck } else { a.r_nom } {
+ continue; // a track must fit at its start cell
+ }
+ self.node[s] = Node { g: 0.0, par: -1, stamp: call, dir: 255, closed: false, since: u16::MAX };
+ let c = (s >> 1) as i32;
+ self.push(if a.goal_layer1 { 0.0 } else { a.hweight * heur(c % nx, c / nx, a.hx, a.hy) }, s as i32);
+ }
+ let mut expanded: i64 = 0;
+ let mut found: i64 = -1;
+ while !self.heap.is_empty() {
+ let s = self.pop() as usize;
+ if self.node[s].closed {
+ continue;
+ }
+ self.node[s].closed = true;
+ let l = s & 1;
+ let c = s >> 1;
+ let (x, y) = ((c % a.nx) as i32, (c / a.nx) as i32);
+ if a.tgt[s] != 0 || (a.goal_layer1 && l == 1) {
+ found = s as i64;
+ break;
+ }
+ expanded += 1;
+ if expanded > a.max_expand {
+ break;
+ }
+ let gcur = self.node[s].g;
+ let pd = self.node[s].dir;
+ let since = self.node[s].since;
+ for d in 0..8usize {
+ // cheap rejections first: reversals and sharp turns, closed states
+ let mut turn = 0.0f32;
+ if pd != 255 && pd as usize != d {
+ let mut t = (pd as i32 - d as i32).abs();
+ if t > 4 {
+ t = 8 - t;
+ }
+ if t >= 3 {
+ continue;
+ }
+ turn = a.turn_cost * t as f32;
+ }
+ let (qx, qy) = (x + DX[d], y + DY[d]);
+ if qx < a.window[0] || qy < a.window[1] || qx > a.window[2] || qy > a.window[3] {
+ continue;
+ }
+ let nc = (qy * nx + qx) as usize;
+ let ns = nc * 2 + l;
+ let q = self.node[ns];
+ if q.stamp == call && q.closed {
+ continue;
+ }
+ let fd = fdist(ns);
+ let odd = d & 1 == 1;
+ let need = a.r_nom + if odd { a.r_diag } else { 0.0 };
+ let mut neck = false;
+ let mut r = need;
+ if fd < need {
+ if a.r_neck <= 0.0 {
+ continue;
+ }
+ let needn = a.r_neck + if odd { a.r_diag } else { 0.0 };
+ if fd < needn {
+ continue;
+ }
+ if !a.neckbox.iter().any(|b| qx >= b[0] && qx <= b[2] && qy >= b[1] && qy <= b[3]) {
+ continue;
+ }
+ neck = true;
+ r = needn;
+ }
+ let step = if odd { 1.414_213_56f32 } else { 1.0f32 };
+ let mut cst = step * if l == 1 { a.bmult } else { 1.0 } + a.cost[ns] * step;
+ if neck {
+ cst += neck_cost * step;
+ }
+ if a.hug > 0.0 && fd > r + HUG_BAND {
+ cst += a.hug * step;
+ }
+ if let Some(at) = a.attract {
+ if at[ns] > r + HUG_BAND {
+ cst += a.attract_cost * step;
+ }
+ }
+ if let Some(sf) = a.soft {
+ // PathFinder: (base + history) * (1 + present factor on conflict)
+ cst += a.hist[ns] * step;
+ if sf[ns].fdist(a.net) < r {
+ if a.pres == f32::INFINITY {
+ continue;
+ }
+ cst *= 1.0 + a.pres;
+ }
+ }
+ cst += turn;
+ let ng = gcur + cst;
+ if q.stamp == call && q.g <= ng {
+ continue;
+ }
+ self.node[ns] = Node { g: ng, par: s as i32, stamp: call, dir: d as u8, closed: false, since: since.saturating_add(1) };
+ self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(qx, qy, a.hx, a.hy) }, ns as i32);
+ }
+ if a.allow_via && a.layer_mask & 3 == 3 {
+ let (s0, s1) = (c * 2, c * 2 + 1);
+ let mut soft_ok = true;
+ let mut vc = a.via_cost + a.via_cmult * (a.cost[s0] + a.cost[s1]);
+ if let Some(sf) = a.soft {
+ let n = (sf[s0].fdist(a.net) < a.r_via) as u32 + (sf[s1].fdist(a.net) < a.r_via) as u32;
+ soft_ok = n == 0 || a.pres != f32::INFINITY;
+ vc += VIA_SOFT * (a.hist[s0] + a.hist[s1]);
+ if n > 0 {
+ vc *= 1.0 + a.pres * n as f32;
+ }
+ }
+ if soft_ok && since >= a.via_gap && a.hole[c] >= a.r_hole && fdist(s0) >= a.r_via && fdist(s1) >= a.r_via && a.padd[s0] >= a.r_vpad && a.padd[s1] >= a.r_vpad {
+ let ns = c * 2 + 1 - l;
+ let ng = gcur + vc;
+ let q = &mut self.node[ns];
+ if !(q.stamp == call && (q.closed || q.g <= ng)) {
+ *q = Node { g: ng, par: s as i32, stamp: call, dir: 255, closed: false, since: 0 };
+ self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(x, y, a.hx, a.hy) }, ns as i32);
+ }
+ }
+ }
+ }
+ if std::env::var("ROUTER_TRACE").is_ok() {
+ eprintln!("EXP {} {}", expanded, found >= 0);
+ }
+ if found < 0 {
+ return None;
+ }
+ let (mut out, mut neck) = (Vec::new(), Vec::new());
+ let mut s = found as i32;
+ while s >= 0 && out.len() < 400_000 {
+ let su = s as usize;
+ // the same test the search used to enter the cell: a full-width track that
+ // barely fits must not be drawn necked all along its run
+ let dd = self.node[su].dir;
+ let odd = dd != 255 && dd & 1 == 1;
+ neck.push((fdist(su) < a.r_nom + if odd { a.r_diag } else { 0.0 }) as u8);
+ out.push(s);
+ s = self.node[su].par;
+ }
+ Some((out, neck))
+ }
+}
diff --git a/tools/router/src/board.rs b/tools/router/src/board.rs
new file mode 100644
index 0000000..730d90e
--- /dev/null
+++ b/tools/router/src/board.rs
@@ -0,0 +1,847 @@
+//! Board model and clearance fields (port of an earlier Python router).
+//!
+//! The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu), with its origin on a
+//! multiple of 0.05 mm, so that parts placed on the placer's 0.05 mm grid have their pads on
+//! cell centres (an outline at 99.975 put 0.5 mm-pitch pins between two cell rows, where no
+//! 0.25 mm neck fits). For every cell, d1/n1
+//! hold the distance to and the net of the nearest copper, d2 the distance to the nearest
+//! copper of another net. A track of width w fits where the foreign distance is
+//! >= w/2 + CLR. Board edge, NPTH holes and keep-outs are net -1 copper in the static
+//! `base` field. Items are kept in insertion order; removal re-inserts the neighbours of the
+//! cleared region, as the Python router does, so ties resolve the same way.
+//!
+//! Footprint copper that is not a pad (`fpcopper`, e.g. a net tie's bridge) is static copper:
+//! of its net when it touches pads of one net, else of no net (foreign to every net) with the
+//! pads it joins cut out, so that the tie's nets still reach their pads from outside.
+//!
+//! Negotiated routing (router::negotiate) commits `soft` items: they go into a second field
+//! (`soft`), which the search may violate at a cost (`pres` per conflicting step plus the
+//! `hist` cost of the cell); everything else is hard.
+
+use crate::astar::{Search, SearchArgs};
+use crate::geom::{poly_poly, Poly, Pt};
+use crate::io::{BoardJson, FpCopperJson};
+use std::collections::HashMap;
+
+pub const RES: f64 = 0.05;
+pub const CAP: f32 = 1.5;
+pub const CLR: f64 = 0.2;
+pub const M: f64 = 0.015; // numeric margin on clearance checks
+pub const RDIAG: f64 = 0.02; // extra margin on diagonal steps
+pub const EDGE_CLR: f64 = 0.5;
+pub const HOLE_CLR: f64 = 0.3;
+pub const HOLE_HOLE: f64 = 0.25; // drill edge to drill edge, any nets
+/// A track may neck down within this distance (mm) of the pad bboxes it joins (default of the
+/// `neck_zone` option).
+pub const NECK_ZONE: f64 = 1.0;
+/// Sample spacing (mm) of footprint copper.
+pub const CU_STEP: f64 = 0.025;
+
+/// Drill of a via of diameter d (as written to the board).
+pub fn via_drill(d: f64) -> f64 {
+ if d >= 0.8 {
+ 0.4
+ } else {
+ 0.3
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Shape {
+ Pad(usize),
+ Seg(Pt, Pt),
+ Via(Pt),
+ /// footprint copper (index into Board::cu)
+ Cu(usize),
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Owner {
+ Pad,
+ Existing,
+ Routed,
+ /// routed by negotiation (or its cleanup): the cleanup may reroute it
+ Negotiated,
+ Waypoint,
+}
+
+#[derive(Clone, Debug)]
+pub struct Item {
+ pub shape: Shape,
+ pub net: i32,
+ pub layers: u8, // bit 0 F.Cu, bit 1 B.Cu
+ pub w: f64,
+ pub bbox: [f64; 4],
+ pub owner: Owner,
+ pub soft: bool,
+}
+
+impl Item {
+ pub fn on(&self, layer: usize) -> bool {
+ self.layers >> layer & 1 == 1
+ }
+}
+
+pub struct Pad {
+ pub refdes: String,
+ pub num: String,
+ pub net: i32,
+ pub layers: u8,
+ pub poly: Poly,
+ pub x: f64,
+ pub y: f64,
+ pub tht: bool,
+ pub drill: f64,
+ pub item: usize,
+}
+
+/// Search settings of one connection (per step or per net in route.toml).
+#[derive(Clone, Copy, Debug)]
+pub struct SearchOpts {
+ pub via_cost: f64,
+ pub via_cmult: f64,
+ pub bmult: f64,
+ pub turn: f64,
+ pub allow_via: bool,
+ pub layer_mask: u8,
+ pub max_expand: i64,
+ pub hweight: f64,
+ /// search only within this margin (mm) around the connection's copper; 0: whole board
+ pub margin: f64,
+ /// extra cost per step that does not run alongside other copper (bundles parallel lines)
+ pub hug: f64,
+ /// a necked step costs 0.3 plus this much per mm of width given up (the cleanup uses 4:
+ /// 1.0 -> 0.2 mm costs 3.5 per step, so a net necks only where its width does not fit)
+ pub neck: f64,
+ /// a track may neck down within this distance (mm) of the pad bboxes it joins
+ pub neck_zone: f64,
+}
+
+impl Default for SearchOpts {
+ fn default() -> Self {
+ SearchOpts { via_cost: 40.0, via_cmult: 0.0, bmult: 3.0, turn: 4.0, allow_via: true, layer_mask: 3, max_expand: 4_000_000, hweight: 1.0, margin: 0.0, hug: 0.0, neck: 0.0, neck_zone: NECK_ZONE }
+ }
+}
+
+pub type Seg = (usize, Pt, Pt, f64); // layer, a, b, width
+
+/// Clearance field of one state: distance to and net of the nearest copper (d1, n1) and
+/// distance to the nearest copper of another net (d2).
+#[derive(Clone, Copy, Debug)]
+pub struct Field {
+ pub d1: f32,
+ pub n1: i32,
+ pub d2: f32,
+}
+
+impl Field {
+ pub const EMPTY: Field = Field { d1: CAP, n1: 0, d2: CAP };
+
+ /// Distance to copper of a net other than `net`.
+ #[inline]
+ pub fn fdist(&self, net: i32) -> f32 {
+ if self.n1 == net {
+ self.d2
+ } else {
+ self.d1
+ }
+ }
+
+ #[inline]
+ fn add(&mut self, dd: f32, net: i32) {
+ if self.n1 == net {
+ self.d1 = self.d1.min(dd);
+ } else if dd < self.d1 {
+ self.d2 = self.d1;
+ self.d1 = dd;
+ self.n1 = net;
+ } else {
+ self.d2 = self.d2.min(dd);
+ }
+ }
+}
+
+pub struct Board {
+ /// grid extent (origin snapped to the grid)
+ pub x0: f64,
+ pub y0: f64,
+ pub x1: f64,
+ pub y1: f64,
+ /// the board outline's bounds, for the edge clearance
+ edge: [f64; 4],
+ pub nx: usize,
+ pub ny: usize,
+ pub n: usize,
+ pub f: Vec<Field>,
+ pub padd: Vec<f32>,
+ pub soft: Vec<Field>,
+ pub hist: Vec<f32>,
+ /// commit soft items and price soft conflicts (`pres` = INFINITY: soft copper is hard)
+ pub soft_mode: bool,
+ pub pres: f32,
+ pub costs: HashMap<String, Vec<f32>>,
+ pub cost: String,
+ /// owner of committed routes
+ pub commit_owner: Owner,
+ base: Vec<f32>, // one layer; both layers share it
+ pub pads: Vec<Pad>,
+ pub items: Vec<Item>,
+ pub alive: Vec<bool>,
+ pub netid: HashMap<String, i32>,
+ pub netnames: Vec<String>, // by net id; id 0 is unused, -1 is ""
+ npth: Vec<(f64, f64, f64)>,
+ /// per cell: distance to the nearest drill edge (pads, NPTH, vias of any net)
+ pub hole: Vec<f32>,
+ hole_base: Vec<f32>,
+ keepouts: Vec<Poly>,
+ /// bundle attraction (cleanup): per state distance to the partners' copper, and its cost
+ attract: Vec<f32>,
+ attract_cost: f32,
+ /// routing area (route.toml `area`): copper stays `area_margin` inside the union
+ area: Vec<Poly>,
+ area_margin: f64,
+ /// footprint copper as sample points (spacing CU_STEP) inside its outline
+ pub cu: Vec<Vec<Pt>>,
+ tgt: Vec<u8>,
+ search: Search,
+}
+
+impl Board {
+ pub fn new(d: &BoardJson, plane_nets: &[String], area: Vec<Poly>, area_margin: f64) -> Board {
+ let [bx0, by0, x1, y1] = d.bounds;
+ // the grid's origin on a multiple of RES (exact multiples stay)
+ let snap = |v: f64| if ((v / RES).round() * RES - v).abs() < 1e-9 { v } else { (v / RES).floor() * RES };
+ let (x0, y0) = (snap(bx0), snap(by0));
+ let nx = ((x1 - x0) / RES - 1e-6).ceil() as usize + 1;
+ let ny = ((y1 - y0) / RES - 1e-6).ceil() as usize + 1;
+ let n = nx * ny;
+ let mut b = Board {
+ x0,
+ y0,
+ x1,
+ y1,
+ edge: d.bounds,
+ nx,
+ ny,
+ n,
+ f: vec![Field::EMPTY; 2 * n],
+ padd: vec![CAP; 2 * n],
+ soft: vec![Field::EMPTY; 2 * n],
+ hist: vec![0.0; 2 * n],
+ soft_mode: false,
+ pres: 0.0,
+ costs: HashMap::from([("none".to_string(), vec![0.0; 2 * n])]),
+ cost: "none".into(),
+ commit_owner: Owner::Routed,
+ base: vec![CAP; n],
+ pads: Vec::new(),
+ items: Vec::new(),
+ alive: Vec::new(),
+ netid: HashMap::new(),
+ netnames: vec![String::new()],
+ npth: Vec::new(),
+ keepouts: d.keepouts.iter().map(|k| Poly::new(k.iter().map(|p| (p[0], p[1])).collect())).collect(),
+ area,
+ area_margin,
+ attract: Vec::new(),
+ attract_cost: 0.0,
+ cu: Vec::new(),
+ tgt: vec![0; 2 * n],
+ hole: vec![CAP; n],
+ hole_base: vec![CAP; n],
+ search: Search::new(2 * n),
+ };
+ for p in &d.pads {
+ let layers = (p.f.is_some() as u8) | (p.b.is_some() as u8) << 1;
+ if layers == 0 {
+ continue;
+ }
+ let net = if p.net.is_empty() || p.net.starts_with("unconnected") {
+ -1
+ } else {
+ match b.netid.get(&p.net) {
+ Some(&k) => k,
+ None => {
+ let k = b.netnames.len() as i32;
+ b.netid.insert(p.net.clone(), k);
+ b.netnames.push(p.net.clone());
+ k
+ }
+ }
+ };
+ let pts = p.f.as_ref().or(p.b.as_ref()).unwrap();
+ b.pads.push(Pad {
+ refdes: p.refdes.clone(),
+ num: p.num.clone(),
+ net,
+ layers,
+ poly: Poly::new(pts.iter().map(|q| (q[0], q[1])).collect()),
+ x: p.x,
+ y: p.y,
+ tht: layers == 3,
+ drill: p.drill,
+ item: usize::MAX,
+ });
+ }
+ b.npth = d.pads.iter().filter(|p| p.npth).map(|p| (p.x, p.y, p.drill)).collect();
+ b.build_static(plane_nets);
+ for c in &d.fpcopper {
+ b.add_fpcopper(c);
+ }
+ let holes: Vec<(f64, f64, f64)> = b.pads.iter().filter(|p| p.tht && p.drill > 0.0).map(|p| (p.x, p.y, p.drill / 2.0)).chain(b.npth.iter().map(|h| (h.0, h.1, h.2 / 2.0))).collect();
+ for (x, y, r) in holes {
+ b.hole_min(x, y, r, true);
+ }
+ b.hole.clone_from(&b.hole_base);
+ b
+ }
+
+ /// Footprint copper as a static item: the net of the pads it touches if they share one,
+ /// else no net with those pads cut out (a net tie's bridge).
+ fn add_fpcopper(&mut self, c: &FpCopperJson) {
+ let l = if c.layer == "B" { 1 } else { 0 };
+ let poly = Poly::new(c.poly.iter().map(|p| (p[0], p[1])).collect());
+ let touch: Vec<usize> = (0..self.pads.len())
+ .filter(|&k| self.pads[k].refdes == c.refdes && self.pads[k].layers >> l & 1 == 1 && poly_poly(&self.pads[k].poly, &poly) <= 1e-6)
+ .collect();
+ let mut nets: Vec<i32> = touch.iter().map(|&k| self.pads[k].net).collect();
+ nets.sort();
+ nets.dedup();
+ let (net, cut) = if nets.len() == 1 { (nets[0], vec![]) } else { (-1, touch) };
+ let bb = poly.bbox;
+ let mut pts = Vec::new();
+ let mut y = bb[1] + CU_STEP / 2.0;
+ while y < bb[3] {
+ let mut x = bb[0] + CU_STEP / 2.0;
+ while x < bb[2] {
+ if poly.contains((x, y)) && cut.iter().all(|&k| self.pads[k].poly.dist((x, y)) > CU_STEP / 2.0) {
+ pts.push((x, y));
+ }
+ x += CU_STEP;
+ }
+ y += CU_STEP;
+ }
+ if pts.is_empty() {
+ return;
+ }
+ let h = CU_STEP / 2.0;
+ let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
+ for &(x, y) in &pts {
+ b = [b[0].min(x - h), b[1].min(y - h), b[2].max(x + h), b[3].max(y + h)];
+ }
+ self.cu.push(pts);
+ let k = self.cu.len() - 1;
+ self.add(Item { shape: Shape::Cu(k), net, layers: 1 << l, w: 0.0, bbox: b, owner: Owner::Pad, soft: false });
+ }
+
+ pub fn netname(&self, net: i32) -> &str {
+ if net < 0 {
+ ""
+ } else {
+ &self.netnames[net as usize]
+ }
+ }
+
+ pub fn cell_xy(&self, i: usize, j: usize) -> Pt {
+ (self.x0 + i as f64 * RES, self.y0 + j as f64 * RES)
+ }
+
+ pub fn xy_cell(&self, x: f64, y: f64) -> (i64, i64) {
+ (((x - self.x0) / RES).round_ties_even() as i64, ((y - self.y0) / RES).round_ties_even() as i64)
+ }
+
+ fn gx(&self, i: usize) -> f64 {
+ self.x0 + i as f64 * RES
+ }
+
+ fn gy(&self, j: usize) -> f64 {
+ self.y0 + j as f64 * RES
+ }
+
+ /// Cell window (inclusive) covering bbox b grown by `pad`, clipped to the grid.
+ pub fn window(&self, b: &[f64; 4], pad: f64) -> (usize, usize, usize, usize) {
+ let i0 = ((b[0] - pad - self.x0) / RES).floor().max(0.0) as usize;
+ let j0 = ((b[1] - pad - self.y0) / RES).floor().max(0.0) as usize;
+ let i1 = (((b[2] + pad - self.x0) / RES).ceil() as i64).min(self.nx as i64 - 1);
+ let j1 = (((b[3] + pad - self.y0) / RES).ceil() as i64).min(self.ny as i64 - 1);
+ (i0, j0, i1.max(-1) as usize, j1.max(-1) as usize)
+ }
+
+ fn build_static(&mut self, plane_nets: &[String]) {
+ let (nx, ny) = (self.nx, self.ny);
+ let mut base = vec![0.0f64; self.n];
+ for j in 0..ny {
+ for i in 0..nx {
+ let (x, y) = (self.gx(i), self.gy(j));
+ let e = self.edge;
+ base[j * nx + i] = (x - e[0]).min(e[2] - x).min(y - e[1]).min(e[3] - y) - (EDGE_CLR - CLR);
+ }
+ }
+ // routing area: outside it is no-net copper, like the board edge (signed distance to
+ // the union, approximated by the deepest containing polygon)
+ if !self.area.is_empty() {
+ for j in 0..ny {
+ for i in 0..nx {
+ let p = (self.gx(i), self.gy(j));
+ let inside = self.area.iter().filter(|a| a.contains(p)).map(|a| a.boundary_dist(p)).fold(f64::NEG_INFINITY, f64::max);
+ let d = if inside.is_finite() { inside } else { -self.area.iter().map(|a| a.dist(p)).fold(f64::INFINITY, f64::min) };
+ let c = &mut base[j * nx + i];
+ *c = c.min(d - (self.area_margin - CLR));
+ }
+ }
+ }
+ // values >= CAP do not matter (the fields are capped), so holes and keep-outs only
+ // need a window around them
+ for &(x, y, dr) in &self.npth.clone() {
+ let r = dr / 2.0 + HOLE_CLR;
+ let (i0, j0, i1, j1) = self.window(&[x, y, x, y], r + 2.0);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let v = (self.gx(i) - x).hypot(self.gy(j) - y) - r + CLR;
+ let c = &mut base[j * nx + i];
+ *c = c.min(v);
+ }
+ }
+ }
+ for k in 0..self.keepouts.len() {
+ let bb = self.keepouts[k].bbox;
+ let (i0, j0, i1, j1) = self.window(&bb, 2.0);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let v = self.keepouts[k].dist((self.gx(i), self.gy(j))) + CLR;
+ let c = &mut base[j * nx + i];
+ *c = c.min(v);
+ }
+ }
+ }
+ for (k, v) in base.iter().enumerate() {
+ self.base[k] = *v as f32;
+ }
+ self.reset_region(None);
+ // pad distance field for via-in-pad avoidance (SMD pads, not exposed plane pads)
+ for k in 0..self.pads.len() {
+ let p = &self.pads[k];
+ if p.tht {
+ continue;
+ }
+ let b = p.poly.bbox;
+ if b[2] - b[0] > 2.5 && b[3] - b[1] > 2.5 && p.net >= 0 && plane_nets.iter().any(|n| n == self.netname(p.net)) {
+ continue;
+ }
+ let (i0, j0, i1, j1) = self.window(&b, 1.0);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let dd = p.poly.dist((self.gx(i), self.gy(j))) as f32;
+ for l in 0..2 {
+ if p.layers >> l & 1 == 1 {
+ let c = &mut self.padd[(j * nx + i) * 2 + l];
+ *c = c.min(dd);
+ }
+ }
+ }
+ }
+ }
+ for k in 0..self.pads.len() {
+ let p = &self.pads[k];
+ let it = Item { shape: Shape::Pad(k), net: p.net, layers: p.layers, w: 0.0, bbox: p.poly.bbox, owner: Owner::Pad, soft: false };
+ let id = self.add(it);
+ self.pads[k].item = id;
+ }
+ }
+
+ /// Append an item and insert it into the fields; returns its id.
+ pub fn add(&mut self, it: Item) -> usize {
+ self.items.push(it);
+ self.alive.push(true);
+ let id = self.items.len() - 1;
+ self.insert(id, None);
+ if let Shape::Via(p) = self.items[id].shape {
+ self.hole_min(p.0, p.1, via_drill(self.items[id].w) / 2.0, false);
+ }
+ id
+ }
+
+ /// Lower the hole field (or its static base) around a drill of radius r at (x, y).
+ fn hole_min(&mut self, x: f64, y: f64, r: f64, base: bool) {
+ let (i0, j0, i1, j1) = self.window(&[x, y, x, y], r + 1.0);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let d = ((self.gx(i) - x).hypot(self.gy(j) - y) - r) as f32;
+ let c = if base { &mut self.hole_base[j * self.nx + i] } else { &mut self.hole[j * self.nx + i] };
+ *c = c.min(d);
+ }
+ }
+ }
+
+ /// Rebuild the hole field around (x, y) after a via there was removed.
+ fn hole_reset(&mut self, x: f64, y: f64) {
+ let (i0, j0, i1, j1) = self.window(&[x, y, x, y], 2.5);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ self.hole[j * self.nx + i] = self.hole_base[j * self.nx + i];
+ }
+ }
+ for o in 0..self.items.len() {
+ if let (true, Shape::Via(p)) = (self.alive[o], self.items[o].shape) {
+ if (p.0 - x).abs() < 4.0 && (p.1 - y).abs() < 4.0 {
+ let r = via_drill(self.items[o].w) / 2.0;
+ let (k0, l0, k1, l1) = self.window(&[p.0, p.1, p.0, p.1], r + 1.0);
+ for j in l0.max(j0)..=l1.min(j1) {
+ for i in k0.max(i0)..=k1.min(i1) {
+ let d = ((self.gx(i) - p.0).hypot(self.gy(j) - p.1) - r) as f32;
+ let c = &mut self.hole[j * self.nx + i];
+ *c = c.min(d);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /// Attract the following searches to the copper of `items` (a net's bundle partners):
+ /// a step farther than the hug band from it costs `cost` more. Distances are exact within
+ /// ATTRACT_R of the items, CAP beyond. `cost` 0 switches it off.
+ pub fn set_attract(&mut self, items: &[usize], cost: f64) {
+ const ATTRACT_R: f64 = 1.5;
+ self.attract_cost = cost as f32;
+ if cost <= 0.0 {
+ return;
+ }
+ self.attract.clear();
+ self.attract.resize(2 * self.n, CAP);
+ for &id in items {
+ let it = &self.items[id];
+ let (i0, j0, i1, j1) = self.window(&it.bbox, ATTRACT_R);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let d = self.item_dist(it, self.gx(i), self.gy(j));
+ for l in 0..2 {
+ if it.on(l) {
+ let a = &mut self.attract[(j * self.nx + i) * 2 + l];
+ *a = a.min(d);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ pub fn reset_region(&mut self, b: Option<&[f64; 4]>) {
+ self.reset(b, false)
+ }
+
+ fn reset(&mut self, b: Option<&[f64; 4]>, soft: bool) {
+ let (i0, j0, i1, j1) = match b {
+ None => (0, 0, self.nx - 1, self.ny - 1),
+ Some(b) => self.window(b, 0.0),
+ };
+ for l in 0..2 {
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let c = j * self.nx + i;
+ if soft {
+ self.soft[c * 2 + l] = Field::EMPTY;
+ } else {
+ let bd = self.base[c];
+ self.f[c * 2 + l] = Field { d1: bd.min(CAP), n1: if bd < CAP { -1 } else { 0 }, d2: CAP };
+ }
+ }
+ }
+ }
+ }
+
+ /// Move all soft items into the hard field (after negotiation).
+ pub fn harden(&mut self) {
+ let ids: Vec<usize> = (0..self.items.len()).filter(|&i| self.alive[i] && self.items[i].soft).collect();
+ for &id in &ids {
+ self.items[id].soft = false;
+ self.insert(id, None);
+ }
+ self.reset(None, true);
+ }
+
+ /// Distance from (x, y) to an item's copper (f64 as in numpy, then f32).
+ pub fn item_dist(&self, it: &Item, x: f64, y: f64) -> f32 {
+ match it.shape {
+ Shape::Pad(k) => self.pads[k].poly.dist((x, y)) as f32,
+ Shape::Seg((x1, y1), (x2, y2)) => {
+ let (dx, dy) = (x2 - x1, y2 - y1);
+ let l2 = dx * dx + dy * dy;
+ let t = if l2 == 0.0 { 0.0 } else { (((x - x1) * dx + (y - y1) * dy) / l2).clamp(0.0, 1.0) };
+ ((x - (x1 + t * dx)).hypot(y - (y1 + t * dy)) - it.w / 2.0) as f32
+ }
+ Shape::Via((vx, vy)) => ((x - vx).hypot(y - vy) - it.w / 2.0) as f32,
+ Shape::Cu(k) => (self.cu[k].iter().map(|p| (x - p.0).hypot(y - p.1)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0) as f32,
+ }
+ }
+
+ fn insert(&mut self, id: usize, clip: Option<&[f64; 4]>) {
+ let it = self.items[id].clone();
+ let b = it.bbox;
+ let (i0, j0, i1, j1) = match clip {
+ Some(c) => {
+ let b2 = [(b[0] - CAP as f64).max(c[0]), (b[1] - CAP as f64).max(c[1]), (b[2] + CAP as f64).min(c[2]), (b[3] + CAP as f64).min(c[3])];
+ if b2[0] > b2[2] || b2[1] > b2[3] {
+ return;
+ }
+ self.window(&b2, 0.0)
+ }
+ None => self.window(&b, CAP as f64),
+ };
+ let net = it.net;
+ let field = if it.soft { &mut self.soft } else { &mut self.f };
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let (x, y) = (self.x0 + i as f64 * RES, self.y0 + j as f64 * RES);
+ let dd = match it.shape {
+ Shape::Pad(k) => self.pads[k].poly.dist((x, y)) as f32,
+ Shape::Seg((x1, y1), (x2, y2)) => {
+ let (dx, dy) = (x2 - x1, y2 - y1);
+ let l2 = dx * dx + dy * dy;
+ let t = if l2 == 0.0 { 0.0 } else { (((x - x1) * dx + (y - y1) * dy) / l2).clamp(0.0, 1.0) };
+ ((x - (x1 + t * dx)).hypot(y - (y1 + t * dy)) - it.w / 2.0) as f32
+ }
+ Shape::Via((vx, vy)) => ((x - vx).hypot(y - vy) - it.w / 2.0) as f32,
+ Shape::Cu(k) => (self.cu[k].iter().map(|p| (x - p.0).hypot(y - p.1)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0) as f32,
+ };
+ for l in 0..2 {
+ if !it.on(l) {
+ continue;
+ }
+ field[(j * self.nx + i) * 2 + l].add(dd, net);
+ }
+ }
+ }
+ }
+
+ pub fn remove_items(&mut self, ids: &[usize]) {
+ for &id in ids {
+ self.alive[id] = false;
+ }
+ let c = CAP as f64;
+ for &id in ids {
+ let ib = self.items[id].bbox;
+ let soft = self.items[id].soft;
+ let b = [ib[0] - c, ib[1] - c, ib[2] + c, ib[3] + c];
+ self.reset(Some(&b), soft);
+ for o in 0..self.items.len() {
+ if !self.alive[o] || self.items[o].soft != soft {
+ continue;
+ }
+ let ob = self.items[o].bbox;
+ if ob[0] - c > b[2] || ob[2] + c < b[0] || ob[1] - c > b[3] || ob[3] + c < b[1] {
+ continue;
+ }
+ self.insert(o, Some(&b));
+ }
+ if let Shape::Via(p) = self.items[id].shape {
+ self.hole_reset(p.0, p.1);
+ }
+ }
+ }
+
+ /// Distance to foreign copper for `net` at state index s.
+ pub fn fdist(&self, s: usize, net: i32) -> f32 {
+ self.f[s].fdist(net)
+ }
+
+ /// Grid states (cell * 2 + layer, sorted) covered by the copper of `ids` on `layers`.
+ pub fn cells_of(&self, ids: &[usize], layers: u8) -> Vec<i32> {
+ let mut out = Vec::new();
+ for &id in ids {
+ let it = &self.items[id];
+ let (i0, j0, i1, j1) = self.window(&it.bbox, 0.05);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ if self.item_dist(it, self.gx(i), self.gy(j)) <= 0.0 {
+ for l in 0..2 {
+ if it.on(l) && layers >> l & 1 == 1 {
+ out.push(((j * self.nx + i) * 2 + l) as i32);
+ }
+ }
+ }
+ }
+ }
+ }
+ out.sort_unstable();
+ out.dedup();
+ out
+ }
+
+ /// A* from the copper of `src` to the copper of `tgt` (and `extra_tgt` cells, or any
+ /// B.Cu cell with `goal_layer1`). Returns the cell path (source first) and neck flags.
+ #[allow(clippy::too_many_arguments)]
+ pub fn route(
+ &mut self,
+ net: i32,
+ src: &[usize],
+ tgt: &[usize],
+ goal_layer1: bool,
+ w: f64,
+ wneck: f64,
+ via_d: f64,
+ neck_items: &[usize],
+ hxy: Option<Pt>,
+ extra_tgt: Option<&[i32]>,
+ o: &SearchOpts,
+ ) -> Option<(Vec<i32>, Vec<u8>)> {
+ let src_cells = self.cells_of(src, 3);
+ if src_cells.is_empty() {
+ return None;
+ }
+ let mut tc = if tgt.is_empty() { Vec::new() } else { self.cells_of(tgt, 3) };
+ if let Some(e) = extra_tgt {
+ tc.extend_from_slice(e);
+ }
+ for &c in &tc {
+ self.tgt[c as usize] = 1;
+ }
+ let hxy = hxy.unwrap_or_else(|| match tgt.first() {
+ Some(&g) => match self.items[g].shape {
+ Shape::Pad(k) => self.pads[k].poly.centroid(),
+ Shape::Via(p) => p,
+ Shape::Seg(a, _) => a,
+ Shape::Cu(k) => self.cu[k][0],
+ },
+ None => (self.x0, self.y0),
+ });
+ let (hx, hy) = self.xy_cell(hxy.0, hxy.1);
+ let mut boxes = Vec::new();
+ for &id in neck_items {
+ let b = self.items[id].bbox;
+ let (i0, j0) = self.xy_cell(b[0] - o.neck_zone, b[1] - o.neck_zone);
+ let (i1, j1) = self.xy_cell(b[2] + o.neck_zone, b[3] + o.neck_zone);
+ boxes.push([i0 as i32, j0 as i32, i1 as i32, j1 as i32]);
+ }
+ let mut window = [0, 0, self.nx as i32 - 1, self.ny as i32 - 1];
+ if o.margin > 0.0 && !tgt.is_empty() {
+ let mut bb = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
+ for &id in src.iter().chain(tgt) {
+ let b = self.items[id].bbox;
+ bb = [bb[0].min(b[0]), bb[1].min(b[1]), bb[2].max(b[2]), bb[3].max(b[3])];
+ }
+ let (i0, j0, i1, j1) = self.window(&bb, o.margin);
+ window = [i0 as i32, j0 as i32, i1 as i32, j1 as i32];
+ }
+ let args = SearchArgs {
+ window,
+ nx: self.nx,
+ n: self.n,
+ f: &self.f,
+ padd: &self.padd,
+ hole: &self.hole,
+ r_hole: (via_drill(via_d) / 2.0 + HOLE_HOLE + M) as f32,
+ via_gap: ((via_drill(via_d) + HOLE_HOLE) / RES).ceil() as u16 + 1,
+ cost: &self.costs[&self.cost],
+ soft: if self.soft_mode { Some(&self.soft) } else { None },
+ hist: &self.hist,
+ pres: self.pres,
+ net,
+ src: &src_cells,
+ tgt: &self.tgt,
+ goal_layer1,
+ hx: hx as i32,
+ hy: hy as i32,
+ r_nom: (w / 2.0 + CLR + M) as f32,
+ r_neck: if wneck != 0.0 { (wneck / 2.0 + CLR + M) as f32 } else { 0.0 },
+ r_via: (via_d / 2.0 + CLR + M) as f32,
+ r_vpad: (via_d / 2.0 + 0.05) as f32,
+ r_diag: RDIAG as f32,
+ neckbox: &boxes,
+ via_cost: o.via_cost as f32,
+ via_cmult: o.via_cmult as f32,
+ bmult: o.bmult as f32,
+ turn_cost: o.turn as f32,
+ allow_via: o.allow_via,
+ max_expand: o.max_expand,
+ layer_mask: o.layer_mask,
+ hweight: o.hweight as f32,
+ hug: o.hug as f32,
+ attract: if self.attract_cost > 0.0 { Some(&self.attract) } else { None },
+ attract_cost: self.attract_cost,
+ neck: o.neck as f32,
+ };
+ let t = std::time::Instant::now();
+ let r = self.search.route(&args);
+ if std::env::var("ROUTER_TRACE").is_ok() {
+ eprintln!("ASTAR {:.6}", t.elapsed().as_secs_f64());
+ }
+ if std::env::var("ROUTER_TRACE").is_ok() {
+ eprintln!("TRACE net={} src={} tgt={} first={:?} last={:?} hx={} hy={} len={:?}", net, src_cells.len(), tc.len(), src_cells.first(), src_cells.last(), hx, hy, r.as_ref().map(|(p, _)| (p.len(), p[p.len() - 1], p[0])));
+ }
+ for &c in &tc {
+ self.tgt[c as usize] = 0;
+ }
+ r.map(|(mut p, mut nk)| {
+ p.reverse();
+ nk.reverse();
+ (p, nk)
+ })
+ }
+
+ /// Cell path to segments (collinear steps of equal width merged) and vias.
+ pub fn path_to_geom(&self, path: &[i32], neck: &[u8], w: f64, wneck: f64) -> (Vec<Seg>, Vec<Pt>) {
+ let pts: Vec<(usize, usize, usize, bool)> = path
+ .iter()
+ .zip(neck)
+ .map(|(&s, &nk)| {
+ let (l, c) = (s as usize & 1, s as usize >> 1);
+ (l, c % self.nx, c / self.nx, nk != 0)
+ })
+ .collect();
+ let width = |a: &(usize, usize, usize, bool), b: &(usize, usize, usize, bool)| if wneck != 0.0 && (a.3 || b.3) { wneck } else { w };
+ let mut segs = Vec::new();
+ let mut vias = Vec::new();
+ let flush = |run: &[(usize, usize, usize, bool)], segs: &mut Vec<Seg>| {
+ if run.len() < 2 {
+ return;
+ }
+ let mut k = 0;
+ while k < run.len() - 1 {
+ let (l, i, j, _) = run[k];
+ let wd = width(&run[k], &run[k + 1]);
+ let d = (run[k + 1].1 as i64 - i as i64, run[k + 1].2 as i64 - j as i64);
+ let mut m = k + 1;
+ while m < run.len() - 1 {
+ let w2 = width(&run[m], &run[m + 1]);
+ if (run[m + 1].1 as i64 - run[m].1 as i64, run[m + 1].2 as i64 - run[m].2 as i64) != d || w2 != wd {
+ break;
+ }
+ m += 1;
+ }
+ segs.push((l, self.cell_xy(i, j), self.cell_xy(run[m].1, run[m].2), wd));
+ k = m;
+ }
+ };
+ let mut run = vec![pts[0]];
+ for &p in &pts[1..] {
+ if p.0 != run[run.len() - 1].0 {
+ flush(&run, &mut segs);
+ vias.push(self.cell_xy(p.1, p.2));
+ run = vec![p];
+ } else {
+ run.push(p);
+ }
+ }
+ flush(&run, &mut segs);
+ (segs, vias)
+ }
+
+ pub fn seg_item(net: i32, l: usize, a: Pt, b: Pt, w: f64, owner: Owner) -> Item {
+ let bbox = [a.0.min(b.0) - w / 2.0, a.1.min(b.1) - w / 2.0, a.0.max(b.0) + w / 2.0, a.1.max(b.1) + w / 2.0];
+ Item { shape: Shape::Seg(a, b), net, layers: 1 << l, w, bbox, owner, soft: false }
+ }
+
+ pub fn via_item(net: i32, p: Pt, d: f64, layers: u8, owner: Owner) -> Item {
+ let r = d / 2.0;
+ Item { shape: Shape::Via(p), net, layers, w: d, bbox: [p.0 - r, p.1 - r, p.0 + r, p.1 + r], owner, soft: false }
+ }
+
+ pub fn commit(&mut self, net: i32, segs: &[Seg], vias: &[Pt], via_d: f64) -> Vec<usize> {
+ let o = self.commit_owner;
+ let mut items: Vec<Item> = segs.iter().map(|&(l, a, b, w)| Board::seg_item(net, l, a, b, w, o)).collect();
+ items.extend(vias.iter().map(|&v| Board::via_item(net, v, via_d, 3, o)));
+ let soft = self.soft_mode;
+ items.into_iter().map(|it| self.add(Item { soft, ..it })).collect()
+ }
+}
diff --git a/tools/router/src/cleanup.rs b/tools/router/src/cleanup.rs
new file mode 100644
index 0000000..d3ed3bc
--- /dev/null
+++ b/tools/router/src/cleanup.rs
@@ -0,0 +1,408 @@
+//! Cleanup after negotiation: reroute each net with the rest fixed (hugging other copper,
+//! kept only if it is no worse), drop vias that connect nothing, pull chains of track tight.
+//! Only negotiated copper (Owner::Negotiated) is touched.
+
+use crate::board::{Item, Owner, Shape, CLR, M, RES};
+use crate::geom::{point_seg, Pt};
+use crate::router::Router;
+use serde_json::json;
+use std::collections::HashMap;
+
+/// Vias count like this much track length (mm) when comparing two routes of a net.
+const VIA_MM: f64 = 2.0;
+/// Necked track (narrower than the net's width) counts this much extra per mm.
+const NECK_MM: f64 = 2.0;
+
+impl Router {
+ fn negotiated(&self, net: i32) -> Vec<usize> {
+ self.net_items[net as usize].iter().copied().filter(|&id| self.b.alive[id] && self.b.items[id].owner == Owner::Negotiated).collect()
+ }
+
+ /// (pieces, vias, track length + NECK_MM x necked length) of a net's copper.
+ fn net_score(&self, net: i32) -> (usize, usize, f64) {
+ let pieces = self.components(&self.net_items_all(net)).len();
+ let (mut vias, mut len) = (0, 0.0);
+ for &id in &self.net_items[net as usize] {
+ match self.b.items[id].shape {
+ Shape::Via(_) => vias += 1,
+ Shape::Seg(a, b) => len += (a.0 - b.0).hypot(a.1 - b.1),
+ Shape::Pad(_) | Shape::Cu(_) => {}
+ }
+ }
+ (pieces, vias, len + NECK_MM * self.net_necked_mm(net))
+ }
+
+ fn take(&mut self, net: i32, ids: &[usize]) -> Vec<Item> {
+ let items: Vec<Item> = ids.iter().map(|&id| self.b.items[id].clone()).collect();
+ self.net_items[net as usize].retain(|id| !ids.contains(id));
+ self.b.remove_items(ids);
+ items
+ }
+
+ fn put(&mut self, net: i32, items: Vec<Item>) -> Vec<usize> {
+ let ids: Vec<usize> = items.into_iter().map(|it| self.b.add(it)).collect();
+ self.net_items[net as usize].extend_from_slice(&ids);
+ ids
+ }
+
+ /// Reroute every negotiated net once with all other copper fixed (hugging other copper,
+ /// necks priced by the width they give up).
+ fn reroute_pass(&mut self, hug: f64, neck: f64, attract: f64) -> (usize, usize) {
+ let jobs = self.jobs.clone();
+ let (mut tried, mut kept) = (0, 0);
+ for j in jobs.iter().filter(|j| !j.plane) {
+ let net = self.nid(&j.name);
+ let old_ids = self.negotiated(net);
+ if old_ids.is_empty() {
+ continue;
+ }
+ tried += 1;
+ let before = self.net_score(net);
+ let failed = self.failed.clone();
+ let old = self.take(net, &old_ids);
+ let mut j2 = j.clone();
+ j2.opts.hug = Some(hug);
+ j2.opts.neck = Some(neck);
+ for jn in &mut j2.joins {
+ jn.3.hug = Some(hug);
+ jn.3.neck = Some(neck);
+ }
+ // bundled nets run alongside their partners' copper where they can
+ self.attract_partners(net, attract);
+ self.route_job(&j2, Some(&[]));
+ self.b.set_attract(&[], 0.0);
+ let after = self.net_score(net);
+ let score = |s: (usize, usize, f64)| s.2 + VIA_MM * s.1 as f64;
+ if after.0 > before.0 || score(after) > score(before) * 1.02 {
+ let new_ids = self.negotiated(net);
+ self.take(net, &new_ids);
+ self.put(net, old);
+ self.failed = failed;
+ } else {
+ kept += 1;
+ }
+ }
+ (tried, kept)
+ }
+
+ /// Remove negotiated vias whose removal leaves the net in as many pieces.
+ fn drop_vias(&mut self) -> usize {
+ let mut n = 0;
+ for net in 1..self.b.netnames.len() as i32 {
+ if self.plane_nets.iter().any(|p| p == self.b.netname(net)) {
+ continue;
+ }
+ for id in self.negotiated(net) {
+ if !matches!(self.b.items[id].shape, Shape::Via(_)) {
+ continue;
+ }
+ let before = self.components(&self.net_items_all(net)).len();
+ let it = self.take(net, &[id]);
+ if self.components(&self.net_items_all(net)).len() > before {
+ self.put(net, it);
+ } else {
+ n += 1;
+ }
+ }
+ }
+ n
+ }
+
+ /// Does a track of width w from a to b on layer l keep its clearance to other nets?
+ /// The field is sampled every RES/2; each sample allows for its distance to the cell
+ /// centre and for the gap to the next sample, so the test is conservative.
+ fn track_clear(&self, net: i32, l: usize, a: Pt, b: Pt, w: f64) -> bool {
+ let len = (b.0 - a.0).hypot(b.1 - a.1);
+ let n = (len / (RES / 2.0)).ceil().max(1.0) as usize;
+ for k in 0..=n {
+ let t = k as f64 / n as f64;
+ let p = (a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1));
+ let (i, j) = self.b.xy_cell(p.0, p.1);
+ if i < 0 || j < 0 || i >= self.b.nx as i64 || j >= self.b.ny as i64 {
+ return false;
+ }
+ let c = self.b.cell_xy(i as usize, j as usize);
+ let off = (c.0 - p.0).hypot(c.1 - p.1) + RES / 4.0;
+ let fd = self.b.f[(j as usize * self.b.nx + i as usize) * 2 + l].fdist(net) as f64;
+ if fd < w / 2.0 + CLR + M + off {
+ return false;
+ }
+ }
+ true
+ }
+
+ /// Octilinear link from a to b (straight, 45 degrees, or a straight and a diagonal leg)
+ /// that keeps clearance, as its points.
+ fn link(&self, net: i32, l: usize, a: Pt, b: Pt, w: f64) -> Option<Vec<Pt>> {
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ if dx.abs() < 1e-9 || dy.abs() < 1e-9 || (dx.abs() - dy.abs()).abs() < 1e-9 {
+ return self.track_clear(net, l, a, b, w).then(|| vec![a, b]);
+ }
+ let d = dx.abs().min(dy.abs());
+ let (sx, sy) = (dx.signum() * d, dy.signum() * d);
+ for c in [(a.0 + sx, a.1 + sy), (b.0 - sx, b.1 - sy)] {
+ if self.track_clear(net, l, a, c, w) && self.track_clear(net, l, c, b, w) {
+ return Some(vec![a, c, b]);
+ }
+ }
+ None
+ }
+
+ /// Split negotiated tracks where other copper of the net ends on them, so every joint is
+ /// a track end.
+ fn split_at_joints(&mut self, net: i32) {
+ let mut pts: Vec<Pt> = Vec::new();
+ for &id in &self.net_items[net as usize] {
+ match self.b.items[id].shape {
+ Shape::Seg(a, b) => pts.extend([a, b]),
+ Shape::Via(p) => pts.push(p),
+ Shape::Pad(_) | Shape::Cu(_) => {}
+ }
+ }
+ for id in self.negotiated(net) {
+ let it = self.b.items[id].clone();
+ let Shape::Seg(a, b) = it.shape else { continue };
+ let near = |p: &Pt, q: Pt| (p.0 - q.0).hypot(p.1 - q.1) < 1e-6;
+ let mut cut: Vec<(f64, Pt)> = pts
+ .iter()
+ .filter(|p| !near(p, a) && !near(p, b) && point_seg(**p, a, b) < 1e-6)
+ .map(|&p| ((p.0 - a.0).hypot(p.1 - a.1), p))
+ .collect();
+ if cut.is_empty() {
+ continue;
+ }
+ cut.sort_by(|x, y| x.0.total_cmp(&y.0));
+ cut.dedup_by(|x, y| (x.0 - y.0).abs() < 1e-6);
+ let mut chain = vec![a];
+ chain.extend(cut.into_iter().map(|c| c.1));
+ chain.push(b);
+ self.take(net, &[id]);
+ let l = if it.on(0) { 0 } else { 1 };
+ let pieces = chain.windows(2).map(|s| crate::board::Board::seg_item(net, l, s[0], s[1], it.w, Owner::Negotiated)).collect();
+ self.put(net, pieces);
+ }
+ }
+
+ /// Chains of negotiated tracks between fixed points (vias, pads, junctions, changes of
+ /// layer or width), as item ids and points.
+ fn chains(&self, net: i32) -> Vec<(Vec<usize>, Vec<Pt>)> {
+ let key = |p: Pt| ((p.0 * 1e5).round() as i64, (p.1 * 1e5).round() as i64);
+ let segs = self.negotiated(net).into_iter().filter(|&id| matches!(self.b.items[id].shape, Shape::Seg(..))).collect::<Vec<_>>();
+ let mut at: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
+ for &id in &segs {
+ if let Shape::Seg(a, b) = self.b.items[id].shape {
+ at.entry(key(a)).or_default().push(id);
+ at.entry(key(b)).or_default().push(id);
+ }
+ }
+ // degree counts every track end of the net, not only negotiated ones
+ let mut deg: HashMap<(i64, i64), usize> = HashMap::new();
+ let mut vias = Vec::new();
+ for &id in &self.net_items[net as usize] {
+ match self.b.items[id].shape {
+ Shape::Seg(a, b) => {
+ *deg.entry(key(a)).or_default() += 1;
+ *deg.entry(key(b)).or_default() += 1;
+ }
+ Shape::Via(p) => vias.push(p),
+ Shape::Pad(_) | Shape::Cu(_) => {}
+ }
+ }
+ let pads: Vec<usize> = self.pads_by_net[net as usize].clone();
+ let fixed = |p: Pt| {
+ let k = key(p);
+ let ids = &at[&k];
+ if deg[&k] != 2 || ids.len() != 2 {
+ return true;
+ }
+ let (s, t) = (&self.b.items[ids[0]], &self.b.items[ids[1]]);
+ s.layers != t.layers
+ || (s.w - t.w).abs() > 1e-9
+ || vias.iter().any(|v| (v.0 - p.0).hypot(v.1 - p.1) < 1e-6)
+ || pads.iter().any(|&k| self.b.pads[k].poly.dist(p) < 1e-6)
+ };
+ let mut used: Vec<usize> = Vec::new();
+ let mut out = Vec::new();
+ for &start in &segs {
+ if used.contains(&start) {
+ continue;
+ }
+ let Shape::Seg(a, b) = self.b.items[start].shape else { continue };
+ // walk back to a fixed end, then forward collecting the chain
+ let (mut cur, mut end) = (start, a);
+ let mut guard = 0;
+ while !fixed(end) && guard < 100_000 {
+ guard += 1;
+ let nxt = *at[&key(end)].iter().find(|&&o| o != cur).unwrap();
+ let Shape::Seg(p, q) = self.b.items[nxt].shape else { unreachable!() };
+ end = if key(p) == key(end) { q } else { p };
+ cur = nxt;
+ }
+ if guard >= 100_000 {
+ used.push(start);
+ continue; // a loop without fixed points
+ }
+ let _ = b;
+ let mut ids = vec![cur];
+ let Shape::Seg(p, q) = self.b.items[cur].shape else { unreachable!() };
+ let mut pts = vec![end];
+ let mut tip = if key(p) == key(end) { q } else { p };
+ pts.push(tip);
+ while !fixed(tip) {
+ let nxt = *at[&key(tip)].iter().find(|&&o| o != *ids.last().unwrap()).unwrap();
+ let Shape::Seg(p, q) = self.b.items[nxt].shape else { unreachable!() };
+ tip = if key(p) == key(tip) { q } else { p };
+ ids.push(nxt);
+ pts.push(tip);
+ }
+ used.extend_from_slice(&ids);
+ out.push((ids, pts));
+ }
+ out
+ }
+
+ /// Replace runs of each chain by octilinear shortcuts where they keep clearance.
+ fn pull_tight(&mut self) -> (usize, f64) {
+ let (mut n, mut saved) = (0, 0.0);
+ for net in 1..self.b.netnames.len() as i32 {
+ if self.negotiated(net).is_empty() {
+ continue;
+ }
+ self.split_at_joints(net);
+ for (ids, pts) in self.chains(net) {
+ if pts.len() < 3 {
+ continue;
+ }
+ let it = self.b.items[ids[0]].clone();
+ let (l, w) = (if it.on(0) { 0 } else { 1 }, it.w);
+ let mut out = vec![pts[0]];
+ let mut i = 0;
+ while i < pts.len() - 1 {
+ let mut step = None;
+ for j in (i + 2..pts.len()).rev() {
+ if let Some(lk) = self.link(net, l, pts[i], pts[j], w) {
+ step = Some((j, lk));
+ break;
+ }
+ }
+ match step {
+ Some((j, lk)) => {
+ out.extend_from_slice(&lk[1..]);
+ i = j;
+ }
+ None => {
+ out.push(pts[i + 1]);
+ i += 1;
+ }
+ }
+ }
+ let length = |v: &[Pt]| v.windows(2).map(|s| (s[1].0 - s[0].0).hypot(s[1].1 - s[0].1)).sum::<f64>();
+ let gain = length(&pts) - length(&out);
+ if gain < 1e-6 {
+ continue;
+ }
+ let before = self.components(&self.net_items_all(net)).len();
+ let old = self.take(net, &ids);
+ let new = out
+ .windows(2)
+ .filter(|s| (s[1].0 - s[0].0).hypot(s[1].1 - s[0].1) > 1e-9)
+ .map(|s| crate::board::Board::seg_item(net, l, s[0], s[1], w, Owner::Negotiated))
+ .collect();
+ let new_ids = self.put(net, new);
+ if self.components(&self.net_items_all(net)).len() > before {
+ self.take(net, &new_ids);
+ self.put(net, old);
+ } else {
+ n += 1;
+ saved += gain;
+ }
+ }
+ }
+ (n, saved)
+ }
+
+ /// Widen necked negotiated tracks (at most the neck width, narrower than the net's width)
+ /// to the widest width, in 0.05 mm steps, that keeps clearance. Stubs inside a pad stay.
+ fn widen(&mut self) -> usize {
+ let mut n = 0;
+ for j in self.jobs.clone() {
+ let net = self.nid(&j.name);
+ let (w, wneck) = self.job_widths(&j);
+ for id in self.negotiated(net) {
+ let it = self.b.items[id].clone();
+ let Shape::Seg(a, b) = it.shape else { continue };
+ if it.w >= w - 1e-9 || it.w > wneck + 1e-9 {
+ continue;
+ }
+ let mid = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
+ if self.pads_by_net[net as usize].iter().any(|&k| self.b.pads[k].poly.contains(mid)) {
+ continue;
+ }
+ let l = if it.on(0) { 0 } else { 1 };
+ let mut cand = w;
+ while cand > it.w + 1e-9 {
+ if self.track_clear(net, l, a, b, cand) {
+ self.take(net, &[id]);
+ self.put(net, vec![crate::board::Board::seg_item(net, l, a, b, cand, Owner::Negotiated)]);
+ n += 1;
+ break;
+ }
+ cand = ((cand - 0.05) * 1e6).round() / 1e6;
+ }
+ }
+ }
+ n
+ }
+
+ /// Remove routed copper that ends nowhere (what KiCad's DRC calls dangling): tracks with
+ /// an end that touches no other copper of the net, and on signal nets vias that touch at
+ /// most one item. Ripped branches leave such remnants. Fixed copper stays.
+ pub fn prune_dangling(&mut self) -> usize {
+ let mut total = 0;
+ loop {
+ let mut gone = Vec::new();
+ for net in 1..self.b.netnames.len() as i32 {
+ let plane = self.plane_nets.iter().any(|p| p == self.b.netname(net));
+ let all = self.net_items_all(net);
+ for &id in &self.net_items[net as usize] {
+ let it = &self.b.items[id];
+ if it.owner == Owner::Existing || !self.b.alive[id] {
+ continue;
+ }
+ let dangling = match it.shape {
+ Shape::Seg(a, b) => {
+ let l = if it.on(0) { 0 } else { 1 };
+ let touches = |p: Pt| all.iter().any(|&o| o != id && self.b.items[o].on(l) && self.b.item_dist(&self.b.items[o], p.0, p.1) <= 1e-4);
+ !touches(a) || !touches(b)
+ }
+ Shape::Via(_) if !plane => all.iter().filter(|&&o| o != id && self.item_item(id, o) <= 1e-4).count() <= 1,
+ _ => false,
+ };
+ if dangling {
+ gone.push((net, id));
+ }
+ }
+ }
+ if gone.is_empty() {
+ return total;
+ }
+ total += gone.len();
+ for (net, id) in gone {
+ self.take(net, &[id]);
+ }
+ }
+ }
+
+ /// The cleanup passes (after a negotiate step).
+ pub fn cleanup(&mut self, hug: f64, neck: f64, attract: f64) {
+ let t = std::time::Instant::now();
+ self.b.commit_owner = Owner::Negotiated;
+ let (tried, kept) = self.reroute_pass(hug, neck, attract);
+ let vias = self.drop_vias();
+ let (chains, saved) = self.pull_tight();
+ let widened = self.widen();
+ let pruned = self.prune_dangling();
+ self.b.commit_owner = Owner::Routed;
+ self.log.push(json!(["cleanup", "rerouted", kept, "of", tried, "vias dropped", vias, "chains tightened", chains, "widened", widened, "dangling pruned", pruned, "mm saved", (saved * 10.0).round() / 10.0, "s", (t.elapsed().as_secs_f64() * 1000.0).round() / 1000.0]));
+ }
+}
diff --git a/tools/router/src/config.rs b/tools/router/src/config.rs
new file mode 100644
index 0000000..090d999
--- /dev/null
+++ b/tools/router/src/config.rs
@@ -0,0 +1,389 @@
+//! route.toml: the board's routing rules (replaces the Python route scripts).
+//!
+//! ```toml
+//! prefix = "/My Sheet/" # net names may leave it out
+//! plane_nets = ["GND"]
+//!
+//! [[fixed]] # fixed copper, loaded before the steps
+//! name = "bus" # path from --fixed bus=FILE, or `path` (relative to the toml)
+//! done = true # its nets are complete: `rest` leaves them alone
+//! [[fixed]]
+//! name = "keep"
+//! unmoved = true # a board dump: keep copper of nets whose parts did not move
+//! exclude = ["GND"]
+//! optional = true
+//!
+//! [costs.sig] # cost maps: rectangles relative to a footprint's origin
+//! zones = [{ layer = "F", fp = "U1", rect = [-8.1, -9.2, 8.1, 10.66], cost = 200 }]
+//! [costs.rudy]
+//! rudy = { scale = 4.0, max = 20.0 } # RUDY congestion of the pads' MSTs on F.Cu
+//!
+//! [[step]]
+//! do = "connect" # via, plane, connect, pair, decaps, rest, repair, tie, stitch
+//! nets = ["XI", "XO"]
+//! cost = "sig" # "none" clears; left out, the previous map stays
+//! ```
+//!
+//! Steps run in order. Pads are written "REF:NUM".
+//!
+//! `do = "pour"` checks the plane nets' pours (board.json `zones`) for islands that leave
+//! pads apart and, with `fix` (default), joins them with vias of diameter `d` (0.6).
+//! `planes = true` on a negotiate step routes the plane nets' drops in the negotiation
+//! (instead of a `plane` step before it), so they can give way to signals.
+//! `[rank]` sets how routed boards compare (see Rank).
+//!
+//! `area = "pours"` keeps all copper inside the plane nets' pours (board.json `zones`), e.g. a
+//! design block's area; `area = [[x, y], ...]` gives a polygon. `area_margin` (mm, default 0)
+//! keeps copper that far inside.
+//!
+//! `[[bundle]] nets = [...]` (pairs, buses): a step of one of these nets that does not run
+//! alongside its bundle partners' copper costs `attract` more (hug is 0.3): on the negotiate
+//! step (default 0, off; 0.5 works well) and on the cleanup step (default 0.5). Soft:
+//! nothing is forced, and the cleanup still keeps a reroute only if it is at most 2 % worse.
+//! Negotiation is where it counts: in the cleanup the space beside a partner is mostly taken.
+//!
+//! `do = "negotiate"` routes every net still in pieces at once (negotiated congestion), with
+//! `cost`, `rounds`, `pres`, `pres_mult`, `hist` and search settings as defaults; a
+//! `[nets.NAME]` table overrides them per net (w, wneck, neck_zone, via_d, root, decaps,
+//! priority, cost, ...) and `[[nets.NAME.join]]` adds pad pairs routed first (a, b, cost, w, wneck,
+//! allow_via). Higher `priority` routes first in each round.
+//!
+//! `[[escape]] nets = [...], from = [x, y], to = [x, y]` reserves escape lines for nets that
+//! leave the block (a module's interface nets, one pad each): a virtual pad per net, spread
+//! evenly from `from` to `to` in the order given (`size` mm square, default 0.25, on F.Cu),
+//! routed with everything else (`w` mm wide, default the nets' own width), so a board only
+//! counts as complete when every such net can still reach the block edge past the block's own
+//! copper. Their copper is left out of the
+//! output (`keep = true` keeps it); the base board routes the real lines.
+//!
+//! `neck_zone` (mm, default 1): a track may neck to `wneck` only within this distance of the
+//! pads it joins. A fine-pitch part whose pins are nearly all used needs more (0.4 mm-pitch
+//! QFN: 2), so neighbouring lines can spread apart before they must be full width.
+
+use crate::router::{NetOpts, PadRef};
+use anyhow::{anyhow, bail, Result};
+use serde::Deserialize;
+use std::collections::BTreeMap;
+
+fn default_planes() -> Vec<String> {
+ vec!["GND".into()]
+}
+
+fn yes() -> bool {
+ true
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Config {
+ #[serde(default)]
+ pub prefix: String,
+ #[serde(default = "default_planes")]
+ pub plane_nets: Vec<String>,
+ #[serde(default)]
+ pub fixed: Vec<Fixed>,
+ #[serde(default)]
+ pub costs: BTreeMap<String, CostDef>,
+ #[serde(default)]
+ pub nets: BTreeMap<String, NetCfg>,
+ #[serde(default)]
+ pub step: Vec<Step>,
+ #[serde(default)]
+ pub rank: Rank,
+ /// Routing area: all copper stays inside it (`area_margin` mm in, default 0).
+ #[serde(default)]
+ pub area: Option<Area>,
+ #[serde(default)]
+ pub area_margin: f64,
+ /// Nets the cleanup draws together: `[[bundle]] nets = ["USB_DP", "USB_DN"]`.
+ #[serde(default)]
+ pub bundle: Vec<Bundle>,
+ /// Escape lines for nets that leave the block, to virtual pads along an edge.
+ #[serde(default)]
+ pub escape: Vec<Escape>,
+}
+
+fn escape_size() -> f64 {
+ 0.25
+}
+
+#[derive(Deserialize, Clone)]
+#[serde(deny_unknown_fields)]
+pub struct Escape {
+ /// in their order along the edge, from `from` to `to`
+ pub nets: Vec<String>,
+ pub from: [f64; 2],
+ pub to: [f64; 2],
+ #[serde(default = "escape_size")]
+ pub size: f64,
+ /// track width of the escape lines (default: the nets' own); the lines only reserve room,
+ /// so they may be as thin as the base board will route them (e.g. 0.15 at a 0.4 mm pitch)
+ pub w: Option<f64>,
+ /// write the escape copper to the output too
+ #[serde(default)]
+ pub keep: bool,
+}
+
+#[derive(Deserialize, Clone)]
+#[serde(deny_unknown_fields)]
+pub struct Bundle {
+ pub nets: Vec<String>,
+}
+
+/// `area = "pours"` (the union of the plane nets' zones in board.json) or a polygon.
+#[derive(Deserialize, Clone)]
+#[serde(untagged)]
+pub enum Area {
+ Pours(String),
+ Poly(Vec<[f64; 2]>),
+}
+
+/// How routed boards of the same board compare (placer --route): fewer split nets, failed
+/// connections and pour islands first, then the lowest score = net length x weight +
+/// via_mm x vias + neck_mm x necked length + bcu_mm x B.Cu length.
+#[derive(Deserialize, Clone)]
+#[serde(deny_unknown_fields, default)]
+pub struct Rank {
+ pub via_mm: f64,
+ pub neck_mm: f64,
+ pub bcu_mm: f64,
+ /// net length weights by glob (`*` only), e.g. { match = "*/SENSE*", weight = 2.0 }
+ pub nets: Vec<RankNet>,
+}
+
+impl Default for Rank {
+ fn default() -> Self {
+ Rank { via_mm: 2.0, neck_mm: 2.0, bcu_mm: 0.0, nets: vec![] }
+ }
+}
+
+#[derive(Deserialize, Clone)]
+#[serde(deny_unknown_fields)]
+pub struct RankNet {
+ #[serde(rename = "match")]
+ pub pattern: String,
+ pub weight: f64,
+}
+
+/// Glob with `*` only.
+pub fn glob(pat: &str, s: &str) -> bool {
+ let parts: Vec<&str> = pat.split('*').collect();
+ if parts.len() == 1 {
+ return pat == s;
+ }
+ let mut rest = s;
+ for (i, p) in parts.iter().enumerate() {
+ if i == 0 {
+ if !rest.starts_with(p) {
+ return false;
+ }
+ rest = &rest[p.len()..];
+ } else if i == parts.len() - 1 {
+ return rest.ends_with(p);
+ } else if let Some(k) = rest.find(p) {
+ rest = &rest[k + p.len()..];
+ } else {
+ return false;
+ }
+ }
+ true
+}
+
+#[derive(Deserialize, Default, Clone)]
+#[serde(deny_unknown_fields)]
+pub struct NetCfg {
+ #[serde(default)]
+ pub join: Vec<JoinCfg>,
+ pub cost: Option<String>,
+ pub root: Option<String>,
+ pub decaps: Option<bool>,
+ pub priority: Option<i32>,
+ pub w: Option<f64>,
+ pub wneck: Option<f64>,
+ pub via_d: Option<f64>,
+ pub via_cost: Option<f64>,
+ pub via_cmult: Option<f64>,
+ pub bmult: Option<f64>,
+ pub turn: Option<f64>,
+ pub allow_via: Option<bool>,
+ pub max_expand: Option<i64>,
+ pub neck: Option<f64>,
+ pub neck_zone: Option<f64>,
+}
+
+/// A pad pair of the net routed first, with its own settings (e.g. AVDD pins joined inside
+/// a QFP's pad ring without vias).
+#[derive(Deserialize, Default, Clone)]
+#[serde(deny_unknown_fields)]
+pub struct JoinCfg {
+ pub a: String,
+ pub b: String,
+ pub cost: Option<String>,
+ pub w: Option<f64>,
+ pub wneck: Option<f64>,
+ pub allow_via: Option<bool>,
+}
+
+impl NetCfg {
+ /// Search settings: these where set, else the step's.
+ pub fn opts(&self, step: &NetOpts) -> NetOpts {
+ NetOpts {
+ w: self.w.or(step.w),
+ wneck: self.wneck.or(step.wneck),
+ via_d: self.via_d.or(step.via_d),
+ via_cost: self.via_cost.or(step.via_cost),
+ via_cmult: self.via_cmult.or(step.via_cmult),
+ bmult: self.bmult.or(step.bmult),
+ turn: self.turn.or(step.turn),
+ allow_via: self.allow_via.or(step.allow_via),
+ max_expand: self.max_expand.or(step.max_expand),
+ hweight: step.hweight,
+ margin: step.margin,
+ hug: step.hug,
+ neck: self.neck.or(step.neck),
+ neck_zone: self.neck_zone.or(step.neck_zone),
+ }
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Fixed {
+ pub name: String,
+ pub path: Option<String>,
+ #[serde(default)]
+ pub unmoved: bool,
+ #[serde(default)]
+ pub exclude: Vec<String>,
+ #[serde(default = "yes")]
+ pub protect: bool,
+ #[serde(default)]
+ pub done: bool,
+ #[serde(default)]
+ pub optional: bool,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct CostDef {
+ #[serde(default)]
+ pub zones: Vec<Zone>,
+ pub rudy: Option<Rudy>,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Zone {
+ pub layer: String,
+ pub fp: Option<String>,
+ pub rect: [f64; 4],
+ pub cost: f64,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Rudy {
+ #[serde(default = "f_layer")]
+ pub layer: String,
+ pub scale: f64,
+ pub max: f64,
+}
+
+fn f_layer() -> String {
+ "F".into()
+}
+
+#[derive(Deserialize, Default)]
+#[serde(deny_unknown_fields)]
+pub struct Step {
+ #[serde(rename = "do")]
+ pub kind: String,
+ pub label: Option<String>,
+ pub cost: Option<String>,
+ pub net: Option<String>,
+ pub nets: Option<Vec<String>>,
+ pub fp: Option<String>,
+ pub at: Option<Vec<[f64; 2]>>,
+ pub d: Option<f64>,
+ pub only: Option<Vec<String>>,
+ pub skip: Option<Vec<String>>,
+ pub exclude: Option<Vec<String>>,
+ pub root: Option<String>,
+ pub pads: Option<Vec<String>>,
+ pub a: Option<String>,
+ pub b: Option<String>,
+ pub pad: Option<String>,
+ pub rounds: Option<usize>,
+ pub radius: Option<f64>,
+ pub pitch: Option<f64>,
+ pub area: Option<[f64; 4]>,
+ pub w: Option<f64>,
+ pub wneck: Option<f64>,
+ pub via_d: Option<f64>,
+ pub via_cost: Option<f64>,
+ pub via_cmult: Option<f64>,
+ pub bmult: Option<f64>,
+ pub turn: Option<f64>,
+ pub allow_via: Option<bool>,
+ pub max_expand: Option<i64>,
+ pub hweight: Option<f64>,
+ pub margin: Option<f64>,
+ pub hug: Option<f64>,
+ /// negotiate (default 0) and cleanup (default 0.5): extra cost per step away from the
+ /// net's [[bundle]] partners
+ pub attract: Option<f64>,
+ /// necked step cost per mm of width given up (cleanup default 4, elsewhere 0)
+ pub neck: Option<f64>,
+ /// a track may neck to `wneck` within this distance (mm) of the pads it joins (default 1)
+ pub neck_zone: Option<f64>,
+ pub pres: Option<f64>,
+ pub pres_mult: Option<f64>,
+ pub hist: Option<f64>,
+ pub decaps: Option<bool>,
+ /// negotiate: route the plane nets' drops in the negotiation too
+ pub planes: Option<bool>,
+ /// pour: stitch islands to the rest of the pour with vias
+ pub fix: Option<bool>,
+}
+
+impl Step {
+ pub fn opts(&self) -> NetOpts {
+ NetOpts {
+ w: self.w,
+ wneck: self.wneck,
+ via_d: self.via_d,
+ via_cost: self.via_cost,
+ via_cmult: self.via_cmult,
+ bmult: self.bmult,
+ turn: self.turn,
+ allow_via: self.allow_via,
+ max_expand: self.max_expand,
+ hweight: self.hweight,
+ margin: self.margin,
+ hug: self.hug,
+ neck: self.neck,
+ neck_zone: self.neck_zone,
+ }
+ }
+
+ pub fn net(&self) -> Result<&str> {
+ self.net.as_deref().ok_or_else(|| anyhow!("step {}: `net` missing", self.kind))
+ }
+}
+
+pub fn pad_ref(s: &str) -> Result<PadRef> {
+ let Some((r, n)) = s.split_once(':') else { bail!("pad {s:?}: write REF:NUM") };
+ Ok((r.to_string(), n.to_string()))
+}
+
+pub fn pad_refs(v: &[String]) -> Result<Vec<PadRef>> {
+ v.iter().map(|s| pad_ref(s)).collect()
+}
+
+impl Config {
+ pub fn load(path: &str) -> Result<Config> {
+ use anyhow::Context;
+ let s = std::fs::read_to_string(path).with_context(|| path.to_string())?;
+ toml::from_str(&s).with_context(|| path.to_string())
+ }
+}
diff --git a/tools/router/src/geom.rs b/tools/router/src/geom.rs
new file mode 100644
index 0000000..f176e39
--- /dev/null
+++ b/tools/router/src/geom.rs
@@ -0,0 +1,281 @@
+//! 2-D geometry in mm: pad polygons, segments, exact distances.
+//!
+//! Point-to-segment distance follows GEOS (shapely), so the distance fields match the
+//! Python router's to the last bit wherever possible.
+
+pub type Pt = (f64, f64);
+
+#[derive(Clone, Debug)]
+pub struct Poly {
+ pub pts: Vec<Pt>,
+ pub bbox: [f64; 4],
+}
+
+impl Poly {
+ pub fn new(mut pts: Vec<Pt>) -> Poly {
+ if pts.len() > 1 && pts[0] == pts[pts.len() - 1] {
+ pts.pop();
+ }
+ let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
+ for &(x, y) in &pts {
+ b[0] = b[0].min(x);
+ b[1] = b[1].min(y);
+ b[2] = b[2].max(x);
+ b[3] = b[3].max(y);
+ }
+ Poly { pts, bbox: b }
+ }
+
+ pub fn edges(&self) -> impl Iterator<Item = (Pt, Pt)> + '_ {
+ let n = self.pts.len();
+ (0..n).map(move |i| (self.pts[i], self.pts[(i + 1) % n]))
+ }
+
+ /// Interior or boundary (GEOS RayCrossingCounter with a robust orientation test).
+ pub fn contains(&self, p: Pt) -> bool {
+ if p.0 < self.bbox[0] || p.0 > self.bbox[2] || p.1 < self.bbox[1] || p.1 > self.bbox[3] {
+ return false;
+ }
+ let mut crossings = 0;
+ for (a, b) in self.edges() {
+ if a.0 < p.0 && b.0 < p.0 {
+ continue;
+ }
+ if p == b {
+ return true;
+ }
+ if a.1 == p.1 && b.1 == p.1 {
+ if p.0 >= a.0.min(b.0) && p.0 <= a.0.max(b.0) {
+ return true;
+ }
+ continue;
+ }
+ if (a.1 > p.1 && b.1 <= p.1) || (b.1 > p.1 && a.1 <= p.1) {
+ let mut o = orientation(a, b, p);
+ if o == 0 {
+ return true;
+ }
+ if b.1 < a.1 {
+ o = -o;
+ }
+ if o > 0 {
+ crossings += 1;
+ }
+ }
+ }
+ crossings % 2 == 1
+ }
+
+ /// Distance from a point to the outline, from either side.
+ pub fn boundary_dist(&self, p: Pt) -> f64 {
+ self.edges().map(|(a, b)| point_seg(p, a, b)).fold(f64::INFINITY, f64::min)
+ }
+
+ /// Distance from a point, 0 inside (shapely's `distance`).
+ pub fn dist(&self, p: Pt) -> f64 {
+ if self.contains(p) {
+ return 0.0;
+ }
+ self.edges().map(|(a, b)| point_seg(p, a, b)).fold(f64::INFINITY, f64::min)
+ }
+
+ fn ring(&self) -> Vec<Pt> {
+ let mut r = self.pts.clone();
+ r.push(self.pts[0]);
+ r
+ }
+
+ /// Area as GEOS computes it (shapely's `area`), so equal pads sort alike.
+ pub fn area(&self) -> f64 {
+ let r = self.ring();
+ if r.len() < 3 {
+ return 0.0;
+ }
+ let x0 = r[0].0;
+ let mut sum = 0.0;
+ for i in 1..r.len() - 1 {
+ sum += (r[i].0 - x0) * (r[i - 1].1 - r[i + 1].1);
+ }
+ (sum / 2.0).abs()
+ }
+
+ /// Area centroid as GEOS computes it (shapely's `centroid`).
+ pub fn centroid(&self) -> Pt {
+ let r = self.ring();
+ let base = r[0];
+ let mut signed = 0.0;
+ for i in 0..r.len() - 1 {
+ signed += r[i].0 * r[i + 1].1 - r[i + 1].0 * r[i].1;
+ }
+ let sign = if signed > 0.0 { -1.0 } else { 1.0 }; // positive area for clockwise shells
+ let (mut cx, mut cy, mut a2) = (0.0, 0.0, 0.0);
+ for i in 0..r.len() - 1 {
+ let (p1, p2) = (r[i], r[i + 1]);
+ let area2 = (p1.0 - base.0) * (p2.1 - base.1) - (p2.0 - base.0) * (p1.1 - base.1);
+ cx += sign * area2 * (base.0 + p1.0 + p2.0);
+ cy += sign * area2 * (base.1 + p1.1 + p2.1);
+ a2 += sign * area2;
+ }
+ if a2 == 0.0 {
+ return base;
+ }
+ (cx / 3.0 / a2, cy / 3.0 / a2)
+ }
+
+ /// Shorter side of the minimum-area rotated rectangle (the pad's narrow width).
+ pub fn minor(&self) -> f64 {
+ let h = hull(&self.pts);
+ let n = h.len();
+ let mut best = (f64::INFINITY, 0.0);
+ for i in 0..n {
+ let (a, b) = (h[i], h[(i + 1) % n]);
+ let l = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
+ if l == 0.0 {
+ continue;
+ }
+ let (ux, uy) = ((b.0 - a.0) / l, (b.1 - a.1) / l);
+ let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
+ for &p in &h {
+ let u = (p.0 - a.0) * ux + (p.1 - a.1) * uy;
+ let v = -(p.0 - a.0) * uy + (p.1 - a.1) * ux;
+ u0 = u0.min(u);
+ u1 = u1.max(u);
+ v0 = v0.min(v);
+ v1 = v1.max(v);
+ }
+ let area = (u1 - u0) * (v1 - v0);
+ if area < best.0 {
+ best = (area, (u1 - u0).min(v1 - v0));
+ }
+ }
+ best.1
+ }
+}
+
+fn hull(pts: &[Pt]) -> Vec<Pt> {
+ let mut p = pts.to_vec();
+ p.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ p.dedup();
+ if p.len() < 3 {
+ return p;
+ }
+ let cross = |o: Pt, a: Pt, b: Pt| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0);
+ let mut h: Vec<Pt> = Vec::new();
+ for &q in p.iter().chain(p.iter().rev().skip(1)) {
+ while h.len() >= 2 && cross(h[h.len() - 2], h[h.len() - 1], q) <= 0.0 {
+ h.pop();
+ }
+ h.push(q);
+ }
+ h.pop();
+ h
+}
+
+// double-double arithmetic for the orientation sign (GEOS CGAlgorithmsDD)
+fn two_sum(a: f64, b: f64) -> (f64, f64) {
+ let s = a + b;
+ let bb = s - a;
+ (s, (a - (s - bb)) + (b - bb))
+}
+
+fn dd_sub(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
+ let (s, e) = two_sum(a.0, -b.0);
+ two_sum(s, e + a.1 - b.1)
+}
+
+fn dd_mul(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
+ let p = a.0 * b.0;
+ let e = a.0.mul_add(b.0, -p) + (a.0 * b.1 + a.1 * b.0);
+ two_sum(p, e)
+}
+
+/// Sign of the turn a -> b -> c: 1 left, -1 right, 0 collinear (robust).
+pub fn orientation(a: Pt, b: Pt, c: Pt) -> i32 {
+ let sign = |d: f64| (d > 0.0) as i32 - (d < 0.0) as i32;
+ let det_l = (a.0 - c.0) * (b.1 - c.1);
+ let det_r = (a.1 - c.1) * (b.0 - c.0);
+ let det = det_l - det_r;
+ let sum = if det_l > 0.0 && det_r > 0.0 {
+ det_l + det_r
+ } else if det_l < 0.0 && det_r < 0.0 {
+ -det_l - det_r
+ } else {
+ return sign(det);
+ };
+ if det.abs() >= 1e-15 * sum {
+ return sign(det);
+ }
+ let dx1 = two_sum(b.0, -a.0);
+ let dy1 = two_sum(b.1, -a.1);
+ let dx2 = two_sum(c.0, -b.0);
+ let dy2 = two_sum(c.1, -b.1);
+ let d = dd_sub(dd_mul(dx1, dy2), dd_mul(dy1, dx2));
+ sign(if d.0 != 0.0 { d.0 } else { d.1 })
+}
+
+/// GEOS `Distance::pointToSegment`.
+pub fn point_seg(p: Pt, a: Pt, b: Pt) -> f64 {
+ if a == b {
+ return ((p.0 - a.0).powi(2) + (p.1 - a.1).powi(2)).sqrt();
+ }
+ let len2 = (b.0 - a.0) * (b.0 - a.0) + (b.1 - a.1) * (b.1 - a.1);
+ let r = ((p.0 - a.0) * (b.0 - a.0) + (p.1 - a.1) * (b.1 - a.1)) / len2;
+ if r <= 0.0 {
+ return ((p.0 - a.0).powi(2) + (p.1 - a.1).powi(2)).sqrt();
+ }
+ if r >= 1.0 {
+ return ((p.0 - b.0).powi(2) + (p.1 - b.1).powi(2)).sqrt();
+ }
+ let s = ((a.1 - p.1) * (b.0 - a.0) - (a.0 - p.0) * (b.1 - a.1)) / len2;
+ s.abs() * len2.sqrt()
+}
+
+fn orient(a: Pt, b: Pt, c: Pt) -> f64 {
+ (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0)
+}
+
+fn on_seg(a: Pt, b: Pt, p: Pt) -> bool {
+ p.0 >= a.0.min(b.0) && p.0 <= a.0.max(b.0) && p.1 >= a.1.min(b.1) && p.1 <= a.1.max(b.1)
+}
+
+pub fn seg_intersect(a: Pt, b: Pt, c: Pt, d: Pt) -> bool {
+ let (o1, o2, o3, o4) = (orient(a, b, c), orient(a, b, d), orient(c, d, a), orient(c, d, b));
+ if ((o1 > 0.0 && o2 < 0.0) || (o1 < 0.0 && o2 > 0.0)) && ((o3 > 0.0 && o4 < 0.0) || (o3 < 0.0 && o4 > 0.0)) {
+ return true;
+ }
+ (o1 == 0.0 && on_seg(a, b, c)) || (o2 == 0.0 && on_seg(a, b, d)) || (o3 == 0.0 && on_seg(c, d, a)) || (o4 == 0.0 && on_seg(c, d, b))
+}
+
+pub fn seg_seg(a: Pt, b: Pt, c: Pt, d: Pt) -> f64 {
+ if seg_intersect(a, b, c, d) {
+ return 0.0;
+ }
+ point_seg(a, c, d).min(point_seg(b, c, d)).min(point_seg(c, a, b)).min(point_seg(d, a, b))
+}
+
+pub fn seg_poly(a: Pt, b: Pt, p: &Poly) -> f64 {
+ if p.contains(a) || p.contains(b) {
+ return 0.0;
+ }
+ p.edges().map(|(c, d)| seg_seg(a, b, c, d)).fold(f64::INFINITY, f64::min)
+}
+
+pub fn poly_poly(p: &Poly, q: &Poly) -> f64 {
+ if p.contains(q.pts[0]) || q.contains(p.pts[0]) {
+ return 0.0;
+ }
+ let mut m = f64::INFINITY;
+ for (a, b) in p.edges() {
+ for (c, d) in q.edges() {
+ m = m.min(seg_seg(a, b, c, d));
+ if m == 0.0 {
+ return 0.0;
+ }
+ }
+ }
+ m
+}
+
+pub fn bbox_gap(a: &[f64; 4], b: &[f64; 4], m: f64) -> bool {
+ a[0] - m > b[2] || a[2] + m < b[0] || a[1] - m > b[3] || a[3] + m < b[1]
+}
diff --git a/tools/router/src/io.rs b/tools/router/src/io.rs
new file mode 100644
index 0000000..be51147
--- /dev/null
+++ b/tools/router/src/io.rs
@@ -0,0 +1,145 @@
+//! JSON formats shared with the Python tools: board.json from tools/router/dump_board.py
+//! in, routes.json for tools/router/write_board.py and plot_routes.py out.
+
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, HashMap};
+
+#[derive(Deserialize, Serialize, Clone)]
+pub struct PadJson {
+ #[serde(rename = "ref")]
+ pub refdes: String,
+ pub num: String,
+ pub net: String,
+ pub x: f64,
+ pub y: f64,
+ pub drill: f64,
+ #[serde(default)]
+ pub npth: bool,
+ #[serde(rename = "F")]
+ pub f: Option<Vec<[f64; 2]>>,
+ #[serde(rename = "B")]
+ pub b: Option<Vec<[f64; 2]>>,
+}
+
+#[derive(Deserialize, Serialize, Clone)]
+pub struct FpJson {
+ pub x: f64,
+ pub y: f64,
+ pub rot: f64,
+ #[serde(default)]
+ pub value: String,
+}
+
+#[derive(Deserialize, Serialize, Clone)]
+pub struct ClassJson {
+ pub track: f64,
+ pub via: f64,
+}
+
+/// Footprint copper that is not a pad, on "F" or "B".
+#[derive(Deserialize, Serialize, Clone)]
+pub struct FpCopperJson {
+ #[serde(rename = "ref")]
+ pub refdes: String,
+ pub layer: String,
+ pub poly: Vec<[f64; 2]>,
+}
+
+/// A copper pour: net, layer ("F.Cu" / "B.Cu") and outline.
+#[derive(Deserialize, Serialize, Clone)]
+pub struct ZoneJson {
+ pub net: String,
+ pub layer: String,
+ pub pts: Vec<[f64; 2]>,
+}
+
+#[derive(Deserialize, Serialize, Clone)]
+pub struct TrackJson {
+ pub net: String,
+ pub layer: String,
+ pub x1: f64,
+ pub y1: f64,
+ pub x2: f64,
+ pub y2: f64,
+ pub w: f64,
+}
+
+#[derive(Deserialize, Serialize, Clone)]
+pub struct ViaJson {
+ pub net: String,
+ pub x: f64,
+ pub y: f64,
+ pub d: f64,
+ #[serde(default)]
+ pub drill: f64,
+}
+
+#[derive(Deserialize, Serialize, Clone)]
+pub struct BoardJson {
+ pub bounds: [f64; 4],
+ pub pads: Vec<PadJson>,
+ #[serde(default)]
+ pub fps: BTreeMap<String, FpJson>,
+ #[serde(default)]
+ pub netclass: HashMap<String, String>,
+ #[serde(default)]
+ pub classes: HashMap<String, ClassJson>,
+ #[serde(default)]
+ pub fpcopper: Vec<FpCopperJson>,
+ /// copper pours (not rule areas): net, layer, outline
+ #[serde(default)]
+ pub zones: Vec<ZoneJson>,
+ #[serde(default)]
+ pub keepouts: Vec<Vec<[f64; 2]>>,
+ /// Owning footprint of each keepout ("" for board rule areas); absent in old dumps.
+ #[serde(default)]
+ pub keepout_refs: Vec<String>,
+ #[serde(default)]
+ pub tracks: Vec<TrackJson>,
+ #[serde(default)]
+ pub vias: Vec<ViaJson>,
+}
+
+impl BoardJson {
+ pub fn load(path: &str) -> anyhow::Result<BoardJson> {
+ use anyhow::Context;
+ let s = std::fs::read_to_string(path).with_context(|| path.to_string())?;
+ serde_json::from_str(&s).with_context(|| path.to_string())
+ }
+}
+
+#[derive(Serialize)]
+pub struct RoutesJson {
+ pub segs: Vec<TrackJson>,
+ pub vias: Vec<ViaJson>,
+ pub failed: Vec<Vec<String>>,
+ pub log: Vec<serde_json::Value>,
+}
+
+#[derive(Deserialize)]
+pub struct PadNet {
+ #[serde(rename = "ref")]
+ pub refdes: String,
+ pub net: String,
+}
+
+/// Fixed copper: a board dump (tracks, vias, fps, pads) or just tracks and vias.
+#[derive(Deserialize)]
+pub struct CopperJson {
+ #[serde(default)]
+ pub tracks: Vec<TrackJson>,
+ #[serde(default)]
+ pub vias: Vec<ViaJson>,
+ #[serde(default)]
+ pub fps: BTreeMap<String, FpJson>,
+ #[serde(default)]
+ pub pads: Vec<PadNet>,
+}
+
+impl CopperJson {
+ pub fn load(path: &str) -> anyhow::Result<CopperJson> {
+ use anyhow::Context;
+ let s = std::fs::read_to_string(path).with_context(|| path.to_string())?;
+ serde_json::from_str(&s).with_context(|| path.to_string())
+ }
+}
diff --git a/tools/router/src/lib.rs b/tools/router/src/lib.rs
new file mode 100644
index 0000000..5156e0b
--- /dev/null
+++ b/tools/router/src/lib.rs
@@ -0,0 +1,15 @@
+//! Grid maze router for 2-layer KiCad boards (see knowledge/tooling/router.md).
+//!
+//! Reads board.json from tools/router/dump_board.py and the board's route.toml, writes
+//! routes.json for tools/router/write_board.py.
+
+pub mod astar;
+pub mod board;
+pub mod cleanup;
+pub mod config;
+pub mod geom;
+pub mod io;
+pub mod placement;
+pub mod pour;
+pub mod router;
+pub mod run;
diff --git a/tools/router/src/main.rs b/tools/router/src/main.rs
new file mode 100644
index 0000000..85802ce
--- /dev/null
+++ b/tools/router/src/main.rs
@@ -0,0 +1,107 @@
+//! router: grid maze router for 2-layer KiCad boards.
+//!
+//! router route BOARD.json ROUTE.toml OUT.json [--fixed NAME=FILE]... [--stop LABEL]
+//! router place BOARD.json PLACEMENT.json OUT.json
+//!
+//! `place` writes BOARD.json with the footprints moved to a placer result (ref -> [x, y, rot]),
+//! so a placement can be routed without KiCad; existing tracks and vias are left as they are.
+//! BOARD.json comes from tools/router/dump_board.py, OUT.json goes to
+//! tools/router/write_board.py. `--stop` ends after the step with that label (to look at
+//! partial results). Prints one summary line:
+//! "RESULT split=<nets in pieces> failed=<connections; a poured plane net's failed drops count
+//! only through islands> islands=<plane pad groups apart>
+//! vias=<n> length=<mm> bcu=<mm> neck=<mm narrower than the net width> score=<[rank]> time=<s>".
+
+use anyhow::{bail, Context, Result};
+use router::config::Config;
+use router::io::BoardJson;
+use router::placement;
+use router::run::Run;
+use std::collections::HashMap;
+use std::path::Path;
+use std::time::Instant;
+
+fn main() -> Result<()> {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ if args.len() == 4 && args[0] == "place" {
+ let mut d = BoardJson::load(&args[1])?;
+ placement::apply(&mut d, &placement::load(&args[2])?)?;
+ std::fs::write(&args[3], serde_json::to_string(&d)?).with_context(|| args[3].to_string())?;
+ return Ok(());
+ }
+ if args.len() < 4 || args[0] != "route" {
+ bail!("usage: router route BOARD.json ROUTE.toml OUT.json [--fixed NAME=FILE]... [--stop LABEL]\n router place BOARD.json PLACEMENT.json OUT.json");
+ }
+ let t0 = Instant::now();
+ let (board, toml, out) = (&args[1], &args[2], &args[3]);
+ let mut fixed = HashMap::new();
+ let mut stop = None;
+ let mut k = 4;
+ while k < args.len() {
+ match args[k].as_str() {
+ "--fixed" => {
+ let (n, f) = args.get(k + 1).and_then(|a| a.split_once('=')).context("--fixed NAME=FILE")?;
+ fixed.insert(n.to_string(), f.to_string());
+ k += 2;
+ }
+ "--stop" => {
+ stop = Some(args.get(k + 1).context("--stop LABEL")?.clone());
+ k += 2;
+ }
+ a => bail!("unknown argument {a}"),
+ }
+ }
+ let d = BoardJson::load(board)?;
+ let cfg = Config::load(toml)?;
+ let base = Path::new(toml).parent().unwrap_or(Path::new("."));
+ let mut run = Run::new(&d, &cfg, base, &fixed, true)?;
+ let t_setup = t0.elapsed().as_secs_f64();
+ for s in &cfg.step {
+ let t = Instant::now();
+ run.step(&cfg, s)?;
+ if std::env::var("ROUTER_TIMES").is_ok() {
+ eprintln!("{:>7.3} s {} {}", t.elapsed().as_secs_f64(), s.kind, s.nets.as_ref().map(|n| n.join(",")).or(s.net.clone()).unwrap_or_default());
+ }
+ if stop.is_some() && s.label == stop {
+ println!("stopped after {}", s.label.as_deref().unwrap_or(""));
+ break;
+ }
+ }
+ let sum = run.summary(&cfg, t0.elapsed().as_secs_f64());
+ let r = &run.r;
+ let incomplete: Vec<_> = r
+ .log
+ .iter()
+ .filter(|l| {
+ let a = l.as_array().unwrap();
+ (a.len() > 4 && a[1] == "pads" && a[4].as_i64() > Some(0)) || (a.len() > 2 && a[1] == "components" && a[2].as_i64() > Some(1))
+ })
+ .collect();
+ println!("incomplete: {incomplete:?}");
+ println!("failed: {:?}", r.failed);
+ let res = r.result();
+ std::fs::write(out, serde_json::to_string(&res)?).with_context(|| out.to_string())?;
+ let len = |l: Option<&str>| -> f64 { res.segs.iter().filter(|s| l.is_none_or(|l| s.layer == l)).map(|s| (s.x2 - s.x1).hypot(s.y2 - s.y1)).sum() };
+ let split = r.split_nets(&r.plane_nets);
+ println!(
+ "segs {} vias {} B.Cu {:.1} mm, setup {:.2} s, total {:.2} s",
+ res.segs.len(),
+ res.vias.len(),
+ len(Some("B.Cu")),
+ t_setup,
+ t0.elapsed().as_secs_f64()
+ );
+ println!(
+ "RESULT split={} failed={} islands={} vias={} length={:.1} bcu={:.1} neck={:.1} score={:.1} time={:.1}",
+ split.len(),
+ sum.failed,
+ sum.islands,
+ res.vias.len(),
+ len(None),
+ len(Some("B.Cu")),
+ sum.neck,
+ sum.score,
+ t0.elapsed().as_secs_f64()
+ );
+ Ok(())
+}
diff --git a/tools/router/src/placement.rs b/tools/router/src/placement.rs
new file mode 100644
index 0000000..9409742
--- /dev/null
+++ b/tools/router/src/placement.rs
@@ -0,0 +1,99 @@
+//! Move footprints of a board.json to a placer result without KiCad.
+//!
+//! Placement files are ref -> [x, y, rotation in degrees], at the top level or under
+//! "placement" (tools/placer). KiCad's y axis points down and its angles turn counter-clockwise
+//! on screen, so a footprint-local point (u, v) lies at
+//! (x + u cos a + v sin a, y - u sin a + v cos a) for orientation a; moving from pose
+//! (x0, y0, a0) to (x1, y1, a1) is that rotation by a1 - a0 about the old origin, then the shift.
+//!
+//! Pads, the footprint's own copper and its rule areas (via `keepout_refs`) move with it.
+//! `tracks` and `vias` stay where they are: the old copper belongs to the old placement.
+//! Footprints on the bottom side are not handled.
+
+use crate::io::BoardJson;
+use anyhow::{bail, Context, Result};
+use std::collections::BTreeMap;
+
+/// Reads a placement file.
+pub fn load(path: &str) -> Result<BTreeMap<String, [f64; 3]>> {
+ let s = std::fs::read_to_string(path).with_context(|| path.to_string())?;
+ let v: serde_json::Value = serde_json::from_str(&s).with_context(|| path.to_string())?;
+ let v = v.get("placement").cloned().unwrap_or(v);
+ serde_json::from_value(v).with_context(|| format!("{path}: expected ref -> [x, y, rot]"))
+}
+
+/// Rigid transform: rotate by an angle (KiCad sense) about (ox, oy), then shift to (nx, ny).
+struct Pose {
+ ox: f64,
+ oy: f64,
+ nx: f64,
+ ny: f64,
+ c: f64,
+ s: f64,
+}
+
+impl Pose {
+ fn new(from: (f64, f64, f64), to: [f64; 3]) -> Pose {
+ let a = (to[2] - from.2).rem_euclid(360.0);
+ // exact values at right angles, so the common rotations add no noise
+ let (s, c) = match a {
+ 0.0 => (0.0, 1.0),
+ 90.0 => (1.0, 0.0),
+ 180.0 => (0.0, -1.0),
+ 270.0 => (-1.0, 0.0),
+ _ => a.to_radians().sin_cos(),
+ };
+ Pose { ox: from.0, oy: from.1, nx: to[0], ny: to[1], c, s }
+ }
+
+ fn pt(&self, x: f64, y: f64) -> (f64, f64) {
+ let (u, v) = (x - self.ox, y - self.oy);
+ (self.nx + u * self.c + v * self.s, self.ny - u * self.s + v * self.c)
+ }
+
+ fn poly(&self, p: &mut [[f64; 2]]) {
+ for q in p {
+ let (x, y) = self.pt(q[0], q[1]);
+ *q = [x, y];
+ }
+ }
+}
+
+/// Moves each listed footprint; errors on unknown references and on bottom-side parts.
+pub fn apply(d: &mut BoardJson, placement: &BTreeMap<String, [f64; 3]>) -> Result<()> {
+ let mut poses = BTreeMap::new();
+ for (r, to) in placement {
+ let f = d.fps.get_mut(r.as_str()).with_context(|| format!("{r} is not on the board"))?;
+ poses.insert(r.as_str(), Pose::new((f.x, f.y, f.rot), *to));
+ (f.x, f.y, f.rot) = (to[0], to[1], to[2]);
+ }
+ for p in &mut d.pads {
+ let Some(pose) = poses.get(p.refdes.as_str()) else { continue };
+ if !p.npth && p.f.is_none() && p.b.is_some() {
+ bail!("{} has a bottom-side pad; flipped footprints are not supported", p.refdes);
+ }
+ (p.x, p.y) = pose.pt(p.x, p.y);
+ for poly in [&mut p.f, &mut p.b].into_iter().flatten() {
+ pose.poly(poly);
+ }
+ }
+ for c in &mut d.fpcopper {
+ if let Some(pose) = poses.get(c.refdes.as_str()) {
+ pose.poly(&mut c.poly);
+ }
+ }
+ if d.keepout_refs.is_empty() {
+ if !d.keepouts.is_empty() {
+ eprintln!("warning: board.json has no keepout_refs (old dump): footprint keep-outs are not moved");
+ }
+ } else if d.keepout_refs.len() != d.keepouts.len() {
+ bail!("keepout_refs and keepouts differ in length");
+ } else {
+ for (k, r) in d.keepouts.iter_mut().zip(&d.keepout_refs) {
+ if let Some(pose) = poses.get(r.as_str()) {
+ pose.poly(k);
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/tools/router/src/pour.rs b/tools/router/src/pour.rs
new file mode 100644
index 0000000..b7aaab4
--- /dev/null
+++ b/tools/router/src/pour.rs
@@ -0,0 +1,224 @@
+//! Pour connectivity of the plane nets: where each copper pour of the board.json (`zones`)
+//! will fill, which pieces of the net's copper the fill joins, and stitching vias for islands.
+//!
+//! A cell fills when it lies in the pour outline and the nearest copper of another net (or the
+//! board edge, keep-out, hole) is at least FILL_R away: the zone clearance plus half KiCad's
+//! minimum fill width, so a neck too thin to fill does not count as a connection. Fill cells
+//! form islands (4-connected, per layer). The net's copper joins an island where its tracks
+//! and vias touch it and where a pad is within THERMAL_R (thermal gap plus spoke). Pieces of
+//! copper with pads that end up apart are what KiCad's DRC reports as unconnected.
+
+use crate::board::{via_drill, SearchOpts, CLR, HOLE_HOLE, M};
+use crate::router::Router;
+use serde_json::json;
+
+/// Fill needs this much room to other nets' copper (mm): clearance 0.2 + half of 0.25.
+const FILL_R: f32 = 0.325;
+/// A pad joins fill within this distance (mm): thermal gap 0.5 plus a little spoke.
+const THERMAL_R: f64 = 0.6;
+
+struct Map {
+ /// island of each state (cell * 2 + layer), -1 where nothing fills
+ lab: Vec<i32>,
+ nisl: usize,
+ /// the net's copper pieces (item ids)
+ pieces: Vec<Vec<usize>>,
+ /// union-find over islands (0..nisl) and pieces (nisl..)
+ par: Vec<usize>,
+}
+
+impl Map {
+ fn find(&mut self, mut a: usize) -> usize {
+ while self.par[a] != a {
+ self.par[a] = self.par[self.par[a]];
+ a = self.par[a];
+ }
+ a
+ }
+
+ fn union(&mut self, a: usize, b: usize) {
+ let (a, b) = (self.find(a), self.find(b));
+ if a != b {
+ self.par[a] = b;
+ }
+ }
+}
+
+impl Router {
+ fn pour_map(&self, net: i32) -> Option<Map> {
+ let b = &self.b;
+ let zones: Vec<_> = self.zones.iter().filter(|z| z.0 == net).collect();
+ if zones.is_empty() {
+ return None;
+ }
+ let mut fill = vec![false; 2 * b.n];
+ for (_, l, poly) in &zones {
+ let (i0, j0, i1, j1) = b.window(&poly.bbox, 0.0);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let s = (j * b.nx + i) * 2 + l;
+ if !fill[s] && b.f[s].fdist(net) >= FILL_R && poly.contains(b.cell_xy(i, j)) {
+ fill[s] = true;
+ }
+ }
+ }
+ }
+ let mut lab = vec![-1i32; 2 * b.n];
+ let mut nisl = 0;
+ let mut stack = Vec::new();
+ for s0 in 0..2 * b.n {
+ if !fill[s0] || lab[s0] >= 0 {
+ continue;
+ }
+ lab[s0] = nisl as i32;
+ stack.push(s0);
+ while let Some(s) = stack.pop() {
+ let (c, l) = (s >> 1, s & 1);
+ let (i, j) = (c % b.nx, c / b.nx);
+ let mut nb = [usize::MAX; 4];
+ if i > 0 {
+ nb[0] = c - 1;
+ }
+ if i + 1 < b.nx {
+ nb[1] = c + 1;
+ }
+ if j > 0 {
+ nb[2] = c - b.nx;
+ }
+ if j + 1 < b.ny {
+ nb[3] = c + b.nx;
+ }
+ for q in nb.into_iter().filter(|&q| q != usize::MAX) {
+ let t = q * 2 + l;
+ if fill[t] && lab[t] < 0 {
+ lab[t] = nisl as i32;
+ stack.push(t);
+ }
+ }
+ }
+ nisl += 1;
+ }
+ let pieces = self.components(&self.net_items_all(net));
+ let mut m = Map { lab, nisl, par: (0..nisl + pieces.len()).collect(), pieces };
+ for p in 0..m.pieces.len() {
+ for id in m.pieces[p].clone() {
+ let it = &b.items[id];
+ let r = if matches!(it.shape, crate::board::Shape::Pad(_)) { THERMAL_R } else { crate::board::RES };
+ let (i0, j0, i1, j1) = b.window(&it.bbox, r);
+ for j in j0..=j1 {
+ for i in i0..=i1 {
+ let (x, y) = b.cell_xy(i, j);
+ for l in 0..2 {
+ let s = (j * b.nx + i) * 2 + l;
+ if it.on(l) && m.lab[s] >= 0 && (b.item_dist(it, x, y) as f64) <= r {
+ let isl = m.lab[s] as usize;
+ m.union(isl, nisl + p);
+ }
+ }
+ }
+ }
+ }
+ }
+ Some(m)
+ }
+
+ /// Roots of the pieces that hold pads, with their pad counts (most pads first).
+ fn pad_groups(&self, m: &mut Map) -> Vec<(usize, usize)> {
+ let mut cnt: std::collections::BTreeMap<usize, usize> = std::collections::BTreeMap::new();
+ for p in 0..m.pieces.len() {
+ let pads = m.pieces[p].iter().filter(|&&id| matches!(self.b.items[id].shape, crate::board::Shape::Pad(_))).count();
+ if pads > 0 {
+ let r = m.find(m.nisl + p);
+ *cnt.entry(r).or_default() += pads;
+ }
+ }
+ let mut v: Vec<(usize, usize)> = cnt.into_iter().collect();
+ v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
+ v
+ }
+
+ /// Groups of a plane net's pads that its pours and copper leave apart, beyond the first
+ /// (0: connected; also 0 when the net has no pour in the board.json).
+ pub fn pour_splits(&self, name: &str) -> usize {
+ let Some(&net) = self.b.netid.get(name) else { return 0 };
+ match self.pour_map(net) {
+ Some(mut m) => self.pad_groups(&mut m).len().saturating_sub(1),
+ None => 0,
+ }
+ }
+
+ /// Join pour islands that hold pads to the main group: a via of diameter d where one layer
+ /// belongs to the island and the other to the main group, else a track (and vias) from the
+ /// group's copper to the main group's fill. Returns (groups left apart, joints added).
+ pub fn pour_fix(&mut self, name: &str, d: f64) -> (usize, usize) {
+ let Some(&net) = self.b.netid.get(name) else { return (0, 0) };
+ let mut added = 0;
+ loop {
+ let Some(mut m) = self.pour_map(net) else { return (0, 0) };
+ let groups = self.pad_groups(&mut m);
+ if groups.len() <= 1 {
+ self.log.push(json!([name, "pour groups apart", 0, "joints added", added]));
+ return (0, added);
+ }
+ let main = groups[0].0;
+ let b = &self.b;
+ let (r_via, r_vpad) = ((d / 2.0 + CLR + M) as f32, (d / 2.0 + 0.05) as f32);
+ let r_hole = (via_drill(d) / 2.0 + HOLE_HOLE + M) as f32;
+ let mut spot = None;
+ 'groups: for &(g, _) in &groups[1..] {
+ for c in 0..b.n {
+ let (s0, s1) = (c * 2, c * 2 + 1);
+ if m.lab[s0] < 0 || m.lab[s1] < 0 {
+ continue;
+ }
+ let (r0, r1) = (m.find(m.lab[s0] as usize), m.find(m.lab[s1] as usize));
+ if !((r0 == g && r1 == main) || (r0 == main && r1 == g)) {
+ continue;
+ }
+ if b.f[s0].fdist(net) >= r_via && b.f[s1].fdist(net) >= r_via && b.padd[s0] >= r_vpad && b.padd[s1] >= r_vpad && b.hole[c] >= r_hole {
+ spot = Some(b.cell_xy(c % b.nx, c / b.nx));
+ break 'groups;
+ }
+ }
+ }
+ if let Some(p) = spot {
+ let items = self.b.commit(net, &[], &[p], d);
+ self.net_items[net as usize].extend_from_slice(&items);
+ added += 1;
+ continue;
+ }
+ // no via joins an island to the main group: route a group's copper to the main
+ // group's fill (a drop that ended in a pocket no pour reaches)
+ let roots: Vec<usize> = (0..m.nisl).map(|i| m.find(i)).collect();
+ let tgt: Vec<i32> = (0..2 * b.n).filter(|&s| m.lab[s] >= 0 && roots[m.lab[s] as usize] == main).map(|s| s as i32).collect();
+ let mut joined = false;
+ for &(g, _) in &groups[1..] {
+ let mine: Vec<usize> = (0..m.pieces.len()).filter(|&p| m.find(m.nisl + p) == g).collect();
+ let src: Vec<usize> = mine.iter().flat_map(|&p| m.pieces[p].clone()).collect();
+ let so = SearchOpts { hweight: 0.0, ..Default::default() };
+ if self.join_to(net, &src, &tgt, d, &so) {
+ joined = true;
+ added += 1;
+ break;
+ }
+ }
+ if !joined {
+ // name the pads of the groups left apart
+ let mut apart = Vec::new();
+ for p in 0..m.pieces.len() {
+ let r = m.find(m.nisl + p);
+ if r == main {
+ continue;
+ }
+ for &id in &m.pieces[p] {
+ if let crate::board::Shape::Pad(k) = self.b.items[id].shape {
+ apart.push(format!("{}:{}", self.b.pads[k].refdes, self.b.pads[k].num));
+ }
+ }
+ }
+ self.log.push(json!([name, "pour groups apart", groups.len() - 1, "joints added", added, "pads apart", apart]));
+ return (groups.len() - 1, added);
+ }
+ }
+ }
+}
diff --git a/tools/router/src/router.rs b/tools/router/src/router.rs
new file mode 100644
index 0000000..e829fe8
--- /dev/null
+++ b/tools/router/src/router.rs
@@ -0,0 +1,1268 @@
+//! Routing strategies on top of the board fields (port of an earlier Python router):
+//! plane drops, component joining, pad pairs, decoupling caps, rip-up and reroute.
+
+use crate::board::{Board, Item, Owner, SearchOpts, Seg, Shape, CLR, CU_STEP, M, RDIAG, RES};
+use crate::geom::{bbox_gap, point_seg, poly_poly, seg_poly, seg_seg, Poly, Pt};
+use crate::io::{BoardJson, FpJson, RoutesJson, TrackJson, ViaJson};
+use serde_json::{json, Value};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+
+/// Per-connection settings; unset fields take the net class or the search defaults.
+#[derive(Clone, Debug, Default)]
+pub struct NetOpts {
+ pub w: Option<f64>,
+ pub wneck: Option<f64>,
+ pub via_d: Option<f64>,
+ pub via_cost: Option<f64>,
+ pub via_cmult: Option<f64>,
+ pub bmult: Option<f64>,
+ pub turn: Option<f64>,
+ pub allow_via: Option<bool>,
+ pub max_expand: Option<i64>,
+ pub hweight: Option<f64>,
+ pub margin: Option<f64>,
+ pub hug: Option<f64>,
+ pub neck: Option<f64>,
+ pub neck_zone: Option<f64>,
+}
+
+impl NetOpts {
+ pub fn search(&self) -> SearchOpts {
+ let d = SearchOpts::default();
+ SearchOpts {
+ via_cost: self.via_cost.unwrap_or(d.via_cost),
+ via_cmult: self.via_cmult.unwrap_or(d.via_cmult),
+ bmult: self.bmult.unwrap_or(d.bmult),
+ turn: self.turn.unwrap_or(d.turn),
+ allow_via: self.allow_via.unwrap_or(d.allow_via),
+ layer_mask: d.layer_mask,
+ max_expand: self.max_expand.unwrap_or(d.max_expand),
+ hweight: self.hweight.unwrap_or(d.hweight),
+ margin: self.margin.unwrap_or(d.margin),
+ hug: self.hug.unwrap_or(d.hug),
+ neck: self.neck.unwrap_or(d.neck),
+ neck_zone: self.neck_zone.unwrap_or(d.neck_zone),
+ }
+ }
+}
+
+pub type PadRef = (String, String);
+
+/// Search margin (mm) for a net rerouted whole after being stuck in conflict.
+const WIDE_MARGIN: f64 = 5.0;
+
+struct Redo {
+ cost: Option<String>,
+ pads: Option<Vec<PadRef>>,
+ root: Option<PadRef>,
+ opts: NetOpts,
+}
+
+pub struct Router {
+ pub b: Board,
+ netclass: HashMap<String, String>,
+ width: HashMap<String, f64>,
+ via: HashMap<String, f64>,
+ pub plane_nets: Vec<String>,
+ pub fps: BTreeMap<String, FpJson>,
+ pub log: Vec<Value>,
+ pub net_items: Vec<Vec<usize>>,
+ pub failed: Vec<Vec<String>>,
+ pub pads_by_net: Vec<Vec<usize>>,
+ registry: HashMap<String, Vec<Redo>>,
+ /// negotiation: each net's search paths (states, neck flags, radii) for conflict checks
+ paths: Vec<Vec<PathRec>>,
+ /// the nets of the last negotiation, for the cleanup
+ pub(crate) jobs: Vec<Job>,
+ /// print progress notes (off when many boards are routed in parallel)
+ pub verbose: bool,
+ /// copper pours: net, layer, outline
+ pub zones: Vec<(i32, usize, crate::geom::Poly)>,
+ /// route.toml [[bundle]]s: nets the cleanup draws together (pairs, buses)
+ pub bundles: Vec<Vec<i32>>,
+ /// nets whose copper the output leaves out (route.toml [[escape]] lines)
+ pub hidden: BTreeSet<i32>,
+ /// track width of [[escape]] nets where the escape sets one (instead of their class's)
+ pub escape_w: HashMap<String, f64>,
+}
+
+struct PathRec {
+ items: Vec<usize>,
+ states: Vec<i32>,
+ neck: Vec<u8>,
+ r_nom: f32,
+ r_neck: f32,
+ r_via: f32,
+}
+
+/// One net of a negotiated routing.
+#[derive(Clone, Debug)]
+pub struct Job {
+ pub name: String,
+ pub cost: String,
+ pub root: Option<PadRef>,
+ pub decaps: bool,
+ pub priority: i32,
+ pub opts: NetOpts,
+ /// a plane net: each SMD pad drops to a via (opts: w 0.4, wneck 0.25, via_cost 12,
+ /// via_cmult 2 unless set)
+ pub plane: bool,
+ /// pad pairs routed first: (a, b, cost map, settings)
+ pub joins: Vec<(PadRef, PadRef, String, NetOpts)>,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Negotiation {
+ pub rounds: usize,
+ pub pres: f32,
+ pub pres_mult: f32,
+ pub hist: f32,
+ /// extra cost per step away from the net's [[bundle]] partners (0: off)
+ pub attract: f64,
+}
+
+pub fn mst(pts: &[Pt]) -> Vec<(Pt, Pt)> {
+ let n = pts.len();
+ if n < 2 {
+ return Vec::new();
+ }
+ let mut in_t = vec![false; n];
+ in_t[0] = true;
+ let mut dist: Vec<f64> = pts.iter().map(|p| (p.0 - pts[0].0).hypot(p.1 - pts[0].1)).collect();
+ let mut par = vec![0; n];
+ let mut edges = Vec::new();
+ for _ in 0..n - 1 {
+ let mut k = usize::MAX;
+ for i in 0..n {
+ if !in_t[i] && (k == usize::MAX || dist[i] < dist[k]) {
+ k = i;
+ }
+ }
+ in_t[k] = true;
+ edges.push((pts[par[k]], pts[k]));
+ for i in 0..n {
+ if !in_t[i] {
+ let d = (pts[i].0 - pts[k].0).hypot(pts[i].1 - pts[k].1);
+ if d < dist[i] {
+ dist[i] = d;
+ par[i] = k;
+ }
+ }
+ }
+ }
+ edges
+}
+
+/// Capacitance in uF from a value such as "100n" or "4.7uF" (0 if unreadable).
+fn cap_value_uf(v: &str) -> f64 {
+ let s = v.trim_start();
+ let end = s.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(s.len());
+ let Ok(x) = s[..end].parse::<f64>() else { return 0.0 };
+ let m = match s[end..].trim_start().chars().next() {
+ Some('p') => 1e-6,
+ Some('n') => 1e-3,
+ Some('u') | Some('µ') => 1.0,
+ Some('m') => 1e3,
+ _ => 1.0,
+ };
+ x * m
+}
+
+impl Router {
+ pub fn new(d: &BoardJson, plane_nets: &[String], area: Vec<Poly>, area_margin: f64) -> Router {
+ let b = Board::new(d, plane_nets, area, area_margin);
+ let mut width: HashMap<String, f64> = HashMap::from([("Default".to_string(), 0.2)]);
+ let mut via = HashMap::new();
+ for (k, c) in &d.classes {
+ width.insert(k.clone(), c.track);
+ if c.via != 0.6 {
+ via.insert(k.clone(), c.via);
+ }
+ }
+ let nn = b.netnames.len();
+ let mut pads_by_net = vec![Vec::new(); nn];
+ for (k, p) in b.pads.iter().enumerate() {
+ if p.net >= 0 {
+ pads_by_net[p.net as usize].push(k);
+ }
+ }
+ let zones = d
+ .zones
+ .iter()
+ .filter_map(|z| {
+ let net = *b.netid.get(&z.net)?;
+ let l = if z.layer == "B.Cu" { 1 } else { 0 };
+ Some((net, l, crate::geom::Poly::new(z.pts.iter().map(|p| (p[0], p[1])).collect())))
+ })
+ .collect();
+ Router {
+ zones,
+ b,
+ netclass: d.netclass.clone(),
+ width,
+ via,
+ plane_nets: plane_nets.to_vec(),
+ fps: d.fps.clone(),
+ log: Vec::new(),
+ net_items: vec![Vec::new(); nn],
+ failed: Vec::new(),
+ pads_by_net,
+ registry: HashMap::new(),
+ paths: (0..nn).map(|_| Vec::new()).collect(),
+ jobs: Vec::new(),
+ verbose: true,
+ bundles: Vec::new(),
+ hidden: BTreeSet::new(),
+ escape_w: HashMap::new(),
+ }
+ }
+
+ pub fn nid(&self, name: &str) -> i32 {
+ *self.b.netid.get(name).unwrap_or_else(|| panic!("no net {name}"))
+ }
+
+ fn nets(&self) -> impl Iterator<Item = i32> {
+ 1..self.b.netnames.len() as i32
+ }
+
+ /// A net's track width unless a step or [nets.NAME] sets one: its [[escape]] width, else its
+ /// class's.
+ fn default_w(&self, name: &str, class: &str) -> f64 {
+ self.escape_w.get(name).copied().unwrap_or_else(|| *self.width.get(class).unwrap_or(&0.2))
+ }
+
+ /// Track width, neck width and via size for a net (class defaults, as pipeline.connect).
+ pub(crate) fn widths(&self, name: &str, o: &NetOpts) -> (f64, f64, f64) {
+ let c = self.netclass.get(name).map(String::as_str).unwrap_or("Default");
+ let w = o.w.unwrap_or_else(|| self.default_w(name, c));
+ let wneck = o.wneck.unwrap_or(if w > 0.2 { 0.2 } else { 0.0 });
+ let via_d = o.via_d.unwrap_or_else(|| *self.via.get(c).unwrap_or(&0.6));
+ (w, wneck, via_d)
+ }
+
+ /// Failed connections that leave the board incomplete: those of nets still in pieces, and
+ /// drops of plane nets without a pour. A net that ended whole by another path is complete
+ /// (a failed join), and a poured plane net is judged by the pour check (`islands`).
+ pub fn failed_count(&self) -> usize {
+ let split = self.split_nets(&self.plane_nets);
+ let poured = |n: &str| self.zones.iter().any(|z| self.b.netname(z.0) == n);
+ self.failed
+ .iter()
+ .filter(|f| if self.plane_nets.contains(&f[0]) { !poured(&f[0]) } else { split.contains(&f[0]) })
+ .count()
+ }
+
+ /// Track and neck width of a job's net (plane drops: 0.4 / 0.25 unless set).
+ pub(crate) fn job_widths(&self, j: &Job) -> (f64, f64) {
+ if j.plane {
+ (j.opts.w.unwrap_or(0.4), j.opts.wneck.unwrap_or(0.25))
+ } else {
+ let (w, wn, _) = self.widths(&j.name, &j.opts);
+ (w, wn)
+ }
+ }
+
+ /// Track length (mm) narrower than its net's width, outside the net's pads (stubs into a
+ /// small pad are not counted). Plane nets are left out.
+ pub fn necked_mm(&self) -> f64 {
+ self.nets().filter(|&n| !self.plane_nets.iter().any(|p| p == self.b.netname(n))).map(|n| self.net_necked_mm(n)).sum()
+ }
+
+ /// necked_mm of one net.
+ pub(crate) fn net_necked_mm(&self, net: i32) -> f64 {
+ let name = self.b.netname(net);
+ let w = match self.jobs.iter().find(|j| j.name == name) {
+ Some(j) => self.job_widths(j).0,
+ None => self.widths(name, &NetOpts::default()).0,
+ };
+ let mut total = 0.0;
+ for &id in &self.net_items[net as usize] {
+ let it = &self.b.items[id];
+ let Shape::Seg(a, c) = it.shape else { continue };
+ if it.w >= w - 1e-9 || !self.b.alive[id] {
+ continue;
+ }
+ let mid = ((a.0 + c.0) / 2.0, (a.1 + c.1) / 2.0);
+ if self.pads_by_net[net as usize].iter().any(|&k| self.b.pads[k].poly.contains(mid)) {
+ continue;
+ }
+ total += (a.0 - c.0).hypot(a.1 - c.1);
+ }
+ total
+ }
+
+ pub fn set_cost(&mut self, name: &str) {
+ assert!(self.b.costs.contains_key(name), "no cost map {name}");
+ self.b.cost = name.to_string();
+ }
+
+ pub fn pad_item(&self, net: i32, r: &PadRef) -> usize {
+ self.pads_by_net[net as usize]
+ .iter()
+ .map(|&k| &self.b.pads[k])
+ .find(|p| p.refdes == r.0 && p.num == r.1)
+ .unwrap_or_else(|| panic!("no pad {}:{} on {}", r.0, r.1, self.b.netname(net)))
+ .item
+ }
+
+ // ----- congestion estimate (RUDY over MST edges of signal nets) -----
+ pub fn build_rudy(&self) -> Vec<f32> {
+ let b = &self.b;
+ let mut r = vec![0f32; b.n];
+ for net in self.nets() {
+ let name = b.netname(net);
+ if self.plane_nets.iter().any(|p| p == name) {
+ continue;
+ }
+ let pts: Vec<Pt> = self.pads_by_net[net as usize].iter().map(|&k| (b.pads[k].x, b.pads[k].y)).collect();
+ for (a, c) in mst(&pts) {
+ let (x0, x1) = (a.0.min(c.0) - 0.4, a.0.max(c.0) + 0.4);
+ let (y0, y1) = (a.1.min(c.1) - 0.4, a.1.max(c.1) + 0.4);
+ let dens = (((x1 - x0) + (y1 - y0)) / ((x1 - x0) * (y1 - y0)) * 0.25) as f32;
+ let (i0, j0) = b.xy_cell(x0, y0);
+ let (i1, j1) = b.xy_cell(x1, y1);
+ for j in j0.max(0)..=j1.min(b.ny as i64 - 1) {
+ for i in i0.max(0)..=i1.min(b.nx as i64 - 1) {
+ r[j as usize * b.nx + i as usize] += dens;
+ }
+ }
+ }
+ }
+ r
+ }
+
+ // ----- geometry helpers -----
+ fn item_xy_dist(&self, id: usize, xy: Pt) -> f32 {
+ self.b.item_dist(&self.b.items[id], xy.0, xy.1)
+ }
+
+ /// Distance between two items' copper (negative where they overlap).
+ pub(crate) fn item_item(&self, a: usize, c: usize) -> f64 {
+ let (ia, ic) = (&self.b.items[a], &self.b.items[c]);
+ let pads = &self.b.pads;
+ match (ia.shape, ic.shape) {
+ (Shape::Pad(p), Shape::Pad(q)) => poly_poly(&pads[p].poly, &pads[q].poly),
+ (Shape::Pad(p), Shape::Seg(s, e)) | (Shape::Seg(s, e), Shape::Pad(p)) => {
+ let w = if let Shape::Seg(..) = ia.shape { ia.w } else { ic.w };
+ seg_poly(s, e, &pads[p].poly) - w / 2.0
+ }
+ (Shape::Pad(p), Shape::Via(v)) | (Shape::Via(v), Shape::Pad(p)) => {
+ let w = if let Shape::Via(..) = ia.shape { ia.w } else { ic.w };
+ pads[p].poly.dist(v) - w / 2.0
+ }
+ (Shape::Seg(s, e), Shape::Seg(t, f)) => seg_seg(s, e, t, f) - ia.w / 2.0 - ic.w / 2.0,
+ (Shape::Seg(s, e), Shape::Via(v)) | (Shape::Via(v), Shape::Seg(s, e)) => point_seg(v, s, e) - ia.w / 2.0 - ic.w / 2.0,
+ (Shape::Via(v), Shape::Via(u)) => (v.0 - u.0).hypot(v.1 - u.1) - ia.w / 2.0 - ic.w / 2.0,
+ // footprint copper: its sample points against the other item
+ (Shape::Cu(k), _) => self.b.cu[k].iter().map(|p| self.b.item_dist(ic, p.0, p.1) as f64).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0,
+ (_, Shape::Cu(k)) => self.b.cu[k].iter().map(|p| self.b.item_dist(ia, p.0, p.1) as f64).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0,
+ }
+ }
+
+ /// Connected pieces of copper, in order of their first item.
+ pub fn components(&self, ids: &[usize]) -> Vec<Vec<usize>> {
+ let n = ids.len();
+ let mut par: Vec<usize> = (0..n).collect();
+ fn f(par: &mut [usize], mut a: usize) -> usize {
+ while par[a] != a {
+ par[a] = par[par[a]];
+ a = par[a];
+ }
+ a
+ }
+ for i in 0..n {
+ let ii = &self.b.items[ids[i]];
+ for j in i + 1..n {
+ let ij = &self.b.items[ids[j]];
+ if ii.layers & ij.layers == 0 || bbox_gap(&ii.bbox, &ij.bbox, 1e-4) {
+ continue;
+ }
+ if self.item_item(ids[i], ids[j]) <= 1e-4 {
+ let (a, c) = (f(&mut par, i), f(&mut par, j));
+ if a != c {
+ par[a] = c;
+ }
+ }
+ }
+ }
+ let mut order: Vec<usize> = Vec::new();
+ let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
+ for i in 0..n {
+ let r = f(&mut par, i);
+ groups.entry(r).or_insert_with(|| {
+ order.push(r);
+ Vec::new()
+ });
+ groups.get_mut(&r).unwrap().push(ids[i]);
+ }
+ order.into_iter().map(|r| groups.remove(&r).unwrap()).collect()
+ }
+
+ /// Draw the next searches towards the copper of the net's [[bundle]] partners (see
+ /// Board::set_attract); returns whether the net has any. Reset with set_attract(&[], 0.0).
+ pub(crate) fn attract_partners(&mut self, net: i32, cost: f64) -> bool {
+ let partners: Vec<i32> = self.bundles.iter().filter(|b| b.contains(&net)).flatten().copied().filter(|&p| p != net).collect();
+ if cost > 0.0 && !partners.is_empty() {
+ let items: Vec<usize> = partners.iter().flat_map(|&p| self.net_items_all(p)).collect();
+ self.b.set_attract(&items, cost);
+ }
+ !partners.is_empty()
+ }
+
+ pub fn net_items_all(&self, net: i32) -> Vec<usize> {
+ let mut v: Vec<usize> = self.pads_by_net[net as usize].iter().map(|&k| self.b.pads[k].item).collect();
+ v.extend_from_slice(&self.net_items[net as usize]);
+ v
+ }
+
+ fn comp_pts(&self, comp: &[usize]) -> Vec<Pt> {
+ let mut pts = Vec::new();
+ for &id in comp {
+ match self.b.items[id].shape {
+ Shape::Seg(a, c) => {
+ pts.push(a);
+ pts.push(c);
+ }
+ Shape::Via(p) => pts.push(p),
+ Shape::Pad(k) => pts.push(self.b.pads[k].poly.centroid()),
+ Shape::Cu(k) => pts.push(self.b.cu[k][0]),
+ }
+ }
+ pts
+ }
+
+ fn item_containing(&self, ids: &[usize], xy: Pt, l: usize) -> Option<usize> {
+ let mut best = None;
+ for &id in ids {
+ let it = &self.b.items[id];
+ if !it.on(l) {
+ continue;
+ }
+ match it.shape {
+ Shape::Pad(k) => {
+ if self.b.pads[k].poly.dist(xy) < 1e-6 {
+ return Some(id);
+ }
+ }
+ _ => {
+ if self.item_xy_dist(id, xy) <= 1e-6 {
+ best = Some(id);
+ }
+ }
+ }
+ }
+ best
+ }
+
+ /// Straight stub from a path end to the centre of the pad, via or track it ends in.
+ fn end_stub(&self, id: usize, xy: Pt, l: usize, w: f64) -> Option<Seg> {
+ let it = &self.b.items[id];
+ let near = |p: Pt| (p.0 - xy.0).hypot(p.1 - xy.1) < 1e-6;
+ match it.shape {
+ Shape::Pad(k) => {
+ let c = self.b.pads[k].poly.centroid();
+ if near(c) {
+ return None;
+ }
+ Some((l, xy, c, w.min(self.b.pads[k].poly.minor())))
+ }
+ Shape::Via(p) => {
+ if it.owner == Owner::Waypoint || near(p) {
+ return None;
+ }
+ Some((l, xy, p, w.min(it.w)))
+ }
+ Shape::Seg(a, c) => {
+ let (dx, dy) = (c.0 - a.0, c.1 - a.1);
+ let l2 = dx * dx + dy * dy;
+ let t = if l2 == 0.0 { 0.0 } else { (((xy.0 - a.0) * dx + (xy.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };
+ let q = (a.0 + t * dx, a.1 + t * dy);
+ if near(q) {
+ return None;
+ }
+ Some((l, xy, q, w.min(it.w)))
+ }
+ Shape::Cu(_) => None,
+ }
+ }
+
+ /// Keep a stub only where its copper clears every foreign item exactly; narrow it if needed.
+ fn safe_stub(&self, net: i32, st: Seg) -> Option<Seg> {
+ let (l, a, c, w) = st;
+ let (x0, y0, x1, y1) = (a.0.min(c.0), a.1.min(c.1), a.0.max(c.0), a.1.max(c.1));
+ let mut dists = Vec::new();
+ for (id, it) in self.b.items.iter().enumerate() {
+ if !self.b.alive[id] || it.net == net || !it.on(l) {
+ continue;
+ }
+ if !(it.bbox[0] < x1 + 1.0 && it.bbox[2] > x0 - 1.0 && it.bbox[1] < y1 + 1.0 && it.bbox[3] > y0 - 1.0) {
+ continue;
+ }
+ dists.push(match it.shape {
+ Shape::Pad(k) => seg_poly(a, c, &self.b.pads[k].poly),
+ Shape::Seg(s, e) => (seg_seg(a, c, s, e) - it.w / 2.0).max(0.0),
+ Shape::Via(p) => (point_seg(p, a, c) - it.w / 2.0).max(0.0),
+ Shape::Cu(k) => (self.b.cu[k].iter().map(|&p| point_seg(p, a, c)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0).max(0.0),
+ });
+ }
+ for wd in [w, 0.25, 0.2] {
+ if wd > w {
+ continue;
+ }
+ if dists.iter().all(|&d| d >= wd / 2.0 + CLR + 0.005) {
+ return Some((l, a, c, wd));
+ }
+ }
+ None
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn do_route(
+ &mut self,
+ net: i32,
+ src: &[usize],
+ tgt: &[usize],
+ w: f64,
+ wneck: f64,
+ via_d: f64,
+ goal_layer1: bool,
+ extra_tgt: Option<&[i32]>,
+ hxy: Option<Pt>,
+ so: &SearchOpts,
+ ) -> Option<Vec<usize>> {
+ let neck_items: Vec<usize> = tgt.iter().chain(src).copied().filter(|&id| matches!(self.b.items[id].shape, Shape::Pad(_))).take(60).collect();
+ let mut r = self.b.route(net, src, tgt, goal_layer1, w, wneck, via_d, &neck_items, hxy, extra_tgt, so);
+ if r.is_none() && so.margin > 0.0 {
+ // nothing inside the window: the whole board
+ r = self.b.route(net, src, tgt, goal_layer1, w, wneck, via_d, &neck_items, hxy, extra_tgt, &SearchOpts { margin: 0.0, ..*so });
+ }
+ let (path, neck) = r?;
+ let (mut segs, vias) = self.b.path_to_geom(&path, &neck, w, wneck);
+ let nx = self.b.nx;
+ let end = |s: i32| {
+ let (l, c) = (s as usize & 1, s as usize >> 1);
+ (l, self.b.cell_xy(c % nx, c / nx))
+ };
+ let (l0, xy0) = end(path[0]);
+ let (l1, xy1) = end(path[path.len() - 1]);
+ let w0 = if wneck != 0.0 && neck[0] != 0 { wneck } else { w };
+ let w1 = if wneck != 0.0 && neck[neck.len() - 1] != 0 { wneck } else { w };
+ let a = self.item_containing(src, xy0, l0).and_then(|id| self.end_stub(id, xy0, l0, w0)).and_then(|s| self.safe_stub(net, s));
+ let tl: Vec<usize> = tgt.iter().chain(&self.net_items[net as usize]).copied().collect();
+ let c = self.item_containing(&tl, xy1, l1).and_then(|id| self.end_stub(id, xy1, l1, w1)).and_then(|s| self.safe_stub(net, s));
+ segs.extend(a);
+ segs.extend(c);
+ let items = self.b.commit(net, &segs, &vias, via_d);
+ if self.b.soft_mode {
+ self.paths[net as usize].push(PathRec {
+ items: items.clone(),
+ states: path,
+ neck,
+ r_nom: (w / 2.0 + CLR + M) as f32,
+ r_neck: if wneck != 0.0 { (wneck / 2.0 + CLR + M) as f32 } else { 0.0 },
+ r_via: (via_d / 2.0 + CLR + M) as f32,
+ });
+ }
+ self.net_items[net as usize].extend_from_slice(&items);
+ Some(items)
+ }
+
+ /// Route from the copper `src` of a net to any of the states `tgt` (0.4 mm track, 0.25 mm
+ /// necks, vias of diameter d).
+ pub(crate) fn join_to(&mut self, net: i32, src: &[usize], tgt: &[i32], d: f64, so: &SearchOpts) -> bool {
+ self.do_route(net, src, &[], 0.4, 0.25, d, false, Some(tgt), None, so).is_some()
+ }
+
+ fn pad_label(&self, id: usize) -> Vec<String> {
+ match self.b.items[id].shape {
+ Shape::Pad(k) => vec![self.b.pads[k].refdes.clone(), self.b.pads[k].num.clone()],
+ _ => vec!["copper".into()],
+ }
+ }
+
+ // ----- plane nets: drop each SMD pad to the bottom plane -----
+ #[allow(clippy::too_many_arguments)]
+ /// `skip_dropped`: leave out pads whose copper already reaches a via or THT pad (a
+ /// negotiation round redoes only the drops it ripped).
+ pub fn route_plane_net(&mut self, name: &str, w: f64, wneck: f64, via_cost: f64, via_cmult: f64, only: Option<&[PadRef]>, skip: &[PadRef], skip_dropped: bool) {
+ let net = self.nid(name);
+ let idx = self.pads_by_net[net as usize].clone();
+ let has = |set: &[PadRef], k: usize| set.iter().any(|r| r.0 == self.b.pads[k].refdes && r.1 == self.b.pads[k].num);
+ let mut dropped = BTreeSet::new();
+ if skip_dropped {
+ for cp in self.components(&self.net_items_all(net)) {
+ let down = cp.iter().any(|&id| match self.b.items[id].shape {
+ Shape::Via(_) => true,
+ Shape::Pad(k) => self.b.pads[k].tht,
+ _ => false,
+ });
+ if down {
+ dropped.extend(cp);
+ }
+ }
+ }
+ let mut smd: Vec<usize> = idx
+ .iter()
+ .copied()
+ .filter(|&k| !self.b.pads[k].tht && only.is_none_or(|o| has(o, k)) && !has(skip, k) && !dropped.contains(&self.b.pads[k].item))
+ .collect();
+ // big pads (exposed pads) first
+ smd.sort_by(|&a, &c| (-self.b.pads[a].poly.area()).total_cmp(&-self.b.pads[c].poly.area()));
+ let mut planed: Vec<usize> = idx.iter().filter(|&&k| self.b.pads[k].tht).map(|&k| self.b.pads[k].item).collect();
+ planed.extend(self.net_items[net as usize].iter().copied().filter(|&id| matches!(self.b.items[id].shape, Shape::Via(_))));
+ let so = SearchOpts { via_cost, via_cmult, bmult: 50.0, turn: 2.0, ..Default::default() };
+ let mut nf = 0;
+ for &k in &smd {
+ let pi = self.b.pads[k].item;
+ let touches = planed.iter().any(|&o| matches!(self.b.items[o].shape, Shape::Pad(_)) && poly_poly(&self.b.pads[k].poly, self.pad_poly(o)) < 1e-6);
+ if touches {
+ continue;
+ }
+ let bb = self.b.pads[k].poly.bbox;
+ if bb[2] - bb[0] > 2.5 && bb[3] - bb[1] > 2.5 {
+ let c = self.b.pads[k].poly.centroid();
+ let (x0, y0) = (self.b.x0, self.b.y0);
+ let v = (((c.0 - x0) / RES).round_ties_even() * RES + x0, ((c.1 - y0) / RES).round_ties_even() * RES + y0);
+ let items = self.b.commit(net, &[], &[v], 0.6);
+ self.net_items[net as usize].extend_from_slice(&items);
+ planed.extend(items);
+ planed.push(pi);
+ continue;
+ }
+ let tgt_cells = if planed.is_empty() { None } else { Some(self.b.cells_of(&planed, 1)) };
+ match self.do_route(net, &[pi], &[], w, wneck, 0.6, true, tgt_cells.as_deref(), None, &so) {
+ None => {
+ let mut f = vec![name.to_string()];
+ f.extend(self.pad_label(pi));
+ self.failed.push(f);
+ nf += 1;
+ }
+ Some(items) => {
+ planed.extend(items);
+ planed.push(pi);
+ }
+ }
+ }
+ self.log.push(json!([name, "plane pads", smd.len(), "failed", nf]));
+ }
+
+ fn pad_poly(&self, id: usize) -> &crate::geom::Poly {
+ match self.b.items[id].shape {
+ Shape::Pad(k) => &self.b.pads[k].poly,
+ _ => unreachable!(),
+ }
+ }
+
+ /// Join all copper of a net (or only the pieces containing `pads`) into one.
+ pub fn connect(&mut self, name: &str, root: Option<&PadRef>, pads: Option<&[PadRef]>, o: &NetOpts) -> usize {
+ let net = self.nid(name);
+ let (w, wneck, via_d) = self.widths(name, o);
+ let so = o.search();
+ let max_tries = 2;
+ let mut tries: HashMap<usize, usize> = HashMap::new();
+ let want: Option<Vec<usize>> = pads.map(|ps| ps.iter().map(|p| self.pad_item(net, p)).collect());
+ let ri = root.map(|r| self.pad_item(net, r));
+ loop {
+ let mut comps = self.components(&self.net_items_all(net));
+ if let Some(want) = &want {
+ comps.retain(|cp| want.iter().any(|w| cp.contains(w)));
+ }
+ if comps.len() <= 1 {
+ break;
+ }
+ let main = match ri {
+ Some(ri) => comps.iter().position(|cp| cp.contains(&ri)).expect("root pad not in the net's copper"),
+ None => {
+ let mut m = 0;
+ for (k, cp) in comps.iter().enumerate() {
+ if cp.len() > comps[m].len() {
+ m = k;
+ }
+ }
+ m
+ }
+ };
+ let p = self.comp_pts(&comps[main]);
+ let mut best: Option<(f64, usize)> = None;
+ for (k, cp) in comps.iter().enumerate() {
+ if k == main || *tries.get(&cp[0]).unwrap_or(&0) >= max_tries {
+ continue;
+ }
+ let q = self.comp_pts(cp);
+ let d = q.iter().flat_map(|a| p.iter().map(move |b| (a.0 - b.0).hypot(a.1 - b.1))).fold(f64::INFINITY, f64::min);
+ if best.is_none_or(|(bd, _)| d < bd) {
+ best = Some((d, k));
+ }
+ }
+ let Some((_, t)) = best else { break };
+ *tries.entry(comps[t][0]).or_insert(0) += 1;
+ // heuristic point: nearest point of the target to the main piece
+ let q = self.comp_pts(&comps[t]);
+ let mut qb = (f64::INFINITY, q[0]);
+ for &a in &q {
+ let d = p.iter().map(|b| (a.0 - b.0).hypot(a.1 - b.1)).fold(f64::INFINITY, f64::min);
+ if d < qb.0 {
+ qb = (d, a);
+ }
+ }
+ let (mc, tc) = (comps[main].clone(), comps[t].clone());
+ if self.do_route(net, &mc, &tc, w, wneck, via_d, false, None, Some(qb.1), &so).is_none() {
+ let mut f = vec![name.to_string()];
+ match tc.iter().find(|&&id| matches!(self.b.items[id].shape, Shape::Pad(_))) {
+ Some(&id) => f.extend(self.pad_label(id)),
+ None => f.push("copper".into()),
+ }
+ self.failed.push(f);
+ }
+ }
+ let n = self.components(&self.net_items_all(net)).len();
+ self.log.push(json!([name, "components", n]));
+ n
+ }
+
+ /// Route pad a to pad b directly (connect would join to the nearest copper of the net).
+ pub fn route_pair(&mut self, name: &str, a: &PadRef, b: &PadRef, o: &NetOpts) -> bool {
+ let net = self.nid(name);
+ let c = self.netclass.get(name).map(String::as_str).unwrap_or("Default");
+ let w = o.w.unwrap_or_else(|| self.default_w(name, c));
+ let wneck = o.wneck.unwrap_or(if w > 0.2 { 0.2 } else { 0.0 });
+ let via_d = o.via_d.unwrap_or_else(|| *self.via.get(c).unwrap_or(&0.6));
+ let (pa, pb) = (self.pad_item(net, a), self.pad_item(net, b));
+ if self.components(&self.net_items_all(net)).iter().any(|cp| cp.contains(&pa) && cp.contains(&pb)) {
+ return true;
+ }
+ if self.do_route(net, &[pa], &[pb], w, wneck, via_d, false, None, None, &o.search()).is_none() {
+ self.failed.push(vec![name.to_string(), b.0.clone(), b.1.clone()]);
+ return false;
+ }
+ true
+ }
+
+ /// Join each decoupling cap on the net to its nearest IC pin before the rest of the net.
+ /// A cap is a 2-pad C* part with its other pad on a plane net; candidates are pins of
+ /// parts with >= 4 pads, and for bulk caps (>= 4.7 uF) also inductors and ferrites.
+ pub fn connect_decaps(&mut self, name: &str, o: &NetOpts) {
+ let net = self.nid(name);
+ let mut nfp: HashMap<&str, usize> = HashMap::new();
+ for q in &self.b.pads {
+ *nfp.entry(q.refdes.as_str()).or_insert(0) += 1;
+ }
+ let idx = &self.pads_by_net[net as usize];
+ let mut pairs = Vec::new();
+ for &k in idx {
+ let p = &self.b.pads[k];
+ if !p.refdes.starts_with('C') {
+ continue;
+ }
+ let other: Vec<_> = self.b.pads.iter().enumerate().filter(|(j, q)| q.refdes == p.refdes && *j != k).map(|(_, q)| q).collect();
+ if other.len() != 1 || other[0].net < 0 || !self.plane_nets.iter().any(|n| n == self.b.netname(other[0].net)) {
+ continue;
+ }
+ let bulk = cap_value_uf(self.fps.get(&p.refdes).map(|f| f.value.as_str()).unwrap_or("")) >= 4.7;
+ let mut best: Option<(f64, usize)> = None;
+ for &j in idx {
+ let q = &self.b.pads[j];
+ let r = q.refdes.as_str();
+ let ok = r != p.refdes && ((nfp[r] >= 4 && !r.starts_with('J') && !r.starts_with("TP")) || (bulk && (r.starts_with('L') || r.starts_with("FB"))));
+ if !ok {
+ continue;
+ }
+ let d = (q.x - p.x).hypot(q.y - p.y);
+ if best.is_none_or(|(bd, _)| d < bd) {
+ best = Some((d, j));
+ }
+ }
+ if let Some((_, j)) = best {
+ let q = &self.b.pads[j];
+ pairs.push(((p.refdes.clone(), p.num.clone()), (q.refdes.clone(), q.num.clone())));
+ }
+ }
+ for (a, b) in pairs {
+ self.route_pair(name, &a, &b, o);
+ }
+ }
+
+ pub fn place_via(&mut self, name: &str, x: f64, y: f64, d: f64) -> Option<usize> {
+ let net = self.nid(name);
+ let (i, j) = self.b.xy_cell(x, y);
+ let (x, y) = self.b.cell_xy(i as usize, j as usize);
+ if (self.b.hole[j as usize * self.b.nx + i as usize] as f64) < crate::board::via_drill(d) / 2.0 + crate::board::HOLE_HOLE + M {
+ if self.verbose {
+ eprintln!("via blocked by a hole {name} {x:.3} {y:.3}");
+ }
+ return None;
+ }
+ for l in 0..2 {
+ let s = (j as usize * self.b.nx + i as usize) * 2 + l;
+ let fd = self.b.fdist(s, net);
+ if fd < (d / 2.0 + CLR + M) as f32 {
+ if self.verbose {
+ eprintln!("via blocked {name} {x:.3} {y:.3} {fd}");
+ }
+ return None;
+ }
+ }
+ let items = self.b.commit(net, &[], &[(x, y)], d);
+ self.net_items[net as usize].extend_from_slice(&items);
+ Some(items[0])
+ }
+
+ /// Tie a pad to a new via at xy (a THT ground pad that tracks would close in).
+ pub fn tie(&mut self, name: &str, pad: &PadRef, xy: Pt, w: Option<f64>, d: f64, o: &NetOpts) -> bool {
+ let net = self.nid(name);
+ let label = vec![name.to_string(), pad.0.clone(), pad.1.clone()];
+ let Some(v) = self.place_via(name, xy.0, xy.1, d) else {
+ self.failed.push(label);
+ return false;
+ };
+ let p = self.pad_item(net, pad);
+ let c = self.netclass.get(name).map(String::as_str).unwrap_or("Default");
+ let w = w.unwrap_or_else(|| self.default_w(name, c));
+ if self.do_route(net, &[p], &[v], w, 0.0, d, false, None, None, &o.search()).is_none() {
+ self.failed.push(label);
+ return false;
+ }
+ true
+ }
+
+ /// Stitching vias on a grid wherever a via clears all foreign copper, keep-outs and the
+ /// edge on both layers and does not land in a pad. Only for a finished board.
+ pub fn stitch(&mut self, name: &str, pitch: f64, d: f64, area: Option<[f64; 4]>) -> usize {
+ let net = self.nid(name);
+ let [x0, y0, x1, y1] = area.unwrap_or([self.b.x0, self.b.y0, self.b.x1, self.b.y1]);
+ let r = (d / 2.0 + CLR + M) as f32;
+ let mut placed = Vec::new();
+ let mut y = y0 + pitch / 2.0;
+ while y < y1 {
+ let mut x = x0 + pitch / 2.0;
+ while x < x1 {
+ let (i, j) = self.b.xy_cell(x, y);
+ let ok = (0..2).all(|l| {
+ let s = (j as usize * self.b.nx + i as usize) * 2 + l;
+ !(self.b.fdist(s, net) < r
+ || self.b.padd[s] < (d / 2.0 + 0.05) as f32
+ || self.b.f[s].n1 == net && self.b.f[s].d1 < (d / 2.0 + 0.3) as f32)
+ });
+ if ok {
+ let p = self.b.cell_xy(i as usize, j as usize);
+ placed.extend(self.b.commit(net, &[], &[p], d));
+ }
+ x += pitch;
+ }
+ y += pitch;
+ }
+ self.net_items[net as usize].extend_from_slice(&placed);
+ self.log.push(json!([name, "stitching vias", placed.len()]));
+ placed.len()
+ }
+
+ // ----- rip-up and reroute -----
+
+ /// connect() that remembers its cost map and settings, so repair() can redo it.
+ pub fn route_net(&mut self, name: &str, cost: Option<&str>, root: Option<&PadRef>, pads: Option<&[PadRef]>, o: &NetOpts) -> usize {
+ self.registry.entry(name.to_string()).or_default().push(Redo {
+ cost: cost.map(String::from),
+ pads: pads.map(|p| p.to_vec()),
+ root: root.cloned(),
+ opts: o.clone(),
+ });
+ if let Some(c) = cost {
+ self.set_cost(c);
+ }
+ self.connect(name, root, pads, o)
+ }
+
+ fn redo(&mut self, name: &str) {
+ let recs = match self.registry.get(name) {
+ Some(r) => r.iter().map(|r| (r.cost.clone(), r.pads.clone(), r.root.clone(), r.opts.clone())).collect(),
+ None => vec![(None, None, None, NetOpts::default())],
+ };
+ for (cost, pads, root, opts) in recs {
+ if let Some(c) = cost {
+ self.set_cost(&c);
+ }
+ self.connect(name, root.as_ref(), pads.as_deref(), &opts);
+ }
+ }
+
+ /// Remove the router's copper of a net (kept existing copper stays).
+ pub fn rip_net(&mut self, name: &str) {
+ let net = self.nid(name) as usize;
+ let items = std::mem::take(&mut self.net_items[net]);
+ let (keep, rip): (Vec<usize>, Vec<usize>) = items.into_iter().partition(|&id| self.b.items[id].owner == Owner::Existing);
+ self.b.remove_items(&rip);
+ self.net_items[net] = keep;
+ self.failed.retain(|f| f[0] != name);
+ }
+
+ /// Nets whose copper is still in more than one piece.
+ pub fn split_nets(&self, skip: &[String]) -> Vec<String> {
+ let mut out = Vec::new();
+ for net in self.nets() {
+ let name = self.b.netname(net);
+ if skip.iter().any(|s| s == name) || self.pads_by_net[net as usize].len() < 2 {
+ continue;
+ }
+ if self.components(&self.net_items_all(net)).len() > 1 {
+ out.push(name.to_string());
+ }
+ }
+ out
+ }
+
+ /// Rip-up and reroute: for each split net, remove the nets with copper within `radius`
+ /// of its unconnected pads, route it first, then route the removed nets again. Only nets
+ /// routed through route_net() are ripped; `protect` nets never are.
+ pub fn repair(&mut self, rounds: usize, radius: f64, protect: &BTreeSet<String>, skip: &[String]) -> Vec<String> {
+ for rnd in 0..rounds {
+ let bad = self.split_nets(skip);
+ self.log.push(json!(["repair", rnd, "split", bad]));
+ if bad.is_empty() {
+ return bad;
+ }
+ for name in &bad {
+ let net = self.nid(name);
+ let comps = self.components(&self.net_items_all(net));
+ if comps.len() <= 1 {
+ continue;
+ }
+ let mut main = 0;
+ for (k, cp) in comps.iter().enumerate() {
+ if cp.len() > comps[main].len() {
+ main = k;
+ }
+ }
+ let pads: Vec<usize> = comps
+ .iter()
+ .enumerate()
+ .filter(|&(k, _)| k != main)
+ .flat_map(|(_, cp)| cp.iter().copied())
+ .filter(|&id| matches!(self.b.items[id].shape, Shape::Pad(_)))
+ .collect();
+ if pads.is_empty() {
+ continue;
+ }
+ let mut victims = BTreeSet::new();
+ for id in 0..self.b.items.len() {
+ let it = &self.b.items[id];
+ if !self.b.alive[id] || it.net < 0 || it.net == net || matches!(it.shape, Shape::Pad(_)) {
+ continue;
+ }
+ let vn = self.b.netname(it.net);
+ if protect.contains(vn) || skip.iter().any(|s| s == vn) || !self.registry.contains_key(vn) || victims.contains(vn) {
+ continue;
+ }
+ if pads.iter().any(|&p| !bbox_gap(&it.bbox, &self.b.items[p].bbox, radius) && self.item_item(id, p) <= radius) {
+ victims.insert(vn.to_string());
+ }
+ }
+ self.rip_net(name);
+ for vn in &victims {
+ self.rip_net(vn);
+ }
+ self.redo(name);
+ for vn in &victims {
+ self.redo(vn);
+ }
+ }
+ }
+ self.split_nets(skip)
+ }
+
+ // ----- negotiated congestion (PathFinder) -----
+
+ /// Remove a net's soft copper (negotiated routes), keeping anything routed before.
+ fn rip_soft(&mut self, net: i32) {
+ let items = std::mem::take(&mut self.net_items[net as usize]);
+ let (rip, keep): (Vec<usize>, Vec<usize>) = items.into_iter().partition(|&id| self.b.items[id].soft);
+ self.b.remove_items(&rip);
+ self.net_items[net as usize] = keep;
+ self.paths[net as usize].clear();
+ let name = self.b.netname(net).to_string();
+ self.failed.retain(|f| f[0] != name);
+ }
+
+ /// Route the nets still in conflict with everyone else's copper hard, trying their orders
+ /// (all of them up to 4 nets, else forward and reverse) and keeping the one that leaves
+ /// the fewest nets in pieces.
+ fn legalize(&mut self, jobs: &[Job], left: &[usize]) {
+ fn perms(v: &[usize]) -> Vec<Vec<usize>> {
+ if v.len() <= 1 {
+ return vec![v.to_vec()];
+ }
+ let mut out = Vec::new();
+ for i in 0..v.len() {
+ let mut rest = v.to_vec();
+ let x = rest.remove(i);
+ for mut p in perms(&rest) {
+ p.insert(0, x);
+ out.push(p);
+ }
+ }
+ out
+ }
+ let orders = if left.len() <= 4 { perms(left) } else { vec![left.to_vec(), left.iter().rev().copied().collect()] };
+ let nets: Vec<i32> = left.iter().map(|&k| self.nid(&jobs[k].name)).collect();
+ let mut best: Option<(usize, usize)> = None; // (split nets, order index)
+ for (oi, order) in orders.iter().enumerate() {
+ for &net in &nets {
+ self.rip_soft(net);
+ }
+ for &k in order {
+ self.route_job(&jobs[k], None);
+ }
+ let split = left.iter().filter(|&&k| !self.job_done(&jobs[k])).count();
+ if best.is_none_or(|(b, _)| split < b) {
+ best = Some((split, oi));
+ }
+ if split == 0 {
+ break;
+ }
+ }
+ let (split, oi) = best.unwrap();
+ self.log.push(json!(["legalize", left.len(), "orders tried", orders.len().min(oi + 1), "split", split]));
+ // without a clean order the board holds the last one tried: route the best again
+ if split != 0 && oi + 1 != orders.len() {
+ for &net in &nets {
+ self.rip_soft(net);
+ }
+ for &k in &orders[oi] {
+ self.route_job(&jobs[k], None);
+ }
+ }
+ }
+
+ /// A job's net is complete: in one piece, or for a plane net every drop routed.
+ fn job_done(&self, j: &Job) -> bool {
+ if j.plane {
+ !self.failed.iter().any(|f| f[0] == j.name)
+ } else {
+ self.components(&self.net_items_all(self.nid(&j.name))).len() <= 1
+ }
+ }
+
+ /// Remove only the connections (paths) of a net that are in conflict.
+ fn rip_paths(&mut self, net: i32, bad: &[usize]) {
+ let ni = net as usize;
+ let mut rip = Vec::new();
+ for (k, p) in std::mem::take(&mut self.paths[ni]).into_iter().enumerate() {
+ if bad.contains(&k) {
+ rip.extend(p.items);
+ } else {
+ self.paths[ni].push(p);
+ }
+ }
+ self.net_items[ni].retain(|id| !rip.contains(id));
+ self.b.remove_items(&rip);
+ let name = self.b.netname(net).to_string();
+ self.failed.retain(|f| f[0] != name);
+ }
+
+ /// Route a job's net; `bad` = its paths in conflict (None: rip the whole net first and
+ /// search a wider window, WIDE_MARGIN, around each connection).
+ pub(crate) fn route_job(&mut self, j: &Job, bad: Option<&[usize]>) {
+ let net = self.nid(&j.name);
+ if j.plane {
+ match bad {
+ Some(b) => self.rip_paths(net, b),
+ None => self.rip_soft(net),
+ }
+ self.set_cost(&j.cost);
+ let (w, wneck) = self.job_widths(j);
+ self.route_plane_net(&j.name, w, wneck, j.opts.via_cost.unwrap_or(12.0), j.opts.via_cmult.unwrap_or(2.0), None, &[], true);
+ return;
+ }
+ let wide;
+ let j = match bad {
+ Some(b) => {
+ self.rip_paths(net, b);
+ j
+ }
+ None => {
+ self.rip_soft(net);
+ let mut w = j.clone();
+ let m = w.opts.margin.map(|m| if m > 0.0 { m.max(WIDE_MARGIN) } else { m });
+ w.opts.margin = m;
+ for jn in &mut w.joins {
+ jn.3.margin = m;
+ }
+ wide = w;
+ &wide
+ }
+ };
+ for (a, b, cost, o) in &j.joins {
+ self.set_cost(cost);
+ self.route_pair(&j.name, a, b, o);
+ }
+ self.set_cost(&j.cost);
+ if j.decaps {
+ self.connect_decaps(&j.name, &j.opts);
+ }
+ self.connect(&j.name, j.root.as_ref(), None, &j.opts);
+ }
+
+ /// States of a net's paths whose copper violates clearance to other nets' soft copper,
+ /// and the nets it conflicts with.
+ fn conflicts(&self, net: i32) -> (Vec<usize>, BTreeSet<i32>, Vec<usize>) {
+ let (mut cells, mut nets, mut bad) = (Vec::new(), BTreeSet::new(), Vec::new());
+ let sf = &self.b.soft;
+ let nx = self.b.nx as i32;
+ let mut hit = |s: usize, r: f32, cells: &mut Vec<usize>| {
+ let f = sf[s];
+ if f.fdist(net) < r {
+ cells.push(s);
+ nets.insert(if f.n1 == net { -2 } else { f.n1 });
+ }
+ };
+ for (pi, p) in self.paths[net as usize].iter().enumerate() {
+ let n0 = cells.len();
+ for k in 0..p.states.len() {
+ let s = p.states[k] as usize;
+ if k > 0 && (p.states[k - 1] as usize & 1) != (s & 1) {
+ hit(s & !1, p.r_via, &mut cells);
+ hit(s | 1, p.r_via, &mut cells);
+ continue;
+ }
+ let diag = k > 0 && {
+ let (a, b) = ((p.states[k - 1] >> 1), (p.states[k] >> 1));
+ a % nx != b % nx && a / nx != b / nx
+ };
+ let r = if p.neck[k] != 0 && p.r_neck > 0.0 { p.r_neck } else { p.r_nom } + if diag { RDIAG as f32 } else { 0.0 };
+ hit(s, r, &mut cells);
+ }
+ if cells.len() > n0 {
+ bad.push(pi);
+ }
+ }
+ nets.remove(&-2);
+ (cells, nets, bad)
+ }
+
+ /// Route all jobs at once: each round routes the nets in conflict against everyone
+ /// else's copper, with conflicts priced by a present factor that grows every round and a
+ /// history cost on cells that stayed in conflict. Nets still in conflict after the last
+ /// round are routed again with other nets' copper hard; what fails then is reported.
+ pub fn negotiate(&mut self, jobs: &[Job], o: &Negotiation) {
+ self.b.soft_mode = true;
+ self.b.commit_owner = Owner::Negotiated;
+ self.b.pres = o.pres;
+ let mut todo: Vec<(usize, Option<Vec<usize>>)> = (0..jobs.len()).map(|k| (k, Some(Vec::new()))).collect();
+ let mut left: Vec<usize> = Vec::new();
+ let mut stuck = vec![0usize; jobs.len()]; // rounds in conflict in a row
+ for round in 0..o.rounds {
+ let t = std::time::Instant::now();
+ for (k, bad) in &todo {
+ let net = self.nid(&jobs[*k].name);
+ self.attract_partners(net, o.attract);
+ self.route_job(&jobs[*k], bad.as_deref());
+ self.b.set_attract(&[], 0.0);
+ }
+ let dt = t.elapsed().as_secs_f64();
+ left.clear();
+ let mut next = Vec::new();
+ let mut ncells = 0;
+ for (k, j) in jobs.iter().enumerate() {
+ let net = self.nid(&j.name);
+ let (cells, others, bad) = self.conflicts(net);
+ if !cells.is_empty() && std::env::var("ROUTER_TRACE").is_ok() && round + 1 == o.rounds {
+ let xy: Vec<_> = cells.iter().map(|&s| { let c = s >> 1; let p = self.b.cell_xy(c % self.b.nx, c / self.b.nx); (s & 1, (p.0 * 100.0).round() / 100.0, (p.1 * 100.0).round() / 100.0) }).collect();
+ eprintln!("CONFLICT {} with {:?}: {:?}", j.name, others.iter().map(|&n| self.b.netname(n)).collect::<Vec<_>>(), xy);
+ }
+ if !cells.is_empty() {
+ ncells += cells.len();
+ for s in cells {
+ self.b.hist[s] += o.hist;
+ }
+ left.push(k);
+ stuck[k] += 1;
+ // reroute the conflicting connections; the whole net if that keeps failing
+ next.push((k, if stuck[k] % 3 == 0 { None } else { Some(bad) }));
+ } else {
+ stuck[k] = 0;
+ }
+ }
+ self.log.push(json!(["negotiate", round, "pres", self.b.pres, "conflicting nets", left.len(), "cells", ncells, "routed", todo.len(), "s", (dt * 1000.0).round() / 1000.0]));
+ if left.is_empty() {
+ break;
+ }
+ todo = next;
+ self.b.pres *= o.pres_mult;
+ }
+ if !left.is_empty() {
+ let names: Vec<&str> = left.iter().map(|&k| jobs[k].name.rsplit('/').next().unwrap()).collect();
+ if self.verbose {
+ println!("still in conflict after {} rounds: {:?}", o.rounds, names);
+ }
+ self.b.pres = f32::INFINITY;
+ self.legalize(jobs, &left);
+ }
+ self.b.soft_mode = false;
+ self.b.pres = 0.0;
+ self.b.harden();
+ self.paths.iter_mut().for_each(Vec::clear);
+ self.b.commit_owner = Owner::Routed;
+ self.jobs = jobs.to_vec();
+ let pruned = self.prune_dangling();
+ self.log.push(json!(["negotiate", "dangling pruned", pruned]));
+ }
+
+ /// Add tracks and vias as fixed copper (saved with the result, never ripped).
+ pub fn load_existing(&mut self, tracks: &[TrackJson], vias: &[ViaJson], keep: impl Fn(&str) -> bool) {
+ for t in tracks {
+ let Some(&net) = self.b.netid.get(&t.net) else { continue };
+ if !keep(&t.net) {
+ continue;
+ }
+ let l = if t.layer == "F.Cu" { 0 } else { 1 };
+ let id = self.b.add(Board::seg_item(net, l, (t.x1, t.y1), (t.x2, t.y2), t.w, Owner::Existing));
+ self.net_items[net as usize].push(id);
+ }
+ for v in vias {
+ let Some(&net) = self.b.netid.get(&v.net) else { continue };
+ if !keep(&v.net) {
+ continue;
+ }
+ let id = self.b.add(Board::via_item(net, (v.x, v.y), v.d, 3, Owner::Existing));
+ self.net_items[net as usize].push(id);
+ }
+ }
+
+ pub fn add_item(&mut self, it: Item) -> usize {
+ let net = it.net;
+ let id = self.b.add(it);
+ if net >= 0 {
+ self.net_items[net as usize].push(id);
+ }
+ id
+ }
+
+ pub fn geometry(&self) -> (Vec<TrackJson>, Vec<ViaJson>) {
+ let (mut segs, mut vias) = (Vec::new(), Vec::new());
+ for net in self.nets().filter(|n| !self.hidden.contains(n)) {
+ let name = self.b.netname(net).to_string();
+ for &id in &self.net_items[net as usize] {
+ let it = &self.b.items[id];
+ match it.shape {
+ Shape::Seg(a, c) if (a.0 - c.0).hypot(a.1 - c.1) < 1e-6 => {}
+ Shape::Seg(a, c) => segs.push(TrackJson {
+ net: name.clone(),
+ layer: if it.on(0) { "F.Cu" } else { "B.Cu" }.into(),
+ x1: a.0,
+ y1: a.1,
+ x2: c.0,
+ y2: c.1,
+ w: it.w,
+ }),
+ Shape::Via(p) => vias.push(ViaJson { net: name.clone(), x: p.0, y: p.1, d: it.w, drill: if it.w >= 0.8 { 0.4 } else { 0.3 } }),
+ Shape::Pad(_) | Shape::Cu(_) => {}
+ }
+ }
+ }
+ (segs, vias)
+ }
+
+ pub fn result(&self) -> RoutesJson {
+ let (segs, vias) = self.geometry();
+ RoutesJson { segs, vias, failed: self.failed.clone(), log: self.log.clone() }
+ }
+}
diff --git a/tools/router/src/run.rs b/tools/router/src/run.rs
new file mode 100644
index 0000000..8de3e65
--- /dev/null
+++ b/tools/router/src/run.rs
@@ -0,0 +1,451 @@
+//! Run a route.toml on a board: fixed copper, cost maps, then the steps in order.
+
+use crate::config::{pad_ref, pad_refs, Area, Config, Step};
+use crate::geom::Poly;
+use crate::io::{BoardJson, CopperJson};
+use crate::router::{mst, Job, Negotiation, Router};
+use anyhow::{bail, Context, Result};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::path::Path;
+
+pub struct Run {
+ pub r: Router,
+ pub protect: BTreeSet<String>,
+ pub done: BTreeSet<String>,
+ pub left: Vec<String>,
+}
+
+fn resolve(r: &Router, prefix: &str, name: &str) -> Result<String> {
+ if r.b.netid.contains_key(name) {
+ return Ok(name.to_string());
+ }
+ let p = format!("{prefix}{name}");
+ if r.b.netid.contains_key(&p) {
+ return Ok(p);
+ }
+ bail!("no net {name:?} (prefix {prefix:?})")
+}
+
+fn build_costs(r: &mut Router, cfg: &Config, d: &BoardJson) -> Result<()> {
+ let (n, nx, ny) = (r.b.n, r.b.nx as i64, r.b.ny as i64);
+ for (name, def) in &cfg.costs {
+ let mut c = vec![0f32; 2 * n];
+ let layer = |s: &str| -> Result<usize> {
+ match s {
+ "F" | "F.Cu" => Ok(0),
+ "B" | "B.Cu" => Ok(1),
+ _ => bail!("cost {name}: layer {s:?} is not F or B"),
+ }
+ };
+ if let Some(ru) = &def.rudy {
+ let l = layer(&ru.layer)?;
+ for (k, v) in r.build_rudy().into_iter().enumerate() {
+ c[k * 2 + l] += (v * ru.scale as f32).min(ru.max as f32);
+ }
+ }
+ for z in &def.zones {
+ let l = layer(&z.layer)?;
+ let (ox, oy) = match &z.fp {
+ Some(f) => {
+ let fp = d.fps.get(f).with_context(|| format!("cost {name}: no footprint {f}"))?;
+ (fp.x, fp.y)
+ }
+ None => (0.0, 0.0),
+ };
+ let (i0, j0) = r.b.xy_cell(ox + z.rect[0], oy + z.rect[1]);
+ let (i1, j1) = r.b.xy_cell(ox + z.rect[2], oy + z.rect[3]);
+ for j in j0.max(0)..=j1.min(ny - 1) {
+ for i in i0.max(0)..=i1.min(nx - 1) {
+ c[(j * nx + i) as usize * 2 + l] += z.cost as f32;
+ }
+ }
+ }
+ r.b.costs.insert(name.clone(), c);
+ }
+ Ok(())
+}
+
+impl Run {
+ /// Load fixed copper and cost maps. `fixed` maps a [[fixed]] name to a file (overrides
+ /// its `path`); `base` is the directory of the route.toml.
+ pub fn new(d: &BoardJson, cfg: &Config, base: &Path, fixed: &HashMap<String, String>, verbose: bool) -> Result<Run> {
+ let area: Vec<Poly> = match &cfg.area {
+ None => Vec::new(),
+ Some(Area::Pours(s)) if s == "pours" => {
+ let a: Vec<Poly> =
+ d.zones.iter().filter(|z| cfg.plane_nets.contains(&z.net)).map(|z| Poly::new(z.pts.iter().map(|p| (p[0], p[1])).collect())).collect();
+ if a.is_empty() {
+ bail!("area = \"pours\": board.json has no zones of {:?}", cfg.plane_nets);
+ }
+ a
+ }
+ Some(Area::Pours(s)) => bail!("area = {s:?}: give \"pours\" or a polygon [[x, y], ...]"),
+ Some(Area::Poly(p)) => vec![Poly::new(p.iter().map(|q| (q[0], q[1])).collect())],
+ };
+ // [[escape]]: a virtual pad per net along the edge (ref "~ESC")
+ let mut de;
+ let (mut hidden, mut escape_w) = (Vec::new(), Vec::new());
+ let d = if cfg.escape.is_empty() {
+ d
+ } else {
+ de = d.clone();
+ let names: BTreeSet<&str> = d.pads.iter().map(|p| p.net.as_str()).collect();
+ let mut k = 0;
+ for e in &cfg.escape {
+ let n = e.nets.len().max(2) - 1;
+ for (i, name) in e.nets.iter().enumerate() {
+ let p = format!("{}{name}", cfg.prefix);
+ let net = if names.contains(name.as_str()) { name.clone() } else if names.contains(p.as_str()) { p } else { bail!("escape: no net {name:?}") };
+ let t = i as f64 / n as f64;
+ // on the routing grid: a pad between two cells may leave no cell to reach it from
+ let snap = |v: f64| (v / crate::board::RES).round() * crate::board::RES;
+ let (x, y, h) = (snap(e.from[0] + t * (e.to[0] - e.from[0])), snap(e.from[1] + t * (e.to[1] - e.from[1])), e.size / 2.0);
+ k += 1;
+ de.pads.push(crate::io::PadJson {
+ refdes: "~ESC".into(),
+ num: k.to_string(),
+ net: net.clone(),
+ x,
+ y,
+ drill: 0.0,
+ npth: false,
+ f: Some(vec![[x - h, y - h], [x + h, y - h], [x + h, y + h], [x - h, y + h]]),
+ b: None,
+ });
+ if let Some(w) = e.w {
+ escape_w.push((net.clone(), w));
+ }
+ if !e.keep {
+ hidden.push(net);
+ }
+ }
+ }
+ &de
+ };
+ let mut r = Router::new(d, &cfg.plane_nets, area, cfg.area_margin);
+ r.hidden = hidden.iter().map(|n| r.b.netid[n]).collect();
+ r.escape_w = escape_w.into_iter().collect();
+ for b in &cfg.bundle {
+ let ids = b.nets.iter().map(|n| resolve(&r, &cfg.prefix, n).map(|n| r.b.netid[&n])).collect::<Result<Vec<i32>>>()?;
+ r.bundles.push(ids);
+ }
+ r.verbose = verbose;
+ let (mut protect, mut done) = (BTreeSet::new(), BTreeSet::new());
+ for f in &cfg.fixed {
+ let path = match (fixed.get(&f.name), &f.path) {
+ (Some(p), _) => p.clone(),
+ (None, Some(p)) => base.join(p).to_string_lossy().into_owned(),
+ (None, None) if f.optional => {
+ if r.verbose {
+ println!("fixed {}: no file, skipped", f.name);
+ }
+ continue;
+ }
+ (None, None) => bail!("fixed {}: give --fixed {}=FILE", f.name, f.name),
+ };
+ let old = CopperJson::load(&path)?;
+ let exclude: Vec<String> = f.exclude.iter().map(|n| resolve(&r, &cfg.prefix, n)).collect::<Result<_>>()?;
+ let keep: BTreeSet<String> = if f.unmoved {
+ // nets whose parts did not move and that lost no part keep their copper
+ let moved: BTreeSet<&str> = d
+ .fps
+ .iter()
+ .filter(|(k, p)| {
+ old.fps.get(*k).is_some_and(|o| (p.x - o.x).abs() > 1e-3 || (p.y - o.y).abs() > 1e-3 || (p.rot - o.rot).rem_euclid(360.0).abs() > 1e-3)
+ })
+ .map(|(k, _)| k.as_str())
+ .collect();
+ let mut refs: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
+ for p in d.pads.iter().filter(|p| !p.net.is_empty()) {
+ refs.entry(&p.net).or_default().insert(&p.refdes);
+ }
+ let mut old_refs: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
+ for p in old.pads.iter().filter(|p| !p.net.is_empty()) {
+ old_refs.entry(&p.net).or_default().insert(&p.refdes);
+ }
+ refs.iter()
+ .filter(|(n, rs)| rs.is_disjoint(&moved) && !exclude.iter().any(|e| e == *n) && old_refs.get(*n).is_none_or(|o| o.is_subset(rs)))
+ .map(|(n, _)| n.to_string())
+ .collect()
+ } else {
+ old.tracks.iter().map(|t| t.net.clone()).filter(|n| !exclude.contains(n)).collect()
+ };
+ r.load_existing(&old.tracks, &old.vias, |n| keep.contains(n));
+ let with_copper: BTreeSet<&str> = old.tracks.iter().filter(|t| keep.contains(&t.net)).map(|t| t.net.as_str()).collect();
+ if r.verbose {
+ println!("fixed {}: {} nets with copper {:?}", f.name, with_copper.len(), with_copper.iter().map(|n| n.rsplit('/').next().unwrap()).collect::<Vec<_>>());
+ }
+ if f.protect {
+ protect.extend(keep.iter().cloned());
+ }
+ if f.done {
+ done.extend(keep.iter().cloned());
+ }
+ }
+ build_costs(&mut r, cfg, d)?;
+ Ok(Run { r, protect, done, left: Vec::new() })
+ }
+
+ pub fn step(&mut self, cfg: &Config, s: &Step) -> Result<()> {
+ let r = &mut self.r;
+ let p = cfg.prefix.as_str();
+ let o = s.opts();
+ let names = |r: &Router| -> Result<Vec<String>> {
+ match (&s.nets, &s.net) {
+ (Some(v), _) => v.iter().map(|n| resolve(r, p, n)).collect(),
+ (None, Some(n)) => Ok(vec![resolve(r, p, n)?]),
+ _ => bail!("step {}: `net` or `nets` missing", s.kind),
+ }
+ };
+ match s.kind.as_str() {
+ "via" => {
+ let net = resolve(r, p, s.net()?)?;
+ let (ox, oy) = match &s.fp {
+ Some(f) => {
+ let fp = r.fps.get(f).with_context(|| format!("via: no footprint {f}"))?;
+ (fp.x, fp.y)
+ }
+ None => (0.0, 0.0),
+ };
+ for a in s.at.as_deref().unwrap_or(&[]) {
+ r.place_via(&net, ox + a[0], oy + a[1], s.d.unwrap_or(0.6));
+ }
+ }
+ "plane" => {
+ let net = resolve(r, p, s.net()?)?;
+ if let Some(c) = &s.cost {
+ r.set_cost(c);
+ }
+ let only = s.only.as_deref().map(pad_refs).transpose()?;
+ let skip = pad_refs(s.skip.as_deref().unwrap_or(&[]))?;
+ r.route_plane_net(&net, s.w.unwrap_or(0.4), s.wneck.unwrap_or(0.25), s.via_cost.unwrap_or(12.0), s.via_cmult.unwrap_or(2.0), only.as_deref(), &skip, false);
+ }
+ "connect" => {
+ let root = s.root.as_deref().map(pad_ref).transpose()?;
+ let pads = s.pads.as_deref().map(pad_refs).transpose()?;
+ for net in names(r)? {
+ r.route_net(&net, s.cost.as_deref(), root.as_ref(), pads.as_deref(), &o);
+ }
+ }
+ "pair" => {
+ let net = resolve(r, p, s.net()?)?;
+ if let Some(c) = &s.cost {
+ r.set_cost(c);
+ }
+ let (a, b) = match (&s.a, &s.b) {
+ (Some(a), Some(b)) => (pad_ref(a)?, pad_ref(b)?),
+ _ => bail!("pair: `a` and `b` needed"),
+ };
+ r.route_pair(&net, &a, &b, &o);
+ }
+ "decaps" => {
+ if let Some(c) = &s.cost {
+ r.set_cost(c);
+ }
+ for net in names(r)? {
+ r.connect_decaps(&net, &o);
+ }
+ }
+ "rest" => {
+ // every other net still in pieces, shortest MST first
+ let mut skip: BTreeSet<String> = self.done.clone();
+ skip.extend(r.plane_nets.iter().cloned());
+ for n in s.exclude.as_deref().unwrap_or(&[]) {
+ skip.insert(resolve(r, p, n)?);
+ }
+ let mut nets = Vec::new();
+ for net in 1..r.b.netnames.len() as i32 {
+ let name = r.b.netname(net).to_string();
+ let idx = &r.pads_by_net[net as usize];
+ if skip.contains(&name) || idx.len() < 2 || r.components(&r.net_items_all(net)).len() <= 1 {
+ continue;
+ }
+ let pts: Vec<_> = idx.iter().map(|&k| (r.b.pads[k].x, r.b.pads[k].y)).collect();
+ let len: f64 = mst(&pts).iter().map(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1)).sum();
+ nets.push((len, name));
+ }
+ nets.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
+ for (_, name) in nets {
+ r.route_net(&name, s.cost.as_deref(), None, None, &o);
+ }
+ }
+ "negotiate" => {
+ let mut skip: BTreeSet<String> = self.done.clone();
+ skip.extend(r.plane_nets.iter().cloned());
+ for n in s.exclude.as_deref().unwrap_or(&[]) {
+ skip.insert(resolve(r, p, n)?);
+ }
+ let mut ncfg: BTreeMap<String, crate::config::NetCfg> = BTreeMap::new();
+ for (n, c) in &cfg.nets {
+ ncfg.insert(resolve(r, p, n)?, c.clone());
+ }
+ // each search stays within 1.5 mm of its connection unless the step says otherwise
+ let o = crate::router::NetOpts { margin: s.margin.or(Some(1.5)), ..o };
+ let mut jobs = Vec::new();
+ for net in 1..r.b.netnames.len() as i32 {
+ let name = r.b.netname(net).to_string();
+ let idx = &r.pads_by_net[net as usize];
+ if skip.contains(&name) || idx.len() < 2 || r.components(&r.net_items_all(net)).len() <= 1 {
+ continue;
+ }
+ let pts: Vec<_> = idx.iter().map(|&k| (r.b.pads[k].x, r.b.pads[k].y)).collect();
+ let len: f64 = mst(&pts).iter().map(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1)).sum();
+ let c = ncfg.get(&name).cloned().unwrap_or_default();
+ let cost = c.cost.clone().or(s.cost.clone()).unwrap_or_else(|| "none".into());
+ let mut joins = Vec::new();
+ for jn in &c.join {
+ let jo = crate::router::NetOpts { w: jn.w, wneck: jn.wneck, allow_via: jn.allow_via, ..c.opts(&o) };
+ joins.push((pad_ref(&jn.a)?, pad_ref(&jn.b)?, jn.cost.clone().unwrap_or_else(|| cost.clone()), jo));
+ }
+ let job = Job {
+ joins,
+ name,
+ cost,
+ root: c.root.as_deref().map(pad_ref).transpose()?,
+ decaps: c.decaps.or(s.decaps).unwrap_or(false),
+ priority: c.priority.unwrap_or(0),
+ opts: c.opts(&o),
+ plane: false,
+ };
+ jobs.push((-job.priority, len, job));
+ }
+ // planes = true: the plane nets' ground drops take part (first in each round)
+ if s.planes.unwrap_or(false) {
+ for name in r.plane_nets.clone() {
+ if !r.b.netid.contains_key(&name) {
+ continue;
+ }
+ let c = ncfg.get(&name).cloned().unwrap_or_default();
+ let cost = c.cost.clone().or(s.cost.clone()).unwrap_or_else(|| "none".into());
+ let job = Job { joins: vec![], name, cost, root: None, decaps: false, priority: c.priority.unwrap_or(10), opts: c.opts(&o), plane: true };
+ jobs.push((-job.priority, 0.0, job));
+ }
+ }
+ jobs.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then_with(|| a.2.name.cmp(&b.2.name)));
+ let jobs: Vec<Job> = jobs.into_iter().map(|j| j.2).collect();
+ let neg = Negotiation {
+ rounds: s.rounds.unwrap_or(30),
+ pres: s.pres.unwrap_or(4.0) as f32,
+ pres_mult: s.pres_mult.unwrap_or(1.5) as f32,
+ hist: s.hist.unwrap_or(1.0) as f32,
+ attract: s.attract.unwrap_or(0.0),
+ };
+ r.negotiate(&jobs, &neg);
+ }
+ "cleanup" => {
+ if r.jobs.is_empty() {
+ bail!("cleanup needs a negotiate step before it");
+ }
+ r.cleanup(s.hug.unwrap_or(0.3), s.neck.unwrap_or(4.0), s.attract.unwrap_or(0.5));
+ }
+ "repair" => {
+ let skip: Vec<String> = match &s.skip {
+ Some(v) => v.iter().map(|n| resolve(r, p, n)).collect::<Result<_>>()?,
+ None => r.plane_nets.clone(),
+ };
+ let left = r.repair(s.rounds.unwrap_or(4), s.radius.unwrap_or(1.2), &self.protect, &skip);
+ if r.verbose {
+ println!("split after repair: {left:?}");
+ }
+ // failures of nets that ended in one piece are history; plane drops are not
+ // part of the split check and keep theirs
+ let planes = r.plane_nets.clone();
+ r.failed.retain(|f| left.contains(&f[0]) || planes.contains(&f[0]));
+ self.left = left;
+ }
+ "tie" => {
+ let net = resolve(r, p, s.net()?)?;
+ if let Some(c) = &s.cost {
+ r.set_cost(c);
+ }
+ let pad = pad_ref(s.pad.as_deref().context("tie: `pad` missing")?)?;
+ let at = s.at.as_deref().and_then(|a| a.first()).context("tie: `at` missing")?;
+ r.tie(&net, &pad, (at[0], at[1]), s.w, s.d.unwrap_or(0.6), &o);
+ }
+ "pour" => {
+ let nets = if s.net.is_some() || s.nets.is_some() { names(r)? } else { r.plane_nets.clone() };
+ for net in nets {
+ let (left, added) = if s.fix.unwrap_or(true) { r.pour_fix(&net, s.d.unwrap_or(0.6)) } else { (r.pour_splits(&net), 0) };
+ if r.verbose {
+ println!("pour {net}: {added} joints added, {left} groups apart");
+ }
+ }
+ }
+ "stitch" => {
+ let net = resolve(r, p, s.net()?)?;
+ r.stitch(&net, s.pitch.unwrap_or(5.0), s.d.unwrap_or(0.6), s.area);
+ }
+ k => bail!("unknown step {k:?}"),
+ }
+ Ok(())
+ }
+}
+
+/// What a routed board came to.
+#[derive(Clone, Debug, Default)]
+pub struct Summary {
+ /// nets (not plane nets) still in more than one piece
+ pub split: usize,
+ /// failed connections, without those of plane nets that have a pour (see islands)
+ pub failed: usize,
+ /// groups of plane-net pads that the pours leave apart (beyond one per net)
+ pub islands: usize,
+ pub vias: usize,
+ pub length: f64,
+ /// track narrower than its net's width, outside pads
+ pub neck: f64,
+ pub bcu: f64,
+ /// [rank] score: weighted length + vias + neck + B.Cu (lower is better)
+ pub score: f64,
+ pub secs: f64,
+}
+
+impl Summary {
+ /// Order for ranking routed boards: fewer split nets, failed connections, pour islands,
+ /// then the [rank] score.
+ pub fn key(&self) -> (usize, usize, usize, i64) {
+ (self.split, self.failed, self.islands, (self.score * 1000.0) as i64)
+ }
+}
+
+impl Run {
+ pub fn summary(&self, cfg: &Config, secs: f64) -> Summary {
+ let r = &self.r;
+ let res = r.result();
+ let len = |s: &crate::io::TrackJson| (s.x2 - s.x1).hypot(s.y2 - s.y1);
+ let rk = &cfg.rank;
+ let weight = |net: &str| {
+ let mut w = 1.0;
+ for n in &rk.nets {
+ if crate::config::glob(&n.pattern, net) || crate::config::glob(&format!("{}{}", cfg.prefix, n.pattern), net) {
+ w = n.weight;
+ }
+ }
+ w
+ };
+ let (neck, bcu) = (r.necked_mm(), res.segs.iter().filter(|s| s.layer == "B.Cu").map(len).sum::<f64>());
+ let wlen: f64 = res.segs.iter().map(|s| len(s) * weight(&s.net)).sum();
+ Summary {
+ split: r.split_nets(&r.plane_nets).len(),
+ failed: r.failed_count(),
+ islands: r.plane_nets.iter().map(|n| r.pour_splits(n)).sum(),
+ vias: res.vias.len(),
+ length: res.segs.iter().map(len).sum(),
+ neck,
+ bcu,
+ score: wlen + rk.via_mm * res.vias.len() as f64 + rk.neck_mm * neck + rk.bcu_mm * bcu,
+ secs,
+ }
+ }
+}
+
+/// Route a board with all steps of a route.toml (quietly, for many boards in parallel).
+pub fn route(d: &BoardJson, cfg: &Config, base: &Path, fixed: &HashMap<String, String>) -> Result<(Run, Summary)> {
+ let t0 = std::time::Instant::now();
+ let mut run = Run::new(d, cfg, base, fixed, false)?;
+ for s in &cfg.step {
+ run.step(cfg, s)?;
+ }
+ let sum = run.summary(cfg, t0.elapsed().as_secs_f64());
+ Ok((run, sum))
+}