← Commit history
silkscreen gerber-audit: name the parts on Gerbers plotted from the drill/place origin, and keep every spot in a record file
The board is put on the Gerbers by outline box size and shift when the boxes are not on each other
(Gerbers plotted from the drill/place file origin named no part). The record lists every spot and is
written to --out, else <run>/silkscreen/gerber-audit.json; the reply names the file.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 files changed
+90−16
crates/adom-aiflow/src/gerber_silk.rs+7−3@@ -280,6 +280,9 @@ fn blobs(r: &Raster, mark: &[bool]) -> Vec<(Pt, f64)> { /// One side's audit. `outline` is the board outline (mm, the Gerbers' frame), `near` names the part /// nearest a point. Returns (record, finding lines).+/// N36: the record lists every spot a side has (up to this many), so the "N more" in the reply can be read there.+pub const RECORD_MAX: usize = 5000;+ pub fn audit_side(side: &str, silk: &str, mask: Option<&str>, outline: &[Pt], edge_mm: f64, min_line_mm: f64, near: &dyn Fn(Pt) -> String) -> (Value, Vec<String>) { let s = parse(silk); let bb = if outline.len() >= 3 {@@ -298,7 +301,7 @@ pub fn audit_side(side: &str, silk: &str, mask: Option<&str>, outline: &[Pt], ed mr.draw(&mi); let both: Vec<bool> = sr.bits.iter().zip(&mr.bits).map(|(a, b)| *a && *b).collect(); let bl: Vec<(Pt, f64)> = blobs(&sr, &both).into_iter().filter(|b| b.1 >= 0.005).collect();- rec["onExposedCopper"] = json!(bl.iter().take(30).map(|(c, a)| json!({"at": [r3(c.0), r3(c.1)], "mm2": r3(*a), "near": near(*c)})).collect::<Vec<_>>());+ rec["onExposedCopper"] = json!(bl.iter().take(RECORD_MAX).map(|(c, a)| json!({"at": [r3(c.0), r3(c.1)], "mm2": r3(*a), "near": near(*c)})).collect::<Vec<_>>()); for (c, a) in bl.iter().take(12) { lines.push(format!("{side} silkscreen on exposed copper at ({:.2}, {:.2}), {:.3} mm2, near {}: the fab clips it there", c.0, c.1, a, near(*c))); } if bl.len() > 12 { lines.push(format!("{side}: {} more spots of silkscreen on exposed copper (the record lists them)", bl.len() - 12)); } } else {@@ -316,14 +319,15 @@ pub fn audit_side(side: &str, silk: &str, mask: Option<&str>, outline: &[Pt], ed if !inside(outline, p) || near_edge { off[k] = true; } } } let bl: Vec<(Pt, f64)> = blobs(&sr, &off).into_iter().filter(|b| b.1 >= 0.005).collect();- rec["nearOrOffEdge"] = json!(bl.iter().take(30).map(|(c, a)| json!({"at": [r3(c.0), r3(c.1)], "mm2": r3(*a), "near": near(*c)})).collect::<Vec<_>>());+ rec["nearOrOffEdge"] = json!(bl.iter().take(RECORD_MAX).map(|(c, a)| json!({"at": [r3(c.0), r3(c.1)], "mm2": r3(*a), "near": near(*c)})).collect::<Vec<_>>()); for (c, a) in bl.iter().take(8) { lines.push(format!("{side} silkscreen off the board or within {edge_mm} mm of the edge at ({:.2}, {:.2}), {:.3} mm2, near {}", c.0, c.1, a, near(*c))); }+ if bl.len() > 8 { lines.push(format!("{side}: {} more spots off the board or near the edge (the record lists them)", bl.len() - 8)); } } // thin printed features: measured on what prints (strokes that merge into a wide glyph are not thin) let thin = thin_parts(&sr, min_line_mm); let bl: Vec<(Pt, f64)> = blobs(&sr, &thin).into_iter().filter(|b| b.1 >= 0.02).collect(); let (n, len) = s.thin(min_line_mm);- rec["thinFeatures"] = json!(bl.iter().take(30).map(|(c, a)| json!({"at": [r3(c.0), r3(c.1)], "mm2": r3(*a), "near": near(*c)})).collect::<Vec<_>>());+ rec["thinFeatures"] = json!(bl.iter().take(RECORD_MAX).map(|(c, a)| json!({"at": [r3(c.0), r3(c.1)], "mm2": r3(*a), "near": near(*c)})).collect::<Vec<_>>()); rec["strokesUnderMinimum"] = json!({"count": n, "lengthMm": (len * 10.0).round() / 10.0, "thinnestMm": s.min_line}); for (c, a) in bl.iter().take(10) { lines.push(format!("{side} silkscreen narrower than {min_line_mm:.2} mm at ({:.2}, {:.2}), {:.3} mm2, near {}: it may not print", c.0, c.1, a, near(*c))); } if bl.len() > 10 { lines.push(format!("{side}: {} more thin spots (the record lists them)", bl.len() - 10)); }
crates/adom-aiflow/src/main.rs+83−13@@ -128,7 +128,7 @@ enum Cmd { #[arg(long)] board: Option<String> }, /// `silkscreen fab-check|fab-tidy [--board B] [--out O] [--size MM]`: the Fab layer standard (issue #163). fab-check reports Fab texts off their parts, values shown and mixed reference sizes; fab-tidy writes a copy of the board with each reference centred on its body, upright along its long axis, one size (shrunk only to fit, floor 0.3 mm), values hidden. Only Fab texts change. Silkscreen { #[arg(value_parser = ["fab-check", "fab-tidy", "gerber-audit"])] action: String, /// default: the run's current board- #[arg(long)] board: Option<String>, /// fab-tidy: where to write the tidied board (default: <board>-fab.kicad_pcb beside it)+ #[arg(long)] board: Option<String>, /// fab-tidy: where to write the tidied board (default: <board>-fab.kicad_pcb beside it); gerber-audit: where to write its record, every spot it found (default: <run>/silkscreen/gerber-audit.json) #[arg(long)] out: Option<String>, /// the board's Fab reference size in mm (default: the most common one on the board) #[arg(long)] size: Option<f64>, /// gerber-audit (issue #134): the folder with the fab's Gerbers, any EDA (default: the run's export, <run>/manufacturing/gerbers) #[arg(long)] dir: Option<String>, /// gerber-audit: the edge clearance in mm@@ -3450,17 +3450,31 @@ fn silk_gerber_audit(files: &[(String, String)], board: Option<&Board>, edge: f6 } } let obox = |pts: &[(f64, f64)]| pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));- let flip: Option<bool> = board.filter(|b| b.outline.len() >= 3 && outline.len() >= 3).and_then(|b| {+ // the board in the Gerbers' frame: Y flipped or not, and shifted when the Gerbers were plotted from the+ // drill/place file origin (N36: an offset frame named no part at all). Gerbers in the board's own frame+ // match as before (the outline boxes on each other, no shift). Otherwise the boxes must have the same+ // size and the shift puts them on each other; of the two, the one whose outline points land on the+ // Gerbers' outline, and Y flipped on a tie (a Gerber's Y points up, a KiCad board's down).+ let frame: Option<(bool, f64, f64)> = board.filter(|b| b.outline.len() >= 3 && outline.len() >= 3).and_then(|b| { let g = obox(&outline);- [false, true].into_iter().find(|f| {- let pts: Vec<(f64, f64)> = b.outline.iter().map(|p| (p.0, if *f { -p.1 } else { p.1 })).collect();+ let flipped = |f: bool| -> Vec<(f64, f64)> { b.outline.iter().map(|p| (p.0, if f { -p.1 } else { p.1 })).collect() };+ if let Some(f) = [false, true].into_iter().find(|f| { let k = obox(&flipped(*f)); (k.0 - g.0).abs() < 0.5 && (k.1 - g.1).abs() < 0.5 && (k.2 - g.2).abs() < 0.5 && (k.3 - g.3).abs() < 0.5 }) {+ return Some((f, 0.0, 0.0));+ }+ let mut best: Option<(f64, (bool, f64, f64))> = None;+ for f in [true, false] {+ let pts = flipped(f); let k = obox(&pts);- (k.0 - g.0).abs() < 0.5 && (k.1 - g.1).abs() < 0.5 && (k.2 - g.2).abs() < 0.5 && (k.3 - g.3).abs() < 0.5- })+ if ((k.2 - k.0) - (g.2 - g.0)).abs() >= 0.5 || ((k.3 - k.1) - (g.3 - g.1)).abs() >= 0.5 { continue; }+ let (dx, dy) = (g.0 - k.0, g.1 - k.1);+ let miss = outline.iter().map(|q| pts.iter().map(|p| ((p.0 + dx - q.0).powi(2) + (p.1 + dy - q.1).powi(2)).sqrt()).fold(f64::MAX, f64::min)).sum::<f64>() / outline.len() as f64;+ if best.as_ref().is_none_or(|b| miss < b.0 - 1e-6) { best = Some((miss, (f, dx, dy))); }+ }+ best.map(|b| b.1) }); let near = |p: (f64, f64)| -> String {- let (Some(b), Some(f)) = (board, flip) else { return "(no board to name the part)".into() };- b.pads.iter().map(|q| (q, ((q.x - p.0).powi(2) + ((if f { -q.y } else { q.y }) - p.1).powi(2)).sqrt())).min_by(|a, c| a.1.total_cmp(&c.1)).map(|(q, d)| format!("{} pad {} ({:.1} mm)", q.reference, q.name, d)).unwrap_or_default()+ let (Some(b), Some((f, dx, dy))) = (board, frame) else { return "(no board to name the part)".into() };+ b.pads.iter().map(|q| (q, ((q.x + dx - p.0).powi(2) + ((if f { -q.y } else { q.y }) + dy - p.1).powi(2)).sqrt())).min_by(|a, c| a.1.total_cmp(&c.1)).map(|(q, d)| format!("{} pad {} ({:.1} mm)", q.reference, q.name, d)).unwrap_or_default() }; let mut sides = Vec::new(); let mut lines = Vec::new();@@ -3474,7 +3488,55 @@ fn silk_gerber_audit(files: &[(String, String)], board: Option<&Board>, edge: f6 lines.extend(l); } if outline.len() < 3 { lines.push("no board outline (no outline Gerber: Profile, Edge_Cuts, GKO or GM1; and no --board that fits), so the edge was not checked".into()); }- (json!({"sides": sides, "outlinePoints": outline.len(), "outlineFrom": if outline.len() >= 3 { outline_from } else { "none" }, "edgeMm": edge, "minLineMm": min_line, "findings": lines, "blocking": false}), lines)+ if board.is_some() && frame.is_none() && outline.len() >= 3 { lines.push("the board's outline is not the size of the Gerbers' outline, so no part is named (is --board the board these Gerbers came from?)".into()); }+ let frame_v = frame.map(|(f, dx, dy)| json!({"yFlipped": f, "shiftMm": [(dx * 1000.0).round() / 1000.0, (dy * 1000.0).round() / 1000.0]}));+ (json!({"sides": sides, "outlinePoints": outline.len(), "outlineFrom": if outline.len() >= 3 { outline_from } else { "none" }, "boardFrame": frame_v, "edgeMm": edge, "minLineMm": min_line, "findings": lines, "blocking": false}), lines)+}++#[cfg(test)]+mod gerber_audit_frame_tests {+ const HEAD: &str = "%FSLAX46Y46*%\n%MOMM*%\n%LPD*%\n%ADD10C,0.150000*%\n%ADD12C,0.080000*%\n";+ /// A 20 x 10 mm board drawn at (100, 100) in KiCad, R1's pad 1 at (105, 105).+ fn board() -> aiflow_board::Board {+ aiflow_board::Board::from_text("t.kicad_pcb", r#"(kicad_pcb (version 20240108) (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (44 "Edge.Cuts" user))+ (net 0 "") (net 1 "A")+ (setup (aux_axis_origin 100 110))+ (gr_rect (start 100 100) (end 120 110) (layer "Edge.Cuts"))+ (footprint "R" (layer "F.Cu") (at 105 105) (property "Reference" "R1") (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu") (net 1 "A"))))"#.to_string()).unwrap()+ }+ /// The Gerbers KiCad plots from the drill/place file origin (100, 110): x - 100, 110 - y.+ fn gerbers(thin: usize) -> Vec<(String, String)> {+ let outline = format!("{HEAD}D10*\nX0Y0D02*\nX20000000Y0D01*\nX20000000Y10000000D01*\nX0Y10000000D01*\nX0Y0D01*\nM02*\n");+ let mut silk = format!("{HEAD}D12*\n");+ for k in 0..thin { let x = 5600000 + (k as i64 % 7) * 1800000; let y = 5000000 + (k as i64 / 7) * 600000 - 2000000; silk.push_str(&format!("X{x}Y{y}D02*\nX{}Y{y}D01*\n", x + 1000000)); }+ silk.push_str("M02*\n");+ vec![("b-Edge_Cuts.gbr".to_string(), outline), ("b-F_Silkscreen.gbr".to_string(), silk)]+ }++ /// N36: Gerbers plotted from the drill/place origin still name the part nearest each finding+ #[test]+ fn an_offset_gerber_frame_still_names_the_parts() {+ let (v, lines) = super::silk_gerber_audit(&gerbers(1), Some(&board()), 0.3, 0.15);+ let all = lines.join("\n");+ assert!(all.contains("narrower than 0.15 mm") && all.contains("near R1 pad 1"), "{all}");+ assert!(!all.contains("no board to name the part"), "{all}");+ assert_eq!(v["boardFrame"]["yFlipped"], true, "{v}");+ assert_eq!(v["boardFrame"]["shiftMm"], serde_json::json!([-100.0, 110.0]), "{v}");+ // a board of another size names nothing, and says why+ let other = aiflow_board::Board::from_text("o.kicad_pcb", r#"(kicad_pcb (version 20240108) (layers (0 "F.Cu" signal) (44 "Edge.Cuts" user)) (gr_rect (start 0 0) (end 30 30) (layer "Edge.Cuts")))"#.to_string()).unwrap();+ let (_, lines) = super::silk_gerber_audit(&gerbers(1), Some(&other), 0.3, 0.15);+ assert!(lines.iter().any(|l| l.contains("not the size of the Gerbers' outline")), "{lines:?}");+ }++ /// N36: the record holds every spot the reply counts ("N more ... (the record lists them)")+ #[test]+ fn the_record_lists_every_spot() {+ let (v, lines) = super::silk_gerber_audit(&gerbers(35), Some(&board()), 0.3, 0.15);+ let top = v["sides"].as_array().unwrap().iter().find(|s| s["side"] == "top").cloned().unwrap_or_else(|| v["sides"][0].clone());+ let n = top["thinFeatures"].as_array().map(Vec::len).unwrap_or(0);+ assert_eq!(n, 35, "{lines:?}");+ assert!(lines.iter().any(|l| l.contains("25 more thin spots (the record lists them)")), "{lines:?}");+ } } /// Issue #193: the BOM references of an MPN, from the parts record.@@ -3918,17 +3980,25 @@ fn main() { ok(&String::from_utf8_lossy(&result.stdout), &["Geometry audit only; native CAD review remains required. `--record` records the silkscreen step proof from a passing audit that covers the board.".into(), rect]); } Cmd::Silkscreen { action, board, out, size, dir: gdir, edge, min_line } if action == "gerber-audit" => {- let _ = (out, size);+ let _ = size; let r = Run::open(&run_dir(&cli)); let gd = gdir.clone().map(PathBuf::from).or_else(|| r.as_ref().map(|r| r.dir.join("manufacturing").join("gerbers"))).unwrap_or_else(|| err("gerber-audit needs --dir <the Gerber folder>", &[])); let files: Vec<(String, String)> = std::fs::read_dir(&gd).map(|d| d.filter_map(|e| e.ok()).filter(|e| e.path().is_file()).filter_map(|e| Some((e.file_name().to_string_lossy().to_string(), std::fs::read_to_string(e.path()).ok()?))).collect()).unwrap_or_else(|e| err(&format!("{}: {e}", gd.display()), &["Export first (`adom-aiflow export`), or pass --dir <the folder with the fab's Gerbers> (Fusion's CAM output, an Altium Gerber set, any EDA).".into()])); let bp = board.clone().or_else(|| r.as_ref().map(|r| r.current_board())); let b = bp.as_deref().and_then(|p| Board::load(p).ok()); let (v, lines) = silk_gerber_audit(&files, b.as_ref(), *edge, *min_line);- if let Some(mut r) = r { r.outcome("silk-gerber-audit", v.clone()); let _ = r.save(); } if v["sides"].as_array().is_none_or(|a| a.is_empty()) { err(&format!("no silkscreen Gerber in {}", gd.display()), &["The audit reads the Legend (silkscreen) Gerber: KiCad's F_Silkscreen, a .GTO/.GBO, or any file whose X2 FileFunction is Legend.".into()]); }- if lines.is_empty() { ok(&format!("the printed silkscreen in {} has no finding: nothing on exposed copper, nothing off the board or within {edge} mm of the edge, no line under {min_line} mm", gd.display()), &[]); return; }- findings(&format!("the printed silkscreen (from the Gerbers in {}, the real glyph outlines):\n {}", gd.display(), lines.join("\n ")), &["Move or shrink the text named, in the board, and export again; every spot has its coordinates in the Gerbers' frame and the part it is nearest. The fab clips silkscreen on exposed copper, so text there loses its pieces.".into()]);+ // N36: the record the reply points to is a file: --out, else the run's silkscreen folder+ let rec_path: Option<PathBuf> = out.clone().map(PathBuf::from).or_else(|| r.as_ref().map(|r| r.dir.join("silkscreen").join("gerber-audit.json")));+ if let Some(rp) = &rec_path {+ if let Some(parent) = rp.parent().filter(|p| !p.as_os_str().is_empty()) { let _ = std::fs::create_dir_all(parent); }+ std::fs::write(rp, serde_json::to_string_pretty(&v).unwrap()).unwrap_or_else(|e| err(&format!("{}: {e}", rp.display()), &[]));+ }+ if let Some(mut r) = r { r.outcome("silk-gerber-audit", v.clone()); let _ = r.save(); }+ let rec_said = rec_path.as_ref().map(|p| format!("; the record: {}", p.display())).unwrap_or_else(|| "; pass --out <file.json> (or --run) to keep the record with every spot".into());+ let lines: Vec<String> = lines.into_iter().map(|l| match &rec_path { Some(p) => l.replace("(the record lists them)", &format!("(listed in {})", p.display())), None => l.replace(" (the record lists them)", "") }).collect();+ if lines.is_empty() { ok(&format!("the printed silkscreen in {} has no finding: nothing on exposed copper, nothing off the board or within {edge} mm of the edge, no line under {min_line} mm{rec_said}", gd.display()), &[]); return; }+ findings(&format!("the printed silkscreen (from the Gerbers in {}, the real glyph outlines{rec_said}):\n {}", gd.display(), lines.join("\n ")), &["Move or shrink the text named, in the board, and export again; every spot has its coordinates in the Gerbers' frame and the part it is nearest. The fab clips silkscreen on exposed copper, so text there loses its pieces.".into()]); } Cmd::Silkscreen { action, board, out, size, .. } => { // issue #163: findings and an offline tidy the AI may run; never a gate