Skip to content
Edit this page

ictdesigntools.draw.drawing

A drawing: its frame, shapes, layers and named styles, and the walk every output shares.

Layer dataclass

Layer(color: int = 7, linetype: str = '')

A CAD layer: an AutoCAD colour index and an optional linetype.

Drawing dataclass

Drawing(
    view: tuple[float, float, float, float] = (
        0.0,
        0.0,
        100.0,
        100.0,
    ),
    items: list = list(),
    title: str = "",
    desc: str = "",
    units: str = "mm",
    stroke: float = 0.35,
    font: float = 2.5,
    layers: dict[str, Layer] = dict(),
    styles: dict[str, Style] = dict(),
)

A drawing in units ("mm", the default, or "in"), framed by view (x, y, width, height; fit() sets it from the content).

style

style(it, theme: dict[str, Style] | None = None) -> Style

The look of a shape: its own values, then its named style (from theme first, then the drawing's), then the defaults.

Source code in src/ictdesigntools/draw/drawing.py
def style(self, it, theme: dict[str, Style] | None = None) -> Style:
    """The look of a shape: its own values, then its named style (from ``theme`` first,
    then the drawing's), then the defaults."""
    named = Style()
    name = getattr(it, "style", "")
    if name:
        if theme and name in theme:
            named = theme[name].over(self.styles.get(name, Style()))
        else:
            named = self.styles.get(name, Style())
    s = own_style(it).over(named).over(DEFAULT_STYLE)
    if s.stroke is None and isinstance(it, (Line, Polyline, Arc)):  # lines are always inked
        s = Style(stroke=INK).over(s)
    return s

components

components() -> list[Component]

Every component placed, inner ones first, each once.

Source code in src/ictdesigntools/draw/drawing.py
def components(self) -> list[Component]:
    """Every component placed, inner ones first, each once."""
    found: dict[str, Component] = {}

    def visit(items):
        for it in items:
            if isinstance(it, Group):
                visit(it.items)
            elif isinstance(it, Use):
                c = it.component
                if c.name in found:
                    if found[c.name] is not c and found[c.name] != c:
                        raise ValueError(f"Two different components are named {c.name!r}.")
                    continue
                visit(c.items)
                found[c.name] = c

    visit(self.items)
    return list(found.values())

walk

Every shape with its transform to the drawing and its layer, components expanded.

Source code in src/ictdesigntools/draw/drawing.py
def walk(self) -> Iterator[tuple[object, Transform, str]]:
    """Every shape with its transform to the drawing and its layer, components expanded."""
    yield from walk(self.items)

bounds

bounds() -> tuple[float, float, float, float] | None

The content's extent (x0, y0, x1, y1), or None when empty.

Source code in src/ictdesigntools/draw/drawing.py
def bounds(self) -> tuple[float, float, float, float] | None:
    """The content's extent (x0, y0, x1, y1), or None when empty."""
    boxes = [b for it, t, _ in self.walk() if (b := shape_bounds(it, t, self.font))]
    if not boxes:
        return None
    return (min(b[0] for b in boxes), min(b[1] for b in boxes),
            max(b[2] for b in boxes), max(b[3] for b in boxes))  # fmt: skip

fit

fit(margin: float = 0.0) -> Drawing

Frame the content with margin around it.

Source code in src/ictdesigntools/draw/drawing.py
def fit(self, margin: float = 0.0) -> Drawing:
    """Frame the content with ``margin`` around it."""
    b = self.bounds()
    if b:
        self.view = (b[0] - margin, b[1] - margin, b[2] - b[0] + 2 * margin,
                     b[3] - b[1] + 2 * margin)  # fmt: skip
    return self

hex6

hex6(color: str) -> str

A CSS hex colour as #rrggbb (#abc is expanded), for outputs that need six digits.

Source code in src/ictdesigntools/draw/drawing.py
def hex6(color: str) -> str:
    """A CSS hex colour as ``#rrggbb`` (``#abc`` is expanded), for outputs that need six digits."""
    c = color.lstrip("#")
    if len(c) in (3, 4):
        c = "".join(ch * 2 for ch in c[:3])
    return "#" + c[:6].lower()

arrowheads

arrowheads(
    it: Line, size: float
) -> list[tuple[tuple[float, float], ...]]

Filled triangles at a line's ends, size long.

Source code in src/ictdesigntools/draw/drawing.py
def arrowheads(it: Line, size: float) -> list[tuple[tuple[float, float], ...]]:
    """Filled triangles at a line's ends, ``size`` long."""
    heads = []
    length = math.hypot(it.x2 - it.x1, it.y2 - it.y1)
    if not it.arrow or length == 0:
        return heads
    ux, uy = (it.x2 - it.x1) / length, (it.y2 - it.y1) / length
    for end in ("start", "end"):
        if it.arrow not in (end, "both"):
            continue
        tip, d = ((it.x1, it.y1), -1) if end == "start" else ((it.x2, it.y2), 1)
        bx, by = tip[0] - d * ux * size, tip[1] - d * uy * size
        px, py = -uy * size / 3, ux * size / 3
        heads.append((tip, (bx + px, by + py), (bx - px, by - py)))
    return heads

earth_strokes

earth_strokes(
    e: Earth,
) -> list[tuple[float, float, float, float]]

The EARTH pattern as line segments, clipped to the area and around the holes.

Source code in src/ictdesigntools/draw/drawing.py
def earth_strokes(e: Earth) -> list[tuple[float, float, float, float]]:
    """The EARTH pattern as line segments, clipped to the area and around the holes."""
    t = e.tile
    gap = t / 4
    segs = []
    nx, ny = math.ceil(e.w / t), math.ceil(e.h / t)
    for i in range(nx):
        for j in range(ny):
            x0, y0 = e.x + i * t, e.y + j * t
            for k in (1, 2, 3):
                if (i + j) % 2 == 0:  # three horizontal strokes
                    y = y0 + k * gap
                    if y >= e.y + e.h:
                        continue
                    a, b = x0 + gap * 0.5, min(x0 + t - gap * 0.5, e.x + e.w)
                    cuts = [(hx, hx + hw) for hx, hy, hw, hh in e.holes if hy <= y <= hy + hh]
                    segs += [(p, y, q, y) for p, q in _clip(a, b, cuts)]
                else:  # three vertical strokes
                    x = x0 + k * gap
                    if x >= e.x + e.w:
                        continue
                    a, b = y0 + gap * 0.5, min(y0 + t - gap * 0.5, e.y + e.h)
                    cuts = [(hy, hy + hh) for hx, hy, hw, hh in e.holes if hx <= x <= hx + hw]
                    segs += [(x, p, x, q) for p, q in _clip(a, b, cuts)]
    return segs

earth_pieces

earth_pieces(
    e: Earth,
) -> list[tuple[float, float, float, float]]

The earth rectangle cut into rectangles that leave out its holes (bands above and below each hole, and pieces either side of it).

Source code in src/ictdesigntools/draw/drawing.py
def earth_pieces(e: Earth) -> list[tuple[float, float, float, float]]:
    """The earth rectangle cut into rectangles that leave out its holes (bands above and below
    each hole, and pieces either side of it)."""
    pieces = [(e.x, e.y, e.w, e.h)]
    for hx, hy, hw, hh in e.holes:
        nxt = []
        for x, y, w, h in pieces:
            if hx >= x + w or hx + hw <= x or hy >= y + h or hy + hh <= y:
                nxt.append((x, y, w, h))
                continue
            top, bottom = max(y, hy), min(y + h, hy + hh)
            right = min(hx + hw, x + w)
            nxt += [(x, y, w, top - y), (x, bottom, w, y + h - bottom),
                    (x, top, max(hx, x) - x, bottom - top),
                    (right, top, x + w - right, bottom - top)]  # fmt: skip
        pieces = [pc for pc in nxt if pc[2] > 1e-6 and pc[3] > 1e-6]
    return pieces

dim_geometry

dim_geometry(d: Dim, font: float)

Dimension line, extension lines, tick marks and text position (x, y, rotation).

Source code in src/ictdesigntools/draw/drawing.py
def dim_geometry(d: Dim, font: float):
    """Dimension line, extension lines, tick marks and text position (x, y, rotation)."""
    s = 1.0 if d.offset >= 0 else -1.0
    if d.vertical:
        x = d.x1 + d.offset
        line = (x, d.y1, x, d.y2)
        ext = [(d.x1, d.y1, x + font * 0.3 * s, d.y1), (d.x2, d.y2, x + font * 0.3 * s, d.y2)]
        ticks = [(x - font * 0.25, y - font * 0.25, x + font * 0.25, y + font * 0.25)
                 for y in (d.y1, d.y2)]  # fmt: skip
        text = (x + s * font * 0.75, (d.y1 + d.y2) / 2, 90.0)
    else:
        y = d.y1 - d.offset
        line = (d.x1, y, d.x2, y)
        ext = [(d.x1, d.y1, d.x1, y - font * 0.3 * s), (d.x2, d.y2, d.x2, y - font * 0.3 * s)]
        ticks = [(x - font * 0.25, y + font * 0.25, x + font * 0.25, y - font * 0.25)
                 for x in (d.x1, d.x2)]  # fmt: skip
        text = ((d.x1 + d.x2) / 2, y - s * font * 0.75, 0.0)
    return line, ext, ticks, text

rect_points

rect_points(
    it: Rect, steps: int = 8
) -> list[tuple[float, float]]

The outline of a rectangle, its corners rounded to rx with steps per corner.

Source code in src/ictdesigntools/draw/drawing.py
def rect_points(it: Rect, steps: int = 8) -> list[tuple[float, float]]:
    """The outline of a rectangle, its corners rounded to ``rx`` with ``steps`` per corner."""
    r = min(it.rx, it.w / 2, it.h / 2)
    x0, y0, x1, y1 = it.x, it.y, it.x + it.w, it.y + it.h
    if r <= 0:
        return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
    pts = []
    for cx, cy, a0 in ((x1 - r, y0 + r, 90), (x0 + r, y0 + r, 180), (x0 + r, y1 - r, 270),
                       (x1 - r, y1 - r, 0)):  # fmt: skip
        for i in range(steps + 1):
            t = math.radians(a0 + 90 * i / steps)
            pts.append((cx + r * math.cos(t), cy - r * math.sin(t)))
    return pts

outline

outline(it, font: float) -> list[tuple[float, float]]

Points that bound a shape in its own coordinates (circles as their bounding square).

Source code in src/ictdesigntools/draw/drawing.py
def outline(it, font: float) -> list[tuple[float, float]]:
    """Points that bound a shape in its own coordinates (circles as their bounding square)."""
    if isinstance(it, (Rect,)):
        return [(it.x, it.y), (it.x + it.w, it.y + it.h), (it.x + it.w, it.y), (it.x, it.y + it.h)]
    if isinstance(it, (Circle, Ring)):
        r = it.r if isinstance(it, Circle) else it.r_outer
        return [(it.cx + dx * r, it.cy + dy * r) for dx in (-1, 1) for dy in (-1, 1)]
    if isinstance(it, (Polygon, Polyline)):
        return list(it.points)
    if isinstance(it, Arc):
        return arc_points(it)
    if isinstance(it, Line):
        return [(it.x1, it.y1), (it.x2, it.y2)]
    if isinstance(it, Text):
        return text_box(it)
    if isinstance(it, Dim):
        line, ext, ticks, (tx, ty, rot) = dim_geometry(it, font)
        pts = [(s[0], s[1]) for s in (line, *ext, *ticks)]
        pts += [(s[2], s[3]) for s in (line, *ext, *ticks)]
        half = font * 0.6
        return pts + [(tx - half, ty - half), (tx + half, ty + half)]
    if isinstance(it, Earth):
        return [(it.x, it.y), (it.x + it.w, it.y + it.h)]
    return []