Running the new --all on the remaining 4 Pro projects (X86 motherboard, 220V power supply, Taishan Pi, Liangshan Pi) surfaced two crash modes not covered by ESP-VoCat: 1. Odd inner-layer count → KiCad rejects the file at load with "3 is not a valid layer count". The 220V power boards have one used inner SIGNAL layer (3 copper total: F.Cu / In1.Cu / B.Cu), but KiCad requires an even copper count. Fixed pcb_writer to pad with one empty inner layer when the inner count is odd, so the total stays even (2, 4, 6, ...). 2. Two BOARDs sharing the same META.title — twin "显示板" boards in the 220V power project — landed in the same project directory and the second silently overwrote the first's .kicad_sch / .kicad_pcb / .kicad_pro. Fixed --all to detect title collisions and suffix every colliding basename with the BOARD uuid prefix (so both '显示板' boards become '显示板_52e8cc76' and '显示板_55d32906' rather than one quietly winning). 71 → 73 unit tests pass (test_odd_inner_signal_count_padded_to_even_total + test_duplicate_board_titles_get_distinct_basenames). Tangentially noted while running this: Taishan Pi and Liangshan Pi are Pro 2.x JSON, not EPRO2 streams — our replay layer reads the files but doesn't decode docType, so SCH/PCB grouping returns nothing. Pro 2.x needs a separate writer; out of scope for this commit. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
244 lines
10 KiB
Python
244 lines
10 KiB
Python
"""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_odd_inner_signal_count_padded_to_even_total():
|
|
"""KiCad rejects odd copper layer counts ('3 is not a valid layer
|
|
count'). A board with one used inner SIGNAL layer must therefore
|
|
declare two — the second is empty padding, but without it the
|
|
loader refuses to open the file at all."""
|
|
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}),
|
|
("ln1", {"_type": "LINE", "layerId": 15,
|
|
"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")]
|
|
# 4 copper total: F.Cu, In1.Cu (used), In2.Cu (padding), B.Cu
|
|
assert cu_layers == ["F.Cu", "In1.Cu", "In2.Cu", "B.Cu"]
|
|
|
|
|
|
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_pour_rectangle_emits_zone_with_filled_polygon():
|
|
"""An EPRO2 POUR with rectangle path on a copper layer must turn into
|
|
a (zone) with both a (polygon ...) boundary and a (filled_polygon ...)
|
|
that mirrors it. Without the filled_polygon, kicad-cli pcb drc never
|
|
runs the zone filler and reports the entire net as unconnected."""
|
|
d = _pcb([
|
|
('["NET","GND"]', {"_type": "NET"}),
|
|
("p1", {"_type": "POUR", "layerId": 1, "netName": "GND",
|
|
"path": [["R", 0, 0, 1000, 1000, 0, 0]]}),
|
|
])
|
|
text = write_pcb(d, project_relations=_empty_pr(d), board_origin_mm=(0.0, 0.0))
|
|
p = parse(text)
|
|
zones = _block(p, "zone")
|
|
assert len(zones) == 1
|
|
z = zones[0]
|
|
layer = next(c for c in z if isinstance(c, list) and c[0] == "layer")
|
|
assert layer[1] == "F.Cu"
|
|
net_name = next(c for c in z if isinstance(c, list) and c[0] == "net_name")
|
|
assert net_name[1] == "GND"
|
|
poly = next(c for c in z if isinstance(c, list) and c[0] == "polygon")
|
|
pts = next(c for c in poly if isinstance(c, list) and c[0] == "pts")
|
|
xys = [c for c in pts if isinstance(c, list) and c[0] == "xy"]
|
|
assert len(xys) == 4 # rectangle has 4 corners
|
|
filled = next(c for c in z if isinstance(c, list) and c[0] == "filled_polygon")
|
|
fpts = next(c for c in filled if isinstance(c, list) and c[0] == "pts")
|
|
assert len([c for c in fpts if isinstance(c, list) and c[0] == "xy"]) == 4
|
|
|
|
|
|
def test_pour_circle_path_sampled_to_polygon():
|
|
"""Circular POURs on copper layers must be approximated as a polygon —
|
|
KiCad zones don't accept (circle ...) primitives, so the fill region
|
|
needs explicit (xy) points around the circumference."""
|
|
d = _pcb([
|
|
('["NET","GND"]', {"_type": "NET"}),
|
|
("p1", {"_type": "POUR", "layerId": 1, "netName": "GND",
|
|
"path": [["CIRCLE", 0, 0, 100]]}),
|
|
])
|
|
text = write_pcb(d, project_relations=_empty_pr(d), board_origin_mm=(0.0, 0.0))
|
|
p = parse(text)
|
|
z = _block(p, "zone")[0]
|
|
poly = next(c for c in z if isinstance(c, list) and c[0] == "polygon")
|
|
pts = next(c for c in poly if isinstance(c, list) and c[0] == "pts")
|
|
xys = [c for c in pts if isinstance(c, list) and c[0] == "xy"]
|
|
# 36 segments by default — enough to approximate a circle for fill
|
|
assert len(xys) >= 12
|
|
|
|
|
|
def test_pour_on_non_copper_layer_skipped():
|
|
"""POURs only make sense as copper zones; an EPRO2 POUR mistakenly
|
|
landed on a silk layer must NOT emit (zone ...) since KiCad zones
|
|
are copper-only and the file would be semantically wrong."""
|
|
d = _pcb([
|
|
('["NET","GND"]', {"_type": "NET"}),
|
|
("p1", {"_type": "POUR", "layerId": 3, "netName": "GND",
|
|
"path": [["R", 0, 0, 100, 100]]}),
|
|
])
|
|
text = write_pcb(d, project_relations=_empty_pr(d), board_origin_mm=(0.0, 0.0))
|
|
p = parse(text)
|
|
assert _block(p, "zone") == []
|
|
|
|
|
|
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")
|