aboutsummaryrefslogtreecommitdiff
path: root/tools/placer/apply.py
blob: db080dc4f9a969f99cea31d34c13894fda190449 (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
"""Write a placer result into a copy of a board: footprint positions and turns, no copper.

Run with KiCad's bundled Python (pcbnew), with the source board closed or saved:

    $KPY tools/placer/apply.py board.kicad_pcb placement.json out.kicad_pcb

placement.json maps ref -> [x, y, rotation in degrees], at the top level or under
"placement" (placer's rank_NN.json). Tracks and vias are deleted (the old routing belongs to
the old placement); zones are kept and refilled by the router's write step. The board's
.kicad_pro is copied next to the output, because pcbnew.SaveBoard would write default net
settings into it (knowledge/tooling/kicad.md, pcbnew quirks).
"""
import json
import os
import shutil
import sys

import pcbnew


def main(src, placement, out):
    d = json.load(open(placement))
    d = d.get("placement", d)
    b = pcbnew.LoadBoard(src)
    seen = set()
    for f in b.GetFootprints():
        r = f.GetReference()
        if r in d:
            x, y, rot = d[r]
            f.SetPosition(pcbnew.VECTOR2I(pcbnew.FromMM(x), pcbnew.FromMM(y)))
            f.SetOrientationDegrees(rot)
            seen.add(r)
    missing = set(d) - seen
    if missing:
        sys.exit("not on the board: %s" % ", ".join(sorted(missing)))
    for t in list(b.GetTracks()):
        b.Delete(t)   # not Remove: it breaks the board lists (knowledge/tooling/kicad.md)
    pro_src = src[:-len(".kicad_pcb")] + ".kicad_pro"
    pro_out = out[:-len(".kicad_pcb")] + ".kicad_pro"
    keep = open(pro_src).read()
    pcbnew.SaveBoard(out, b)
    open(pro_out, "w").write(keep)
    dru = src[:-len(".kicad_pcb")] + ".kicad_dru"
    if os.path.exists(dru):
        shutil.copy(dru, out[:-len(".kicad_pcb")] + ".kicad_dru")
    print("placed %d footprints -> %s" % (len(seen), out))


if __name__ == "__main__":
    main(*sys.argv[1:4])