"""Serialize a `GerberFile` to RS-274X text.
The header order is fixed: `TF` file attributes, `FS`, `MO`, `AM` macros,
`AD` apertures with their `TA` runs, then the body, then `M02`. The body is
a state machine over polarity, the current aperture, the plot mode, the
attribute dictionary and the current point; every one of those is modal, and
several of the defects this format is prone to are a missed modal update
rather than a malformed word.
Output is deterministic: no clock is read here (the creation date is
injected), D-codes come from a sorted key, and macros are emitted in name
order.
"""
from __future__ import annotations
from .apertures import assign, circle_aperture, macros
from .contours import scrub, split_arc, validate
from .model import (
ArcObj,
Aperture,
AttrSet,
Contour,
Draw,
Flash,
GerberFile,
FileMeta,
GraphicObject,
Polarity,
Region,
Seg,
Surface,
escape_field,
)
from .units import coord, decimal
Point = tuple[float, float]
[docs]
def emit_gerber(file: GerberFile, meta: FileMeta) -> str:
"""The complete text of one Gerber file, `M02*` included."""
apertures = _apertures(file)
dcodes = assign(apertures)
lines: list[str] = []
lines += _file_attributes(file, meta)
if meta.compat.names:
lines.append(f"G04 Compatibility: {' '.join(meta.compat.names)}*")
lines.append("%FSLAX46Y46*%")
lines.append("%MOMM*%")
for macro in macros(apertures):
lines.append(f"%AM{macro.name}*")
lines.append("*\n".join(macro.body) + "*%")
_emit_apertures(lines, dcodes)
lines.append("%LPD*%")
lines.append("G75*")
lines.append("G01*")
_Body(lines, dcodes).run(file.objects)
lines.append("M02*")
return "\n".join(lines) + "\n"
def _apertures(file: GerberFile) -> set[Aperture]:
"""Every aperture the objects use.
A file made only of regions still needs one: a region uses no aperture,
but a current aperture must be selected, and the convention is a
zero-size circle that images nothing.
"""
found = {
obj.aperture for obj in file.objects if isinstance(obj, (Flash, Draw, ArcObj))
}
if not found and any(isinstance(o, (Region, Surface)) for o in file.objects):
found.add(circle_aperture(0.0))
return found
def _file_attributes(file: GerberFile, meta: FileMeta) -> list[str]:
software = meta.software
project = meta.project
lines = [
_attr_command(
"TF",
".GenerationSoftware",
(software.vendor, software.application, software.version),
),
_attr_command("TF", ".CreationDate", (meta.creation_date,)),
_attr_command(
"TF", ".ProjectId", (project.name, project.guid, project.revision)
),
# the identifier field is optional; the spec suggests a GUID and a
# literal like "Original" would be another tool's convention, not a
# spec value
_attr_command("TF", ".SameCoordinates", ()),
_attr_command("TF", ".FileFunction", tuple(file.function.render().split(","))),
]
lines.append(_attr_command("TF", ".FilePolarity", (file.polarity,)))
return lines
def _attr_command(kind: str, name: str, values: tuple[str, ...]) -> str:
body = "".join("," + escape_field(v) for v in values)
return f"%{kind}{name}{body}*%"
def _emit_apertures(lines: list[str], dcodes: dict[Aperture, int]) -> None:
"""`AD` commands in D-code order, each under its own `TA` run.
Aperture attributes are diffed the same way object attributes are, and
cleared before an `AD` that is meant to carry none - otherwise the
dictionary leaks the previous aperture's function onto the next one.
"""
current: dict[str, tuple[str, ...]] = {}
for aperture, code in sorted(dcodes.items(), key=lambda item: item[1]):
_diff(lines, "TA", current, dict(aperture.attrs))
params = "X".join(decimal(p) for p in aperture.params)
tail = f",{params}" if params else ""
lines.append(f"%ADD{code}{aperture.template_name}{tail}*%")
_diff(lines, "TA", current, {})
UNDELETABLE = frozenset({".C"})
"""Attribute names that cannot be spelled in a `TD`.
`.C` is the one. The spec's formal grammar guards it with a lookahead -
`'.C' &','`, commented "To prevent this rule from parsing .CRot etc." - so
`.C` only matches when a comma follows it. That is what keeps `%TO.C,U1*%`
from being read as the start of `.CRot`, but it also means `%TD.C*%`, where
a `*` follows, matches no alternative at all: the other names are plain
literals and `user_name` "cannot start with a dot".
5.5's prose allows it ("the name of the attribute to delete") and the
grammar does not, and the grammar is what the Reference Gerber Viewer's
syntax checker implements - it rejects `%TD.C*%` and then aborts, leaving the
rest of the file unchecked. So the command is never emitted; see `_diff`.
"""
[docs]
def needs_reset(
current: dict[str, tuple[str, ...]], desired: dict[str, tuple[str, ...]]
) -> bool:
"""Whether getting from `current` to `desired` needs a bare `%TD*%`.
True when an attribute that has to go cannot be named in a `TD`.
"""
return any(
name in UNDELETABLE and current[name] != desired.get(name) for name in current
)
def _diff(
lines: list[str],
kind: str,
current: dict[str, tuple[str, ...]],
desired: dict[str, tuple[str, ...]],
) -> None:
"""Bring the attribute dictionary from `current` to `desired`.
Deletion is per name (`%TD.N*%`) wherever the name can be spelled in a
`TD` at all, because a bare `%TD*%` drops every aperture and object
attribute at once and then has to re-emit everything still wanted, which
is the easy way to lose one.
`UNDELETABLE` names force the bare form instead, since there is no other
way to clear them; everything desired is then re-emitted from an empty
dictionary. A caller tracking more than one dictionary must pre-empt that
with `needs_reset`, because the file has a single dictionary and a bare
`TD` empties all of it - see `_Body._set_attrs`.
"""
stale = [name for name in current if current[name] != desired.get(name)]
if needs_reset(current, desired):
lines.append("%TD*%")
current.clear()
else:
for name in stale:
lines.append(f"%TD{name}*%")
del current[name]
for name, values in desired.items():
if current.get(name) != values:
lines.append(_attr_command(kind, name, values))
current[name] = values
class _Body:
"""The modal plot state while objects are written."""
def __init__(self, lines: list[str], dcodes: dict[Aperture, int]) -> None:
self.lines = lines
self.dcodes = dcodes
self.aperture: int | None = None
self.polarity = Polarity.DARK
self.mode = "G01"
self.point: Point | None = None
# TA and TO live in one dictionary in the format, but they are set
# by different commands, so they are tracked apart here. The two
# namespaces are disjoint in practice - no standard name is both an
# aperture and an object attribute.
self.obj_attrs: dict[str, tuple[str, ...]] = {}
self.aper_attrs: dict[str, tuple[str, ...]] = {}
def run(self, objects: list[GraphicObject]) -> None:
for obj in objects:
match obj:
case Flash():
self._flash(obj)
case Draw():
self._draw(obj)
case ArcObj():
self._arc(obj)
case Region():
self._region(obj.contours, obj.polarity, obj.attrs, obj.aper_attrs)
case Surface():
self._surface(obj)
self._polarity(Polarity.DARK)
# -- state --------------------------------------------------------
def _select(self, aperture: Aperture) -> None:
code = self.dcodes[aperture]
if self.aperture != code:
self.lines.append(f"D{code}*")
self.aperture = code
def _polarity(self, polarity: Polarity) -> None:
if self.polarity != polarity:
self.lines.append("%LPC*%" if polarity is Polarity.CLEAR else "%LPD*%")
self.polarity = polarity
def _plot(self, mode: str) -> None:
# modal: after a G02 or G03 a straight D01 without I/J is invalid, so
# G01 has to be re-emitted rather than assumed from the header
if self.mode != mode:
self.lines.append(f"{mode}*")
self.mode = mode
def _set_attrs(self, obj_attrs: AttrSet, aper_attrs: AttrSet = ()) -> None:
"""Set the dictionary for the object about to be written.
Regions take their aperture attributes from the dictionary as it
stands at `G36` (5.3.1); that is the only way a pour carries
`Conductor` or a tie carries `EtchedComponent`. Every other object
asks for no `TA`, so the diff clears a region's attributes after its
`G37` with no special case.
A bare `%TD*%` is decided here rather than inside either diff. The
file has one attribute dictionary while this tracks two, so a reset
forced by the object attributes also clears the aperture attributes;
letting the `TO` diff emit it on its own would leave `aper_attrs`
claiming a `Conductor` the file had just dropped, and the next pour
would quietly image with no aperture function at all.
"""
want_aper = dict(aper_attrs)
want_obj = dict(obj_attrs)
if needs_reset(self.aper_attrs, want_aper) or needs_reset(
self.obj_attrs, want_obj
):
self.lines.append("%TD*%")
self.aper_attrs.clear()
self.obj_attrs.clear()
_diff(self.lines, "TA", self.aper_attrs, want_aper)
_diff(self.lines, "TO", self.obj_attrs, want_obj)
def _move(self, point: Point) -> None:
if self.point is None or self.point != point:
self.lines.append(f"X{coord(point[0])}Y{coord(point[1])}D02*")
self.point = point
# -- objects ------------------------------------------------------
def _flash(self, flash: Flash) -> None:
self._polarity(Polarity.DARK)
self._select(flash.aperture)
self._set_attrs(flash.attrs)
self.lines.append(f"X{coord(flash.x)}Y{coord(flash.y)}D03*")
self.point = (flash.x, flash.y)
def _draw(self, draw: Draw) -> None:
self._polarity(Polarity.DARK)
self._select(draw.aperture)
self._set_attrs(draw.attrs)
self._plot("G01")
self._move((draw.x1, draw.y1))
self.lines.append(f"X{coord(draw.x2)}Y{coord(draw.y2)}D01*")
self.point = (draw.x2, draw.y2)
def _arc(self, arc: ArcObj) -> None:
self._polarity(Polarity.DARK)
self._select(arc.aperture)
self._set_attrs(arc.attrs)
self._plot("G03" if arc.ccw else "G02")
self._move((arc.x1, arc.y1))
start, end = (arc.x1, arc.y1), (arc.x2, arc.y2)
center = (arc.cx, arc.cy)
for point in [*split_arc(start, end, center, arc.ccw), end]:
self._arc_step(point, center)
def _arc_step(self, end: Point, center: Point) -> None:
assert self.point is not None
i, j = center[0] - self.point[0], center[1] - self.point[1]
self.lines.append(f"X{coord(end[0])}Y{coord(end[1])}I{coord(i)}J{coord(j)}D01*")
self.point = end
def _surface(self, surface: Surface) -> None:
"""An island and its holes, as the dark/clear pair 4.10.4 recommends
over cut-ins.
The holes inherit the island's object attributes, deliberately: the
dictionary is still set when they are emitted, and the cleared area
does belong to that net's surface.
"""
self._region(
(surface.island,), Polarity.DARK, surface.attrs, surface.aper_attrs
)
for hole in surface.holes:
self._region((hole,), Polarity.CLEAR, surface.attrs, surface.aper_attrs)
def _region(
self,
contours: tuple[Contour, ...],
polarity: Polarity,
attrs: AttrSet,
aper_attrs: AttrSet,
) -> None:
if not contours:
return
self._polarity(polarity)
# a region has no aperture, but one must be current; 4.10 says the
# D01s inside G36 do not use it
if self.aperture is None and self.dcodes:
self._select(min(self.dcodes, key=lambda a: self.dcodes[a]))
self._set_attrs(attrs, aper_attrs)
self.lines.append("G36*")
for contour in contours:
clean = scrub(contour)
validate(clean)
self._contour(clean)
self.lines.append("G37*")
# 4.10.1: a D02 starts a contour, so the next one must not inherit a
# current point from this region
self.point = None
def _contour(self, contour: Contour) -> None:
self.lines.append(f"X{coord(contour.start[0])}Y{coord(contour.start[1])}D02*")
self.point = contour.start
self._plot("G01")
for segment in contour.segments:
if isinstance(segment, Seg):
self._plot("G01")
self.lines.append(f"X{coord(segment.x)}Y{coord(segment.y)}D01*")
self.point = (segment.x, segment.y)
else:
self._plot("G03" if segment.ccw else "G02")
self._arc_step((segment.x, segment.y), (segment.cx, segment.cy))