//! The placement problem: parts, pads, nets from export.py's JSON, plus the sidecar config //! (placement.toml) and what can be inferred from the netlist (decoupling caps, pin normals, //! fine-pitch fan-out bands, fixed parts). //! //! Labels beyond the netlist: `[[link]]` keeps two pads within a distance (a net tie on a //! Kelvin pad), `[[pull]]` draws the pads of interface nets towards a board side (where the //! host connects), `[[replicate]]` makes repeated channels copies of the first one at a fixed //! pitch (followers move with their master and are never moved on their own). use crate::geom::{poly_rects, Pt, Rect}; use anyhow::{bail, Context, Result}; use serde::Deserialize; use std::collections::HashMap; // ---------- export.py JSON ---------- #[derive(Deserialize)] struct JPad { num: String, net: String, x: f64, y: f64, w: f64, h: f64, tht: bool, } #[derive(Deserialize)] struct JPart { #[serde(rename = "ref")] reference: String, value: String, fpid: String, x: f64, y: f64, rot: f64, locked: bool, board_only: bool, fields: HashMap, court: Vec>, pads: Vec, } #[derive(Deserialize)] struct JKeepout { poly: Vec<[f64; 2]>, footprints: bool, pads: bool, #[serde(default)] tracks: bool, } #[derive(Deserialize)] struct JClass { track: f64, clearance: f64, } #[derive(Deserialize)] struct JProblem { bounds: [f64; 4], parts: Vec, netclass: HashMap, #[serde(default)] classes: HashMap, fill: Vec, keepouts: Vec, } // ---------- placement.toml ---------- /// Cost weights. Lengths are in mm, areas in mm^2. #[derive(Deserialize, Clone, Debug)] #[serde(default, deny_unknown_fields)] pub struct Weights { /// per mm of ratsnest (MST) length, times the net weight pub length: f64, /// per crossing of two ratsnest lines, times the mean weight of both nets pub crossing: f64, /// per line that leaves a pin backwards, times the detour (part size); not scaled by net weight pub escape: f64, /// per ratsnest line over another net's pad, times the net weight pub block: f64, /// per mm from a decoupling cap to its pin (ground pad counts half) pub decap: f64, /// beyond the decap limit (3 mm, 8 mm for bulk caps): per mm^2 for the first 2 mm, then 4 per mm pub decap_limit: f64, /// per mm that a decoupled IC pin is farther than 3 mm from its nearest cap pub cover: f64, /// per mm^2 of courtyard overlap, outside the board, in a keep-out or outside a group bbox pub overlap: f64, /// per mm^2 of another part's pad in a fine-pitch IC's fan-out band pub band: f64, /// fan-out band width in front of fine-pitch pin rows (mm) pub fanout: f64, /// copper-to-edge clearance for pads (mm) pub edge: f64, /// [[link]] past its distance: per mm^2 for the first 2 mm, then 4 per mm (times its weight) pub link: f64, /// [[pull]]: per mm from a pad to its side of the part's group bbox, else of the board /// (times its weight) pub pull: f64, } impl Default for Weights { fn default() -> Self { Weights { length: 1.0, crossing: 4.0, escape: 3.0, block: 3.0, decap: 3.0, decap_limit: 20.0, cover: 4.0, overlap: 100.0, band: 40.0, fanout: 1.0, edge: 0.5, link: 20.0, pull: 1.0, } } } #[derive(Deserialize, Default)] #[serde(deny_unknown_fields)] struct CNet { #[serde(rename = "match")] pattern: String, weight: f64, } #[derive(Deserialize, Default)] #[serde(deny_unknown_fields)] struct CGroup { name: String, #[serde(default)] parts: Vec, bbox: Option<[f64; 4]>, } #[derive(Deserialize, Default)] #[serde(deny_unknown_fields)] struct CAttach { part: String, /// "U2.21" pin: String, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct CLink { /// "NT1.2" a: String, b: String, /// pad centre distance (mm) allowed without cost max: f64, #[serde(default = "one")] weight: f64, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct CPull { /// net name globs nets: Vec, /// "N", "S", "E" or "W" side: String, #[serde(default = "one")] weight: f64, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct CReplicate { /// channels, each a list of parts; channel k's part i follows channel 0's part i parts: Vec>, /// offset (mm) from one channel to the next, in board axes pitch: [f64; 2], } fn one() -> f64 { 1.0 } #[derive(Deserialize, Default)] #[serde(default, deny_unknown_fields)] struct Config { fixed: Vec, /// net-class name -> weight; classes not listed weigh 1 class: HashMap, net: Vec, group: Vec, attach: Vec, link: Vec, pull: Vec, replicate: Vec, weights: Weights, } // ---------- model ---------- pub struct Pad { pub part: usize, pub num: String, /// None for unconnected pads and fill nets pub net: Option, pub fill: bool, pub local: Pt, pub half: Pt, /// outward direction a track leaves the pin in, footprint-local pub normal: Option, /// through-hole (blocks both layers) pub tht: bool, } pub struct Part { pub reference: String, pub fpid: String, pub fixed: bool, pub at0: Pt, pub rot0: u8, pub pads: Vec, pub court: Vec, /// bounding box of the courtyard (local) pub hull: Rect, /// fine-pitch ICs: pad envelope grown by the fan-out width (local) pub band: Option, /// detour length when a line leaves a pin backwards pub detour: f64, /// non-fill nets on this part pub nets: Vec, /// all groups this part belongs to, innermost first pub groups: Vec, /// links this part has a pad in pub links: Vec, /// [[pull]] pads: (pad, outward unit vector of the side, weight) pub pulls: Vec<(usize, Pt, f64)>, /// replicated channel: (master part, offset from it); moves only with the master pub follow: Option<(usize, Pt)>, /// parts that follow this one pub followers: Vec, } pub struct Link { pub a: usize, pub b: usize, pub max: f64, pub weight: f64, } pub struct Decap { pub part: usize, pub sig: usize, pub gnd: usize, pub bulk: bool, /// candidate pins (pad) with the ground pins of the same part pub cands: Vec<(usize, Vec)>, } pub struct Net { pub name: String, pub pads: Vec, pub weight: f64, /// track width + clearance of the net's class (mm): the room one track takes pub pitch: f64, pub decaps: Vec, /// IC pins that need a cap within 3 mm pub cover: Vec, } pub struct Group { pub name: String, pub bbox: Option, /// movable members, including those of subgroups pub parts: Vec, } pub struct Model { pub parts: Vec, pub pads: Vec, pub nets: Vec, pub decaps: Vec, pub groups: Vec, pub links: Vec, pub bounds: Rect, /// rule areas no courtyard may enter pub keepouts: Vec, /// rule areas no pad may enter pub pad_keepouts: Vec, /// rule areas no track may enter pub track_keepouts: Vec, pub w: Weights, pub movable: Vec, } const COURT_MARGIN: f64 = 0.03; fn glob(pat: &str, s: &str) -> bool { // '*' only 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 } fn cap_uf(v: &str) -> f64 { let v = v.trim(); let k = v.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(v.len()); let n: f64 = v[..k].parse().unwrap_or(0.0); let f = match v[k..].chars().next() { Some('p') => 1e-6, Some('n') => 1e-3, Some('u') | Some('ยต') => 1.0, Some('m') => 1e3, _ => 1.0, }; n * f } fn is_ic(reference: &str, npads: usize) -> bool { npads >= 4 && !reference.starts_with(['J', 'P']) && !reference.starts_with("TP") } /// Outward direction of each pad: 2-pad parts along their axis, ICs and connectors from the /// side of the pad envelope the pad sits on (pads elongated along it decide first); centre /// pads (exposed pads, module ground pads) and THT pads have none. fn normals(pads: &[JPad]) -> Vec> { let smd: Vec<&JPad> = pads.iter().filter(|p| !p.tht).collect(); if smd.len() == 2 && pads.len() == 2 { let c = ((smd[0].x + smd[1].x) / 2.0, (smd[0].y + smd[1].y) / 2.0); return pads .iter() .map(|p| { let (dx, dy) = (p.x - c.0, p.y - c.1); let l = (dx * dx + dy * dy).sqrt(); (l > 1e-6).then(|| (dx / l, dy / l)) }) .collect(); } if smd.len() < 3 { return pads.iter().map(|_| None).collect(); } let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); for p in &smd { x0 = x0.min(p.x); y0 = y0.min(p.y); x1 = x1.max(p.x); y1 = y1.max(p.y); } let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); pads.iter() .map(|p| { if p.tht { return None; } let d = [p.x - x0, x1 - p.x, p.y - y0, y1 - p.y]; let m = d.iter().cloned().fold(f64::MAX, f64::min); if m > 0.3 { return None; // not on the perimeter } if p.w > 1.3 * p.h { return Some((if p.x < cx { -1.0 } else { 1.0 }, 0.0)); } if p.h > 1.3 * p.w { return Some((0.0, if p.y < cy { -1.0 } else { 1.0 })); } let dirs = [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0)]; let (mut nx, mut ny) = (0.0, 0.0); for (k, dir) in dirs.iter().enumerate() { if d[k] < m + 0.2 { nx += dir.0; ny += dir.1; } } let l = ((nx * nx + ny * ny) as f64).sqrt(); (l > 1e-6).then(|| (nx / l, ny / l)) }) .collect() } fn rot_steps(deg: f64) -> u8 { (((deg / 90.0).round() as i64).rem_euclid(4)) as u8 } impl Model { pub fn load(problem: &str, config: &str) -> Result { let jp: JProblem = serde_json::from_str(&std::fs::read_to_string(problem).with_context(|| problem.to_string())?)?; let cfg: Config = toml::from_str(&std::fs::read_to_string(config).with_context(|| config.to_string())?) .with_context(|| format!("parsing {config}"))?; let w = cfg.weights.clone(); let fillset: std::collections::HashSet<&str> = jp.fill.iter().map(|s| s.as_str()).collect(); let is_fill = |n: &str| { fillset.contains(n) || { let base = n.rsplit('/').next().unwrap_or(n); matches!(base, "GND" | "GNDA" | "GNDD" | "AGND" | "DGND" | "VSS" | "PGND") } }; // nets let mut netid: HashMap = HashMap::new(); let mut nets: Vec = Vec::new(); let mut names: Vec<&String> = jp.netclass.keys().collect(); names.sort(); for n in names { if is_fill(n) { continue; } let cls = &jp.netclass[n]; let mut weight = *cfg.class.get(cls).unwrap_or(&1.0); for o in &cfg.net { if glob(&o.pattern, n) { weight = o.weight; } } let pitch = jp.classes.get(cls).map(|c| c.track + c.clearance).unwrap_or(0.4); netid.insert(n.clone(), nets.len()); nets.push(Net { name: n.clone(), pads: vec![], weight, pitch, decaps: vec![], cover: vec![] }); } // parts and pads let mut parts = Vec::new(); let mut pads = Vec::new(); let fixed_cfg: std::collections::HashSet<&str> = cfg.fixed.iter().map(|s| s.as_str()).collect(); for (pi, p) in jp.parts.iter().enumerate() { // grown by a bit more than half the courtyard line: KiCad's DRC flags courtyards // that touch, so parts must keep at least one grid step apart let mut court: Vec = p.court.iter().flat_map(|poly| poly_rects(poly)).map(|r| r.grow(COURT_MARGIN)).collect(); if court.is_empty() { for q in &p.pads { court.push(Rect::around((q.x, q.y), q.w / 2.0 + 0.25, q.h / 2.0 + 0.25)); } } let hull = court.iter().skip(1).fold(court[0], |a, r| a.union(r)); let field_fixed = p.fields.get("Place_Fixed").map(|v| !v.is_empty() && v != "0" && v != "no").unwrap_or(false); let hole = p.fpid.contains("MountingHole") || p.fpid.contains("DIN_Post") || p.fpid.contains("DIN_Housing"); let fixed = p.locked || p.board_only || hole || field_fixed || fixed_cfg.contains(p.reference.as_str()); let ns = normals(&p.pads); let mut ids = vec![]; for (q, n) in p.pads.iter().zip(ns) { let net = netid.get(&q.net).copied(); if let Some(k) = net { nets[k].pads.push(pads.len()); } ids.push(pads.len()); pads.push(Pad { part: pi, num: q.num.clone(), net, fill: is_fill(&q.net), local: (q.x, q.y), half: (q.w / 2.0, q.h / 2.0), normal: n, tht: q.tht, }); } // fine-pitch: >= 8 SMD pads with neighbours closer than 0.7 mm let smd: Vec<&JPad> = p.pads.iter().filter(|q| !q.tht).collect(); let pitch = smd .iter() .enumerate() .flat_map(|(i, a)| smd[i + 1..].iter().map(move |b| ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt())) .fold(f64::MAX, f64::min); let band = (smd.len() >= 8 && pitch < 0.7).then(|| { smd.iter() .map(|q| Rect::around((q.x, q.y), q.w / 2.0, q.h / 2.0)) .reduce(|a, b| a.union(&b)) .unwrap() .grow(w.fanout) }); let mut pn: Vec = ids.iter().filter_map(|&k| pads[k].net).collect(); pn.sort(); pn.dedup(); parts.push(Part { reference: p.reference.clone(), fpid: p.fpid.clone(), fixed, at0: (p.x, p.y), rot0: rot_steps(p.rot), pads: ids, court, hull, band, detour: ((hull.x1 - hull.x0) + (hull.y1 - hull.y0)) / 2.0, nets: pn, groups: vec![], links: vec![], pulls: vec![], follow: None, followers: vec![], }); } let pref: HashMap = parts.iter().enumerate().map(|(i, p)| (p.reference.clone(), i)).collect(); // decoupling caps: C with one pad on a fill net, the other on a net with IC pins let mut decaps = Vec::new(); let xtal_nets: std::collections::HashSet = parts .iter() .filter(|p| p.reference.starts_with('Y')) .flat_map(|p| p.nets.clone()) .collect(); let attach: HashMap<&str, &str> = cfg.attach.iter().map(|a| (a.part.as_str(), a.pin.as_str())).collect(); for (pi, (p, jpart)) in parts.iter().zip(&jp.parts).enumerate() { if !p.reference.starts_with('C') || p.pads.len() != 2 { continue; } let (a, b) = (p.pads[0], p.pads[1]); let (sig, gnd) = match (pads[a].fill, pads[b].fill) { (false, true) => (a, b), (true, false) => (b, a), _ => continue, }; let Some(net) = pads[sig].net else { continue }; let bulk = cap_uf(&jpart.value) >= 4.7; let mut cands = vec![]; if let Some(pin) = attach.get(p.reference.as_str()) { let (r, num) = pin.split_once('.').context("attach pin must be REF.PIN")?; let Some(&ic) = pref.get(r) else { bail!("attach {}: no part {r}", p.reference) }; let Some(&k) = parts[ic].pads.iter().find(|&&k| pads[k].num == num) else { bail!("attach {}: no pin {pin}", p.reference) }; cands.push(k); } else { for &k in &nets[net].pads { let q = &parts[pads[k].part]; let ok = is_ic(&q.reference, q.pads.len()) || (bulk && q.reference.starts_with(['L', 'F'])); if pads[k].part != pi && ok { cands.push(k); } } } if cands.is_empty() { continue; } let cands = cands .into_iter() .map(|k| { let g = parts[pads[k].part].pads.iter().copied().filter(|&j| pads[j].fill).collect(); (k, g) }) .collect(); nets[net].decaps.push(decaps.len()); decaps.push(Decap { part: pi, sig, gnd, bulk, cands }); } // IC pins on nets with a small cap need a cap within 3 mm (crystal nets excluded) for (ni, net) in nets.iter_mut().enumerate() { if xtal_nets.contains(&ni) || !net.decaps.iter().any(|&d| !decaps[d].bulk) { continue; } net.cover = net .pads .iter() .copied() .filter(|&k| { let q = &parts[pads[k].part]; is_ic(&q.reference, q.pads.len()) && !q.reference.starts_with(['Y', 'L', 'F']) }) .collect(); } // links, pulls and replicated channels let pad_of = |parts: &[Part], s: &str, what: &str| -> Result { let (r, num) = s.split_once('.').with_context(|| format!("{what} {s}: write REF.PIN"))?; let Some(&pi) = pref.get(r) else { bail!("{what} {s}: no part {r}") }; parts[pi].pads.iter().copied().find(|&k| pads[k].num == num).with_context(|| format!("{what} {s}: no pin {num}")) }; let mut links = Vec::new(); for l in &cfg.link { let (a, b) = (pad_of(&parts, &l.a, "link")?, pad_of(&parts, &l.b, "link")?); for k in [a, b] { let pi = pads[k].part; if !parts[pi].links.contains(&links.len()) { parts[pi].links.push(links.len()); } } links.push(Link { a, b, max: l.max, weight: l.weight }); } for pl in &cfg.pull { let dir = match pl.side.as_str() { "N" => (0.0, -1.0), "S" => (0.0, 1.0), "W" => (-1.0, 0.0), "E" => (1.0, 0.0), o => bail!("pull: side {o:?} is not N, S, E or W"), }; for (pi, jpart) in jp.parts.iter().enumerate() { for (q, &k) in jpart.pads.iter().zip(&parts[pi].pads.clone()) { if pl.nets.iter().any(|g| glob(g, &q.net)) { parts[pi].pulls.push((k, dir, pl.weight)); } } } } for rp in &cfg.replicate { let Some(first) = rp.parts.first() else { continue }; for (c, chan) in rp.parts.iter().enumerate().skip(1) { if chan.len() != first.len() { bail!("replicate: channel {c} has {} parts, channel 0 has {}", chan.len(), first.len()); } for (r0, r) in first.iter().zip(chan) { let (Some(&m0), Some(&f)) = (pref.get(r0.as_str()), pref.get(r.as_str())) else { bail!("replicate: no part {r0} or {r}") }; if parts[m0].fpid != parts[f].fpid { bail!("replicate: {r} ({}) is not the footprint of {r0} ({})", parts[f].fpid, parts[m0].fpid); } if parts[m0].fixed || parts[f].fixed { bail!("replicate: {r0} and {r} must both be movable"); } parts[f].follow = Some((m0, (rp.pitch[0] * c as f64, rp.pitch[1] * c as f64))); parts[m0].followers.push(f); } } } // groups: from the config and from Place_Group fields ("eth/xtal" is a subgroup of "eth") let mut groups: Vec = Vec::new(); let mut gid: HashMap = HashMap::new(); let mut member: Vec<(usize, String)> = vec![]; for (pi, p) in jp.parts.iter().enumerate() { if let Some(g) = p.fields.get("Place_Group").filter(|g| !g.is_empty()) { member.push((pi, g.clone())); } } for g in &cfg.group { gid.insert(g.name.clone(), groups.len()); groups.push(Group { name: g.name.clone(), bbox: g.bbox.map(|b| Rect::new(b[0], b[1], b[2], b[3])), parts: vec![] }); for r in &g.parts { let Some(&pi) = pref.get(r.as_str()) else { bail!("group {}: no part {r}", g.name) }; member.retain(|(q, _)| *q != pi); // the config overrides the field member.push((pi, g.name.clone())); } } for (pi, g) in member { // the group and every parent group let segs: Vec<&str> = g.split('/').collect(); for k in (1..=segs.len()).rev() { let name = segs[..k].join("/"); let id = *gid.entry(name.clone()).or_insert_with(|| { groups.push(Group { name: name.clone(), bbox: None, parts: vec![] }); groups.len() - 1 }); if !parts[pi].fixed && parts[pi].follow.is_none() && !groups[id].parts.contains(&pi) { groups[id].parts.push(pi); } if !parts[pi].groups.contains(&id) { parts[pi].groups.push(id); } } } let keepouts = jp.keepouts.iter().filter(|k| k.footprints).flat_map(|k| poly_rects(&k.poly)).collect(); let pad_keepouts = jp.keepouts.iter().filter(|k| k.pads).flat_map(|k| poly_rects(&k.poly)).collect(); let track_keepouts = jp.keepouts.iter().filter(|k| k.tracks).flat_map(|k| poly_rects(&k.poly)).collect(); let movable = (0..parts.len()).filter(|&i| !parts[i].fixed && parts[i].follow.is_none()).collect(); let b = jp.bounds; Ok(Model { parts, pads, nets, decaps, groups, links, bounds: Rect::new(b[0], b[1], b[2], b[3]), keepouts, pad_keepouts, track_keepouts, w, movable, }) } /// Put every follower at its master's pose plus its offset. pub fn sync(&self, at: &mut [Pt], rot: &mut [u8]) { for (i, p) in self.parts.iter().enumerate() { if let Some((m0, off)) = p.follow { at[i] = (at[m0].0 + off.0, at[m0].1 + off.1); rot[i] = rot[m0]; } } } pub fn part(&self, r: &str) -> Option { self.parts.iter().position(|p| p.reference == r) } }