master
Ray
Publish 0.5.1
6234640
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
//! Plan view (#21): a plain, static 2D layout view of a molecule, labelled by net.
//!
//! Draws the board outline (wings included), machine pins and contacts labelled by net with copper sized from the
//! library's hole OD, free contact slots dashed, each footprint's pads with pin numbers and a pin-1 mark at its
//! placement and rotation, passives, pin-to-contact lines (planning) or traces (built board), and the measured
//! minimum copper clearance from every part to the nearest other copper. Courtyards are drawn too (on by default; a
//! placement review hinges on them): overlapping pairs in red, pairs a design names as courtyard exceptions in amber.
//!
//! Two inputs, one look:
//! - `Scene::from_layout`: before routing. The headless molecule plan (`bun scripts/plan.ts` in
//! adom-inc/adom-tsci-molecule, its `planMolecule` JSON) plus footprints (`.kicad_mod`) and their placements.
//! - `Scene::from_circuit`: a built board's `circuit.json`, with traces.
//!
//! Coordinates are board millimetres, y up; the SVG flips y.
use anyhow::{anyhow, bail, Context, Result};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
pub type Pt = (f64, f64);
// ─── geometry ──────────────────────────────────────────────────────────────
#[derive(Clone, Debug)]
pub enum Shape {
Circle { c: Pt, r: f64 },
Poly(Vec<Pt>),
}
impl Shape {
pub fn centre(&self) -> Pt {
match self {
Shape::Circle { c, .. } => *c,
Shape::Poly(p) => {
let n = p.len() as f64;
(p.iter().map(|q| q.0).sum::<f64>() / n, p.iter().map(|q| q.1).sum::<f64>() / n)
}
}
}
fn bounds(&self) -> (f64, f64, f64, f64) {
match self {
Shape::Circle { c, r } => (c.0 - r, c.1 - r, c.0 + r, c.1 + r),
Shape::Poly(p) => p.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, q| {
(b.0.min(q.0), b.1.min(q.1), b.2.max(q.0), b.3.max(q.1))
}),
}
}
}
fn rot(p: Pt, deg: f64) -> Pt {
let a = deg.to_radians();
(p.0 * a.cos() - p.1 * a.sin(), p.0 * a.sin() + p.1 * a.cos())
}
fn rect_poly(c: Pt, w: f64, h: f64, deg: f64) -> Vec<Pt> {
[(-w / 2.0, -h / 2.0), (w / 2.0, -h / 2.0), (w / 2.0, h / 2.0), (-w / 2.0, h / 2.0)]
.iter()
.map(|&q| { let r = rot(q, deg); (c.0 + r.0, c.1 + r.1) })
.collect()
}
/// A stadium (oval / pill pad) as a 16-segment polygon.
fn stadium_poly(c: Pt, w: f64, h: f64, deg: f64) -> Vec<Pt> {
let r = w.min(h) / 2.0;
let (ax, ay) = if w >= h { (w / 2.0 - r, 0.0) } else { (0.0, h / 2.0 - r) };
let mut pts = Vec::new();
for (sx, sy, a0) in [(ax, ay, -90.0f64), (-ax, -ay, 90.0)] {
let a0 = if w >= h { a0 } else { a0 + 90.0 };
for k in 0..=8 {
let a = (a0 + k as f64 * 22.5).to_radians();
let q = rot((sx + r * a.cos(), sy + r * a.sin()), deg);
pts.push((c.0 + q.0, c.1 + q.1));
}
}
pts
}
fn seg_point_dist(p: Pt, a: Pt, b: Pt) -> f64 {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let l2 = dx * dx + dy * dy;
let t = if l2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };
((p.0 - a.0 - t * dx).powi(2) + (p.1 - a.1 - t * dy).powi(2)).sqrt()
}
fn cross(o: Pt, a: Pt, b: Pt) -> f64 { (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0) }
fn segs_cross(a: Pt, b: Pt, c: Pt, d: Pt) -> bool {
let (d1, d2, d3, d4) = (cross(c, d, a), cross(c, d, b), cross(a, b, c), cross(a, b, d));
((d1 > 0.0) != (d2 > 0.0)) && ((d3 > 0.0) != (d4 > 0.0)) && d1 != 0.0 && d2 != 0.0 && d3 != 0.0 && d4 != 0.0
}
/// A proper crossing with a tolerance: an endpoint within `eps` (cross product, mm²) of the other line counts as on
/// it. Exported outlines carry float noise (x 3.6000000000000005 at one end of an edge, 3.5999999999999996 at the
/// other), which a strict test reads as two touching courtyards crossing.
fn segs_cross_by(a: Pt, b: Pt, c: Pt, d: Pt, eps: f64) -> bool {
let (d1, d2, d3, d4) = (cross(c, d, a), cross(c, d, b), cross(a, b, c), cross(a, b, d));
d1.abs() > eps && d2.abs() > eps && d3.abs() > eps && d4.abs() > eps && ((d1 > 0.0) != (d2 > 0.0)) && ((d3 > 0.0) != (d4 > 0.0))
}
fn inside(p: Pt, poly: &[Pt]) -> bool {
let mut c = false;
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
if (a.1 > p.1) != (b.1 > p.1) && p.0 < (b.0 - a.0) * (p.1 - a.1) / (b.1 - a.1) + a.0 { c = !c; }
}
c
}
/// Distance from a point to a polygon's outline, inside or out.
fn boundary_dist(p: Pt, poly: &[Pt]) -> f64 {
(0..poly.len()).map(|i| seg_point_dist(p, poly[i], poly[(i + 1) % poly.len()])).fold(f64::MAX, f64::min)
}
/// Distance from a point to a polygon's area: 0 inside.
fn point_poly_dist(p: Pt, poly: &[Pt]) -> f64 {
if inside(p, poly) { return 0.0; }
boundary_dist(p, poly)
}
/// Edge-to-edge distance between two copper shapes; 0 when they touch or overlap.
/// Distance between two polygons' boundaries (vertex to edge, both ways): for a pour inside the board outline this
/// is its pullback from the edge; for two disjoint pours, the gap between them.
pub fn poly_gap(a: &[Pt], b: &[Pt]) -> f64 {
let one = |p: &[Pt], q: &[Pt]| p.iter().map(|&v| boundary_dist(v, q)).fold(f64::MAX, f64::min);
one(a, b).min(one(b, a))
}
pub fn distance(a: &Shape, b: &Shape) -> f64 {
match (a, b) {
(Shape::Circle { c: ca, r: ra }, Shape::Circle { c: cb, r: rb }) => {
(((ca.0 - cb.0).powi(2) + (ca.1 - cb.1).powi(2)).sqrt() - ra - rb).max(0.0)
}
(Shape::Circle { c, r }, Shape::Poly(p)) | (Shape::Poly(p), Shape::Circle { c, r }) => (point_poly_dist(*c, p) - r).max(0.0),
(Shape::Poly(p), Shape::Poly(q)) => {
let n = p.len();
let m = q.len();
for i in 0..n {
for j in 0..m {
if segs_cross(p[i], p[(i + 1) % n], q[j], q[(j + 1) % m]) { return 0.0; }
}
}
if inside(p[0], q) || inside(q[0], p) { return 0.0; }
let mut d = f64::MAX;
for &v in p { d = d.min(point_poly_dist(v, q)); }
for &v in q { d = d.min(point_poly_dist(v, p)); }
d
}
}
}
/// Whether two shapes share area (KiCad's courtyards_overlap): crossing edges, a vertex strictly inside the other, or
/// circles closer than their radii. Outlines that only touch along an edge or at a point do not overlap.
pub fn overlaps(a: &Shape, b: &Shape) -> bool {
const EPS: f64 = 1e-6;
let strictly_inside = |p: Pt, poly: &[Pt]| inside(p, poly) && boundary_dist(p, poly) > EPS;
match (a, b) {
(Shape::Circle { c: ca, r: ra }, Shape::Circle { c: cb, r: rb }) => ((ca.0 - cb.0).powi(2) + (ca.1 - cb.1).powi(2)).sqrt() < ra + rb - EPS,
(Shape::Circle { c, r }, Shape::Poly(p)) | (Shape::Poly(p), Shape::Circle { c, r }) => inside(*c, p) || point_poly_dist(*c, p) < r - EPS,
(Shape::Poly(p), Shape::Poly(q)) => {
let (n, m) = (p.len(), q.len());
(0..n).any(|i| (0..m).any(|j| segs_cross_by(p[i], p[(i + 1) % n], q[j], q[(j + 1) % m], 1e-9)))
|| p.iter().any(|v| strictly_inside(*v, q)) || q.iter().any(|v| strictly_inside(*v, p))
// equal or nested outlines with no crossing and no strictly-inside vertex: test the centroids
|| strictly_inside(Shape::Poly(p.clone()).centre(), q) || strictly_inside(Shape::Poly(q.clone()).centre(), p)
}
}
}
// ─── scene ─────────────────────────────────────────────────────────────────
#[derive(Clone, Debug, PartialEq)]
pub enum CopperKind { MachinePin, Contact, Pad }
#[derive(Clone, Debug)]
pub struct Copper {
pub owner: String, // MP1, MC3, U1, C1
pub pin: Option<String>, // pad number for footprint pads
pub net: Option<String>,
pub shape: Shape,
pub kind: CopperKind,
}
#[derive(Clone, Debug)]
pub struct Part {
pub refdes: String,
pub label: Option<String>,
pub body: Vec<Vec<Pt>>, // fab outline polygons / polylines, board frame
pub chip: bool, // drawn as a chip (body, pin numbers) rather than a passive
/// fill the body: a footprint's fab outline sits inside the pads; circuit.json only has the component's bounding
/// box, which covers the pads and the traces under the chip, so it is drawn as an outline
pub body_fill: bool,
}
#[derive(Clone, Debug)]
pub struct Trace { pub a: Pt, pub b: Pt, pub width: f64, pub bottom: bool }
#[derive(Clone, Debug, Default)]
pub struct Scene {
pub title: String,
pub outline: Vec<Pt>,
pub nominal: Option<(f64, f64, Pt)>, // nominal (wingless) width, height, centre: dotted
pub size_note: String,
pub copper: Vec<Copper>,
pub parts: Vec<Part>,
pub traces: Vec<Trace>,
pub vias: Vec<(Pt, f64)>,
pub free_slots: Vec<(Pt, f64)>,
pub lines: Vec<(Pt, Pt)>, // pin-to-contact assignment
pub courtyards: Vec<(String, Shape)>, // top-side courtyard per part (owner, closed outline or circle)
pub courtyard_exceptions: Vec<CourtyardException>,
pub show_courtyards: bool,
/// copper pours (circuit.json `pcb_copper_pour`), drawn under the copper and measured
pub pours: Vec<Pour>,
/// silkscreen text (circuit.json `pcb_silkscreen_text`), drawn when `show_silk`
pub silk: Vec<SilkText>,
pub show_silk: bool,
/// nets ringed yellow on contacts: the machine pins' nets plus any the design names as power
pub power_nets: Vec<String>,
}
#[derive(Clone, Debug)]
pub struct Pour { pub net: Option<String>, pub layer: String, pub outline: Vec<Pt> }
#[derive(Clone, Debug)]
pub struct SilkText { pub text: String, pub at: Pt, pub ccw_rotation: f64, pub size: f64, pub bottom: bool }
/// Measured pour geometry: the narrowest gap between pours of different nets on one layer, and each pour's
/// pullback from the board edge.
#[derive(Clone, Debug, serde::Serialize)]
pub struct PourReport {
pub layer: String,
pub nets: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub gap_mm: Option<f64>,
pub edge_pullback_mm: f64,
}
/// A pair of parts whose courtyards may overlap by decision (claude-pcb-f411 design.json `rules.courtyardExceptions`).
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CourtyardException { pub refs: [String; 2], #[serde(default)] pub reason: String }
#[derive(Clone, Debug, serde::Serialize)]
pub struct CourtyardOverlap { pub a: String, pub b: String, pub excepted: bool, #[serde(skip_serializing_if = "String::is_empty")] pub reason: String }
#[derive(Clone, Debug, serde::Serialize)]
pub struct Clearance { pub part: String, pub mm: f64, pub from: String, pub to: String }
impl Scene {
/// Per layer: the pours' nets, the narrowest gap between pours of different nets, and the smallest pullback of
/// any pour from the board outline.
pub fn pour_report(&self) -> Vec<PourReport> {
let mut layers: Vec<String> = self.pours.iter().map(|p| p.layer.clone()).collect();
layers.sort(); layers.dedup();
let r3 = |v: f64| (v * 1000.0).round() / 1000.0;
layers.into_iter().map(|layer| {
let ps: Vec<&Pour> = self.pours.iter().filter(|p| p.layer == layer).collect();
let mut gap: Option<f64> = None;
for (i, a) in ps.iter().enumerate() {
for b in ps.iter().skip(i + 1) {
if a.net.is_some() && a.net == b.net { continue; }
let d = poly_gap(&a.outline, &b.outline);
gap = Some(gap.map_or(d, |g: f64| g.min(d)));
}
}
let edge = ps.iter().map(|p| poly_gap(&p.outline, &self.outline)).fold(f64::MAX, f64::min);
PourReport { layer, nets: ps.iter().map(|p| p.net.clone().unwrap_or_else(|| "?".into())).collect(), gap_mm: gap.map(r3), edge_pullback_mm: r3(edge) }
}).collect()
}
fn is_power(&self, net: &Option<String>) -> bool { net.as_ref().map_or(false, |n| self.power_nets.iter().any(|p| p == n)) }
/// Minimum copper clearance from each part to the nearest copper of another owner on another (or unknown) net.
pub fn clearances(&self) -> Vec<Clearance> {
let mut out = Vec::new();
for part in &self.parts {
let mut best: Option<Clearance> = None;
for a in self.copper.iter().filter(|c| c.owner == part.refdes) {
for b in self.copper.iter().filter(|c| c.owner != part.refdes) {
if a.net.is_some() && a.net == b.net { continue; }
let d = distance(&a.shape, &b.shape);
if best.as_ref().map_or(true, |x| d < x.mm) {
let name = |c: &Copper| match &c.pin { Some(p) => format!("{}.{}", c.owner, p), None => c.owner.clone() };
best = Some(Clearance { part: part.refdes.clone(), mm: (d * 1000.0).round() / 1000.0, from: name(a), to: name(b) });
}
}
}
out.extend(best);
}
out
}
/// Pairs of parts whose courtyards share area (touching does not count), each marked if the design names it as an
/// exception.
pub fn courtyard_overlaps(&self) -> Vec<CourtyardOverlap> {
let mut out: Vec<CourtyardOverlap> = Vec::new();
for (i, (a, sa)) in self.courtyards.iter().enumerate() {
for (b, sb) in self.courtyards.iter().skip(i + 1) {
if a == b || !overlaps(sa, sb) { continue; }
let (x, y) = if a < b { (a, b) } else { (b, a) };
if out.iter().any(|o| &o.a == x && &o.b == y) { continue; }
let ex = self.courtyard_exceptions.iter().find(|e| (&e.refs[0] == a && &e.refs[1] == b) || (&e.refs[0] == b && &e.refs[1] == a));
out.push(CourtyardOverlap { a: x.clone(), b: y.clone(), excepted: ex.is_some(), reason: ex.map(|e| e.reason.clone()).unwrap_or_default() });
}
}
out.sort_by(|p, q| (p.excepted, &p.a, &p.b).cmp(&(q.excepted, &q.a, &q.b)));
out
}
/// Straight pin-to-contact lines that cross each other: a fan-out that will need vias or detours.
pub fn crossings(&self) -> usize {
let l = &self.lines;
(0..l.len()).map(|i| (i + 1..l.len()).filter(|&j| segs_cross(l[i].0, l[i].1, l[j].0, l[j].1)).count()).sum()
}
/// Empty grid slots on the board's outer rows and columns (the contact ring), between machine pins and contacts.
/// The pitch is one grid for the board: the smallest spacing on any of those lines.
fn find_free_slots(&mut self) {
let holes: Vec<(Pt, f64)> = self.copper.iter()
.filter(|c| c.kind != CopperKind::Pad)
.filter_map(|c| match c.shape { Shape::Circle { c, .. } => Some((c, 0.0)), _ => None })
.collect();
let r = self.copper.iter().find(|c| c.kind == CopperKind::Contact)
.and_then(|c| if let Shape::Circle { r, .. } = c.shape { Some(r) } else { None });
let Some(r) = r else { return };
let key = |v: f64| (v * 1000.0).round() as i64;
let mut rows: Vec<(usize, i64, Vec<f64>)> = Vec::new();
for axis in 0..2 {
let mut lines: BTreeMap<i64, Vec<f64>> = BTreeMap::new();
for (p, _) in &holes {
let (on, along) = if axis == 0 { (p.1, p.0) } else { (p.0, p.1) };
lines.entry(key(on)).or_default().push(along);
}
// only the outermost row / column on each side carries contact slots; lines across the interior
// (a wing contact column to the opposite one) are not slots
let (lo, hi) = (*lines.keys().next().unwrap_or(&0), *lines.keys().last().unwrap_or(&0));
for (on, mut v) in lines {
if v.len() < 2 || (on != lo && on != hi) { continue; }
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
rows.push((axis, on, v));
}
}
// one grid for the board: the smallest spacing on any row or column (the contact pitch)
let pitch = rows.iter().flat_map(|(_, _, v)| v.windows(2).map(|w| w[1] - w[0])).filter(|d| *d > 1e-6).fold(f64::MAX, f64::min);
if pitch == f64::MAX { return; }
let mut slots = Vec::new();
for (axis, on, v) in rows {
{
for w in v.windows(2) {
let n = ((w[1] - w[0]) / pitch).round() as i64;
for k in 1..n {
let a = w[0] + k as f64 * pitch;
let p = if axis == 0 { (a, on as f64 / 1000.0) } else { (on as f64 / 1000.0, a) };
if !slots.iter().any(|(q, _): &(Pt, f64)| key(q.0) == key(p.0) && key(q.1) == key(p.1)) { slots.push((p, r)); }
}
}
}
}
self.free_slots = slots;
}
/// One line from each contact to the same-net pad of `fanout` (default: the part with the most pads).
fn assignment_lines(&mut self, fanout: Option<&str>) {
let mut counts: HashMap<&str, usize> = HashMap::new();
for c in self.copper.iter().filter(|c| c.kind == CopperKind::Pad) { *counts.entry(&c.owner).or_default() += 1; }
let chip = fanout.map(str::to_string)
.or_else(|| counts.iter().max_by_key(|(k, n)| (**n, std::cmp::Reverse(**k))).map(|(k, _)| k.to_string()));
let Some(chip) = chip else { return };
let mut lines = Vec::new();
for c in self.copper.iter().filter(|c| c.kind == CopperKind::Contact) {
let Some(net) = &c.net else { continue };
let to = c.shape.centre();
let pad = self.copper.iter()
.filter(|p| p.owner == chip && p.net.as_ref() == Some(net))
.min_by(|a, b| {
let d = |s: &Shape| { let q = s.centre(); (q.0 - to.0).hypot(q.1 - to.1) };
d(&a.shape).partial_cmp(&d(&b.shape)).unwrap()
});
if let Some(p) = pad { lines.push((p.shape.centre(), to)); }
}
self.lines = lines;
}
fn bounds(&self) -> (f64, f64, f64, f64) {
let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
let mut add = |x: f64, y: f64| { b = (b.0.min(x), b.1.min(y), b.2.max(x), b.3.max(y)); };
for p in &self.outline { add(p.0, p.1); }
for c in &self.copper { let s = c.shape.bounds(); add(s.0, s.1); add(s.2, s.3); }
b
}
}
// ─── KiCad footprints ──────────────────────────────────────────────────────
#[derive(Clone, Debug)]
pub enum Sx { Atom(String), List(Vec<Sx>) }
impl Sx {
fn head(&self) -> Option<&str> { match self { Sx::List(v) => match v.first() { Some(Sx::Atom(a)) => Some(a), _ => None }, _ => None } }
fn items(&self) -> &[Sx] { match self { Sx::List(v) => v, _ => &[] } }
fn child(&self, name: &str) -> Option<&Sx> { self.items().iter().find(|c| c.head() == Some(name)) }
fn children<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Sx> + 'a { self.items().iter().filter(move |c| c.head() == Some(name)) }
fn atom(&self, i: usize) -> Option<&str> { match self.items().get(i) { Some(Sx::Atom(a)) => Some(a), _ => None } }
fn num(&self, i: usize) -> Option<f64> { self.atom(i).and_then(|a| a.parse().ok()) }
fn atoms(&self) -> Vec<&str> { self.items().iter().skip(1).filter_map(|c| if let Sx::Atom(a) = c { Some(a.as_str()) } else { None }).collect() }
}
pub fn parse_sexpr(text: &str) -> Result<Sx> {
let mut stack: Vec<Vec<Sx>> = vec![Vec::new()];
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'(' => stack.push(Vec::new()),
')' => {
let done = stack.pop().ok_or_else(|| anyhow!("unbalanced )"))?;
stack.last_mut().ok_or_else(|| anyhow!("unbalanced )"))?.push(Sx::List(done));
}
'"' => {
let mut s = String::new();
while let Some(c) = chars.next() {
match c { '\\' => { if let Some(n) = chars.next() { s.push(n); } } '"' => break, _ => s.push(c) }
}
stack.last_mut().unwrap().push(Sx::Atom(s));
}
c if c.is_whitespace() => {}
c => {
let mut s = String::from(c);
while let Some(&n) = chars.peek() { if n == '(' || n == ')' || n.is_whitespace() { break; } s.push(n); chars.next(); }
stack.last_mut().unwrap().push(Sx::Atom(s));
}
}
}
if stack.len() != 1 { bail!("unbalanced ("); }
stack.pop().unwrap().into_iter().next().ok_or_else(|| anyhow!("empty file"))
}
/// A footprint's copper pads (pin number, shape in the footprint frame, y up) and its fab outline.
pub struct Footprint { pub pads: Vec<(String, Shape)>, pub fab: Vec<Vec<Pt>>, pub courtyard: Vec<Shape> }
/// Join F.CrtYd line segments into closed loops (KiCad footprints draw courtyards as separate fp_lines).
fn chain_loops(mut segs: Vec<(Pt, Pt)>) -> Vec<Vec<Pt>> {
let near = |a: Pt, b: Pt| (a.0 - b.0).abs() < 1e-4 && (a.1 - b.1).abs() < 1e-4;
let mut loops = Vec::new();
while let Some((a, b)) = segs.pop() {
let mut pts = vec![a, b];
while let Some(k) = segs.iter().position(|(p, q)| near(*p, *pts.last().unwrap()) || near(*q, *pts.last().unwrap())) {
let (p, q) = segs.swap_remove(k);
pts.push(if near(p, *pts.last().unwrap()) { q } else { p });
if near(*pts.last().unwrap(), pts[0]) { break; }
}
if pts.len() > 3 && near(*pts.last().unwrap(), pts[0]) { pts.pop(); loops.push(pts); }
}
loops
}
pub fn read_footprint(path: &Path) -> Result<Footprint> {
let text = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
let root = parse_sexpr(&text).with_context(|| format!("parse {}", path.display()))?;
let xy = |s: &Sx| -> Option<Pt> { Some((s.num(1)?, -s.num(2)?)) }; // KiCad y down -> y up
let mut pads = Vec::new();
for pad in root.children("pad") {
let num = pad.atom(1).unwrap_or("").to_string();
let shape = pad.atom(3).unwrap_or("rect");
let layers = pad.child("layers").map(|l| l.atoms().join(" ")).unwrap_or_default();
if !layers.contains(".Cu") || num.is_empty() { continue; }
let at = pad.child("at").ok_or_else(|| anyhow!("pad {num} has no (at)"))?;
let c = xy(at).ok_or_else(|| anyhow!("pad {num}: bad (at)"))?;
// KiCad pad angles are clockwise in y-down, which is counter-clockwise in y-up
let deg = at.num(3).unwrap_or(0.0);
let size = pad.child("size").ok_or_else(|| anyhow!("pad {num} has no (size)"))?;
let (w, h) = (size.num(1).unwrap_or(0.0), size.num(2).unwrap_or(0.0));
let s = match shape {
"circle" => Shape::Circle { c, r: w / 2.0 },
"oval" => Shape::Poly(stadium_poly(c, w, h, deg)),
_ => Shape::Poly(rect_poly(c, w, h, deg)),
};
pads.push((num, s));
}
let mut fab = Vec::new();
let (mut courtyard, mut crt_segs) = (Vec::new(), Vec::new());
for item in root.items() {
let layer = item.child("layer").and_then(|l| l.atom(1));
if layer == Some("F.CrtYd") {
let (s, e) = (item.child("start").and_then(|s| xy(s)), item.child("end").and_then(|s| xy(s)));
match item.head() {
Some("fp_line") => if let (Some(a), Some(b)) = (s, e) { crt_segs.push((a, b)); },
Some("fp_rect") => if let (Some(a), Some(b)) = (s, e) { courtyard.push(Shape::Poly(vec![a, (b.0, a.1), b, (a.0, b.1)])); },
Some("fp_poly") => if let Some(pts) = item.child("pts") { courtyard.push(Shape::Poly(pts.children("xy").filter_map(|p| xy(p)).collect())); },
Some("fp_circle") => if let (Some(c), Some(e)) = (item.child("center").and_then(|s| xy(s)), e) {
courtyard.push(Shape::Circle { c, r: ((e.0 - c.0).powi(2) + (e.1 - c.1).powi(2)).sqrt() });
},
_ => {}
}
continue;
}
let on_fab = layer == Some("F.Fab");
if !on_fab { continue; }
match item.head() {
Some("fp_poly") => if let Some(pts) = item.child("pts") { fab.push(pts.children("xy").filter_map(|p| xy(p)).collect()); },
Some("fp_line") => if let (Some(a), Some(b)) = (item.child("start").and_then(|s| xy(s)), item.child("end").and_then(|s| xy(s))) { fab.push(vec![a, b]); },
Some("fp_rect") => if let (Some(a), Some(b)) = (item.child("start").and_then(|s| xy(s)), item.child("end").and_then(|s| xy(s))) {
fab.push(vec![a, (b.0, a.1), b, (a.0, b.1), a]);
},
_ => {}
}
}
courtyard.extend(chain_loops(crt_segs).into_iter().map(Shape::Poly));
Ok(Footprint { pads, fab, courtyard })
}
fn place(p: Pt, at: Pt, deg: f64) -> Pt { let q = rot(p, deg); (at.0 + q.0, at.1 + q.1) }
fn place_shape(s: &Shape, at: Pt, deg: f64) -> Shape {
match s {
Shape::Circle { c, r } => Shape::Circle { c: place(*c, at, deg), r: *r },
Shape::Poly(p) => Shape::Poly(p.iter().map(|q| place(*q, at, deg)).collect()),
}
}
// ─── input 1: headless plan + footprints ───────────────────────────────────
/// The planning input: `plan` is `planMolecule`'s JSON (inline, or a path relative to the layout file).
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Layout {
#[serde(default)] pub title: Option<String>,
pub plan: Value,
/// relabel contacts (e.g. a turned chip re-orders which net each slot carries): designator -> net
#[serde(default)] pub contact_nets: BTreeMap<String, String>,
/// machine pin nets (e.g. MP1: GND); unlabelled pins show their designator
#[serde(default)] pub machine_pin_nets: BTreeMap<String, String>,
#[serde(default)] pub parts: Vec<LayoutPart>,
/// the part the assignment lines fan out from (default: the part with the most pads)
#[serde(default)] pub fanout: Option<String>,
/// pairs whose courtyards may overlap by decision; drawn in amber, not red
#[serde(default)] pub courtyard_exceptions: Vec<CourtyardException>,
/// nets ringed yellow on contacts, beyond the machine pins' nets (which are power by the molecule rule)
#[serde(default)] pub power_nets: Vec<String>,
}
#[derive(serde::Deserialize)]
pub struct LayoutPart {
#[serde(rename = "ref")] pub refdes: String,
pub footprint: String,
#[serde(default)] pub x: f64,
#[serde(default)] pub y: f64,
#[serde(default)] pub rotation: f64,
/// pad number -> net
#[serde(default)] pub pins: BTreeMap<String, String>,
#[serde(default)] pub label: Option<String>,
}
impl Scene {
pub fn from_layout(path: &Path) -> Result<Scene> {
let base = path.parent().unwrap_or(Path::new(".")).to_path_buf();
let layout: Layout = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?)
.with_context(|| format!("{}: not a plan-view layout", path.display()))?;
Scene::from_layout_value(layout, &base, path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default())
}
pub fn from_layout_value(layout: Layout, base: &Path, fallback_title: String) -> Result<Scene> {
let plan: Value = match &layout.plan {
Value::String(p) => serde_json::from_str(&std::fs::read_to_string(base.join(p)).with_context(|| format!("read plan {p}"))?)?,
v => v.clone(),
};
let board = plan.get("board").ok_or_else(|| anyhow!("plan has no `board`: expected planMolecule JSON (bun scripts/plan.ts)"))?;
let f = |v: &Value, k: &str| v.get(k).and_then(Value::as_f64).ok_or_else(|| anyhow!("plan: missing number `{k}`"));
let mut s = Scene { title: layout.title.clone().unwrap_or(fallback_title), show_courtyards: true, courtyard_exceptions: layout.courtyard_exceptions.clone(), ..Default::default() };
s.outline = board.get("outline").and_then(Value::as_array).ok_or_else(|| anyhow!("plan: board.outline missing"))?
.iter().map(|p| Ok((f(p, "x")?, f(p, "y")?))).collect::<Result<_>>()?;
let centre = board.get("center").map(|c| (f(c, "x").unwrap_or(0.0), f(c, "y").unwrap_or(0.0))).unwrap_or((0.0, 0.0));
let (w, h) = (f(board, "width")?, f(board, "height")?);
let (nw, nh) = (f(board, "nominalWidth")?, f(board, "nominalHeight")?);
let wings = board.get("wings");
let wing = |k: &str| wings.and_then(|w| w.get(k)).and_then(Value::as_f64).unwrap_or(0.0);
// the nominal (wingless) board sits inside the wings: centre shifted back by half the wing difference
let ncentre = (centre.0 - (wing("right") - wing("left")) / 2.0, centre.1 - (wing("top") - wing("bottom")) / 2.0);
if (nw - w).abs() > 1e-6 || (nh - h).abs() > 1e-6 { s.nominal = Some((nw, nh, ncentre)); }
let wing_note: Vec<String> = ["left", "right", "top", "bottom"].iter().filter(|k| wing(k) > 1e-6).map(|k| format!("{} {}", k, fmt_mm(wing(k)))).collect();
s.size_note = format!("{} x {} mm{}", fmt_mm(w), fmt_mm(h), if wing_note.is_empty() { String::new() } else { format!(" (wings: {})", wing_note.join(", ")) });
for p in plan.get("machinePins").and_then(Value::as_array).into_iter().flatten() {
let name = p.get("name").and_then(Value::as_str).unwrap_or("MP").to_string();
let c = (f(p, "x")?, f(p, "y")?);
// the library's courtyard: a circle of the part's bounding box less 0.01 (r 0.99 on a 2 mm pin)
if let Some(bb) = p.get("boundingBox").and_then(Value::as_f64) { s.courtyards.push((name.clone(), Shape::Circle { c, r: bb / 2.0 - 0.01 })); }
s.copper.push(Copper {
net: layout.machine_pin_nets.get(&name).cloned(), owner: name, pin: None, kind: CopperKind::MachinePin,
shape: Shape::Circle { c, r: f(p, "holeOD")? / 2.0 },
});
}
for c in plan.get("contacts").and_then(Value::as_array).into_iter().flatten() {
let d = c.get("designator").and_then(Value::as_str).unwrap_or("MC").to_string();
let net = layout.contact_nets.get(&d).cloned().or_else(|| c.get("net").and_then(Value::as_str).map(str::to_string));
let at = (f(c, "x")?, f(c, "y")?);
if let Some(bb) = c.get("boundingBox").and_then(Value::as_f64) { s.courtyards.push((d.clone(), Shape::Circle { c: at, r: bb / 2.0 - 0.01 })); }
s.copper.push(Copper { owner: d, pin: None, net, kind: CopperKind::Contact, shape: Shape::Circle { c: at, r: f(c, "holeOD")? / 2.0 } });
}
for part in &layout.parts {
let fp = read_footprint(&base.join(&part.footprint))?;
let at = (part.x, part.y);
for cy in &fp.courtyard { s.courtyards.push((part.refdes.clone(), place_shape(cy, at, part.rotation))); }
for (num, shape) in &fp.pads {
s.copper.push(Copper { owner: part.refdes.clone(), pin: Some(num.clone()), net: part.pins.get(num).cloned(), kind: CopperKind::Pad, shape: place_shape(shape, at, part.rotation) });
}
s.parts.push(Part {
refdes: part.refdes.clone(), label: part.label.clone(),
body: fp.fab.iter().map(|p| p.iter().map(|q| place(*q, at, part.rotation)).collect()).collect(),
chip: fp.pads.len() > 3,
body_fill: true,
});
}
let mut power: Vec<String> = layout.machine_pin_nets.values().cloned().chain(layout.power_nets.iter().cloned()).collect();
power.sort(); power.dedup();
s.power_nets = power;
s.find_free_slots();
s.assignment_lines(layout.fanout.as_deref());
Ok(s)
}
}
fn fmt_mm(v: f64) -> String { let s = format!("{:.3}", v); s.trim_end_matches('0').trim_end_matches('.').to_string() }
// ─── input 2: a built board's circuit.json ─────────────────────────────────
fn of<'a>(cj: &'a [Value], t: &'a str) -> impl Iterator<Item = &'a Value> + 'a {
cj.iter().filter(move |e| e.get("type").and_then(Value::as_str) == Some(t))
}
impl Scene {
pub fn from_circuit(cj: &[Value], title: &str) -> Result<Scene> {
let s_ = |e: &Value, k: &str| e.get(k).and_then(Value::as_str).map(str::to_string);
let n_ = |e: &Value, k: &str| e.get(k).and_then(Value::as_f64);
let pt = |e: &Value| -> Option<Pt> { Some((n_(e, "x")?, n_(e, "y")?)) };
// nets: union the source ports and nets each source_trace connects; name a group by its source_net
let mut parent: HashMap<String, String> = HashMap::new();
fn find(p: &mut HashMap<String, String>, x: &str) -> String {
let up = p.get(x).cloned().unwrap_or_else(|| x.to_string());
if up == x { return up; }
let r = find(p, &up); p.insert(x.to_string(), r.clone()); r
}
for t in of(cj, "source_trace") {
let ids: Vec<String> = ["connected_source_port_ids", "connected_source_net_ids"].iter()
.flat_map(|k| t.get(*k).and_then(Value::as_array).cloned().unwrap_or_default())
.filter_map(|v| v.as_str().map(str::to_string)).collect();
for w in ids.windows(2) { let (a, b) = (find(&mut parent, &w[0]), find(&mut parent, &w[1])); if a != b { parent.insert(a, b); } }
}
let mut group_name: HashMap<String, String> = HashMap::new();
for n in of(cj, "source_net") {
if let (Some(id), Some(name)) = (s_(n, "source_net_id"), s_(n, "name")) {
let g = find(&mut parent, &id);
group_name.entry(g).or_insert(name);
}
}
let mut port_net: HashMap<String, String> = HashMap::new(); // pcb_port_id -> net name
let src_of_pcb: HashMap<String, String> = of(cj, "pcb_port").filter_map(|p| Some((s_(p, "pcb_port_id")?, s_(p, "source_port_id")?))).collect();
for (pcb, src) in &src_of_pcb {
let g = find(&mut parent, src);
if let Some(n) = group_name.get(&g) { port_net.insert(pcb.clone(), n.clone()); }
}
let src_name: HashMap<String, String> = of(cj, "source_component").filter_map(|c| Some((s_(c, "source_component_id")?, s_(c, "name")?))).collect();
let src_mpn: HashMap<String, String> = of(cj, "source_component").filter_map(|c| Some((s_(c, "source_component_id")?, s_(c, "manufacturer_part_number")?))).collect();
let comp_name: HashMap<String, String> = of(cj, "pcb_component")
.filter_map(|c| Some((s_(c, "pcb_component_id")?, src_name.get(&s_(c, "source_component_id")?)?.clone()))).collect();
let pin_of = |e: &Value| -> Option<String> {
let hints: Vec<String> = e.get("port_hints").and_then(Value::as_array).cloned().unwrap_or_default().iter().filter_map(|v| v.as_str().map(str::to_string)).collect();
hints.iter().find(|h| h.chars().all(|c| c.is_ascii_digit())).cloned()
.or_else(|| hints.iter().find_map(|h| h.strip_prefix("pin").map(str::to_string)))
.or_else(|| hints.first().cloned())
};
let mut s = Scene { title: title.to_string(), show_courtyards: true, ..Default::default() };
let board = of(cj, "pcb_board").next().ok_or_else(|| anyhow!("circuit.json has no pcb_board"))?;
let outline: Vec<Pt> = board.get("outline").and_then(Value::as_array).map(|o| o.iter().filter_map(pt).collect()).unwrap_or_default();
let (w, h) = (n_(board, "width").unwrap_or(0.0), n_(board, "height").unwrap_or(0.0));
let c = board.get("center").and_then(pt).unwrap_or((0.0, 0.0));
s.outline = if outline.len() >= 3 { outline } else { rect_poly(c, w, h, 0.0) };
s.size_note = format!("{} x {} mm", fmt_mm(w), fmt_mm(h));
let kind_of = |name: &str| if name.starts_with("MP") && name[2..].chars().all(|c| c.is_ascii_digit()) { CopperKind::MachinePin }
else if name.starts_with("MC") && name[2..].chars().all(|c| c.is_ascii_digit()) { CopperKind::Contact } else { CopperKind::Pad };
let mut pad_counts: HashMap<String, usize> = HashMap::new();
let mut push = |s: &mut Scene, e: &Value, shape: Shape| {
let owner = s_(e, "pcb_component_id").and_then(|id| comp_name.get(&id).cloned()).unwrap_or_else(|| "?".into());
let kind = kind_of(&owner);
let net = s_(e, "pcb_port_id").and_then(|p| port_net.get(&p).cloned());
let pin = if kind == CopperKind::Pad { pin_of(e) } else { None };
*pad_counts.entry(owner.clone()).or_default() += 1;
s.copper.push(Copper { owner, pin, net, shape, kind });
};
for e in of(cj, "pcb_smtpad") {
if e.get("layer").and_then(Value::as_str) == Some("bottom") { continue; }
let Some(c) = pt(e) else { continue };
let deg = n_(e, "ccw_rotation").or_else(|| n_(e, "rotation")).unwrap_or(0.0);
let shape = match s_(e, "shape").as_deref() {
Some("circle") => Shape::Circle { c, r: n_(e, "radius").unwrap_or(0.0) },
Some("polygon") => Shape::Poly(e.get("points").and_then(Value::as_array).map(|p| p.iter().filter_map(pt).collect()).unwrap_or_default()),
Some("pill") => Shape::Poly(stadium_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), deg)),
_ => Shape::Poly(rect_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), deg)),
};
push(&mut s, e, shape);
}
for e in of(cj, "pcb_plated_hole") {
let Some(c) = pt(e) else { continue };
let shape = match s_(e, "shape").as_deref() {
Some("circle") => Shape::Circle { c, r: n_(e, "outer_diameter").unwrap_or(0.0) / 2.0 },
Some("pill") | Some("oval") => Shape::Poly(stadium_poly(c, n_(e, "outer_width").unwrap_or(0.0), n_(e, "outer_height").unwrap_or(0.0), n_(e, "ccw_rotation").unwrap_or(0.0))),
_ => Shape::Poly(rect_poly(c, n_(e, "rect_pad_width").or_else(|| n_(e, "outer_width")).unwrap_or(0.0), n_(e, "rect_pad_height").or_else(|| n_(e, "outer_height")).unwrap_or(0.0), 0.0)),
};
push(&mut s, e, shape);
}
for comp in of(cj, "pcb_component") {
let Some(name) = s_(comp, "pcb_component_id").and_then(|id| comp_name.get(&id).cloned()) else { continue };
if kind_of(&name) != CopperKind::Pad || !pad_counts.contains_key(&name) { continue; }
let chip = pad_counts[&name] > 3;
let body = if chip {
let (cw, ch) = (n_(comp, "width").unwrap_or(0.0), n_(comp, "height").unwrap_or(0.0));
comp.get("center").and_then(pt).map(|c| vec![rect_poly(c, cw, ch, n_(comp, "rotation").unwrap_or(0.0))]).unwrap_or_default()
} else { vec![] };
let label = s_(comp, "source_component_id").and_then(|id| src_mpn.get(&id).cloned());
s.parts.push(Part { refdes: name, label, body, chip, body_fill: false });
}
for t in of(cj, "pcb_trace") {
let pts: Vec<&Value> = t.get("route").and_then(Value::as_array).map(|r| r.iter().collect()).unwrap_or_default();
for w in pts.windows(2) {
let (a, b) = (w[0], w[1]);
if s_(a, "route_type").as_deref() != Some("wire") || s_(b, "route_type").as_deref() != Some("wire") { continue; }
if s_(a, "layer") != s_(b, "layer") { continue; }
if let (Some(pa), Some(pb)) = (pt(a), pt(b)) {
s.traces.push(Trace { a: pa, b: pb, width: n_(a, "width").unwrap_or(0.15), bottom: s_(a, "layer").as_deref() == Some("bottom") });
}
}
}
// courtyards (top side; a bottom-side copy would draw the same outline twice)
for e in of(cj, "pcb_courtyard_outline").chain(of(cj, "pcb_courtyard_circle")).chain(of(cj, "pcb_courtyard_rect")) {
if e.get("layer").and_then(Value::as_str) == Some("bottom") { continue; }
let Some(owner) = s_(e, "pcb_component_id").and_then(|id| comp_name.get(&id).cloned()) else { continue };
let shape = match s_(e, "type").as_deref() {
Some("pcb_courtyard_circle") => match (e.get("center").and_then(pt), n_(e, "radius")) { (Some(c), Some(r)) => Shape::Circle { c, r }, _ => continue },
Some("pcb_courtyard_rect") => match e.get("center").and_then(pt) { Some(c) => Shape::Poly(rect_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), n_(e, "ccw_rotation").unwrap_or(0.0))), None => continue },
_ => {
let pts: Vec<Pt> = e.get("outline").and_then(Value::as_array).map(|o| o.iter().filter_map(pt).collect()).unwrap_or_default();
if pts.len() < 3 { continue; }
Shape::Poly(pts)
}
};
s.courtyards.push((owner, shape));
}
for v in of(cj, "pcb_via") { if let Some(c) = pt(v) { s.vias.push((c, n_(v, "outer_diameter").unwrap_or(0.6) / 2.0)); } }
let net_name: HashMap<String, String> = of(cj, "source_net").filter_map(|n| Some((s_(n, "source_net_id")?, s_(n, "name")?))).collect();
for e in of(cj, "pcb_copper_pour") {
let outline: Vec<Pt> = match s_(e, "shape").as_deref() {
Some("brep") => e.pointer("/brep_shape/outer_ring/vertices").and_then(Value::as_array).map(|v| v.iter().filter_map(pt).collect()).unwrap_or_default(),
Some("polygon") => e.get("points").and_then(Value::as_array).map(|v| v.iter().filter_map(pt).collect()).unwrap_or_default(),
Some("rect") => match e.get("center").and_then(pt) { Some(c) => rect_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), n_(e, "rotation").unwrap_or(0.0)), None => vec![] },
_ => vec![],
};
if outline.len() < 3 { continue; }
let net = s_(e, "source_net_id").and_then(|id| net_name.get(&id).cloned());
s.pours.push(Pour { net, layer: s_(e, "layer").unwrap_or_else(|| "top".into()), outline });
}
for e in of(cj, "pcb_silkscreen_text") {
let Some(at) = e.get("anchor_position").and_then(pt) else { continue };
s.silk.push(SilkText {
text: s_(e, "text").unwrap_or_default(), at, ccw_rotation: n_(e, "ccw_rotation").unwrap_or(0.0),
size: n_(e, "font_size").unwrap_or(0.4), bottom: s_(e, "layer").as_deref() == Some("bottom"),
});
}
// machine pins carry power only (molecule rule), so their nets are the power nets
let mut power: Vec<String> = s.copper.iter().filter(|c| c.kind == CopperKind::MachinePin).filter_map(|c| c.net.clone()).collect();
power.sort(); power.dedup();
s.power_nets = power;
s.find_free_slots();
Ok(s)
}
}
// ─── SVG ───────────────────────────────────────────────────────────────────
fn esc(t: &str) -> String { t.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) }
fn path_d(p: &[Pt], close: bool) -> String {
let mut d = String::new();
for (i, q) in p.iter().enumerate() { let _ = write!(d, "{}{:.4},{:.4}", if i == 0 { "M" } else { " L" }, q.0, -q.1); }
if close { d.push_str(" Z"); }
d
}
fn shape_svg(s: &Shape, attrs: &str) -> String {
match s {
Shape::Circle { c, r } => format!(r#"<circle cx="{:.4}" cy="{:.4}" r="{:.4}" {attrs}/>"#, c.0, -c.1, r),
Shape::Poly(p) => format!(r#"<path d="{}" {attrs}/>"#, path_d(p, true)),
}
}
fn text_fit(label: &str, width: f64, max: f64) -> f64 { (width / (label.chars().count().max(1) as f64 * 0.62)).min(max) }
/// One scene as an SVG group at the origin, plus its frame (min x, min y in SVG space, width, height).
fn scene_group(s: &Scene) -> (String, (f64, f64, f64, f64)) {
let (x0, y0, x1, y1) = s.bounds();
let pad = 1.2;
let clear = s.clearances();
let crossings = s.crossings();
let mut notes = vec![s.size_note.clone()];
// the tightest clearances by name; on a busy board the rest as one line (the JSON report keeps every part)
let mut by_mm: Vec<&Clearance> = clear.iter().collect();
by_mm.sort_by(|a, b| a.mm.partial_cmp(&b.mm).unwrap().then(a.part.cmp(&b.part)));
let shown = if by_mm.len() > 6 { 4 } else { by_mm.len() };
for c in &by_mm[..shown] { notes.push(format!("{} to nearest copper: {:.2} mm ({} to {})", c.part, c.mm, c.from, c.to)); }
if by_mm.len() > shown { notes.push(format!("other {} parts: {:.2} mm or more to the nearest copper", by_mm.len() - shown, by_mm[shown].mm)); }
if !s.lines.is_empty() { notes.push(format!("straight pin-to-contact lines crossing: {crossings}")); }
let overlaps = if s.show_courtyards { s.courtyard_overlaps() } else { vec![] };
for r in s.pour_report() {
notes.push(format!("{} pours {}: {}edge pullback {:.2} mm", r.layer, r.nets.join(", "),
r.gap_mm.map(|g| format!("gap {g:.2} mm, ")).unwrap_or_default(), r.edge_pullback_mm));
}
if s.show_courtyards && !s.courtyards.is_empty() {
let bad: Vec<String> = overlaps.iter().filter(|o| !o.excepted).map(|o| format!("{}-{}", o.a, o.b)).collect();
let ok: Vec<String> = overlaps.iter().filter(|o| o.excepted).map(|o| format!("{}-{}", o.a, o.b)).collect();
notes.push(format!("courtyard overlaps: {}{}", if bad.is_empty() { "none".to_string() } else { bad.join(", ") },
if ok.is_empty() { String::new() } else { format!("; named exceptions: {}", ok.join(", ")) }));
}
// text scales with the board, so a 70 mm board's captions read like a 10 mm molecule's
let scale = ((x1 - x0) / 12.0).max(1.0);
let title_size = text_fit(&s.title, (x1 - x0 + 2.0 * pad) * 0.98, 0.9 * scale);
// one caption size, the largest at which every line fits the board's width (side-by-side scenes never collide)
let note_size = notes.iter().map(|n| text_fit(n, x1 - x0 + 2.0 * pad, 0.55 * scale)).fold(0.55 * scale, f64::min);
let line = note_size * 1.6;
let top = -y1 - pad - title_size * 1.8; // title above the board
let bottom = -y0 + pad + line * notes.len() as f64 + 0.4;
let frame = (x0 - pad, top - 0.6, (x1 - x0) + 2.0 * pad, bottom - (top - 0.6));
let mut g = String::new();
let cx = (x0 + x1) / 2.0;
let _ = write!(g, r##"<text x="{cx:.3}" y="{:.3}" font-size="{title_size:.3}" text-anchor="middle" fill="#111">{}</text>"##, top + title_size * 0.7, esc(&s.title));
let _ = write!(g, r##"<path d="{}" fill="#2f4a30" stroke="#999" stroke-width="0.2"/>"##, path_d(&s.outline, true));
if let Some((w, h, c)) = s.nominal {
let _ = write!(g, r##"<path d="{}" fill="none" stroke="#9c9" stroke-width="0.06" stroke-dasharray="0.15 0.25"/>"##, path_d(&rect_poly(c, w, h, 0.0), true));
}
// pours under everything else: bottom ones as seen through the board
for pour in &s.pours {
let style = if pour.layer == "bottom" { r##"fill="#4a7fd0" fill-opacity="0.32" stroke="#8fb4ee" stroke-width="0.05" stroke-dasharray="0.25 0.15""## }
else { r##"fill="#e05a3a" fill-opacity="0.28" stroke="#f09a80" stroke-width="0.05""## };
let _ = write!(g, r#"<g class="pour"><title>{} pour, {}</title><path d="{}" {style}/></g>"#, esc(pour.net.as_deref().unwrap_or("?")), esc(&pour.layer), path_d(&pour.outline, true));
}
if s.show_courtyards {
let flagged = |owner: &str, excepted: bool| overlaps.iter().any(|o| o.excepted == excepted && (o.a == owner || o.b == owner));
for (owner, cy) in &s.courtyards {
// KiCad's courtyard magenta; red where an unexcused overlap involves the part, amber where only exceptions do
let style = if flagged(owner, false) { r##"fill="#ff3b3b" fill-opacity="0.12" stroke="#ff3b3b" stroke-width="0.07""## }
else if flagged(owner, true) { r##"fill="#f5a623" fill-opacity="0.12" stroke="#f5a623" stroke-width="0.07" stroke-dasharray="0.2 0.12""## }
else { r##"fill="none" stroke="#ff26e2" stroke-width="0.04" opacity="0.8""## };
let _ = write!(g, r#"<g class="courtyard"><title>{} courtyard</title>{}</g>"#, esc(owner), shape_svg(cy, style));
}
}
for t in &s.traces {
let col = if t.bottom { "#4a7fd0" } else { "#e05a3a" };
let _ = write!(g, r#"<line x1="{:.4}" y1="{:.4}" x2="{:.4}" y2="{:.4}" stroke="{col}" stroke-width="{:.4}" stroke-linecap="round" opacity="0.9"/>"#, t.a.0, -t.a.1, t.b.0, -t.b.1, t.width);
}
for (a, b) in &s.lines {
let _ = write!(g, r##"<line x1="{:.4}" y1="{:.4}" x2="{:.4}" y2="{:.4}" stroke="#f99" stroke-width="0.07" opacity="0.85"/>"##, a.0, -a.1, b.0, -b.1);
}
// footprint pads, then chip bodies over their centres, then pin numbers
for c in s.copper.iter().filter(|c| c.kind == CopperKind::Pad) {
let chip = s.parts.iter().any(|p| p.refdes == c.owner && p.chip);
g.push_str(&shape_svg(&c.shape, if chip { r##"fill="#e44""## } else { r##"fill="#c9a227""## }));
}
for part in &s.parts {
for poly in &part.body {
let closed = poly.len() > 2;
let style = if part.chip && closed && part.body_fill { r##"fill="#222" fill-opacity="0.88" stroke="#aaa" stroke-width="0.08""## } else { r##"fill="none" stroke="#aaa" stroke-width="0.08""## };
let _ = write!(g, r#"<path d="{}" {style}/>"#, path_d(poly, closed));
}
}
for part in s.parts.iter().filter(|p| p.chip) {
let pads: Vec<&Copper> = s.copper.iter().filter(|c| c.owner == part.refdes).collect();
let (mx, my) = { let n = pads.len() as f64; (pads.iter().map(|c| c.shape.centre().0).sum::<f64>() / n, pads.iter().map(|c| c.shape.centre().1).sum::<f64>() / n) };
for c in &pads {
let Some(pin) = &c.pin else { continue };
// pin number just inside the pad's inner end, towards the part centre
let q = c.shape.centre();
let (b0, b1, b2, b3) = c.shape.bounds();
let along_x = (b2 - b0) > (b3 - b1);
let inner = if along_x { (if q.0 > mx { b0 } else { b2 }, q.1) } else { (q.0, if q.1 > my { b1 } else { b3 }) };
let off = 0.35;
let p = if along_x { (inner.0 + if q.0 > mx { -off } else { off }, inner.1) } else { (inner.0, inner.1 + if q.1 > my { -off } else { off }) };
let size = 0.3_f64.min(if along_x { b3 - b1 } else { b2 - b0 } * 0.9);
let rotate = if along_x { String::new() } else { format!(r#" transform="rotate(-90 {:.4} {:.4})""#, p.0, -p.1) };
let _ = write!(g, r##"<text x="{:.4}" y="{:.4}" font-size="{size:.3}" text-anchor="middle" dominant-baseline="central" fill="#ccc"{rotate}>{}</text>"##, p.0, -p.1, esc(pin));
if pin == "1" {
let d = if along_x { (p.0 + if q.0 > mx { -0.45 } else { 0.45 }, p.1) } else { (p.0, p.1 + if q.1 > my { -0.45 } else { 0.45 }) };
let _ = write!(g, r##"<circle cx="{:.4}" cy="{:.4}" r="0.14" fill="white"/>"##, d.0, -d.1);
}
}
// refdes and part name on two lines across the body, inside the pin-number columns
let b = pads.iter().fold((f64::MAX, f64::MIN, f64::MAX, f64::MIN), |b, c| { let s = c.shape.bounds(); (b.0.min(s.0), b.1.max(s.2), b.2.min(s.1), b.3.max(s.3)) });
// horizontal unless the chip is clearly tall; the part name only where it stays readable
let wide = (b.3 - b.2) < 1.6 * (b.1 - b.0);
let room = if wide { b.1 - b.0 } else { b.3 - b.2 } * 0.5;
let lines: Vec<String> = std::iter::once(part.refdes.clone())
.chain(part.label.clone().filter(|l| text_fit(l, room, 0.6) >= 0.28)).collect();
let size = lines.iter().map(|l| text_fit(l, room, 0.6)).fold(f64::MAX, f64::min);
let rotate = if wide { String::new() } else { format!(r#" transform="rotate(-90 {mx:.4} {:.4})""#, -my) };
for (i, l) in lines.iter().enumerate() {
let dy = (i as f64 - (lines.len() as f64 - 1.0) / 2.0) * size * 1.25;
let _ = write!(g, r##"<g{rotate}><text x="{mx:.4}" y="{:.4}" font-size="{size:.3}" text-anchor="middle" dominant-baseline="central" fill="white">{}</text></g>"##, -my + dy, esc(l));
}
}
for part in s.parts.iter().filter(|p| !p.chip) {
let pads: Vec<&Copper> = s.copper.iter().filter(|c| c.owner == part.refdes).collect();
if pads.is_empty() { continue; }
let b = pads.iter().fold((f64::MAX, f64::MIN, f64::MAX, f64::MIN), |b, c| { let s = c.shape.bounds(); (b.0.min(s.0), b.1.max(s.2), b.2.min(s.1), b.3.max(s.3)) });
let _ = write!(g, r##"<text x="{:.4}" y="{:.4}" font-size="0.45" text-anchor="middle" fill="white">{}</text>"##, (b.0 + b.1) / 2.0, -(b.3 + 0.12), esc(&part.refdes));
}
for (c, r) in &s.vias {
let _ = write!(g, r##"<circle cx="{:.4}" cy="{:.4}" r="{r:.4}" fill="#bbb" stroke="#555" stroke-width="0.04"/>"##, c.0, -c.1);
}
for (c, r) in &s.free_slots {
let _ = write!(g, r##"<circle cx="{:.4}" cy="{:.4}" r="{r:.4}" fill="none" stroke="#fc8" stroke-width="0.07" stroke-dasharray="0.18 0.14"/>"##, c.0, -c.1);
}
for c in s.copper.iter().filter(|c| c.kind != CopperKind::Pad) {
let mp = c.kind == CopperKind::MachinePin;
let style = if mp { r##"fill="#d63" stroke="#fe9" stroke-width="0.13""## }
else if s.is_power(&c.net) { r##"fill="#c33" stroke="#ffd54a" stroke-width="0.18""## }
else { r##"fill="#c33" stroke="#111" stroke-width="0.08""## };
g.push_str(&shape_svg(&c.shape, style));
let label = c.net.clone().unwrap_or_else(|| c.owner.clone());
let q = c.shape.centre();
let (b0, _, b2, _) = c.shape.bounds();
let size = text_fit(&label, (b2 - b0) * 0.92, if mp { 0.5 } else { 0.42 });
let _ = write!(g, r##"<text x="{:.4}" y="{:.4}" font-size="{size:.3}" font-weight="bold" text-anchor="middle" dominant-baseline="central" fill="white"><title>{}</title>{}</text>"##, q.0, -q.1, esc(&c.owner), esc(&label));
}
if s.show_silk {
// top silk only: bottom silk reads mirrored through the board and sits under the top-side parts
for t in s.silk.iter().filter(|t| !t.bottom) {
let fill = r##"fill="#f4f4f4""##;
let _ = write!(g, r#"<text x="{:.4}" y="{:.4}" font-size="{:.3}" text-anchor="middle" dominant-baseline="central" {fill} transform="rotate({:.3} {:.4} {:.4})">{}</text>"#,
t.at.0, -t.at.1, t.size, -t.ccw_rotation, t.at.0, -t.at.1, esc(&t.text));
}
}
for (i, n) in notes.iter().enumerate() {
let size = note_size;
let _ = write!(g, r##"<text x="{cx:.3}" y="{:.3}" font-size="{size:.3}" text-anchor="middle" fill="#111">{}</text>"##, -y0 + pad + line * (i as f64 + 0.6), esc(n));
}
(g, frame)
}
/// Scenes side by side in one SVG (two orientations of the same chip, for example).
pub fn render_svg(scenes: &[Scene]) -> String {
let mut body = String::new();
let mut x = 0.0;
let mut height: f64 = 0.0;
let gap = 2.0;
for s in scenes {
let (g, (fx, fy, fw, fh)) = scene_group(s);
let _ = write!(body, r#"<g transform="translate({:.4} {:.4})">{g}</g>"#, x - fx, -fy);
x += fw + gap;
height = height.max(fh);
}
let width = (x - gap).max(1.0);
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width:.3} {height:.3}" width="{:.0}" height="{:.0}" font-family="DejaVu Sans, Arial, sans-serif"><rect width="100%" height="100%" fill="white"/>{body}</svg>"##,
width * 40.0, height * 40.0
)
}
pub fn circuit_json_scene(path: &Path, title: &str) -> Result<Scene> {
let cj: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?)
.with_context(|| format!("{}: not circuit JSON", path.display()))?;
Scene::from_circuit(&cj, title)
}
pub fn default_circuit_json(project: &Path) -> PathBuf { project.join("dist/lib/index/circuit.json") }
/// Courtyard exceptions from a file: a design.json carrying `rules.courtyardExceptions` (the claude-pcb-f411 board
/// contract), or a bare `[{ "refs": [a, b], "reason": ... }]` list.
pub fn read_courtyard_exceptions(path: &Path) -> Result<Vec<CourtyardException>> {
let v: Value = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?)?;
let list = if v.is_array() { v } else { v.pointer("/rules/courtyardExceptions").cloned().unwrap_or(Value::Array(vec![])) };
Ok(serde_json::from_value(list).with_context(|| format!("{}: courtyard exceptions must be [{{refs: [a, b], reason}}]", path.display()))?)
}
/// The project's own exceptions, when it has a design.json that names any.
pub fn project_courtyard_exceptions(project: &Path) -> Vec<CourtyardException> {
let p = project.join("design.json");
if p.exists() { read_courtyard_exceptions(&p).unwrap_or_default() } else { vec![] }
}
/// A claude-pcb-f411 board's design.json applied to its circuit.json scene: courtyard exceptions
/// (`rules.courtyardExceptions`), machine pin roles (`mountingPinRoles`, for pins the circuit leaves unnamed) and
/// extra power nets (`powerNets`) for the yellow rings.
pub fn apply_design(scene: &mut Scene, design: &Path) -> Result<()> {
let v: Value = serde_json::from_str(&std::fs::read_to_string(design).with_context(|| format!("read {}", design.display()))?)
.with_context(|| format!("{}: not JSON", design.display()))?;
scene.courtyard_exceptions = read_courtyard_exceptions(design)?;
if let Some(roles) = v.get("mountingPinRoles").and_then(Value::as_object) {
for c in scene.copper.iter_mut().filter(|c| c.kind == CopperKind::MachinePin && c.net.is_none()) {
if let Some(n) = roles.get(&c.owner).and_then(Value::as_str) { c.net = Some(n.to_string()); }
}
scene.power_nets.extend(roles.values().filter_map(Value::as_str).map(str::to_string));
}
scene.power_nets.extend(v.get("powerNets").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string));
scene.power_nets.sort(); scene.power_nets.dedup();
Ok(())
}
/// The design.json of the board a circuit.json was built from (<board>/dist/lib/index/circuit.json), if any.
pub fn default_design(circuit: &Path) -> Option<PathBuf> {
let d = circuit.parent()?.parent()?.parent()?.parent()?.join("design.json");
d.exists().then_some(d)
}
/// Scenes for `render`: planning layouts side by side, or one built board (circuit.json + its design.json).
pub fn scenes_for(layouts: &[PathBuf], circuit: Option<&Path>, design: Option<&Path>, title: Option<&str>, courtyards: bool) -> Result<Vec<Scene>> {
let mut scenes = if let Some(cj) = circuit {
let title = title.map(str::to_string).unwrap_or_else(|| {
cj.parent().and_then(|p| p.parent()).and_then(|p| p.parent()).and_then(|p| p.parent())
.and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "board".into())
});
let mut scene = circuit_json_scene(cj, &title)?;
if let Some(d) = design.map(Path::to_path_buf).or_else(|| default_design(cj)) { apply_design(&mut scene, &d)?; }
scene.show_silk = true;
vec![scene]
} else {
layouts.iter().map(|p| Scene::from_layout(p)).collect::<Result<Vec<_>>>()?
};
if !courtyards { for s in &mut scenes { s.show_courtyards = false; } }
Ok(scenes)
}
/// The measurements behind a render, as JSON (positions included, so a render can be checked against its source).
pub fn report(scenes: &[Scene], out: &Path) -> Value {
let r4 = |v: f64| (v * 10000.0).round() / 10000.0;
Value::Array(scenes.iter().map(|s| serde_json::json!({
"title": s.title, "size": s.size_note, "out": out,
"machinePins": s.copper.iter().filter(|c| c.kind == CopperKind::MachinePin).map(|c| { let q = c.shape.centre(); serde_json::json!({"name": c.owner, "net": c.net, "x": r4(q.0), "y": r4(q.1)}) }).collect::<Vec<_>>(),
"contacts": s.copper.iter().filter(|c| c.kind == CopperKind::Contact).map(|c| { let q = c.shape.centre(); serde_json::json!({"name": c.owner, "net": c.net, "x": r4(q.0), "y": r4(q.1), "power": s.is_power(&c.net)}) }).collect::<Vec<_>>(),
"pads": s.copper.iter().filter(|c| c.kind == CopperKind::Pad).map(|c| { let q = c.shape.centre(); serde_json::json!({"part": c.owner, "pin": c.pin, "net": c.net, "x": r4(q.0), "y": r4(q.1)}) }).collect::<Vec<_>>(),
"clearances": s.clearances(), "crossings": s.crossings(),
"freeSlots": s.free_slots.iter().map(|(p, _)| [p.0, p.1]).collect::<Vec<_>>(),
"courtyardOverlaps": if s.show_courtyards { s.courtyard_overlaps() } else { vec![] },
"pours": s.pour_report(),
"silk": s.silk.iter().map(|t| serde_json::json!({"text": t.text, "x": t.at.0, "y": t.at.1, "ccwRotation": t.ccw_rotation, "size": t.size, "bottom": t.bottom})).collect::<Vec<_>>(),
})).collect())
}
/// One summary block per scene, as the CLI prints it.
pub fn summary(scenes: &[Scene]) -> Vec<String> {
let mut out = Vec::new();
for s in scenes {
out.push(format!("{}: {}", s.title, s.size_note));
for c in s.clearances() { out.push(format!(" {} to nearest copper: {:.2} mm ({}-{})", c.part, c.mm, c.from, c.to)); }
if !s.lines.is_empty() { out.push(format!(" pin-to-contact lines crossing: {}", s.crossings())); }
for r in s.pour_report() {
out.push(format!(" {} pours {}: {}edge pullback {:.3} mm", r.layer, r.nets.join(", "), r.gap_mm.map(|g| format!("gap {g:.3} mm, ")).unwrap_or_default(), r.edge_pullback_mm));
}
if s.show_courtyards {
for o in s.courtyard_overlaps() {
out.push(format!(" courtyards overlap: {}-{}{}", o.a, o.b, if o.excepted { format!(" (named exception: {})", o.reason) } else { String::new() }));
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
const FP: &str = r#"(footprint "T" (layer "F.Cu")
(fp_poly (pts (xy -1 -1) (xy 1 -1) (xy 1 1) (xy -1 1)) (stroke (width 0.1) (type solid)) (fill no) (layer "F.Fab"))
(fp_line (start -2.2 -1.2) (end 2.2 -1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))
(fp_line (start 2.2 -1.2) (end 2.2 1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))
(fp_line (start -2.2 1.2) (end 2.2 1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))
(fp_line (start -2.2 1.2) (end -2.2 -1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))
(pad "1" smd rect (at -1.5 -0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))
(pad "2" smd rect (at -1.5 0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))
(pad "3" smd rect (at 1.5 0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))
(pad "4" smd rect (at 1.5 -0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))
(pad "" np_thru_hole circle (at 0 0) (size 0.5 0.5) (drill 0.5) (layers "*.Cu")))"#;
fn plan() -> Value {
// planMolecule shape: 8x8 MediumShort, contacts on the left column
json!({
"board": {"width": 10, "height": 10, "nominalWidth": 10, "nominalHeight": 10, "center": {"x": 0, "y": 0}, "cornerRadius": 0,
"wings": {"left": 0, "right": 0, "top": 0, "bottom": 0},
"outline": [{"x": 5, "y": -5}, {"x": 5, "y": 5}, {"x": -5, "y": 5}, {"x": -5, "y": -5}]},
"machinePins": [{"name": "MP1", "x": -4, "y": -4, "holeOD": 1.6, "boundingBox": 2}, {"name": "MP2", "x": -4, "y": 4, "holeOD": 1.6, "boundingBox": 2},
{"name": "MP3", "x": 4, "y": 4, "holeOD": 1.6, "boundingBox": 2}, {"name": "MP4", "x": 4, "y": -4, "holeOD": 1.6, "boundingBox": 2}],
"contacts": [{"designator": "MC1", "net": "A", "x": -4, "y": -2, "holeOD": 1.3, "boundingBox": 2}, {"designator": "MC2", "net": "B", "x": -4, "y": 2, "holeOD": 1.3, "boundingBox": 2},
{"designator": "MC3", "net": "C", "x": 4, "y": 0, "holeOD": 1.3, "boundingBox": 2}]
})
}
fn layout_scene(rotation: f64) -> Scene {
// one directory per call: the tests run in parallel and must not read each other's half-written files
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = N.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let dir = std::env::temp_dir().join(format!("plan-view-test-{}-{}-{n}", std::process::id(), rotation));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("t.kicad_mod"), FP).unwrap();
let layout: Layout = serde_json::from_value(json!({
"title": "t", "plan": plan(), "machinePinNets": {"MP1": "GND"},
"parts": [{"ref": "U1", "footprint": "t.kicad_mod", "rotation": rotation, "pins": {"1": "B", "2": "A", "3": "C", "4": "GND"}}]
})).unwrap();
Scene::from_layout_value(layout, &dir, "x".into()).unwrap()
}
#[test]
fn parses_pads_fab_and_skips_non_copper_names() {
let dir = std::env::temp_dir().join(format!("plan-view-fp-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("t.kicad_mod"), FP).unwrap();
let fp = read_footprint(&dir.join("t.kicad_mod")).unwrap();
assert_eq!(fp.pads.iter().map(|p| p.0.as_str()).collect::<Vec<_>>(), ["1", "2", "3", "4"]);
// KiCad y down -> y up: pad 1 at (-1.5, -0.5) is at (-1.5, +0.5)
assert!((fp.pads[0].1.centre().1 - 0.5).abs() < 1e-9);
assert_eq!(fp.fab.len(), 1);
}
#[test]
fn distances() {
let a = Shape::Circle { c: (0.0, 0.0), r: 0.65 };
let b = Shape::Circle { c: (2.0, 0.0), r: 0.65 };
assert!((distance(&a, &b) - 0.7).abs() < 1e-9);
let r = Shape::Poly(rect_poly((3.0, 0.0), 1.0, 1.0, 0.0));
assert!((distance(&a, &r) - 1.85).abs() < 1e-9);
// a 1 mm square turned 45 degrees at x 4.5: its left corner is at 4.5 - 0.7071, 0.2929 from the edge at 3.5
let r2 = Shape::Poly(rect_poly((4.5, 0.0), 1.0, 1.0, 45.0));
assert!((distance(&r, &r2) - (1.0 - 0.5f64.hypot(0.5))).abs() < 1e-9);
assert_eq!(distance(&r, &Shape::Poly(rect_poly((3.2, 0.0), 1.0, 1.0, 0.0))), 0.0);
}
#[test]
fn plan_scene_labels_nets_and_measures_clearance() {
let s = layout_scene(0.0);
let labels: Vec<_> = s.copper.iter().filter(|c| c.kind != CopperKind::Pad).map(|c| c.net.clone().unwrap_or(c.owner.clone())).collect();
assert_eq!(labels, ["GND", "MP2", "MP3", "MP4", "A", "B", "C"]);
let c = s.clearances();
assert_eq!(c.len(), 1);
// U1 pad 4 (GND, x 1..2, y 0.3..0.7) to MC3 (C, at 4,0, r 0.65): the nearest other-net copper; pad 3 is on C
// itself, and the left pads sit 2.4 mm from the other-net contacts
assert_eq!((c[0].part.as_str(), c[0].from.as_str(), c[0].to.as_str()), ("U1", "U1.4", "MC3"));
assert!((c[0].mm - ((4.0f64 + 0.09).sqrt() - 0.65)).abs() < 1e-3);
assert_eq!(s.lines.len(), 3);
}
#[test]
fn crossings_follow_rotation() {
assert_eq!(layout_scene(0.0).crossings(), 0);
// turned 180: A and B end up on the right, C on the left, so the lines cross the chip and each other
assert!(layout_scene(180.0).crossings() > 0);
}
#[test]
fn free_slots_between_contacts() {
let s = layout_scene(0.0);
// left column: MP1 -4, MC1 -2, (0 empty), MC2 2, MP2 4 -> one free slot at (-4, 0)
assert!(s.free_slots.iter().any(|(p, _)| (p.0 + 4.0).abs() < 1e-9 && p.1.abs() < 1e-9));
// right column: MP4 -4, MC3 0, MP3 4 -> free at (4, -2) and (4, 2); the empty top and bottom rows between the
// machine pins have three free slots each, on the board's 2 mm grid
assert!(s.free_slots.iter().any(|(p, _)| (p.0 - 4.0).abs() < 1e-9 && (p.1 - 2.0).abs() < 1e-9));
assert_eq!(s.free_slots.len(), 9);
}
#[test]
fn circuit_scene_names_nets_and_draws_traces() {
let cj: Vec<Value> = serde_json::from_value(json!([
{"type": "pcb_board", "center": {"x": 0, "y": 0}, "width": 10, "height": 10},
{"type": "source_component", "source_component_id": "s1", "name": "MC1"},
{"type": "source_component", "source_component_id": "s2", "name": "U1"},
{"type": "pcb_component", "pcb_component_id": "p1", "source_component_id": "s1", "center": {"x": -4, "y": 0}, "width": 2, "height": 2},
{"type": "pcb_component", "pcb_component_id": "p2", "source_component_id": "s2", "center": {"x": 0, "y": 0}, "width": 3, "height": 2},
{"type": "source_port", "source_port_id": "sp1"}, {"type": "source_port", "source_port_id": "sp2"},
{"type": "pcb_port", "pcb_port_id": "pp1", "source_port_id": "sp1"}, {"type": "pcb_port", "pcb_port_id": "pp2", "source_port_id": "sp2"},
{"type": "source_net", "source_net_id": "n1", "name": "SDA"},
{"type": "source_trace", "connected_source_port_ids": ["sp1", "sp2"], "connected_source_net_ids": ["n1"]},
{"type": "pcb_plated_hole", "pcb_component_id": "p1", "pcb_port_id": "pp1", "shape": "circle", "x": -4, "y": 0, "outer_diameter": 1.3},
{"type": "pcb_smtpad", "pcb_component_id": "p2", "pcb_port_id": "pp2", "shape": "rect", "x": -1, "y": 0, "width": 0.6, "height": 0.4, "layer": "top", "port_hints": ["1", "pin1"]},
{"type": "pcb_trace", "route": [{"route_type": "wire", "x": -4, "y": 0, "width": 0.2, "layer": "top"}, {"route_type": "wire", "x": -1, "y": 0, "width": 0.2, "layer": "top"}]}
])).unwrap();
let s = Scene::from_circuit(&cj, "b").unwrap();
let mc = s.copper.iter().find(|c| c.owner == "MC1").unwrap();
assert_eq!(mc.net.as_deref(), Some("SDA"));
assert_eq!(s.copper.iter().find(|c| c.owner == "U1").unwrap().pin.as_deref(), Some("1"));
assert_eq!(s.traces.len(), 1);
let svg = render_svg(&[s]);
assert!(svg.contains(">SDA</text>"));
}
/// A 10.4 x 14 board with two bottom pours 0.3 mm apart and 0.4 mm in from the edge (the 74HC595BQ molecule's),
/// a GND machine pin, a GND contact, a corner label at 45 degrees and one bottom silk line.
fn poured_board() -> Vec<Value> {
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| json!([{"x": x0, "y": y0}, {"x": x1, "y": y0}, {"x": x1, "y": y1}, {"x": x0, "y": y1}]);
serde_json::from_value(json!([
{"type": "pcb_board", "center": {"x": 0, "y": 0}, "width": 10.4, "height": 14},
{"type": "source_net", "source_net_id": "n1", "name": "VCC"}, {"type": "source_net", "source_net_id": "n2", "name": "GND"},
{"type": "pcb_copper_pour", "layer": "bottom", "source_net_id": "n1", "shape": "brep", "brep_shape": {"outer_ring": {"vertices": rect(-4.8, 3.025, 4.8, 6.6)}, "inner_rings": []}},
{"type": "pcb_copper_pour", "layer": "bottom", "source_net_id": "n2", "shape": "brep", "brep_shape": {"outer_ring": {"vertices": rect(-4.8, -6.6, 4.8, 2.725)}, "inner_rings": []}},
{"type": "source_component", "source_component_id": "s1", "name": "MP1"}, {"type": "source_component", "source_component_id": "s2", "name": "MC1"},
{"type": "pcb_component", "pcb_component_id": "p1", "source_component_id": "s1"}, {"type": "pcb_component", "pcb_component_id": "p2", "source_component_id": "s2"},
{"type": "source_port", "source_port_id": "sp1"}, {"type": "source_port", "source_port_id": "sp2"},
{"type": "pcb_port", "pcb_port_id": "pp1", "source_port_id": "sp1"}, {"type": "pcb_port", "pcb_port_id": "pp2", "source_port_id": "sp2"},
{"type": "source_trace", "connected_source_port_ids": ["sp1", "sp2"], "connected_source_net_ids": ["n2"]},
{"type": "pcb_plated_hole", "pcb_component_id": "p1", "pcb_port_id": "pp1", "shape": "circle", "x": -4, "y": -4, "outer_diameter": 1.6},
{"type": "pcb_plated_hole", "pcb_component_id": "p2", "pcb_port_id": "pp2", "shape": "circle", "x": 2, "y": -6, "outer_diameter": 1.3},
{"type": "pcb_silkscreen_text", "text": "GND", "anchor_position": {"x": 3.2, "y": -5.3}, "ccw_rotation": 45, "font_size": 0.4, "layer": "top"},
{"type": "pcb_silkscreen_text", "text": "UNDER", "anchor_position": {"x": 0, "y": 0}, "ccw_rotation": 0, "font_size": 0.5, "layer": "bottom"}
])).unwrap()
}
#[test]
fn pours_measure_gap_and_edge_pullback() {
let s = Scene::from_circuit(&poured_board(), "b").unwrap();
let r = s.pour_report();
assert_eq!(r.len(), 1);
assert_eq!((r[0].layer.as_str(), r[0].nets.clone()), ("bottom", vec!["VCC".to_string(), "GND".to_string()]));
assert_eq!(r[0].gap_mm, Some(0.3));
assert_eq!(r[0].edge_pullback_mm, 0.4);
// same-net pours are one region: no gap reported between them
let mut same = s.clone();
for p in &mut same.pours { p.net = Some("GND".into()); }
assert_eq!(same.pour_report()[0].gap_mm, None);
}
#[test]
fn silk_keeps_rotation_and_only_top_silk_is_drawn() {
let mut s = Scene::from_circuit(&poured_board(), "b").unwrap();
let gnd = s.silk.iter().find(|t| t.text == "GND").unwrap();
assert_eq!((gnd.ccw_rotation, gnd.size, gnd.bottom), (45.0, 0.4, false));
assert!(s.silk.iter().any(|t| t.text == "UNDER" && t.bottom));
s.show_silk = true;
let svg = render_svg(&[s]);
// SVG y is down, so a 45 degree counter-clockwise label is rotate(-45)
assert!(svg.contains(r#"transform="rotate(-45.000 3.2000 5.3000)">GND</text>"#));
assert!(!svg.contains(">UNDER</text>"));
}
#[test]
fn machine_pin_nets_ring_contacts_yellow() {
let s = Scene::from_circuit(&poured_board(), "b").unwrap();
assert_eq!(s.power_nets, vec!["GND".to_string()]);
let svg = render_svg(&[s]);
assert!(svg.contains(r##"fill="#c33" stroke="#ffd54a""##), "the GND contact is ringed");
// a layout: machinePinNets plus powerNets
let dir = std::env::temp_dir().join(format!("plan-view-power-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let layout: Layout = serde_json::from_value(json!({"plan": plan(), "machinePinNets": {"MP1": "GND"}, "powerNets": ["B"]})).unwrap();
let l = Scene::from_layout_value(layout, &dir, "x".into()).unwrap();
assert_eq!(l.power_nets, vec!["B".to_string(), "GND".to_string()]);
let svg = render_svg(&[l]);
assert_eq!(svg.matches(r##"fill="#c33" stroke="#ffd54a""##).count(), 1, "only MC2 (net B) is ringed");
}
#[test]
fn design_json_names_pins_power_nets_and_exceptions() {
let mut cj = poured_board();
// the machine pin loses its net: design.json's mountingPinRoles names it
cj.retain(|e| e.get("type").and_then(Value::as_str) != Some("source_trace"));
let mut s = Scene::from_circuit(&cj, "b").unwrap();
assert!(s.power_nets.is_empty());
let dir = std::env::temp_dir().join(format!("plan-view-design-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("design.json"), json!({
"mountingPinRoles": {"MP1": "GND"}, "powerNets": ["VIN"],
"rules": {"courtyardExceptions": [{"refs": ["U1", "MP2"], "reason": "r"}]}
}).to_string()).unwrap();
apply_design(&mut s, &dir.join("design.json")).unwrap();
assert_eq!(s.copper.iter().find(|c| c.owner == "MP1").unwrap().net.as_deref(), Some("GND"));
assert_eq!(s.power_nets, vec!["GND".to_string(), "VIN".to_string()]);
assert_eq!(s.courtyard_exceptions.len(), 1);
}
fn placed_at(x: f64, exceptions: Value) -> Scene {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = N.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let dir = std::env::temp_dir().join(format!("plan-view-cy-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("t.kicad_mod"), FP).unwrap();
let layout: Layout = serde_json::from_value(json!({
"plan": plan(), "courtyardExceptions": exceptions,
"parts": [{"ref": "U1", "footprint": "t.kicad_mod", "x": x, "y": 0}]
})).unwrap();
Scene::from_layout_value(layout, &dir, "x".into()).unwrap()
}
#[test]
fn courtyard_lines_chain_into_one_closed_outline() {
let s = placed_at(0.0, json!([]));
let u1: Vec<_> = s.courtyards.iter().filter(|(o, _)| o == "U1").collect();
assert_eq!(u1.len(), 1);
match &u1[0].1 { Shape::Poly(p) => assert_eq!(p.len(), 4), _ => panic!("expected a polygon") }
// every machine pin and contact gets the library's courtyard circle (r 0.99)
assert_eq!(s.courtyards.iter().filter(|(_, c)| matches!(c, Shape::Circle { r, .. } if (*r - 0.99).abs() < 1e-9)).count(), 7);
}
#[test]
fn courtyard_overlaps_are_flagged_unless_named() {
// U1's courtyard spans x -2.2..2.2; at x 0 it is clear of the contact column's circles (edge at -3.01)
assert!(placed_at(0.0, json!([])).courtyard_overlaps().is_empty());
// moved left by 1.5 mm its corners (-3.7, ±1.2) sit 0.85 mm from MC1 / MC2 (at -4, ±2), inside their r 0.99
let o = placed_at(-1.5, json!([])).courtyard_overlaps();
assert_eq!(o.iter().map(|o| (o.a.as_str(), o.b.as_str(), o.excepted)).collect::<Vec<_>>(), [("MC1", "U1", false), ("MC2", "U1", false)]);
// a named exception turns its pair amber; the other stays an error
let s = placed_at(-1.5, json!([{"refs": ["U1", "MC1"], "reason": "checked"}]));
let o = s.courtyard_overlaps();
assert_eq!(o.iter().map(|o| (o.a.as_str(), o.b.as_str(), o.excepted)).collect::<Vec<_>>(), [("MC2", "U1", false), ("MC1", "U1", true)]);
let svg = render_svg(&[s.clone()]);
assert!(svg.contains("#ff3b3b") && svg.contains("#f5a623"));
assert!(svg.contains("courtyard overlaps: MC2-U1; named exceptions: MC1-U1"));
let mut off = s; off.show_courtyards = false;
assert!(!render_svg(&[off]).contains("class=\"courtyard\""));
}
#[test]
fn rotated_courtyard_rects_turn_with_their_part() {
// a 1.9 x 1.1 courtyard turned 90 is 1.1 wide: at x 1.6 it clears a circle of r 0.99 at the origin
// (gap 1.6 - 0.55 - 0.99 = 0.06); unturned it would reach 1.6 - 0.95 = 0.65 and overlap
let cj: Vec<Value> = serde_json::from_value(json!([
{"type": "pcb_board", "center": {"x": 0, "y": 0}, "width": 10, "height": 10},
{"type": "source_component", "source_component_id": "s1", "name": "MC1"},
{"type": "source_component", "source_component_id": "s2", "name": "C1"},
{"type": "pcb_component", "pcb_component_id": "p1", "source_component_id": "s1", "center": {"x": 0, "y": 0}},
{"type": "pcb_component", "pcb_component_id": "p2", "source_component_id": "s2", "center": {"x": 1.6, "y": 0}},
{"type": "pcb_courtyard_circle", "pcb_component_id": "p1", "layer": "top", "center": {"x": 0, "y": 0}, "radius": 0.99},
{"type": "pcb_courtyard_rect", "pcb_component_id": "p2", "layer": "top", "center": {"x": 1.6, "y": 0}, "width": 1.9, "height": 1.1, "ccw_rotation": 90}
])).unwrap();
assert!(Scene::from_circuit(&cj, "r").unwrap().courtyard_overlaps().is_empty());
}
#[test]
fn touching_courtyards_do_not_overlap() {
let a = Shape::Poly(rect_poly((0.0, 0.0), 2.0, 2.0, 0.0));
assert!(!overlaps(&a, &Shape::Poly(rect_poly((2.0, 0.0), 2.0, 2.0, 0.0)))); // shared edge
assert!(!overlaps(&a, &Shape::Poly(rect_poly((2.0, 2.0), 2.0, 2.0, 0.0)))); // shared corner
assert!(overlaps(&a, &Shape::Poly(rect_poly((1.9, 0.5), 2.0, 2.0, 0.0)))); // 0.1 mm in
assert!(overlaps(&a, &Shape::Poly(rect_poly((0.0, 0.0), 2.0, 2.0, 0.0)))); // identical
assert!(!overlaps(&Shape::Circle { c: (0.0, 0.0), r: 1.0 }, &Shape::Circle { c: (2.0, 0.0), r: 1.0 }));
assert!(overlaps(&Shape::Circle { c: (0.0, 0.0), r: 1.0 }, &Shape::Circle { c: (1.9, 0.0), r: 1.0 }));
assert!(!overlaps(&Shape::Circle { c: (2.0, 0.0), r: 1.0 }, &a)); // touches the edge
// float noise on a shared edge (the AMS1117's U1 / C2 courtyards: shapely measures 0 mm² between them)
let u = Shape::Poly(vec![(2.15, -2.7), (3.5999999999999996, -2.7), (3.6000000000000005, 1.4999999999999996), (2.15, 1.5)]);
let c2 = Shape::Poly(vec![(5.06, -1.83), (5.06, 1.13), (3.6, 1.13), (3.6, -1.83)]);
assert!(!overlaps(&u, &c2));
}
#[test]
fn exceptions_read_from_a_design_json_or_a_list() {
let dir = std::env::temp_dir().join(format!("plan-view-ex-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("design.json"), r#"{"rules": {"courtyardExceptions": [{"refs": ["U1", "MP2"], "reason": "r"}]}}"#).unwrap();
std::fs::write(dir.join("list.json"), r#"[{"refs": ["C1", "U1"]}]"#).unwrap();
assert_eq!(project_courtyard_exceptions(&dir)[0].refs, ["U1".to_string(), "MP2".to_string()]);
assert_eq!(read_courtyard_exceptions(&dir.join("list.json")).unwrap()[0].refs[0], "C1");
assert!(project_courtyard_exceptions(&dir.join("nowhere")).is_empty());
}
#[test]
fn svg_draws_two_scenes_side_by_side() {
let svg = render_svg(&[layout_scene(0.0), layout_scene(180.0)]);
assert_eq!(svg.matches("<g transform").count(), 2);
assert!(svg.contains("stroke-dasharray=\"0.18 0.14\"")); // free slot
assert!(svg.contains("to nearest copper"));
}
}