aboutsummaryrefslogtreecommitdiff
path: root/tools/router-rs/src/router.rs
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-rs/src/router.rs
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-rs/src/router.rs')
-rw-r--r--tools/router-rs/src/router.rs1268
1 files changed, 0 insertions, 1268 deletions
diff --git a/tools/router-rs/src/router.rs b/tools/router-rs/src/router.rs
deleted file mode 100644
index b22b78a..0000000
--- a/tools/router-rs/src/router.rs
+++ /dev/null
@@ -1,1268 +0,0 @@
-//! Routing strategies on top of the board fields (port of tools/router/pipeline.py):
-//! 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() }
- }
-}