# SPDX-License-Identifier: Apache-2.0
"""Lid decoration builders."""
from __future__ import annotations
from dataclasses import dataclass, fields, replace
from typing import TYPE_CHECKING, Any
from pyboxbuilder.enums import ColorMode, LabelFinial, LabelMode, LabelShape, PatternType
if TYPE_CHECKING:
from pyboxbuilder import Color
MIN_TEXT_HEIGHT_MM = 4.0
"""Shortest a label may print before it is skipped instead (FR-020).
Below this an FDM printer cannot hold the strokes of a letter apart, so the
label comes out as a smudge; skipping it leaves a clean lid instead.
"""
MAX_TEXT_HEIGHT_MM = 16.0
"""Tallest a label is scaled to by default so short words on large lids do not look overwhelming."""
LID_BORDER_MM = 8.0
"""Solid margin around everything on a lid — its pattern and its label alike.
The border is what the lid is picked up and located by, and on a sliding lid it
is what rides in the grooves, so it has to survive whatever is put on the face.
**One number** covers both: a label set to a different margin from the pattern
reads as a mistake, because what a viewer sees is a single band of plain lid
and one thing crossing it.
"""
LABEL_INSET_MM = 2.0
"""How far the label sits *inside* the lid's border, beyond the border itself.
The border is a band of plain lid, and a label that runs to its inner edge
reads as though it is touching the pattern rather than sitting in a space of
its own. Two millimetres is enough to separate them without shrinking the text
noticeably — on a card lid it costs about half a millimetre of cap height.
"""
BORDER_MARGIN_MM = LID_BORDER_MM + LABEL_INSET_MM
"""Margin an auto-sized label keeps clear of the lid's edge.
The lid's border plus the label's own inset, so the text sits inside the band
the pattern stops at rather than level with it."""
PATTERN_BORDER_MM = LID_BORDER_MM
"""Solid margin left around a lid's pattern, when nothing else says."""
[docs]
@dataclass(frozen=True)
class PatternBuilder:
"""Through-hole pattern configuration for a lid.
A pattern is specified by the **pitch** between holes and the **web** left
between them. The web is the one with a right answer — it is what prints,
and what carries the lid — so it is the one to state; the hole size follows
from the two.
"""
type: PatternType | str = PatternType.HEX
"""Which pattern to cut. See :class:`~pyboxbuilder.enums.PatternType`."""
colors: tuple[Color | str, ...] | list[Color | str] = ()
"""Accent colours for the pattern's top layer, if any."""
spacing: float | None = None
"""Centre-to-centre distance between holes, in mm.
``None`` derives it from the area being filled — an eighth of its shorter
side, never below 5mm — so the same pattern reads the same on a token lid
and a card lid."""
web: float | None = None
"""Material left between neighbouring holes, in mm.
``None`` uses :data:`~pyboxbuilder.lid.pattern.DEFAULT_WEB_MM`. Raising it
thickens the ribs without changing the pitch; the holes shrink to make
room."""
border: float | None = None
"""Solid margin around the whole pattern, in mm.
``None`` uses :data:`PATTERN_BORDER_MM`. ``0`` runs the pattern to the
lid's edge, which is rarely what a lid wants — see that constant."""
inlay: bool | None = None
"""When True, inlay the pattern flush into the lid; ``None`` defaults to ``True`` for multi-colour patterns."""
through_inlay: bool | tuple[int, ...] = False
"""When True, colored inlays extend completely through the lid thickness instead of just the top layer.
Can also be a tuple of color indices (e.g. (0,)) that extend through the lid while others remain top-layer."""
inlay_depth_mm: float | None = None
"""Depth in mm of top-layer inlays (defaults to INLAY_DEPTH_MM = 0.6mm)."""
through_holes: bool = False
"""When True in inlay mode, cutouts/holes inside pattern shapes penetrate completely through the lid."""
hole_ratio: float = 0.5
"""Relative inner hole size for shapes with holes (such as RING), from 0.1 to 0.9."""
backing_pattern: PatternType | str | None = PatternType.HEX
"""Lattice pattern cut into the back of the lid behind top-layer inlays to reduce plastic use (defaults to HEX)."""
backing_spacing: float | None = None
"""Centre-to-centre distance between holes in the backing lattice, in mm; ``None`` derives from lid size."""
backing_web: float | None = None
"""Material left between neighbouring holes in the backing lattice, in mm; ``None`` uses default web."""
top_skin_mm: float | None = None
"""Solid top skin thickness in mm supporting thin colored inlays above the backing lattice (defaults to 0.8mm)."""
def __post_init__(self) -> None:
"""Convert list through_inlay to tuple and coerce string type."""
if isinstance(self.type, str):
object.__setattr__(self, "type", PatternType(self.type.lower()))
if isinstance(self.backing_pattern, str):
object.__setattr__(self, "backing_pattern", PatternType(self.backing_pattern.lower()))
if isinstance(self.through_inlay, list):
object.__setattr__(self, "through_inlay", tuple(self.through_inlay))
if isinstance(self.colors, (list, tuple)):
from pybosl2 import Color
object.__setattr__(
self,
"colors",
tuple(c if isinstance(c, Color) else Color(c) for c in self.colors),
)
if self.inlay is None:
is_multicolor_tessellation = self.type in (
PatternType.STEPPED_CUBE,
PatternType.TUMBLING_BLOCKS,
PatternType.CHEVRON,
PatternType.PENROSE,
PatternType.AMMANN_BEENKER,
)
object.__setattr__(self, "inlay", bool(self.colors) or is_multicolor_tessellation)
[docs]
@classmethod
def stepped_cube(
cls,
colors: tuple[Color | str, ...] | list[Color | str] = (),
*,
peak_color: Color | str | None = None,
valley_color: Color | str | None = None,
left_color: Color | str | None = None,
right_color: Color | str | None = None,
spacing: float | None = None,
web: float | None = None,
border: float | None = None,
backing_pattern: PatternType | str | None = PatternType.HEX,
**kwargs: Any,
) -> PatternBuilder:
"""Create a 4-colour stepped 3D cube & diamond tessellation pattern.
Colours can be passed as a sequence ``colors=(peak, valley, left, right)``
or individually via ``peak_color``, ``valley_color``, ``left_color``, and
``right_color`` (any omitted face falls back to the default stepped-cube palette).
"""
from pybosl2 import Color
from pyboxbuilder.lid.pattern import _DEFAULT_TESSELLATION_PALETTES
resolved_colors: tuple[Color | str, ...] | list[Color | str] = colors
if not resolved_colors and any(
c is not None for c in (peak_color, valley_color, left_color, right_color)
):
defaults = _DEFAULT_TESSELLATION_PALETTES["stepped_cube"]
resolved_colors = (
Color(peak_color) if isinstance(peak_color, str) else (peak_color or defaults[0]),
Color(valley_color) if isinstance(valley_color, str) else (valley_color or defaults[1]),
Color(left_color) if isinstance(left_color, str) else (left_color or defaults[2]),
Color(right_color) if isinstance(right_color, str) else (right_color or defaults[3]),
)
return cls(
type=PatternType.STEPPED_CUBE,
colors=resolved_colors,
spacing=spacing,
web=web,
border=border,
inlay=kwargs.pop("inlay", True),
backing_pattern=backing_pattern,
**kwargs,
)
[docs]
@classmethod
def penrose(
cls,
colors: tuple[Color | str, ...] | list[Color | str] = (),
*,
thick_colors: tuple[Color | str, ...] | list[Color | str] | Color | str | None = None,
thin_colors: tuple[Color | str, ...] | list[Color | str] | Color | str | None = None,
spacing: float | None = None,
web: float | None = None,
border: float | None = None,
backing_pattern: PatternType | str | None = PatternType.HEX,
**kwargs: Any,
) -> PatternBuilder:
"""Create a multi-colour 10-fold quasiperiodic Penrose rhombus tessellation pattern.
Supports 2, 3, 4, 5 or more colours via ``colors=(...)``, or separate
``thick_colors`` (72° rhombi) and ``thin_colors`` (36° rhombi).
"""
from pybosl2 import Color
from pyboxbuilder.lid.pattern import _DEFAULT_TESSELLATION_PALETTES
def _norm_list(val: Any, fallback: tuple[Color, ...]) -> list[Color]:
if val is None:
return list(fallback)
if isinstance(val, (str, Color)):
c = val if isinstance(val, Color) else Color(val)
return [c, c]
items = [x if isinstance(x, Color) else Color(x) for x in val]
if len(items) == 1:
return [items[0], items[0]]
return items
resolved_colors: tuple[Color | str, ...] | list[Color | str] = colors
if not resolved_colors and (thick_colors is not None or thin_colors is not None):
defaults = _DEFAULT_TESSELLATION_PALETTES["penrose"]
tk = _norm_list(thick_colors, defaults[:2])
tn = _norm_list(thin_colors, defaults[2:4])
resolved_colors = (*tk[:2], *tn[:2])
return cls(
type=PatternType.PENROSE,
colors=resolved_colors,
spacing=spacing,
web=web,
border=border,
inlay=kwargs.pop("inlay", True),
backing_pattern=backing_pattern,
**kwargs,
)
@property
def border_width(self) -> float:
"""The border, resolved."""
return PATTERN_BORDER_MM if self.border is None else max(0.0, self.border)
[docs]
@dataclass(frozen=True)
class LidBuilder:
"""Lid decoration configuration.
One of these usually describes a *style* rather than a single lid — the
same frame, pattern and colours across a whole insert — so
:meth:`titled` makes a copy carrying one box's text instead of repeating
the style at every box (FR-000b)::
LEAF = LidBuilder(label_mode=LabelMode.FRAMELESS, diagonal=True,
pattern=PatternBuilder(PatternType.HEX))
...
project.box(BoxType.SLIDING, "Favor", lid=LEAF.titled("Favors"))
Examples:
A frameless diagonal label on a hex-patterned lid:
.. pythonscad-example::
project = Project("FancyGame", game_box_size=(300, 200, 80))
STYLE = LidBuilder(
label_mode=LabelMode.FRAMELESS,
diagonal=True,
pattern=PatternBuilder(PatternType.HEX, spacing=10.0),
)
project.box(
BoxType.SLIDING, "Treasure", size=(90, 70, 40),
lid=STYLE.titled("Treasure", text_color=Color("gold")),
)
project.show(only="Treasure")
"""
text: str | None = None
"""Label text; ``None`` leaves the lid unlabelled."""
label_mode: LabelMode | None = None
"""Framed (border + hatching behind the text) or frameless (text only).
``None`` means :attr:`~pyboxbuilder.enums.LabelMode.FRAMED`. It is spelled
as ``None`` rather than defaulted directly so a per-mode override can tell
"I want framed" from "I said nothing about the frame" — see
:meth:`for_mode`."""
label_shape: LabelShape | str | None = None
"""Plaque silhouette for framed labels (``RECT``, ``PILL``, ``CHAMFERED``,
``HEXAGON``, ``HEX_BRACKET``, ``NOTCHED``, ``RIBBON``, ``DOUBLE_FRAME``,
``UNDERLINE``, ``OVAL``, ``SCALLOPED``, ``BRACKET``, ``SHIELD``, ``SCROLL``,
``CORNER_STUD``, or ``ORNATE_FRAME``).
``None`` defaults to :attr:`~pyboxbuilder.enums.LabelShape.RECT`. Non-rect
decorative shapes default to a clean solid interior plaque unless
``label_solid_background=False`` is passed explicitly."""
font: str | None = None
"""Font family/style for lid label text (e.g. ``"Futura:style=Bold"``);
``None`` uses the library default (``"Liberation Sans:style=Bold"``)."""
text_spacing: float | None = None
"""Letter-spacing multiplier for lid label text (e.g. ``1.18`` for wide
sci-fi tracking); ``None`` uses ``1.0``."""
label_finial: LabelFinial | str | None = None
"""Decorative typographic ornament placed underneath the label text
(``NONE``, ``DIAMOND``, ``TRIPLE_DOT``, ``FLEURON``, ``CHEVRON``,
``SCROLLWORK``, or ``SPEAR``). Inlaid in ``frame_color`` when set,
falling back to ``text_color``."""
diagonal: bool | None = None
"""Run the text corner to corner rather than along the lid; ``None`` is no."""
text_color: Color | None = None
"""Colour the lettering is inlaid in; ``None`` uses black (FR-022).
A label is read against a lid whose colour is the game's choice, so the
default is the one colour that reads against all of them."""
frame_color: Color | None = None
"""Top-layer colour of the framed label's outer edge border ring;
``None`` leaves the border the box's own lid colour. The interior
1.5mm spacing and strips holding the text always keep the lid colour
with open through-holes between the strips."""
pattern: PatternBuilder | PatternType | str | None = PatternBuilder(PatternType.HEX)
"""Through-hole pattern, or ``None`` for a plain lid."""
pattern_color: Color | str | None = None
"""Colour of the pattern's top layer; ``None`` contrasts with the body."""
pattern_colors: tuple[Color | str, ...] | list[Color | str] | None = None
"""Palette of colours for multi-colour patterns; falls back to pattern.colors or pattern_color."""
pattern_through_inlay: bool | tuple[int, ...] | None = None
"""Override for whether pattern inlays extend completely through the lid thickness."""
pattern_inlay_depth_mm: float | None = None
"""Override for top-layer pattern inlay depth in mm."""
backing_pattern: PatternBuilder | PatternType | str | None = None
"""Override for the backing lattice pattern on the lid underside behind top-layer inlays (defaults to HEX)."""
top_skin_mm: float | None = None
"""Override for the solid top skin thickness in mm supporting thin colored inlays above the backing lattice."""
logo: Any | None = None
"""SVG path (monochrome or multi-colour), a single- or multi-coloured ``Bosl2Solid``,
a ``PatternResult``, a sequence of ``(shape, colour)`` pairs, or a callable
``(width, length, depth) -> ...`` returning any of those."""
logo_color: Color | None = None
"""Default colour for uncoloured logo parts in inlaid mode; ``None`` uses ``text_color``."""
logo_position: str | None = None
"""Placement of ``logo`` when combined with ``text`` inside a label:
``"top"`` (default when both ``text`` and ``logo`` are set), ``"left"``,
``"right"``, ``"bottom"``, or ``"center"`` (overlapping / standalone)."""
label_logo_size_mm: float | None = None
"""Target height/width in mm for an image/logo bay embedded inside a framed label.
``None`` sizes it automatically from the text height and available lid area."""
min_text_height_mm: float | None = None
"""Below this the label is skipped rather than printed illegibly (FR-020).
``None`` uses :data:`MIN_TEXT_HEIGHT_MM`."""
max_text_height_mm: float | None = None
"""Maximum cap height for auto-sized label text in mm; ``None`` uses
:data:`MAX_TEXT_HEIGHT_MM`."""
border_margin_mm: float | None = None
"""Margin the auto-sized label keeps clear of the lid's edge; ``None`` uses
:data:`BORDER_MARGIN_MM`."""
label_border_mm: float | None = None
"""Solid outer border width of the label backing plate; ``None`` uses defaults."""
label_text_gap_mm: float | None = None
"""Gap between label text and inside of the border; ``None`` uses defaults."""
label_rounding_mm: float | None = None
"""Corner rounding radius of the label backing plate; ``None`` uses defaults."""
label_solid_background: bool | None = None
"""Use a solid unperforated background inside a framed label instead of
diagonal hatching slots; ``None`` uses open through-hole strips unless
``label_background_color`` is set."""
label_background_color: Color | str | None = None
"""Top-layer colour for the solid interior background inside a framed label's
border ring. Setting a colour automatically enables a solid background (no
hatching holes); ``None`` leaves a solid background in the lid's own colour."""
label_clearance_mm: float | None = None
"""Solid margin kept around the **lettering** where a pattern meets it.
``None`` uses :data:`~pyboxbuilder.lid.decorate.LABEL_CLEARANCE_MM`, which
is ``0``: the holes stop at the glyphs, so the letters read as letters and
not as letters on a plaque. They keep their support either way — the
keep-out is the glyph outline, and the label is inlaid into the lid rather
than perched on it. Raise it for a lid whose pattern is coarse enough that
a stroke would otherwise finish on the very edge of a hole."""
label_center: tuple[float, float] | None = None
"""Explicit ``(x, y)`` center position for the label in the lid's local frame.
When ``None`` on a polygon lid, the label is placed in the largest
inscribed rectangular space."""
label_area: tuple[float, float, float, float] | None = None
"""Explicit ``(x, y, width, length)`` bounding box for the label in the lid's local frame.
When ``None`` on a polygon lid, the largest inscribed rectangle is used."""
min_hole_size_mm: float = 10.0
"""Minimum span (width/length in mm) for the central opening in a polygon lid frame.
If the inner opening in the middle is smaller than this value, it is omitted,
leaving the label plate continuous and solid."""
mmu_label: LidBuilder | None = None
"""Fields to override for the multi-material export (see :meth:`for_mode`)."""
single_label: LidBuilder | None = None
"""Fields to override for the single-colour export."""
def __post_init__(self) -> None:
"""Convert list pattern_through_inlay to tuple and coerce pattern/label_mode."""
if isinstance(self.label_mode, str):
object.__setattr__(self, "label_mode", LabelMode(self.label_mode.lower()))
if isinstance(self.label_shape, str):
object.__setattr__(self, "label_shape", LabelShape(self.label_shape.lower()))
if isinstance(self.label_finial, str):
object.__setattr__(self, "label_finial", LabelFinial(self.label_finial.lower()))
if isinstance(self.logo_position, str):
object.__setattr__(self, "logo_position", self.logo_position.lower())
if isinstance(self.pattern, str):
object.__setattr__(self, "pattern", PatternBuilder(PatternType(self.pattern.lower())))
elif isinstance(self.pattern, PatternType):
object.__setattr__(self, "pattern", PatternBuilder(self.pattern))
if isinstance(self.backing_pattern, str):
object.__setattr__(self, "backing_pattern", PatternType(self.backing_pattern.lower()))
if isinstance(self.pattern_through_inlay, list):
object.__setattr__(self, "pattern_through_inlay", tuple(self.pattern_through_inlay))
if isinstance(self.pattern_color, str):
from pybosl2 import Color
object.__setattr__(self, "pattern_color", Color(self.pattern_color))
if isinstance(self.label_background_color, str):
from pybosl2 import Color
object.__setattr__(self, "label_background_color", Color(self.label_background_color))
if isinstance(self.pattern_colors, (list, tuple)):
from pybosl2 import Color
object.__setattr__(
self,
"pattern_colors",
tuple(c if isinstance(c, Color) else Color(c) for c in self.pattern_colors),
)
[docs]
def titled(self, text: str, **overrides: Any) -> LidBuilder:
"""Return this lid style, carrying a particular box's text.
Args:
text: The label for this box.
**overrides: Any other field to change for this box — usually a
colour.
Returns:
A copy; the style it was made from is unchanged.
"""
return replace(self, text=text, **overrides)
@property
def mode(self) -> LabelMode:
"""The label style, resolved."""
return self.label_mode if self.label_mode is not None else LabelMode.FRAMED
@property
def shape(self) -> LabelShape:
"""The framed label plaque shape, resolved."""
if isinstance(self.label_shape, LabelShape):
return self.label_shape
if isinstance(self.label_shape, str):
return LabelShape(self.label_shape.lower())
return LabelShape.RECT
@property
def finial(self) -> LabelFinial:
"""The decorative ornament placed underneath label text, resolved."""
if isinstance(self.label_finial, LabelFinial):
return self.label_finial
if isinstance(self.label_finial, str):
return LabelFinial(self.label_finial.lower())
return LabelFinial.NONE
@property
def is_diagonal(self) -> bool:
"""Whether the text runs corner to corner, resolved."""
return bool(self.diagonal)
@property
def min_text_height(self) -> float:
"""The shortest printable label, resolved."""
return self.min_text_height_mm if self.min_text_height_mm is not None else MIN_TEXT_HEIGHT_MM
@property
def max_text_height(self) -> float:
"""The tallest auto-sized label cap height, resolved."""
return self.max_text_height_mm if self.max_text_height_mm is not None else MAX_TEXT_HEIGHT_MM
@property
def label_clearance(self) -> float:
"""The margin kept around the lettering, resolved."""
from pyboxbuilder.lid.decorate import LABEL_CLEARANCE_MM
return self.label_clearance_mm if self.label_clearance_mm is not None else LABEL_CLEARANCE_MM
@property
def border_margin(self) -> float:
"""The margin kept clear at the lid's edge, resolved."""
return self.border_margin_mm if self.border_margin_mm is not None else BORDER_MARGIN_MM
[docs]
def for_mode(self, mode: ColorMode | str) -> LidBuilder:
"""Return this lid as it prints in one colour mode.
A per-mode override carries **only the fields it sets**. That has to be
decided by what the caller passed rather than by comparing against the
field's default, which is what this used to do: a `single_label` asking
for `LabelMode.FRAMED` was indistinguishable from one that said nothing,
`diagonal=False` could not turn off a diagonal, and the margins were
taken from the override whether it mentioned them or not.
Args:
mode: :class:`~pyboxbuilder.enums.ColorMode` or string (``"mmu"`` or ``"single"``).
Returns:
The effective configuration; ``self`` when that mode sets nothing.
"""
mode_val = mode.value if isinstance(mode, ColorMode) else str(mode).lower()
override = self.mmu_label if mode_val == "mmu" else self.single_label
if override is None:
return self
return replace(self, **override._stated(), mmu_label=None, single_label=None)
def _stated(self) -> dict[str, Any]:
"""Return the fields this override actually names.
A `LidBuilder` used as an override is a sparse record: every field
defaults to ``None``, so "not mentioned" is representable and distinct
from every value the field can take. That is why `label_mode`,
`diagonal` and the two margins are ``| None`` rather than carrying
their defaults directly — the defaults live in the properties above.
"""
return {
f.name: getattr(self, f.name)
for f in fields(self)
if f.name not in ("mmu_label", "single_label") and getattr(self, f.name) is not None
}
[docs]
def resolve_for_mode(self, mode: ColorMode | str) -> LidBuilder:
"""Return the deprecated alias for :meth:`for_mode`."""
import warnings
warnings.warn(
"LidBuilder.resolve_for_mode() is deprecated; use for_mode().",
DeprecationWarning,
stacklevel=2,
)
return self.for_mode(mode)