diff options
| author | Louis <louis@dnge.de> | 2026-11-11 10:32:51 +0100 |
|---|---|---|
| committer | Louis <louis@dnge.de> | 2026-11-11 10:32:51 +0100 |
| commit | a59e8e99243a895197a30d6cd6dd8d744dd606de (patch) | |
| tree | 8910cc7476ff1317932257dfc8497a0f9ffc29f7 /tools/router | |
| parent | 6f2bbe1f94e4321c329f92ec3420f6d32fd7b26d (diff) | |
| download | hw-toolchain-a59e8e99243a895197a30d6cd6dd8d744dd606de.tar.gz | |
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')
| -rw-r--r-- | tools/router/Cargo.lock | 191 | ||||
| -rw-r--r-- | tools/router/Cargo.toml | 22 | ||||
| -rw-r--r-- | tools/router/README.md | 20 | ||||
| -rw-r--r-- | tools/router/astar.c | 136 | ||||
| -rw-r--r-- | tools/router/pcbroute.py | 356 | ||||
| -rw-r--r-- | tools/router/pipeline.py | 638 | ||||
| -rw-r--r-- | tools/router/plot_routes.py | 2 | ||||
| -rw-r--r-- | tools/router/requirements.txt | 4 | ||||
| -rw-r--r-- | tools/router/src/astar.rs | 320 | ||||
| -rw-r--r-- | tools/router/src/board.rs | 847 | ||||
| -rw-r--r-- | tools/router/src/cleanup.rs | 408 | ||||
| -rw-r--r-- | tools/router/src/config.rs | 389 | ||||
| -rw-r--r-- | tools/router/src/geom.rs | 281 | ||||
| -rw-r--r-- | tools/router/src/io.rs | 145 | ||||
| -rw-r--r-- | tools/router/src/lib.rs | 15 | ||||
| -rw-r--r-- | tools/router/src/main.rs | 107 | ||||
| -rw-r--r-- | tools/router/src/placement.rs | 99 | ||||
| -rw-r--r-- | tools/router/src/pour.rs | 224 | ||||
| -rw-r--r-- | tools/router/src/router.rs | 1268 | ||||
| -rw-r--r-- | tools/router/src/run.rs | 451 |
20 files changed, 4781 insertions, 1142 deletions
diff --git a/tools/router/Cargo.lock b/tools/router/Cargo.lock new file mode 100644 index 0000000..04eead0 --- /dev/null +++ b/tools/router/Cargo.lock @@ -0,0 +1,191 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "router" +version = "0.1.0" +dependencies = [ + "anyhow", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tools/router/Cargo.toml b/tools/router/Cargo.toml new file mode 100644 index 0000000..12d5a17 --- /dev/null +++ b/tools/router/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "router" +version = "0.1.0" +edition = "2021" +description = "Grid maze router for 2-layer KiCad boards (see knowledge/tooling/router.md)" + +[lib] +name = "router" +path = "src/lib.rs" + +[[bin]] +name = "router" +path = "src/main.rs" + +[dependencies] +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "1" + +[profile.release] +debug = 1 diff --git a/tools/router/README.md b/tools/router/README.md index a3f594e..847ed25 100644 --- a/tools/router/README.md +++ b/tools/router/README.md @@ -1,12 +1,18 @@ # Router -Scripted 2-layer grid maze router (A* in `astar.c`, strategies in `pipeline.py`), the -predecessor of the Rust router in `../router-rs`. Documentation, workflow and lessons: -[knowledge/tooling/router.md](../../knowledge/tooling/router.md). +Grid router for 2-layer KiCad boards with negotiated congestion (all nets at once, plane-net +drops optionally included), cleanup passes, a pour-connectivity check and ordered steps, all +configured per board in a `route.toml`. Footprint copper such as net-tie bridges is respected; +`area = "pours"` keeps all copper inside the plane pours (a design block's area). The placer +links the crate to route its candidates. -Setup once: +KiCad I/O (run with KiCad's Python, see `../kicad_env.sh`): `dump_board.py` writes board.json, +`write_board.py` writes routes.json back into a board. `plot_routes.py` draws a route (plain +Python with `../requirements.txt`). - python3 -m venv tools/router/.venv - tools/router/.venv/bin/pip install -r tools/router/requirements.txt +Documentation and lessons: [knowledge/tooling/router.md](../../knowledge/tooling/router.md); +end to end on your board: [knowledge/tooling/pnr.md](../../knowledge/tooling/pnr.md). -The C core compiles itself (`cc`) on first import. + cargo build --release + target/release/router route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL] + target/release/router place board.json placement.json moved.json diff --git a/tools/router/astar.c b/tools/router/astar.c deleted file mode 100644 index 3b3ccb5..0000000 --- a/tools/router/astar.c +++ /dev/null @@ -1,136 +0,0 @@ -// Grid A* maze router core, 2 layers (0 = F.Cu, 1 = B.Cu). -// Clearance uses exact distance fields: d1/n1 = distance to and net of nearest copper, -// d2 = distance to nearest copper of a net other than n1. Foreign distance for net X: -// n1 == X ? d2 : d1. -#include <stdint.h> -#include <stdlib.h> -#include <string.h> -#include <math.h> - -static int NX, NY, N; -static float *G = 0; static int32_t *PAR = 0; static uint32_t *STAMP = 0; static uint8_t *DIR = 0; static uint8_t *CLOSED = 0; -static uint32_t CALL = 0; -static int32_t *HEAPI = 0; static float *HEAPF = 0; static int HN = 0, HCAP = 0; - -int init(int nx, int ny) { - NX = nx; NY = ny; N = nx * ny; - free(G); free(PAR); free(STAMP); free(DIR); free(CLOSED); free(HEAPI); free(HEAPF); - G = malloc(sizeof(float) * 2 * N); PAR = malloc(sizeof(int32_t) * 2 * N); - STAMP = calloc(2 * N, sizeof(uint32_t)); DIR = malloc(2 * N); CLOSED = malloc(2 * N); - HCAP = 1 << 22; HEAPI = malloc(sizeof(int32_t) * HCAP); HEAPF = malloc(sizeof(float) * HCAP); - CALL = 0; - return (G && PAR && STAMP && DIR && CLOSED && HEAPI && HEAPF) ? 0 : -1; -} - -static void hpush(float f, int32_t i) { - if (HN >= HCAP) { HCAP *= 2; HEAPI = realloc(HEAPI, sizeof(int32_t) * HCAP); HEAPF = realloc(HEAPF, sizeof(float) * HCAP); } - int k = HN++; - while (k > 0) { int p = (k - 1) >> 1; if (HEAPF[p] <= f) break; HEAPF[k] = HEAPF[p]; HEAPI[k] = HEAPI[p]; k = p; } - HEAPF[k] = f; HEAPI[k] = i; -} -static int32_t hpop(void) { - int32_t top = HEAPI[0]; float lf = HEAPF[--HN]; int32_t li = HEAPI[HN]; - int k = 0; - while (1) { int c = 2 * k + 1; if (c >= HN) break; if (c + 1 < HN && HEAPF[c + 1] < HEAPF[c]) c++; if (HEAPF[c] >= lf) break; HEAPF[k] = HEAPF[c]; HEAPI[k] = HEAPI[c]; k = c; } - HEAPF[k] = lf; HEAPI[k] = li; - return top; -} - -static const int DX[8] = {1, 1, 0, -1, -1, -1, 0, 1}; -static const int DY[8] = {0, 1, 1, 1, 0, -1, -1, -1}; - -static inline float fdist(const float *d1, const int32_t *n1, const float *d2, int32_t s, int net) { - return n1[s] == net ? d2[s] : d1[s]; -} -static inline float heur(int x, int y, int hx, int hy) { - int ax = abs(x - hx), ay = abs(y - hy); - return (ax > ay ? ax : ay) + 0.41421356f * (ax < ay ? ax : ay); -} - -// Returns path length (cells, target back to source) or -1. -// neck flag per output cell: 1 if only the neck radius passed. -int route(const float *d1, const int32_t *n1, const float *d2, const float *padd, const float *costmap, - int net, const int32_t *src, int nsrc, const uint8_t *tgt, int goal_layer1, - int hx, int hy, - float r_nom, float r_neck, float r_via, float r_vpad, float r_diag, - const int32_t *neckbox, int nbox, - float via_cost, float via_cmult, float bmult, float turn_cost, int allow_via, int max_expand, - int32_t *out, uint8_t *outneck, int maxout, int layer_mask) -{ - CALL++; - if (CALL == 0) { memset(STAMP, 0, sizeof(uint32_t) * 2 * N); CALL = 1; } - HN = 0; - for (int i = 0; i < nsrc; i++) { - int32_t s = src[i]; - int L = s / N; if (!((layer_mask >> L) & 1)) continue; - float sfd = fdist(d1, n1, d2, s, net); - if (sfd < (r_neck > 0 ? r_neck : r_nom)) continue; // a track must fit at its start cell - STAMP[s] = CALL; G[s] = 0; PAR[s] = -1; DIR[s] = 255; CLOSED[s] = 0; - int c = s % N; - hpush(goal_layer1 ? 0 : heur(c % NX, c / NX, hx, hy), s); - } - int expanded = 0, found = -1; - while (HN > 0) { - int32_t s = hpop(); - if (CLOSED[s]) continue; - CLOSED[s] = 1; - int L = s / N; int c = s % N; int x = c % NX, y = c / NX; - if ((tgt && tgt[s]) || (goal_layer1 && L == 1)) { found = s; break; } - if (++expanded > max_expand) break; - float gcur = G[s]; - int pd = DIR[s]; - for (int d = 0; d < 8; d++) { - int qx = x + DX[d], qy = y + DY[d]; - if (qx < 0 || qy < 0 || qx >= NX || qy >= NY) continue; - int nc = qy * NX + qx; int32_t ns = (int32_t)(L * N + nc); - float fd = fdist(d1, n1, d2, ns, net); - float need = r_nom + ((d & 1) ? r_diag : 0); - int neck = 0; - if (fd < need) { - if (r_neck <= 0) continue; - float needn = r_neck + ((d & 1) ? r_diag : 0); - if (fd < needn) continue; - int nb = 0; - for (int b = 0; b < nbox; b++) { if (qx >= neckbox[4*b] && qx <= neckbox[4*b+2] && qy >= neckbox[4*b+1] && qy <= neckbox[4*b+3]) { nb = 1; break; } } - if (!nb) continue; - neck = 1; - } - float step = (d & 1) ? 1.41421356f : 1.0f; - float cst = step * (L ? bmult : 1.0f) + (costmap ? costmap[(size_t)L * N + nc] * step : 0); - if (neck) cst += 0.3f * step; - if (pd != 255 && pd != d) { - int t = abs(pd - d); if (t > 4) t = 8 - t; - if (t >= 3) continue; - cst += turn_cost * t; - } - float ng = gcur + cst; - if (STAMP[ns] == CALL && (CLOSED[ns] || G[ns] <= ng)) continue; - STAMP[ns] = CALL; G[ns] = ng; PAR[ns] = s; DIR[ns] = (uint8_t)d; CLOSED[ns] = 0; - hpush(ng + (goal_layer1 ? 0 : heur(qx, qy, hx, hy)), ns); - } - if (allow_via && ((layer_mask & 3) == 3)) { - int32_t s0 = c, s1 = N + c; - if (fdist(d1, n1, d2, s0, net) >= r_via && fdist(d1, n1, d2, s1, net) >= r_via && - padd[s0] >= r_vpad && padd[s1] >= r_vpad) { - int32_t ns = (int32_t)((1 - L) * N + c); - float ng = gcur + via_cost + (costmap ? via_cmult * (costmap[c] + costmap[N + c]) : 0); - if (!(STAMP[ns] == CALL && (CLOSED[ns] || G[ns] <= ng))) { - STAMP[ns] = CALL; G[ns] = ng; PAR[ns] = s; DIR[ns] = 255; CLOSED[ns] = 0; - hpush(ng + (goal_layer1 ? 0 : heur(x, y, hx, hy)), ns); - } - } - } - } - if (found < 0) return -1; - int n = 0; int32_t s = found; - while (s >= 0 && n < maxout) { - int32_t p = PAR[s]; - float fd = fdist(d1, n1, d2, s, net); - // the same test the search used to enter the cell: a full-width track that barely - // fits (e.g. 0.5 mm beside a bus line) must not be drawn necked all along its run - int dd = DIR[s]; - outneck[n] = fd < r_nom + ((dd != 255 && (dd & 1)) ? r_diag : 0) ? 1 : 0; - out[n++] = s; s = p; - } - return n; -} diff --git a/tools/router/pcbroute.py b/tools/router/pcbroute.py deleted file mode 100644 index 24f932e..0000000 --- a/tools/router/pcbroute.py +++ /dev/null @@ -1,356 +0,0 @@ -"""Grid maze router for 2-layer boards (Python side; the search runs in astar.c). - -The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu). Clearance uses exact -distance fields: for every cell the distance to the nearest copper (d1, its net n1) -and to the nearest copper of any other net (d2). A track of width w fits where the -distance to foreign copper is >= w/2 + CLR. Necks (narrower width) are allowed only -near pads, so fine-pitch pins can be entered. - - -Call setup(x0, y0, x1, y1) with the board extents before creating a Board. -""" -import ctypes, json, math, os, subprocess -import numpy as np -import shapely -from shapely.geometry import Polygon, Point, box, LineString -from scipy import ndimage - -HERE = os.path.dirname(os.path.abspath(__file__)) -_LIB = os.path.join(HERE, "libastar.dylib") -if not os.path.exists(_LIB) or os.path.getmtime(_LIB) < os.path.getmtime(os.path.join(HERE, "astar.c")): - subprocess.run(["cc", "-O3", "-shared", "-fPIC", "-o", _LIB, os.path.join(HERE, "astar.c")], check=True) -lib = ctypes.CDLL(_LIB) -fp = np.ctypeslib.ndpointer -lib.init.argtypes = [ctypes.c_int, ctypes.c_int] -lib.route.restype = ctypes.c_int -lib.route.argtypes = [fp(np.float32), fp(np.int32), fp(np.float32), fp(np.float32), fp(np.float32), - ctypes.c_int, fp(np.int32), ctypes.c_int, fp(np.uint8), ctypes.c_int, - ctypes.c_int, ctypes.c_int, - ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, - fp(np.int32), ctypes.c_int, - ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_int, ctypes.c_int, - fp(np.int32), fp(np.uint8), ctypes.c_int, ctypes.c_int] - -RES = 0.05 -X0 = Y0 = X1 = Y1 = 0.0 -NX = NY = N = 0 - - -def setup(x0, y0, x1, y1): - """Set the grid to the board extents (mm). Call before Board().""" - global X0, Y0, X1, Y1, NX, NY, N - X0, Y0, X1, Y1 = x0, y0, x1, y1 - NX = int(round((X1 - X0) / RES)) + 1 - NY = int(round((Y1 - Y0) / RES)) + 1 - N = NX * NY -CAP = 1.5 -CLR = 0.2 -M = 0.015 # numeric margin on clearance checks -RDIAG = 0.02 # extra margin on diagonal steps -EDGE_CLR = 0.5 # copper to board edge -HOLE_CLR = 0.3 # copper to NPTH hole edge - -def cell_xy(i, j): return X0 + i * RES, Y0 + j * RES -def xy_cell(x, y): return int(round((x - X0) / RES)), int(round((y - Y0) / RES)) - -class Item: - __slots__ = ("kind", "net", "layers", "geom", "bbox", "w", "owner") - def __init__(self, kind, net, layers, geom, w=0.0, owner=None): - self.kind, self.net, self.layers, self.geom, self.w, self.owner = kind, net, layers, geom, w, owner - if kind == "pad": - self.bbox = geom.bounds - elif kind == "seg": - (x1, y1), (x2, y2) = geom - self.bbox = (min(x1, x2) - w / 2, min(y1, y2) - w / 2, max(x1, x2) + w / 2, max(y1, y2) + w / 2) - elif kind == "via": - x, y = geom; r = w / 2 - self.bbox = (x - r, y - r, x + r, y + r) - - def dist(self, X, Y): - if self.kind == "pad": - return shapely.distance(shapely.points(X, Y), self.geom).astype(np.float32) - if self.kind == "seg": - (x1, y1), (x2, y2) = self.geom - dx, dy = x2 - x1, y2 - y1 - L2 = dx * dx + dy * dy - if L2 == 0: t = np.zeros_like(X) - else: t = np.clip(((X - x1) * dx + (Y - y1) * dy) / L2, 0, 1) - return (np.hypot(X - (x1 + t * dx), Y - (y1 + t * dy)) - self.w / 2).astype(np.float32) - if self.kind == "via": - x, y = self.geom - return (np.hypot(X - x, Y - y) - self.w / 2).astype(np.float32) - - -class Board: - def __init__(self, board_json, netclass_of, domains, plane_nets=("GND",)): - d = json.load(open(board_json)) if isinstance(board_json, str) else board_json - self.plane_nets = set(plane_nets) - self.fpcopper = d.get("fpcopper", []) - self.keepouts = [Polygon(k) for k in d.get("keepouts", [])] - self.fps = d["fps"] - self.netid = {"": -1} - self.netname = {-1: ""} - self.pads = [] # dicts with poly, net id, layers, ref, num, center - for p in d["pads"]: - layers = tuple(L for L, k in ((0, "F"), (1, "B")) if p[k]) - if not layers: continue - name = p["net"] - if not name or name.startswith("unconnected"): - nid = -1 - else: - if name not in self.netid: - k = len(self.netid); self.netid[name] = k; self.netname[k] = name - nid = self.netid[name] - poly = Polygon(p["F"] or p["B"]) - self.pads.append(dict(ref=p["ref"], num=p["num"], net=nid, layers=layers, poly=poly, - x=p["x"], y=p["y"], drill=p["drill"], tht=len(layers) == 2)) - self.npth = [(p["x"], p["y"], p["drill"]) for p in d["pads"] if p.get("npth")] - self.netclass_of = netclass_of - self.domains = domains - self.items = [] - self.d1 = np.full((2, NY, NX), CAP, np.float32) - self.n1 = np.zeros((2, NY, NX), np.int32) - self.d2 = np.full((2, NY, NX), CAP, np.float32) - self.padd = np.full((2, NY, NX), CAP, np.float32) - self.cost = np.zeros((2, NY, NX), np.float32) - self.base = np.full((2, NY, NX), CAP, np.float32) - gx = X0 + np.arange(NX) * RES; gy = Y0 + np.arange(NY) * RES - self.GX, self.GY = np.meshgrid(gx, gy) - lib.init(NX, NY) - self.tgt = np.zeros(2 * N, np.uint8) - self.out = np.zeros(400000, np.int32); self.outneck = np.zeros(400000, np.uint8) - self.routes = {} # net id -> list of route records (segments/vias) - - # ---------- static obstacles ---------- - def build_static(self, keepouts=(), domain_seeds=()): - keepouts = list(keepouts) + self.keepouts - GX, GY = self.GX, self.GY - edge = np.minimum.reduce([GX - X0, X1 - GX, GY - Y0, Y1 - GY]) - base = edge - (EDGE_CLR - CLR) - for (x, y, dr) in self.npth: - r = dr / 2 + HOLE_CLR - base = np.minimum(base, np.hypot(GX - x, GY - y) - r + CLR) - for poly in keepouts: - dd = shapely.distance(shapely.points(GX.ravel(), GY.ravel()), poly).reshape(GX.shape) - base = np.minimum(base, dd + CLR) - # isolation domains (e.g. isolated RS485): voronoi to domain pad copper, eroded by - # 1.55 mm each side. Skipped when the board has none. - dom_ids = sorted(set(self.domains.values()) | {"LOGIC"}) - if len(dom_ids) == 1: - dom_ids = [] - dist_stack = [] - for dmn in dom_ids: - mask = np.zeros((NY, NX), bool) - for p in self.pads: - if p["net"] < 0: continue - if self.domains.get(self.netname[p["net"]], "LOGIC") != dmn: continue - b = p["poly"].bounds - i0, j0 = xy_cell(b[0], b[1]); i1, j1 = xy_cell(b[2], b[3]) - sub = shapely.contains_xy(p["poly"], GX[j0:j1+1, i0:i1+1], GY[j0:j1+1, i0:i1+1]) - mask[j0:j1+1, i0:i1+1] |= sub - ci, cj = xy_cell(p["x"], p["y"]); mask[cj, ci] = True - for (sd, sx, sy) in domain_seeds: - if sd == dmn: - ci, cj = xy_cell(sx, sy); mask[cj, ci] = True - dist_stack.append(ndimage.distance_transform_edt(~mask) * RES) - if dom_ids: - dist_stack = np.array(dist_stack) - owner = np.argmin(dist_stack, axis=0) - self.dom_owner = owner; self.dom_ids = dom_ids - allowed = np.zeros((NY, NX), bool) - for k in range(len(dom_ids)): - m = owner == k - dout = ndimage.distance_transform_edt(m) * RES # distance to nearest non-m cell - allowed |= m & (dout >= 1.55) - dforb = ndimage.distance_transform_edt(allowed) * RES # distance from allowed cell to forbidden - base = np.minimum(base, np.where(allowed, dforb + CLR - RES, -1.0)) - self.allowed = allowed - base = base.astype(np.float32) - self.base[0] = base; self.base[1] = base - self.reset_region(None) - # pad distance field for via-in-pad avoidance (SMD pads, not exposed pads) - for p in self.pads: - if p["tht"]: continue - b = p["poly"].bounds - if (b[2] - b[0]) > 2.5 and (b[3] - b[1]) > 2.5 and p["net"] >= 0 and self.netname[p["net"]] in self.plane_nets: - continue # exposed GND pad: vias allowed - sl, X, Y = self.window(b, 1.0) - dd = shapely.distance(shapely.points(X, Y), p["poly"]).astype(np.float32) - for L in p["layers"]: - v = self.padd[L][sl]; np.minimum(v, dd, out=v) - for p in self.pads: - it = Item("pad", p["net"], p["layers"], p["poly"], owner=("pad", p["ref"], p["num"])) - p["item"] = it - self.items.append(it) - self.insert(it) - if True: - # footprint copper that is not a pad (net-tie bridges, antenna graphics) - for g in self.fpcopper: - poly = Polygon(g["poly"]).buffer(0) - for p in self.pads: - if p["ref"] == g["ref"]: poly = poly.difference(p["poly"]) - if poly.is_empty: continue - # a net tie's bridge is GND copper (it joins the AGND pad to GND) - nid = self.netid.get("GND", -1) if g["ref"].startswith("NT") else -1 - it = Item("pad", nid, (0,) if g["layer"] == "F" else (1,), poly, owner=("fpcopper", g["ref"])) - self.items.append(it); self.insert(it) - # KiCad sees this graphic as net-less for hole clearance (0.3 mm to the via hole) - sl, X, Y = self.window(poly.bounds, 1.0) - dd = shapely.distance(shapely.points(X, Y), poly).astype(np.float32) - 0.1 - for L in (0, 1): - v = self.padd[L][sl]; np.minimum(v, dd, out=v) - - def window(self, b, pad): - i0 = max(0, int(math.floor((b[0] - pad - X0) / RES))); j0 = max(0, int(math.floor((b[1] - pad - Y0) / RES))) - i1 = min(NX - 1, int(math.ceil((b[2] + pad - X0) / RES))); j1 = min(NY - 1, int(math.ceil((b[3] + pad - Y0) / RES))) - sl = (slice(j0, j1 + 1), slice(i0, i1 + 1)) - return sl, self.GX[sl], self.GY[sl] - - def reset_region(self, b): - if b is None: - sl = (slice(None), slice(None)) - else: - sl, _, _ = self.window(b, 0) - for L in (0, 1): - bd = self.base[L][sl] - self.d1[L][sl] = np.minimum(bd, CAP) - self.n1[L][sl] = np.where(bd < CAP, -1, 0) - self.d2[L][sl] = CAP - - def insert(self, it, clip=None): - b = it.bbox - if clip is not None: - b2 = (max(b[0] - CAP, clip[0]), max(b[1] - CAP, clip[1]), min(b[2] + CAP, clip[2]), min(b[3] + CAP, clip[3])) - if b2[0] > b2[2] or b2[1] > b2[3]: return - sl, X, Y = self.window(b2, 0) - else: - sl, X, Y = self.window(b, CAP) - dd = it.dist(X, Y) - net = it.net - for L in it.layers: - d1 = self.d1[L][sl]; n1 = self.n1[L][sl]; d2 = self.d2[L][sl] - same = n1 == net - np.minimum(d1, dd, out=d1, where=same) - m = (~same) & (dd < d1) - d2[m] = d1[m]; d1[m] = dd[m]; n1[m] = net - o = (~same) & (~m) - np.minimum(d2, dd, out=d2, where=o) - - def remove_items(self, items): - if not items: return - ids = set(id(i) for i in items) - self.items = [i for i in self.items if id(i) not in ids] - for it in items: - b = (it.bbox[0] - CAP, it.bbox[1] - CAP, it.bbox[2] + CAP, it.bbox[3] + CAP) - self.reset_region(b) - for o in self.items: - ob = o.bbox - if ob[0] - CAP > b[2] or ob[2] + CAP < b[0] or ob[1] - CAP > b[3] or ob[3] + CAP < b[1]: continue - self.insert(o, clip=b) - - # ---------- routing ---------- - def cells_of(self, items, layers=(0, 1)): - out = [] - for it in items: - sl, X, Y = self.window(it.bbox, 0.05) - dd = it.dist(X, Y) - jj, ii = np.nonzero(dd <= 0.0) - j0, i0 = sl[0].start, sl[1].start - c = (jj + j0) * NX + (ii + i0) - for L in it.layers: - if L in layers: out.append(L * N + c) - if not out: return np.zeros(0, np.int32) - return np.unique(np.concatenate(out)).astype(np.int32) - - def route(self, net, src_items, tgt_items=None, goal_layer1=False, w=0.2, wneck=0.0, via_d=0.6, - via_cost=40.0, via_cmult=0.0, bmult=3.0, turn=4.0, allow_via=True, layer_mask=3, neck_items=(), max_expand=4000000, - hxy=None, extra_tgt_cells=None): - src = self.cells_of(src_items) - if len(src) == 0: return None - if tgt_items: - tc = self.cells_of(tgt_items) - else: - tc = np.zeros(0, np.int32) - if extra_tgt_cells is not None and len(extra_tgt_cells): - tc = np.concatenate([tc, extra_tgt_cells]).astype(np.int32) - self.tgt[tc] = 1 - if hxy is None: - if tgt_items: - g0 = tgt_items[0] - c = g0.geom.centroid if g0.kind == "pad" else (Point(g0.geom) if g0.kind == "via" else Point(g0.geom[0])) - hxy = (c.x, c.y) - else: - hxy = (X0, Y0) - hx, hy = xy_cell(*hxy) - boxes = [] - for it in neck_items: - b = it.bbox - i0, j0 = xy_cell(b[0] - 1.0, b[1] - 1.0); i1, j1 = xy_cell(b[2] + 1.0, b[3] + 1.0) - boxes += [i0, j0, i1, j1] - boxes = np.array(boxes or [0, 0, -1, -1], np.int32) - r_nom = w / 2 + CLR + M - r_neck = (wneck / 2 + CLR + M) if wneck else 0.0 - r_via = via_d / 2 + CLR + M - r_vpad = via_d / 2 + 0.05 - n = lib.route(self.d1.ravel(), self.n1.ravel(), self.d2.ravel(), self.padd.ravel(), self.cost.ravel(), - net, src, len(src), self.tgt, int(goal_layer1), hx, hy, - r_nom, r_neck, r_via, r_vpad, RDIAG, boxes, len(boxes) // 4, - via_cost, via_cmult, bmult, turn, int(allow_via), max_expand, - self.out, self.outneck, len(self.out), layer_mask) - self.tgt[tc] = 0 - if n < 0: return None - path = self.out[:n][::-1].copy(); neck = self.outneck[:n][::-1].copy() - return path, neck - - def path_to_geom(self, net, path, neck, w, wneck, via_d): - """Convert a cell path into segments and vias (lists).""" - pts = [] - for s, nk in zip(path, neck): - L = int(s // N); c = int(s % N) - pts.append((L, c % NX, c // NX, int(nk))) - segs, vias = [], [] - run = [pts[0]] - def flush(run): - if len(run) < 2: return - # widths per step - k = 0 - while k < len(run) - 1: - L, i, j, nk = run[k] - wd = wneck if (wneck and (run[k][3] or run[k + 1][3])) else w - # extend while direction and width constant - di, dj = run[k + 1][1] - i, run[k + 1][2] - j - m = k + 1 - while m < len(run) - 1: - w2 = wneck if (wneck and (run[m][3] or run[m + 1][3])) else w - if (run[m + 1][1] - run[m][1], run[m + 1][2] - run[m][2]) != (di, dj) or w2 != wd: break - m += 1 - segs.append((L, cell_xy(i, j), cell_xy(run[m][1], run[m][2]), wd)) - k = m - for p in pts[1:]: - if p[0] != run[-1][0]: - flush(run) - vias.append(cell_xy(p[1], p[2])) - run = [p] - else: - run.append(p) - flush(run) - return segs, vias - - def commit(self, net, segs, vias, via_d, tag): - items = [] - for (L, a, b, wd) in segs: - it = Item("seg", net, (L,), (a, b), w=wd, owner=tag) - items.append(it) - for v in vias: - items.append(Item("via", net, (0, 1), v, w=via_d, owner=tag)) - for it in items: - self.items.append(it); self.insert(it) - return items - - def stub(self, net, cell_xy_pt, L, target_item, w): - """Straight stub from a path end to the centre of the pad it ends in (if inside).""" - if target_item.kind != "pad": return None - c = target_item.geom.centroid - if target_item.geom.contains(Point(cell_xy_pt)) and (abs(c.x - cell_xy_pt[0]) > 1e-6 or abs(c.y - cell_xy_pt[1]) > 1e-6): - return (L, cell_xy_pt, (c.x, c.y), w) - return None diff --git a/tools/router/pipeline.py b/tools/router/pipeline.py deleted file mode 100644 index f7783d3..0000000 --- a/tools/router/pipeline.py +++ /dev/null @@ -1,638 +0,0 @@ -"""Routing strategies on top of pcbroute: plane drops, tree routing, component joining. - -Typical use (see knowledge/tooling/router.md): - - R = Router("board.json") # from dump_board.py - R.route_plane_net("GND") # every SMD ground pad gets its own via to the plane - R.connect("/Comms ETH/XI") # join all copper of a net - R.save("routes.json") # for write_board.py -""" -import sys, time, math, json -import numpy as np -from shapely.geometry import Point, LineString -import pcbroute as P -from pcbroute import Item, Board, cell_xy, xy_cell, RES, CLR, M - -# Filled in by Router() from the board dump: net -> class, class -> width / via size. -NETCLASS, WIDTH, VIA, DOMAINS = {}, {"Default": 0.2}, {}, {} -PLANE_NETS = ["GND"] - -def pad_minor(poly): - r = poly.minimum_rotated_rectangle - xs, ys = r.exterior.coords.xy - e = [math.hypot(xs[i+1]-xs[i], ys[i+1]-ys[i]) for i in range(2)] - return min(e) - -class Router: - def __init__(self, board_json, seeds=(), plane_nets=("GND",), domains=None): - d = json.load(open(board_json)) if isinstance(board_json, str) else board_json - P.setup(*d["bounds"]) - NETCLASS.clear(); NETCLASS.update(d.get("netclass", {})) - WIDTH.update({k: v["track"] for k, v in d.get("classes", {}).items()}) - VIA.update({k: v["via"] for k, v in d.get("classes", {}).items() if v["via"] != 0.6}) - PLANE_NETS[:] = list(plane_nets) - DOMAINS.clear(); DOMAINS.update(domains or {}) - self.B = Board(d, NETCLASS, DOMAINS, plane_nets=plane_nets) - self.B.build_static(domain_seeds=seeds) - self.log = [] - self.net_items = {} # net -> list of committed items - self.connected = {} # net -> set of pad indexes connected to the main tree - self.failed = [] - self.pads_by_net = {} - for k, p in enumerate(self.B.pads): - if p["net"] >= 0: self.pads_by_net.setdefault(p["net"], []).append(k) - - def nid(self, name): return self.B.netid[name] - def cls(self, name): return NETCLASS.get(name, "Default") - - # ----- congestion estimate (RUDY over MST edges of signal nets) ----- - def build_rudy(self, weight=8.0, exclude=()): - B = self.B - R = np.zeros((P.NY, P.NX), np.float32) - for net, idx in self.pads_by_net.items(): - name = B.netname[net] - if name in PLANE_NETS or name in exclude: continue - pts = [(B.pads[k]["x"], B.pads[k]["y"]) for k in idx] - for (a, b) in mst(pts): - x0, x1 = sorted((a[0], b[0])); y0, y1 = sorted((a[1], b[1])) - x0 -= 0.4; x1 += 0.4; y0 -= 0.4; y1 += 0.4 - dens = ((x1 - x0) + (y1 - y0)) / ((x1 - x0) * (y1 - y0)) * 0.25 - i0, j0 = xy_cell(x0, y0); i1, j1 = xy_cell(x1, y1) - R[max(j0,0):j1+1, max(i0,0):i1+1] += dens - self.rudy = R - return R - - def set_cost(self, F=None, Bc=None): - self.B.cost[0] = 0 if F is None else F - self.B.cost[1] = 0 if Bc is None else Bc - - # ----- helpers ----- - def item_containing(self, items, xy, L): - best = None - for it in items: - if L not in it.layers: continue - if it.kind == "pad": - if it.geom.contains(Point(xy)) or it.geom.distance(Point(xy)) < 1e-6: return it - else: - d = it.dist(np.array([xy[0]]), np.array([xy[1]]))[0] - if d <= 1e-6: best = it - return best - - def end_stub(self, it, xy, L, w): - if it is None: return None - if it.kind == "pad": - c = it.geom.centroid - if math.hypot(c.x - xy[0], c.y - xy[1]) < 1e-6: return None - wd = min(w, pad_minor(it.geom)) - return (L, xy, (c.x, c.y), wd) - if it.kind == "via": - if it.owner and it.owner[0] == "wp": return None - x, y = it.geom - if math.hypot(x - xy[0], y - xy[1]) < 1e-6: return None - return (L, xy, (x, y), min(w, it.w)) - if it.kind == "seg": - (x1, y1), (x2, y2) = it.geom - ls = LineString([(x1, y1), (x2, y2)]) - q = ls.interpolate(ls.project(Point(xy))) - if math.hypot(q.x - xy[0], q.y - xy[1]) < 1e-6: return None - return (L, xy, (q.x, q.y), min(w, it.w)) - - def do_route(self, net, src_items, tgt_items, w, wneck, via_d, goal_layer1=False, extra_tgt=None, tag=None, **kw): - B = self.B - neck_items = [it for it in list(tgt_items or []) + list(src_items) if it.kind == "pad"][:60] - r = B.route(net, src_items, tgt_items, goal_layer1=goal_layer1, w=w, wneck=wneck, via_d=via_d, - neck_items=neck_items, extra_tgt_cells=extra_tgt, **kw) - if r is None: return None - path, neck = r - segs, vias = B.path_to_geom(net, path, neck, w, wneck, via_d) - # stubs at both ends - s0 = int(path[0]); s1 = int(path[-1]) - L0, c0 = s0 // P.N, s0 % P.N; L1, c1 = s1 // P.N, s1 % P.N - xy0 = cell_xy(c0 % P.NX, c0 // P.NX); xy1 = cell_xy(c1 % P.NX, c1 // P.NX) - w0 = wneck if (wneck and neck[0]) else w - w1 = wneck if (wneck and neck[-1]) else w - st = [] - a = self.end_stub(self.item_containing(src_items, xy0, L0), xy0, L0, w0) - a = self.safe_stub(net, a) - if a: st.append(a) - tl = list(tgt_items or []) + [it for it in self.net_items.get(net, [])] - b = self.end_stub(self.item_containing(tl, xy1, L1), xy1, L1, w1) - b = self.safe_stub(net, b) - if b: st.append(b) - items = B.commit(net, segs + st, vias, via_d, tag) - self.net_items.setdefault(net, []).extend(items) - return items - - # ----- plane nets: drop each top SMD pad to the bottom plane ----- - def route_plane_net(self, name, w=0.4, wneck=0.25, via_cost=12.0, via_cmult=2.0, order=None, only=None, skip=(), extra_planed=()): - B = self.B; net = self.nid(name) - idx = self.pads_by_net[net] - smd = [k for k in idx if not B.pads[k]["tht"] and (only is None or (B.pads[k]["ref"], B.pads[k]["num"]) in only) - and (B.pads[k]["ref"], B.pads[k]["num"]) not in skip] - # big pads (exposed pads) first - smd.sort(key=lambda k: -B.pads[k]["poly"].area) - planed = [B.pads[k]["item"] for k in idx if B.pads[k]["tht"]] + [it for it in self.net_items.get(net, []) if it.kind == "via"] + list(extra_planed) - nf = 0 - for k in smd: - p = B.pads[k] - if self.touches(p["item"], planed): - continue - bb = p["poly"].bounds - if bb[2] - bb[0] > 2.5 and bb[3] - bb[1] > 2.5: - c = p["poly"].centroid - items = B.commit(net, [], [(round((c.x - P.X0) / RES) * RES + P.X0, round((c.y - P.Y0) / RES) * RES + P.Y0)], 0.6, ("plane", name)) - self.net_items.setdefault(net, []).extend(items) - planed += items + [p["item"]] - continue - tgt_cells = B.cells_of(planed, layers=(0,)) if planed else None - items = self.do_route(net, [p["item"]], [], w, wneck, 0.6, goal_layer1=True, extra_tgt=tgt_cells, - via_cost=via_cost, via_cmult=via_cmult, bmult=50.0, turn=2.0, tag=("plane", name)) - if items is None: - self.failed.append((name, p["ref"], p["num"])); nf += 1; continue - planed += items + [p["item"]] - self.log.append((name, "plane pads", len(smd), "failed", nf)) - - def safe_stub(self, net, st): - """Keep a stub only where its copper clears every foreign item exactly; narrow it if needed.""" - if st is None: return None - L, a, b, w = st - line = LineString([a, b]) - x0, y0, x1, y1 = line.bounds - foreign = [it for it in self.B.items if it.net != net and L in it.layers and - it.bbox[0] < x1 + 1 and it.bbox[2] > x0 - 1 and it.bbox[1] < y1 + 1 and it.bbox[3] > y0 - 1] - shapes = [item_shape(it) for it in foreign] - for wd in (w, 0.25, 0.2): - if wd > w: continue - if all(line.distance(sh) >= wd / 2 + CLR + 0.005 for sh in shapes): - return (L, a, b, wd) - return None - - def touches(self, it, items): - for o in items: - if o.kind == "pad" and it.kind == "pad": - if it.geom.distance(o.geom) < 1e-6: return True - return False - - # ----- tree routing for an ordinary net ----- - def route_tree(self, name, root=None, w=None, wneck=None, via_d=None, **kw): - B = self.B; net = self.nid(name) - c = self.cls(name) - w = w or WIDTH[c] - if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 - via_d = via_d or VIA.get(c, 0.6) - idx = list(self.pads_by_net[net]) - if root is None: - root = idx[0] - else: - root = [k for k in idx if (B.pads[k]["ref"], B.pads[k]["num"]) == root][0] - tree_pads = {root} - tree_items = [B.pads[root]["item"]] - # pads that physically overlap tree copper are already connected - def absorb(): - changed = True - while changed: - changed = False - for k in idx: - if k in tree_pads: continue - pi = B.pads[k]["item"] - for it in tree_items: - if set(it.layers) & set(pi.layers) and (pi.geom.distance(Point(it.geom) if it.kind == "via" else (LineString(it.geom) if it.kind == "seg" else it.geom)) <= (it.w / 2 if it.kind != "pad" else 0) + 1e-6): - tree_pads.add(k); tree_items.append(pi); changed = True; break - absorb() - tries = {} - nfail = 0 - while len(tree_pads) < len(idx): - # nearest unconnected pad to the tree - best = None - for k in idx: - if k in tree_pads or tries.get(k, 0) >= 1: continue - p = B.pads[k] - dmin = min(math.hypot(p["x"] - B.pads[t]["x"], p["y"] - B.pads[t]["y"]) for t in tree_pads) - if best is None or dmin < best[0]: best = (dmin, k) - if best is None: break - k = best[1]; tries[k] = tries.get(k, 0) + 1 - items = self.do_route(net, tree_items, [B.pads[k]["item"]], w, wneck, via_d, tag=("tree", name), **kw) - if items is None: - nfail += 1; self.failed.append((name, B.pads[k]["ref"], B.pads[k]["num"])) - continue - tree_items.extend(items) - tree_pads.add(k); tree_items.append(B.pads[k]["item"]) - absorb() - self.log.append((name, "pads", len(idx), "unrouted", len(idx) - len(tree_pads))) - return len(idx) - len(tree_pads) - - def rip_net(self, name): - """Remove the router's copper of a net (kept existing copper stays).""" - net = self.nid(name) - items = self.net_items.pop(net, []) - keep = [it for it in items if it.owner and it.owner[0] == "existing"] - self.B.remove_items([it for it in items if not (it.owner and it.owner[0] == "existing")]) - if keep: - self.net_items[net] = keep - self.failed = [f for f in self.failed if f[0] != name] - - # ----- export ----- - def geometry(self): - segs, vias = [], [] - for net, items in self.net_items.items(): - name = self.B.netname[net] - for it in items: - if it.kind == "seg": - (a, b) = it.geom - segs.append(dict(net=name, layer="F.Cu" if it.layers[0] == 0 else "B.Cu", x1=a[0], y1=a[1], x2=b[0], y2=b[1], w=it.w)) - elif it.kind == "via": - vias.append(dict(net=name, x=it.geom[0], y=it.geom[1], d=it.w, drill=0.4 if it.w >= 0.8 else 0.3)) - return segs, vias - - def save(self, path): - segs, vias = self.geometry() - json.dump(dict(segs=segs, vias=vias, failed=self.failed, log=self.log), open(path, "w"), indent=0) - - def load(self, path): - d = json.load(open(path)) - B = self.B - for s in d["segs"]: - net = self.nid(s["net"]) - it = Item("seg", net, (0 if s["layer"] == "F.Cu" else 1,), ((s["x1"], s["y1"]), (s["x2"], s["y2"])), w=s["w"], owner=("load",)) - B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) - for v in d["vias"]: - net = self.nid(v["net"]) - it = Item("via", net, (0, 1), (v["x"], v["y"]), w=v["d"], owner=("load",)) - B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) - self.failed = [tuple(f) for f in d["failed"]] - - -def load_existing(self, d, keep=lambda t: True): - """Add tracks/vias from a board dump as fixed copper (they are saved with the result).""" - B = self.B - for s in d.get("tracks", []): - if s["net"] not in B.netid or not keep(s): continue - net = self.nid(s["net"]) - it = Item("seg", net, (0 if s["layer"] == "F.Cu" else 1,), ((s["x1"], s["y1"]), (s["x2"], s["y2"])), w=s["w"], owner=("existing",)) - B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) - for v in d.get("vias", []): - if v["net"] not in B.netid or not keep(v): continue - net = self.nid(v["net"]) - it = Item("via", net, (0, 1), (v["x"], v["y"]), w=v["d"], owner=("existing",)) - B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) - -Router.load_existing = load_existing - - -def mst(pts): - n = len(pts) - if n < 2: return [] - inT = [False] * n; inT[0] = True - dist = [math.hypot(pts[i][0] - pts[0][0], pts[i][1] - pts[0][1]) for i in range(n)] - par = [0] * n; edges = [] - for _ in range(n - 1): - k = min((i for i in range(n) if not inT[i]), key=lambda i: dist[i]) - inT[k] = True; edges.append((pts[par[k]], pts[k])) - for i in range(n): - if not inT[i]: - d = math.hypot(pts[i][0] - pts[k][0], pts[i][1] - pts[k][1]) - if d < dist[i]: dist[i] = d; par[i] = k - return edges - -def _wp(net, x, y, L): - return Item("via", net, (L,), (x, y), w=0.12, owner=("wp",)) - -def route_waypoints(self, name, root, wps, w, wneck, via_d, **kw): - """Route a trunk from the root pad through waypoints [(x, y, layer)]; returns tree items.""" - B = self.B; net = self.nid(name) - idx = self.pads_by_net[net] - rk = [k for k in idx if (B.pads[k]["ref"], B.pads[k]["num"]) == root][0] - tree = [B.pads[rk]["item"]] + list(self.net_items.get(net, [])) - for (x, y, L) in wps: - wp = _wp(net, x, y, L) - items = self.do_route(net, tree, [wp], w, wneck, via_d, tag=("trunk", name), **kw) - if items is None: - print("waypoint failed", name, x, y); return None - tree += items - return tree - -Router.route_waypoints = route_waypoints - -def route_tree_from(self, name, tree_items, w=None, wneck=None, via_d=None, skip=(), **kw): - """Prim-style completion of a net from existing tree items.""" - B = self.B; net = self.nid(name) - c = self.cls(name) - w = w or WIDTH[c] - if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 - via_d = via_d or VIA.get(c, 0.6) - idx = [k for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) not in skip] - tree_items = list(tree_items) - tree_pads = set() - def absorb(): - changed = True - while changed: - changed = False - for k in idx: - if k in tree_pads: continue - pi = B.pads[k]["item"] - for it in tree_items: - if it is pi: tree_pads.add(k); changed = True; break - if not (set(it.layers) & set(pi.layers)): continue - g = Point(it.geom) if it.kind == "via" else (LineString(it.geom) if it.kind == "seg" else it.geom) - if pi.geom.distance(g) <= (it.w / 2 if it.kind != "pad" else 0) + 1e-6: - tree_pads.add(k); tree_items.append(pi); changed = True; break - absorb() - pts = [] - for it in tree_items: - if it.kind == "seg": pts += list(it.geom) - elif it.kind == "via": pts.append(it.geom) - else: c0 = it.geom.centroid; pts.append((c0.x, c0.y)) - tries = set() - while True: - cand = [k for k in idx if k not in tree_pads and k not in tries] - if not cand: break - P = np.array(pts) - best = min(cand, key=lambda k: np.min(np.hypot(P[:, 0] - B.pads[k]["x"], P[:, 1] - B.pads[k]["y"]))) - tries.add(best) - items = self.do_route(net, tree_items, [B.pads[best]["item"]], w, wneck, via_d, tag=("tree", name), **kw) - if items is None: - self.failed.append((name, B.pads[best]["ref"], B.pads[best]["num"])); continue - tree_items.extend(items); tree_items.append(B.pads[best]["item"]); tree_pads.add(best) - for it in items: - if it.kind == "seg": pts += list(it.geom) - elif it.kind == "via": pts.append(it.geom) - c0 = B.pads[best]["item"].geom.centroid; pts.append((c0.x, c0.y)) - absorb() - un = len(idx) - len(tree_pads) - self.log.append((name, "pads", len(idx), "unrouted", un)) - return tree_items - -Router.route_tree_from = route_tree_from - -# ---------------- component-based net completion ---------------- -from shapely.strtree import STRtree - -def item_shape(it): - if it.kind == "pad": return it.geom - if it.kind == "seg": return LineString(it.geom).buffer(it.w / 2, quad_segs=4) - return Point(it.geom).buffer(it.w / 2, quad_segs=4) - -def components(items): - shapes = [item_shape(i) for i in items] - tree = STRtree(shapes) - par = list(range(len(items))) - def f(a): - while par[a] != a: par[a] = par[par[a]]; a = par[a] - return a - for i, s in enumerate(shapes): - for j in tree.query(s.buffer(1e-4)): - j = int(j) - if j <= i: continue - if not (set(items[i].layers) & set(items[j].layers)): continue - if s.distance(shapes[j]) <= 1e-4: - a, b = f(i), f(j) - if a != b: par[a] = b - groups = {} - for i in range(len(items)): groups.setdefault(f(i), []).append(items[i]) - return list(groups.values()) - -def net_items_all(self, net, pads_only_subset=None): - B = self.B - pads = [B.pads[k]["item"] for k in self.pads_by_net[net]] - return pads + list(self.net_items.get(net, [])) - -def comp_pts(comp): - pts = [] - for it in comp: - if it.kind == "seg": pts += list(it.geom) - elif it.kind == "via": pts.append(it.geom) - else: - c = it.geom.centroid; pts.append((c.x, c.y)) - return np.array(pts) - -def connect(self, name, root=None, pads=None, w=None, wneck=None, via_d=None, max_tries=2, **kw): - """Join all copper of a net (or only the components containing `pads`) into one.""" - B = self.B; net = self.nid(name) - c = self.cls(name) - w = w or WIDTH[c] - if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 - via_d = via_d or VIA.get(c, 0.6) - def padit(rn): - return [B.pads[k]["item"] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(rn)][0] - tries = {} - while True: - comps = components(net_items_all(self, net)) - if pads is not None: - want = [padit(p) for p in pads] - comps = [cp for cp in comps if any(any(x is it for x in cp) for it in want)] - if len(comps) <= 1: break - if root is not None: - ri = padit(root) - main = [cp for cp in comps if any(x is ri for x in cp)][0] - else: - main = max(comps, key=len) - others = [cp for cp in comps if cp is not main and tries.get(id(cp[0]), 0) < max_tries] - if not others: break - P = comp_pts(main) - def dist(cp): - Q = comp_pts(cp) - return np.min(np.hypot(P[:, None, 0] - Q[None, :, 0], P[:, None, 1] - Q[None, :, 1])) - tgt = min(others, key=dist) - tries[id(tgt[0])] = tries.get(id(tgt[0]), 0) + 1 - # heuristic point: nearest point of target to main - Q = comp_pts(tgt) - dd = np.min(np.hypot(Q[:, None, 0] - P[None, :, 0], Q[:, None, 1] - P[None, :, 1]), axis=1) - q = Q[int(np.argmin(dd))] - items = self.do_route(net, main, tgt, w, wneck, via_d, tag=("conn", name), hxy=(q[0], q[1]), **kw) - if items is None: - tp = [it for it in tgt if it.kind == "pad"] - lab = tp[0].owner[1:] if tp else ("copper",) - self.failed.append((name,) + tuple(lab)) - comps = components(net_items_all(self, net)) - self.log.append((name, "components", len(comps))) - return len(comps) - -Router.connect = connect - -def place_via(self, name, x, y, d=0.6): - B = self.B; net = self.nid(name) - i, j = xy_cell(x, y); x, y = cell_xy(i, j) - for L in (0, 1): - s = L * P.N + j * P.NX + i - fd = B.d2.ravel()[s] if B.n1.ravel()[s] == net else B.d1.ravel()[s] - if fd < d / 2 + CLR + M: - print("via blocked", name, x, y, fd); return None - items = B.commit(net, [], [(x, y)], d, ("via", name)) - self.net_items.setdefault(net, []).extend(items) - return items[0] -Router.place_via = place_via - - -def cap_value_uf(v): - import re - m = re.match(r"\s*([\d.]+)\s*([pnuµm]?)F?", v or "") - if not m: - return 0.0 - return float(m.group(1)) * {"p": 1e-6, "n": 1e-3, "u": 1, "µ": 1, "m": 1e3, "": 1}[m.group(2)] - - -def connect_decaps(self, name, **kw): - """Join each decoupling cap on net `name` 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; bulk caps (>= 4.7 uF) may also go to an inductor or ferrite (L*, FB*). - """ - B = self.B; net = self.nid(name) - pads = [B.pads[k] for k in self.pads_by_net[net]] - for p in pads: - f = B.fps[p["ref"]] - if not p["ref"].startswith("C"): - continue - other = [q for q in B.pads if q["ref"] == p["ref"] and q is not p] - if len(other) != 1 or other[0]["net"] < 0 or B.netname[other[0]["net"]] not in PLANE_NETS: - continue - nfp = {} - for q in B.pads: - nfp[q["ref"]] = nfp.get(q["ref"], 0) + 1 - bulk = cap_value_uf(f["value"]) >= 4.7 - cand = [q for q in pads if q["ref"] != p["ref"] and (nfp[q["ref"]] >= 4 and not q["ref"].startswith(("J", "TP")) - or (bulk and q["ref"].startswith(("L", "FB"))))] - if not cand: - continue - q = min(cand, key=lambda q: math.hypot(q["x"] - p["x"], q["y"] - p["y"])) - self.route_pair(name, (p["ref"], p["num"]), (q["ref"], q["num"]), **kw) - -Router.connect_decaps = connect_decaps - - -def route_pair(self, name, a, b, w=None, wneck=None, via_d=None, **kw): - """Route pad a to pad b directly (connect() would join to the nearest copper of the net).""" - B = self.B; net = self.nid(name) - c = self.cls(name) - w = w or WIDTH.get(c, 0.2) - if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 - via_d = via_d or VIA.get(c, 0.6) - pa = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(a)][0] - pb = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(b)][0] - if any(x is pb["item"] for cp in components(net_items_all(self, net)) if any(y is pa["item"] for y in cp) for x in cp): - return True - items = self.do_route(net, [pa["item"]], [pb["item"]], w, wneck, via_d, tag=("pair", name), **kw) - if items is None: - self.failed.append((name,) + tuple(b)) - return False - return True - -Router.route_pair = route_pair - - -def stitch(self, name, pitch=5.0, d=0.6, box=None): - """Stitching vias on a grid wherever a via of net `name` clears all foreign copper, - keep-outs and the board edge on both layers, and does not land in a pad.""" - B = self.B; net = self.nid(name) - x0, y0, x1, y1 = box or (P.X0, P.Y0, P.X1, P.Y1) - placed = [] - r = d / 2 + CLR + M - y = y0 + pitch / 2 - while y < y1: - x = x0 + pitch / 2 - while x < x1: - i, j = xy_cell(x, y) - ok = True - for L in (0, 1): - s = L * P.N + j * P.NX + i - fd = B.d2.ravel()[s] if B.n1.ravel()[s] == net else B.d1.ravel()[s] - if fd < r or B.padd.ravel()[s] < d / 2 + 0.05 or B.n1.ravel()[s] == net and B.d1.ravel()[s] < d / 2 + 0.3: - ok = False - if ok: - placed += B.commit(net, [], [cell_xy(i, j)], d, ("stitch", name)) - x += pitch - y += pitch - self.net_items.setdefault(net, []).extend(placed) - self.log.append((name, "stitching vias", len(placed))) - return placed - -Router.stitch = stitch - - -def tie(self, name, pad, xy, w=None, d=0.6, **kw): - """Tie a pad to a new via at xy (e.g. a THT ground pad that pours may not reach once - tracks close in around it). Run it before the tracks that would close it in.""" - B = self.B; net = self.nid(name) - v = self.place_via(name, xy[0], xy[1], d) - if v is None: - self.failed.append((name,) + tuple(pad)); return False - p = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(pad)][0] - items = self.do_route(net, [p["item"]], [v], w or WIDTH.get(self.cls(name), 0.2), 0.0, d, tag=("tie", name), **kw) - if items is None: - self.failed.append((name,) + tuple(pad)); return False - return True - -Router.tie = tie - - -# ---------------- rip-up and reroute ---------------- - -def route_net(self, name, cost=None, pads=None, **kw): - """connect() that remembers its cost maps and arguments, so repair() can redo it.""" - self.registry = getattr(self, "registry", {}) - self.registry.setdefault(name, []).append((cost, pads, kw)) - if cost is not None: - self.set_cost(**cost) - return self.connect(name, pads=pads, **kw) - -Router.route_net = route_net - - -def _redo(self, name): - for cost, pads, kw in self.registry.get(name, [(None, None, {})]): - if cost is not None: - self.set_cost(**cost) - self.connect(name, pads=pads, **kw) - - -def split_nets(self, skip=()): - """Nets (by name) whose copper is still in more than one piece.""" - out = [] - for net, idx in self.pads_by_net.items(): - name = self.B.netname[net] - if name in skip or len(idx) < 2: - continue - if len(components(net_items_all(self, net))) > 1: - out.append(name) - return out - -Router.split_nets = split_nets - - -def repair(self, rounds=4, radius=1.2, protect=(), skip=("GND",)): - """Rip-up and reroute: for each split net, remove the nets with copper within `radius` - of its unconnected pieces, route it first, then route the removed nets again. - Only nets routed through route_net() are ripped; `protect` nets are never ripped.""" - B = self.B - for rnd in range(rounds): - bad = self.split_nets(skip) - self.log.append(("repair", rnd, "split", bad)) - if not bad: - return [] - for name in bad: - net = self.nid(name) - comps = components(net_items_all(self, net)) - if len(comps) <= 1: - continue - main = max(comps, key=len) - shapes = [item_shape(it).buffer(radius) for cp in comps if cp is not main for it in cp if it.kind == "pad"] - if not shapes: - continue - victims = set() - for it in B.items: - if it.net < 0 or it.net == net or it.kind == "pad": - continue - vn = B.netname[it.net] - if vn in protect or vn in skip or vn not in self.registry: - continue - g = item_shape(it) - if any(g.intersects(s) for s in shapes): - victims.add(vn) - for vn in [name] + sorted(victims): - self.rip_net(vn) - _redo(self, name) - for vn in sorted(victims): - _redo(self, vn) - return self.split_nets(skip) - -Router.repair = repair diff --git a/tools/router/plot_routes.py b/tools/router/plot_routes.py index f7b3976..81b11c2 100644 --- a/tools/router/plot_routes.py +++ b/tools/router/plot_routes.py @@ -1,6 +1,6 @@ """Plot router output over the board's pads, one colour per net, failed pins marked. - tools/router/.venv/bin/python tools/router/plot_routes.py board.json routes.json out.png [x0 y0 x1 y1] + tools/.venv/bin/python tools/router/plot_routes.py board.json routes.json out.png [x0 y0 x1 y1] Pads are grey (F.Cu darker, B.Cu-only lighter); F.Cu tracks solid, B.Cu tracks dashed; vias are circles; every net is labelled at its longest segment; pins listed in diff --git a/tools/router/requirements.txt b/tools/router/requirements.txt deleted file mode 100644 index 3f89b23..0000000 --- a/tools/router/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -numpy -shapely -scipy -matplotlib 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)) +} |
