diff options
| author | Louis <louis@dnge.de> | 2026-11-11 10:08:41 +0100 |
|---|---|---|
| committer | Louis <louis@dnge.de> | 2026-11-11 10:08:41 +0100 |
| commit | 2e433fcd0d1afadd8ab786dd30d7d4546bdee43d (patch) | |
| tree | f2a5603703d56b08c1eaa672eaf529ec4b2cc3fa /tools/silk_refs.py | |
| download | hw-toolchain-2e433fcd0d1afadd8ab786dd30d7d4546bdee43d.tar.gz | |
hw-toolchain: placer, routers and KiCad helpers for agent-driven hardware work
Rust placer (simulated annealing) and negotiated-congestion router for
2-layer KiCad boards, pnr.sh to place, route, DRC-check and install
candidates, Python KiCad helpers, repo conventions (AGENTS.md) and the
tool documentation under knowledge/. Konnect (KiCad MCP, AGPL) as a
submodule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/silk_refs.py')
| -rw-r--r-- | tools/silk_refs.py | 133 |
1 files changed, 133 insertions, 0 deletions
diff --git a/tools/silk_refs.py b/tools/silk_refs.py new file mode 100644 index 0000000..51c4f65 --- /dev/null +++ b/tools/silk_refs.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Place footprint reference designators where they do not collide with copper or each other. + +Run with KiCad's bundled Python after routing: + + $KPY tools/silk_refs.py board.kicad_pcb [out.kicad_pcb] [--size 0.8] [--skip P1,P2] + +For each visible reference (largest parts first) it tries positions around the part's +courtyard: above, below, left, right (horizontal text), then left/right reading vertically, +then the corners, then the same ring 0.6 mm further out. Other parts' silk outlines count as obstacles. +(Smaller text is not tried: it runs into the board's minimum text height.) The first position whose text box +(plus 0.15 mm) clears every pad and via (tracks are under mask), keeps 0.5 mm from the board edge and clears all +references already placed wins. Parts with no free spot keep their reference on F.Fab only +(hidden on silk) and are listed, so nothing ends up over a pad. Pours are ignored: silk on +a pour is fine. + +pcbnew.SaveBoard rewrites the .kicad_pro; it is copied before and restored after. +""" +import argparse +import os + +import pcbnew + +MM = 1e6 + + +def box(b, m=0.0): + return (b.GetLeft() / MM - m, b.GetTop() / MM - m, b.GetRight() / MM + m, b.GetBottom() / MM + m) + + +def inside(outline, b, m): + """Box b grown by m lies inside the board outline: its perimeter sampled every 0.25 mm, so a + box cannot straddle a notch between two connector tabs (the outline's bounding box would let + it hang past the real edge there).""" + x0, y0, x1, y1 = b[0] - m, b[1] - m, b[2] + m, b[3] + m + nx, ny = max(1, int((x1 - x0) / 0.25)), max(1, int((y1 - y0) / 0.25)) + pts = [(x0 + (x1 - x0) * i / nx, y) for i in range(nx + 1) for y in (y0, y1)] + pts += [(x, y0 + (y1 - y0) * j / ny) for j in range(ny + 1) for x in (x0, x1)] + return all(outline.Contains(pcbnew.VECTOR2I_MM(x, y)) for x, y in pts) + + +def hit(a, b): + return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("board") + ap.add_argument("out", nargs="?") + ap.add_argument("--size", type=float, default=0.8) + ap.add_argument("--skip", default="", help="references to leave alone") + a = ap.parse_args() + out = a.out or a.board + b = pcbnew.LoadBoard(a.board) + skip = set(r for r in a.skip.split(",") if r) + outline = pcbnew.SHAPE_POLY_SET() + b.GetBoardPolygonOutlines(outline, False) + + copper = [] + for f in b.GetFootprints(): + for p in f.Pads(): + copper.append(box(p.GetBoundingBox(), 0.15)) + for t in b.GetTracks(): # tracks are under solder mask; silk may cross them + if t.GetClass() == "PCB_VIA": + copper.append(box(t.GetBoundingBox(), 0.1)) + silk = [] # footprint silk graphics (outlines, pin-1 marks) of other parts + for f in b.GetFootprints(): + for g in f.GraphicalItems(): + if g.GetLayer() == pcbnew.F_SilkS and g.GetClass() != "PCB_TEXT": + silk.append((f.GetReference(), box(g.GetBoundingBox(), 0.1))) + bodies = {} + for f in b.GetFootprints(): + cy = f.GetCourtyard(pcbnew.F_CrtYd) + if cy.OutlineCount(): + bodies[f.GetReference()] = box(cy.BBox()) + + placed, missing = [], [] + fps = sorted([f for f in b.GetFootprints() if f.Reference().IsVisible() and f.GetReference() not in skip + and f.GetLayer() == pcbnew.F_Cu], + key=lambda f: (-(f.GetBoundingBox().GetWidth() * f.GetBoundingBox().GetHeight()), f.GetReference())) + todo = [(f, a.size) for f in fps] + while todo: + f, size = todo.pop(0) + t = f.Reference() + t.SetTextSize(pcbnew.VECTOR2I_MM(size, size)) + t.SetTextThickness(pcbnew.FromMM(size * 0.15)) + t.SetLayer(pcbnew.F_SilkS) + bb = bodies.get(f.GetReference(), box(f.GetBoundingBox())) + cx, cy = (bb[0] + bb[2]) / 2, (bb[1] + bb[3]) / 2 + found = None + for ring in (0.0, 0.6): + x0, y0, x1, y1 = bb[0] - ring, bb[1] - ring, bb[2] + ring, bb[3] + ring + h = size + cands = [(cx, y0 - h * 0.7, 0), (cx, y1 + h * 0.7, 0), (x0 - h, cy, 0), (x1 + h, cy, 0), + (x0 - h * 0.7, cy, 90), (x1 + h * 0.7, cy, 90), + (x0, y0 - h * 0.7, 0), (x1, y0 - h * 0.7, 0), (x0, y1 + h * 0.7, 0), (x1, y1 + h * 0.7, 0)] + for (x, y, rot) in cands: + t.SetTextAngleDegrees(rot) + t.SetPosition(pcbnew.VECTOR2I_MM(x, y)) + if rot == 0 and x < cx - 0.01: + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_RIGHT) + elif rot == 0 and x > cx + 0.01 and abs(y - cy) < 0.01: + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_LEFT) + else: + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_CENTER) + tb = box(t.GetBoundingBox(), 0.15) + if not inside(outline, tb, 0.5): + continue + if any(hit(tb, c) for c in copper) or any(hit(tb, p) for p in placed) or \ + any(r != f.GetReference() and hit(tb, g) for r, g in silk): + continue + found = tb + break + if found: + break + if found: + placed.append(found) + else: + t.SetPosition(pcbnew.VECTOR2I_MM(cx, cy)) + t.SetTextAngleDegrees(0) + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_CENTER) + t.SetLayer(pcbnew.F_Fab) + missing.append(f.GetReference()) + pro = out[:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro).read() if os.path.exists(pro) else None + pcbnew.SaveBoard(out, b) + if keep is not None: + open(pro, "w").write(keep) + print("placed %d references; on F.Fab only (no free spot): %s" % (len(placed), ", ".join(missing) or "none")) + + +if __name__ == "__main__": + main() |
