use crate::csv_field;
use crate::board::{Board, Placement, Shape};
use crate::graphic::GraphicLayer;
use crate::{Document, Point};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
pub const SILK_WIDTH: i32 = 150;
pub const OUTLINE_WIDTH: i32 = 100;
pub const TEXT_HEIGHT: i32 = 1000;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FabricationFile {
pub name: String,
pub contents: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Fabrication {
pub files: Vec<FabricationFile>,
pub warnings: Vec<String>,
}
impl Fabrication {
pub fn zip(&self) -> Vec<u8> {
zip(self
.files
.iter()
.map(|f| (f.name.as_str(), f.contents.as_bytes())))
}
}
impl Document {
pub fn fabrication(&self, name: &str) -> Result<Fabrication, String> {
self.validate()?;
if self.board.layer_count == 1 {
if let Some(p) = self.board.placements.iter().find(|p| p.has_back_copper_pad()) {
let reference = self
.components
.iter()
.find(|c| c.id == p.component)
.map_or("A part", |c| c.reference.as_str());
return Err(format!(
"{reference} has pads on the back copper, which a one-layer board does not have: add a second copper layer or move those pads to the front."
));
}
if let Some(p) = self.board.placements.iter().find(|p| p.footprint.pads.iter().any(|pad| pad.vias.is_some())) {
let reference = self
.components
.iter()
.find(|c| c.id == p.component)
.map_or("A part", |c| c.reference.as_str());
return Err(format!(
"{reference} has vias in its pads, which a one-layer board cannot carry: add a second copper layer or take the vias out of its pads."
));
}
}
let netlist = self.netlist();
let refilled;
let board = if self.board.zones.is_empty() {
&self.board
} else {
let mut copy = self.board.clone();
copy.fill_zones(&netlist);
refilled = copy;
&refilled
};
let base: String = name
.trim()
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || "-_.".contains(c) {
c
} else {
'_'
}
})
.collect();
let base = if base.is_empty() {
"board".into()
} else {
base
};
let origin = Origin::new(board);
let last = board.layer_count - 1;
let mut files = vec![];
let mut add = |suffix: &str, contents: String| {
files.push(FabricationFile {
name: format!("{base}-{suffix}"),
contents,
})
};
for layer in 0..board.layer_count {
let (name, extension, function) = if layer == 0 {
("F_Cu".to_owned(), "gtl".to_owned(), "Copper,L1,Top")
} else if layer == last {
("B_Cu".into(), "gbl".into(), "Copper,L{},Bot")
} else {
(
format!("In{layer}_Cu"),
format!("g{}", layer + 1),
"Copper,L{},Inr",
)
};
let function = function.replace("{}", &(u32::from(layer) + 1).to_string());
add(
&format!("{name}.{extension}"),
copper(board, &origin, layer).finish(&function, "Positive"),
);
}
for (top, side) in [(true, "F"), (false, "B")] {
let (letter, position) = if top { ('t', "Top") } else { ('b', "Bot") };
add(
&format!("{side}_Mask.g{letter}s"),
mask(board, &origin, top).finish(&format!("Soldermask,{position}"), "Negative"),
);
add(
&format!("{side}_Paste.g{letter}p"),
paste(board, &origin, top).finish(&format!("Paste,{position}"), "Positive"),
);
}
let mut unsupported = BTreeSet::new();
for (top, side) in [(true, "F"), (false, "B")] {
let (letter, position) = if top { ('t', "Top") } else { ('b', "Bot") };
let layer = legend(self, &origin, top, &mut unsupported);
add(
&format!("{side}_Silkscreen.g{letter}o"),
layer.finish(&format!("Legend,{position}"), "Positive"),
);
}
let mut profile = Gerber::default();
profile.select(Aperture::Circle(OUTLINE_WIDTH), Some("Profile"));
for ring in std::iter::once(&board.outline).chain(board.cutouts.iter().map(|c| &c.points)) {
profile.stroke(ring.iter().chain(&ring[..1]).map(|p| origin.point(*p)));
}
add("Edge_Cuts.gm1", profile.finish("Profile,NP", "Positive"));
let (plated, unplated, spans) = drills(board, &origin);
let layers = board.layer_count;
for ((from, to), holes) in &spans {
let kind = if *from == 0 || *to + 1 == layers { "Blind" } else { "Buried" };
let (a, b) = (from + 1, to + 1);
add(
&format!("{kind}_{a}_{b}.drl"),
excellon(holes, &format!("Plated,{a},{b},{kind}"), &format!("Plated,{kind}")),
);
}
add(
"PTH.drl",
excellon(&plated, &format!("Plated,1,{layers},PTH"), "Plated,PTH"),
);
if !unplated.is_empty() {
add(
"NPTH.drl",
excellon(
&unplated,
&format!("NonPlated,1,{layers},NPTH"),
"NonPlated,NPTH",
),
);
}
let mut warnings = vec![];
if board.zones != self.board.zones {
warnings.push(
"The zones' fill was out of date, so these files carry a fresh fill: \
fill the zones on the board to see what was sent."
.to_owned(),
);
}
let findings = board.drc(&netlist);
if !findings.is_empty() {
let unrouted = findings
.iter()
.filter(|v| v.kind == crate::board::ViolationKind::Unrouted)
.count();
warnings.push(format!(
"The design rule check has {} finding(s), {unrouted} of them unrouted connections. \
Fix them before ordering boards.",
findings.len()
));
}
if !unsupported.is_empty() {
warnings.push(format!(
"Silkscreen text shows these characters as '?': {}",
unsupported.iter().collect::<String>()
));
}
add("pos.csv", self.pick_and_place_csv());
add("bom.csv", self.electronics_bom_csv());
let readme = readme(self, &files, &warnings);
files.push(FabricationFile {
name: format!("{base}-README.txt"),
contents: readme,
});
Ok(Fabrication { files, warnings })
}
pub fn pick_and_place_csv(&self) -> String {
let origin = Origin::new(&self.board);
let mut rows: Vec<(&str, String)> = vec![];
for placement in &self.board.placements {
let Some(component) = self.placed_part(placement) else {
continue;
};
let (x, y) = origin.point(placement.at);
let rotation = (4 - u32::from(placement.rotation % 4)) % 4 * 90;
rows.push((
&component.reference,
[
csv_field(&component.reference),
csv_field(&component.value),
csv_field(&placement.footprint.name),
format!("{}mm", millimetres(x / 1000)),
format!("{}mm", millimetres(y / 1000)),
rotation.to_string(),
if placement.bottom { "Bottom" } else { "Top" }.into(),
]
.join(","),
));
}
rows.sort_by(|a, b| natural(a.0).cmp(&natural(b.0)));
let mut out = String::from("Designator,Val,Package,Mid X,Mid Y,Rotation,Layer\n");
for (_, row) in rows {
out.push_str(&row);
out.push('\n');
}
out
}
pub fn electronics_bom_csv(&self) -> String {
let mut groups: BTreeMap<(String, String), Vec<&str>> = BTreeMap::new();
for component in self.components.iter().filter(|c| self.on_board(c)) {
if component.symbol.power_net.is_some() {
continue;
}
let footprint = self
.board
.placements
.iter()
.find(|p| p.component == component.id)
.map(|p| p.footprint.name.clone())
.or_else(|| component.pads.as_ref().map(|f| f.name.clone()))
.or_else(|| component.symbol.properties.get("Footprint").cloned())
.unwrap_or_default();
groups
.entry((component.value.clone(), footprint))
.or_default()
.push(&component.reference);
}
let mut lines: Vec<_> = groups
.into_iter()
.map(|((value, footprint), mut references)| {
references.sort_by(|a, b| natural(a).cmp(&natural(b)));
(value, footprint, references)
})
.collect();
lines.sort_by(|a, b| natural(a.2[0]).cmp(&natural(b.2[0])));
let mut out = String::from("Comment,Designator,Footprint,Quantity\n");
for (value, footprint, references) in lines {
let _ = writeln!(
out,
"{},{},{},{}",
csv_field(&value),
csv_field(&references.join(",")),
csv_field(&footprint),
references.len()
);
}
out
}
fn placed_part(&self, placement: &Placement) -> Option<&crate::Component> {
self.components
.iter()
.find(|c| c.id == placement.component && c.symbol.power_net.is_none())
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ReadBack {
pub top_flashes: usize,
pub bottom_flashes: usize,
pub plated_holes: usize,
pub unplated_holes: usize,
pub outline_mm: (f64, f64),
pub placements: usize,
pub bom_lines: usize,
}
impl Fabrication {
pub fn read_back(&self) -> ReadBack {
let text = |suffix: &str| {
self.files
.iter()
.find(|f| f.name.ends_with(suffix))
.map_or("", |f| f.contents.as_str())
};
let flashes = |t: &str| t.lines().filter(|l| l.starts_with('X') && l.ends_with("D03*")).count();
let holes = |t: &str| t.lines().filter(|l| l.starts_with('X')).count();
let rows = |t: &str| t.lines().count().saturating_sub(1);
let mut min = (i64::MAX, i64::MAX);
let mut max = (i64::MIN, i64::MIN);
for line in text("-Edge_Cuts.gm1").lines() {
let Some((x, rest)) = line.strip_prefix('X').and_then(|l| l.split_once('Y')) else {
continue;
};
let y = rest.split('D').next().unwrap_or("");
if let (Ok(x), Ok(y)) = (x.parse::<i64>(), y.parse::<i64>()) {
min = (min.0.min(x), min.1.min(y));
max = (max.0.max(x), max.1.max(y));
}
}
let outline_mm = if min.0 <= max.0 {
((max.0 - min.0) as f64 / 1e6, (max.1 - min.1) as f64 / 1e6)
} else {
(0., 0.)
};
ReadBack {
top_flashes: flashes(text("-F_Cu.gtl")),
bottom_flashes: flashes(text("-B_Cu.gbl")),
plated_holes: holes(text("-PTH.drl")),
unplated_holes: holes(text("-NPTH.drl")),
outline_mm,
placements: rows(text("-pos.csv")),
bom_lines: rows(text("-bom.csv")),
}
}
}
fn natural(text: &str) -> Vec<(String, u64)> {
let mut key = vec![];
let mut letters = String::new();
let mut digits = String::new();
for c in text.chars() {
if c.is_ascii_digit() {
digits.push(c);
} else {
if !digits.is_empty() {
key.push((std::mem::take(&mut letters), digits.parse().unwrap_or(u64::MAX)));
digits.clear();
}
letters.push(c);
}
}
key.push((letters, digits.parse().unwrap_or(0)));
key
}
fn readme(document: &Document, files: &[FabricationFile], warnings: &[String]) -> String {
let board = &document.board;
let (min, max) = board.outline_bounds();
let mut out = String::from("Fabrication files\n=================\n\n");
let _ = writeln!(
out,
"Board: {} copper layer(s), outline {} x {} mm.",
board.layer_count,
millimetres(i64::from(max.x) - i64::from(min.x)),
millimetres(i64::from(max.y) - i64::from(min.y)),
);
out.push_str(
"Units are millimetres. Every file shares one origin, the lower-left corner of the\n\
board outline, with Y up. All layers are viewed from the top.\n\n",
);
for file in files {
let (_, suffix) = file.name.rsplit_once('-').unwrap_or(("", &file.name));
let what = match suffix.split('.').next().unwrap_or("") {
"F_Cu" => "Gerber X2, top copper".to_owned(),
"B_Cu" => "Gerber X2, bottom copper".to_owned(),
inner if inner.starts_with("In") && inner.ends_with("_Cu") => {
format!("Gerber X2, inner copper layer {}", &inner[2..inner.len() - 3])
}
"F_Mask" => "Gerber X2, top solder mask (negative: flashes are openings)".into(),
"B_Mask" => "Gerber X2, bottom solder mask (negative: flashes are openings)".into(),
"F_Paste" => "Gerber X2, top paste stencil".into(),
"B_Paste" => "Gerber X2, bottom paste stencil".into(),
"F_Silkscreen" => "Gerber X2, top silkscreen (legend)".into(),
"B_Silkscreen" => "Gerber X2, bottom silkscreen (legend)".into(),
"Edge_Cuts" => "Gerber X2, board outline (profile)".into(),
"PTH" => "Excellon, plated holes (vias and component holes)".into(),
span if span.starts_with("Blind_") || span.starts_with("Buried_") => {
let mut parts = span.split('_');
let kind = parts.next().unwrap_or("").to_lowercase();
let (a, b) = (parts.next().unwrap_or("?"), parts.next().unwrap_or("?"));
format!("Excellon, {kind} vias drilled between copper layers {a} and {b}")
}
"NPTH" => "Excellon, non-plated holes".into(),
"pos" => "pick and place (centroid), JLCPCB CPL columns".into(),
"bom" => "bill of materials, JLCPCB BOM columns, grouped by value and footprint".into(),
_ => continue,
};
let _ = writeln!(out, "{:<32} {what}", file.name);
}
out.push_str(
"\nPick and place: Mid X / Mid Y are each footprint's origin. Rotation is degrees\n\
counter-clockwise seen from the top; a bottom part's is its mirrored footprint's,\n\
also seen from the top, with no assembler-specific correction.\n",
);
if !warnings.is_empty() {
out.push_str("\nWarnings:\n");
for warning in warnings {
let _ = writeln!(out, "- {warning}");
}
}
out
}
struct Origin {
left: i64,
bottom: i64,
}
impl Origin {
fn new(board: &Board) -> Self {
let (min, max) = board.outline_bounds();
Self {
left: i64::from(min.x),
bottom: i64::from(max.y),
}
}
fn point(&self, p: Point) -> (i64, i64) {
(
(i64::from(p.x) - self.left) * 1000,
(self.bottom - i64::from(p.y)) * 1000,
)
}
fn middle(&self, a: Point, b: Point) -> (i64, i64) {
(
(i64::from(a.x) + i64::from(b.x) - 2 * self.left) * 500,
(2 * self.bottom - i64::from(a.y) - i64::from(b.y)) * 500,
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Aperture {
Circle(i32),
Rect(i32, i32),
Obround(i32, i32),
}
#[derive(Default)]
struct Gerber {
apertures: Vec<(Aperture, Option<&'static str>)>,
current: Option<usize>,
body: String,
}
impl Gerber {
fn select(&mut self, aperture: Aperture, function: Option<&'static str>) {
let key = (aperture, function);
let index = match self.apertures.iter().position(|a| *a == key) {
Some(index) => index,
None => {
self.apertures.push(key);
self.apertures.len() - 1
}
};
if self.current != Some(index) {
self.current = Some(index);
let _ = writeln!(self.body, "D{}*", index + 10);
}
}
fn flash(&mut self, (x, y): (i64, i64)) {
let _ = writeln!(self.body, "X{x}Y{y}D03*");
}
fn stroke(&mut self, points: impl IntoIterator<Item = (i64, i64)>) {
for (i, (x, y)) in points.into_iter().enumerate() {
let operation = if i == 0 { "D02" } else { "D01" };
let _ = writeln!(self.body, "X{x}Y{y}{operation}*");
}
}
fn shape(&mut self, origin: &Origin, shape: Shape, grow: i32, function: Option<&'static str>) {
let (shape, grow) = (shape.grown(grow), 0);
match shape {
Shape::Polygon { points, radius } => {
if let Some(function) = function {
let _ = writeln!(self.body, "%TA.AperFunction,{function}*%");
}
self.body.push_str("G36*\n");
self.stroke(points.iter().chain(points.first()).map(|p| origin.point(*p)));
self.body.push_str("G37*\n");
if function.is_some() {
self.body.push_str("%TD*%\n");
}
if radius > 0 {
self.select(Aperture::Circle(2 * radius), function);
self.stroke(points.iter().chain(points.first()).map(|p| origin.point(*p)));
}
}
Shape::RoundRect { min, max, radius } => {
if let Some(function) = function {
let _ = writeln!(self.body, "%TA.AperFunction,{function}*%");
}
let (lo, hi) = (
Point::new(min.x + radius, min.y + radius),
Point::new(max.x - radius, max.y - radius),
);
let walk = [
(Point::new(max.x, hi.y), Point::new(hi.x, max.y), hi),
(Point::new(lo.x, max.y), Point::new(min.x, hi.y), Point::new(lo.x, hi.y)),
(Point::new(min.x, lo.y), Point::new(lo.x, min.y), lo),
(Point::new(hi.x, min.y), Point::new(max.x, lo.y), Point::new(hi.x, lo.y)),
];
let (x, y) = origin.point(Point::new(max.x, lo.y));
let _ = writeln!(self.body, "G36*\nX{x}Y{y}D02*");
for (line_end, arc_end, centre) in walk {
let (x, y) = origin.point(line_end);
let _ = writeln!(self.body, "X{x}Y{y}D01*");
let (cx, cy) = origin.point(centre);
let (ex, ey) = origin.point(arc_end);
let _ = writeln!(self.body, "G02*\nX{ex}Y{ey}I{}J{}D01*\nG01*", cx - x, cy - y);
}
self.body.push_str("G37*\n");
if function.is_some() {
self.body.push_str("%TD*%\n");
}
}
Shape::Rect { min, max } => {
self.select(
Aperture::Rect(max.x - min.x + 2 * grow, max.y - min.y + 2 * grow),
function,
);
self.flash(origin.middle(min, max));
}
Shape::Capsule { a, b, radius } => {
let diameter = 2 * (radius + grow);
if a == b {
self.select(Aperture::Circle(diameter), function);
self.flash(origin.point(a));
} else if a.x == b.x || a.y == b.y {
let (dx, dy) = (a.x.abs_diff(b.x) as i32, a.y.abs_diff(b.y) as i32);
self.select(Aperture::Obround(dx + diameter, dy + diameter), function);
self.flash(origin.middle(a, b));
} else {
self.select(Aperture::Circle(diameter), function);
self.stroke([origin.point(a), origin.point(b)]);
}
}
}
}
fn finish(self, file_function: &str, polarity: &str) -> String {
let mut out = String::new();
let _ = writeln!(
out,
"%TF.GenerationSoftware,eCAD,Schematic and PCB Studio,{}*%",
env!("CARGO_PKG_VERSION")
);
out.push_str("%TF.SameCoordinates,Original*%\n");
let _ = writeln!(out, "%TF.FileFunction,{file_function}*%");
let _ = writeln!(out, "%TF.FilePolarity,{polarity}*%");
out.push_str("%FSLAX46Y46*%\n%MOMM*%\n%LPD*%\nG01*\nG75*\n");
for (index, (aperture, function)) in self.apertures.iter().enumerate() {
if let Some(function) = function {
let _ = writeln!(out, "%TA.AperFunction,{function}*%");
}
let template = match *aperture {
Aperture::Circle(d) => format!("C,{}", millimetres(d)),
Aperture::Rect(w, h) => format!("R,{}X{}", millimetres(w), millimetres(h)),
Aperture::Obround(w, h) => format!("O,{}X{}", millimetres(w), millimetres(h)),
};
let _ = writeln!(out, "%ADD{}{template}*%", index + 10);
if function.is_some() {
out.push_str("%TD*%\n");
}
}
out.push_str(&self.body);
out.push_str("M02*\n");
out
}
}
fn millimetres(um: impl Into<i64>) -> String {
let um = um.into();
let sign = if um < 0 { "-" } else { "" };
format!("{sign}{}.{:03}", um.abs() / 1000, um.abs() % 1000)
}
fn pad_has_copper(placement: &Placement, index: usize) -> bool {
let pad = &placement.footprint.pads[index];
match pad.hole_size() {
Some(hole) if !pad.plated => pad.size.x > hole.x && pad.size.y > hole.y,
_ => true,
}
}
fn copper(board: &Board, origin: &Origin, layer: u8) -> Gerber {
let last = board.layer_count - 1;
let mut gerber = Gerber::default();
for zone in board.zones.iter().filter(|z| z.layer == layer && !z.fill.is_empty()) {
let _ = writeln!(gerber.body, "%TA.AperFunction,Conductor*%");
let _ = writeln!(gerber.body, "%TO.N,{}*%", zone.net.replace(['*', '%', ','], "_"));
for piece in &zone.fill {
let ring = crate::board::zones::fractured(piece);
gerber.body.push_str("G36*\n");
gerber.stroke(ring.iter().chain(ring.first()).map(|p| origin.point(*p)));
gerber.body.push_str("G37*\n");
}
gerber.body.push_str("%TD*%\n");
}
for placement in &board.placements {
for (index, pad) in placement.footprint.pads.iter().enumerate() {
let (from, to) = placement.pad_layers(pad, board.layer_count);
if !(from..=to).contains(&layer) || !pad_has_copper(placement, index) {
continue;
}
let function = match (pad.drill, pad.plated) {
(None, _) => "SMDPad,CuDef",
(Some(_), true) => "ComponentPad",
(Some(_), false) if layer == 0 || layer == last => "WasherPad",
(Some(_), false) => continue,
};
gerber.shape(origin, placement.pad_shape(pad), 0, Some(function));
}
}
for track in board.tracks.iter().filter(|t| t.layer == layer) {
gerber.select(Aperture::Circle(track.width), Some("Conductor"));
gerber.stroke(track.points.iter().map(|p| origin.point(*p)));
}
for via in board.all_vias().iter().filter(|v| {
let (from, to) = v.layers(board.layer_count);
(from..=to).contains(&layer)
}) {
gerber.shape(
origin,
Shape::circle(via.at, via.diameter / 2),
0,
Some("ViaPad"),
);
}
gerber
}
fn mask(board: &Board, origin: &Origin, top: bool) -> Gerber {
let mut gerber = Gerber::default();
if !board.rules.tent_vias {
let last = board.layer_count - 1;
for via in board.vias.iter().filter(|v| {
let (from, to) = v.layers(board.layer_count);
if top { from == 0 } else { to == last }
}) {
gerber.shape(origin, Shape::circle(via.at, via.diameter / 2), board.rules.mask_expansion, None);
}
}
for (via, tented, far_is_bottom) in board.pad_vias() {
if !tented && far_is_bottom != top {
gerber.shape(origin, Shape::circle(via.at, via.diameter / 2), board.rules.mask_expansion, None);
}
}
for placement in &board.placements {
for pad in &placement.footprint.pads {
if pad_mask_open(board, placement, pad, top) {
gerber.shape(
origin,
placement.pad_shape(pad),
pad.layers.mask_margin.unwrap_or(board.rules.mask_expansion),
None,
);
}
}
}
gerber
}
pub fn pad_mask_open(board: &Board, placement: &Placement, pad: &crate::board::Pad, top: bool) -> bool {
let side = if top { 0 } else { board.layer_count - 1 };
let (from, to) = placement.pad_layers(pad, board.layer_count);
let reaches = ((from..=to).contains(&side) && (top || side != 0)) || (!top && pad.drill.is_some());
reaches && !covered(pad, placement.front_faces(top))
}
fn covered(pad: &crate::board::Pad, front: bool) -> bool {
if front { pad.layers.cover_front } else { pad.layers.cover_back }
}
fn paste(board: &Board, origin: &Origin, top: bool) -> Gerber {
let last = board.layer_count - 1;
let mut gerber = Gerber::default();
for placement in &board.placements {
for pad in placement
.footprint
.pads
.iter()
.filter(|p| p.drill.is_none() && !p.layers.no_paste)
{
let (layer, _) = placement.pad_layers(pad, board.layer_count);
if (top && layer == 0) || (!top && last != 0 && layer == last) {
for shape in placement.pad_paste(pad) {
gerber.shape(origin, shape, 0, None);
}
}
}
}
gerber
}
fn legend(
document: &Document,
origin: &Origin,
top: bool,
unsupported: &mut BTreeSet<char>,
) -> Gerber {
let mut gerber = Gerber::default();
let layer = if top { GraphicLayer::FrontSilk } else { GraphicLayer::BackSilk };
for (width, filled, strokes) in document.board.drawing_on(layer) {
ink(&mut gerber, origin, width, filled, &strokes);
}
for placement in &document.board.placements {
for (width, filled, strokes) in placement.drawing_on(layer) {
ink(&mut gerber, origin, width, filled, &strokes);
}
if placement.bottom == top {
continue;
}
let Some(component) = document
.components
.iter()
.find(|c| c.id == placement.component)
else {
continue;
};
let (min, max) = placement.courtyard();
let anchor = Point::new(
((i64::from(min.x) + i64::from(max.x)) / 2) as i32,
min.y - SILK_WIDTH,
);
for stroke in crate::font::text_strokes(&component.reference, anchor, TEXT_HEIGHT, !top, unsupported) {
gerber.select(Aperture::Circle(SILK_WIDTH), None);
gerber.stroke(stroke.iter().map(|p| origin.point(*p)));
}
}
gerber
}
fn ink(gerber: &mut Gerber, origin: &Origin, width: i32, filled: bool, strokes: &[Vec<Point>]) {
for line in strokes {
gerber.select(Aperture::Circle(width.max(1)), None);
if filled && line.len() >= 4 {
gerber.body.push_str("G36*\n");
gerber.stroke(line.iter().map(|p| origin.point(*p)));
gerber.body.push_str("G37*\n");
}
if width > 0 {
gerber.stroke(line.iter().map(|p| origin.point(*p)));
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Hole {
Via,
Component,
}
type Drills = BTreeMap<(i32, Hole), Vec<((i64, i64), (i64, i64))>>;
fn drills(board: &Board, origin: &Origin) -> (Drills, Drills, BTreeMap<(u8, u8), Drills>) {
let (mut plated, mut unplated) = (Drills::new(), Drills::new());
let mut spans: BTreeMap<(u8, u8), Drills> = BTreeMap::new();
for via in &board.all_vias() {
let at = origin.point(via.at);
let target = match via.kind(board.layer_count) {
crate::board::ViaKind::Through => &mut plated,
_ => spans.entry(via.layers(board.layer_count)).or_default(),
};
target.entry((via.drill, Hole::Via)).or_default().push((at, at));
}
for placement in &board.placements {
for pad in &placement.footprint.pads {
if let (Some(Shape::Capsule { a, b, radius }), Some(hole)) = (placement.pad_hole(pad), pad.hole_size()) {
let target = if pad.plated { &mut plated } else { &mut unplated };
let tool = if a == b { hole.x.min(hole.y) } else { 2 * radius };
target
.entry((tool, Hole::Component))
.or_default()
.push((origin.point(a), origin.point(b)));
}
}
}
(plated, unplated, spans)
}
fn excellon(holes: &Drills, file_function: &str, plating: &str) -> String {
let mut out = String::from("M48\n");
let _ = writeln!(out, "; DRILL file {{eCAD {}}}", env!("CARGO_PKG_VERSION"));
out.push_str("; FORMAT={-:-/ absolute / metric / decimal}\n");
let _ = writeln!(
out,
"; #@! TF.GenerationSoftware,eCAD,Schematic and PCB Studio,{}",
env!("CARGO_PKG_VERSION")
);
let _ = writeln!(out, "; #@! TF.FileFunction,{file_function}");
out.push_str("FMAT,2\nMETRIC\n");
for (tool, (diameter, kind)) in holes.keys().enumerate() {
let kind = match kind {
Hole::Via => "ViaDrill",
Hole::Component => "ComponentDrill",
};
let _ = writeln!(out, "; #@! TA.AperFunction,{plating},{kind}");
let _ = writeln!(out, "T{}C{}", tool + 1, millimetres(*diameter));
}
out.push_str("%\nG05\n");
for (tool, hits) in holes.values().enumerate() {
let _ = writeln!(out, "T{}", tool + 1);
let at = |(x, y): (i64, i64)| {
format!("X{}Y{}", millimetres(x.div_euclid(1000)), millimetres(y.div_euclid(1000)))
};
for (a, b) in hits {
if a == b {
let _ = writeln!(out, "{}", at(*a));
} else {
let _ = writeln!(out, "{}G85{}", at(*a), at(*b));
}
}
}
out.push_str("M30\n");
out
}
pub fn crc32(bytes: &[u8]) -> u32 {
let mut crc = u32::MAX;
for &byte in bytes {
crc ^= u32::from(byte);
for _ in 0..8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
}
}
!crc
}
pub fn zip<'a>(entries: impl IntoIterator<Item = (&'a str, &'a [u8])>) -> Vec<u8> {
const DOS_DATE: u16 = (1 << 5) | 1;
let mut out = vec![];
let mut directory = vec![];
let mut count: u16 = 0;
let push16 = |v: &mut Vec<u8>, x: u16| v.extend_from_slice(&x.to_le_bytes());
let push32 = |v: &mut Vec<u8>, x: u32| v.extend_from_slice(&x.to_le_bytes());
for (name, data) in entries {
let offset = out.len() as u32;
let (crc, size, name_len) = (crc32(data), data.len() as u32, name.len() as u16);
for (record, signature) in [(&mut out, 0x0403_4b50), (&mut directory, 0x0201_4b50)] {
push32(record, signature);
if signature == 0x0201_4b50 {
push16(record, 20); }
push16(record, 10); push16(record, 0); push16(record, 0); push16(record, 0); push16(record, DOS_DATE);
push32(record, crc);
push32(record, size);
push32(record, size);
push16(record, name_len);
push16(record, 0); if signature == 0x0201_4b50 {
push16(record, 0); push16(record, 0); push16(record, 0); push32(record, 0); push32(record, offset);
}
record.extend_from_slice(name.as_bytes());
}
out.extend_from_slice(data);
count += 1;
}
let (start, length) = (out.len() as u32, directory.len() as u32);
out.extend_from_slice(&directory);
push32(&mut out, 0x0605_4b50);
push16(&mut out, 0);
push16(&mut out, 0);
push16(&mut out, count);
push16(&mut out, count);
push32(&mut out, length);
push32(&mut out, start);
push16(&mut out, 0);
out
}
pub fn zip_entries(archive: &[u8]) -> Vec<(String, usize)> {
let u16_at = |i: usize| -> Option<usize> {
Some(u16::from_le_bytes(archive.get(i..i + 2)?.try_into().ok()?) as usize)
};
let u32_at = |i: usize| -> Option<usize> {
Some(u32::from_le_bytes(archive.get(i..i + 4)?.try_into().ok()?) as usize)
};
let read = || -> Option<Vec<(String, usize)>> {
let end = archive.len().checked_sub(22)?;
if u32_at(end)? != 0x0605_4b50 {
return None;
}
let mut entry = u32_at(end + 16)?;
let mut out = vec![];
for _ in 0..u16_at(end + 10)? {
if u32_at(entry)? != 0x0201_4b50 {
return None;
}
let name_len = u16_at(entry + 28)?;
let name = archive.get(entry + 46..entry + 46 + name_len)?;
out.push((String::from_utf8_lossy(name).into_owned(), u32_at(entry + 24)?));
entry += 46 + name_len + u16_at(entry + 30)? + u16_at(entry + 32)?;
}
Some(out)
};
read().unwrap_or_default()
}