aboutsummaryrefslogtreecommitdiff
path: root/tools/silk_refs.py
blob: 51c4f6504fbbc707a5b15bde1601c57662c17edf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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()