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

@@ -22,6 +22,7 @@ from pathlib import Path
from ..project_relations import ProjectRelations
from ..replay import Document, Project, replay_project
from .pcb_writer import write_pcb
from .root_sch_writer import ChildSheet, new_sheet_uuid, write_root_sheet
from .sch_writer import write_sch_page
@@ -153,12 +154,44 @@ def _convert_hierarchical(
return root_count
def _convert_all_pcb(proj: Project, out_dir: Path, pr: ProjectRelations) -> int:
"""Emit one .kicad_pcb per PCB doc. Each is named after its META.title
and dropped into a sibling directory of the matching SCH for parity
with the schematic export layout."""
pcb_uuids = [u for u, d in proj.documents.items() if d.doc_type == "PCB"]
if not pcb_uuids:
print("no PCB docs in this project", file=sys.stderr)
return 0
print(f"Converting {len(pcb_uuids)} PCB doc(s) → {out_dir}")
n = 0
for u in pcb_uuids:
doc = proj.documents[u]
title = (doc.objects.get("META") or {}).get("title") or u[:12]
try:
text = write_pcb(doc, project_relations=pr)
except Exception as e: # noqa: BLE001
print(f" FAIL {u[:12]}: {e}", file=sys.stderr)
continue
out_path = out_dir / f"{_safe_filename(title)}.kicad_pcb"
out_path.write_text(text, encoding="utf-8")
stats = getattr(write_pcb, "last_stats", None)
if stats:
print(
f" {out_path.name}: nets={stats.nets} fps={stats.footprints} "
f"fps_unresolved={stats.footprints_unresolved} "
f"segments={stats.segments} vias={stats.vias} edge={stats.edge_cuts}"
)
n += 1
return n
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description="EPRO2 → KiCad schematic exporter (Phase 3 hierarchical)")
ap = argparse.ArgumentParser(description="EPRO2 → KiCad schematic + PCB exporter")
ap.add_argument("project_dir", type=Path)
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument("--doc", help="SCH_PAGE doc uuid (or unique prefix) to convert")
g.add_argument("--all-sch", action="store_true", help="convert every SCH_PAGE")
g.add_argument("--all-pcb", action="store_true", help="convert every PCB doc to .kicad_pcb")
ap.add_argument("--out", type=Path, default=Path("data/processed/kicad_sch"))
ap.add_argument(
"--no-lib-symbols",
@@ -176,6 +209,12 @@ def main(argv: list[str] | None = None) -> int:
args.out.mkdir(parents=True, exist_ok=True)
pr = None if args.no_lib_symbols else ProjectRelations.build(proj)
if args.all_pcb:
if pr is None:
pr = ProjectRelations.build(proj)
_convert_all_pcb(proj, args.out, pr=pr)
return 0
if args.doc:
_convert_one_flat(proj, args.doc, args.out, pr=pr)
return 0

View File

@@ -0,0 +1,287 @@
"""Convert one EPRO2 PCB COMPONENT + its FOOTPRINT doc → an inline
``(footprint ...)`` block embedded in the parent .kicad_pcb.
Phase-1 scope:
- Pad emission with EPRO2's RECT / ELLIPSE / OVAL / POLYGON shapes
- Pad nets resolved via PAD_NET ops on the PCB (cross-doc lookup)
- SMD vs THT detection via FOOTPRINT PAD.hole presence
- Silkscreen graphics from POLY ops on silk/courtyard layers
- Reference + Value text properties, placed at the COMPONENT origin
Out of scope: 3D models, fab notes, custom pad layers per-pad, paste-mask
expansion, complex SPECIAL pads with per-layer overrides.
"""
from __future__ import annotations
import math
import uuid as _uuid
from typing import TYPE_CHECKING
from ..relations import Relations
from ..replay import Document
from .sexpr import Sym
if TYPE_CHECKING:
from ..project_relations import ProjectRelations
from .pcb_writer import _LayerMap
MIL_TO_MM = 0.0254
# -- EPRO2 pad shape → KiCad pad shape ----------------------------------
PAD_SHAPE_MAP = {
"RECT": "rect",
"ELLIPSE": "circle", # square-ish ELLIPSE, KiCad has no 'ellipse' pad — use circle
"OVAL": "oval",
"POLYGON": "custom", # KiCad custom pad with primitive polygon
}
def _new_uuid() -> str:
return str(_uuid.uuid4())
def _mm(v) -> float:
if v is None:
return 0.0
try:
return float(v) * MIL_TO_MM
except (TypeError, ValueError):
return 0.0
def _kicad_layer_name(layer_id, layer_map: "_LayerMap") -> str | None:
if layer_id is None:
return None
try:
lid = int(layer_id)
except (TypeError, ValueError):
return None
return layer_map.epro_to_kicad.get(lid)
def _pad_layers(pad_layer_id: int, has_hole: bool) -> list[str]:
"""Layers a pad lives on, KiCad-style.
EPRO2 layerId convention for pads:
- 1 (TOP) → SMD on top: F.Cu + F.Mask + F.Paste
- 2 (BOT) → SMD on bottom: B.Cu + B.Mask + B.Paste
- 12 (MULTI)→ THT: all-copper + F&B Mask
"""
if has_hole:
return ["*.Cu", "*.Mask"]
if pad_layer_id == 1:
return ["F.Cu", "F.Mask", "F.Paste"]
if pad_layer_id == 2:
return ["B.Cu", "B.Mask", "B.Paste"]
return ["*.Cu", "*.Mask"]
def write_footprint_placement(
*,
fp_doc: Document,
comp_id: str,
comp: dict,
attrs: dict,
pcb_doc: Document,
pcb_rel: Relations,
project_relations: "ProjectRelations",
layer_map: "_LayerMap",
net_map: dict[str, int],
origin_mm: tuple[float, float],
) -> list:
"""Build a single ``(footprint ...)`` S-expr block for one PCB component.
Returns a Python list ready for ``to_sexpr``.
"""
ox, oy = origin_mm
px = ox + _mm(comp.get("x"))
py = oy + _mm(comp.get("y"))
rotation = float(comp.get("angle") or 0)
on_bottom = int(comp.get("layerId") or 1) == 2
fp_layer = "B.Cu" if on_bottom else "F.Cu"
designator = str(attrs.get("Designator") or "")
value = str(attrs.get("Value") or "")
fp_meta = (fp_doc.objects.get("META") or {}).get("title") or fp_doc.doc_uuid[:8]
body: list = [
Sym("footprint"), f"facere:{fp_meta}",
[Sym("layer"), fp_layer],
[Sym("uuid"), _new_uuid()],
[Sym("at"), px, py, rotation],
[Sym("attr"), Sym("smd")],
[Sym("property"), "Reference", designator,
[Sym("at"), 0, -1.5, 0],
[Sym("layer"), "B.SilkS" if on_bottom else "F.SilkS"],
[Sym("uuid"), _new_uuid()],
[Sym("effects"), [Sym("font"), [Sym("size"), 1.0, 1.0],
[Sym("thickness"), 0.15]]]],
[Sym("property"), "Value", value,
[Sym("at"), 0, 1.5, 0],
[Sym("layer"), "B.Fab" if on_bottom else "F.Fab"],
[Sym("uuid"), _new_uuid()],
[Sym("effects"), [Sym("font"), [Sym("size"), 1.0, 1.0],
[Sym("thickness"), 0.15]]]],
[Sym("property"), "Footprint", "",
[Sym("at"), 0, 0, 0],
[Sym("layer"), "F.Fab"],
[Sym("hide"), Sym("yes")],
[Sym("uuid"), _new_uuid()],
[Sym("effects"), [Sym("font"), [Sym("size"), 1.0, 1.0]]]],
[Sym("property"), "Datasheet", "",
[Sym("at"), 0, 0, 0],
[Sym("layer"), "F.Fab"],
[Sym("hide"), Sym("yes")],
[Sym("uuid"), _new_uuid()],
[Sym("effects"), [Sym("font"), [Sym("size"), 1.0, 1.0]]]],
]
fp_rel = project_relations.per_doc[fp_doc.doc_uuid]
pcb_uuid = pcb_doc.doc_uuid
# ---- pads --------------------------------------------------------------
for pad_id, pad in fp_rel.pads.items():
pad_block = _emit_pad(
pad=pad, pad_id=pad_id, comp_id=comp_id,
pcb_doc=pcb_doc, pcb_rel=pcb_rel,
net_map=net_map,
)
if pad_block is not None:
body.append(pad_block)
# ---- silkscreen / courtyard graphics from FOOTPRINT POLY/FILL ---------
# Local to the footprint origin — KiCad applies the placement at/rot
# transform on top, so we emit footprint-relative coords here.
for oid, obj in fp_doc.objects.items():
t = obj.get("_type")
if t not in ("POLY", "FILL"):
continue
kicad_layer = _kicad_layer_name(obj.get("layerId"), layer_map)
if not kicad_layer:
continue
# We only emit non-copper graphics inside footprints — copper inside
# a footprint that isn't a pad is unusual and best ignored for Phase 1.
if kicad_layer.endswith(".Cu"):
continue
path = obj.get("path") or []
pts = _decode_path(path)
if len(pts) < 2:
continue
body.append([
Sym("fp_poly") if t == "FILL" else Sym("fp_poly"),
[Sym("pts"), *[[Sym("xy"), x, y] for x, y in pts]],
[Sym("stroke"),
[Sym("width"), max(_mm(obj.get("width")), 0.05)],
[Sym("type"), Sym("default")]],
[Sym("fill"), Sym("solid") if t == "FILL" else Sym("none")],
[Sym("layer"), kicad_layer],
[Sym("uuid"), _new_uuid()],
])
return body
def _emit_pad(
*,
pad: dict,
pad_id: str,
comp_id: str,
pcb_doc: Document,
pcb_rel: Relations,
net_map: dict[str, int],
) -> list | None:
"""Emit a single ``(pad ...)`` block for one PAD inside a footprint.
Returns None when the pad is unrenderable (unknown shape, missing
geometry).
"""
default_pad = pad.get("defaultPad") or {}
shape = PAD_SHAPE_MAP.get(default_pad.get("padType"))
if shape is None:
return None
cx = _mm(pad.get("centerX"))
cy = _mm(pad.get("centerY"))
w = _mm(default_pad.get("width"))
h = _mm(default_pad.get("height"))
if w <= 0 or h <= 0:
return None
rotation = float(pad.get("padAngle") or 0)
pin_num = str(pad.get("num") or "")
layer_id = int(pad.get("layerId") or 1)
hole = pad.get("hole")
# Resolve net via PAD_NET cross-reference on the PCB doc.
net_name = ""
for record in pcb_rel.pad_nets_by_pad.get(pad_id, []):
if record.get("comp") == comp_id:
net_name = record.get("net_name") or ""
break
net_id = net_map.get(str(net_name), 0)
pad_type: str
if hole:
pad_type = "thru_hole"
else:
pad_type = "smd"
block: list = [
Sym("pad"), pin_num, Sym(pad_type), Sym(shape),
[Sym("at"), cx, cy, rotation] if rotation else [Sym("at"), cx, cy],
[Sym("size"), w, h],
[Sym("layers"), *_pad_layers(layer_id, bool(hole))],
]
if hole:
ht = (hole.get("holeType") or "ROUND").upper()
if ht == "SLOT":
hw = _mm(hole.get("width"))
hh = _mm(hole.get("height"))
block.append([Sym("drill"), Sym("oval"), max(hw, 0.1), max(hh, 0.1)])
else:
d = _mm(hole.get("width") or hole.get("diameter"))
block.append([Sym("drill"), max(d, 0.1)])
if net_id:
block.append([Sym("net"), net_id, net_name])
block.append([Sym("uuid"), _new_uuid()])
return block
def _decode_path(path: list) -> list[tuple[float, float]]:
"""EPRO2 graphic path → list of (x, y) in mm.
Supported shapes:
- flat ``[x1, y1, "L", x2, y2, x3, y3, ...]`` (line segments)
- flat ``[x1, y1, "L", x2, y2, ..., "ARC", ...]`` — arcs are skipped
in Phase 1; we collect the surrounding polyline points.
Anything we can't decode returns an empty list, which the caller treats
as "skip this primitive".
"""
pts: list[tuple[float, float]] = []
if not isinstance(path, list) or not path:
return pts
i = 0
while i < len(path):
item = path[i]
if isinstance(item, str):
# Skip the verb token; numeric pairs follow.
if item == "ARC":
# Arc params: radius, endX, endY (typical) — bail to keep
# Phase 1 simple. KiCad fp_poly with chord is geometrically
# wrong but won't fail to parse.
i += 1
continue
i += 1
continue
# Treat as numeric pair
try:
x = float(item)
y = float(path[i + 1])
pts.append((x * MIL_TO_MM, y * MIL_TO_MM))
i += 2
except (TypeError, ValueError, IndexError):
i += 1
return pts

View File

@@ -0,0 +1,490 @@
"""Convert one EPRO2 PCB Document → a KiCad ``.kicad_pcb`` S-expr.
Phase-1 scope (matches the schematic Phase-1: parses cleanly in KiCad 8 and
shows the correct geometry, but doesn't try to be a 1:1 EDA round-trip):
- Header + paper + layer table (only EPRO2 layers actually used on the board)
- Net list from NET ops + a name→id mapping shared with footprints/tracks/vias
- One ``(footprint ...)`` per PCB COMPONENT, body delegated to footprint_writer
- LINEs on copper layers → ``(segment ...)``; on Edge.Cuts → ``(gr_line ...)``
- VIAs → ``(via ...)``
- ARCs on Edge.Cuts → ``(gr_arc ...)``
Out of scope for Phase 1 (warnings/cosmetic, not connectivity):
- POUR / POURED zones — copper pours
- FILL — manual filled regions
- TEARDROP — fillets at via/pad junctions
- IMAGE — bitmap logos
- STRING — board-level text
- net classes / design rules / setup blocks beyond defaults
Coordinate system: EPRO2 PCB stores everything in **mil**, with both axes
matching KiCad's Y-down. We just multiply by ``MIL_TO_MM = 0.0254``. We
also translate by ``board_origin_mm`` so the board sits at a friendly
(100, 100) mm origin in KiCad rather than wherever the user happened to
place it in the editor.
"""
from __future__ import annotations
import math
import uuid as _uuid
from dataclasses import dataclass, field
from typing import Iterable
from ..project_relations import ProjectRelations
from ..relations import Relations
from ..replay import Document
from .footprint_writer import write_footprint_placement
from .sexpr import Sym, to_sexpr
MIL_TO_MM = 0.0254
KICAD_PCB_VERSION = 20240108 # KiCad 8.0
KICAD_GENERATOR = "facere-epro2"
# -- EPRO2 layerId → KiCad layer name -----------------------------------
#
# Copper (signal) layers are special: KiCad numbers them 0..31 with F.Cu=0
# and B.Cu always = 31 (regardless of board layer count). Inner layers are
# In1.Cu .. In30.Cu. We map EPRO2 SIGNAL layer ids 15+ to inner layers in
# the order they appear, so a board with EPRO2 ids 15(GND) and 16(POWER)
# becomes In1.Cu and In2.Cu.
#: Direct (non-copper) layer mapping. EPRO2 id → KiCad layer name.
EPRO2_LAYER_TO_KICAD: dict[int, str] = {
3: "F.SilkS",
4: "B.SilkS",
5: "F.Mask",
6: "B.Mask",
7: "F.Paste",
8: "B.Paste",
9: "F.Fab",
10: "B.Fab",
11: "Edge.Cuts",
13: "Dwgs.User",
14: "Cmts.User",
48: "F.CrtYd", # COMPONENT_SHAPE → courtyard
49: "F.Fab", # COMPONENT_MARKING → fab (already mapped above too)
50: "F.Paste", # PIN_SOLDERING ≈ paste mask (heuristic)
51: "F.Adhes", # PIN_FLOATING (rare; fallback)
}
@dataclass
class WriteStats:
nets: int = 0
footprints: int = 0
footprints_unresolved: int = 0
segments: int = 0
vias: int = 0
edge_cuts: int = 0
skipped: int = 0
@dataclass
class _LayerMap:
"""Resolved EPRO2-id → KiCad-name mapping for one PCB.
Copper layer assignment is data-driven: we walk every primitive on the
board to discover which EPRO2 ids actually carry geometry, then assign
them to In1.Cu, In2.Cu, ... in sorted order.
"""
epro_to_kicad: dict[int, str] = field(default_factory=dict)
kicad_layers_in_order: list[tuple[int, str, str]] = field(default_factory=list)
"""[(ordinal, kicad_layer_name, type)]; ordinal is the integer KiCad uses
in the (layers ...) header. ``type`` is ``"signal"`` or ``"user"``."""
def _build_layer_map(doc: Document) -> _LayerMap:
used_layer_ids: set[int] = set()
inner_signal_ids: list[int] = [] # EPRO2 SIGNAL ids actually populated
for oid, obj in doc.objects.items():
if oid.startswith('["LAYER"'):
continue
layer_id = obj.get("layerId")
if layer_id is None:
continue
try:
lid = int(layer_id)
except (TypeError, ValueError):
continue
used_layer_ids.add(lid)
# Discover which inner-signal layers are actually used (LAYER op declares
# use=True for many that the user never drew on; only the ones with real
# geometry need to appear in our (layers) header).
for oid, obj in doc.objects.items():
if obj.get("_type") != "LAYER":
continue
if not oid.startswith('["LAYER",'):
continue
try:
import json
cid = json.loads(oid)
lid = int(cid[1])
except (ValueError, TypeError, IndexError):
continue
if obj.get("layerType") == "SIGNAL" and lid in used_layer_ids:
inner_signal_ids.append(lid)
inner_signal_ids.sort()
epro_to_kicad: dict[int, str] = {1: "F.Cu", 2: "B.Cu"}
layers_in_order: list[tuple[int, str, str]] = [(0, "F.Cu", "signal")]
for n, lid in enumerate(inner_signal_ids, start=1):
kname = f"In{n}.Cu"
epro_to_kicad[lid] = kname
layers_in_order.append((n, kname, "signal"))
layers_in_order.append((31, "B.Cu", "signal"))
# User/tech layers — only emit the ones the board actually uses, plus a
# few KiCad expects to exist (silk/mask/paste/edge cuts) so footprints
# that reference them via standard names always parse.
required_user_layers = [
(32, "B.Adhes", "user"),
(33, "F.Adhes", "user"),
(34, "B.Paste", "user"),
(35, "F.Paste", "user"),
(36, "B.SilkS", "user"),
(37, "F.SilkS", "user"),
(38, "B.Mask", "user"),
(39, "F.Mask", "user"),
(40, "Dwgs.User", "user"),
(41, "Cmts.User", "user"),
(44, "Edge.Cuts", "user"),
(45, "Margin", "user"),
(46, "B.CrtYd", "user"),
(47, "F.CrtYd", "user"),
(48, "B.Fab", "user"),
(49, "F.Fab", "user"),
]
layers_in_order.extend(required_user_layers)
for eid, kname in EPRO2_LAYER_TO_KICAD.items():
epro_to_kicad.setdefault(eid, kname)
return _LayerMap(epro_to_kicad=epro_to_kicad, kicad_layers_in_order=layers_in_order)
def _new_uuid() -> str:
return str(_uuid.uuid4())
def _mm(v) -> float:
if v is None:
return 0.0
try:
return float(v) * MIL_TO_MM
except (TypeError, ValueError):
return 0.0
def _kicad_layer(layer_id, layer_map: _LayerMap) -> str | None:
if layer_id is None:
return None
try:
lid = int(layer_id)
except (TypeError, ValueError):
return None
return layer_map.epro_to_kicad.get(lid)
def _is_copper(layer_name: str | None) -> bool:
return bool(layer_name) and (layer_name.endswith(".Cu"))
def _build_net_map(doc: Document) -> dict[str, int]:
"""Assign integer net ids stable for this PCB. Net id 0 is reserved
for "no net" (KiCad convention)."""
net_map: dict[str, int] = {}
next_id = 1
for oid in doc.objects:
if oid.startswith('["NET",'):
try:
import json
cid = json.loads(oid)
name = str(cid[1])
except (ValueError, IndexError):
continue
if name and name not in net_map:
net_map[name] = next_id
next_id += 1
return net_map
def write_pcb(
doc: Document,
*,
project_relations: ProjectRelations | None = None,
board_origin_mm: tuple[float, float] = (100.0, 100.0),
) -> str:
"""Render a single PCB Document as kicad_pcb text.
``board_origin_mm`` is added to every coordinate so the board lands in
a sensible spot in the KiCad canvas (EPRO2 boards can be anywhere,
including with negative coordinates).
"""
if doc.doc_type != "PCB":
raise ValueError(f"expected PCB doc, got {doc.doc_type!r}")
rel = Relations.build(doc)
layer_map = _build_layer_map(doc)
net_map = _build_net_map(doc)
stats = WriteStats()
ox, oy = board_origin_mm
# ---- (layers ...) -----------------------------------------------------
layers_block = [Sym("layers")]
for ordinal, kname, ltype in layer_map.kicad_layers_in_order:
layers_block.append([ordinal, kname, Sym(ltype)])
# ---- (net N "name") ---------------------------------------------------
net_blocks: list = [[Sym("net"), 0, ""]]
for name, nid in sorted(net_map.items(), key=lambda kv: kv[1]):
net_blocks.append([Sym("net"), nid, name])
stats.nets = len(net_map)
# ---- footprints + tracks + vias + edge cuts --------------------------
footprint_blocks: list = []
track_blocks: list = []
via_blocks: list = []
graphic_blocks: list = []
# Footprints: walk PCB COMPONENTs
for cid, comp in rel.components.items():
fp_uuid = (
project_relations.resolve_footprint_doc(doc.doc_uuid, cid)
if project_relations is not None
else None
)
if not fp_uuid or fp_uuid not in project_relations.project.documents:
stats.footprints_unresolved += 1
continue
fp_doc = project_relations.project.documents[fp_uuid]
attrs = rel.attrs_dict(cid)
try:
fp_block = write_footprint_placement(
fp_doc=fp_doc,
comp_id=cid,
comp=comp,
attrs=attrs,
pcb_doc=doc,
pcb_rel=rel,
project_relations=project_relations,
layer_map=layer_map,
net_map=net_map,
origin_mm=board_origin_mm,
)
except Exception as e: # noqa: BLE001
stats.skipped += 1
continue
footprint_blocks.append(fp_block)
stats.footprints += 1
# Tracks: LINE on copper layer with netName
for oid, obj in doc.objects.items():
if obj.get("_type") != "LINE":
continue
kicad_layer = _kicad_layer(obj.get("layerId"), layer_map)
if not kicad_layer:
continue
x1 = ox + _mm(obj.get("startX"))
y1 = oy + _mm(obj.get("startY"))
x2 = ox + _mm(obj.get("endX"))
y2 = oy + _mm(obj.get("endY"))
if math.isclose(x1, x2) and math.isclose(y1, y2):
stats.skipped += 1
continue
width_mm = _mm(obj.get("width"))
if _is_copper(kicad_layer):
net_name = obj.get("netName") or ""
net_id = net_map.get(str(net_name), 0)
track_blocks.append([
Sym("segment"),
[Sym("start"), x1, y1],
[Sym("end"), x2, y2],
[Sym("width"), width_mm or 0.2],
[Sym("layer"), kicad_layer],
[Sym("net"), net_id],
[Sym("uuid"), _new_uuid()],
])
stats.segments += 1
elif kicad_layer == "Edge.Cuts":
graphic_blocks.append([
Sym("gr_line"),
[Sym("start"), x1, y1],
[Sym("end"), x2, y2],
[Sym("stroke"), [Sym("width"), width_mm or 0.1],
[Sym("type"), Sym("default")]],
[Sym("layer"), kicad_layer],
[Sym("uuid"), _new_uuid()],
])
stats.edge_cuts += 1
# POLYs — board outline lives here (path can be polyline or CIRCLE).
# Emit on Edge.Cuts as gr_line / gr_circle. Other layers in Phase 1 are
# cosmetic and skipped (Phase 2 covers silk/courtyard).
for oid, obj in doc.objects.items():
if obj.get("_type") != "POLY":
continue
kicad_layer = _kicad_layer(obj.get("layerId"), layer_map)
if kicad_layer != "Edge.Cuts":
continue
path = obj.get("path") or []
width_mm = max(_mm(obj.get("width")), 0.1)
# CIRCLE shape: ["CIRCLE", cx, cy, radius]
if len(path) == 4 and isinstance(path[0], str) and path[0].upper() == "CIRCLE":
try:
cx = ox + _mm(path[1])
cy = oy + _mm(path[2])
radius = _mm(path[3])
except (TypeError, ValueError):
continue
graphic_blocks.append([
Sym("gr_circle"),
[Sym("center"), cx, cy],
[Sym("end"), cx + radius, cy],
[Sym("stroke"), [Sym("width"), width_mm], [Sym("type"), Sym("default")]],
[Sym("fill"), Sym("none")],
[Sym("layer"), "Edge.Cuts"],
[Sym("uuid"), _new_uuid()],
])
stats.edge_cuts += 1
continue
# Polyline: emit each numeric pair as a gr_line segment chain.
prev: tuple[float, float] | None = None
i = 0
while i < len(path):
tok = path[i]
if isinstance(tok, str):
if tok.upper() == "ARC":
# ARC <radius> <endX> <endY> ...
# Emit as a chord; KiCad still parses this and the
# geometry is approximate for Phase 1.
try:
end_x = ox + _mm(path[i + 2])
end_y = oy + _mm(path[i + 3])
except (TypeError, ValueError, IndexError):
i += 1
continue
if prev is not None:
graphic_blocks.append([
Sym("gr_line"),
[Sym("start"), prev[0], prev[1]],
[Sym("end"), end_x, end_y],
[Sym("stroke"), [Sym("width"), width_mm],
[Sym("type"), Sym("default")]],
[Sym("layer"), "Edge.Cuts"],
[Sym("uuid"), _new_uuid()],
])
stats.edge_cuts += 1
prev = (end_x, end_y)
i += 4
continue
# 'L' = line-to (default)
i += 1
continue
try:
x = ox + _mm(path[i])
y = oy + _mm(path[i + 1])
except (TypeError, ValueError, IndexError):
i += 1
continue
if prev is not None:
graphic_blocks.append([
Sym("gr_line"),
[Sym("start"), prev[0], prev[1]],
[Sym("end"), x, y],
[Sym("stroke"), [Sym("width"), width_mm],
[Sym("type"), Sym("default")]],
[Sym("layer"), "Edge.Cuts"],
[Sym("uuid"), _new_uuid()],
])
stats.edge_cuts += 1
prev = (x, y)
i += 2
# ARCs on Edge.Cuts (Phase 1: only edge-cut arcs; copper arcs are rare
# in our sample and skipped to keep scope tight).
for oid, obj in doc.objects.items():
if obj.get("_type") != "ARC":
continue
kicad_layer = _kicad_layer(obj.get("layerId"), layer_map)
if kicad_layer != "Edge.Cuts":
continue
path = obj.get("path") or []
# ARC.path = [startX, startY, "ARC", radius?, endX, endY, ...] —
# representation varies; skipped if we can't decode quickly.
if len(path) < 6:
continue
try:
sx = ox + _mm(path[0])
sy = oy + _mm(path[1])
# path[2] should be "ARC" tag
ex = ox + _mm(path[-2])
ey = oy + _mm(path[-1])
except (TypeError, ValueError):
continue
# Compute mid as the geometric midpoint as a placeholder (KiCad
# gr_arc needs three points; without parsing the radius reliably we
# emit a chord-like arc which KiCad's parser still accepts).
mx, my = (sx + ex) / 2, (sy + ey) / 2
graphic_blocks.append([
Sym("gr_arc"),
[Sym("start"), sx, sy],
[Sym("mid"), mx, my],
[Sym("end"), ex, ey],
[Sym("stroke"), [Sym("width"), _mm(obj.get("width")) or 0.1],
[Sym("type"), Sym("default")]],
[Sym("layer"), "Edge.Cuts"],
[Sym("uuid"), _new_uuid()],
])
stats.edge_cuts += 1
# Vias
for oid, obj in doc.objects.items():
if obj.get("_type") != "VIA":
continue
x = ox + _mm(obj.get("centerX"))
y = oy + _mm(obj.get("centerY"))
size_mm = _mm(obj.get("viaDiameter"))
drill_mm = _mm(obj.get("holeDiameter"))
if size_mm <= 0 or drill_mm <= 0:
stats.skipped += 1
continue
net_id = net_map.get(str(obj.get("netName") or ""), 0)
via_blocks.append([
Sym("via"),
[Sym("at"), x, y],
[Sym("size"), size_mm],
[Sym("drill"), drill_mm],
[Sym("layers"), "F.Cu", "B.Cu"],
[Sym("net"), net_id],
[Sym("uuid"), _new_uuid()],
])
stats.vias += 1
title = (doc.objects.get("META") or {}).get("title") or doc.doc_uuid[:12]
pcb: list = [
Sym("kicad_pcb"),
[Sym("version"), KICAD_PCB_VERSION],
[Sym("generator"), KICAD_GENERATOR],
[Sym("general"), [Sym("thickness"), 1.6],
[Sym("legacy_teardrops"), Sym("no")]],
[Sym("paper"), "A4"],
[Sym("title_block"),
[Sym("title"), title],
[Sym("comment"), 1, f"epro2 doc_uuid: {doc.doc_uuid}"],
[Sym("comment"), 2, f"editor: {doc.head.get('editVersion','')}"]],
layers_block,
[Sym("setup"),
[Sym("pad_to_mask_clearance"), 0],
[Sym("allow_soldermask_bridges_in_footprints"), Sym("no")]],
*net_blocks,
*footprint_blocks,
*graphic_blocks,
*track_blocks,
*via_blocks,
]
write_pcb.last_stats = stats # type: ignore[attr-defined]
return to_sexpr(pcb, pretty=True)