From 2e433fcd0d1afadd8ab786dd30d7d4546bdee43d Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 11 Nov 2026 10:08:41 +0100 Subject: hw-toolchain: placer, routers and KiCad helpers for agent-driven hardware work Rust placer (simulated annealing) and negotiated-congestion router for 2-layer KiCad boards, pnr.sh to place, route, DRC-check and install candidates, Python KiCad helpers, repo conventions (AGENTS.md) and the tool documentation under knowledge/. Konnect (KiCad MCP, AGPL) as a submodule. Co-Authored-By: Claude Opus 5.5 --- tools/router-rs/src/config.rs | 389 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 389 insertions(+) create mode 100644 tools/router-rs/src/config.rs (limited to 'tools/router-rs/src/config.rs') diff --git a/tools/router-rs/src/config.rs b/tools/router-rs/src/config.rs new file mode 100644 index 0000000..090d999 --- /dev/null +++ b/tools/router-rs/src/config.rs @@ -0,0 +1,389 @@ +//! route.toml: the board's routing rules (replaces the Python route scripts). +//! +//! ```toml +//! prefix = "/My Sheet/" # net names may leave it out +//! plane_nets = ["GND"] +//! +//! [[fixed]] # fixed copper, loaded before the steps +//! name = "bus" # path from --fixed bus=FILE, or `path` (relative to the toml) +//! done = true # its nets are complete: `rest` leaves them alone +//! [[fixed]] +//! name = "keep" +//! unmoved = true # a board dump: keep copper of nets whose parts did not move +//! exclude = ["GND"] +//! optional = true +//! +//! [costs.sig] # cost maps: rectangles relative to a footprint's origin +//! zones = [{ layer = "F", fp = "U1", rect = [-8.1, -9.2, 8.1, 10.66], cost = 200 }] +//! [costs.rudy] +//! rudy = { scale = 4.0, max = 20.0 } # RUDY congestion of the pads' MSTs on F.Cu +//! +//! [[step]] +//! do = "connect" # via, plane, connect, pair, decaps, rest, repair, tie, stitch +//! nets = ["XI", "XO"] +//! cost = "sig" # "none" clears; left out, the previous map stays +//! ``` +//! +//! Steps run in order. Pads are written "REF:NUM". +//! +//! `do = "pour"` checks the plane nets' pours (board.json `zones`) for islands that leave +//! pads apart and, with `fix` (default), joins them with vias of diameter `d` (0.6). +//! `planes = true` on a negotiate step routes the plane nets' drops in the negotiation +//! (instead of a `plane` step before it), so they can give way to signals. +//! `[rank]` sets how routed boards compare (see Rank). +//! +//! `area = "pours"` keeps all copper inside the plane nets' pours (board.json `zones`), e.g. a +//! design block's area; `area = [[x, y], ...]` gives a polygon. `area_margin` (mm, default 0) +//! keeps copper that far inside. +//! +//! `[[bundle]] nets = [...]` (pairs, buses): a step of one of these nets that does not run +//! alongside its bundle partners' copper costs `attract` more (hug is 0.3): on the negotiate +//! step (default 0, off; 0.5 works well) and on the cleanup step (default 0.5). Soft: +//! nothing is forced, and the cleanup still keeps a reroute only if it is at most 2 % worse. +//! Negotiation is where it counts: in the cleanup the space beside a partner is mostly taken. +//! +//! `do = "negotiate"` routes every net still in pieces at once (negotiated congestion), with +//! `cost`, `rounds`, `pres`, `pres_mult`, `hist` and search settings as defaults; a +//! `[nets.NAME]` table overrides them per net (w, wneck, neck_zone, via_d, root, decaps, +//! priority, cost, ...) and `[[nets.NAME.join]]` adds pad pairs routed first (a, b, cost, w, wneck, +//! allow_via). Higher `priority` routes first in each round. +//! +//! `[[escape]] nets = [...], from = [x, y], to = [x, y]` reserves escape lines for nets that +//! leave the block (a module's interface nets, one pad each): a virtual pad per net, spread +//! evenly from `from` to `to` in the order given (`size` mm square, default 0.25, on F.Cu), +//! routed with everything else (`w` mm wide, default the nets' own width), so a board only +//! counts as complete when every such net can still reach the block edge past the block's own +//! copper. Their copper is left out of the +//! output (`keep = true` keeps it); the base board routes the real lines. +//! +//! `neck_zone` (mm, default 1): a track may neck to `wneck` only within this distance of the +//! pads it joins. A fine-pitch part whose pins are nearly all used needs more (0.4 mm-pitch +//! QFN: 2), so neighbouring lines can spread apart before they must be full width. + +use crate::router::{NetOpts, PadRef}; +use anyhow::{anyhow, bail, Result}; +use serde::Deserialize; +use std::collections::BTreeMap; + +fn default_planes() -> Vec { + vec!["GND".into()] +} + +fn yes() -> bool { + true +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + #[serde(default)] + pub prefix: String, + #[serde(default = "default_planes")] + pub plane_nets: Vec, + #[serde(default)] + pub fixed: Vec, + #[serde(default)] + pub costs: BTreeMap, + #[serde(default)] + pub nets: BTreeMap, + #[serde(default)] + pub step: Vec, + #[serde(default)] + pub rank: Rank, + /// Routing area: all copper stays inside it (`area_margin` mm in, default 0). + #[serde(default)] + pub area: Option, + #[serde(default)] + pub area_margin: f64, + /// Nets the cleanup draws together: `[[bundle]] nets = ["USB_DP", "USB_DN"]`. + #[serde(default)] + pub bundle: Vec, + /// Escape lines for nets that leave the block, to virtual pads along an edge. + #[serde(default)] + pub escape: Vec, +} + +fn escape_size() -> f64 { + 0.25 +} + +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct Escape { + /// in their order along the edge, from `from` to `to` + pub nets: Vec, + pub from: [f64; 2], + pub to: [f64; 2], + #[serde(default = "escape_size")] + pub size: f64, + /// track width of the escape lines (default: the nets' own); the lines only reserve room, + /// so they may be as thin as the base board will route them (e.g. 0.15 at a 0.4 mm pitch) + pub w: Option, + /// write the escape copper to the output too + #[serde(default)] + pub keep: bool, +} + +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct Bundle { + pub nets: Vec, +} + +/// `area = "pours"` (the union of the plane nets' zones in board.json) or a polygon. +#[derive(Deserialize, Clone)] +#[serde(untagged)] +pub enum Area { + Pours(String), + Poly(Vec<[f64; 2]>), +} + +/// How routed boards of the same board compare (placer --route): fewer split nets, failed +/// connections and pour islands first, then the lowest score = net length x weight + +/// via_mm x vias + neck_mm x necked length + bcu_mm x B.Cu length. +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields, default)] +pub struct Rank { + pub via_mm: f64, + pub neck_mm: f64, + pub bcu_mm: f64, + /// net length weights by glob (`*` only), e.g. { match = "*/SENSE*", weight = 2.0 } + pub nets: Vec, +} + +impl Default for Rank { + fn default() -> Self { + Rank { via_mm: 2.0, neck_mm: 2.0, bcu_mm: 0.0, nets: vec![] } + } +} + +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct RankNet { + #[serde(rename = "match")] + pub pattern: String, + pub weight: f64, +} + +/// Glob with `*` only. +pub fn glob(pat: &str, s: &str) -> bool { + let parts: Vec<&str> = pat.split('*').collect(); + if parts.len() == 1 { + return pat == s; + } + let mut rest = s; + for (i, p) in parts.iter().enumerate() { + if i == 0 { + if !rest.starts_with(p) { + return false; + } + rest = &rest[p.len()..]; + } else if i == parts.len() - 1 { + return rest.ends_with(p); + } else if let Some(k) = rest.find(p) { + rest = &rest[k + p.len()..]; + } else { + return false; + } + } + true +} + +#[derive(Deserialize, Default, Clone)] +#[serde(deny_unknown_fields)] +pub struct NetCfg { + #[serde(default)] + pub join: Vec, + pub cost: Option, + pub root: Option, + pub decaps: Option, + pub priority: Option, + pub w: Option, + pub wneck: Option, + pub via_d: Option, + pub via_cost: Option, + pub via_cmult: Option, + pub bmult: Option, + pub turn: Option, + pub allow_via: Option, + pub max_expand: Option, + pub neck: Option, + pub neck_zone: Option, +} + +/// A pad pair of the net routed first, with its own settings (e.g. AVDD pins joined inside +/// a QFP's pad ring without vias). +#[derive(Deserialize, Default, Clone)] +#[serde(deny_unknown_fields)] +pub struct JoinCfg { + pub a: String, + pub b: String, + pub cost: Option, + pub w: Option, + pub wneck: Option, + pub allow_via: Option, +} + +impl NetCfg { + /// Search settings: these where set, else the step's. + pub fn opts(&self, step: &NetOpts) -> NetOpts { + NetOpts { + w: self.w.or(step.w), + wneck: self.wneck.or(step.wneck), + via_d: self.via_d.or(step.via_d), + via_cost: self.via_cost.or(step.via_cost), + via_cmult: self.via_cmult.or(step.via_cmult), + bmult: self.bmult.or(step.bmult), + turn: self.turn.or(step.turn), + allow_via: self.allow_via.or(step.allow_via), + max_expand: self.max_expand.or(step.max_expand), + hweight: step.hweight, + margin: step.margin, + hug: step.hug, + neck: self.neck.or(step.neck), + neck_zone: self.neck_zone.or(step.neck_zone), + } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Fixed { + pub name: String, + pub path: Option, + #[serde(default)] + pub unmoved: bool, + #[serde(default)] + pub exclude: Vec, + #[serde(default = "yes")] + pub protect: bool, + #[serde(default)] + pub done: bool, + #[serde(default)] + pub optional: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CostDef { + #[serde(default)] + pub zones: Vec, + pub rudy: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Zone { + pub layer: String, + pub fp: Option, + pub rect: [f64; 4], + pub cost: f64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Rudy { + #[serde(default = "f_layer")] + pub layer: String, + pub scale: f64, + pub max: f64, +} + +fn f_layer() -> String { + "F".into() +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +pub struct Step { + #[serde(rename = "do")] + pub kind: String, + pub label: Option, + pub cost: Option, + pub net: Option, + pub nets: Option>, + pub fp: Option, + pub at: Option>, + pub d: Option, + pub only: Option>, + pub skip: Option>, + pub exclude: Option>, + pub root: Option, + pub pads: Option>, + pub a: Option, + pub b: Option, + pub pad: Option, + pub rounds: Option, + pub radius: Option, + pub pitch: Option, + pub area: Option<[f64; 4]>, + pub w: Option, + pub wneck: Option, + pub via_d: Option, + pub via_cost: Option, + pub via_cmult: Option, + pub bmult: Option, + pub turn: Option, + pub allow_via: Option, + pub max_expand: Option, + pub hweight: Option, + pub margin: Option, + pub hug: Option, + /// negotiate (default 0) and cleanup (default 0.5): extra cost per step away from the + /// net's [[bundle]] partners + pub attract: Option, + /// necked step cost per mm of width given up (cleanup default 4, elsewhere 0) + pub neck: Option, + /// a track may neck to `wneck` within this distance (mm) of the pads it joins (default 1) + pub neck_zone: Option, + pub pres: Option, + pub pres_mult: Option, + pub hist: Option, + pub decaps: Option, + /// negotiate: route the plane nets' drops in the negotiation too + pub planes: Option, + /// pour: stitch islands to the rest of the pour with vias + pub fix: Option, +} + +impl Step { + pub fn opts(&self) -> NetOpts { + NetOpts { + w: self.w, + wneck: self.wneck, + via_d: self.via_d, + via_cost: self.via_cost, + via_cmult: self.via_cmult, + bmult: self.bmult, + turn: self.turn, + allow_via: self.allow_via, + max_expand: self.max_expand, + hweight: self.hweight, + margin: self.margin, + hug: self.hug, + neck: self.neck, + neck_zone: self.neck_zone, + } + } + + pub fn net(&self) -> Result<&str> { + self.net.as_deref().ok_or_else(|| anyhow!("step {}: `net` missing", self.kind)) + } +} + +pub fn pad_ref(s: &str) -> Result { + let Some((r, n)) = s.split_once(':') else { bail!("pad {s:?}: write REF:NUM") }; + Ok((r.to_string(), n.to_string())) +} + +pub fn pad_refs(v: &[String]) -> Result> { + v.iter().map(|s| pad_ref(s)).collect() +} + +impl Config { + pub fn load(path: &str) -> Result { + use anyhow::Context; + let s = std::fs::read_to_string(path).with_context(|| path.to_string())?; + toml::from_str(&s).with_context(|| path.to_string()) + } +} -- cgit v1.3