main
John Lauer Public-facing docs: final-board images, Fields numbers from the final solve, clips merged into one page 5b68870
"""Build buck-12v5v-molecule.kicad_pcb from netlist.json with KiCad 10's own Python (pcbnew).

Run on a machine with KiCad 10:  "<KiCad>/10.0/bin/python.exe" build_board.py
Writes buck-12v5v-molecule.kicad_pcb (+ .kicad_pro, .kicad_dru) next to this script and
build_board.json (what was placed, nets, any warnings).

Molecule coordinates (netlist.json `fixed`) are mm from the centre of MP1 (lower-left pin),
y up; KiCad is y down, so KiCad = (X0 + x, Y0 - y).
"""
import json, os, sys, shutil
import pcbnew

HERE = os.path.dirname(os.path.abspath(__file__))
NAME = "buck-12v5v-molecule"
KICAD_SHARE = os.environ.get("KICAD_SHARE", r"C:\Program Files\KiCad\10.0\share\kicad")
X0, Y0 = 100.0, 100.0
mm = pcbnew.FromMM

net = json.load(open(os.path.join(HERE, "netlist.json"), encoding="utf-8"))
mol = net["molecule"]
report = {"placed": [], "warnings": []}


def lib_dir(lib):
    local = os.path.join(HERE, "lib", lib + ".pretty")
    if os.path.isdir(local):
        return local
    return os.path.join(KICAD_SHARE, "footprints", lib + ".pretty")


def kc(x, y):
    return pcbnew.VECTOR2I(mm(X0 + x), mm(Y0 - y))


path = os.path.join(HERE, NAME + ".kicad_pcb")
board = pcbnew.NewBoard(path)

# ---- stackup / rules -------------------------------------------------------
board.SetCopperLayerCount(2)
ds = board.GetDesignSettings()
ds.SetBoardThickness(mm(1.6))
ds.m_MinClearance = mm(0.1)
ds.m_TrackMinWidth = mm(0.1)
ds.m_ViasMinSize = mm(0.25)
ds.m_MinThroughDrill = mm(0.15)
ds.m_ViasMinAnnularWidth = mm(0.1)
ds.m_CopperEdgeClearance = mm(0.2)
ds.m_HoleToHoleMin = mm(0.2)
try:
    nc = ds.m_NetSettings.GetDefaultNetclass()
    nc.SetClearance(mm(0.15)); nc.SetTrackWidth(mm(0.2)); nc.SetViaDiameter(mm(0.45)); nc.SetViaDrill(mm(0.2))
except Exception as e:  # API differences between KiCad versions: the .kicad_dru still enforces the limits
    report["warnings"].append(f"default netclass not set: {e}")

# ---- nets -------------------------------------------------------------------
nets = {}
for name in net["nets"]:
    ni = pcbnew.NETINFO_ITEM(board, name)
    board.Add(ni)
    nets[name] = ni
pin_net = {}
for name, pins in net["nets"].items():
    for p in pins:
        pin_net[p] = name

# ---- footprints ---------------------------------------------------------------
stage_x = -2.0
for c in net["components"]:
    lib, fpname = c["fp"].split(":")
    fp = pcbnew.FootprintLoad(lib_dir(lib), fpname)
    if fp is None:
        report["warnings"].append(f"{c['ref']}: footprint {c['fp']} not found")
        continue
    fp.SetReference(c["ref"])
    fp.SetValue(c["value"])
    fp.SetFPIDAsString(c["fp"])
    for k, v in (("MPN", c.get("mpn", "")), ("Manufacturer", c.get("mfr", "")), ("Source", c.get("src", "")),
                 ("Function", c.get("block", ""))):
        if v:
            fp.SetField(k, v)
            for f in fp.GetFields():
                if f.GetName() == k:
                    f.SetVisible(False)
    # molecule parts: models live in the project so the board travels
    if lib == "Molecule" or lib == "buck12v5v":
        for m in fp.Models():
            m.m_Filename = "${KIPRJMOD}/3d/" + os.path.basename(m.m_Filename)
    board.Add(fp)
    if "fixed" in c:
        fp.SetPosition(kc(c["fixed"]["x"], c["fixed"]["y"]))
        fp.SetLocked(True)
        where = "fixed"
    else:
        bb = fp.GetBoundingBox(False)
        w = pcbnew.ToMM(bb.GetWidth())
        fp.SetPosition(pcbnew.VECTOR2I(mm(X0 + stage_x + w / 2 + 0.5), mm(Y0 + 8)))
        stage_x += w + 1.0
        where = "staging"
    for pad in fp.Pads():
        key = f"{c['ref']}.{pad.GetNumber()}"
        n = pin_net.get(key)
        if n:
            pad.SetNet(nets[n])
        elif pad.GetNumber():
            report["warnings"].append(f"{key}: no net")
    report["placed"].append({"ref": c["ref"], "fp": c["fp"], "where": where})

# ---- outline: pin span + 2 mm margin, rounded corners -----------------------------------
# Corner radius = the edge margin, centred on each corner pin, so the edge stays the same distance
# from the pin all the way round (a 45 degree chamfer reads as unfinished).
sx, sy = mol["pin_span_mm"]
m = mol["edge_margin_mm"]
x0, y0, x1, y1 = -m, -m, sx + m, sy + m
def edge_line(a, b):
    seg = pcbnew.PCB_SHAPE(board); seg.SetShape(pcbnew.SHAPE_T_SEGMENT)
    seg.SetStart(kc(*a)); seg.SetEnd(kc(*b)); seg.SetLayer(pcbnew.Edge_Cuts); seg.SetWidth(mm(0.05)); board.Add(seg)
def edge_arc(cx, cy, a0):
    import math
    pt = lambda a: (cx + m * math.cos(math.radians(a)), cy + m * math.sin(math.radians(a)))
    arc = pcbnew.PCB_SHAPE(board); arc.SetShape(pcbnew.SHAPE_T_ARC)
    arc.SetArcGeometry(kc(*pt(a0)), kc(*pt(a0 + 45)), kc(*pt(a0 + 90))); arc.SetLayer(pcbnew.Edge_Cuts); arc.SetWidth(mm(0.05)); board.Add(arc)
# design frame: y up, MP1 at (0, 0); kc() maps it to KiCad's y-down frame, so the angles below are in the design frame
edge_line((0, y0), (sx, y0)); edge_line((x1, 0), (x1, sy)); edge_line((sx, y1), (0, y1)); edge_line((x0, sy), (x0, 0))
edge_arc(0, 0, 180); edge_arc(sx, 0, 270); edge_arc(sx, sy, 0); edge_arc(0, sy, 90)

origin = kc(0, 0)
ds.SetAuxOrigin(origin)
ds.SetGridOrigin(origin)

tb = board.GetTitleBlock()
tb.SetTitle("12 V to 5 V / 1 A buck molecule (TPS54202)")
tb.SetCompany("Adom")
tb.SetRevision("A")
tb.SetComment(0, "Molecule: 24 x 16 mm medium pin grid, origin = MP1 centre")
tb.SetComment(1, "Fab: 3rd party fab, 2-layer, 1.6 mm; current sized for 0.5 oz copper")

pcbnew.SaveBoard(path, board)
shutil.copyfile(os.path.join(HERE, "rules", "fab-2L.kicad_dru"), os.path.join(HERE, NAME + ".kicad_dru"))
report["board"] = path
report["nets"] = len(nets)
report["footprints"] = len(report["placed"])
json.dump(report, open(os.path.join(HERE, "build_board.json"), "w"), indent=1)
print(json.dumps({k: report[k] for k in ("board", "nets", "footprints")} | {"warnings": report["warnings"]}))