"""Aperture templates, macro construction, and D-code assignment.
A flash cannot rotate or mirror its aperture - `LM`/`LR`/`LS` exist but are
poorly supported downstream - so the transform is carried by the aperture
itself. Rotation is an `AM` parameter (`$1`) supplied by the `AD`, which is
why one macro serves every rotation of a shape; mirroring changes the vertex
list, so a mirrored shape is simply different macro content.
Everything built here flashes. A pad shape a macro cannot express exactly is
composed from primitives or linearized, never turned into a region: 4.10
requires that all pads are flashed and all flashes are pads, so a `G36`
surface is not a pad as far as CAM is concerned whatever it looks like.
"""
from __future__ import annotations
import math
from collections.abc import Iterable, Sequence
from .model import Aperture, AttrSet, Macro, render_attrs
from .units import decimal
MAX_OUTLINE_VERTICES = 5000
"""4.5.1.6's per-primitive ceiling, counted as coordinate pairs minus one.
A macro may hold any number of primitives, so a shape needing more can be
decomposed; nothing real should come close. Pours are not affected - a pour
is a region, and regions carry no vertex limit, which is why 4.5.1.6 directs
them there.
"""
ROTATION = "$1"
"""Every primitive takes the macro's rotation argument, so a composition
rotates as one shape about the flash point."""
[docs]
class ApertureError(ValueError):
"""A shape cannot be expressed as an aperture."""
# --------------------------------------------------------------------------
# macro primitives
[docs]
def circle(
diameter: float,
x: float = 0.0,
y: float = 0.0,
*,
on: bool = True,
rotation: str = ROTATION,
) -> str:
"""A code 1 circle primitive, rotated about the macro origin."""
return f"1,{int(on)},{decimal(diameter)},{decimal(x)},{decimal(y)},{rotation}"
[docs]
def center_line(
width: float,
height: float,
x: float = 0.0,
y: float = 0.0,
*,
on: bool = True,
rotation: str = ROTATION,
) -> str:
"""A code 21 center line primitive: a rectangle about (x, y)."""
return (
f"21,{int(on)},{decimal(width)},{decimal(height)},"
f"{decimal(x)},{decimal(y)},{rotation}"
)
[docs]
def vector_line(
width: float,
start: tuple[float, float],
end: tuple[float, float],
*,
on: bool = True,
rotation: str = ROTATION,
) -> str:
"""A code 20 vector line primitive: a stroke with square ends."""
return (
f"20,{int(on)},{decimal(width)},{decimal(start[0])},{decimal(start[1])},"
f"{decimal(end[0])},{decimal(end[1])},{rotation}"
)
[docs]
def outline(
points: Sequence[tuple[float, float]], *, on: bool = True, rotation: str = ROTATION
) -> str:
"""A code 4 outline primitive from a closed ring of straight segments.
The ring is closed here if the caller has not closed it. Straight
segments only: a macro outline has no arc, which is the single real
limit of the aperture system.
Raises:
ApertureError: fewer than three distinct points, or more vertices
than 4.5.1.6 allows in one primitive.
"""
ring = list(points)
if ring and ring[0] != ring[-1]:
ring.append(ring[0])
vertices = len(ring) - 1
if vertices < 3:
raise ApertureError(f"outline primitive needs three vertices, got {vertices}")
if vertices > MAX_OUTLINE_VERTICES:
raise ApertureError(
f"outline primitive holds at most {MAX_OUTLINE_VERTICES} vertices, "
f"got {vertices}; decompose the shape or loosen the linearization"
)
coords = ",".join(f"{decimal(x)},{decimal(y)}" for x, y in ring)
return f"4,{int(on)},{vertices},{coords},{rotation}"
[docs]
def polygon(
diameter: float,
vertices: int,
x: float = 0.0,
y: float = 0.0,
*,
on: bool = True,
rotation: str = ROTATION,
) -> str:
"""A code 5 regular polygon primitive."""
return (
f"5,{int(on)},{vertices},{decimal(x)},{decimal(y)},"
f"{decimal(diameter)},{rotation}"
)
[docs]
def thermal(
outer: float,
inner: float,
gap: float,
x: float = 0.0,
y: float = 0.0,
*,
rotation: str = ROTATION,
) -> str:
"""A code 7 thermal primitive. It has no exposure parameter."""
return (
f"7,{decimal(x)},{decimal(y)},{decimal(outer)},"
f"{decimal(inner)},{decimal(gap)},{rotation}"
)
# --------------------------------------------------------------------------
# standard templates
#
# A standard template cannot rotate (except P) and its optional hole must be
# round, centered and strictly inside the aperture. Anything else is a macro.
def _hole_params(size: float, hole: float | None) -> tuple[float, ...]:
if hole is None:
return ()
if hole <= 0 or hole >= size:
raise ApertureError(
f"a standard aperture hole must be > 0 and strictly inside the "
f"aperture: hole {hole} in {size}"
)
return (hole,)
[docs]
def circle_aperture(
diameter: float, *, hole: float | None = None, attrs: AttrSet = ()
) -> Aperture:
"""`C,<diameter>[X<hole>]`. Rotation is irrelevant to a circle."""
return Aperture("C", (diameter, *_hole_params(diameter, hole)), attrs)
[docs]
def rect_aperture(
width: float, height: float, *, hole: float | None = None, attrs: AttrSet = ()
) -> Aperture:
"""`R,<w>X<h>[X<hole>]`, axis-aligned."""
return Aperture(
"R", (width, height, *_hole_params(min(width, height), hole)), attrs
)
[docs]
def obround_aperture(
width: float, height: float, *, hole: float | None = None, attrs: AttrSet = ()
) -> Aperture:
"""`O,<w>X<h>[X<hole>]`, axis-aligned; a capsule at 0 or 90 degrees."""
return Aperture(
"O", (width, height, *_hole_params(min(width, height), hole)), attrs
)
[docs]
def polygon_aperture(
diameter: float,
vertices: int,
rotation: float = 0.0,
*,
hole: float | None = None,
attrs: AttrSet = (),
) -> Aperture:
"""`P,<outer>X<n>[X<rot>[X<hole>]]`, the only rotatable standard template.
Raises:
ApertureError: the vertex count is outside 3 to 12.
"""
if not 3 <= vertices <= 12:
raise ApertureError(
f"a regular polygon aperture takes 3 to 12 vertices, got {vertices}"
)
return Aperture(
"P", (diameter, vertices, rotation, *_hole_params(diameter, hole)), attrs
)
# --------------------------------------------------------------------------
# shape builders
#
# Each returns an aperture whose last AD modifier is the rotation the macro
# takes as $1, so the macro is shared across rotations and the rotation
# stays in the aperture key. With `baked`, the rotation is applied to the
# primitive coordinates instead, every primitive takes a literal 0 and the
# AD has no rotation modifier, so a reader that mishandles the rotation
# argument has nothing to mishandle.
Point = tuple[float, float]
BAKED = "0"
"""The primitive rotation of a baked macro."""
[docs]
def rotate(points: Iterable[Point], rotation: float) -> list[Point]:
"""Points rotated counterclockwise about the macro origin, in degrees,
which is what a reader does with a macro's rotation argument."""
c, s = math.cos(math.radians(rotation)), math.sin(math.radians(rotation))
return [(x * c - y * s, x * s + y * c) for x, y in points]
[docs]
def macro_aperture(
body: Sequence[str],
params: Sequence[float],
rotation: float | None,
attrs: AttrSet = (),
) -> Aperture:
"""Instantiate a macro built from primitive lines.
`rotation` is appended as the last `AD` modifier, which is the `$1` the
primitives reference. None is a baked macro: its primitives reference no
rotation and the `AD` carries none.
"""
rotated = () if rotation is None else (rotation,)
return Aperture(Macro(tuple(body)), (*params, *rotated), attrs)
def _box(width: float, height: float, x: float = 0.0, y: float = 0.0) -> list[Point]:
w, h = width / 2, height / 2
return [(x - w, y - h), (x + w, y - h), (x + w, y + h), (x - w, y + h)]
[docs]
def rotated_rect(
width: float,
height: float,
rotation: float,
attrs: AttrSet = (),
*,
baked: bool = False,
) -> Aperture:
"""A rectangle at an arbitrary angle.
Prefer `rect_aperture` at 0 or 90 degrees; the standard template is what
every consumer handles best.
Args:
baked: apply the rotation to the coordinates rather than pass it to
the macro.
"""
if baked:
# a center line at rotation 0 is axis-aligned, so the rotated
# rectangle is an outline of its corners
ring = rotate(_box(width, height), rotation)
body = [comment("rectangle"), outline(ring, rotation=BAKED)]
return macro_aperture(body, [], None, attrs)
return macro_aperture(
[comment("rectangle"), center_line(width, height)], [], rotation, attrs
)
[docs]
def rotated_capsule(
width: float,
height: float,
rotation: float,
attrs: AttrSet = (),
*,
baked: bool = False,
) -> Aperture:
"""A capsule (obround) at an arbitrary angle, exact rather than
linearized: a rectangular body between two end circles.
Args:
width: length of the enclosing box along X.
height: length along Y. The smaller dimension is the cap diameter.
baked: apply the rotation to the coordinates rather than pass it to
the macro.
"""
if width >= height:
cap, reach, body = height, (width - height) / 2, (width - height, height)
centers = [(-reach, 0.0), (reach, 0.0)]
else:
cap, reach, body = width, (height - width) / 2, (width, height - width)
centers = [(0.0, -reach), (0.0, reach)]
if baked:
# the body is an outline rather than a code 20 vector line: 20 is
# what readers get wrong most often, and 4 is what they all handle
lines = [
comment("capsule"),
outline(rotate(_box(*body), rotation), rotation=BAKED),
]
lines += [
circle(cap, x, y, rotation=BAKED) for x, y in rotate(centers, rotation)
]
return macro_aperture(lines, [], None, attrs)
lines = [comment("capsule"), center_line(*body)]
lines += [circle(cap, x, y) for x, y in centers]
return macro_aperture(lines, [], rotation, attrs)
[docs]
def rounded_rect(
width: float,
height: float,
radius: float,
rotation: float,
attrs: AttrSet = (),
*,
baked: bool = False,
) -> Aperture:
"""A rectangle with round corners, exact: two overlapping center lines
plus a circle at each corner. This is how the official `sample_macro.gbr`
builds one, and it avoids linearizing a shape that has a closed form.
Args:
baked: apply the rotation to the coordinates rather than pass it to
the macro.
Raises:
ApertureError: the radius does not fit in the rectangle.
"""
if radius <= 0 or 2 * radius > min(width, height):
raise ApertureError(f"corner radius {radius} does not fit in {width}x{height}")
dx, dy = width / 2 - radius, height / 2 - radius
corners = [(dx, dy), (-dx, dy), (-dx, -dy), (dx, -dy)]
bars = [(width, height - 2 * radius), (width - 2 * radius, height)]
if baked:
lines = [comment("rounded rectangle")]
lines += [outline(rotate(_box(*bar), rotation), rotation=BAKED) for bar in bars]
lines += [
circle(2 * radius, x, y, rotation=BAKED)
for x, y in rotate(corners, rotation)
]
return macro_aperture(lines, [], None, attrs)
lines = [comment("rounded rectangle")]
lines += [center_line(*bar) for bar in bars]
lines += [circle(2 * radius, x, y) for x, y in corners]
return macro_aperture(lines, [], rotation, attrs)
[docs]
def outlines_aperture(
islands: Sequence[tuple[Sequence[Point], Sequence[Sequence[Point]]]],
rotation: float,
attrs: AttrSet = (),
*,
label: str = "outline",
baked: bool = False,
) -> Aperture:
"""Straight-edged outlines with holes, in the aperture's own frame.
Args:
islands: each outer ring with its holes, unrotated. A hole is an
exposure-off outline, which only clears within this aperture.
label: the macro's comment line.
baked: apply the rotation to the coordinates rather than pass it to
the macro.
"""
token = BAKED if baked else ROTATION
def ring(points: Sequence[Point]) -> list[Point]:
return rotate(points, rotation) if baked else list(points)
lines = [comment(label)]
for outer, holes in islands:
lines.append(outline(ring(outer), rotation=token))
lines += [outline(ring(hole), on=False, rotation=token) for hole in holes]
return macro_aperture(lines, [], None if baked else rotation, attrs)
[docs]
def outline_aperture(
points: Sequence[Point],
rotation: float,
attrs: AttrSet = (),
*,
mirrored: bool = False,
baked: bool = False,
) -> Aperture:
"""A straight-edged outline in the aperture's own frame.
Args:
points: the ring, in the unrotated aperture frame.
mirrored: mirror the vertex list across the Y axis. Mirroring cannot
be an `AD` parameter the way rotation can, so it becomes
different macro content - which is the normal case, since every
bottom-side placement is mirrored.
baked: apply the rotation to the coordinates rather than pass it to
the macro.
"""
ring = [(-x, y) for x, y in reversed(points)] if mirrored else list(points)
return outlines_aperture([(ring, [])], rotation, attrs, baked=baked)
[docs]
def donut(outer: float, inner: float, attrs: AttrSet = ()) -> Aperture:
"""An annular pad: a circle with a smaller centered round hole.
The hole is transparent, not clear - 4.4.6, "holes do not clear the
objects under them" - so a donut pad over a same-net pour leaves the pour
showing through the middle, which is the real copper.
"""
return circle_aperture(outer, hole=inner, attrs=attrs)
[docs]
def regular_polygon_points(diameter: float, vertices: int) -> list[tuple[float, float]]:
"""The vertex ring of a regular polygon, for callers that need it as an
outline rather than as the `P` template."""
radius = diameter / 2
return [
(
radius * math.cos(2 * math.pi * i / vertices),
radius * math.sin(2 * math.pi * i / vertices),
)
for i in range(vertices)
]
# --------------------------------------------------------------------------
# table assembly
[docs]
def aperture_key(aperture: Aperture) -> tuple[str, str]:
"""The sort key that fixes an aperture's D-code.
Sorting rather than first-intern order is what keeps golden files stable
under a design edit: with first-use numbering one added pad renumbers
every aperture after it.
"""
return (
f"{aperture.template_name}," + "X".join(decimal(p) for p in aperture.params),
render_attrs(aperture.attrs),
)
[docs]
def assign(apertures: set[Aperture]) -> dict[Aperture, int]:
"""Give every aperture a D-code, from 10 upwards, by sorted key."""
return {a: 10 + i for i, a in enumerate(sorted(apertures, key=aperture_key))}
[docs]
def macros(apertures: set[Aperture]) -> list[Macro]:
"""Every macro the apertures instantiate, deduplicated by content and
ordered by generated name."""
found = {a.macro.name: a.macro for a in apertures if a.macro is not None}
return [found[name] for name in sorted(found)]