main
Drew Owens Add KiCad 10 Spine PCB, STEP, Gerbers/BOM/CPL, and parametric mechanical CAD/STL/STEP e614ae8
#!/usr/bin/env python3
"""Build initial Microgoose Spine 2-layer KiCad 10 PCB from design/netlist.json."""

from __future__ import annotations

import json
import math
import uuid
from pathlib import Path

import pcbnew

ROOT = Path(__file__).resolve().parent.parent
KICAD_DIR = ROOT / "kicad"
NETLIST_PATH = ROOT / "design" / "netlist.json"
PLACEMENT_PATH = ROOT / "aiflow" / "placement_coords.json"

SCH_UUID_NS = uuid.UUID("7b3c9e52-64f1-4a8e-9b14-2c8d5e103f77")


def det_uuid(tag: str) -> str:
    return str(uuid.uuid5(SCH_UUID_NS, tag))


def v2i(x_mm: float, y_mm: float) -> pcbnew.VECTOR2I:
    return pcbnew.VECTOR2I(pcbnew.FromMM(x_mm), pcbnew.FromMM(y_mm))


def add_edge_line(board: pcbnew.BOARD, x1: float, y1: float, x2: float, y2: float) -> None:
    sh = pcbnew.PCB_SHAPE(board)
    sh.SetShape(pcbnew.SHAPE_T_SEGMENT)
    sh.SetLayer(pcbnew.Edge_Cuts)
    sh.SetWidth(pcbnew.FromMM(0.1))
    sh.SetStart(v2i(x1, y1))
    sh.SetEnd(v2i(x2, y2))
    board.Add(sh)


def add_edge_arc(
    board: pcbnew.BOARD,
    sx: float,
    sy: float,
    mx: float,
    my: float,
    ex: float,
    ey: float,
) -> None:
    sh = pcbnew.PCB_SHAPE(board)
    sh.SetShape(pcbnew.SHAPE_T_ARC)
    sh.SetLayer(pcbnew.Edge_Cuts)
    sh.SetWidth(pcbnew.FromMM(0.1))
    sh.SetArcGeometry(v2i(sx, sy), v2i(mx, my), v2i(ex, ey))
    board.Add(sh)


def main() -> None:
    netlist = json.loads(NETLIST_PATH.read_text())
    coords = json.loads(PLACEMENT_PATH.read_text())
    comp_map = {c["ref"]: c for c in netlist["components"]}

    board_path = KICAD_DIR / "microgoose-spine.kicad_pcb"
    board = pcbnew.NewBoard(str(board_path))
    board.SetCopperLayerCount(2)

    ds = board.GetDesignSettings()
    ds.SetCopperLayerCount(2)
    ds.SetBoardThickness(pcbnew.FromMM(1.6))
    x0, y0 = coords["origin_mp1_kicad_mm"]
    ds.SetAuxOrigin(v2i(x0, y0))
    ds.SetGridOrigin(v2i(x0, y0))

    # Build pin -> net lookup from design/netlist.json
    pin_to_net: dict[str, str] = {}
    net_items: dict[str, pcbnew.NETINFO_ITEM] = {}
    for idx, (net_name, pins) in enumerate(netlist["nets"].items(), start=1):
        ni = pcbnew.NETINFO_ITEM(board, net_name, idx)
        board.Add(ni)
        net_items[net_name] = ni
        for pin_ref in pins:
            pin_to_net[pin_ref] = net_name

    # Closed 70.0 x 70.0 mm Edge.Cuts rounded rectangle (R = 3.0 mm centered on MP1..MP4)
    # MP1 = (100, 150), MP2 = (164, 150), MP3 = (100, 86), MP4 = (164, 86)
    r = 3.0
    d45 = r * math.sqrt(0.5)
    # 1. Bottom straight: (100, 153) -> (164, 153)
    add_edge_line(board, 100.0, 153.0, 164.0, 153.0)
    # 2. Bottom-right arc around MP2 (164, 150): (164, 153) -> (167, 150)
    add_edge_arc(board, 164.0, 153.0, 164.0 + d45, 150.0 + d45, 167.0, 150.0)
    # 3. Right straight: (167, 150) -> (167, 86)
    add_edge_line(board, 167.0, 150.0, 167.0, 86.0)
    # 4. Top-right arc around MP4 (164, 86): (167, 86) -> (164, 83)
    add_edge_arc(board, 167.0, 86.0, 164.0 + d45, 86.0 - d45, 164.0, 83.0)
    # 5. Top straight: (164, 83) -> (100, 83)
    add_edge_line(board, 164.0, 83.0, 100.0, 83.0)
    # 6. Top-left arc around MP3 (100, 86): (100, 83) -> (97, 86)
    add_edge_arc(board, 100.0, 83.0, 100.0 - d45, 86.0 - d45, 97.0, 86.0)
    # 7. Left straight: (97, 86) -> (97, 150)
    add_edge_line(board, 97.0, 86.0, 97.0, 150.0)
    # 8. Bottom-left arc around MP1 (100, 150): (97, 150) -> (100, 153)
    add_edge_arc(board, 97.0, 150.0, 100.0 - d45, 150.0 + d45, 100.0, 153.0)

    pcm_pretty = str(KICAD_DIR / "lib" / "PCM_microgoose.pretty")
    adom_pretty = str(KICAD_DIR / "lib" / "adom.pretty")

    for ref, comp in comp_map.items():
        if ref.startswith("TP"):
            fp = pcbnew.FootprintLoad(adom_pretty, "Adom_TestPoint_D0.5mm")
            assert fp is not None, f"Could not load Adom_TestPoint_D0.5mm for {ref}"
            fp.SetFPIDAsString("adom:Adom_TestPoint_D0.5mm")
            fp.SetAttributes(fp.GetAttributes() | pcbnew.FP_EXCLUDE_FROM_BOM)
        else:
            fp_name = comp["fp"].split(":", 1)[1]
            fp = pcbnew.FootprintLoad(pcm_pretty, fp_name)
            assert fp is not None, f"Could not load {fp_name} for {ref}"
            fp.SetFPIDAsString(f"PCM_microgoose:{fp_name}")
            fp.SetAttributes(fp.GetAttributes() & ~pcbnew.FP_EXCLUDE_FROM_BOM)

        sym_uuid = det_uuid(f"sym-{ref}")
        fp.SetPath(pcbnew.KIID_PATH(f"/{sym_uuid}"))
        fp.SetReference(ref)
        fp.SetValue(str(comp["value"]))
        if comp.get("mpn"):
            fp.SetField("MPN", str(comp["mpn"]))
        if comp.get("mfr"):
            fp.SetField("Manufacturer", str(comp["mfr"]))
        for fld in fp.GetFields():
            if fld.GetName() in ("MPN", "Manufacturer", "Datasheet", "Footprint"):
                fld.SetVisible(False)

        # Ensure silkscreen Reference >= 0.85 mm height & 0.15 mm thickness, Value hidden on F.Fab
        ref_field = fp.Reference()
        ref_field.SetLayer(pcbnew.F_SilkS)
        ref_field.SetTextSize(v2i(0.9, 0.9))
        ref_field.SetTextThickness(pcbnew.FromMM(0.15))
        ref_field.SetVisible(True)

        val_field = fp.Value()
        val_field.SetLayer(pcbnew.F_Fab)
        val_field.SetVisible(False)

        # Position: locked fixed coordinates for molecule pins/contacts, initial staging grid for movable SMT parts
        if "fixed" in comp:
            pos = coords["final_kicad"][ref]
            fp.SetPosition(v2i(pos["x"], pos["y"]))
            fp.SetOrientationDegrees(float(pos["rot"]))
            fp.SetLocked(True)
        else:
            pos = coords["staging_kicad"][ref]
            fp.SetPosition(v2i(pos["x"], pos["y"]))
            fp.SetOrientationDegrees(float(pos["rot"]))
            fp.SetLocked(False)

        # Assign pad nets (skip unnamed "" paste-only pads!)
        for pad in fp.Pads():
            pnum = pad.GetNumber().strip()
            if not pnum:
                continue
            key = f"{ref}.{pnum}"
            if key in pin_to_net:
                pad.SetNet(net_items[pin_to_net[key]])

        board.Add(fp)

    pcbnew.SaveBoard(str(board_path), board)
    print(f"OK: built {board_path} ({len(comp_map)} footprints, {len(net_items)} nets)")


if __name__ == "__main__":
    main()