tools/epro2/kicad: Phase-1 .kicad_pcb exporter — 6/6 boards open in KiCad 8

Phase-1 scope: produce a .kicad_pcb that kicad-cli loads cleanly and
that has the right geometry (nets, footprints, tracks, vias, board
outline) — not a 1:1 EDA round-trip. Skipped on purpose for Phase 2:
copper pours (POUR/POURED), manual FILL, teardrops, board-level
strings/images, ARC circle-center recovery.

What lands:
  - pcb_writer.write_pcb(): header/general, data-driven layer table
    (F.Cu = ord 0; B.Cu = ord 31; SIGNAL inner ids 15+ allocated to
    In1.Cu/In2.Cu/... in EPRO2-id sorted order so used inner layers
    stay contiguous), net-name → integer id map (id 0 reserved for the
    empty net per KiCad convention), LINE→segment / LINE→gr_line on
    Edge.Cuts, layer-11 POLY paths walked into Edge.Cuts gr_line chains
    (the actual board outline lives on POLY here, not LINE — without
    this stats showed edge=0), VIA→via.
  - footprint_writer.write_footprint_placement(): inline (footprint ...)
    blocks per PCB COMPONENT. EPRO2 RECT/ELLIPSE/OVAL/POLYGON pad
    shapes mapped to KiCad rect/circle/oval/custom; SMD vs THT detected
    by PAD.hole presence; SLOT holes use (drill oval w h). Pad nets
    resolved cross-doc via the existing PCB.PAD_NET → footprint.pad
    chain in ProjectRelations. layerId=2 component → (layer B.Cu) +
    text on B.SilkS so bottom-side parts render correctly.

Smoke test on ESP-VoCat (6 PCBs): all 6 pass `kicad-cli pcb export svg`
and render. DRC on smallest (MicBoard) reports 145 violations + 75
unconnected — most of the unconnected are GND nets that the EPRO2
source resolves through POUR copper, which Phase 2 will export.

CLI: `python -m tools.epro2.kicad <project> --all-pcb --out <dir>`
emits one .kicad_pcb per PCB doc.

52 → 65 unit tests pass. Float comparisons in tests use math.isclose
because the s-expr 6-decimal trim doesn't preserve strict equality
through `value * MIL_TO_MM` round-trips.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-29 00:18:32 +08:00
parent fc2a45f658
commit e61404478e
6 changed files with 1211 additions and 1 deletions

View File

@@ -0,0 +1,165 @@
"""Footprint writer regression: synthetic PCB+FOOTPRINT pair → (footprint ...)."""
import math
from tools.epro2.kicad._sexpr_reader import parse
from tools.epro2.kicad.pcb_writer import MIL_TO_MM, write_pcb
from tools.epro2.project_relations import ProjectRelations
from tools.epro2.replay import Document, Project
def _close(a, b):
return math.isclose(a, b, abs_tol=1e-6)
def _block(parsed, name):
return [c for c in parsed if isinstance(c, list) and c and c[0] == name]
def _build(fp_objs: list[tuple[str, dict]],
pcb_objs: list[tuple[str, dict]],
comp_id: str = "C1",
fp_uuid: str = "FP1") -> str:
fp = Document(doc_uuid=fp_uuid, doc_type="FOOTPRINT")
fp.objects["META"] = {"_type": "META", "title": "TestFp"}
for k, v in fp_objs:
fp.objects[k] = v
pcb = Document(doc_uuid="pcb1", doc_type="PCB")
pcb.head = {"docType": "PCB", "editVersion": "3.2.91"}
for k, v in pcb_objs:
pcb.objects[k] = v
proj = Project(project_uuid="p")
proj.documents[fp_uuid] = fp
proj.documents["pcb1"] = pcb
pr = ProjectRelations.build(proj)
return write_pcb(pcb, project_relations=pr, board_origin_mm=(0.0, 0.0))
def test_smd_rect_pad_lands_on_top_copper_mask_and_paste():
"""A rectangular SMD pad on EPRO2 layer 1 (TOP) must write its layers
as F.Cu/F.Mask/F.Paste in KiCad — leaving any of those out drops the
pad from solder mask / paste stencil and the board fails fab."""
text = _build(
fp_objs=[
("p1", {"_type": "PAD", "num": "1", "centerX": 0, "centerY": 0,
"padAngle": 0, "layerId": 1, "hole": None,
"defaultPad": {"padType": "RECT", "width": 30, "height": 20},
"specialPad": []}),
],
pcb_objs=[
("C1", {"_type": "COMPONENT", "x": 100, "y": 100, "angle": 0, "layerId": 1}),
("a1", {"_type": "ATTR", "parentId": "C1", "key": "Footprint", "value": "FP1"}),
],
)
p = parse(text)
fp = _block(p, "footprint")[0]
pads = [c for c in fp if isinstance(c, list) and c[0] == "pad"]
assert len(pads) == 1
pad = pads[0]
assert pad[1] == "1"
assert pad[2] == "smd"
assert pad[3] == "rect"
layers = next(c for c in pad if isinstance(c, list) and c[0] == "layers")
assert set(layers[1:]) == {"F.Cu", "F.Mask", "F.Paste"}
def test_pad_with_hole_writes_thru_hole_and_drill():
"""A PAD with `hole` set is THT — must be `thru_hole`, span `*.Cu` and
have a `(drill ...)` block. Slot holes additionally need the
`(drill oval w h)` two-arg form."""
text = _build(
fp_objs=[
("p1", {"_type": "PAD", "num": "1", "centerX": 0, "centerY": 0,
"padAngle": 0, "layerId": 12,
"hole": {"holeType": "ROUND", "width": 12, "height": 12},
"defaultPad": {"padType": "ELLIPSE", "width": 24, "height": 24}}),
("p2", {"_type": "PAD", "num": "2", "centerX": 50, "centerY": 0,
"padAngle": 0, "layerId": 12,
"hole": {"holeType": "SLOT", "width": 30, "height": 12},
"defaultPad": {"padType": "OVAL", "width": 50, "height": 24}}),
],
pcb_objs=[
("C1", {"_type": "COMPONENT", "x": 100, "y": 100, "angle": 0}),
("a1", {"_type": "ATTR", "parentId": "C1", "key": "Footprint", "value": "FP1"}),
],
)
p = parse(text)
fp = _block(p, "footprint")[0]
pads = [c for c in fp if isinstance(c, list) and c[0] == "pad"]
assert len(pads) == 2
by_num = {pad[1]: pad for pad in pads}
# Round through-hole
p1 = by_num["1"]
assert p1[2] == "thru_hole"
drill1 = next(c for c in p1 if isinstance(c, list) and c[0] == "drill")
assert _close(drill1[1], 12 * MIL_TO_MM)
# Slot through-hole
p2 = by_num["2"]
drill2 = next(c for c in p2 if isinstance(c, list) and c[0] == "drill")
assert drill2[1] == "oval"
assert _close(drill2[2], 30 * MIL_TO_MM)
assert _close(drill2[3], 12 * MIL_TO_MM)
def test_pad_net_resolved_via_pad_net_op():
"""KiCad needs `(net N "name")` on each pad to know which net it
belongs to. The mapping comes from the PCB-level PAD_NET op (not
from anything in the footprint), so it has to be pulled cross-doc."""
text = _build(
fp_objs=[
("p1", {"_type": "PAD", "num": "1", "centerX": 0, "centerY": 0,
"layerId": 1, "hole": None,
"defaultPad": {"padType": "RECT", "width": 30, "height": 20}}),
],
pcb_objs=[
('["NET","GND"]', {"_type": "NET"}),
("C1", {"_type": "COMPONENT", "x": 0, "y": 0, "angle": 0}),
("a1", {"_type": "ATTR", "parentId": "C1", "key": "Footprint", "value": "FP1"}),
('["PAD_NET","C1","1","p1"]', {"_type": "PAD_NET", "padNet": "GND"}),
],
)
p = parse(text)
fp = _block(p, "footprint")[0]
pad = next(c for c in fp if isinstance(c, list) and c[0] == "pad")
net_block = next(c for c in pad if isinstance(c, list) and c[0] == "net")
assert net_block[2] == "GND"
assert net_block[1] >= 1
def test_component_on_bottom_layer_gets_b_cu_layer():
"""COMPONENT.layerId=2 places the footprint on B.Cu, with text
properties moved to B.SilkS / B.Fab. Without this a bottom-side
component renders on F.Cu and the netlist routes through phantom
geometry."""
text = _build(
fp_objs=[
("p1", {"_type": "PAD", "num": "1", "centerX": 0, "centerY": 0,
"layerId": 1, "hole": None,
"defaultPad": {"padType": "RECT", "width": 30, "height": 20}}),
],
pcb_objs=[
("C1", {"_type": "COMPONENT", "x": 0, "y": 0, "angle": 0, "layerId": 2}),
("a1", {"_type": "ATTR", "parentId": "C1", "key": "Footprint", "value": "FP1"}),
],
)
p = parse(text)
fp = _block(p, "footprint")[0]
layer = next(c for c in fp if isinstance(c, list) and c[0] == "layer")
assert layer[1] == "B.Cu"
def test_unresolved_footprint_skipped_with_diagnostic():
"""A COMPONENT without a Footprint ATTR pointing at a real
FOOTPRINT doc must be skipped — emitting an empty (footprint ...)
block would crash kicad-cli on load."""
pcb = Document(doc_uuid="pcb1", doc_type="PCB")
pcb.head = {"docType": "PCB", "editVersion": "3.2.91"}
pcb.objects["C1"] = {"_type": "COMPONENT", "x": 0, "y": 0}
# No matching FOOTPRINT doc, no Footprint ATTR
proj = Project(project_uuid="p")
proj.documents["pcb1"] = pcb
pr = ProjectRelations.build(proj)
text = write_pcb(pcb, project_relations=pr)
p = parse(text)
assert _block(p, "footprint") == []
assert getattr(write_pcb, "last_stats").footprints_unresolved == 1

View File

@@ -0,0 +1,162 @@
"""PCB writer regression: synthetic PCB doc → kicad_pcb → re-parse."""
import math
from tools.epro2.kicad._sexpr_reader import parse
from tools.epro2.kicad.pcb_writer import MIL_TO_MM, write_pcb
from tools.epro2.project_relations import ProjectRelations
from tools.epro2.replay import Document, Project
def _close(a, b):
"""Float-close: 6-decimal s-expr roundtrip can lose strict equality."""
return math.isclose(a, b, abs_tol=1e-6)
def _block(parsed, name):
return [c for c in parsed if isinstance(c, list) and c and c[0] == name]
def _pcb(objs, doc_uuid="pcb1") -> Document:
d = Document(doc_uuid=doc_uuid, doc_type="PCB")
d.head = {"docType": "PCB", "editVersion": "3.2.91"}
for k, v in objs:
d.objects[k] = v
return d
def _empty_pr(pcb_doc: Document) -> ProjectRelations:
p = Project(project_uuid="p")
p.documents[pcb_doc.doc_uuid] = pcb_doc
return ProjectRelations.build(p)
def test_writer_emits_header_and_layers():
d = _pcb([("META", {"_type": "META", "title": "BoardX"})])
text = write_pcb(d, project_relations=_empty_pr(d))
p = parse(text)
assert p[0] == "kicad_pcb"
layers = _block(p, "layers")[0]
# F.Cu is always ordinal 0, B.Cu always 31 — KiCad convention.
rows = [row for row in layers[1:] if isinstance(row, list)]
by_name = {r[1]: r[0] for r in rows}
assert by_name["F.Cu"] == 0
assert by_name["B.Cu"] == 31
assert "Edge.Cuts" in by_name
def test_inner_signal_layers_inserted_in_id_order():
"""An EPRO2 4-layer board with SIGNAL ids 15 and 16 actually used must
map to In1.Cu and In2.Cu (in EPRO2-id sorted order) so the PCB
layer-stack ordering matches the editor's intent."""
d = _pcb([
('["LAYER",1]', {"_type": "LAYER", "layerType": "TOP", "use": True}),
('["LAYER",2]', {"_type": "LAYER", "layerType": "BOTTOM", "use": True}),
('["LAYER",15]', {"_type": "LAYER", "layerType": "SIGNAL", "use": True}),
('["LAYER",16]', {"_type": "LAYER", "layerType": "SIGNAL", "use": True}),
# Drive "used" flag by including a primitive on each inner layer
("ln1", {"_type": "LINE", "layerId": 15,
"startX": 0, "startY": 0, "endX": 100, "endY": 0, "width": 6}),
("ln2", {"_type": "LINE", "layerId": 16,
"startX": 0, "startY": 0, "endX": 100, "endY": 0, "width": 6}),
])
text = write_pcb(d, project_relations=_empty_pr(d))
p = parse(text)
rows = [r for r in _block(p, "layers")[0][1:] if isinstance(r, list)]
cu_layers = [r[1] for r in rows if r[1].endswith(".Cu")]
assert cu_layers == ["F.Cu", "In1.Cu", "In2.Cu", "B.Cu"]
def test_nets_get_stable_integer_ids_starting_at_1():
"""KiCad reserves net id 0 for "no net" — our user-defined nets must
start at 1 so segments referencing them don't collide with the empty
net."""
d = _pcb([
('["NET","GND"]', {"_type": "NET"}),
('["NET","VCC"]', {"_type": "NET"}),
])
text = write_pcb(d, project_relations=_empty_pr(d))
p = parse(text)
nets = _block(p, "net")
by_name = {n[2]: n[1] for n in nets}
assert by_name[""] == 0
assert sorted([by_name["GND"], by_name["VCC"]]) == [1, 2]
def test_segment_emitted_for_copper_line_with_net():
d = _pcb([
('["NET","GND"]', {"_type": "NET"}),
("ln1", {"_type": "LINE", "layerId": 1, "netName": "GND", "width": 6,
"startX": 100, "startY": 200, "endX": 500, "endY": 200}),
])
text = write_pcb(d, project_relations=_empty_pr(d), board_origin_mm=(0.0, 0.0))
p = parse(text)
segs = _block(p, "segment")
assert len(segs) == 1
seg = segs[0]
start = next(c for c in seg if isinstance(c, list) and c[0] == "start")
end = next(c for c in seg if isinstance(c, list) and c[0] == "end")
assert _close(start[1], 100 * MIL_TO_MM)
assert _close(start[2], 200 * MIL_TO_MM)
assert _close(end[1], 500 * MIL_TO_MM)
layer = next(c for c in seg if isinstance(c, list) and c[0] == "layer")
assert layer[1] == "F.Cu"
net_ref = next(c for c in seg if isinstance(c, list) and c[0] == "net")
assert net_ref[1] >= 1
def test_via_emitted_with_size_and_drill():
d = _pcb([
('["NET","SIG"]', {"_type": "NET"}),
("v1", {"_type": "VIA", "centerX": 100, "centerY": 200,
"viaDiameter": 24, "holeDiameter": 12, "netName": "SIG"}),
])
text = write_pcb(d, project_relations=_empty_pr(d), board_origin_mm=(0.0, 0.0))
p = parse(text)
vias = _block(p, "via")
assert len(vias) == 1
v = vias[0]
at = next(c for c in v if isinstance(c, list) and c[0] == "at")
assert _close(at[1], 100 * MIL_TO_MM)
size = next(c for c in v if isinstance(c, list) and c[0] == "size")
assert _close(size[1], 24 * MIL_TO_MM)
drill = next(c for c in v if isinstance(c, list) and c[0] == "drill")
assert _close(drill[1], 12 * MIL_TO_MM)
def test_outline_poly_emitted_as_edge_cuts_lines():
"""POLY on layer 11 is the board outline and must convert to
(gr_line ... (layer Edge.Cuts)) chains so KiCad recognises the
board boundary — without this the board has no Edge.Cuts geometry
and DRC reports invalid_outline."""
d = _pcb([
("p1", {"_type": "POLY", "layerId": 11, "width": 4,
"path": [0, 0, "L", 1000, 0, 1000, 1000, 0, 1000, 0, 0]}),
])
text = write_pcb(d, project_relations=_empty_pr(d), board_origin_mm=(0.0, 0.0))
p = parse(text)
lines = _block(p, "gr_line")
assert len(lines) == 4 # square: 4 sides
layers = {next(c for c in ln if isinstance(c, list) and c[0] == "layer")[1]
for ln in lines}
assert layers == {"Edge.Cuts"}
def test_zero_length_segment_skipped():
d = _pcb([
("ln1", {"_type": "LINE", "layerId": 1, "netName": "GND", "width": 6,
"startX": 5, "startY": 5, "endX": 5, "endY": 5}),
])
text = write_pcb(d, project_relations=_empty_pr(d))
p = parse(text)
assert _block(p, "segment") == []
assert getattr(write_pcb, "last_stats").skipped == 1
def test_non_pcb_doc_rejected():
d = Document(doc_uuid="x", doc_type="SCH_PAGE")
try:
write_pcb(d)
except ValueError:
return
raise AssertionError("expected ValueError for non-PCB doc")