diff make_glyphs.py @ 0:b5a96b547b01

initial public version
author ark
date 2026-11-03 01:29 +0100
parents
children 4836a7408849
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make_glyphs.py	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,390 @@
+#!/usr/bin/env python3
+"""Write glyph outlines and screw hole positions for the OpenSCAD model.
+
+For one font and text, this writes an SVG file per glyph and a check image
+per glyph into generated/<font>_<text>/, and the data file glyphs.scad,
+which main.scad includes. All sizes are in mm at the size the holes were
+placed for.
+
+Holes: per glyph one near the top and one near the bottom end, along the
+glyph's main axis, in the middle of the stroke and with room for the
+countersink head plus a minimum wall. See place_holes().
+"""
+
+import argparse
+import logging
+import math
+import os
+import re
+import shlex
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw
+
+import fontlib as fl
+
+
+def parse_args():
+    """Parse the command line."""
+    p = argparse.ArgumentParser(description=__doc__,
+                                formatter_class=argparse.RawDescriptionHelpFormatter)
+    p.add_argument("font", help="PostScript name of the font, or the path of its preview PNG")
+    p.add_argument("text", help="the text, one line")
+    p.add_argument("--out", default="generated",
+                   help="directory for the glyph directories (default: %(default)s)")
+    p.add_argument("--data", default="glyphs.scad",
+                   help="data file for main.scad (default: %(default)s)")
+    s = p.add_argument_group("size")
+    s.add_argument("--layout", choices=["text", "glyph"], default="glyph",
+                   help="layout whose maximum size is the default size (default: %(default)s)")
+    s.add_argument("--angle", type=float, default=0,
+                   help="rotation on the bed in degrees, for the default size; "
+                        "-1 for the best angle (default: %(default)s)")
+    s.add_argument("--size", type=float,
+                   help="height of the tallest glyph in mm (default: the maximum)")
+    h = p.add_argument_group("holes")
+    h.add_argument("--screw-d", type=float, default=4,
+                   help="screw diameter in mm, for the check images (default: %(default)s)")
+    h.add_argument("--head-d", type=float, default=8,
+                   help="countersink head diameter in mm (default: %(default)s)")
+    h.add_argument("--wall-lines", type=float, default=2,
+                   help="minimum wall around the head, in line widths (default: %(default)s)")
+    h.add_argument("--target", type=float, default=.85,
+                   help="position of the top hole along the axis, 0 bottom to 1 top; "
+                        "the bottom hole mirrors it (default: %(default)s)")
+    h.add_argument("--side-weight", type=float, default=.5,
+                   help="penalty for sideways distance from the axis (default: %(default)s)")
+    h.add_argument("--centre-weight", type=float, default=.3,
+                   help="reward for sitting in the middle of the stroke (default: %(default)s)")
+    h.add_argument("--vertical-axis", action="store_true",
+                   help="use a vertical axis instead of the glyph's main axis")
+    h.add_argument("--grid", type=float, default=.5,
+                   help="sample spacing in mm (default: %(default)s)")
+    b = p.add_argument_group("printer")
+    b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)")
+    b.add_argument("--margin", type=float, default=10,
+                   help="bed margin in mm (default: %(default)s)")
+    b.add_argument("--line-width", type=float, default=.4,
+                   help="line width in mm (default: %(default)s)")
+    return p.parse_args()
+
+
+def warn(msg):
+    """Print a warning to stderr."""
+    print(f"warning: {msg}", file=sys.stderr)
+
+
+def text_name(text):
+    """Text as a file name part: letters and digits kept, other characters
+    as u and their hexadecimal code point."""
+    return "".join(c if re.fullmatch(r"[A-Za-z0-9]", c) else f"u{ord(c):04x}" for c in text)
+
+
+# --------------------------------------------------------------- hole placement
+
+def place_holes(g, args):
+    """Find the two screw hole positions of a glyph.
+
+    1. Distance from each inside grid point to the outline.
+    2. Allowed points: room for the countersink head plus the minimum wall.
+    3. Axis: main axis of the inked area (or vertical), pointing up.
+    4. Each point gets a position along the axis, 0 at the lower end and 1
+       at the upper end, and a sideways distance from the axis.
+    5. In each half, the allowed point with the best score wins. The score
+       rewards closeness to the target position, penalises sideways
+       distance relative to the glyph length, and rewards being in the
+       middle of the stroke: distance to the outline relative to the
+       largest distance nearby.
+    6. A half without allowed points gets its largest inscribed circle.
+
+    Args:
+        g: Glyph in mm.
+        args: command line arguments.
+
+    Returns:
+        dict with 'holes' ([[x, y, r], [x, y, r]], top first, r the radius of
+        the largest circle that fits there), 'fits' (per hole), 'grid',
+        'mask', 'allowed', 'axis' (centre, direction, lower and upper end
+        along the axis), 'r_req' and 'group_masks'.
+    """
+    r_req = args.head_d / 2 + args.wall_lines * args.line_width
+    grid = fl.Grid.around(g.bbox(), args.grid, 2 * args.grid)
+    mask, group_masks = fl.rasterise(g.groups, grid)
+    pts = grid.points().reshape(grid.ny, grid.nx, 2)
+    a, b = fl.boundary_segments(g.groups, 1.0)
+    d = np.zeros(mask.shape)
+    d[mask] = fl.distance_to_segments(pts[mask], a, b)
+
+    inside = pts[mask]
+    centre = inside.mean(axis=0)
+    if args.vertical_axis:
+        axis = np.array([0.0, 1.0])
+    else:
+        evals, evecs = np.linalg.eigh(np.cov((inside - centre).T))
+        axis = evecs[:, int(np.argmax(evals))]
+    if axis[1] < 0 or (axis[1] == 0 and axis[0] < 0):
+        axis = -axis
+    normal = np.array([-axis[1], axis[0]])
+    s = (pts - centre) @ axis
+    u = (pts - centre) @ normal
+    smin, smax = s[mask].min(), s[mask].max()
+    length = smax - smin
+    t = (s - smin) / length
+
+    radius = max(1, int(math.ceil(d.max() / grid.step)))
+    nearby = fl.max_filter(d, radius)
+    centred = d / np.maximum(nearby, 1e-9)
+    score = (-np.abs(t - np.where(t >= .5, args.target, 1 - args.target))
+             - args.side_weight * np.abs(u) / length
+             + args.centre_weight * centred)
+    allowed = mask & (d >= r_req)
+
+    holes, fits = [], []
+    for half in (t >= .5, t <= .5):
+        cand = allowed & half
+        fits.append(bool(cand.any()))
+        if cand.any():
+            idx = np.unravel_index(np.argmax(np.where(cand, score, -np.inf)), mask.shape)
+        else:
+            cand = mask & half
+            idx = np.unravel_index(np.argmax(np.where(cand, d, -np.inf)), mask.shape)
+        holes.append([*pts[idx], d[idx]])
+    return {"holes": holes, "fits": fits, "grid": grid, "mask": mask, "allowed": allowed,
+            "axis": (centre, axis, smin, smax), "r_req": r_req, "group_masks": group_masks}
+
+
+# --------------------------------------------------------------------- backing
+
+def closing_connected(groups, radius, step):
+    """True if growing the outline by radius and shrinking it back gives a
+    single piece. Checked on a grid of the given step."""
+    pts_all = np.concatenate([c for grp in groups for c in grp])
+    bbox = (*pts_all.min(axis=0), *pts_all.max(axis=0))
+    grid = fl.Grid.around(bbox, step, radius + 3 * step)
+    mask, _ = fl.rasterise(groups, grid)
+    pts = grid.points()
+    flat = mask.ravel()
+    a, b = fl.boundary_segments(groups, 1.0)
+    d_out = np.full(len(pts), np.inf)
+    d_out[~flat] = fl.distance_to_segments(pts[~flat], a, b)
+    grown = mask | (d_out.reshape(mask.shape) <= radius)
+    # shrink: keep points at least radius from the cells outside the grown shape
+    edge = ~grown & fl.grow1(grown)
+    q = pts[edge.ravel()]
+    keep = np.zeros(len(pts), dtype=bool)
+    gflat = grown.ravel()
+    keep[gflat] = fl.distance_to_segments(pts[gflat], q, q) >= radius - step / 2
+    closed = mask | keep.reshape(mask.shape)
+    return fl.components(closed) == 1
+
+
+def backing_radius(g, labels, count, args):
+    """Radius for growing and shrinking the outline so that the backing
+    connects all parts of a glyph.
+
+    The gaps between parts are measured, and the largest gap needed to
+    connect them all is found (largest edge of a minimum spanning tree).
+    Radii from half that gap upwards are tried until the result is one
+    piece.
+
+    Returns:
+        the radius in mm, 0 for a glyph of one part, -1 if no tried radius
+        connects the parts (the backing then uses the convex hull).
+    """
+    if count == 1:
+        return 0.0
+    parts = [[grp for grp, lab in zip(g.groups, labels) if lab == p] for p in range(count)]
+    segs = [fl.boundary_segments(pg, 1.0) for pg in parts]
+    gap = np.zeros((count, count))
+    for i in range(count):
+        for j in range(count):
+            if i != j:
+                gap[i, j] = fl.distance_to_segments(segs[i][0], *segs[j]).min()
+    gap = np.minimum(gap, gap.T)
+    # Prim's algorithm for the minimum spanning tree
+    in_tree, worst = {0}, 0.0
+    while len(in_tree) < count:
+        best = min((gap[i, j], j) for i in in_tree for j in range(count) if j not in in_tree)
+        worst = max(worst, best[0])
+        in_tree.add(best[1])
+    for radius in (worst / 2 + args.line_width, worst, 1.5 * worst, 2 * worst):
+        step = max(args.grid, min(1.0, radius / 3))
+        if closing_connected(g.groups, radius, step):
+            return radius
+    return -1.0
+
+
+# ---------------------------------------------------------------------- output
+
+def write_svg(path, g):
+    """Write the glyph as SVG, one path element per contour group.
+
+    OpenSCAD fills each path element by the even-odd rule and combines the
+    elements. Coordinates are mm, glyph origin at the SVG origin. The page
+    is the positive quadrant up to the glyph's extent; OpenSCAD maps an SVG
+    point (x, y) to (x, page height - y).
+    """
+    _, _, xmax, ymax = g.bbox()
+    w, h = max(xmax, 1.0), max(ymax, 1.0)
+    paths = []
+    for group in g.groups:
+        d = " ".join("M " + " L ".join(f"{x:.4f},{h - y:.4f}" for x, y in c) + " Z"
+                     for c in group)
+        paths.append(f'<path d="{d}"/>')
+    with open(path, "w") as f:
+        f.write(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w:.4f}mm" '
+                f'height="{h:.4f}mm" viewBox="0 0 {w:.4f} {h:.4f}">\n')
+        f.write("\n".join(paths))
+        f.write("\n</svg>\n")
+
+
+def write_check_image(path, res, args):
+    """Write an image of the hole placement: glyph grey, allowed area green,
+    axis blue, screw hole and countersink head red."""
+    grid, mask, allowed = res["grid"], res["mask"], res["allowed"]
+    img = np.full(mask.shape + (3,), 255, dtype=np.uint8)
+    img[mask] = (190, 190, 190)
+    img[allowed] = (170, 220, 170)
+    im = Image.fromarray(img[::-1])
+    d = ImageDraw.Draw(im)
+
+    def px(x, y):
+        return ((x - grid.x0) / grid.step, grid.ny - 1 - (y - grid.y0) / grid.step)
+
+    centre, axis, smin, smax = res["axis"]
+    d.line([px(*(centre + smin * axis)), px(*(centre + smax * axis))],
+           fill=(40, 80, 220), width=3)
+    for (x, y, r), fits in zip(res["holes"], res["fits"]):
+        cx, cy = px(x, y)
+        for rad, width in ((args.head_d / 2, 3), (res["r_req"], 1)):
+            rp = rad / grid.step
+            d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp), outline=(200, 30, 30), width=width)
+        rp = args.screw_d / 2 / grid.step
+        d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp),
+                  fill=(200, 30, 30) if fits else (240, 140, 0))
+    im.save(path, optimize=True)
+
+
+def scad_str(s):
+    """OpenSCAD string literal."""
+    return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def scad_num(v):
+    """Number for OpenSCAD with 4 decimals, trailing zeros removed."""
+    return f"{v:.4f}".rstrip("0").rstrip(".")
+
+
+def scad_pts(pts):
+    """List of points for OpenSCAD."""
+    return "[" + ", ".join(f"[{scad_num(x)}, {scad_num(y)}]" for x, y in pts) + "]"
+
+
+# ------------------------------------------------------------------------ main
+
+def main():
+    """Lay out the text, place the holes and write the output files."""
+    logging.disable(logging.WARNING)
+    args = parse_args()
+    info = fl.find_face(args.font)
+    face = fl.Face(info)
+    missing = [c for c in args.text if ord(c) not in face.cmap]
+    if missing:
+        sys.exit(f"{info.psname} has no glyph for {''.join(missing)!r}")
+    placed = face.layout(args.text)
+    if all(g.empty for _, g in placed):
+        sys.exit("the text has no visible glyphs")
+    for _, g in placed:
+        if g.fill_error > 0.001:
+            warn(f"{g.char!r}: outline differs from the font's filling "
+                 f"on {100 * g.fill_error:.1f}% of its area")
+
+    usable = fl.usable_area(args.bed, args.margin, args.line_width)
+    sizes = fl.max_sizes(placed, usable)
+    angle = sizes[args.layout]["angle"] if args.angle < 0 else args.angle
+    size_max = fl.size_at(placed, usable, args.layout, angle)
+    size = args.size or size_max
+    if size > size_max + 1e-6:
+        warn(f"size {size:.1f} mm exceeds the maximum of {size_max:.1f} mm "
+             f"for the {args.layout} layout at {angle:g} degrees")
+    height = max(g.bbox()[3] - g.bbox()[1] for _, g in placed if not g.empty)
+    k = size / height
+
+    name = f"{info.file_name}_{text_name(args.text)}"
+    outdir = os.path.join(args.out, name)
+    os.makedirs(outdir, exist_ok=True)
+    for f in os.listdir(outdir):
+        if f.endswith((".svg", ".png")):
+            os.remove(os.path.join(outdir, f))
+
+    print(f"font {info.psname} ({info.family} {info.style}), text {args.text!r}")
+    print(f"maximum size: text layout {sizes['text']['size0']:.1f} mm, "
+          f"best {sizes['text']['size']:.1f} mm at {sizes['text']['angle']} degrees; "
+          f"glyph layout {sizes['glyph']['size0']:.1f} mm, "
+          f"best {sizes['glyph']['size']:.1f} mm at {sizes['glyph']['angle']} degrees")
+    print(f"holes placed for size {size:.1f} mm")
+
+    done, entries = {}, []
+    for x, g in placed:
+        if g.empty:
+            continue
+        stem = f"u{ord(g.char):04x}"
+        if g.char not in done:
+            gm = g.scaled(k)
+            res = place_holes(gm, args)
+            count, labels = fl.part_count(gm.groups, res["group_masks"])
+            back_r = backing_radius(gm, labels, count, args)
+            write_svg(os.path.join(outdir, stem + ".svg"), gm)
+            write_check_image(os.path.join(outdir, f"check_{stem}.png"), res, args)
+            hull = fl.convex_hull(np.concatenate(gm.contours))
+            done[g.char] = (gm, res, count, back_r, hull)
+            for (hx, hy, r), fits, where in zip(res["holes"], res["fits"], ("top", "bottom")):
+                if not fits:
+                    warn(f"{g.char!r}: no room for the countersink head at the {where} hole: "
+                         f"largest circle radius {r:.1f} mm, needed {res['r_req']:.1f} mm")
+            if count > 1:
+                warn(f"{g.char!r} has {count} separate parts; print it with backing")
+                if back_r < 0:
+                    warn(f"{g.char!r}: growing and shrinking does not connect the parts; "
+                         f"the backing uses the convex hull")
+            print(f"{g.char!r}: holes " + ", ".join(
+                f"({hx:.1f}, {hy:.1f}) r {r:.1f}" for hx, hy, r in res["holes"])
+                  + (f", {count} parts, backing radius {back_r:.1f}" if count > 1 else ""))
+        gm, res, count, back_r, hull = done[g.char]
+        entries.append((g.char, f"{outdir}/{stem}.svg", x * k, gm.bbox(), hull,
+                        res["holes"], count, back_r))
+
+    with open(args.data, "w") as f:
+        f.write(f"// generated by make_glyphs.py, do not edit\n"
+                f"// {shlex.join(['make_glyphs.py'] + sys.argv[1:])}\n\n")
+        f.write(f"g_font = {scad_str(info.psname)};\n")
+        f.write(f"g_text = {scad_str(args.text)};\n")
+        f.write(f"// font and text for file names\ng_name = {scad_str(name)};\n")
+        f.write(f"// height of the tallest glyph in mm; all lengths below are at this size\n"
+                f"g_size = {scad_num(size)};\n")
+        f.write(f"// placement parameters: head diameter, wall in line widths, line width\n"
+                f"g_placement = [{scad_num(args.head_d)}, {scad_num(args.wall_lines)}, "
+                f"{scad_num(args.line_width)}];\n")
+        f.write("// maximum sizes in mm: [size at 0 degrees, best angle, size at best angle]\n")
+        for layout in ("text", "glyph"):
+            m = sizes[layout]
+            f.write(f"g_max_{layout} = [{scad_num(m['size0'])}, {m['angle']}, "
+                    f"{scad_num(m['size'])}];\n")
+        f.write("// glyphs without spaces: [character, svg file, x offset in the text,\n"
+                "//   ink bounding box [xmin, ymin, xmax, ymax], convex hull,\n"
+                "//   holes [[x, y, largest circle radius], ...] top first, parts,\n"
+                "//   backing radius (0 one part, -1 convex hull)]\n")
+        f.write("g_glyphs = [\n")
+        for char, svg, off, bbox, hull, holes, count, back_r in entries:
+            f.write(f"  [{scad_str(char)}, {scad_str(svg)}, {scad_num(off)},\n"
+                    f"   [{', '.join(scad_num(v) for v in bbox)}],\n"
+                    f"   {scad_pts(hull)},\n"
+                    f"   [{', '.join('[' + ', '.join(scad_num(v) for v in h) + ']' for h in holes)}],"
+                    f" {count}, {scad_num(back_r)}],\n")
+        f.write("];\n")
+    print(f"wrote {outdir}/ and {args.data}")
+
+
+if __name__ == "__main__":
+    main()