aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
committerLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
commita59e8e99243a895197a30d6cd6dd8d744dd606de (patch)
tree8910cc7476ff1317932257dfc8497a0f9ffc29f7
parent6f2bbe1f94e4321c329f92ec3420f6d32fd7b26d (diff)
downloadhw-toolchain-main.tar.gz
Keep only the current router: drop the Python router, router-rs -> routerHEADmain
The sequential Python/C router (pcbroute.py, pipeline.py, astar.c) is gone. The Rust crate takes its place at tools/router/, next to the KiCad I/O scripts it uses (dump_board.py, write_board.py, plot_routes.py). knowledge/tooling/router.md is now the Rust router's reference; the small Python venv for plots and 3D checks moves to tools/.venv (tools/requirements.txt). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--.gitignore6
-rw-r--r--AGENTS.md4
-rw-r--r--README.md6
-rw-r--r--knowledge/index.md4
-rw-r--r--knowledge/tooling/compose-board.md2
-rw-r--r--knowledge/tooling/height-check.md2
-rw-r--r--knowledge/tooling/housing-inputs.md2
-rw-r--r--knowledge/tooling/model-check.md2
-rw-r--r--knowledge/tooling/placement-check.md2
-rw-r--r--knowledge/tooling/placer.md4
-rw-r--r--knowledge/tooling/pnr.md19
-rw-r--r--knowledge/tooling/router.md194
-rw-r--r--knowledge/tooling/rust-router.md151
-rw-r--r--knowledge/tooling/thermal-vias.md2
-rw-r--r--tools/height_check.py2
-rw-r--r--tools/housing_inputs.py2
-rw-r--r--tools/placer/Cargo.toml2
-rw-r--r--tools/placer/src/main.rs2
-rw-r--r--tools/pnr.sh2
-rw-r--r--tools/pnr_eval.sh2
-rw-r--r--tools/requirements.txt (renamed from tools/router/requirements.txt)2
-rw-r--r--tools/router-rs/README.md13
-rw-r--r--tools/router/Cargo.lock (renamed from tools/router-rs/Cargo.lock)0
-rw-r--r--tools/router/Cargo.toml (renamed from tools/router-rs/Cargo.toml)2
-rw-r--r--tools/router/README.md20
-rw-r--r--tools/router/astar.c136
-rw-r--r--tools/router/pcbroute.py356
-rw-r--r--tools/router/pipeline.py638
-rw-r--r--tools/router/plot_routes.py2
-rw-r--r--tools/router/src/astar.rs (renamed from tools/router-rs/src/astar.rs)2
-rw-r--r--tools/router/src/board.rs (renamed from tools/router-rs/src/board.rs)4
-rw-r--r--tools/router/src/cleanup.rs (renamed from tools/router-rs/src/cleanup.rs)0
-rw-r--r--tools/router/src/config.rs (renamed from tools/router-rs/src/config.rs)0
-rw-r--r--tools/router/src/geom.rs (renamed from tools/router-rs/src/geom.rs)0
-rw-r--r--tools/router/src/io.rs (renamed from tools/router-rs/src/io.rs)0
-rw-r--r--tools/router/src/lib.rs (renamed from tools/router-rs/src/lib.rs)2
-rw-r--r--tools/router/src/main.rs (renamed from tools/router-rs/src/main.rs)0
-rw-r--r--tools/router/src/placement.rs (renamed from tools/router-rs/src/placement.rs)0
-rw-r--r--tools/router/src/pour.rs (renamed from tools/router-rs/src/pour.rs)0
-rw-r--r--tools/router/src/router.rs (renamed from tools/router-rs/src/router.rs)2
-rw-r--r--tools/router/src/run.rs (renamed from tools/router-rs/src/run.rs)0
-rw-r--r--tools/thermal_vias.py2
42 files changed, 178 insertions, 1415 deletions
diff --git a/.gitignore b/.gitignore
index 83ca88e..a6dacab 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,10 +3,8 @@ __pycache__/
# Rust and Python build output
tools/placer/target/
-tools/router-rs/target/
-tools/router/.venv/
-tools/router/libastar.dylib
-tools/router/libastar.so
+tools/router/target/
+tools/.venv/
# KiCad local state and backups
*-backups/
diff --git a/AGENTS.md b/AGENTS.md
index 71fa964..25cbb5b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -14,7 +14,7 @@ Conventions for AI-assisted hardware development with KiCad 10 for electronics,
| `projects/<name>/` | One directory per board: KiCad project, its enclosure, fab releases. |
| `CAD/` | Mechanical parts not tied to one project. |
| `datasheets/` | Datasheet PDFs, named `<MPN>.pdf` (keep these out of public repos; vendors own the copyright). |
-| `tools/` | Scripts and helpers: placer, routers, board edits, checks. |
+| `tools/` | Scripts and helpers: placer, router, board edits, checks. |
| `experiments/<name>/` | Tool experiments on copies of boards; scratch output in `out/` is git-ignored. |
### Libraries
@@ -49,7 +49,7 @@ KiCad's Python and `kicad-cli` are found by `tools/kicad_env.sh` (shell) and `to
| Task | Tool | Notes |
|---|---|---|
| Place and route a whole board | `sh tools/pnr.sh run/install DIR` | [pnr](knowledge/tooling/pnr.md) |
-| Route a placed board | `tools/router-rs` (`route.toml`) | [Rust router](knowledge/tooling/rust-router.md) |
+| Route a placed board | `tools/router` (`route.toml`) | [Router](knowledge/tooling/router.md) |
| Place parts | `tools/placer` (`placement.toml`) | [Placer](knowledge/tooling/placer.md) |
| Rate a placement | `tools/placement_check.py` | [Placement check](knowledge/tooling/placement-check.md) |
| Generate a schematic from Python | `tools/schgen.py` | [schgen](knowledge/tooling/schgen.md) |
diff --git a/README.md b/README.md
index f6cbf0b..0fc37d2 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
Tools and conventions for building KiCad boards with an AI agent in the loop. At its core is an automatic **placer and router for 2-layer KiCad boards**, written in Rust:
- **Placer** (`tools/placer`): simulated annealing over footprint positions and rotations. Its cost terms come from hand placement: ratsnest length and crossings, decoupling distance, fan-out bands, groups, links and replicated channels.
-- **Router** (`tools/router-rs`): a 0.05 mm grid router with negotiated congestion (PathFinder), so all nets route at once with no net order. It adds cleanup passes, a pour-connectivity model for the ground plane, escape lines for module interfaces, and a TOML config per board.
+- **Router** (`tools/router`): a 0.05 mm grid router with negotiated congestion (PathFinder), so all nets route at once with no net order. It adds cleanup passes, a pour-connectivity model for the ground plane, escape lines for module interfaces, and a TOML config per board.
- **pnr.sh**: places 32 candidates, routes all of them, checks the best ones with KiCad's DRC and installs the one you pick.
Around it are KiCad helpers in Python (headless "Update PCB from Schematic", a schematic generator, a placement checker, board composition from routed modules, connector tabs, thermal vias, 3D model checks), an `AGENTS.md` with repo conventions for coding agents, and the notes in `knowledge/` that record how the tools work and what was learned using them.
@@ -14,7 +14,7 @@ Requirements: KiCad 10 (`kicad-cli` and a Python with `pcbnew`) and Rust stable.
``` sh
git clone https://git.dnge.de/hw-toolchain && cd hw-toolchain
-cargo build --release --manifest-path tools/router-rs/Cargo.toml
+cargo build --release --manifest-path tools/router/Cargo.toml
cargo build --release --manifest-path tools/placer/Cargo.toml
# myboard/ holds myboard.kicad_pro/.kicad_sch/.kicad_pcb + placement.toml + route.toml
@@ -24,7 +24,7 @@ sh tools/pnr.sh install path/to/myboard rank_00
The minimal `placement.toml` and `route.toml`, routing an already placed board, and what to do when a board does not route: **[knowledge/tooling/pnr.md](knowledge/tooling/pnr.md)**.
-Reference: [Rust router and route.toml](knowledge/tooling/rust-router.md), [Placer and placement.toml](knowledge/tooling/placer.md), [Placement for routing](knowledge/topics/placement-for-routing.md). Everything else: [knowledge/index.md](knowledge/index.md).
+Reference: [Router and route.toml](knowledge/tooling/router.md), [Placer and placement.toml](knowledge/tooling/placer.md), [Placement for routing](knowledge/topics/placement-for-routing.md). Everything else: [knowledge/index.md](knowledge/index.md).
The tools are found relative to themselves. The board can live anywhere.
diff --git a/knowledge/index.md b/knowledge/index.md
index 58273ab..f9ed069 100644
--- a/knowledge/index.md
+++ b/knowledge/index.md
@@ -8,12 +8,10 @@ Entry point to the notes on the toolchain. Conventions: [AGENTS.md](../AGENTS.md
## Tooling
-[Rust router](tooling/rust-router.md)
+[Router](tooling/router.md)
[Placer (automatic placement)](tooling/placer.md)
-[Router (Python, sequential)](tooling/router.md)
-
[Placement check](tooling/placement-check.md)
[Schematic generator (schgen)](tooling/schgen.md)
diff --git a/knowledge/tooling/compose-board.md b/knowledge/tooling/compose-board.md
index 41c8b25..c850b9c 100644
--- a/knowledge/tooling/compose-board.md
+++ b/knowledge/tooling/compose-board.md
@@ -38,7 +38,7 @@ Close the board in KiCad first. The `.kicad_pro` is restored after SaveBoard.
## What it handles and what not
- Each tile's pours get priority `module priority + index`. Butting tiles' GND pours touch, which DRC reports as `zones_intersect` at equal priority.
-- Copies keep the module's routing exactly. Base-board nets between tiles stay unrouted; route them afterwards, e.g. with the [Rust router](rust-router.md) and the whole board as `[[fixed]]` copper.
+- Copies keep the module's routing exactly. Base-board nets between tiles stay unrouted; route them afterwards, e.g. with the [Router](router.md) and the whole board as `[[fixed]]` copper.
- Rotations other than 0/180° are not tested.
- KiCad API notes:
- `FOOTPRINT.Duplicate(addToParentGroup)` takes an argument; the other items' `Duplicate()` takes none.
diff --git a/knowledge/tooling/height-check.md b/knowledge/tooling/height-check.md
index f64fcff..745ef28 100644
--- a/knowledge/tooling/height-check.md
+++ b/knowledge/tooling/height-check.md
@@ -3,7 +3,7 @@
`tools/height_check.py` checks every top-side part of a DIN-rail board against the height limits of the printed housing ([DIN-rail board format](../topics/din-rail-format.md)).
``` sh
-tools/router/.venv/bin/python tools/height_check.py myboard/myboard.kicad_pcb
+tools/.venv/bin/python tools/height_check.py myboard/myboard.kicad_pcb
```
- **Housing footprint:** the board must carry `HW:DIN_Housing_<k>TE` (from `tools/din_template.py`). Its position is the housing centre, and `k` selects the dimensions. The limits come from `dims()` in `tools/din_template.py`, so the check, the footprint notes and the templates share one source.
diff --git a/knowledge/tooling/housing-inputs.md b/knowledge/tooling/housing-inputs.md
index a0e38ae..51e0916 100644
--- a/knowledge/tooling/housing-inputs.md
+++ b/knowledge/tooling/housing-inputs.md
@@ -3,7 +3,7 @@
`tools/housing_inputs.py` prints the numbers a board's DIN-rail housing needs: where each PCB tab is, what kind of opening each edge connector gets, and where the spacer frame must clear through-hole pins.
``` sh
-tools/router/.venv/bin/python tools/housing_inputs.py myboard/myboard.kicad_pcb
+tools/.venv/bin/python tools/housing_inputs.py myboard/myboard.kicad_pcb
```
- **Housing coordinates:** origin at the `HW:DIN_Housing_<k>TE` footprint, X = board x − centre, Y = centre − board y (Y up), so the numbers go straight into CAD box features.
diff --git a/knowledge/tooling/model-check.md b/knowledge/tooling/model-check.md
index a4ae99c..77dfefc 100644
--- a/knowledge/tooling/model-check.md
+++ b/knowledge/tooling/model-check.md
@@ -3,7 +3,7 @@
`tools/model_check.py` checks a footprint's 3D model placement against its pads, without opening KiCad.
``` sh
-tools/router/.venv/bin/python tools/model_check.py libraries/footprints/HW.pretty/<name>.kicad_mod [-D HW_LIB=...]
+tools/.venv/bin/python tools/model_check.py libraries/footprints/HW.pretty/<name>.kicad_mod [-D HW_LIB=...]
```
- **Transform:** it reads the footprint's `(model …)` offset, scale and rotation, loads the STEP file's vertices and applies KiCad's transform: scale, then rotate X, Y, Z (KiCad negates the angles), then offset. 3D Y points up, footprint Y points down.
diff --git a/knowledge/tooling/placement-check.md b/knowledge/tooling/placement-check.md
index bfe3897..7e4b6af 100644
--- a/knowledge/tooling/placement-check.md
+++ b/knowledge/tooling/placement-check.md
@@ -55,4 +55,4 @@ Score: 100, minus a penalty per finding, down to a minimum of 0:
- **Rotation suggestions cover only 2-pad parts.** For ICs and connectors, try the turns by hand.
- `tools/placement_slots.py board.kicad_pcb slots.json [--out moved.kicad_pcb]` hill-climbs which part sits in which of a set of fixed slots (and which way it faces) against this checker's penalties. See the script's docstring for the format. It does not replace setting decoupling caps by hand: it can swap two caps out of pin order, because the ratsnest does not care.
-Related: [Placer](placer.md), [Rust router](rust-router.md).
+Related: [Placer](placer.md), [Router](router.md).
diff --git a/knowledge/tooling/placer.md b/knowledge/tooling/placer.md
index 3e3493d..1f6dc59 100644
--- a/knowledge/tooling/placer.md
+++ b/knowledge/tooling/placer.md
@@ -1,6 +1,6 @@
# Placer
-`tools/placer/` places a board's footprints automatically by simulated annealing (Rust). The cost terms were learned from hand placement, and the [Rust router](rust-router.md) is the final judge: route the best candidates and pick by the routed result. [Place and route your own board](pnr.md) runs the whole chain.
+`tools/placer/` places a board's footprints automatically by simulated annealing (Rust). The cost terms were learned from hand placement, and the [Router](router.md) is the final judge: route the best candidates and pick by the routed result. [Place and route your own board](pnr.md) runs the whole chain.
## Run
@@ -121,4 +121,4 @@ What went wrong first, so it does not again:
- Not modelled, so check by hand: Kelvin taps, and references that `silk_refs.py` cannot fit (those go to F.Fab).
- Footprints with bottom-side pads (KiCad `_ThermalVias` variants) are refused. Use the plain footprint and [Thermal vias](thermal-vias.md) after routing.
-Related: [Placement check](placement-check.md), [Router (Python)](router.md), [Placement for routing](../topics/placement-for-routing.md).
+Related: [Placement check](placement-check.md), [Placement for routing](../topics/placement-for-routing.md).
diff --git a/knowledge/tooling/pnr.md b/knowledge/tooling/pnr.md
index 4d2489b..2326cbc 100644
--- a/knowledge/tooling/pnr.md
+++ b/knowledge/tooling/pnr.md
@@ -1,6 +1,6 @@
# Place and route your own board (pnr)
-`tools/pnr.sh` takes a KiCad board with its schematic and gives you routed candidates that KiCad's DRC has checked. It places the parts with the [Placer](placer.md) (simulated annealing, 32 runs), routes every candidate with the [Rust router](rust-router.md) (negotiated congestion), then runs apply → route → write → DRC on the best six and installs the one you choose.
+`tools/pnr.sh` takes a KiCad board with its schematic and gives you routed candidates that KiCad's DRC has checked. It places the parts with the [Placer](placer.md) (simulated annealing, 32 runs), routes every candidate with the [Router](router.md) (negotiated congestion), then runs apply → route → write → DRC on the best six and installs the one you choose.
You can also run only the router on a board you placed yourself. See [Route a placed board](#route-a-placed-board).
@@ -10,8 +10,9 @@ You can also run only the router on a board you placed yourself. See [Route a pl
- On macOS both come from `KiCad.app` and are found automatically.
- On Linux, the distribution package puts `pcbnew` into the system Python.
- Override with `KICAD_PYTHON=...` and `KICAD_CLI=...` ([tools/kicad_env.sh](../../tools/kicad_env.sh)).
-- **Rust** (stable, via rustup). `pnr.sh` builds the placer, and the router crate links into it. Build the router binary yourself once: `cargo build --release --manifest-path tools/router-rs/Cargo.toml`.
-- `python3` (3.8+) for the small JSON summaries.
+- **Rust** (stable, via rustup). `pnr.sh` builds the placer, and the router crate links into it. Build the router binary yourself once: `cargo build --release --manifest-path tools/router/Cargo.toml`.
+- `python3` (3.8+) for the small JSON summaries. For the plots and the 3D/height checks, make a venv once:
+ `python3 -m venv tools/.venv && tools/.venv/bin/pip install -r tools/requirements.txt` (numpy, matplotlib).
- Two-layer boards. The router uses F.Cu and B.Cu only.
## The board directory
@@ -20,7 +21,7 @@ You can also run only the router on a board you placed yourself. See [Route a pl
myboard/
myboard.kicad_pro / .kicad_sch / .kicad_pcb name = directory name
placement.toml what the placer must know (can be almost empty)
- route.toml how to route (see rust-router.md)
+ route.toml how to route (see router.md)
```
The board needs:
@@ -64,7 +65,7 @@ do = "cleanup"
do = "pour" # check the GND pour for islands and join them with vias
```
-That is enough for a first run. The [Placer](placer.md) and [Rust router](rust-router.md) pages list what else there is: groups and regions, decap pin assignments, links, pulls, replicated channels, bundles, escapes, cost zones and per-net settings.
+That is enough for a first run. The [Placer](placer.md) and [Router](router.md) pages list what else there is: groups and regions, decap pin assignments, links, pulls, replicated channels, bundles, escapes, cost zones and per-net settings.
## Run
@@ -97,13 +98,13 @@ Close the board in KiCad first. Both commands refuse while KiCad's lock file is
``` sh
. tools/kicad_env.sh
-R=tools/router-rs/target/release/router
+R=tools/router/target/release/router
$KPY tools/router/dump_board.py myboard.kicad_pcb /tmp/board.json
$R route /tmp/board.json route.toml /tmp/routes.json
$KPY tools/router/write_board.py myboard.kicad_pcb /tmp/routes.json /tmp/routed.kicad_pcb --replace --prune-vias GND
cp myboard.kicad_pro /tmp/routed.kicad_pro
$KC pcb drc --refill-zones /tmp/routed.kicad_pcb
-$KPY tools/router/plot_routes.py /tmp/board.json /tmp/routes.json /tmp/routes.png # needs the router venv
+tools/.venv/bin/python tools/router/plot_routes.py /tmp/board.json /tmp/routes.json /tmp/routes.png
```
The last line of `route` reads `RESULT split=0 failed=0 islands=0 vias=… length=…`. Zeros mean complete. KiCad's DRC is the judge.
@@ -113,8 +114,8 @@ The last line of `route` reads `RESULT split=0 failed=0 islands=0 vias=… lengt
Most failures come from the placement, not the router:
- **A pin that never connects** on every candidate: something walls it in. Look at the plot, then give it a fan-out band, keep a corridor free, or raise the net's `priority` in `route.toml`.
-- **Interface lines of a block** with one pad each: add `[[escape]]` lines (see the [Rust router](rust-router.md) page), or complete boards will wall them in.
+- **Interface lines of a block** with one pad each: add `[[escape]]` lines (see the [Router](router.md) page), or complete boards will wall them in.
- **Fine-pitch parts off the 0.05 mm grid**: put fixed parts' origins on multiples of 0.05 mm.
- **Placer cost does not predict routability.** Route more candidates (`RUNS=64`) rather than tuning the cost weights.
-See [Placement for routing](../topics/placement-for-routing.md) for the rules behind this. The [Rust router](rust-router.md) page has the lessons that came out of real boards.
+See [Placement for routing](../topics/placement-for-routing.md) for the rules behind this. The [Router](router.md) page has the lessons that came out of real boards.
diff --git a/knowledge/tooling/router.md b/knowledge/tooling/router.md
index 136f1e8..c6c615f 100644
--- a/knowledge/tooling/router.md
+++ b/knowledge/tooling/router.md
@@ -1,95 +1,151 @@
-# Router (Python)
+# Router
-`tools/router/` is the scripted grid maze router that came before the [Rust router](rust-router.md). It routes one net at a time, in an order the board's own `route.py` script sets. New boards should use the Rust router, with a `route.toml` instead of a `route.py`. This router stays for existing scripts. Its board I/O (`dump_board.py`, `write_board.py`, `plot_routes.py`) is shared by both.
+`tools/router/` routes 2-layer KiCad boards on a 0.05 mm grid with **negotiated congestion** (PathFinder): all nets at once, so there is no net order to get wrong. The Rust crate sits next to its KiCad I/O scripts: `dump_board.py` exports the board, `write_board.py` writes the routes back, and `plot_routes.py` draws them (each net in its own colour, B.Cu dashed, failed pins crossed). It is also a library: the [Placer](placer.md) links it to route its candidates in-process. KiCad's DRC stays the judge.
-## Setup
+For the end-to-end flow on your own board, start with [Place and route your own board](pnr.md).
+
+## Use
``` sh
-python3 -m venv tools/router/.venv
-tools/router/.venv/bin/pip install -r tools/router/requirements.txt # numpy, shapely, scipy, matplotlib
+cargo build --release --manifest-path tools/router/Cargo.toml
+. tools/kicad_env.sh # KPY, KC
+R=tools/router/target/release/router
+$KPY tools/router/dump_board.py board.kicad_pcb board.json
+$R route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL]
+$R place board.json placement.json moved.json # move parts to a placer result, without KiCad
+$KPY tools/router/write_board.py board.kicad_pcb routes.json out.kicad_pcb --replace [--zones zones.json] --prune-vias GND
+$KC pcb drc --refill-zones out.kicad_pcb
```
-The C core (`astar.c`) compiles itself with `cc` on first import.
+The last line of `route` is:
-## How it works
+```
+RESULT split=<nets in pieces> failed=<connections> islands=<plane-net pad groups the pours leave apart>
+ vias= length= bcu= neck=<mm narrower than the net's width, outside pads> score=<[rank]> time=
+```
-- **Grid:** 0.05 mm cells on F.Cu and B.Cu.
- - Exact distance fields hold, for every cell, the distance to the nearest copper and to the nearest copper of another net.
- - A track of width w fits where foreign copper is at least w/2 + 0.2 mm away.
- - Near pads it may neck down (e.g. 0.5 mm power to 0.2 mm), so fine-pitch pins can be entered.
-- **Search** (`astar.c`): 8-direction A* with costs for vias (default 40 cells), turns and B.Cu (`bmult`, default 3), plus optional cost maps per layer. No via lands in a pad.
-- **Strategies** (`pipeline.py`):
- - `route_plane_net("GND")`: each SMD ground pad gets its own via to the B.Cu plane;
- - `connect(net)`: joins all copper of a net, nearest piece first;
- - `route_pair(net, a, b)`: pad to pad;
- - `connect_decaps(net)`: each decoupling cap to its own nearest IC pin, before the rest of the net;
- - `tie(net, pad, xy)`: pad to a new via;
- - `route_waypoints(...)`: a trunk through fixed points;
- - `stitch("GND", pitch)`: stitching vias wherever they fit (finished boards only);
- - `load_existing(dump)`: fixed copper, e.g. a planned bus, loaded before anything else;
- - `route_net(...)` + `repair()`: rip-up and reroute.
-- **Board I/O** (KiCad's Python):
- - `dump_board.py` writes pads, net classes and widths, keep-outs, zones and existing copper to JSON. The output is sorted, so the same placement always gives the same dump. KiCad orders footprints by UUID, which a regenerated board draws anew, and the router's result depends on pad order.
- - `write_board.py` writes tracks, vias and pours (`--replace`, `--diff`, `--zones`, `--prune-vias GND`). `--diff` changes only the items that differ, so untouched copper keeps its exact drill and width. Every mode restores the `.kicad_pro` that `SaveBoard` resets ([KiCad notes](kicad.md)).
-- **Debugging:** `plot_routes.py board.json routes.json out.png [x0 y0 x1 y1]` draws each net in its own colour with its name, B.Cu dashed and failed pins crossed. KiCad's SVG export cannot show which net blocks which; this can.
+`ROUTER_TIMES=1` prints each step's time. `ROUTER_TRACE=1` prints each search and the conflicts left after the last negotiation round.
-## Workflow
+`write_board.py` options:
-``` sh
-. tools/kicad_env.sh # KPY, KC
-VPY=tools/router/.venv/bin/python
-$KPY tools/router/dump_board.py board.kicad_pcb /tmp/board.json
-$VPY my_board/route.py /tmp/board.json /tmp/routes.json # the board's own script
-$VPY tools/router/plot_routes.py /tmp/board.json /tmp/routes.json /tmp/z.png 110 90 130 110
-$KPY tools/router/write_board.py board.kicad_pcb /tmp/routes.json board.kicad_pcb --replace --prune-vias GND
-$KC pcb drc --refill-zones --schematic-parity board.kicad_pcb
-$KPY tools/silk_refs.py board.kicad_pcb # references off pads and each other
-```
+- `--replace` deletes the board's tracks and vias first.
+- `--diff` changes only what differs from the board. Use it when `routes.json` also holds the board's own copper, for example a `[[fixed]]` dump, so that untouched copper keeps its exact drill and width.
+- `--prune-vias NET` removes that net's vias that connect nothing.
+- `--zones` adds pours from a JSON file.
-`silk_refs.py` keeps each reference 0.5 mm inside the real board outline, clear of pads, vias and other silk.
+All three restore the `.kicad_pro` that pcbnew's `SaveBoard` would reset.
-Close the board in KiCad and check for its `~*.lck` file before writing. Run with `PYTHONHASHSEED=0` so a rebuild gives the same board.
+## route.toml
-To take parts off a routed board, use `tools/prune_copper.py board.kicad_pcb --remove J3 [--clip X0,Y0,X1,Y1] [--netlist board.net]`. It does four things:
+The doc comment of `src/config.rs` is the full reference. In short:
-1. deletes the footprints;
-2. optionally cuts the outline down, clipping zones and deleting copper outside;
-3. renames nets to the schematic's names;
-4. deletes whatever DRC would call dangling, repeating until nothing is left (KiCad's own `TestTrackEndpointDangling`).
+### Board-wide
-## Order that works (sequential routing)
+- `prefix`: a sheet path such as `"/My Sheet/"` that net names in the file may leave out.
+- `plane_nets`: nets that reach their pads through pours and drop vias, usually `["GND"]`. With `area = "pours"`, give a sheet-local plane its full name (e.g. `/Iso/GND_ISO`). Zones are matched literally, and a missing pour silently shrinks the area.
+- `area`: limits where copper may go.
+ - `"pours"` keeps all copper inside the plane nets' pours, e.g. a design block that will be pasted onto a larger board.
+ - `[[x, y], ...]` gives a polygon instead.
+ - `area_margin` (mm) keeps copper that far inside.
+- `[[bundle]] nets = [...]`: pairs and buses that should run side by side. A step that does not hug a partner's copper costs `attract` more. Set `attract` on the negotiate step (0.5 works well); the cleanup step defaults to 0.5. It is soft attraction, not coupled routing.
+- `[[fixed]]`: copper loaded before the steps.
+ - `name` + `--fixed NAME=FILE`, or `path` relative to the toml.
+ - A JSON of tracks and vias, or a board dump with `unmoved = true` (keep the copper of nets whose parts did not move).
+ - `done = true` marks its nets complete. `protect = true` protects it from rip-up.
+ - `exclude = [...]`, `optional = true`.
+- `[costs.NAME]`: cost maps.
+ - `zones = [{ layer = "F"|"B", fp = "U1", rect = [x0, y0, x1, y1], cost = 200 }]`. Rectangles are relative to the footprint origin and do not turn with it. Without `fp` they are absolute. Zones add up.
+ - `rudy = { scale, max }`: RUDY congestion of the pads' MSTs.
+ - `none` is empty. A step's `cost` stays set for the following steps.
+- `[nets.NAME]`: per-net settings.
+ - `w` (width) and `wneck` (neck width).
+ - `neck_zone`: how far from a pad a track may neck; default 1 mm.
+ - `root` (`"U1:19"`, where the net's tree grows from) and `decaps` (each decoupling cap to its pin first).
+ - `priority` (higher routes first), `cost`, `bmult` (B.Cu multiplier) and `via_cost`.
+ - `[[nets.NAME.join]]` pad pairs routed first: `{ a = "U1:4", b = "U1:8", w, wneck, cost, allow_via }`.
+- `[[escape]]`: reserves a way out for nets that leave a block, such as a module's interface lines with one pad each.
+ - Keys: `nets = [...]`, `from = [x, y]`, `to = [x, y]`, `size` (default 0.25), `w`, `keep`.
+ - It adds one virtual pad per net, evenly spaced from `from` to `to` and snapped to the grid, and routes them in the same negotiation.
+ - Their copper is left out of `routes.json` unless `keep = true`.
+ - A board only counts as complete if every interface line can still reach the edge.
+- `[rank]`: how routed boards compare (used by `placer --route` and `pnr.sh`).
+ - First: split nets, failed connections, pour islands.
+ - Then a score: Σ length × net weight (`nets = [{ match = "*/ETH_*", weight = 2 }]`, `*` globs) + `via_mm` (2) × vias + `neck_mm` (2) × necked mm + `bcu_mm` (0) × B.Cu mm.
-1. **Keep hand routing** of nets whose parts did not move (`load_existing`). Those nets are protected from rip-up.
-2. **Ground:** fixed vias under a QFP without an exposed pad, its GND pins to those vias, then every other SMD ground pad to its own via. If signal lines will close in THT ground pads, tie them to their own via now.
-3. **The fine-pitch IC's own pins first:** crystal, regulator caps, bias resistor. Join analog supply pins inside the pad ring, then the PHY pairs, then control and bus lines.
-4. **Supplies after the signals:** decaps pad to pad, then the rest of each rail. Wide power trunks go around signals easily; signals cannot get past an early trunk.
-5. **Other signals, shortest first.**
-6. `repair()`, then pours, then DRC.
+### Steps (`[[step]] do = ...`, in order)
-**Buses between two ICs:** do not leave them to a one-net-at-a-time router; a six-line bus took 37 vias that way. Instead:
+| Step | What it does |
+| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `negotiate` | routes every net still in pieces at once. `planes = true` negotiates the plane nets' pad drops too, so they give way to signals. Also: `cost`, `rounds`, `pres`, `pres_mult`, `hist`, `margin` (search window around each connection, default 1.5 mm), `attract` |
+| `repair` | rips up what lies around failures and routes again (`rounds`) |
+| `cleanup` | reroutes each net once with the rest fixed: shorter, fewer vias, tighter octilinear shortcuts, necks widened (`neck`, default 4) |
+| `pour` | models the plane net's pour fill, finds islands that leave pads apart and joins them with vias (`fix`, default true; `d` via size) |
+| `via` | fixed vias, e.g. ground vias inside a QFP pad ring |
+| `plane` | each SMD pad of a plane net drops to its own via before the negotiation (`only`, `skip`) |
+| `connect`, `pair`, `decaps`, `rest`, `tie`, `stitch` | ordered steps (outside the negotiation): nets in a given order, pad to pad, caps to pins, everything left, pad to a new via, stitching vias (finished boards only) |
-1. Work out the crossings from the pin orders on both ends.
-2. Give each layer an order that needs no crossings.
-3. Write the geometry as fixed copper and route the rest around it.
+`label = "x"` on a step and `--stop x` end the run after that step.
-That took 8 vias. The Rust router's negotiation makes this mostly unnecessary.
+Two typical recipes:
-## Cost zones
+- `negotiate` (with `planes = true`) → `repair` → `cleanup` → `pour`.
+- `via` + `plane` for ground first, then `negotiate` → `repair` → `cleanup`.
-- **F.Cu under a module** with pads underneath, and **inside a QFP pad ring** (reserved for its ground vias): cost 200 per cell. That is effectively forbidden, but not a hard keep-out, so GND drops can still use it.
-- **Block tile:** make the board outline the tile plus the copper-to-edge clearance on the sides that face other blocks. The router and DRC then keep all copper inside the tile.
-- **Quiet zone on B.Cu** under a crystal, PHY or Ethernet IC: +10 per cell for signals, which keeps the ground plane whole where it matters.
-- **A failure within 0.4 s** means a pin is enclosed, not that the search budget ran out. Test the net alone on the empty board, and after each phase, to find which phase encloses it.
+## How it works
-## Rip-up and reroute
+- **Grid**: 0.05 mm, origin snapped to a multiple of 0.05 mm (the edge clearance uses the true outline), so pads of parts on the placer's grid sit on cell centres.
+- **Fields** (`board.rs`):
+ - Per cell and layer: the distance to and net of the nearest copper, and the distance to the nearest copper of another net.
+ - Board edge, NPTH and keep-outs are static no-net copper.
+ - Footprint copper that is not a pad (a net tie's bridge) is static too, sampled every 0.025 mm.
+ - A track of width w fits where foreign copper is at least w/2 + clearance away. It may neck to `wneck` only within `neck_zone` of the pads it joins.
+ - Separate fields keep vias out of SMD pads and drill edges 0.25 mm apart (KiCad's `min_hole_to_hole`).
+- **Search** (`astar.rs`): 8-direction A* with turn cost (no turns over 90°), via cost, B.Cu multiplier (3) and cost maps. It uses a radix heap, which works because the octile heuristic is consistent.
+- **Negotiation** (`router.rs`):
+ - Every net in pieces is a job. Tracks routed in negotiation are soft.
+ - A step onto other nets' soft copper costs (base + history) × (1 + present factor).
+ - After each round only the conflicting connections are rerouted. A net that stays in conflict for three rounds is rerouted whole with a wider window.
+ - Present factor 4, × 1.5 per round, up to 30 rounds.
+ - Whatever still conflicts is routed with soft copper made hard, trying every order of up to four such nets. Then all copper is hardened and dangling remnants are pruned.
+- **Cleanup** (`cleanup.rs`):
+ - Each net is rerouted with the rest fixed. Steps that hug other copper are cheaper, so lines bundle.
+ - A reroute is kept if it is at most 2 % worse (length + 2 mm per via + 2 × necked mm) and splits nothing.
+ - Vias that are not needed go.
+ - Same-layer chains are pulled tight to octilinear shortcuts, and necked tracks widen wherever clearance allows.
+- **Pours** (`pour.rs`):
+ - A plane net's pours fill where foreign copper is at least clearance + half the minimum fill width away.
+ - The net's copper joins an island where tracks and vias touch it, and where pads are within thermal-gap + spoke distance.
+ - Pad groups left apart get a via or a short track to the main island. Whatever stays apart is reported as `islands`.
+- **Placer link**:
+ - `placer run ... --route board.json route.toml --route-top K` routes the best K placements in parallel and ranks them.
+ - `placer route PROBLEM CONFIG board.json route.toml OUT PLACEMENT...` does the same for existing placement files.
+ - Memory: about 160 MB per board routed at once.
-`route_net(name, cost=..., **kw)` records each connection's cost map and settings. `repair(rounds, protect=kept_nets)` works in four steps:
+## Lessons from real boards
-1. finds nets still in several pieces;
-2. removes the nets with copper within 1.2 mm of the unconnected pieces;
-3. routes the failed net first;
-4. routes the removed nets again with their recorded settings.
+- **Net order was the limit, and negotiation removes it.** With the same grid, costs and A*, a one-net-at-a-time router completed 5 of 32 placer candidates on a dense ESP32 + Ethernet board. Negotiation completed 20, and later 26 with bundle attraction.
+- **PathFinder's multiplicative form matters.** With additive costs (step + present + history), the present factor swamps history, and two nets keep trading the same crossing. (base + history) × (1 + present) converged in about 12 rounds.
+- **Hard pre-routes can box in pins** that negotiation cannot free later. Prefer `planes = true` over `plane` steps when ground drops wall in signal pins.
+- **Interface escapes in a block.** Without `[[escape]]`, "complete" boards walled in an MCU's interface pins with supply and crystal tracks.
+ - Don't put cost zones on the escape channels. They price the layer for the escape lines too, which then drop to B.Cu with a via at each fine-pitch pin.
+ - Space escape pads at least 0.5 mm apart for 0.2 mm lines. Lines need 0.415 mm, and at 0.45 mm the slack is less than one grid step.
+ - Choose `from`/`to` so that the pitch is a multiple of 0.05 mm.
+ - Keep the escape corridor free of parts. Covering the whole pin side with a footprint rule area works.
+- **Fine-pitch parts must sit on the 0.05 mm grid.** A QFN 0.01 mm off the cells failed random pins on every placement. Put fixed parts' origins on multiples of 0.05 mm. The placer keeps its own parts on the grid.
+- **0.4 mm QFN vs 0.5 mm LQFP**: two 0.2 mm tracks cannot leave neighbouring 0.4 mm-pitch pins side by side. If nearly every pin is used, all lines must neck (`wneck = 0.15`, `neck_zone = 2`). When a fine-pitch MCU has many consecutive pins in use, compare packages before tuning the router: the LQFP routed every time, the QFN never.
+- **Routing a base board between fixed blocks**:
+ - Load the whole board dump as `[[fixed]] unmoved = true, protect = true` and route only what is still apart.
+ - Raise `margin` on the negotiate step (e.g. 20). Otherwise the 1.5 mm window never reaches the free channel between blocks, and lines cut through them.
+ - Write the result with `write_board.py --diff`.
+- **Rerouting a few nets on a finished board**: strip those nets' copper from a copy, dump it, and load the dump as `[[fixed]] unmoved = true` **without** `done = true`. With `done = true` the stripped nets count as done too, and negotiate gets no jobs.
+- **Starved thermal spokes**: the router does not model thermal-relief spokes. Through-hole plane pads next to signal pins can end with one spoke (KiCad DRC `starved_thermal`). On small pours, solid zone connections for those pads fix it.
+- **Bundle attraction only works in the negotiation.** In the cleanup the space beside a partner is already taken. With `attract = 0.5` on negotiate, pair coupling went from about 2–9 % to about 30 %, with fewer vias. Too strong (2) pulls nets off their short paths.
+- **Placement measures do not predict routability.** Spearman |ρ| ≤ 0.3 between unconnected pins and placer cost, crossings, RUDY or a coarse global route. Rank by routing instead (`--route`).
+- A weighted A* heuristic (1.5–2) made negotiation slower and worse. Search windows and partial reroutes were what helped.
-It cannot fix placement. If a net fails alone on the empty board, or fails again after repair, change the placement ([Placement for routing](../topics/placement-for-routing.md)).
+## Limits
-Related: [Placement check](placement-check.md), [Net classes](../topics/netclasses.md).
+- Two layers only. Footprints with bottom-side pads are refused: use the plain exposed-pad footprint, then [Thermal vias](thermal-vias.md) after routing.
+- Differential pairs are routed as single nets; bundles only attract.
+- No thermal-spoke check in the pour model.
+- Negotiated boards take 4–15 s each on a 50-part board, single-threaded per board.
diff --git a/knowledge/tooling/rust-router.md b/knowledge/tooling/rust-router.md
deleted file mode 100644
index 430fbd2..0000000
--- a/knowledge/tooling/rust-router.md
+++ /dev/null
@@ -1,151 +0,0 @@
-# Rust router
-
-`tools/router-rs/` routes 2-layer KiCad boards on a 0.05 mm grid with **negotiated congestion** (PathFinder): all nets at once, so there is no net order to get wrong. It reads a board dump from `tools/router/dump_board.py` and writes `routes.json` for `tools/router/write_board.py`. It is also a library: the [Placer](placer.md) links it to route its candidates in-process. KiCad's DRC stays the judge.
-
-For the end-to-end flow on your own board, start with [Place and route your own board](pnr.md).
-
-## Use
-
-``` sh
-cargo build --release --manifest-path tools/router-rs/Cargo.toml
-. tools/kicad_env.sh # KPY, KC
-R=tools/router-rs/target/release/router
-$KPY tools/router/dump_board.py board.kicad_pcb board.json
-$R route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL]
-$R place board.json placement.json moved.json # move parts to a placer result, without KiCad
-$KPY tools/router/write_board.py board.kicad_pcb routes.json out.kicad_pcb --replace [--zones zones.json] --prune-vias GND
-$KC pcb drc --refill-zones out.kicad_pcb
-```
-
-The last line of `route` is:
-
-```
-RESULT split=<nets in pieces> failed=<connections> islands=<plane-net pad groups the pours leave apart>
- vias= length= bcu= neck=<mm narrower than the net's width, outside pads> score=<[rank]> time=
-```
-
-`ROUTER_TIMES=1` prints each step's time. `ROUTER_TRACE=1` prints each search and the conflicts left after the last negotiation round.
-
-`write_board.py` options:
-
-- `--replace` deletes the board's tracks and vias first.
-- `--diff` changes only what differs from the board. Use it when `routes.json` also holds the board's own copper, for example a `[[fixed]]` dump, so that untouched copper keeps its exact drill and width.
-- `--prune-vias NET` removes that net's vias that connect nothing.
-- `--zones` adds pours from a JSON file.
-
-All three restore the `.kicad_pro` that pcbnew's `SaveBoard` would reset.
-
-## route.toml
-
-The doc comment of `src/config.rs` is the full reference. In short:
-
-### Board-wide
-
-- `prefix`: a sheet path such as `"/My Sheet/"` that net names in the file may leave out.
-- `plane_nets`: nets that reach their pads through pours and drop vias, usually `["GND"]`. With `area = "pours"`, give a sheet-local plane its full name (e.g. `/Iso/GND_ISO`). Zones are matched literally, and a missing pour silently shrinks the area.
-- `area`: limits where copper may go.
- - `"pours"` keeps all copper inside the plane nets' pours, e.g. a design block that will be pasted onto a larger board.
- - `[[x, y], ...]` gives a polygon instead.
- - `area_margin` (mm) keeps copper that far inside.
-- `[[bundle]] nets = [...]`: pairs and buses that should run side by side. A step that does not hug a partner's copper costs `attract` more. Set `attract` on the negotiate step (0.5 works well); the cleanup step defaults to 0.5. It is soft attraction, not coupled routing.
-- `[[fixed]]`: copper loaded before the steps.
- - `name` + `--fixed NAME=FILE`, or `path` relative to the toml.
- - A JSON of tracks and vias, or a board dump with `unmoved = true` (keep the copper of nets whose parts did not move).
- - `done = true` marks its nets complete. `protect = true` protects it from rip-up.
- - `exclude = [...]`, `optional = true`.
-- `[costs.NAME]`: cost maps.
- - `zones = [{ layer = "F"|"B", fp = "U1", rect = [x0, y0, x1, y1], cost = 200 }]`. Rectangles are relative to the footprint origin and do not turn with it. Without `fp` they are absolute. Zones add up.
- - `rudy = { scale, max }`: RUDY congestion of the pads' MSTs.
- - `none` is empty. A step's `cost` stays set for the following steps.
-- `[nets.NAME]`: per-net settings.
- - `w` (width) and `wneck` (neck width).
- - `neck_zone`: how far from a pad a track may neck; default 1 mm.
- - `root` (`"U1:19"`, where the net's tree grows from) and `decaps` (each decoupling cap to its pin first).
- - `priority` (higher routes first), `cost`, `bmult` (B.Cu multiplier) and `via_cost`.
- - `[[nets.NAME.join]]` pad pairs routed first: `{ a = "U1:4", b = "U1:8", w, wneck, cost, allow_via }`.
-- `[[escape]]`: reserves a way out for nets that leave a block, such as a module's interface lines with one pad each.
- - Keys: `nets = [...]`, `from = [x, y]`, `to = [x, y]`, `size` (default 0.25), `w`, `keep`.
- - It adds one virtual pad per net, evenly spaced from `from` to `to` and snapped to the grid, and routes them in the same negotiation.
- - Their copper is left out of `routes.json` unless `keep = true`.
- - A board only counts as complete if every interface line can still reach the edge.
-- `[rank]`: how routed boards compare (used by `placer --route` and `pnr.sh`).
- - First: split nets, failed connections, pour islands.
- - Then a score: Σ length × net weight (`nets = [{ match = "*/ETH_*", weight = 2 }]`, `*` globs) + `via_mm` (2) × vias + `neck_mm` (2) × necked mm + `bcu_mm` (0) × B.Cu mm.
-
-### Steps (`[[step]] do = ...`, in order)
-
-| Step | What it does |
-| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `negotiate` | routes every net still in pieces at once. `planes = true` negotiates the plane nets' pad drops too, so they give way to signals. Also: `cost`, `rounds`, `pres`, `pres_mult`, `hist`, `margin` (search window around each connection, default 1.5 mm), `attract` |
-| `repair` | rips up what lies around failures and routes again (`rounds`) |
-| `cleanup` | reroutes each net once with the rest fixed: shorter, fewer vias, tighter octilinear shortcuts, necks widened (`neck`, default 4) |
-| `pour` | models the plane net's pour fill, finds islands that leave pads apart and joins them with vias (`fix`, default true; `d` via size) |
-| `via` | fixed vias, e.g. ground vias inside a QFP pad ring |
-| `plane` | each SMD pad of a plane net drops to its own via before the negotiation (`only`, `skip`) |
-| `connect`, `pair`, `decaps`, `rest`, `tie`, `stitch` | sequential steps: nets in a given order, pad to pad, caps to pins, everything left, pad to a new via, stitching vias (finished boards only) |
-
-`label = "x"` on a step and `--stop x` end the run after that step.
-
-Two typical recipes:
-
-- `negotiate` (with `planes = true`) → `repair` → `cleanup` → `pour`.
-- `via` + `plane` for ground first, then `negotiate` → `repair` → `cleanup`.
-
-## How it works
-
-- **Grid**: 0.05 mm, origin snapped to a multiple of 0.05 mm (the edge clearance uses the true outline), so pads of parts on the placer's grid sit on cell centres.
-- **Fields** (`board.rs`):
- - Per cell and layer: the distance to and net of the nearest copper, and the distance to the nearest copper of another net.
- - Board edge, NPTH and keep-outs are static no-net copper.
- - Footprint copper that is not a pad (a net tie's bridge) is static too, sampled every 0.025 mm.
- - A track of width w fits where foreign copper is at least w/2 + clearance away. It may neck to `wneck` only within `neck_zone` of the pads it joins.
- - Separate fields keep vias out of SMD pads and drill edges 0.25 mm apart (KiCad's `min_hole_to_hole`).
-- **Search** (`astar.rs`): 8-direction A* with turn cost (no turns over 90°), via cost, B.Cu multiplier (3) and cost maps. It uses a radix heap, which works because the octile heuristic is consistent.
-- **Negotiation** (`router.rs`):
- - Every net in pieces is a job. Tracks routed in negotiation are soft.
- - A step onto other nets' soft copper costs (base + history) × (1 + present factor).
- - After each round only the conflicting connections are rerouted. A net that stays in conflict for three rounds is rerouted whole with a wider window.
- - Present factor 4, × 1.5 per round, up to 30 rounds.
- - Whatever still conflicts is routed with soft copper made hard, trying every order of up to four such nets. Then all copper is hardened and dangling remnants are pruned.
-- **Cleanup** (`cleanup.rs`):
- - Each net is rerouted with the rest fixed. Steps that hug other copper are cheaper, so lines bundle.
- - A reroute is kept if it is at most 2 % worse (length + 2 mm per via + 2 × necked mm) and splits nothing.
- - Vias that are not needed go.
- - Same-layer chains are pulled tight to octilinear shortcuts, and necked tracks widen wherever clearance allows.
-- **Pours** (`pour.rs`):
- - A plane net's pours fill where foreign copper is at least clearance + half the minimum fill width away.
- - The net's copper joins an island where tracks and vias touch it, and where pads are within thermal-gap + spoke distance.
- - Pad groups left apart get a via or a short track to the main island. Whatever stays apart is reported as `islands`.
-- **Placer link**:
- - `placer run ... --route board.json route.toml --route-top K` routes the best K placements in parallel and ranks them.
- - `placer route PROBLEM CONFIG board.json route.toml OUT PLACEMENT...` does the same for existing placement files.
- - Memory: about 160 MB per board routed at once.
-
-## Lessons from real boards
-
-- **Net order was the limit, and negotiation removes it.** With the same grid, costs and A*, a one-net-at-a-time router completed 5 of 32 placer candidates on a dense ESP32 + Ethernet board. Negotiation completed 20, and later 26 with bundle attraction.
-- **PathFinder's multiplicative form matters.** With additive costs (step + present + history), the present factor swamps history, and two nets keep trading the same crossing. (base + history) × (1 + present) converged in about 12 rounds.
-- **Hard pre-routes can box in pins** that negotiation cannot free later. Prefer `planes = true` over `plane` steps when ground drops wall in signal pins.
-- **Interface escapes in a block.** Without `[[escape]]`, "complete" boards walled in an MCU's interface pins with supply and crystal tracks.
- - Don't put cost zones on the escape channels. They price the layer for the escape lines too, which then drop to B.Cu with a via at each fine-pitch pin.
- - Space escape pads at least 0.5 mm apart for 0.2 mm lines. Lines need 0.415 mm, and at 0.45 mm the slack is less than one grid step.
- - Choose `from`/`to` so that the pitch is a multiple of 0.05 mm.
- - Keep the escape corridor free of parts. Covering the whole pin side with a footprint rule area works.
-- **Fine-pitch parts must sit on the 0.05 mm grid.** A QFN 0.01 mm off the cells failed random pins on every placement. Put fixed parts' origins on multiples of 0.05 mm. The placer keeps its own parts on the grid.
-- **0.4 mm QFN vs 0.5 mm LQFP**: two 0.2 mm tracks cannot leave neighbouring 0.4 mm-pitch pins side by side. If nearly every pin is used, all lines must neck (`wneck = 0.15`, `neck_zone = 2`). When a fine-pitch MCU has many consecutive pins in use, compare packages before tuning the router: the LQFP routed every time, the QFN never.
-- **Routing a base board between fixed blocks**:
- - Load the whole board dump as `[[fixed]] unmoved = true, protect = true` and route only what is still apart.
- - Raise `margin` on the negotiate step (e.g. 20). Otherwise the 1.5 mm window never reaches the free channel between blocks, and lines cut through them.
- - Write the result with `write_board.py --diff`.
-- **Rerouting a few nets on a finished board**: strip those nets' copper from a copy, dump it, and load the dump as `[[fixed]] unmoved = true` **without** `done = true`. With `done = true` the stripped nets count as done too, and negotiate gets no jobs.
-- **Starved thermal spokes**: the router does not model thermal-relief spokes. Through-hole plane pads next to signal pins can end with one spoke (KiCad DRC `starved_thermal`). On small pours, solid zone connections for those pads fix it.
-- **Bundle attraction only works in the negotiation.** In the cleanup the space beside a partner is already taken. With `attract = 0.5` on negotiate, pair coupling went from about 2–9 % to about 30 %, with fewer vias. Too strong (2) pulls nets off their short paths.
-- **Placement measures do not predict routability.** Spearman |ρ| ≤ 0.3 between unconnected pins and placer cost, crossings, RUDY or a coarse global route. Rank by routing instead (`--route`).
-- A weighted A* heuristic (1.5–2) made negotiation slower and worse. Search windows and partial reroutes were what helped.
-
-## Limits
-
-- Two layers only. Footprints with bottom-side pads are refused: use the plain exposed-pad footprint, then [Thermal vias](thermal-vias.md) after routing.
-- Differential pairs are routed as single nets; bundles only attract.
-- No thermal-spoke check in the pour model.
-- Negotiated boards take 4–15 s each on a 50-part board, single-threaded per board.
diff --git a/knowledge/tooling/thermal-vias.md b/knowledge/tooling/thermal-vias.md
index ecd9390..47efba6 100644
--- a/knowledge/tooling/thermal-vias.md
+++ b/knowledge/tooling/thermal-vias.md
@@ -1,6 +1,6 @@
# Thermal vias (tools/thermal_vias.py)
-The [Placer](placer.md) and the [Rust router](rust-router.md) refuse footprints with bottom-side pads ("U1 has a bottom-side pad; flipped footprints are not supported"). KiCad's `_ThermalVias` footprint variants carry a B.Cu copy of the exposed pad, so they are refused too. Instead:
+The [Placer](placer.md) and the [Router](router.md) refuse footprints with bottom-side pads ("U1 has a bottom-side pad; flipped footprints are not supported"). KiCad's `_ThermalVias` footprint variants carry a B.Cu copy of the exposed pad, so they are refused too. Instead:
1. Use the plain exposed-pad footprint in the schematic.
2. Keep B.Cu free under the pad with a cost zone in `route.toml`, e.g. `{ layer = "B", fp = "U3", rect = [-2.5, -2.5, 2.5, 2.5], cost = 100 }`. Zone rects do not turn with the part, so use a square that both orientations share.
diff --git a/tools/height_check.py b/tools/height_check.py
index fa1e6e8..ad0c039 100644
--- a/tools/height_check.py
+++ b/tools/height_check.py
@@ -1,6 +1,6 @@
"""Check part heights on a DIN-rail board against the printed housing.
- tools/router/.venv/bin/python tools/height_check.py projects/<name>/kicad/<name>.kicad_pcb
+ tools/.venv/bin/python tools/height_check.py projects/<name>/kicad/<name>.kicad_pcb
Finds the HW:DIN_Housing_<k>TE footprint (its position is the housing centre), loads every
top-side footprint's 3D model (STEP vertices, transformed like KiCad does) and compares each
diff --git a/tools/housing_inputs.py b/tools/housing_inputs.py
index c6361db..1080c79 100644
--- a/tools/housing_inputs.py
+++ b/tools/housing_inputs.py
@@ -1,6 +1,6 @@
"""Numbers for a project's DIN-rail housing: notches, pockets, spacer-frame tongues and pin cutouts.
- tools/router/.venv/bin/python tools/housing_inputs.py projects/<name>/kicad/<name>.kicad_pcb
+ tools/.venv/bin/python tools/housing_inputs.py projects/<name>/kicad/<name>.kicad_pcb
Prints, in housing coordinates (X along the rail, Y up = board -y, origin at the
HW:DIN_Housing_<k>TE footprint), what the per-project changes of the DIN housing model need:
diff --git a/tools/placer/Cargo.toml b/tools/placer/Cargo.toml
index 64ddf81..0d8424a 100644
--- a/tools/placer/Cargo.toml
+++ b/tools/placer/Cargo.toml
@@ -8,7 +8,7 @@ description = "Simulated-annealing component placer for KiCad boards (see knowle
anyhow = "1"
rand = { version = "0.8", features = ["small_rng"] }
rayon = "1"
-router = { path = "../router-rs" }
+router = { path = "../router" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "1"
diff --git a/tools/placer/src/main.rs b/tools/placer/src/main.rs
index c94f865..5218bf7 100644
--- a/tools/placer/src/main.rs
+++ b/tools/placer/src/main.rs
@@ -14,7 +14,7 @@
//! OUT_DIR/runs.tsv. A placement file maps ref -> [x, y, rotation in degrees], either at the
//! top level or under "placement".
//!
-//! `--route` routes the best K placements in-process with tools/router-rs (BOARD.json is any
+//! `--route` routes the best K placements in-process with tools/router (BOARD.json is any
//! dump of the board from tools/router/dump_board.py; parts are moved to each placement) and
//! ranks them by the router's result (split nets, failed connections, pour islands, then the
//! route.toml's [rank] score of length, vias, necked and B.Cu length): OUT_DIR/routed.tsv,
diff --git a/tools/pnr.sh b/tools/pnr.sh
index b21bde5..48292ba 100644
--- a/tools/pnr.sh
+++ b/tools/pnr.sh
@@ -1,5 +1,5 @@
#!/bin/sh
-# Place and route a board with tools/placer + tools/router-rs, check the best candidates with
+# Place and route a board with tools/placer + tools/router, check the best candidates with
# KiCad's DRC, and install one. See knowledge/tooling/pnr.md.
#
# sh tools/pnr.sh run BOARD_DIR [TOP] # 32 placements, all routed; DRC of the TOP (6) best
diff --git a/tools/pnr_eval.sh b/tools/pnr_eval.sh
index ed73828..04f290a 100644
--- a/tools/pnr_eval.sh
+++ b/tools/pnr_eval.sh
@@ -11,7 +11,7 @@
T=$(cd "$(dirname "$0")" && pwd)
. "$T/kicad_env.sh"
: "${E:?set E to the board directory}" "${BOARD:?set BOARD to the board name}"
-ROUTER=${ROUTER:-$T/router-rs/target/release/router}
+ROUTER=${ROUTER:-$T/router/target/release/router}
TOML=${TOML:-$E/route.toml}
PLANE=${PLANE:-GND} # the plane net whose dangling vias write_board.py prunes
export E BOARD ROUTER TOML PLANE
diff --git a/tools/router/requirements.txt b/tools/requirements.txt
index 3f89b23..aa094d9 100644
--- a/tools/router/requirements.txt
+++ b/tools/requirements.txt
@@ -1,4 +1,2 @@
numpy
-shapely
-scipy
matplotlib
diff --git a/tools/router-rs/README.md b/tools/router-rs/README.md
deleted file mode 100644
index 969c415..0000000
--- a/tools/router-rs/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Router (Rust)
-
-Grid router for 2-layer KiCad boards with negotiated congestion (all nets at once, ground drops
-optionally included), cleanup passes, a pour-connectivity check and a sequential mode that runs
-the old route scripts' order from a `route.toml`. Footprint copper such as net-tie bridges is
-respected; `area = "pours"` in route.toml keeps all copper inside the plane pours (a design block's area).
-Reads board.json from `tools/router/dump_board.py`, writes routes.json for
-`tools/router/write_board.py`; the placer links it to route its candidates.
-Documentation and lessons: [knowledge/tooling/rust-router.md](../../knowledge/tooling/rust-router.md); end to end on your board: [knowledge/tooling/pnr.md](../../knowledge/tooling/pnr.md).
-
- 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-rs/Cargo.lock b/tools/router/Cargo.lock
index 04eead0..04eead0 100644
--- a/tools/router-rs/Cargo.lock
+++ b/tools/router/Cargo.lock
diff --git a/tools/router-rs/Cargo.toml b/tools/router/Cargo.toml
index c7ff51a..12d5a17 100644
--- a/tools/router-rs/Cargo.toml
+++ b/tools/router/Cargo.toml
@@ -2,7 +2,7 @@
name = "router"
version = "0.1.0"
edition = "2021"
-description = "Grid maze router for 2-layer KiCad boards (see knowledge/tooling/rust-router.md)"
+description = "Grid maze router for 2-layer KiCad boards (see knowledge/tooling/router.md)"
[lib]
name = "router"
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-rs/src/astar.rs b/tools/router/src/astar.rs
index 2be7595..0a91f7a 100644
--- a/tools/router-rs/src/astar.rs
+++ b/tools/router/src/astar.rs
@@ -1,4 +1,4 @@
-//! Grid A* core, 2 layers (port of tools/router/astar.c with the same arithmetic in f32;
+//! 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.
diff --git a/tools/router-rs/src/board.rs b/tools/router/src/board.rs
index 137b4fa..730d90e 100644
--- a/tools/router-rs/src/board.rs
+++ b/tools/router/src/board.rs
@@ -1,4 +1,4 @@
-//! Board model and clearance fields (port of tools/router/pcbroute.py).
+//! 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
@@ -95,7 +95,7 @@ pub struct Pad {
pub item: usize,
}
-/// Search settings of one connection (pcbroute.Board.route keyword arguments).
+/// Search settings of one connection (per step or per net in route.toml).
#[derive(Clone, Copy, Debug)]
pub struct SearchOpts {
pub via_cost: f64,
diff --git a/tools/router-rs/src/cleanup.rs b/tools/router/src/cleanup.rs
index d3ed3bc..d3ed3bc 100644
--- a/tools/router-rs/src/cleanup.rs
+++ b/tools/router/src/cleanup.rs
diff --git a/tools/router-rs/src/config.rs b/tools/router/src/config.rs
index 090d999..090d999 100644
--- a/tools/router-rs/src/config.rs
+++ b/tools/router/src/config.rs
diff --git a/tools/router-rs/src/geom.rs b/tools/router/src/geom.rs
index f176e39..f176e39 100644
--- a/tools/router-rs/src/geom.rs
+++ b/tools/router/src/geom.rs
diff --git a/tools/router-rs/src/io.rs b/tools/router/src/io.rs
index be51147..be51147 100644
--- a/tools/router-rs/src/io.rs
+++ b/tools/router/src/io.rs
diff --git a/tools/router-rs/src/lib.rs b/tools/router/src/lib.rs
index 925b1af..5156e0b 100644
--- a/tools/router-rs/src/lib.rs
+++ b/tools/router/src/lib.rs
@@ -1,4 +1,4 @@
-//! Grid maze router for 2-layer KiCad boards (see knowledge/tooling/rust-router.md).
+//! 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.
diff --git a/tools/router-rs/src/main.rs b/tools/router/src/main.rs
index 85802ce..85802ce 100644
--- a/tools/router-rs/src/main.rs
+++ b/tools/router/src/main.rs
diff --git a/tools/router-rs/src/placement.rs b/tools/router/src/placement.rs
index 9409742..9409742 100644
--- a/tools/router-rs/src/placement.rs
+++ b/tools/router/src/placement.rs
diff --git a/tools/router-rs/src/pour.rs b/tools/router/src/pour.rs
index b7aaab4..b7aaab4 100644
--- a/tools/router-rs/src/pour.rs
+++ b/tools/router/src/pour.rs
diff --git a/tools/router-rs/src/router.rs b/tools/router/src/router.rs
index b22b78a..e829fe8 100644
--- a/tools/router-rs/src/router.rs
+++ b/tools/router/src/router.rs
@@ -1,4 +1,4 @@
-//! Routing strategies on top of the board fields (port of tools/router/pipeline.py):
+//! 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};
diff --git a/tools/router-rs/src/run.rs b/tools/router/src/run.rs
index 8de3e65..8de3e65 100644
--- a/tools/router-rs/src/run.rs
+++ b/tools/router/src/run.rs
diff --git a/tools/thermal_vias.py b/tools/thermal_vias.py
index 744d0d6..d2e7425 100644
--- a/tools/thermal_vias.py
+++ b/tools/thermal_vias.py
@@ -1,6 +1,6 @@
"""Add a grid of thermal vias to the exposed pads of the given footprints, after routing.
-The routers (tools/router-rs, tools/placer) refuse footprints with bottom-side pads, so the
+The routers (tools/router, tools/placer) refuse footprints with bottom-side pads, so the
KiCad "_ThermalVias" footprint variants cannot be used. Use the plain exposed-pad footprint,
keep B.Cu clear under the pad with a router cost zone (route.toml), and run this on the routed
board. Each via takes the pad's net; a via is skipped where it would come within the clearance