use crate::graphic::{GraphicLayer, LayerGraphic};
use crate::{Document, Netlist, Point, Uuid, footprint};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
pub const COURTYARD_MARGIN: i32 = 250;
const PLACEMENT_SPACING: i32 = 2000;
const SEAT_GAP: i32 = 1000;
pub mod net_classes;
pub mod zones;
pub use net_classes::{ClassReason, DEFAULT_CLASS, NetClass};
pub use zones::{FillPiece, Zone};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum PadShape {
#[default]
Rect,
Circle,
Oval,
RoundRect,
Trapezoid,
Custom,
}
pub const MAX_PAD_CORNERS: usize = 1000;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PadLayers {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub cover_front: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub cover_back: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub no_paste: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mask_margin: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub paste_margin: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub paste_windows: Option<PasteWindows>,
}
impl PadLayers {
pub fn is_auto(&self) -> bool {
*self == Self::default()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PasteWindows {
pub columns: u8,
pub rows: u8,
pub gap: i32,
}
impl PasteWindows {
pub fn problem(&self) -> Option<&'static str> {
if !(1..=20).contains(&self.columns) || !(1..=20).contains(&self.rows) {
Some("needs between 1 and 20 paste windows each way")
} else if !(0..=10_000).contains(&self.gap) {
Some("needs a paste window gap between 0 and 10 mm")
} else {
None
}
}
pub fn cut(&self, aperture: &Shape) -> Vec<Shape> {
let (min, max) = aperture.bounds();
let (columns, rows) = (i64::from(self.columns.max(1)), i64::from(self.rows.max(1)));
let gap = i64::from(self.gap.max(0));
let span = |lo: i32, hi: i32, n: i64, k: i64| {
let (lo, hi) = (i64::from(lo), i64::from(hi));
let cell = (hi - lo - gap * (n - 1)) as f64 / n as f64;
let start = lo as f64 + k as f64 * (cell + gap as f64);
(start.round() as i32, (start + cell).round() as i32)
};
let mut out = vec![];
for row in 0..rows {
let (y0, y1) = span(min.y, max.y, rows, row);
for column in 0..columns {
let (x0, x1) = span(min.x, max.x, columns, column);
if x1 > x0 && y1 > y0 {
let (lo, hi) = (Point::new(x0, y0), Point::new(x1, y1));
if aperture.covers_box(lo, hi) {
out.push(Shape::Rect { min: lo, max: hi });
}
}
}
}
out
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Pad {
pub number: String,
pub at: Point,
pub size: Point,
#[serde(default)]
pub shape: PadShape,
#[serde(default)]
pub drill: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub drill_height: Option<i32>,
#[serde(default = "plated_by_default")]
pub plated: bool,
#[serde(default, skip_serializing_if = "is_zero")]
pub corner_radius: i32,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub back: bool,
#[serde(default, skip_serializing_if = "PadLayers::is_auto")]
pub layers: PadLayers,
#[serde(default, skip_serializing_if = "is_origin")]
pub trapezoid_delta: Point,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub polygon: Vec<Point>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vias: Option<PadVias>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PadVias {
pub columns: u8,
pub rows: u8,
pub pitch: Point,
pub drill: i32,
pub diameter: i32,
#[serde(default = "plated_by_default")]
pub tented: bool,
}
pub const MAX_PAD_VIAS_EACH_WAY: u8 = 20;
fn plated_by_default() -> bool {
true
}
fn is_zero(v: &i32) -> bool {
*v == 0
}
fn is_origin(p: &Point) -> bool {
*p == Point::default()
}
impl Pad {
pub fn smd(number: impl Into<String>, at: Point, size: Point, shape: PadShape) -> Self {
Self {
number: number.into(),
at,
size,
shape,
drill: None,
drill_height: None,
plated: true,
corner_radius: 0,
back: false,
layers: PadLayers::default(),
trapezoid_delta: Point::default(),
polygon: vec![],
vias: None,
}
}
pub fn via_points(&self) -> Vec<Point> {
let Some(v) = self.vias else { return vec![] };
let at = |k: i64, n: u8, pitch: i32, centre: i32| {
let offset = (2 * k - (i64::from(n) - 1)) * i64::from(pitch) / 2;
(i64::from(centre) + offset).clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32
};
let mut out = vec![];
for row in 0..i64::from(v.rows) {
for column in 0..i64::from(v.columns) {
out.push(Point::new(
at(column, v.columns, v.pitch.x, self.at.x),
at(row, v.rows, v.pitch.y, self.at.y),
));
}
}
out
}
pub fn vias_problem(&self) -> Option<String> {
let v = self.vias?;
if self.drill.is_some() {
return Some("carries a via grid only as a surface-mount pad".into());
}
if !(1..=MAX_PAD_VIAS_EACH_WAY).contains(&v.columns) || !(1..=MAX_PAD_VIAS_EACH_WAY).contains(&v.rows) {
return Some(format!("needs between 1 and {MAX_PAD_VIAS_EACH_WAY} vias each way"));
}
if !(1..=10_000).contains(&v.drill) || v.diameter <= v.drill || v.diameter > 20_000 {
return Some("needs a via drill up to 10 mm and a via diameter larger than its drill".into());
}
if (v.columns > 1 && v.pitch.x < v.diameter) || (v.rows > 1 && v.pitch.y < v.diameter) || v.pitch.x > 100_000 || v.pitch.y > 100_000 {
return Some("needs a via pitch at least the via diameter".into());
}
let copper = self.local_shape();
if self.via_points().iter().any(|p| copper.depth(*p) < f64::from(v.diameter) / 2.) {
return Some("has a via that leaves its copper".into());
}
None
}
pub fn effective_corner_radius(&self) -> i32 {
match self.shape {
PadShape::RoundRect => self.corner_radius.clamp(0, self.size.x.min(self.size.y) / 2),
PadShape::Custom => self.corner_radius.clamp(0, 100_000),
_ => 0,
}
}
pub fn corners(&self) -> Option<Vec<Point>> {
let at = |x: i64, y: i64| {
let c = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32;
Point::new(c(i64::from(self.at.x) + x), c(i64::from(self.at.y) + y))
};
match self.shape {
PadShape::Trapezoid => {
let (hx, hy) = (i64::from(self.size.x) / 2, i64::from(self.size.y) / 2);
let (dx, dy) = (i64::from(self.trapezoid_delta.x) / 2, i64::from(self.trapezoid_delta.y) / 2);
Some(vec![
at(-hx - dy, hy + dx),
at(hx + dy, hy - dx),
at(hx - dy, -hy + dx),
at(-hx + dy, -hy - dx),
])
}
PadShape::Custom => Some(self.polygon.iter().map(|p| at(i64::from(p.x), i64::from(p.y))).collect()),
_ => None,
}
}
pub fn local_shape(&self) -> Shape {
match self.corners() {
Some(corners) => Shape::polygon(corners, self.effective_corner_radius()),
None => Shape::rounded_pad(self.at, self.size, self.shape, self.effective_corner_radius()),
}
}
pub fn outline_problem(&self) -> Option<String> {
let far = |v: i32| !(-100_000_000..=100_000_000).contains(&v);
match self.shape {
PadShape::Trapezoid => {
let d = self.trapezoid_delta;
if d.x.unsigned_abs() >= self.size.y.unsigned_abs() || d.y.unsigned_abs() >= self.size.x.unsigned_abs() {
return Some("needs a taper shorter than the side it narrows".into());
}
if d.x != 0 && d.y != 0 {
return Some("tapers one pair of sides only".into());
}
None
}
PadShape::Custom => {
let n = self.polygon.len();
if n < 3 {
return Some("needs at least three corners".into());
}
if n > MAX_PAD_CORNERS {
return Some(format!("has more than {MAX_PAD_CORNERS} corners"));
}
if self.polygon.iter().any(|p| far(p.x) || far(p.y)) || far(self.at.x) || far(self.at.y) {
return Some("lies outside the drawing area".into());
}
if ring_area2(&self.polygon) == 0 {
return Some("encloses no area".into());
}
if ring_crosses_itself(&self.polygon) {
return Some("crosses itself".into());
}
if polygon_depth(&self.polygon, Point::default()) + f64::from(self.effective_corner_radius()) < 0. {
return Some("does not cover its own position".into());
}
None
}
_ => None,
}
}
pub fn copper_sides(&self) -> (bool, bool) {
match self.drill {
Some(_) => (true, true),
None => (!self.back, self.back),
}
}
pub fn mask_open(&self, front: bool) -> bool {
let (f, b) = self.copper_sides();
if front {
f && !self.layers.cover_front
} else {
b && !self.layers.cover_back
}
}
pub fn paste_open(&self, front: bool) -> bool {
self.drill.is_none() && !self.layers.no_paste && self.back != front
}
pub fn hole_size(&self) -> Option<Point> {
let width = self.drill?;
Some(Point::new(width, self.drill_height.unwrap_or(width)))
}
pub fn local_hole(&self) -> Option<Shape> {
Some(Shape::pad(self.at, self.hole_size()?, PadShape::Oval))
}
pub fn annular_ring(&self) -> Option<i32> {
let drill = self.drill.filter(|_| self.plated)?;
if self.drill_height.is_none() && self.corners().is_none() {
return Some((self.size.x.min(self.size.y) - drill) / 2);
}
Some(self.hole_clearance()?.floor() as i32)
}
fn hole_clearance(&self) -> Option<f64> {
let Shape::Capsule { a, b, radius } = self.local_hole()? else {
return None;
};
let copper = self.local_shape();
if let Shape::Polygon { points, radius: round } = &copper {
let within = polygon_contains(points, a)
&& polygon_contains(points, b)
&& ring_edges(points).all(|(p, q)| !segments_intersect(p, q, a, b));
if !within {
let len = f64::from(b.x - a.x).hypot(f64::from(b.y - a.y));
let steps = (len.ceil() as usize).clamp(1, 4096);
let step = len / steps as f64;
let depth = (0..=steps)
.map(|k| {
let t = k as f64 / steps as f64;
let p = Point::new(
(f64::from(a.x) + t * f64::from(b.x - a.x)).round() as i32,
(f64::from(a.y) + t * f64::from(b.y - a.y)).round() as i32,
);
copper.depth(p)
})
.fold(f64::INFINITY, f64::min);
return Some(depth - step / 2. - f64::from(radius));
}
let edges = ring_edges(points).map(|(p, q)| segment_distance(p, q, a, b)).fold(f64::INFINITY, f64::min);
return Some(edges + f64::from(*round) - f64::from(radius));
}
Some(copper.depth(a).min(copper.depth(b)) - f64::from(radius))
}
fn hole_problem(&self) -> Option<&'static str> {
let hole = self.hole_size()?;
let far = |v: i32| !(-100_000_000..=100_000_000).contains(&v);
if [self.at.x, self.at.y, self.size.x, self.size.y, hole.x, hole.y].into_iter().any(far) {
return Some("lies outside the drawing area");
}
if hole.x <= 0 || hole.y <= 0 {
Some("needs a positive drill")
} else if self.drill_height.is_some() && self.hole_clearance().is_some_and(|c| c < 0.) {
Some("has a slot larger than the pad")
} else if self.drill_height.is_none() && self.corners().is_some() && self.hole_clearance().is_some_and(|c| c < 0.) {
Some("has a drill larger than the pad")
} else if self.drill_height.is_none() && hole.x > self.size.x.max(self.size.y) {
Some("has a drill larger than the pad")
} else {
None
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Model {
pub path: String,
#[serde(default)]
pub offset: [f64; 3],
#[serde(default = "unit_scale")]
pub scale: [f64; 3],
#[serde(default)]
pub rotation: [f64; 3],
}
fn unit_scale() -> [f64; 3] {
[1., 1., 1.]
}
impl Model {
pub fn step_path(&self) -> String {
match self.path.strip_suffix(".wrl") {
Some(stem) => format!("{stem}.step"),
None => self.path.clone(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Footprint {
pub name: String,
pub pads: Vec<Pad>,
#[serde(default)]
pub silk: Vec<Vec<Point>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<Model>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub courtyard_margin: Option<i32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graphics: Vec<LayerGraphic>,
}
impl Footprint {
pub fn validate(&self) -> Result<(), String> {
if self.name.trim().is_empty() {
return Err("Enter a footprint name.".into());
}
self.validate_placeable()
}
pub fn validate_placeable(&self) -> Result<(), String> {
for pad in &self.pads {
let name = if pad.number.is_empty() {
"An unnumbered pad".to_owned()
} else {
format!("Pad {}", pad.number)
};
if pad.size.x <= 0 || pad.size.y <= 0 {
return Err(format!("{name} needs a positive width and height."));
}
if let Some(problem) = pad.outline_problem() {
return Err(format!("{name} {problem}."));
}
if let Some(problem) = pad.hole_problem() {
return Err(format!("{name} {problem}."));
}
if !(0..=100_000).contains(&pad.corner_radius) {
return Err(format!("{name} needs a corner radius between 0 and 100 mm."));
}
let margins = [pad.layers.mask_margin, pad.layers.paste_margin];
if margins.into_iter().flatten().any(|m| !(-10_000..=10_000).contains(&m)) {
return Err(format!("{name} has a mask or paste margin beyond 10 mm."));
}
if let Some(problem) = pad.layers.paste_windows.and_then(|w| w.problem()) {
return Err(format!("{name} {problem}."));
}
if let Some(problem) = pad.vias_problem() {
return Err(format!("{name} {problem}."));
}
}
if self.courtyard_margin.is_some_and(|m| !(0..=100_000).contains(&m)) {
return Err("The courtyard clearance must be between 0 and 100 mm.".into());
}
if self.silk.iter().any(|line| line.len() < 2) {
return Err("Silkscreen lines need at least two points.".into());
}
if self.graphics.len() > 100_000 {
return Err("A footprint can carry at most 100000 drawn items.".into());
}
for (i, graphic) in self.graphics.iter().enumerate() {
if let Some(problem) = graphic.problem() {
return Err(format!("Drawing {} on {} {problem}.", i + 1, graphic.layer.name()));
}
}
if let Some(model) = &self.model {
let numbers = model
.offset
.iter()
.chain(&model.scale)
.chain(&model.rotation);
if model.path.trim().is_empty() || numbers.into_iter().any(|v| !v.is_finite()) {
return Err("The 3D model needs a file and finite placement numbers.".into());
}
}
let id = Uuid::nil();
let board = Board {
placements: vec![Placement {
component: id,
footprint: self.clone(),
at: Point::new(0, 0),
rotation: 0,
bottom: false,
}],
..Board::default()
};
board.validate(&BTreeSet::from([id]))
}
pub fn drawing(&self) -> impl Iterator<Item = Drawn> + '_ {
let silk = self.silk.iter().map(|line| Drawn {
layer: GraphicLayer::FrontSilk,
width: crate::fabrication::SILK_WIDTH,
filled: false,
strokes: vec![line.clone()],
});
silk.chain(self.graphics.iter().map(|g| Drawn {
layer: g.layer,
width: g.width(),
filled: g.filled,
strokes: g.strokes(!g.layer.front()),
}))
}
pub fn drawn_courtyard(&self, front: bool) -> Option<(Point, Point)> {
let layer = if front { GraphicLayer::FrontCourtyard } else { GraphicLayer::BackCourtyard };
let points: Vec<Point> = self
.graphics
.iter()
.filter(|g| g.layer == layer)
.flat_map(LayerGraphic::points)
.collect();
bounds_of(&points)
}
pub fn bounds(&self) -> (Point, Point) {
let mut points: Vec<Point> = self
.pads
.iter()
.flat_map(|p| {
let (min, max) = match p.corners() {
Some(_) => p.local_shape().bounds(),
None => Shape::pad(p.at, p.size, PadShape::Rect).bounds(),
};
[min, max]
})
.collect();
points.extend(self.silk.iter().flatten().copied());
points.extend(
self.graphics
.iter()
.filter(|g| g.layer.is_silk())
.flat_map(LayerGraphic::points),
);
bounds_of(&points).unwrap_or_default()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Drawn {
pub layer: GraphicLayer,
pub width: i32,
pub filled: bool,
pub strokes: Vec<Vec<Point>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Placement {
pub component: Uuid,
pub footprint: Footprint,
pub at: Point,
#[serde(default)]
pub rotation: u8,
#[serde(default)]
pub bottom: bool,
}
impl Placement {
pub fn transform(&self, p: Point) -> Point {
let p = if self.bottom {
Point::new(-p.x, p.y)
} else {
p
};
p.rotate(self.rotation).offset(self.at)
}
pub fn pad_shape(&self, pad: &Pad) -> Shape {
let size = if self.rotation % 2 == 1 {
Point::new(pad.size.y, pad.size.x)
} else {
pad.size
};
match pad.corners() {
Some(corners) => Shape::polygon(
corners.into_iter().map(|p| self.transform(p)).collect(),
pad.effective_corner_radius(),
),
None => Shape::rounded_pad(self.transform(pad.at), size, pad.shape, pad.effective_corner_radius()),
}
}
pub fn pad_vias(&self, pad_index: usize) -> Vec<Via> {
let Some(pad) = self.footprint.pads.get(pad_index) else { return vec![] };
let Some(grid) = pad.vias else { return vec![] };
pad.via_points()
.into_iter()
.enumerate()
.map(|(k, p)| Via {
id: Uuid::from_u128(
self.component.as_u128() ^ (0x7061_6476_6961_u128 << 80) ^ ((pad_index as u128) << 32) ^ (k as u128 + 1),
),
at: self.transform(p),
diameter: grid.diameter,
drill: grid.drill,
span: None,
})
.collect()
}
pub fn pad_paste(&self, pad: &Pad) -> Vec<Shape> {
let margin = pad.layers.paste_margin.unwrap_or(0);
let Some(windows) = pad.layers.paste_windows else {
return self.pad_shape(pad).grown_parts(margin);
};
let holes: Vec<Shape> = match pad.vias {
Some(grid) => pad.via_points().into_iter().map(|p| Shape::circle(p, grid.drill / 2)).collect(),
None => vec![],
};
pad.local_shape()
.grown_parts(margin)
.iter()
.flat_map(|aperture| windows.cut(aperture))
.filter(|window| holes.iter().all(|hole| hole.distance(window) > 0.))
.filter_map(|window| {
let Shape::Rect { min, max } = window else { return None };
let (a, b) = (self.transform(min), self.transform(max));
Some(Shape::Rect {
min: Point::new(a.x.min(b.x), a.y.min(b.y)),
max: Point::new(a.x.max(b.x), a.y.max(b.y)),
})
})
.collect()
}
pub fn pad_hole(&self, pad: &Pad) -> Option<Shape> {
let hole = pad.hole_size()?;
let hole = if self.rotation % 2 == 1 { Point::new(hole.y, hole.x) } else { hole };
Some(Shape::pad(self.transform(pad.at), hole, PadShape::Oval))
}
pub fn pad_layers(&self, pad: &Pad, layer_count: u8) -> (u8, u8) {
let last = layer_count.saturating_sub(1);
match (pad.drill, self.bottom != pad.back) {
(Some(_), _) => (0, last),
(None, false) => (0, 0),
(None, true) => (last, last),
}
}
pub fn has_back_copper_pad(&self) -> bool {
self.footprint.pads.iter().any(|pad| pad.drill.is_none() && pad.back != self.bottom)
}
pub fn front_faces(&self, board_top: bool) -> bool {
board_top != self.bottom
}
pub fn drawing_on(&self, layer: GraphicLayer) -> Vec<(i32, bool, Vec<Vec<Point>>)> {
self.footprint
.drawing()
.filter(|d| if self.bottom { d.layer.flipped() } else { d.layer } == layer)
.map(|d| {
let strokes = d
.strokes
.into_iter()
.map(|line| line.into_iter().map(|p| self.transform(p)).collect())
.collect();
(d.width, d.filled, strokes)
})
.collect()
}
pub fn place_graphic(&self, graphic: &LayerGraphic) -> (GraphicLayer, Vec<Vec<Point>>) {
let layer = if self.bottom { graphic.layer.flipped() } else { graphic.layer };
let strokes = graphic
.strokes(!graphic.layer.front())
.into_iter()
.map(|line| line.into_iter().map(|p| self.transform(p)).collect())
.collect();
(layer, strokes)
}
pub fn back_courtyard(&self) -> Option<(Point, Point)> {
let (min, max) = self.footprint.drawn_courtyard(false)?;
let corners = [min, max, Point::new(min.x, max.y), Point::new(max.x, min.y)]
.map(|p| self.transform(p));
bounds_of(&corners)
}
pub fn courtyard_on(&self, top: bool) -> Option<(Point, Point)> {
if self.bottom != top { Some(self.courtyard()) } else { self.back_courtyard() }
}
pub fn courtyard(&self) -> (Point, Point) {
let drawn = self.footprint.drawn_courtyard(true);
let (min, max) = drawn.unwrap_or_else(|| self.footprint.bounds());
let corners = [min, max, Point::new(min.x, max.y), Point::new(max.x, min.y)]
.map(|p| self.transform(p));
let (min, max) = bounds_of(&corners).unwrap_or_default();
let margin = match drawn {
Some(_) => 0,
None => self.footprint.courtyard_margin.unwrap_or(COURTYARD_MARGIN),
};
(
Point::new(min.x - margin, min.y - margin),
Point::new(max.x + margin, max.y + margin),
)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Track {
pub id: Uuid,
pub layer: u8,
pub width: i32,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub fixed_width: bool,
pub points: Vec<Point>,
}
impl Track {
pub fn new(layer: u8, width: i32, points: Vec<Point>) -> Self {
Self {
id: Uuid::new_v4(),
layer,
width,
fixed_width: false,
points: simplify_path(points),
}
}
pub fn segments(&self) -> impl Iterator<Item = Shape> + '_ {
self.points
.windows(2)
.map(|s| Shape::segment(s[0], s[1], self.width))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Via {
pub id: Uuid,
pub at: Point,
pub diameter: i32,
pub drill: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub span: Option<(u8, u8)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ViaKind {
Through,
Blind,
Buried,
}
impl Via {
pub fn through(at: Point, diameter: i32, drill: i32) -> Self {
Self { id: Uuid::new_v4(), at, diameter, drill, span: None }
}
pub fn layers(&self, layer_count: u8) -> (u8, u8) {
let last = layer_count.saturating_sub(1);
match self.span {
Some((from, to)) => (from.min(last), to.min(last)),
None => (0, last),
}
}
pub fn kind(&self, layer_count: u8) -> ViaKind {
let last = layer_count.saturating_sub(1);
match self.layers(layer_count) {
(0, to) if to == last => ViaKind::Through,
(from, to) if from == 0 || to == last => ViaKind::Blind,
_ => ViaKind::Buried,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DesignRules {
pub track_width: i32,
pub clearance: i32,
pub via_diameter: i32,
pub via_drill: i32,
pub edge_clearance: i32,
pub routing_grid: i32,
#[serde(default)]
pub net_widths: BTreeMap<String, i32>,
#[serde(default = "default_mask_expansion")]
pub mask_expansion: i32,
#[serde(default)]
pub autoroute_vias: ViaPolicy,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub net_classes: Vec<NetClass>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub net_class_of: BTreeMap<String, String>,
#[serde(
default = "default_min_annular_ring",
skip_serializing_if = "is_default_min_annular_ring"
)]
pub min_annular_ring: i32,
#[serde(default = "tented_by_default", skip_serializing_if = "Clone::clone")]
pub tent_vias: bool,
#[serde(
default = "default_min_hole_spacing",
skip_serializing_if = "is_default_min_hole_spacing"
)]
pub min_hole_spacing: i32,
}
fn tented_by_default() -> bool {
true
}
fn default_mask_expansion() -> i32 {
50
}
pub const DEFAULT_MIN_ANNULAR_RING: i32 = 130;
fn default_min_annular_ring() -> i32 {
DEFAULT_MIN_ANNULAR_RING
}
fn is_default_min_annular_ring(v: &i32) -> bool {
*v == DEFAULT_MIN_ANNULAR_RING
}
pub const DEFAULT_MIN_HOLE_SPACING: i32 = 250;
fn default_min_hole_spacing() -> i32 {
DEFAULT_MIN_HOLE_SPACING
}
fn is_default_min_hole_spacing(v: &i32) -> bool {
*v == DEFAULT_MIN_HOLE_SPACING
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ViaPolicy {
Allow,
#[default]
Avoid,
Never,
}
impl Default for DesignRules {
fn default() -> Self {
Self {
track_width: 250,
clearance: 200,
via_diameter: 600,
via_drill: 300,
edge_clearance: 300,
routing_grid: 100,
net_widths: BTreeMap::new(),
mask_expansion: default_mask_expansion(),
autoroute_vias: ViaPolicy::default(),
net_classes: vec![],
net_class_of: BTreeMap::new(),
min_annular_ring: DEFAULT_MIN_ANNULAR_RING,
tent_vias: true,
min_hole_spacing: DEFAULT_MIN_HOLE_SPACING,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Board {
pub outline: Vec<Point>,
pub layer_count: u8,
#[serde(default)]
pub placements: Vec<Placement>,
#[serde(default)]
pub tracks: Vec<Track>,
#[serde(default)]
pub vias: Vec<Via>,
#[serde(default)]
pub rules: DesignRules,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub zones: Vec<Zone>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graphics: Vec<BoardGraphic>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cutouts: Vec<BoardCutout>,
}
pub const MAX_CUTOUT_CORNERS: usize = 1000;
pub const MAX_CUTOUTS: usize = 1000;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BoardCutout {
pub id: Uuid,
pub points: Vec<Point>,
}
impl BoardCutout {
pub fn new(points: Vec<Point>) -> Self {
Self { id: Uuid::new_v4(), points }
}
}
fn ring_edges(ring: &[Point]) -> impl Iterator<Item = (Point, Point)> + '_ {
let n = ring.len();
(0..n).map(move |i| (ring[i], ring[(i + 1) % n]))
}
fn ring_crosses_itself(ring: &[Point]) -> bool {
let n = ring.len();
(0..n).any(|i| {
(i + 2..n).any(|j| {
(i, j) != (0, n - 1)
&& segments_intersect(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n])
})
})
}
fn rings_touch(a: &[Point], b: &[Point]) -> bool {
ring_edges(a).any(|(p, q)| ring_edges(b).any(|(r, s)| segments_intersect(p, q, r, s)))
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BoardGraphic {
pub id: Uuid,
#[serde(flatten)]
pub graphic: LayerGraphic,
}
impl BoardGraphic {
pub fn new(graphic: LayerGraphic) -> Self {
Self { id: Uuid::new_v4(), graphic }
}
pub fn problem(&self) -> Option<String> {
if self.graphic.layer.is_courtyard() {
return Some(format!(
"is on {}: a courtyard belongs to a part's footprint, not to the board",
self.graphic.layer.name()
));
}
self.graphic.problem().map(str::to_owned)
}
}
impl Board {
pub fn drawing_on(&self, layer: GraphicLayer) -> Vec<(i32, bool, Vec<Vec<Point>>)> {
self.graphics
.iter()
.filter(|g| g.graphic.layer == layer)
.map(|g| (g.graphic.width(), g.graphic.filled, g.graphic.strokes(!layer.front())))
.collect()
}
}
impl Default for Board {
fn default() -> Self {
Self {
outline: rectangle(Point::new(0, 0), Point::new(60_000, 40_000)),
layer_count: 2,
placements: vec![],
tracks: vec![],
vias: vec![],
rules: DesignRules::default(),
zones: vec![],
graphics: vec![],
cutouts: vec![],
}
}
}
pub const SUBSTRATE_THICKNESS: i32 = 1_600;
pub const COPPER_THICKNESS: i32 = 35;
pub fn layer_z(layer: u8, layer_count: u8) -> i32 {
let last = layer_count.saturating_sub(1);
if layer == 0 || last == 0 {
return 0;
}
let layer = layer.min(last);
-(SUBSTRATE_THICKNESS as i64 * i64::from(layer) / i64::from(last)) as i32
}
pub fn layer_name(layer: u8, layer_count: u8) -> String {
if layer == 0 {
"F.Cu".into()
} else if layer + 1 >= layer_count {
"B.Cu".into()
} else {
format!("In{layer}.Cu")
}
}
fn grow_box(min: Point, max: Point, grow: i32) -> (Point, Point) {
if grow >= 0 {
return (
Point::new(min.x - grow, min.y - grow),
Point::new(max.x + grow, max.y + grow),
);
}
let shrink = |lo: i32, hi: i32| {
let (a, b) = (lo - grow, hi + grow);
if a < b {
(a, b)
} else {
let mid = (i64::from(lo) + i64::from(hi)).div_euclid(2) as i32;
(mid, mid + 1)
}
};
let (x0, x1) = shrink(min.x, max.x);
let (y0, y1) = shrink(min.y, max.y);
(Point::new(x0, y0), Point::new(x1, y1))
}
pub fn rectangle(min: Point, max: Point) -> Vec<Point> {
vec![min, Point::new(max.x, min.y), max, Point::new(min.x, max.y)]
}
#[derive(Clone, Debug, PartialEq)]
pub enum Shape {
Rect {
min: Point,
max: Point,
},
Capsule {
a: Point,
b: Point,
radius: i32,
},
RoundRect {
min: Point,
max: Point,
radius: i32,
},
Polygon {
points: Vec<Point>,
radius: i32,
},
}
impl Shape {
pub fn polygon(mut points: Vec<Point>, radius: i32) -> Self {
if ring_area2(&points) < 0 {
points.reverse();
}
Self::Polygon { points, radius: radius.max(0) }
}
fn anchor(&self) -> Point {
match self {
Self::Rect { min, .. } => *min,
Self::RoundRect { min, max, radius } => Self::core(*min, *max, *radius).0,
Self::Capsule { a, .. } => *a,
Self::Polygon { points, .. } => points.first().copied().unwrap_or_default(),
}
}
pub fn covers_box(&self, min: Point, max: Point) -> bool {
let corners = rectangle(min, max);
if !corners.iter().all(|c| self.depth(*c) >= 0.) {
return false;
}
let Self::Polygon { .. } = self else {
return true;
};
let ring = self.outline(8);
let (lo, hi) = (Point::new(min.x + 1, min.y + 1), Point::new(max.x - 1, max.y - 1));
lo.x > hi.x || lo.y > hi.y || ring_edges(&ring).all(|(p, q)| segment_rect_distance(p, q, lo, hi) > 0.)
}
pub fn pad(center: Point, size: Point, shape: PadShape) -> Self {
Self::rounded_pad(center, size, shape, 0)
}
pub fn rounded_pad(center: Point, size: Point, shape: PadShape, corner: i32) -> Self {
let half = Point::new(size.x / 2, size.y / 2);
match shape {
PadShape::RoundRect if corner > 0 => {
let min = Point::new(center.x - half.x, center.y - half.y);
Self::RoundRect {
min,
max: Point::new(min.x + size.x, min.y + size.y),
radius: corner.min(size.x.min(size.y) / 2),
}
}
PadShape::Rect | PadShape::RoundRect | PadShape::Trapezoid | PadShape::Custom => {
let min = Point::new(center.x - half.x, center.y - half.y);
Self::Rect {
min,
max: Point::new(min.x + size.x, min.y + size.y),
}
}
PadShape::Circle => Self::circle(center, size.x.min(size.y) / 2),
PadShape::Oval => {
let radius = size.x.min(size.y) / 2;
let reach = Point::new((half.x - radius).max(0), (half.y - radius).max(0));
Self::Capsule {
a: Point::new(center.x - reach.x, center.y - reach.y),
b: Point::new(center.x + reach.x, center.y + reach.y),
radius,
}
}
}
}
pub fn circle(center: Point, radius: i32) -> Self {
Self::Capsule {
a: center,
b: center,
radius,
}
}
pub fn segment(a: Point, b: Point, width: i32) -> Self {
Self::Capsule {
a,
b,
radius: width / 2,
}
}
pub fn grown(&self, grow: i32) -> Self {
if grow == 0 {
return self.clone();
}
if let Self::Polygon { points, radius } = self {
let radius = radius + grow;
if radius >= 0 {
return Self::Polygon { points: points.clone(), radius };
}
return match shrink_ring(points, -radius) {
Some(points) => Self::Polygon { points, radius: 0 },
None => Self::circle(polygon_inner_point(points), 1),
};
}
match *self {
Self::Rect { min, max } => {
let (min, max) = grow_box(min, max, grow);
Self::Rect { min, max }
}
Self::RoundRect { min, max, radius } => {
let (min, max) = grow_box(min, max, grow);
let radius = (radius + grow).clamp(0, (max.x - min.x).min(max.y - min.y) / 2);
if radius == 0 { Self::Rect { min, max } } else { Self::RoundRect { min, max, radius } }
}
Self::Capsule { a, b, radius } => Self::Capsule {
a,
b,
radius: (radius + grow).max(1),
},
Self::Polygon { .. } => unreachable!(),
}
}
pub fn swept_corners(&self) -> Option<Vec<SweptCorner>> {
let Self::Polygon { points, radius } = self else { return None };
if *radius == 0 {
return None;
}
let (raw, concave) = swept_outline(points, *radius, 8);
if concave && ring_crosses_itself(&raw) {
return None;
}
Some(swept_corners_of(points, *radius))
}
pub fn grown_parts(&self, grow: i32) -> Vec<Self> {
match self {
Self::Polygon { points, radius } if radius + grow < 0 => shrink_parts(points, -(radius + grow))
.into_iter()
.map(|points| Self::Polygon { points, radius: 0 })
.collect(),
_ => vec![self.grown(grow)],
}
}
fn core(min: Point, max: Point, radius: i32) -> (Point, Point) {
(
Point::new(min.x + radius, min.y + radius),
Point::new(max.x - radius, max.y - radius),
)
}
pub fn outline(&self, facets: usize) -> Vec<Point> {
let arc = |out: &mut Vec<Point>, c: Point, r: i32, from: f64, steps: usize, sweep: f64| {
for i in 0..=steps {
let t = from + sweep * i as f64 / steps.max(1) as f64;
out.push(Point::new(
c.x + (f64::from(r) * t.cos()).round() as i32,
c.y + (f64::from(r) * t.sin()).round() as i32,
));
}
};
let quarter = std::f64::consts::FRAC_PI_2;
let facets = facets.max(1);
if let Self::Polygon { points, radius } = self {
if *radius == 0 {
return points.clone();
}
let (out, concave) = swept_outline(points, *radius, facets);
return if concave { remove_loops(out) } else { out };
}
match *self {
Self::Rect { min, max } => rectangle(min, max),
Self::RoundRect { min, max, radius } => {
let (lo, hi) = Self::core(min, max, radius);
let mut out = vec![];
for (k, c) in [Point::new(hi.x, lo.y), hi, Point::new(lo.x, hi.y), lo]
.into_iter()
.enumerate()
{
arc(&mut out, c, radius, quarter * (k as f64 - 1.), facets, quarter);
}
out.dedup();
if out.len() > 1 && out.first() == out.last() {
out.pop();
}
out
}
Self::Capsule { a, b, radius } => {
let (dx, dy) = (f64::from(b.x - a.x), f64::from(b.y - a.y));
let base = if dx == 0. && dy == 0. { 0. } else { dy.atan2(dx) } - quarter;
let mut out = vec![];
arc(&mut out, b, radius, base, 2 * facets, 2. * quarter);
if a == b {
out.pop();
arc(&mut out, a, radius, base + 2. * quarter, 2 * facets, 2. * quarter);
out.pop();
} else {
arc(&mut out, a, radius, base + 2. * quarter, 2 * facets, 2. * quarter);
}
out.dedup();
if out.len() > 1 && out.first() == out.last() {
out.pop();
}
out
}
Self::Polygon { .. } => unreachable!(),
}
}
pub fn bounds(&self) -> (Point, Point) {
if let Self::Polygon { points, radius } = self {
let (min, max) = bounds_of(points).unwrap_or_default();
return (
Point::new(min.x.saturating_sub(*radius), min.y.saturating_sub(*radius)),
Point::new(max.x.saturating_add(*radius), max.y.saturating_add(*radius)),
);
}
match *self {
Self::Rect { min, max } | Self::RoundRect { min, max, .. } => (min, max),
Self::Capsule { a, b, radius } => (
Point::new(a.x.min(b.x) - radius, a.y.min(b.y) - radius),
Point::new(a.x.max(b.x) + radius, a.y.max(b.y) + radius),
),
Self::Polygon { .. } => unreachable!(),
}
}
pub fn center(&self) -> Point {
let (min, max) = self.bounds();
Point::new(
((i64::from(min.x) + i64::from(max.x)) / 2) as i32,
((i64::from(min.y) + i64::from(max.y)) / 2) as i32,
)
}
pub fn distance_to_point(&self, p: Point) -> f64 {
if let Self::Polygon { points, radius } = self {
return (-polygon_depth(points, p) - f64::from(*radius)).max(0.);
}
match *self {
Self::Rect { min, max } => point_rect_distance(p, min, max),
Self::RoundRect { min, max, radius } => {
let (lo, hi) = Self::core(min, max, radius);
(point_rect_distance(p, lo, hi) - f64::from(radius)).max(0.)
}
Self::Capsule { a, b, radius } => {
(point_segment_distance(p, a, b) - f64::from(radius)).max(0.)
}
Self::Polygon { .. } => unreachable!(),
}
}
pub fn depth(&self, p: Point) -> f64 {
let inside_box = |min: Point, max: Point| {
let d = [p.x - min.x, max.x - p.x, p.y - min.y, max.y - p.y];
f64::from(d.into_iter().min().unwrap_or(0))
};
if let Self::Polygon { points, radius } = self {
return polygon_depth(points, p) + f64::from(*radius);
}
match *self {
Self::Rect { min, max } => {
let inner = inside_box(min, max);
if inner >= 0. { inner } else { -point_rect_distance(p, min, max) }
}
Self::RoundRect { min, max, radius } => {
let (lo, hi) = Self::core(min, max, radius);
let inner = inside_box(lo, hi);
f64::from(radius) + if inner >= 0. { inner } else { -point_rect_distance(p, lo, hi) }
}
Self::Capsule { a, b, radius } => f64::from(radius) - point_segment_distance(p, a, b),
Self::Polygon { .. } => unreachable!(),
}
}
pub fn contains(&self, p: Point) -> bool {
self.distance_to_point(p) <= 0.
}
pub fn distance(&self, other: &Self) -> f64 {
if let Self::Polygon { points, radius } = self {
if points.is_empty() {
return f64::INFINITY;
}
if polygon_contains(points, other.anchor()) || other.contains(points[0]) {
return 0.;
}
let edges = ring_edges(points)
.map(|(a, b)| Self::Capsule { a, b, radius: 0 }.distance(other))
.fold(f64::INFINITY, f64::min);
return (edges - f64::from(*radius)).max(0.);
}
if let Self::Polygon { .. } = other {
return other.distance(self);
}
if let Self::RoundRect { min, max, radius } = *self {
let (lo, hi) = Self::core(min, max, radius);
return (Self::Rect { min: lo, max: hi }.distance(other) - f64::from(radius)).max(0.);
}
if let Self::RoundRect { .. } = *other {
return other.distance(self);
}
match (self.clone(), other.clone()) {
(Self::Rect { min: a0, max: a1 }, Self::Rect { min: b0, max: b1 }) => {
let dx = (i64::from(a0.x) - i64::from(b1.x))
.max(i64::from(b0.x) - i64::from(a1.x))
.max(0) as f64;
let dy = (i64::from(a0.y) - i64::from(b1.y))
.max(i64::from(b0.y) - i64::from(a1.y))
.max(0) as f64;
dx.hypot(dy)
}
(Self::Rect { min, max }, Self::Capsule { a, b, radius })
| (Self::Capsule { a, b, radius }, Self::Rect { min, max }) => {
(segment_rect_distance(a, b, min, max) - f64::from(radius)).max(0.)
}
(
Self::Capsule {
a: a0,
b: a1,
radius: ra,
},
Self::Capsule {
a: b0,
b: b1,
radius: rb,
},
) => (segment_distance(a0, a1, b0, b1) - f64::from(ra) - f64::from(rb)).max(0.),
(Self::RoundRect { .. } | Self::Polygon { .. }, _) | (_, Self::RoundRect { .. } | Self::Polygon { .. }) => {
unreachable!()
}
}
}
}
fn cross(o: Point, a: Point, b: Point) -> i64 {
(i64::from(a.x) - i64::from(o.x)) * (i64::from(b.y) - i64::from(o.y))
- (i64::from(a.y) - i64::from(o.y)) * (i64::from(b.x) - i64::from(o.x))
}
fn within_box(a: Point, b: Point, p: Point) -> bool {
p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x) && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y)
}
pub fn segments_intersect(a: Point, b: Point, c: Point, d: Point) -> bool {
let d1 = cross(c, d, a);
let d2 = cross(c, d, b);
let d3 = cross(a, b, c);
let d4 = cross(a, b, d);
if d1.signum() * d2.signum() < 0 && d3.signum() * d4.signum() < 0 {
return true;
}
(d1 == 0 && within_box(c, d, a))
|| (d2 == 0 && within_box(c, d, b))
|| (d3 == 0 && within_box(a, b, c))
|| (d4 == 0 && within_box(a, b, d))
}
pub fn point_segment_distance(p: Point, a: Point, b: Point) -> f64 {
let (px, py) = (f64::from(p.x), f64::from(p.y));
let (ax, ay) = (f64::from(a.x), f64::from(a.y));
let (dx, dy) = (f64::from(b.x) - ax, f64::from(b.y) - ay);
let len2 = dx * dx + dy * dy;
let t = if len2 == 0. {
0.
} else {
(((px - ax) * dx + (py - ay) * dy) / len2).clamp(0., 1.)
};
(px - ax - t * dx).hypot(py - ay - t * dy)
}
fn segment_distance(a: Point, b: Point, c: Point, d: Point) -> f64 {
if segments_intersect(a, b, c, d) {
return 0.;
}
point_segment_distance(a, c, d)
.min(point_segment_distance(b, c, d))
.min(point_segment_distance(c, a, b))
.min(point_segment_distance(d, a, b))
}
fn point_rect_distance(p: Point, min: Point, max: Point) -> f64 {
let dx = (i64::from(min.x) - i64::from(p.x))
.max(i64::from(p.x) - i64::from(max.x))
.max(0) as f64;
let dy = (i64::from(min.y) - i64::from(p.y))
.max(i64::from(p.y) - i64::from(max.y))
.max(0) as f64;
dx.hypot(dy)
}
fn segment_rect_distance(a: Point, b: Point, min: Point, max: Point) -> f64 {
let corners = rectangle(min, max);
if within_box(min, max, a)
|| within_box(min, max, b)
|| (0..4).any(|i| segments_intersect(a, b, corners[i], corners[(i + 1) % 4]))
{
return 0.;
}
corners
.iter()
.map(|c| point_segment_distance(*c, a, b))
.fold(
point_rect_distance(a, min, max).min(point_rect_distance(b, min, max)),
f64::min,
)
}
pub fn polygon_contains(polygon: &[Point], p: Point) -> bool {
let (px, py) = (f64::from(p.x), f64::from(p.y));
let mut inside = false;
for (i, a) in polygon.iter().enumerate() {
let b = polygon[(i + 1) % polygon.len()];
let (ax, ay, bx, by) = (
f64::from(a.x),
f64::from(a.y),
f64::from(b.x),
f64::from(b.y),
);
if (ay > py) != (by > py) && px < ax + (py - ay) * (bx - ax) / (by - ay) {
inside = !inside;
}
}
inside
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SweptCorner {
Arc { centre: Point, radius: i32, from: f64, sweep: f64 },
Meet(f64, f64),
}
impl SweptCorner {
pub fn ends(&self) -> ((f64, f64), (f64, f64)) {
match *self {
Self::Arc { centre, radius, from, sweep } => {
let at = |t: f64| (f64::from(centre.x) + f64::from(radius) * t.cos(), f64::from(centre.y) + f64::from(radius) * t.sin());
(at(from), at(from + sweep))
}
Self::Meet(x, y) => ((x, y), (x, y)),
}
}
}
fn swept_corners_of(points: &[Point], radius: i32) -> Vec<SweptCorner> {
let n = points.len();
let r = f64::from(radius);
(0..n)
.map(|i| {
let (prev, here, next) = (points[(i + n - 1) % n], points[i], points[(i + 1) % n]);
let (d0, d1) = (unit(prev, here), unit(here, next));
let (n0, n1) = ((d0.1, -d0.0), (d1.1, -d1.0));
if d0.0 * d1.1 - d0.1 * d1.0 > 1e-12 {
let from = n0.1.atan2(n0.0);
let mut sweep = n1.1.atan2(n1.0) - from;
while sweep <= 0. {
sweep += 2. * std::f64::consts::PI;
}
SweptCorner::Arc { centre: here, radius, from, sweep }
} else {
let (mx, my) = miter(n0, n1);
SweptCorner::Meet(f64::from(here.x) + mx * r, f64::from(here.y) + my * r)
}
})
.collect()
}
fn swept_outline(points: &[Point], radius: i32, facets: usize) -> (Vec<Point>, bool) {
let quarter = std::f64::consts::FRAC_PI_2;
let mut out = vec![];
let round = |(x, y): (f64, f64)| Point::new(x.round() as i32, y.round() as i32);
for corner in swept_corners_of(points, radius) {
match corner {
SweptCorner::Arc { centre, radius, from, sweep } => {
let steps = ((sweep / quarter) * facets.max(1) as f64).ceil().max(1.) as usize;
for k in 0..=steps {
let t = from + sweep * k as f64 / steps as f64;
out.push(round((
f64::from(centre.x) + f64::from(radius) * t.cos(),
f64::from(centre.y) + f64::from(radius) * t.sin(),
)));
}
}
SweptCorner::Meet(x, y) => out.push(round((x, y))),
}
}
out.dedup();
if out.len() > 1 && out.first() == out.last() {
out.pop();
}
let n = points.len();
let concave = (0..n).any(|i| cross(points[(i + n - 1) % n], points[i], points[(i + 1) % n]) < 0);
(out, concave)
}
pub(crate) fn polygon_depth(polygon: &[Point], p: Point) -> f64 {
let d = ring_edges(polygon)
.map(|(a, b)| point_segment_distance(p, a, b))
.fold(f64::INFINITY, f64::min);
if polygon_contains(polygon, p) { d } else { -d }
}
fn ring_area2(ring: &[Point]) -> i128 {
ring_edges(ring)
.map(|(a, b)| i128::from(a.x) * i128::from(b.y) - i128::from(b.x) * i128::from(a.y))
.sum()
}
fn unit(a: Point, b: Point) -> (f64, f64) {
let (dx, dy) = (f64::from(b.x) - f64::from(a.x), f64::from(b.y) - f64::from(a.y));
let len = dx.hypot(dy);
if len == 0. { (0., 0.) } else { (dx / len, dy / len) }
}
fn miter(n0: (f64, f64), n1: (f64, f64)) -> (f64, f64) {
let (sx, sy) = (n0.0 + n1.0, n0.1 + n1.1);
let dot = 1. + n0.0 * n1.0 + n0.1 * n1.1;
if dot < 1e-9 { n1 } else { (sx / dot, sy / dot) }
}
fn shrink_parts(ring: &[Point], by: i32) -> Vec<Vec<Point>> {
type Line = ((f64, f64), (f64, f64));
let d = f64::from(by);
let meet = |((px, py), (ux, uy)): Line, ((qx, qy), (vx, vy)): Line| -> Option<(f64, f64)> {
let turn = ux * vy - uy * vx;
if turn.abs() < 1e-9 {
return (ux * vx + uy * vy > 0.).then_some((qx, qy));
}
let t = ((qx - px) * vy - (qy - py) * vx) / turn;
Some((px + t * ux, py + t * uy))
};
let mut lines: Vec<Line> = ring_edges(ring)
.filter(|(a, b)| a != b)
.map(|(a, b)| {
let u = unit(a, b);
((f64::from(a.x) - u.1 * d, f64::from(a.y) + u.0 * d), u)
})
.collect();
for _ in 0..=ring.len() {
let n = lines.len();
if n < 3 {
return vec![];
}
let Some(corners) = (0..n).map(|i| meet(lines[(i + n - 1) % n], lines[i])).collect::<Option<Vec<(f64, f64)>>>() else {
return vec![];
};
let run = |i: usize| {
let (s, e) = (corners[i], corners[(i + 1) % n]);
(e.0 - s.0) * lines[i].1.0 + (e.1 - s.1) * lines[i].1.1
};
match (0..n).filter(|&i| run(i) <= 0.5).min_by(|&i, &j| run(i).total_cmp(&run(j))) {
Some(worst) => {
lines.remove(worst);
}
None => {
let out: Vec<Point> = corners.iter().map(|c| Point::new(c.0.round() as i32, c.1.round() as i32)).collect();
let mut parts = vec![];
split_loops(out, &mut parts, &mut ring.len().max(8));
parts.retain(|part| {
part.iter().all(|p| polygon_depth(ring, *p) >= d - 2.) && !ring_crosses_itself(part)
});
return parts;
}
}
}
vec![]
}
fn shrink_ring(ring: &[Point], by: i32) -> Option<Vec<Point>> {
shrink_parts(ring, by).into_iter().max_by_key(|part| ring_area2(part))
}
fn split_loops(ring: Vec<Point>, out: &mut Vec<Vec<Point>>, budget: &mut usize) {
let n = ring.len();
let crossing = (0..n).find_map(|i| {
let (a, b) = (ring[i], ring[(i + 1) % n]);
(i + 2..n).find_map(|j| {
let (c, d) = (ring[j], ring[(j + 1) % n]);
((i, j) != (0, n - 1) && segments_intersect(a, b, c, d)).then_some((i, j))
})
});
match crossing {
Some((i, j)) if *budget > 0 && n >= 4 => {
*budget -= 1;
let x = crossing_point(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n]);
let mut outer: Vec<Point> = ring[..=i].to_vec();
outer.push(x);
outer.extend_from_slice(&ring[j + 1..]);
let mut inner = vec![x];
inner.extend_from_slice(&ring[i + 1..=j]);
for mut part in [outer, inner] {
part.dedup();
if part.len() > 1 && part.first() == part.last() {
part.pop();
}
if part.len() >= 3 {
split_loops(part, out, budget);
}
}
}
_ => {
if n >= 3 && ring_area2(&ring) > 0 {
out.push(ring);
}
}
}
}
fn crossing_point(a: Point, b: Point, c: Point, d: Point) -> Point {
let (u, v) = ((f64::from(b.x - a.x), f64::from(b.y - a.y)), (f64::from(d.x - c.x), f64::from(d.y - c.y)));
let turn = u.0 * v.1 - u.1 * v.0;
if turn.abs() < 1e-9 {
return if within_box(a, b, c) { c } else { a };
}
let t = (f64::from(c.x - a.x) * v.1 - f64::from(c.y - a.y) * v.0) / turn;
Point::new((f64::from(a.x) + t * u.0).round() as i32, (f64::from(a.y) + t * u.1).round() as i32)
}
fn remove_loops(mut ring: Vec<Point>) -> Vec<Point> {
'cut: for _ in 0..ring.len() {
let n = ring.len();
if n < 4 {
break;
}
for i in 0..n {
let (a, b) = (ring[i], ring[(i + 1) % n]);
for j in i + 2..n {
if (i, j) == (0, n - 1) {
continue;
}
let (c, d) = (ring[j], ring[(j + 1) % n]);
if a.x.max(b.x) < c.x.min(d.x)
|| c.x.max(d.x) < a.x.min(b.x)
|| a.y.max(b.y) < c.y.min(d.y)
|| c.y.max(d.y) < a.y.min(b.y)
|| !segments_intersect(a, b, c, d)
{
continue;
}
let x = crossing_point(a, b, c, d);
let mut outer: Vec<Point> = ring[..=i].to_vec();
outer.push(x);
outer.extend_from_slice(&ring[j + 1..]);
let mut inner = vec![x];
inner.extend_from_slice(&ring[i + 1..=j]);
outer.dedup();
inner.dedup();
ring = if ring_area2(&inner) > ring_area2(&outer) { inner } else { outer };
continue 'cut;
}
}
break;
}
ring
}
pub fn polygon_inner_point(ring: &[Point]) -> Point {
let Some((min, max)) = bounds_of(ring) else {
return Point::default();
};
let y = (i64::from(min.y) + i64::from(max.y)) / 2;
let mut xs: Vec<f64> = ring_edges(ring)
.filter(|(a, b)| (i64::from(a.y) > y) != (i64::from(b.y) > y))
.map(|(a, b)| {
let t = (y as f64 - f64::from(a.y)) / (f64::from(b.y) - f64::from(a.y));
f64::from(a.x) + t * (f64::from(b.x) - f64::from(a.x))
})
.collect();
xs.sort_by(f64::total_cmp);
let widest = xs.chunks(2).filter(|c| c.len() == 2).max_by(|a, b| (a[1] - a[0]).total_cmp(&(b[1] - b[0])));
match widest {
Some(c) => Point::new(((c[0] + c[1]) / 2.).round() as i32, y as i32),
None => ring[0],
}
}
fn bounds_of(points: &[Point]) -> Option<(Point, Point)> {
let first = *points.first()?;
Some(points.iter().fold((first, first), |(min, max), p| {
(
Point::new(min.x.min(p.x), min.y.min(p.y)),
Point::new(max.x.max(p.x), max.y.max(p.y)),
)
}))
}
pub fn simplify_path(points: Vec<Point>) -> Vec<Point> {
let mut clean: Vec<Point> = vec![];
for p in points {
if clean.last() == Some(&p) {
continue;
}
if clean.len() >= 2 {
let a = clean[clean.len() - 2];
let b = clean[clean.len() - 1];
let forward = (i64::from(b.x) - i64::from(a.x)) * (i64::from(p.x) - i64::from(b.x))
+ (i64::from(b.y) - i64::from(a.y)) * (i64::from(p.y) - i64::from(b.y));
if cross(a, b, p) == 0 && forward > 0 {
clean.pop();
}
}
clean.push(p);
}
clean
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum CopperRef {
Pad { placement: usize, pad: usize },
Track { track: usize, segment: usize },
Via(usize),
}
#[derive(Clone, Debug)]
pub struct CopperItem {
pub owner: CopperRef,
pub shape: Shape,
pub layers: (u8, u8),
}
impl CopperItem {
fn shares_layer(&self, other: &Self) -> bool {
self.layers.0 <= other.layers.1 && other.layers.0 <= self.layers.1
}
}
#[derive(Clone, Debug, Default)]
pub struct Connectivity {
pub items: Vec<CopperItem>,
pub islands: Vec<usize>,
pub island_count: usize,
pub item_nets: Vec<Option<String>>,
pub island_nets: Vec<BTreeSet<String>>,
pub zone_islands: Vec<Vec<usize>>,
}
impl Connectivity {
pub fn island_net(&self, island: usize) -> Option<&str> {
let nets = &self.island_nets[island];
(nets.len() == 1).then(|| nets.iter().next().unwrap().as_str())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Airwire {
pub net: String,
pub a: Point,
pub b: Point,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ViolationKind {
Short,
Clearance,
TrackWidth,
BoardEdge,
MissingPad,
Courtyard,
AnnularRing,
Hole,
Stitching,
Unrouted,
PinSeat,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Violation {
pub kind: ViolationKind,
pub message: String,
pub at: Point,
}
struct Dsu(Vec<usize>);
impl Dsu {
fn new(n: usize) -> Self {
Self((0..n).collect())
}
fn root(&mut self, mut i: usize) -> usize {
while self.0[i] != i {
self.0[i] = self.0[self.0[i]];
i = self.0[i];
}
i
}
fn join(&mut self, a: usize, b: usize) -> bool {
let (a, b) = (self.root(a), self.root(b));
if a != b {
self.0[a.max(b)] = a.min(b);
}
a != b
}
}
fn object_key(owner: CopperRef) -> (u8, usize, usize) {
match owner {
CopperRef::Pad { placement, pad } => (0, placement, pad),
CopperRef::Track { track, .. } => (1, track, 0),
CopperRef::Via(v) => (2, v, 0),
}
}
fn near_pairs(items: &[CopperItem], slack: i32, mut visit: impl FnMut(usize, usize)) {
let bounds: Vec<_> = items.iter().map(|i| i.shape.bounds()).collect();
let mut order: Vec<usize> = (0..items.len()).collect();
order.sort_by_key(|&i| (bounds[i].0.x, i));
for (k, &i) in order.iter().enumerate() {
let (min, max) = bounds[i];
for &j in &order[k + 1..] {
let (other_min, other_max) = bounds[j];
if other_min.x > max.x.saturating_add(slack) {
break;
}
if other_min.y > max.y.saturating_add(slack)
|| min.y > other_max.y.saturating_add(slack)
|| !items[i].shares_layer(&items[j])
{
continue;
}
visit(i.min(j), i.max(j));
}
}
}
pub fn pin_nets(netlist: &Netlist) -> BTreeMap<(Uuid, String), String> {
netlist
.nets
.iter()
.flat_map(|n| {
n.pins
.iter()
.map(|p| ((p.component_id, p.number.clone()), n.name.clone()))
})
.collect()
}
impl Board {
pub fn outline_bounds(&self) -> (Point, Point) {
bounds_of(&self.outline).unwrap_or_default()
}
pub fn outline_is_rectangle(&self) -> bool {
let (min, max) = self.outline_bounds();
self.outline.len() == 4
&& self
.outline
.iter()
.all(|p| (p.x == min.x || p.x == max.x) && (p.y == min.y || p.y == max.y))
&& min.x < max.x
&& min.y < max.y
}
pub fn outline_contains(&self, p: Point) -> bool {
polygon_contains(&self.outline, p) && !self.cutouts.iter().any(|c| polygon_contains(&c.points, p))
}
pub fn outline_edges(&self) -> impl Iterator<Item = (Point, Point)> + '_ {
std::iter::once(self.outline.as_slice())
.chain(self.cutouts.iter().map(|c| c.points.as_slice()))
.flat_map(ring_edges)
}
pub fn cutout_problem(&self, points: &[Point], except: Option<usize>) -> Option<String> {
self.cutout_problem_among(points, &self.cutouts, except)
}
fn cutout_problem_among(&self, points: &[Point], others: &[BoardCutout], except: Option<usize>) -> Option<String> {
if points.len() < 3 {
return Some("needs at least three corners".into());
}
if points.len() > MAX_CUTOUT_CORNERS {
return Some(format!("has more than {MAX_CUTOUT_CORNERS} corners"));
}
if zones::ring_area(points) == 0. {
return Some("encloses no area".into());
}
if ring_crosses_itself(points) {
return Some("crosses itself".into());
}
if points.iter().any(|&p| !polygon_contains(&self.outline, p)) || rings_touch(points, &self.outline) {
return Some("is not wholly inside the board outline".into());
}
let bounds = bounds_of(points);
for (k, other) in others.iter().enumerate() {
let apart = match (bounds, bounds_of(&other.points)) {
(Some((a0, a1)), Some((b0, b1))) => a1.x < b0.x || b1.x < a0.x || a1.y < b0.y || b1.y < a0.y,
_ => true,
};
if Some(k) == except || apart {
continue;
}
if rings_touch(points, &other.points)
|| polygon_contains(&other.points, points[0])
|| polygon_contains(points, other.points[0])
{
return Some(format!("overlaps cutout {}", k + 1));
}
}
None
}
pub fn set_layer_count(&mut self, count: u8) -> Result<(), String> {
if !(1..=32).contains(&count) {
return Err("Boards need between 1 and 32 copper layers".into());
}
let old_last = self.layer_count.saturating_sub(1);
let new_last = count - 1;
if self
.tracks
.iter()
.any(|t| t.layer != 0 && t.layer != old_last && t.layer >= new_last)
{
return Err("Move or delete the tracks on removed inner layers first".into());
}
if self
.zones
.iter()
.any(|z| z.layer != 0 && z.layer != old_last && z.layer >= new_last)
{
return Err("Move or delete the zones on removed inner layers first".into());
}
if count == 1 && self.zones.iter().any(|z| z.layer != 0) {
return Err("A single-layer board cannot keep bottom zones".into());
}
if count == 1
&& (!self.vias.is_empty()
|| !self.pad_vias().is_empty()
|| self.placements.iter().any(|p| p.bottom || p.has_back_copper_pad())
|| self.tracks.iter().any(|t| t.layer != 0))
{
return Err(
"A single-layer board cannot keep vias (a pad's own included), bottom tracks, bottom-side parts, or back-side pads".into(),
);
}
let remap = |layer: u8| -> Option<u8> {
if layer == 0 {
Some(0)
} else if layer == old_last {
Some(new_last)
} else if layer < new_last {
Some(layer)
} else {
None
}
};
let mut spans = vec![];
for via in &self.vias {
spans.push(match via.span {
None => None,
Some((from, to)) => match (remap(from), remap(to)) {
(Some(from), Some(to)) if from < to => Some((from, to)),
_ => return Err("Move or delete the blind and buried vias on removed inner layers first".into()),
},
});
}
for (via, span) in self.vias.iter_mut().zip(spans) {
via.span = span;
}
for track in &mut self.tracks {
if track.layer == old_last && old_last != 0 {
track.layer = new_last;
}
}
for zone in &mut self.zones {
if zone.layer == old_last && old_last != 0 {
zone.layer = new_last;
}
}
self.layer_count = count;
Ok(())
}
pub fn placement(&self, component: Uuid) -> Option<&Placement> {
self.placements.iter().find(|p| p.component == component)
}
pub fn pad_vias(&self) -> Vec<(Via, bool, bool)> {
let mut out = vec![];
for placement in &self.placements {
for (index, pad) in placement.footprint.pads.iter().enumerate() {
let Some(grid) = pad.vias else { continue };
let (layer, _) = placement.pad_layers(pad, self.layer_count);
let far_is_bottom = layer == 0;
out.extend(placement.pad_vias(index).into_iter().map(|via| (via, grid.tented, far_is_bottom)));
}
}
out
}
pub fn all_vias(&self) -> Vec<Via> {
let mut out = self.vias.clone();
out.extend(self.pad_vias().into_iter().map(|(via, _, _)| via));
out
}
pub fn copper(&self) -> Vec<CopperItem> {
let mut items = vec![];
for (pi, placement) in self.placements.iter().enumerate() {
for (pad_index, pad) in placement.footprint.pads.iter().enumerate() {
items.push(CopperItem {
owner: CopperRef::Pad {
placement: pi,
pad: pad_index,
},
shape: placement.pad_shape(pad),
layers: placement.pad_layers(pad, self.layer_count),
});
}
}
for (ti, track) in self.tracks.iter().enumerate() {
for (segment, shape) in track.segments().enumerate() {
items.push(CopperItem {
owner: CopperRef::Track { track: ti, segment },
shape,
layers: (track.layer, track.layer),
});
}
}
for (vi, via) in self.all_vias().iter().enumerate() {
items.push(CopperItem {
owner: CopperRef::Via(vi),
shape: Shape::circle(via.at, via.diameter / 2),
layers: via.layers(self.layer_count),
});
}
items
}
pub fn connectivity(&self, netlist: &Netlist) -> Connectivity {
self.connectivity_of(netlist, true)
}
pub fn connectivity_of(&self, netlist: &Netlist, with_zones: bool) -> Connectivity {
let items = self.copper();
let pins = pin_nets(netlist);
let pieces: Vec<(usize, &FillPiece)> = if with_zones {
self.zones
.iter()
.enumerate()
.flat_map(|(z, zone)| zone.fill.iter().map(move |p| (z, p)))
.collect()
} else {
vec![]
};
let mut dsu = Dsu::new(items.len() + pieces.len());
near_pairs(&items, 0, |i, j| {
if items[i].shape.distance(&items[j].shape) <= 0.5 {
dsu.join(i, j);
}
});
for (k, (z, piece)) in pieces.iter().enumerate() {
let layer = self.zones[*z].layer;
let (min, max) = piece.bounds();
for (i, item) in items.iter().enumerate() {
let (lo, hi) = item.shape.bounds();
if item.layers.0 <= layer
&& layer <= item.layers.1
&& lo.x <= max.x
&& hi.x >= min.x
&& lo.y <= max.y
&& hi.y >= min.y
&& piece.touches(&item.shape)
{
dsu.join(i, items.len() + k);
}
}
}
let mut numbering = BTreeMap::new();
let mut all: Vec<usize> = (0..items.len() + pieces.len())
.map(|i| {
let next = numbering.len();
*numbering.entry(dsu.root(i)).or_insert(next)
})
.collect();
let piece_islands = all.split_off(items.len());
let islands = all;
let mut zone_islands: Vec<Vec<usize>> = if with_zones {
self.zones.iter().map(|z| Vec::with_capacity(z.fill.len())).collect()
} else {
vec![]
};
for ((z, _), island) in pieces.iter().zip(piece_islands) {
zone_islands[*z].push(island);
}
let item_nets: Vec<Option<String>> = items
.iter()
.map(|item| match item.owner {
CopperRef::Pad { placement, pad } => {
let placement = &self.placements[placement];
let number = &placement.footprint.pads[pad].number;
pins.get(&(placement.component, number.clone())).cloned()
}
_ => None,
})
.collect();
let mut island_nets = vec![BTreeSet::new(); numbering.len()];
for (island, net) in islands.iter().zip(&item_nets) {
if let Some(net) = net {
island_nets[*island].insert(net.clone());
}
}
Connectivity {
island_count: numbering.len(),
items,
islands,
item_nets,
island_nets,
zone_islands,
}
}
pub fn ratsnest(&self, conn: &Connectivity) -> Vec<Airwire> {
let mut net_pads: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
for (i, net) in conn.item_nets.iter().enumerate() {
if let Some(net) = net {
net_pads.entry(net).or_default().push(i);
}
}
let mut island_anchors: BTreeMap<usize, Vec<Point>> = BTreeMap::new();
for (i, item) in conn.items.iter().enumerate() {
let anchors = island_anchors.entry(conn.islands[i]).or_default();
match item.owner {
CopperRef::Track { .. } => {
if let Shape::Capsule { a, b, .. } = item.shape {
anchors.extend([a, b]);
}
}
CopperRef::Via(_) => anchors.push(item.shape.center()),
CopperRef::Pad { .. } => {}
}
}
let mut airwires = vec![];
for (net, pads) in net_pads {
let islands: BTreeSet<usize> = pads.iter().map(|&i| conn.islands[i]).collect();
if islands.len() < 2 {
continue;
}
let mut anchors: Vec<(usize, Point)> = pads
.iter()
.map(|&i| (conn.islands[i], conn.items[i].shape.center()))
.collect();
let extra: Vec<(usize, Point)> = islands
.iter()
.flat_map(|&island| {
island_anchors
.get(&island)
.into_iter()
.flatten()
.map(move |p| (island, *p))
})
.collect();
if anchors.len() + extra.len() <= 400 {
anchors.extend(extra);
}
anchors.sort();
anchors.dedup();
let mut pairs = vec![];
for i in 0..anchors.len() {
for j in i + 1..anchors.len() {
if anchors[i].0 != anchors[j].0 {
let dx = i64::from(anchors[i].1.x) - i64::from(anchors[j].1.x);
let dy = i64::from(anchors[i].1.y) - i64::from(anchors[j].1.y);
pairs.push((dx * dx + dy * dy, i, j));
}
}
}
pairs.sort_unstable();
let index: BTreeMap<usize, usize> =
islands.iter().enumerate().map(|(i, &s)| (s, i)).collect();
let mut dsu = Dsu::new(islands.len());
let mut joined = 1;
for (_, i, j) in pairs {
if dsu.join(index[&anchors[i].0], index[&anchors[j].0]) {
airwires.push(Airwire {
net: net.to_owned(),
a: anchors[i].1,
b: anchors[j].1,
});
joined += 1;
if joined == islands.len() {
break;
}
}
}
}
airwires
}
fn describe(&self, owner: CopperRef, references: &BTreeMap<Uuid, String>) -> String {
match owner {
CopperRef::Pad { placement, pad } => {
let placement = &self.placements[placement];
format!(
"{} pad {}",
references
.get(&placement.component)
.map_or("?", String::as_str),
placement.footprint.pads[pad].number
)
}
CopperRef::Track { track, .. } => format!(
"track on {}",
layer_name(self.tracks[track].layer, self.layer_count)
),
CopperRef::Via(_) => "via".into(),
}
}
fn describe_on(&self, owner: CopperRef, nets: &BTreeSet<String>, references: &BTreeMap<Uuid, String>) -> String {
let what = self.describe(owner, references);
if nets.is_empty() {
what
} else {
format!("{what} ({})", nets.iter().cloned().collect::<Vec<_>>().join(", "))
}
}
fn drilled_holes(&self) -> Vec<(CopperItem, bool)> {
let gaps = |(from, to): (u8, u8)| (from, to.saturating_sub(1).max(from));
let mut holes = vec![];
for (pi, placement) in self.placements.iter().enumerate() {
for (pad_index, pad) in placement.footprint.pads.iter().enumerate() {
let Some(shape) = placement.pad_hole(pad) else { continue };
let item = CopperItem {
owner: CopperRef::Pad { placement: pi, pad: pad_index },
shape,
layers: gaps(placement.pad_layers(pad, self.layer_count)),
};
holes.push((item, pad.plated));
}
}
for (vi, via) in self.all_vias().iter().enumerate() {
let item = CopperItem {
owner: CopperRef::Via(vi),
shape: Shape::circle(via.at, via.drill / 2),
layers: gaps(via.layers(self.layer_count)),
};
holes.push((item, true));
}
holes
}
fn hole_findings(&self, conn: &Connectivity, references: &BTreeMap<Uuid, String>) -> Vec<Violation> {
let holes = self.drilled_holes();
let own_vias = self.vias.len();
let grid_owner: Vec<CopperRef> = self
.placements
.iter()
.enumerate()
.flat_map(|(pi, placement)| {
(0..placement.footprint.pads.len()).flat_map(move |pad_index| {
let count = placement.pad_vias(pad_index).len();
std::iter::repeat_n(CopperRef::Pad { placement: pi, pad: pad_index }, count)
})
})
.collect();
let pad_of_via = |owner: CopperRef| match owner {
CopperRef::Via(v) if v >= own_vias => grid_owner.get(v - own_vias).copied(),
_ => None,
};
let label = |owner: CopperRef| match (owner, pad_of_via(owner)) {
(_, Some(pad)) => format!("a via in {}", self.describe(pad, references)),
(CopperRef::Via(_), None) => "via".to_owned(),
(owner, None) => format!("{} hole", self.describe(owner, references)),
};
let spacing = f64::from(self.rules.min_hole_spacing);
let mm = |v: f64| v / 1000.;
let mut violations = vec![];
let items: Vec<CopperItem> = holes.iter().map(|(item, _)| item.clone()).collect();
let mut grids_reported = BTreeSet::new();
near_pairs(&items, self.rules.min_hole_spacing.max(1), |i, j| {
let (a, b) = (&items[i], &items[j]);
let gap = a.shape.distance(&b.shape);
if !(gap + 0.5 < spacing || gap == 0.) {
return;
}
let (ca, cb) = (a.shape.center(), b.shape.center());
let at = Point::new(
((i64::from(ca.x) + i64::from(cb.x)) / 2) as i32,
((i64::from(ca.y) + i64::from(cb.y)) / 2) as i32,
);
let message = match (pad_of_via(a.owner), pad_of_via(b.owner)) {
(Some(pa), Some(pb)) if pa == pb => {
if !grids_reported.insert(pa) {
return;
}
format!(
"{}'s vias: {:.3} mm between holes, minimum hole spacing {:.3} mm",
self.describe(pa, references),
mm(gap),
mm(spacing)
)
}
_ => format!(
"{} to {}: {:.3} mm between holes, minimum hole spacing {:.3} mm",
label(a.owner),
label(b.owner),
mm(gap),
mm(spacing)
),
};
violations.push(Violation { kind: ViolationKind::Hole, message, at });
});
let nets_of = |island: usize| conn.island_nets[island].iter().map(String::as_str);
let mut pad_items = BTreeMap::new();
for (i, item) in conn.items.iter().enumerate() {
if let CopperRef::Pad { .. } = item.owner {
pad_items.insert(object_key(item.owner), i);
}
}
for (hole, _) in holes.iter().filter(|(_, plated)| !plated) {
let Some(&own) = pad_items.get(&object_key(hole.owner)) else { continue };
let own_island = conn.islands[own];
let own_net = conn.island_net(own_island);
let unplated = format!("{}'s unplated hole", self.describe(hole.owner, references));
let pad_copper = &conn.items[own].shape;
let reported_by_copper = |related: bool, gap_to_pad: f64, required: i32| {
!related && gap_to_pad + 0.5 < f64::from(required)
};
let too_near = |gap: f64, required: i32| gap + 0.5 < f64::from(required) || gap == 0.;
let mut reported = BTreeSet::new();
for (i, item) in conn.items.iter().enumerate() {
let island = conn.islands[i];
if i == own || !(item.layers.0 <= hole.layers.1 + 1 && hole.layers.0 <= item.layers.1) {
continue;
}
let related = island == own_island || own_net.is_some() && conn.island_net(island) == own_net;
let (required, class) = self.rules.clearance_between_nets(nets_of(own_island), nets_of(island));
if reported_by_copper(related, pad_copper.distance(&item.shape), required) {
continue;
}
let gap = hole.shape.distance(&item.shape);
if too_near(gap, required) && reported.insert(object_key(item.owner)) {
violations.push(Violation {
kind: ViolationKind::Hole,
message: format!(
"{unplated} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
self.describe_on(item.owner, &conn.island_nets[island], references),
mm(gap),
class.name,
mm(f64::from(required))
),
at: hole.shape.center(),
});
}
}
let edge_clearance = f64::from(self.rules.edge_clearance);
let off_edge = |shape: &Shape| {
let gap = self
.outline_edges()
.map(|(a, b)| shape.distance(&Shape::segment(a, b, 0)))
.fold(f64::INFINITY, f64::min);
!self.outline_contains(shape.center()) || gap + 0.5 < edge_clearance || gap == 0.
};
if off_edge(&hole.shape) && !off_edge(pad_copper) {
violations.push(Violation {
kind: ViolationKind::Hole,
message: format!(
"{unplated} is outside the board or within {:.3} mm of its edge",
mm(edge_clearance)
),
at: hole.shape.center(),
});
}
for (z, zone) in self.zones.iter().enumerate() {
for (k, piece) in zone.fill.iter().enumerate() {
let island = conn.zone_islands[z][k];
let related = island == own_island || own_net == Some(zone.net.as_str());
let (required, class) = self.rules.clearance_between_nets(nets_of(own_island), [zone.net.as_str()]);
if reported_by_copper(related, piece.distance(pad_copper), required) {
continue;
}
let gap = piece.distance(&hole.shape);
if too_near(gap, required) {
violations.push(Violation {
kind: ViolationKind::Hole,
message: format!(
"{unplated} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
zones::describe(zone, self.layer_count),
mm(gap),
class.name,
mm(f64::from(required))
),
at: hole.shape.center(),
});
break;
}
}
}
}
violations
}
pub fn drc(&self, netlist: &Netlist) -> Vec<Violation> {
let conn = self.connectivity(netlist);
let references: BTreeMap<Uuid, String> = netlist
.nets
.iter()
.flat_map(|n| &n.pins)
.map(|p| (p.component_id, p.reference.clone()))
.collect();
let object = |owner: CopperRef| match owner {
CopperRef::Pad { placement, pad } => (0, placement, pad),
CopperRef::Track { track, .. } => (1, track, 0),
CopperRef::Via(v) => (2, v, 0),
};
let mut violations = vec![];
for (island, nets) in conn.island_nets.iter().enumerate() {
if nets.len() > 1 {
let at = conn
.islands
.iter()
.position(|&i| i == island)
.map_or_else(Point::default, |i| conn.items[i].shape.center());
violations.push(Violation {
kind: ViolationKind::Short,
message: format!(
"Short circuit between {}",
nets.iter().cloned().collect::<Vec<_>>().join(", ")
),
at,
});
}
}
let nets_of = |island: usize| conn.island_nets[island].iter().map(String::as_str);
let mut reported = BTreeSet::new();
near_pairs(&conn.items, self.rules.max_clearance(), |i, j| {
let (island_i, island_j) = (conn.islands[i], conn.islands[j]);
if island_i == island_j {
return;
}
if let (Some(a), Some(b)) = (conn.island_net(island_i), conn.island_net(island_j))
&& a == b
{
return;
}
let (a, b) = (&conn.items[i], &conn.items[j]);
let (required, class) = self.rules.clearance_between_nets(nets_of(island_i), nets_of(island_j));
let clearance = f64::from(required);
let gap = a.shape.distance(&b.shape);
let key = (object(a.owner), object(b.owner));
if gap + 0.5 < clearance && reported.insert(key) {
let (ca, cb) = (a.shape.center(), b.shape.center());
violations.push(Violation {
kind: ViolationKind::Clearance,
message: format!(
"{} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
self.describe_on(a.owner, &conn.island_nets[island_i], &references),
self.describe_on(b.owner, &conn.island_nets[island_j], &references),
gap / 1000.,
class.name,
clearance / 1000.
),
at: Point::new(
((i64::from(ca.x) + i64::from(cb.x)) / 2) as i32,
((i64::from(ca.y) + i64::from(cb.y)) / 2) as i32,
),
});
}
});
let edge_clearance = f64::from(self.rules.edge_clearance);
for (z, zone) in self.zones.iter().enumerate() {
let label = zones::describe(zone, self.layer_count);
let mut reported = BTreeSet::new();
for (k, piece) in zone.fill.iter().enumerate() {
let island = conn.zone_islands[z][k];
let (min, max) = piece.bounds();
for (i, item) in conn.items.iter().enumerate() {
if !(item.layers.0 <= zone.layer && zone.layer <= item.layers.1)
|| conn.islands[i] == island
{
continue;
}
if conn.island_net(conn.islands[i]) == Some(zone.net.as_str())
&& conn.island_net(island) == Some(zone.net.as_str())
{
continue;
}
let (lo, hi) = item.shape.bounds();
let slack = self.rules.max_clearance();
if lo.x > max.x + slack
|| hi.x < min.x - slack
|| lo.y > max.y + slack
|| hi.y < min.y - slack
{
continue;
}
let (required, class) =
self.rules.clearance_between_nets([zone.net.as_str()], nets_of(conn.islands[i]));
let clearance = f64::from(required);
let gap = piece.distance(&item.shape);
if gap + 0.5 < clearance && reported.insert(object(item.owner)) {
violations.push(Violation {
kind: ViolationKind::Clearance,
message: format!(
"{label} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
self.describe_on(item.owner, &conn.island_nets[conn.islands[i]], &references),
gap / 1000.,
class.name,
clearance / 1000.
),
at: item.shape.center(),
});
}
}
for (other_z, other) in self.zones.iter().enumerate().skip(z + 1) {
if other.layer != zone.layer || other.net == zone.net {
continue;
}
for (m, other_piece) in other.fill.iter().enumerate() {
if conn.zone_islands[other_z][m] == island {
continue;
}
let (required, class) =
self.rules.clearance_between(Some(zone.net.as_str()), Some(other.net.as_str()));
let clearance = f64::from(required);
let gap = piece.distance_to_piece(other_piece);
if gap + 0.5 < clearance {
violations.push(Violation {
kind: ViolationKind::Clearance,
message: format!(
"{label} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
zones::describe(other, self.layer_count),
gap / 1000.,
class.name,
clearance / 1000.
),
at: other_piece.outer[0],
});
}
}
}
let edge_gap = piece
.edges()
.flat_map(|(a, b)| {
let edge = Shape::segment(a, b, 0);
self.outline_edges()
.map(move |(c, d)| edge.distance(&Shape::segment(c, d, 0)))
})
.fold(f64::INFINITY, f64::min);
let covers_cutout = self.cutouts.iter().any(|c| piece.contains(c.points[0]));
if !self.outline_contains(piece.outer[0])
|| edge_gap + 0.5 < edge_clearance
|| edge_gap == 0.
|| covers_cutout
{
violations.push(Violation {
kind: ViolationKind::BoardEdge,
message: format!(
"{label} is outside the board or within {:.3} mm of its edge",
edge_clearance / 1000.
),
at: piece.outer[0],
});
}
}
}
let mut reported = BTreeSet::new();
for item in &conn.items {
let center = item.shape.center();
let gap = self
.outline_edges()
.map(|(a, b)| item.shape.distance(&Shape::segment(a, b, 0)))
.fold(f64::INFINITY, f64::min);
if (!self.outline_contains(center) || gap + 0.5 < edge_clearance || gap == 0.)
&& reported.insert(object(item.owner))
{
violations.push(Violation {
kind: ViolationKind::BoardEdge,
message: format!(
"{} is outside the board or within {:.3} mm of its edge",
self.describe(item.owner, &references),
edge_clearance / 1000.
),
at: center,
});
}
}
let mut reported = BTreeSet::new();
for (i, item) in conn.items.iter().enumerate() {
let CopperRef::Track { track, .. } = item.owner else { continue };
let t = &self.tracks[track];
let nets = &conn.island_nets[conn.islands[i]];
let (required, rule) = match conn.island_net(conn.islands[i]) {
Some(net) if self.rules.net_widths.contains_key(net) => {
(self.rules.width_for(net), format!("{net}'s width"))
}
_ => {
let class = self.rules.class_of_nets(nets.iter().map(String::as_str));
let widest = nets
.iter()
.map(|n| self.rules.width_for(n))
.max()
.unwrap_or(class.track_width);
(widest, format!("{} width", class.name))
}
};
if t.width < required && reported.insert(track) {
violations.push(Violation {
kind: ViolationKind::TrackWidth,
message: format!(
"track on {}{}: {:.3} mm wide, {rule} {:.3} mm required",
layer_name(t.layer, self.layer_count),
if nets.is_empty() {
String::new()
} else {
format!(" ({})", nets.iter().cloned().collect::<Vec<_>>().join(", "))
},
f64::from(t.width) / 1000.,
f64::from(required) / 1000.
),
at: t.points.first().copied().unwrap_or_default(),
});
}
}
let overlap = |a: Option<(Point, Point)>, b: Option<(Point, Point)>| match (a, b) {
(Some((a0, a1)), Some((b0, b1))) => a0.x < b1.x && b0.x < a1.x && a0.y < b1.y && b0.y < a1.y,
_ => false,
};
for (i, a) in self.placements.iter().enumerate() {
for b in &self.placements[i + 1..] {
if [true, false].into_iter().any(|top| overlap(a.courtyard_on(top), b.courtyard_on(top))) {
violations.push(Violation {
kind: ViolationKind::Courtyard,
message: format!(
"Courtyards of {} and {} overlap",
references.get(&a.component).map_or("?", String::as_str),
references.get(&b.component).map_or("?", String::as_str)
),
at: Point::new((a.at.x + b.at.x) / 2, (a.at.y + b.at.y) / 2),
});
}
}
}
if self.layer_count == 1 {
for placement in self.placements.iter().filter(|p| p.has_back_copper_pad()) {
violations.push(Violation {
kind: ViolationKind::MissingPad,
message: format!(
"{} has pads on the back copper, which a one-layer board does not have",
references.get(&placement.component).map_or("?", String::as_str)
),
at: placement.at,
});
}
for placement in self.placements.iter().filter(|p| p.footprint.pads.iter().any(|pad| pad.vias.is_some())) {
violations.push(Violation {
kind: ViolationKind::MissingPad,
message: format!(
"{} has vias in its pads, which a one-layer board cannot carry",
references.get(&placement.component).map_or("?", String::as_str)
),
at: placement.at,
});
}
}
let ring = self.rules.min_annular_ring;
for placement in &self.placements {
for pad in &placement.footprint.pads {
if let Some(have) = pad.annular_ring().filter(|r| *r < ring) {
let reference = references.get(&placement.component).map_or("?", String::as_str);
let name = if pad.number.is_empty() { "unnumbered pad".to_owned() } else { format!("pad {}", pad.number) };
violations.push(Violation {
kind: ViolationKind::AnnularRing,
message: format!(
"{reference} {name}: annular ring {:.3} mm, {:.3} mm required",
f64::from(have) / 1000.,
f64::from(ring) / 1000.
),
at: placement.transform(pad.at),
});
}
}
}
for via in &self.all_vias() {
let have = (via.diameter - via.drill) / 2;
if have < ring {
violations.push(Violation {
kind: ViolationKind::AnnularRing,
message: format!(
"Via: annular ring {:.3} mm, {:.3} mm required",
f64::from(have) / 1000.,
f64::from(ring) / 1000.
),
at: via.at,
});
}
}
violations.extend(self.hole_findings(&conn, &references));
for net in netlist.nets.iter().filter(|n| n.pins.len() > 1) {
for pin in &net.pins {
if let Some(placement) = self.placement(pin.component_id)
&& !placement
.footprint
.pads
.iter()
.any(|p| p.number == pin.number)
{
violations.push(Violation {
kind: ViolationKind::MissingPad,
message: format!(
"{} pin {} (net {}) has no pad in footprint {}",
pin.reference, pin.number, net.name, placement.footprint.name
),
at: placement.at,
});
}
}
}
violations.extend(self.stitching_findings(netlist));
for wire in self.ratsnest(&conn) {
violations.push(Violation {
kind: ViolationKind::Unrouted,
message: format!("Unrouted connection in net {}", wire.net),
at: Point::new((wire.a.x + wire.b.x) / 2, (wire.a.y + wire.b.y) / 2),
});
}
violations.sort_by(|a, b| (a.kind, &a.message, a.at).cmp(&(b.kind, &b.message, b.at)));
violations
}
pub fn validate(&self, components: &BTreeSet<Uuid>) -> Result<(), String> {
let valid = |p: Point| p.x.abs_diff(0) <= 100_000_000 && p.y.abs_diff(0) <= 100_000_000;
let size = |v: i32| (1..=100_000_000).contains(&v);
if !(1..=32).contains(&self.layer_count) {
return Err("Boards need between 1 and 32 copper layers".into());
}
if self.outline.len() < 3 || self.outline.iter().any(|p| !valid(*p)) {
return Err("Board outline needs at least three valid points".into());
}
let r = &self.rules;
if !size(r.track_width)
|| !(0..=100_000_000).contains(&r.clearance)
|| !(0..=100_000_000).contains(&r.edge_clearance)
|| !size(r.via_drill)
|| r.via_diameter <= r.via_drill
|| !size(r.via_diameter)
|| !(10..=100_000).contains(&r.routing_grid)
|| r.net_widths.values().any(|w| !size(*w))
|| !(0..=10_000).contains(&r.mask_expansion)
|| !(0..=10_000).contains(&r.min_annular_ring)
|| !(0..=10_000).contains(&r.min_hole_spacing)
{
return Err("Invalid design rules".into());
}
r.check_net_classes()?;
let mut placed = BTreeSet::new();
for p in &self.placements {
if !components.contains(&p.component) {
return Err("Footprint refers to a missing component".into());
}
if !placed.insert(p.component) {
return Err("Component has more than one footprint".into());
}
if !valid(p.at) || p.rotation > 3 {
return Err("Invalid footprint placement".into());
}
for pad in &p.footprint.pads {
if !valid(pad.at)
|| !size(pad.size.x)
|| !size(pad.size.y)
|| pad.outline_problem().is_some()
|| pad.layers.paste_windows.is_some_and(|w| w.problem().is_some())
|| pad.vias_problem().is_some()
|| pad.hole_problem().is_some()
|| pad.hole_size().is_some_and(|h| !size(h.x) || !size(h.y))
|| !(0..=100_000).contains(&pad.corner_radius)
|| [pad.layers.mask_margin, pad.layers.paste_margin]
.into_iter()
.flatten()
.any(|m| !(-10_000..=10_000).contains(&m))
{
return Err(format!("Invalid pad in footprint {}", p.footprint.name));
}
}
if p.footprint.courtyard_margin.is_some_and(|m| !(0..=100_000).contains(&m)) {
return Err(format!("Invalid courtyard clearance in footprint {}", p.footprint.name));
}
if p.footprint.silk.iter().flatten().any(|q| !valid(*q)) {
return Err("Invalid footprint silkscreen".into());
}
if p.footprint.graphics.len() > 100_000
|| p.footprint.graphics.iter().any(|g| g.problem().is_some())
{
return Err(format!("Invalid drawing in footprint {}", p.footprint.name));
}
}
if self.graphics.len() > 100_000 {
return Err("A board holds at most 100000 drawn items".into());
}
let mut ids = BTreeSet::new();
if !self.graphics.iter().all(|g| ids.insert(g.id)) {
return Err("Two board drawings share an id".into());
}
if let Some((n, problem)) = self
.graphics
.iter()
.enumerate()
.find_map(|(n, g)| g.problem().map(|p| (n, p)))
{
return Err(format!("Board drawing {} {problem}", n + 1));
}
if self.cutouts.len() > MAX_CUTOUTS {
return Err(format!("A board holds at most {MAX_CUTOUTS} cutouts"));
}
let mut ids = BTreeSet::new();
if !self.cutouts.iter().all(|c| ids.insert(c.id)) {
return Err("Two board cutouts share an id".into());
}
for (n, c) in self.cutouts.iter().enumerate() {
if c.points.iter().any(|q| !valid(*q)) {
return Err(format!("Cutout {} has a corner off the drawing area", n + 1));
}
if let Some(problem) = self.cutout_problem_among(&c.points, &self.cutouts[..n], None) {
return Err(format!("Cutout {} {problem}", n + 1));
}
}
for t in &self.tracks {
if t.layer >= self.layer_count
|| !size(t.width)
|| t.points.len() < 2
|| t.points.iter().any(|q| !valid(*q))
|| t.points.windows(2).any(|s| s[0] == s[1])
{
return Err("Tracks need a valid layer, width, and nonzero segments".into());
}
}
for v in &self.vias {
if !valid(v.at) || !size(v.drill) || v.diameter <= v.drill {
return Err("Invalid via".into());
}
if v.span.is_some_and(|(from, to)| from >= to || to >= self.layer_count) {
return Err("A blind or buried via needs two different layers of the board".into());
}
}
for zone in &self.zones {
zone.validate(self.layer_count)?;
}
Ok(())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BoardSync {
pub added: usize,
pub removed: usize,
pub without_pads: Vec<String>,
pub outline_grew: Option<(Point, Point)>,
}
pub fn needs_footprint(component: &crate::Component) -> bool {
!component.off_board && (component.pads.is_some() || (component.symbol.power_net.is_none()
&& !component.reference.starts_with('#')
&& !component.symbol.pins.is_empty()))
}
impl Document {
pub fn sync_board(&mut self) -> BoardSync {
let wanted: BTreeSet<Uuid> = self
.components
.iter()
.filter(|c| needs_footprint(c))
.map(|c| c.id)
.collect();
let before = self.board.placements.len();
self.board
.placements
.retain(|p| wanted.contains(&p.component));
let removed = before - self.board.placements.len();
let was_empty = self.board.placements.is_empty();
let mut added = vec![];
let mut without_pads = vec![];
for c in self.components.iter().filter(|c| wanted.contains(&c.id)) {
if self.board.placement(c.id).is_some() {
continue;
}
let Some(pads) = &c.pads else {
without_pads.push(c.reference.clone());
continue;
};
self.board.placements.push(Placement {
component: c.id,
footprint: pads.clone(),
at: Point::default(),
rotation: 0,
bottom: false,
});
added.push(c.id);
}
without_pads.sort_by(|a, b| footprint::natural_cmp(a, b));
let size = |(min, max): (Point, Point)| Point::new(max.x - min.x, max.y - min.y);
let before = size(self.board.outline_bounds());
if was_empty {
self.auto_place();
} else if !added.is_empty() {
let homeless = self.seat_in_free_room(&added);
if !homeless.is_empty() {
let (min, _) = self.board.outline_bounds();
let top = self
.board
.placements
.iter()
.filter(|p| !homeless.contains(&p.component))
.map(|p| p.courtyard().1.y + PLACEMENT_SPACING)
.max()
.unwrap_or(min.y + PLACEMENT_SPACING);
self.pack(&homeless, top);
}
}
let after = size(self.board.outline_bounds());
BoardSync {
added: added.len(),
removed,
without_pads,
outline_grew: (!was_empty && after != before).then_some((before, after)),
}
}
pub fn place_by_nets(&mut self) {
let order = self.placement_order();
let homeless = self.seat_in_free_room(&order);
if !homeless.is_empty() {
let (min, _) = self.board.outline_bounds();
let top = self
.board
.placements
.iter()
.filter(|p| !homeless.contains(&p.component))
.map(|p| p.courtyard().1.y + PLACEMENT_SPACING)
.max()
.unwrap_or(min.y + PLACEMENT_SPACING);
self.pack(&homeless, top);
}
}
fn seat_in_free_room(&mut self, ids: &[Uuid]) -> Vec<Uuid> {
let mut pending: BTreeSet<Uuid> = ids.iter().copied().collect();
let mut nets_of: BTreeMap<Uuid, Vec<usize>> = BTreeMap::new();
for (n, net) in self.netlist().nets.iter().enumerate() {
let members: BTreeSet<Uuid> = net.pins.iter().map(|p| p.component_id).collect();
if members.len() <= 8 {
for m in members {
nets_of.entry(m).or_default().push(n);
}
}
}
let (min, max) = self.board.outline_bounds();
let clearance = f64::from(self.board.rules.max_clearance());
let gap = f64::from(SEAT_GAP);
let mut homeless = vec![];
for &id in ids {
let Some(index) = self.board.placements.iter().position(|p| p.component == id) else {
continue;
};
let seated: Vec<&Placement> = self
.board
.placements
.iter()
.filter(|p| !pending.contains(&p.component))
.collect();
let mine = nets_of.get(&id).cloned().unwrap_or_default();
let near: Vec<Point> = seated
.iter()
.filter(|p| {
nets_of
.get(&p.component)
.is_some_and(|theirs| theirs.iter().any(|n| mine.contains(n)))
})
.map(|p| p.at)
.collect();
let centre = |points: &[Point]| {
let n = points.len().max(1) as i64;
let (x, y) = points
.iter()
.fold((0i64, 0i64), |(x, y), p| (x + i64::from(p.x), y + i64::from(p.y)));
Point::new((x / n) as i32, (y / n) as i32)
};
let target = if !near.is_empty() {
centre(&near)
} else if !seated.is_empty() {
centre(&seated.iter().map(|p| p.at).collect::<Vec<_>>())
} else {
Point::new((min.x + max.x) / 2, (min.y + max.y) / 2)
};
let mut placement = self.board.placements[index].clone();
placement.at = Point::default();
let mounted_top = !placement.bottom;
let on_side = |top: bool| -> Vec<Shape> {
seated
.iter()
.filter_map(|p| p.courtyard_on(top))
.map(|(min, max)| Shape::Rect { min, max })
.collect()
};
let (courtyards, other_side) = (on_side(mounted_top), on_side(!mounted_top));
let back = placement.back_courtyard();
let copper: Vec<Shape> = self
.board
.copper()
.into_iter()
.filter(|item| match item.owner {
CopperRef::Pad { placement, .. } => {
!pending.contains(&self.board.placements[placement].component)
}
_ => true,
})
.map(|item| item.shape)
.collect();
let (c0, c1) = placement.courtyard();
let step = 500;
let span = |lo: i32, hi: i32, c_lo: i32, c_hi: i32| {
let first = snap_up(lo + SEAT_GAP - c_lo, step);
let last = snap_down(hi - SEAT_GAP - c_hi, step);
(first..=last).step_by(step as usize)
};
let mut spots: Vec<Point> = span(min.x, max.x, c0.x, c1.x)
.flat_map(|x| span(min.y, max.y, c0.y, c1.y).map(move |y| Point::new(x, y)))
.collect();
let middle = Point::new((c0.x + c1.x) / 2, (c0.y + c1.y) / 2);
let far = |at: &Point| {
let (dx, dy) = (
i64::from(at.x + middle.x - target.x),
i64::from(at.y + middle.y - target.y),
);
(dx * dx + dy * dy, at.y, at.x)
};
spots.sort_by_key(far);
let free = spots.into_iter().find(|&at| {
let body = Shape::Rect { min: c0.offset(at), max: c1.offset(at) };
let corners = [
c0.offset(at),
c1.offset(at),
Point::new(c0.x, c1.y).offset(at),
Point::new(c1.x, c0.y).offset(at),
];
corners.iter().all(|&p| self.board.outline_contains(p))
&& self
.board
.outline_edges()
.all(|(a, b)| body.distance(&Shape::segment(a, b, 0)) >= gap)
&& courtyards.iter().all(|c| body.distance(c) >= gap)
&& back.is_none_or(|(b0, b1)| {
let back = Shape::Rect { min: b0.offset(at), max: b1.offset(at) };
other_side.iter().all(|c| back.distance(c) >= gap)
})
&& copper.iter().all(|c| body.distance(c) >= clearance)
});
match free {
Some(at) => {
placement.at = at;
self.board.placements[index] = placement;
pending.remove(&id);
}
None => homeless.push(id),
}
}
homeless
}
pub fn auto_place(&mut self) {
let order = self.placement_order();
let (min, _) = self.board.outline_bounds();
self.pack(&order, min.y + PLACEMENT_SPACING);
let (min, max) = self.board.outline_bounds();
let corners: Vec<Point> = self
.board
.placements
.iter()
.flat_map(|p| {
let (a, b) = p.courtyard();
[a, b]
})
.collect();
if let Some((a, b)) = bounds_of(&corners) {
let centre = |lo: i32, hi: i32, a: i32, b: i32| {
let shift = (lo + hi) / 2 - (a + b) / 2;
shift.div_euclid(100) * 100
};
let shift = Point::new(
centre(min.x, max.x, a.x, b.x),
centre(min.y, max.y, a.y, b.y),
);
for p in &mut self.board.placements {
p.at = p.at.offset(shift);
}
}
}
fn placement_order(&self) -> Vec<Uuid> {
let placed: BTreeSet<Uuid> = self.board.placements.iter().map(|p| p.component).collect();
let mut neighbours: BTreeMap<Uuid, BTreeSet<Uuid>> = BTreeMap::new();
for net in self.netlist().nets {
let members: BTreeSet<Uuid> = net
.pins
.iter()
.map(|p| p.component_id)
.filter(|c| placed.contains(c))
.collect();
if members.len() > 8 {
continue;
}
for a in &members {
neighbours
.entry(*a)
.or_default()
.extend(members.iter().filter(|b| *b != a));
}
}
let mut seeds: Vec<&crate::Component> = self
.components
.iter()
.filter(|c| placed.contains(&c.id))
.collect();
seeds.sort_by(|a, b| {
b.symbol
.pins
.len()
.cmp(&a.symbol.pins.len())
.then_with(|| footprint::natural_cmp(&a.reference, &b.reference))
});
let reference: BTreeMap<Uuid, &str> = self
.components
.iter()
.map(|c| (c.id, c.reference.as_str()))
.collect();
let mut order = vec![];
let mut seen = BTreeSet::new();
for seed in seeds {
if !seen.insert(seed.id) {
continue;
}
let mut queue = std::collections::VecDeque::from([seed.id]);
while let Some(id) = queue.pop_front() {
order.push(id);
let mut next: Vec<Uuid> = neighbours
.get(&id)
.into_iter()
.flatten()
.filter(|n| !seen.contains(*n))
.copied()
.collect();
next.sort_by(|a, b| footprint::natural_cmp(reference[a], reference[b]));
for n in next {
seen.insert(n);
queue.push_back(n);
}
}
}
order
}
fn pack(&mut self, ids: &[Uuid], top: i32) {
let (min, max) = self.board.outline_bounds();
let left = min.x + PLACEMENT_SPACING;
let right = max.x - PLACEMENT_SPACING;
let mut cursor = Point::new(left, top);
let mut row_height = 0;
for id in ids {
let Some(p) = self
.board
.placements
.iter_mut()
.find(|p| p.component == *id)
else {
continue;
};
p.at = Point::default();
let (c0, c1) = p.courtyard();
let (w, h) = (c1.x - c0.x, c1.y - c0.y);
if cursor.x + w > right && cursor.x > left {
cursor = Point::new(left, cursor.y + row_height + PLACEMENT_SPACING);
row_height = 0;
}
p.at = Point::new(snap_up(cursor.x - c0.x, 100), snap_up(cursor.y - c0.y, 100));
cursor.x += w + PLACEMENT_SPACING;
row_height = row_height.max(h);
}
let bottom = cursor.y + row_height + PLACEMENT_SPACING;
if bottom > max.y && self.board.outline_is_rectangle() {
self.board.outline = rectangle(min, Point::new(max.x, snap_up(bottom, 1000)));
}
}
pub fn fit_board_outline(&mut self, margin: i32) {
let corners: Vec<Point> = self
.board
.placements
.iter()
.flat_map(|p| {
let (a, b) = p.courtyard();
[a, b]
})
.chain(self.board.tracks.iter().flat_map(|t| t.points.clone()))
.chain(self.board.vias.iter().map(|v| v.at))
.chain(self.board.cutouts.iter().flat_map(|c| c.points.clone()))
.collect();
if let Some((min, max)) = bounds_of(&corners) {
self.board.outline = rectangle(
Point::new(
snap_down(min.x - margin, 1000),
snap_down(min.y - margin, 1000),
),
Point::new(snap_up(max.x + margin, 1000), snap_up(max.y + margin, 1000)),
);
}
}
pub fn track_nets(&self) -> BTreeMap<Uuid, String> {
let connectivity = self.board.connectivity(&self.netlist());
let mut nets = BTreeMap::new();
for (i, item) in connectivity.items.iter().enumerate() {
if let CopperRef::Track { track, .. } = item.owner
&& let Some(net) = connectivity.island_net(connectivity.islands[i])
{
nets.insert(self.board.tracks[track].id, net.to_owned());
}
}
nets
}
pub fn apply_net_widths(&mut self) -> usize {
let nets = self.track_nets();
let rules = self.board.rules.clone();
let mut changed = 0;
for track in self.board.tracks.iter_mut().filter(|t| !t.fixed_width) {
let width = nets
.get(&track.id)
.map_or(rules.track_width, |net| rules.width_for(net));
if track.width != width {
track.width = width;
changed += 1;
}
}
changed
}
pub fn set_track_width(&mut self, id: Uuid, width: i32) -> Result<(), String> {
if !(1..=100_000_000).contains(&width) {
return Err("A track needs a positive width".into());
}
let track = self
.board
.tracks
.iter_mut()
.find(|t| t.id == id)
.ok_or("Track no longer exists")?;
track.width = width;
track.fixed_width = true;
Ok(())
}
pub fn follow_net_width(&mut self, id: Uuid) {
let width = self
.track_nets()
.get(&id)
.map_or(self.board.rules.track_width, |net| {
self.board.rules.width_for(net)
});
if let Some(track) = self.board.tracks.iter_mut().find(|t| t.id == id) {
track.width = width;
track.fixed_width = false;
}
}
pub fn board_drc(&self) -> Vec<Violation> {
self.board.drc(&self.netlist())
}
}
fn snap_up(v: i32, step: i32) -> i32 {
v.div_euclid(step) * step + if v.rem_euclid(step) == 0 { 0 } else { step }
}
fn snap_down(v: i32, step: i32) -> i32 {
v.div_euclid(step) * step
}