view fontlib.py @ 4:4836a7408849

more elaborate hole finding
author ark
date 2026-11-03 15:51 +0100
parents b5a96b547b01
children
line wrap: on
line source

"""Font lookup, glyph outlines and geometry helpers for the house number scripts.

Shared by make_preview.py and make_glyphs.py. Fonts are found through
fontconfig (fc-list) and read with fontTools. Glyph outlines are flattened
into polygons, so the preview, the hole calculation and the OpenSCAD model
all use the same shapes.

Coordinates are in font units until a script scales them to mm. The y axis
points up.
"""

import math
import os
import subprocess
from collections import deque
from dataclasses import dataclass, field

import numpy as np
from fontTools.pens.basePen import BasePen
from fontTools.ttLib import TTFont

FC_FORMAT = ("%{file}\t%{index}\t%{postscriptname}\t%{family[0]}\t"
             "%{style[0]}\t%{slant}\t%{spacing}\t%{variable}\n")


# ---------------------------------------------------------------- font lookup

@dataclass
class FaceInfo:
    """One font face as listed by fontconfig.

    Attributes:
        file: path of the font file.
        index: fontconfig index. The lower 16 bits are the face number in a
            collection, the upper 16 bits the 1-based named instance of a
            variable font (0 for the default instance).
        psname: PostScript name, used as the identifier of the face.
        family: family name.
        style: style name.
        italic: true for italic and oblique faces.
        mono: true for monospaced faces.
    """
    file: str
    index: int
    psname: str
    family: str
    style: str
    italic: bool
    mono: bool

    @property
    def file_name(self):
        """File name stem for this face: the PostScript name without a
        leading dot, so the files of Apple's system fonts are not hidden."""
        return self.psname.lstrip(".")


def list_faces():
    """List the font faces known to fontconfig.

    Variable font entries that stand for the whole variable font are left
    out; their named instances are listed separately. Faces without a
    PostScript name are left out. When several faces share a PostScript
    name, the first one is kept.

    Returns:
        list of FaceInfo, sorted by file name stem.
    """
    out = subprocess.run(["fc-list", "--format", FC_FORMAT],
                         capture_output=True, text=True, check=True).stdout
    faces = {}
    for line in out.splitlines():
        parts = line.split("\t")
        if len(parts) != 8:
            continue
        file, index, psname, family, style, slant, spacing, variable = parts
        if variable == "True" or not psname:
            continue
        if not file.lower().endswith((".ttf", ".otf", ".ttc", ".otc")):
            continue
        info = FaceInfo(file=file, index=int(index), psname=psname,
                        family=family, style=style,
                        italic=float(slant or 0) > 0,
                        mono=spacing == "100")
        faces.setdefault(info.file_name, info)
    return [faces[k] for k in sorted(faces, key=str.lower)]


def find_face(name):
    """Find a face by PostScript name or by the path of its preview PNG.

    Args:
        name: PostScript name, with or without leading dot, or a path whose
            file name stem is the name (such as preview/Helvetica-Bold.png).

    Returns:
        the FaceInfo.

    Raises:
        LookupError: no face of that name.
    """
    stem = os.path.basename(name)
    if stem.lower().endswith(".png"):
        stem = stem[:-4]
    stem = stem.lstrip(".")
    for face in list_faces():
        if face.file_name == stem:
            return face
    raise LookupError(f"no font with PostScript name {stem!r}")


# ------------------------------------------------------------------ outlines

class _FlattenPen(BasePen):
    """Pen that turns glyph outlines into closed polygons.

    Curves are split into straight segments so that no point of a segment
    is further than the tolerance from the curve.
    """

    def __init__(self, glyphset, tolerance):
        """Args:
            glyphset: glyph set, used to draw components.
            tolerance: largest distance between curve and segments, in font
                units.
        """
        super().__init__(glyphset)
        self.tolerance = tolerance
        self.contours = []
        self._cur = []

    def _segments(self, second_diff):
        """Number of segments for a curve whose largest second difference of
        control points is second_diff."""
        return max(1, math.ceil(math.sqrt(second_diff / (4 * self.tolerance))))

    def _moveTo(self, pt):
        self._cur = [pt]

    def _lineTo(self, pt):
        self._cur.append(pt)

    def _curveToOne(self, p1, p2, p3):
        p0 = self._getCurrentPoint()
        dd = max(math.dist((p0[0] - 2 * p1[0] + p2[0], p0[1] - 2 * p1[1] + p2[1]), (0, 0)),
                 math.dist((p1[0] - 2 * p2[0] + p3[0], p1[1] - 2 * p2[1] + p3[1]), (0, 0)))
        n = self._segments(3 * dd)
        for i in range(1, n + 1):
            t = i / n
            a, b, c, d = (1 - t) ** 3, 3 * t * (1 - t) ** 2, 3 * t * t * (1 - t), t ** 3
            self._cur.append((a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0],
                              a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]))

    def _qCurveToOne(self, p1, p2):
        p0 = self._getCurrentPoint()
        dd = math.dist((p0[0] - 2 * p1[0] + p2[0], p0[1] - 2 * p1[1] + p2[1]), (0, 0))
        n = self._segments(dd)
        for i in range(1, n + 1):
            t = i / n
            a, b, c = (1 - t) ** 2, 2 * t * (1 - t), t * t
            self._cur.append((a * p0[0] + b * p1[0] + c * p2[0],
                              a * p0[1] + b * p1[1] + c * p2[1]))

    def _closePath(self):
        pts = np.array(self._cur, dtype=float)
        self._cur = []
        if len(pts) and np.allclose(pts[0], pts[-1]):
            pts = pts[:-1]
        if len(pts) >= 3:
            # drop repeated points
            keep = np.any(np.diff(pts, axis=0, append=pts[:1]) != 0, axis=1)
            pts = pts[keep]
        if len(pts) >= 3:
            self.contours.append(pts)

    def _endPath(self):
        # open contours do not occur in fonts; close them anyway
        self._closePath()


@dataclass
class Glyph:
    """Outline of one character.

    Attributes:
        char: the character.
        advance: advance width in font units.
        contours: closed polygons as (n, 2) arrays, font units.
        groups: contours grouped for filling, see group_contours().
        fill_error: fraction of the glyph area where the grouped outline
            differs from the font's intended filling, see fill_error().
    """
    char: str
    advance: float
    contours: list
    groups: list = field(default_factory=list)
    fill_error: float = 0.0

    @property
    def empty(self):
        """True for glyphs without outline, such as a space."""
        return not self.contours

    def bbox(self):
        """Ink bounding box as (xmin, ymin, xmax, ymax)."""
        pts = np.concatenate(self.contours)
        return (*pts.min(axis=0), *pts.max(axis=0))

    def scaled(self, k, dx=0.0):
        """Copy with all coordinates multiplied by k and shifted by dx."""
        off = np.array([dx, 0.0])
        return Glyph(self.char, self.advance * k,
                     [c * k + off for c in self.contours],
                     [[c * k + off for c in g] for g in self.groups])


class Face:
    """An opened font face, positioned at its named instance if it has one.

    Attributes:
        info: the FaceInfo.
        font: the fontTools TTFont.
        upm: units per em.
        location: axis coordinates of the named instance, or None.
    """

    def __init__(self, info):
        """Open the face.

        Args:
            info: FaceInfo from list_faces() or find_face().
        """
        self.info = info
        self.font = TTFont(info.file, fontNumber=info.index & 0xFFFF, lazy=True)
        self.upm = self.font["head"].unitsPerEm
        self.location = None
        instance = info.index >> 16
        if instance and "fvar" in self.font:
            self.location = dict(self.font["fvar"].instances[instance - 1].coordinates)
        self.glyphset = self.font.getGlyphSet(location=self.location)
        self.cmap = self.font.getBestCmap() or {}

    @property
    def weight(self):
        """Weight on the 100 to 900 scale of the OS/2 table."""
        if self.location and "wght" in self.location:
            return round(self.location["wght"])
        if "fvar" in self.font:
            for axis in self.font["fvar"].axes:
                if axis.axisTag == "wght":
                    return round(axis.defaultValue)
        if "OS/2" in self.font:
            return self.font["OS/2"].usWeightClass
        return 400

    @property
    def classification(self):
        """'serif' or 'sans' from the PANOSE data of the OS/2 table, or None
        when the font does not classify itself as Latin text."""
        if "OS/2" not in self.font:
            return None
        panose = self.font["OS/2"].panose
        if panose.bFamilyType != 2:
            return None
        if 2 <= panose.bSerifStyle <= 10:
            return "serif"
        if 11 <= panose.bSerifStyle <= 13:
            return "sans"
        return None

    @property
    def mono(self):
        """True for monospaced faces."""
        return self.info.mono or bool(getattr(self.font.get("post"), "isFixedPitch", 0))

    def has_chars(self, text):
        """True if the face has a glyph for every character of text."""
        return all(ord(c) in self.cmap for c in text)

    def glyph(self, char, tolerance=None):
        """Outline of one character.

        Args:
            char: the character.
            tolerance: flattening tolerance in font units. Default: 1/10000
                of the em, about 0.04 mm for a 280 mm digit.

        Returns:
            Glyph with contours and fill groups.

        Raises:
            KeyError: the face has no glyph for the character.
        """
        name = self.cmap.get(ord(char))
        if name is None:
            raise KeyError(f"{self.info.psname} has no glyph for {char!r}")
        pen = _FlattenPen(self.glyphset, tolerance or self.upm / 10000)
        g = self.glyphset[name]
        g.draw(pen)
        glyph = Glyph(char, g.width, pen.contours)
        if glyph.contours:
            glyph.groups = group_contours(glyph.contours)
            glyph.fill_error = fill_error(glyph.contours, glyph.groups)
        return glyph

    def layout(self, text):
        """Outlines of the characters of text, placed as the font spaces
        them on one line.

        Args:
            text: the text.

        Returns:
            list of (x offset in font units, Glyph), one per character,
            spaces included.
        """
        x, out = 0.0, []
        for char in text:
            glyph = self.glyph(char)
            out.append((x, glyph))
            x += glyph.advance
        return out


# --------------------------------------------------------------- polygons

def signed_area(poly):
    """Signed area of a polygon, positive for counter-clockwise order."""
    x, y = poly[:, 0], poly[:, 1]
    return 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(np.roll(x, -1), y))


def points_in_polygon(points, poly):
    """Even-odd inside test of points against one polygon.

    Args:
        points: (n, 2) array.
        poly: (m, 2) array, closed implicitly.

    Returns:
        bool array of length n.
    """
    inside = np.zeros(len(points), dtype=bool)
    px, py = points[:, 0], points[:, 1]
    ax, ay = poly[:, 0], poly[:, 1]
    bx, by = np.roll(ax, -1), np.roll(ay, -1)
    for i in range(len(poly)):
        crosses = (ay[i] > py) != (by[i] > py)
        if not crosses.any():
            continue
        xc = ax[i] + (py - ay[i]) * (bx[i] - ax[i]) / (by[i] - ay[i] + (by[i] == ay[i]))
        inside ^= crosses & (px < xc)
    return inside


def split_self_intersections(contour):
    """Split a contour that crosses itself into loops that do not.

    The crossing points are inserted on both segments. Then, as long as a
    crossing point occurs twice in the point sequence, the part between the
    two occurrences is cut off as a separate loop.

    Args:
        contour: (n, 2) array.

    Returns:
        list of (k, 2) arrays. Loops of negligible area are dropped.
    """
    n = len(contour)
    a, b = contour, np.roll(contour, -1, axis=0)
    d = b - a
    cuts = [[] for _ in range(n)]
    label = 0
    for i in range(n - 2):
        j = np.arange(i + 2, n if i else n - 1)
        if not len(j):
            continue
        den = d[i, 0] * d[j, 1] - d[i, 1] * d[j, 0]
        ok = np.abs(den) > 1e-12
        den = np.where(ok, den, 1)
        w = a[j] - a[i]
        t = (w[:, 0] * d[j, 1] - w[:, 1] * d[j, 0]) / den
        u = (w[:, 0] * d[i, 1] - w[:, 1] * d[i, 0]) / den
        hit = ok & (t > 1e-9) & (t < 1 - 1e-9) & (u > 1e-9) & (u < 1 - 1e-9)
        for k in np.nonzero(hit)[0]:
            pt = a[i] + t[k] * d[i]
            cuts[i].append((t[k], label, pt))
            cuts[j[k]].append((u[k], label, pt))
            label += 1
    if not label:
        return [contour]
    seq = []
    for i in range(n):
        seq.append((-1, a[i]))
        seq.extend((lab, pt) for _, lab, pt in sorted(cuts[i], key=lambda c: c[0]))
    loops, todo = [], [seq]
    while todo:
        cur = todo.pop()
        first = {}
        for pos, (lab, _) in enumerate(cur):
            if lab < 0:
                continue
            if lab in first:
                p, q = first[lab], pos
                todo.append([(-1, pt) for _, pt in cur[p:q]])
                todo.append(cur[:p] + [(-1, cur[q][1])] + cur[q + 1:])
                break
            first[lab] = pos
        else:
            loops.append(np.array([pt for _, pt in cur]))
    scale = abs(signed_area(contour)) or 1
    return [lp for lp in loops if len(lp) >= 3 and abs(signed_area(lp)) > 1e-6 * scale]


def group_contours(contours):
    """Group contours so that even-odd filling of each group, combined by
    union, gives the non-zero filling the font intends.

    Contours that cross themselves are split into simple loops first. Each
    group is one outer contour followed by the holes inside it. Outer
    contours turn the same way as the largest contour; the others are
    holes. A hole is given to the smallest outer contour that contains all
    its points. A hole inside no outer contour is filled under the non-zero
    rule, so it becomes an outer contour itself. Outer contours come out
    counter-clockwise, holes clockwise.

    Args:
        contours: list of (n, 2) arrays.

    Returns:
        list of groups, each a list of (n, 2) arrays, outer contour first.
    """
    contours = [lp for c in contours for lp in split_self_intersections(c)]
    areas = [signed_area(c) for c in contours]
    outer_sign = math.copysign(1, areas[int(np.argmax(np.abs(areas)))])
    outers = [i for i, a in enumerate(areas) if math.copysign(1, a) == outer_sign]
    holes = {}
    for i, a in enumerate(areas):
        if i in outers:
            continue
        best = None
        for j in outers:
            if abs(areas[j]) > abs(a) and points_in_polygon(contours[i], contours[j]).all():
                if best is None or abs(areas[j]) < abs(areas[best]):
                    best = j
        holes.setdefault(best, []).append(i)
    ccw = [c if signed_area(c) > 0 else c[::-1] for c in contours]
    groups = [[ccw[i]] + [ccw[h][::-1] for h in holes.get(i, [])] for i in outers]
    groups += [[ccw[h]] for h in holes.get(None, [])]
    return groups


def fill_error(contours, groups, cells=250):
    """Compare the union of even-odd filled groups with the non-zero filling
    of the original contours, on a coarse grid.

    Args:
        contours: original contours.
        groups: result of group_contours().
        cells: grid cells along the longer side of the bounding box.

    Returns:
        mismatching cells as a fraction of the non-zero filled cells.
    """
    pts = np.concatenate(contours)
    lo, hi = pts.min(axis=0), pts.max(axis=0)
    step = max(hi - lo) / cells
    grid = Grid.around((*lo, *hi), step, 2 * step)
    nonzero = rasterise_winding(contours, grid)
    grouped, _ = rasterise(groups, grid)
    return float((nonzero != grouped).sum()) / max(1, int(nonzero.sum()))


def densify(contour, max_len):
    """Contour with long segments split so none is longer than max_len."""
    a, b = contour, np.roll(contour, -1, axis=0)
    n = np.maximum(1, np.ceil(np.linalg.norm(b - a, axis=1) / max_len).astype(int))
    if (n == 1).all():
        return contour
    out = [a[i] + (b[i] - a[i]) * (k / n[i]) for i in range(len(a)) for k in range(n[i])]
    return np.array(out)


def visible_runs(groups, max_len):
    """Polylines along the outline of the union of all groups.

    Parts of a contour that lie inside another group are hidden by the
    union and left out. Contours are first split into segments no longer
    than max_len; each segment is kept or dropped by its midpoint.

    Args:
        groups: contour groups from group_contours().
        max_len: longest segment for the visibility test.

    Returns:
        list of (k, 2) arrays. A fully visible contour comes out closed,
        with its first point repeated at the end.
    """
    runs = []
    for gi, group in enumerate(groups):
        others = [g for gj, g in enumerate(groups) if gj != gi]
        for c in group:
            if not others:
                runs.append(np.vstack([c, c[:1]]))
                continue
            c = densify(c, max_len)
            a, b = c, np.roll(c, -1, axis=0)
            mid = (a + b) / 2
            hidden = np.zeros(len(c), dtype=bool)
            for o in others:
                hidden |= inside_group(mid, o)
            if not hidden.any():
                runs.append(np.vstack([c, c[:1]]))
                continue
            # start at a hidden segment so every visible run is contiguous
            run = []
            for k in np.roll(np.arange(len(c)), -int(np.argmax(hidden))):
                if hidden[k]:
                    if run:
                        runs.append(np.array(run))
                    run = []
                else:
                    if not run:
                        run.append(a[k])
                    run.append(b[k])
            if run:
                runs.append(np.array(run))
    return runs


def boundary_segments(groups, max_len):
    """Segments of the outline of the union of all groups, see
    visible_runs().

    Returns:
        (a, b): (m, 2) arrays of segment start and end points.
    """
    runs = visible_runs(groups, max_len)
    return (np.concatenate([r[:-1] for r in runs]),
            np.concatenate([r[1:] for r in runs]))


def inside_group(points, group):
    """Even-odd inside test of points against one contour group."""
    inside = np.zeros(len(points), dtype=bool)
    for c in group:
        inside ^= points_in_polygon(points, c)
    return inside


def convex_hull(points):
    """Convex hull by the monotone chain method.

    Args:
        points: (n, 2) array.

    Returns:
        (k, 2) array, counter-clockwise.
    """
    pts = sorted(map(tuple, np.unique(points, axis=0)))
    if len(pts) < 3:
        return np.array(pts)

    def half(seq):
        out = []
        for p in seq:
            while len(out) >= 2 and ((out[-1][0] - out[-2][0]) * (p[1] - out[-2][1])
                                     - (out[-1][1] - out[-2][1]) * (p[0] - out[-2][0])) <= 0:
                out.pop()
            out.append(p)
        return out

    lower, upper = half(pts), half(reversed(pts))
    return np.array(lower[:-1] + upper[:-1])


def rotated_extent(points, angle):
    """Width and height of the bounding box of points rotated by angle
    degrees counter-clockwise."""
    a = math.radians(angle)
    rot = np.array([[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]])
    r = points @ rot.T
    return np.ptp(r[:, 0]), np.ptp(r[:, 1])


# ------------------------------------------------------------- size fitting

def usable_area(bed, margin, line_width):
    """Side of the square available for glyphs: the bed minus its margin,
    minus frame and frame gap of one line width each on both sides."""
    return bed - 2 * margin - 4 * line_width


def _fit_shapes(placed):
    """Convex hulls to fit on the bed and the tallest ink height.

    Returns:
        (height, {'text': [hull of the whole text], 'glyph': [hull per glyph]})
    """
    inked = [(x, g) for x, g in placed if not g.empty]
    height = max(g.bbox()[3] - g.bbox()[1] for _, g in inked)
    hulls = [convex_hull(np.concatenate(g.contours)) for _, g in inked]
    text_hull = convex_hull(np.concatenate([h + [x, 0] for (x, _), h in zip(inked, hulls)]))
    return height, {"text": [text_hull], "glyph": hulls}


def size_at(placed, usable, layout, angle):
    """Largest print size for one layout and angle.

    Size is the height of the tallest glyph's ink. In the text layout the
    whole text has to fit the usable square; in the glyph layout every glyph
    on its own, all at the same scale.

    Args:
        placed: result of Face.layout(), or the same structure in mm.
        usable: side of the usable square in mm.
        layout: 'text' or 'glyph'.
        angle: rotation on the bed in degrees.

    Returns:
        size in mm.
    """
    height, shapes = _fit_shapes(placed)
    extent = max(max(rotated_extent(h, angle)) for h in shapes[layout])
    return usable / extent * height


def max_sizes(placed, usable):
    """Largest print size for both layouts, at 0 degrees and at the best
    angle. Angles from 0 to 90 degrees in 1 degree steps are tried.

    Args:
        placed: result of Face.layout(), or the same structure in mm.
        usable: side of the usable square in mm.

    Returns:
        dict with keys 'text' and 'glyph', each a dict with 'size0' (size at
        0 degrees), 'angle' (best angle) and 'size' (size at that angle), in
        mm. See size_at().
    """
    height, shapes = _fit_shapes(placed)
    result = {}
    for layout, hulls in shapes.items():
        sizes = [usable / max(max(rotated_extent(h, a)) for h in hulls) * height
                 for a in range(91)]
        best = int(np.argmax(sizes))
        result[layout] = {"size0": sizes[0], "angle": best, "size": sizes[best]}
    return result


# ------------------------------------------------------------------ rasters

@dataclass
class Grid:
    """Regular grid of sample points.

    Point (i, j) lies at (x0 + i * step, y0 + j * step). Arrays over the
    grid have shape (ny, nx), row j and column i.
    """
    x0: float
    y0: float
    step: float
    nx: int
    ny: int

    @classmethod
    def around(cls, bbox, step, pad):
        """Grid covering bbox = (xmin, ymin, xmax, ymax) plus pad on all
        sides."""
        x0, y0 = bbox[0] - pad, bbox[1] - pad
        nx = int(math.ceil((bbox[2] + pad - x0) / step)) + 1
        ny = int(math.ceil((bbox[3] + pad - y0) / step)) + 1
        return cls(x0, y0, step, nx, ny)

    def points(self):
        """All grid points as an (ny * nx, 2) array, row by row."""
        xs = self.x0 + np.arange(self.nx) * self.step
        ys = self.y0 + np.arange(self.ny) * self.step
        gx, gy = np.meshgrid(xs, ys)
        return np.stack([gx.ravel(), gy.ravel()], axis=1)


def _scanline_toggles(contours, grid, signed):
    """Crossings of contour edges with the grid rows.

    Each crossing is counted at the first grid point to its right. With
    signed set, upward edges count +1 and downward edges -1; otherwise all
    count 1.

    Returns:
        int array of shape (grid.ny, grid.nx + 1). Its cumulative sum along
        the rows gives the crossing count left of each point.
    """
    toggles = np.zeros((grid.ny, grid.nx + 1), dtype=np.int32)
    for c in contours:
        a, b = c, np.roll(c, -1, axis=0)
        ya, yb = a[:, 1], b[:, 1]
        lo, hi = np.minimum(ya, yb), np.maximum(ya, yb)
        # rows whose y lies in [lo, hi)
        j0 = np.clip(np.ceil((lo - grid.y0) / grid.step).astype(int), 0, grid.ny)
        j1 = np.clip(np.ceil((hi - grid.y0) / grid.step).astype(int), 0, grid.ny)
        counts = np.maximum(j1 - j0, 0)
        total = int(counts.sum())
        if not total:
            continue
        edge = np.repeat(np.arange(len(c)), counts)
        rows = np.repeat(j0, counts) + (np.arange(total)
                                        - np.repeat(np.cumsum(counts) - counts, counts))
        y = grid.y0 + rows * grid.step
        t = (y - ya[edge]) / (yb[edge] - ya[edge])
        x = a[edge, 0] + t * (b[edge, 0] - a[edge, 0])
        col = np.clip(np.floor((x - grid.x0) / grid.step).astype(int) + 1, 0, grid.nx)
        weight = np.where(yb[edge] > ya[edge], 1, -1) if signed else 1
        np.add.at(toggles, (rows, col), weight)
    return toggles


def rasterise_group(group, grid):
    """Even-odd inside test of all grid points against one contour group.

    Returns:
        bool array of shape (grid.ny, grid.nx).
    """
    toggles = _scanline_toggles(group, grid, signed=False)
    return (np.cumsum(toggles, axis=1)[:, :grid.nx] % 2).astype(bool)


def rasterise_winding(contours, grid):
    """Non-zero inside test of all grid points against a set of contours.

    Returns:
        bool array of shape (grid.ny, grid.nx).
    """
    toggles = _scanline_toggles(contours, grid, signed=True)
    return np.cumsum(toggles, axis=1)[:, :grid.nx] != 0


def rasterise(groups, grid):
    """Inside test of all grid points against the union of contour groups.

    Returns:
        (mask, group_masks): bool array of shape (grid.ny, grid.nx) and the
        list of masks of the single groups.
    """
    masks = [rasterise_group(g, grid) for g in groups]
    return np.logical_or.reduce(masks), masks


def distance_to_segments(points, a, b, chunk=2048):
    """Distance from each point to the nearest of a set of segments.

    Args:
        points: (n, 2) array.
        a, b: (m, 2) arrays of segment start and end points.
        chunk: points handled per step, to limit memory use.

    Returns:
        (n,) array.
    """
    # float32 and separate x and y arrays: about 3 times faster than
    # float64 arrays with a coordinate axis
    a = np.asarray(a, dtype=np.float32)
    ab = np.asarray(b, dtype=np.float32) - a
    inv = 1 / np.maximum((ab ** 2).sum(axis=1), 1e-12)
    ax, ay, abx, aby = a[:, 0], a[:, 1], ab[:, 0], ab[:, 1]
    pts = np.asarray(points, dtype=np.float32)
    out = np.empty(len(points))
    for s in range(0, len(points), chunk):
        dx = pts[s:s + chunk, 0:1] - ax
        dy = pts[s:s + chunk, 1:2] - ay
        t = np.clip((dx * abx + dy * aby) * inv, 0, 1)
        dx -= t * abx
        dy -= t * aby
        out[s:s + chunk] = np.sqrt((dx * dx + dy * dy).min(axis=1))
    return out


def max_filter(arr, radius):
    """Largest value within a square window of radius cells around each
    cell, computed with doubling shifts along both axes."""
    out = arr
    for axis in (0, 1):
        out = _max_1d(out, radius, axis)
    return out


def _max_1d(arr, radius, axis):
    """Largest value within radius cells along one axis."""
    width = 2 * radius + 1
    pad = [(0, 0), (0, 0)]
    pad[axis] = (radius, radius + width)
    a = np.pad(arr, pad, constant_values=-np.inf)
    span, cur = 1, a
    # cur holds the maximum over windows of length span
    while span * 2 <= width:
        cur = np.maximum(cur, np.roll(cur, -span, axis=axis))
        span *= 2
    res = np.maximum(cur, np.roll(cur, -(width - span), axis=axis))
    n = arr.shape[axis]
    return np.take(res, np.arange(n), axis=axis)


def components(mask):
    """Number of 4-connected components of a bool mask."""
    seen = np.zeros_like(mask)
    ny, nx = mask.shape
    count = 0
    for start in zip(*np.nonzero(mask)):
        if seen[start]:
            continue
        count += 1
        seen[start] = True
        queue = deque([start])
        while queue:
            j, i = queue.popleft()
            for dj, di in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                q = (j + dj, i + di)
                if 0 <= q[0] < ny and 0 <= q[1] < nx and mask[q] and not seen[q]:
                    seen[q] = True
                    queue.append(q)
    return count


def part_count(groups, group_masks):
    """Number of separate parts of a glyph: groups that overlap or touch
    form one part.

    Args:
        groups: contour groups.
        group_masks: their masks from rasterise().

    Returns:
        (count, labels): number of parts and the part number of each group.
    """
    n = len(groups)
    parent = list(range(n))

    def root(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    grown = [grow1(m) for m in group_masks]
    for i in range(n):
        for j in range(i + 1, n):
            if (grown[i] & group_masks[j]).any():
                parent[root(i)] = root(j)
    roots = sorted({root(i) for i in range(n)})
    labels = [roots.index(root(i)) for i in range(n)]
    return len(roots), labels


def grow1(mask):
    """Mask grown by one cell in the four axis directions."""
    out = mask.copy()
    out[1:] |= mask[:-1]
    out[:-1] |= mask[1:]
    out[:, 1:] |= mask[:, :-1]
    out[:, :-1] |= mask[:, 1:]
    return out