"""Export a board's placement problem for the Rust placer (tools/placer) as JSON. Run with KiCad's bundled Python (pcbnew); the board can be open in KiCad (it reads the saved file): kicad-cli sch export netlist -o board.net board.kicad_sch $KPY tools/placer/export.py board.kicad_pcb problem.json [board.net] The netlist is optional and gives the pin types (power_in etc.), which a board made by script does not carry. Geometry is in the footprint's own frame (orientation 0, origin at the anchor), so the placer can turn parts by 90 degree steps. Output keys: bounds [x0, y0, x1, y1] of the board outline (mm, without the Edge.Cuts line width) parts ref, value, fpid, x, y, rot (deg), locked, board_only, fields (Place_* symbol fields), court (F.CrtYd polygons, local), pads (num, net, pintype, x, y, w, h local, tht) netclass net -> class name; classes: class name -> track width and clearance (mm) fill nets with a copper zone (they reach their pads through a pour and a via) keepouts rule areas (board and footprint) that forbid footprints, pads or tracks: poly in board coordinates, footprints / pads / tracks true where forbidden. Plus, for an outline that is not its bbox (e.g. a connector tab), the bbox outside the outline grown by the copper-to-edge clearance as a pad keep-out: the placer checks pads against the bbox only, so a pad beside a tab could reach the real edge (seen: a cap 0.4 mm from the edge next to a jack tab) """ import json import re import sys import pcbnew MM = 1e6 def polys(ps): out = [] for k in range(ps.OutlineCount()): ol = ps.Outline(k) out.append([[round(ol.CPoint(i).x / MM, 4), round(ol.CPoint(i).y / MM, 4)] for i in range(ol.PointCount())]) return out def pintypes(netlist): """(ref, pin) -> pintype from a KiCad netlist.""" return {(r, p): t for r, p, t in re.findall( r'\(node\s+\(ref "([^"]*)"\)\s+\(pin "([^"]*)"\)(?:\s+\(pinfunction "[^"]*"\))?\s+\(pintype "([^"]*)"\)', open(netlist).read())} def main(src, out, netlist=None): types = pintypes(netlist) if netlist else {} b = pcbnew.LoadBoard(src) outline = pcbnew.SHAPE_POLY_SET() b.GetBoardPolygonOutlines(outline, True) bb = outline.BBox() d = dict(bounds=[bb.GetLeft() / MM, bb.GetTop() / MM, bb.GetRight() / MM, bb.GetBottom() / MM], parts=[], netclass={}, classes={}, fill=[], keepouts=[]) # the bbox outside the outline, grown by the copper-to-edge clearance: pads stay out outside = pcbnew.SHAPE_POLY_SET() outside.NewOutline() for x, y in ((bb.GetLeft(), bb.GetTop()), (bb.GetRight(), bb.GetTop()), (bb.GetRight(), bb.GetBottom()), (bb.GetLeft(), bb.GetBottom())): outside.Append(x, y) outside.BooleanSubtract(outline) if outside.OutlineCount(): outside.Inflate(b.GetDesignSettings().m_CopperEdgeClearance, pcbnew.CORNER_STRATEGY_CHAMFER_ALL_CORNERS, pcbnew.FromMM(0.005)) for poly in polys(outside): d["keepouts"].append(dict(poly=poly, footprints=False, pads=True, tracks=False)) # rule areas before the footprints are moved to their local frame below zones = list(b.Zones()) + [z for f in b.GetFootprints() for z in f.Zones()] for z in zones: if z.GetIsRuleArea() and (z.GetDoNotAllowFootprints() or z.GetDoNotAllowPads() or z.GetDoNotAllowTracks()): for poly in polys(z.Outline()): d["keepouts"].append(dict(poly=poly, footprints=z.GetDoNotAllowFootprints(), pads=z.GetDoNotAllowPads(), tracks=z.GetDoNotAllowTracks())) for f in sorted(b.GetFootprints(), key=lambda f: f.GetReference()): part = dict(ref=f.GetReference(), value=f.GetValue(), fpid=f.GetFPIDAsString(), x=f.GetPosition().x / MM, y=f.GetPosition().y / MM, rot=f.GetOrientationDegrees(), locked=f.IsLocked(), board_only=bool(f.GetAttributes() & pcbnew.FP_BOARD_ONLY), back=f.GetLayer() == pcbnew.B_Cu, fields={fl.GetName(): fl.GetText() for fl in f.GetFields() if fl.GetName().startswith("Place_")}) # local frame: the loaded board is never saved, so turn and move the footprint home f.SetOrientationDegrees(0) f.SetPosition(pcbnew.VECTOR2I(0, 0)) f.BuildCourtyardCaches() part["court"] = polys(f.GetCourtyard(pcbnew.F_CrtYd)) part["pads"] = [] for p in f.Pads(): r = p.GetBoundingBox() part["pads"].append(dict(num=p.GetNumber(), net=p.GetNetname(), pintype=types.get((part["ref"], p.GetNumber()), p.GetPinType()), x=round(p.GetPosition().x / MM, 4), y=round(p.GetPosition().y / MM, 4), w=round(r.GetWidth() / MM, 4), h=round(r.GetHeight() / MM, 4), tht=p.GetAttribute() in (pcbnew.PAD_ATTRIB_PTH, pcbnew.PAD_ATTRIB_NPTH))) part["pads"].sort(key=lambda p: (p["num"], p["x"], p["y"])) d["parts"].append(part) for name, ni in b.GetNetInfo().NetsByName().items(): if str(name): d["netclass"][str(name)] = ni.GetNetClassName() pro = json.load(open(src[:-len(".kicad_pcb")] + ".kicad_pro")) for c in pro["net_settings"]["classes"]: d["classes"][c["name"]] = dict(track=c["track_width"], clearance=c["clearance"]) d["fill"] = sorted({z.GetNetname() for z in b.Zones() if not z.GetIsRuleArea() and z.GetNetname()}) json.dump(d, open(out, "w"), indent=1) print("parts %d, pads %d, nets %d, fill %s, keepouts %d, bounds %s" % ( len(d["parts"]), sum(len(p["pads"]) for p in d["parts"]), len(d["netclass"]), d["fill"], len(d["keepouts"]), d["bounds"])) if __name__ == "__main__": main(*sys.argv[1:4])