wobblyhead hg > 3dprints > house_number
comparison make_glyphs.py @ 0:b5a96b547b01
initial public version
| author | ark |
|---|---|
| date | 2026-11-03 01:29 +0100 |
| parents | |
| children | 4836a7408849 |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:b5a96b547b01 |
|---|---|
| 1 #!/usr/bin/env python3 | |
| 2 """Write glyph outlines and screw hole positions for the OpenSCAD model. | |
| 3 | |
| 4 For one font and text, this writes an SVG file per glyph and a check image | |
| 5 per glyph into generated/<font>_<text>/, and the data file glyphs.scad, | |
| 6 which main.scad includes. All sizes are in mm at the size the holes were | |
| 7 placed for. | |
| 8 | |
| 9 Holes: per glyph one near the top and one near the bottom end, along the | |
| 10 glyph's main axis, in the middle of the stroke and with room for the | |
| 11 countersink head plus a minimum wall. See place_holes(). | |
| 12 """ | |
| 13 | |
| 14 import argparse | |
| 15 import logging | |
| 16 import math | |
| 17 import os | |
| 18 import re | |
| 19 import shlex | |
| 20 import sys | |
| 21 | |
| 22 import numpy as np | |
| 23 from PIL import Image, ImageDraw | |
| 24 | |
| 25 import fontlib as fl | |
| 26 | |
| 27 | |
| 28 def parse_args(): | |
| 29 """Parse the command line.""" | |
| 30 p = argparse.ArgumentParser(description=__doc__, | |
| 31 formatter_class=argparse.RawDescriptionHelpFormatter) | |
| 32 p.add_argument("font", help="PostScript name of the font, or the path of its preview PNG") | |
| 33 p.add_argument("text", help="the text, one line") | |
| 34 p.add_argument("--out", default="generated", | |
| 35 help="directory for the glyph directories (default: %(default)s)") | |
| 36 p.add_argument("--data", default="glyphs.scad", | |
| 37 help="data file for main.scad (default: %(default)s)") | |
| 38 s = p.add_argument_group("size") | |
| 39 s.add_argument("--layout", choices=["text", "glyph"], default="glyph", | |
| 40 help="layout whose maximum size is the default size (default: %(default)s)") | |
| 41 s.add_argument("--angle", type=float, default=0, | |
| 42 help="rotation on the bed in degrees, for the default size; " | |
| 43 "-1 for the best angle (default: %(default)s)") | |
| 44 s.add_argument("--size", type=float, | |
| 45 help="height of the tallest glyph in mm (default: the maximum)") | |
| 46 h = p.add_argument_group("holes") | |
| 47 h.add_argument("--screw-d", type=float, default=4, | |
| 48 help="screw diameter in mm, for the check images (default: %(default)s)") | |
| 49 h.add_argument("--head-d", type=float, default=8, | |
| 50 help="countersink head diameter in mm (default: %(default)s)") | |
| 51 h.add_argument("--wall-lines", type=float, default=2, | |
| 52 help="minimum wall around the head, in line widths (default: %(default)s)") | |
| 53 h.add_argument("--target", type=float, default=.85, | |
| 54 help="position of the top hole along the axis, 0 bottom to 1 top; " | |
| 55 "the bottom hole mirrors it (default: %(default)s)") | |
| 56 h.add_argument("--side-weight", type=float, default=.5, | |
| 57 help="penalty for sideways distance from the axis (default: %(default)s)") | |
| 58 h.add_argument("--centre-weight", type=float, default=.3, | |
| 59 help="reward for sitting in the middle of the stroke (default: %(default)s)") | |
| 60 h.add_argument("--vertical-axis", action="store_true", | |
| 61 help="use a vertical axis instead of the glyph's main axis") | |
| 62 h.add_argument("--grid", type=float, default=.5, | |
| 63 help="sample spacing in mm (default: %(default)s)") | |
| 64 b = p.add_argument_group("printer") | |
| 65 b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)") | |
| 66 b.add_argument("--margin", type=float, default=10, | |
| 67 help="bed margin in mm (default: %(default)s)") | |
| 68 b.add_argument("--line-width", type=float, default=.4, | |
| 69 help="line width in mm (default: %(default)s)") | |
| 70 return p.parse_args() | |
| 71 | |
| 72 | |
| 73 def warn(msg): | |
| 74 """Print a warning to stderr.""" | |
| 75 print(f"warning: {msg}", file=sys.stderr) | |
| 76 | |
| 77 | |
| 78 def text_name(text): | |
| 79 """Text as a file name part: letters and digits kept, other characters | |
| 80 as u and their hexadecimal code point.""" | |
| 81 return "".join(c if re.fullmatch(r"[A-Za-z0-9]", c) else f"u{ord(c):04x}" for c in text) | |
| 82 | |
| 83 | |
| 84 # --------------------------------------------------------------- hole placement | |
| 85 | |
| 86 def place_holes(g, args): | |
| 87 """Find the two screw hole positions of a glyph. | |
| 88 | |
| 89 1. Distance from each inside grid point to the outline. | |
| 90 2. Allowed points: room for the countersink head plus the minimum wall. | |
| 91 3. Axis: main axis of the inked area (or vertical), pointing up. | |
| 92 4. Each point gets a position along the axis, 0 at the lower end and 1 | |
| 93 at the upper end, and a sideways distance from the axis. | |
| 94 5. In each half, the allowed point with the best score wins. The score | |
| 95 rewards closeness to the target position, penalises sideways | |
| 96 distance relative to the glyph length, and rewards being in the | |
| 97 middle of the stroke: distance to the outline relative to the | |
| 98 largest distance nearby. | |
| 99 6. A half without allowed points gets its largest inscribed circle. | |
| 100 | |
| 101 Args: | |
| 102 g: Glyph in mm. | |
| 103 args: command line arguments. | |
| 104 | |
| 105 Returns: | |
| 106 dict with 'holes' ([[x, y, r], [x, y, r]], top first, r the radius of | |
| 107 the largest circle that fits there), 'fits' (per hole), 'grid', | |
| 108 'mask', 'allowed', 'axis' (centre, direction, lower and upper end | |
| 109 along the axis), 'r_req' and 'group_masks'. | |
| 110 """ | |
| 111 r_req = args.head_d / 2 + args.wall_lines * args.line_width | |
| 112 grid = fl.Grid.around(g.bbox(), args.grid, 2 * args.grid) | |
| 113 mask, group_masks = fl.rasterise(g.groups, grid) | |
| 114 pts = grid.points().reshape(grid.ny, grid.nx, 2) | |
| 115 a, b = fl.boundary_segments(g.groups, 1.0) | |
| 116 d = np.zeros(mask.shape) | |
| 117 d[mask] = fl.distance_to_segments(pts[mask], a, b) | |
| 118 | |
| 119 inside = pts[mask] | |
| 120 centre = inside.mean(axis=0) | |
| 121 if args.vertical_axis: | |
| 122 axis = np.array([0.0, 1.0]) | |
| 123 else: | |
| 124 evals, evecs = np.linalg.eigh(np.cov((inside - centre).T)) | |
| 125 axis = evecs[:, int(np.argmax(evals))] | |
| 126 if axis[1] < 0 or (axis[1] == 0 and axis[0] < 0): | |
| 127 axis = -axis | |
| 128 normal = np.array([-axis[1], axis[0]]) | |
| 129 s = (pts - centre) @ axis | |
| 130 u = (pts - centre) @ normal | |
| 131 smin, smax = s[mask].min(), s[mask].max() | |
| 132 length = smax - smin | |
| 133 t = (s - smin) / length | |
| 134 | |
| 135 radius = max(1, int(math.ceil(d.max() / grid.step))) | |
| 136 nearby = fl.max_filter(d, radius) | |
| 137 centred = d / np.maximum(nearby, 1e-9) | |
| 138 score = (-np.abs(t - np.where(t >= .5, args.target, 1 - args.target)) | |
| 139 - args.side_weight * np.abs(u) / length | |
| 140 + args.centre_weight * centred) | |
| 141 allowed = mask & (d >= r_req) | |
| 142 | |
| 143 holes, fits = [], [] | |
| 144 for half in (t >= .5, t <= .5): | |
| 145 cand = allowed & half | |
| 146 fits.append(bool(cand.any())) | |
| 147 if cand.any(): | |
| 148 idx = np.unravel_index(np.argmax(np.where(cand, score, -np.inf)), mask.shape) | |
| 149 else: | |
| 150 cand = mask & half | |
| 151 idx = np.unravel_index(np.argmax(np.where(cand, d, -np.inf)), mask.shape) | |
| 152 holes.append([*pts[idx], d[idx]]) | |
| 153 return {"holes": holes, "fits": fits, "grid": grid, "mask": mask, "allowed": allowed, | |
| 154 "axis": (centre, axis, smin, smax), "r_req": r_req, "group_masks": group_masks} | |
| 155 | |
| 156 | |
| 157 # --------------------------------------------------------------------- backing | |
| 158 | |
| 159 def closing_connected(groups, radius, step): | |
| 160 """True if growing the outline by radius and shrinking it back gives a | |
| 161 single piece. Checked on a grid of the given step.""" | |
| 162 pts_all = np.concatenate([c for grp in groups for c in grp]) | |
| 163 bbox = (*pts_all.min(axis=0), *pts_all.max(axis=0)) | |
| 164 grid = fl.Grid.around(bbox, step, radius + 3 * step) | |
| 165 mask, _ = fl.rasterise(groups, grid) | |
| 166 pts = grid.points() | |
| 167 flat = mask.ravel() | |
| 168 a, b = fl.boundary_segments(groups, 1.0) | |
| 169 d_out = np.full(len(pts), np.inf) | |
| 170 d_out[~flat] = fl.distance_to_segments(pts[~flat], a, b) | |
| 171 grown = mask | (d_out.reshape(mask.shape) <= radius) | |
| 172 # shrink: keep points at least radius from the cells outside the grown shape | |
| 173 edge = ~grown & fl.grow1(grown) | |
| 174 q = pts[edge.ravel()] | |
| 175 keep = np.zeros(len(pts), dtype=bool) | |
| 176 gflat = grown.ravel() | |
| 177 keep[gflat] = fl.distance_to_segments(pts[gflat], q, q) >= radius - step / 2 | |
| 178 closed = mask | keep.reshape(mask.shape) | |
| 179 return fl.components(closed) == 1 | |
| 180 | |
| 181 | |
| 182 def backing_radius(g, labels, count, args): | |
| 183 """Radius for growing and shrinking the outline so that the backing | |
| 184 connects all parts of a glyph. | |
| 185 | |
| 186 The gaps between parts are measured, and the largest gap needed to | |
| 187 connect them all is found (largest edge of a minimum spanning tree). | |
| 188 Radii from half that gap upwards are tried until the result is one | |
| 189 piece. | |
| 190 | |
| 191 Returns: | |
| 192 the radius in mm, 0 for a glyph of one part, -1 if no tried radius | |
| 193 connects the parts (the backing then uses the convex hull). | |
| 194 """ | |
| 195 if count == 1: | |
| 196 return 0.0 | |
| 197 parts = [[grp for grp, lab in zip(g.groups, labels) if lab == p] for p in range(count)] | |
| 198 segs = [fl.boundary_segments(pg, 1.0) for pg in parts] | |
| 199 gap = np.zeros((count, count)) | |
| 200 for i in range(count): | |
| 201 for j in range(count): | |
| 202 if i != j: | |
| 203 gap[i, j] = fl.distance_to_segments(segs[i][0], *segs[j]).min() | |
| 204 gap = np.minimum(gap, gap.T) | |
| 205 # Prim's algorithm for the minimum spanning tree | |
| 206 in_tree, worst = {0}, 0.0 | |
| 207 while len(in_tree) < count: | |
| 208 best = min((gap[i, j], j) for i in in_tree for j in range(count) if j not in in_tree) | |
| 209 worst = max(worst, best[0]) | |
| 210 in_tree.add(best[1]) | |
| 211 for radius in (worst / 2 + args.line_width, worst, 1.5 * worst, 2 * worst): | |
| 212 step = max(args.grid, min(1.0, radius / 3)) | |
| 213 if closing_connected(g.groups, radius, step): | |
| 214 return radius | |
| 215 return -1.0 | |
| 216 | |
| 217 | |
| 218 # ---------------------------------------------------------------------- output | |
| 219 | |
| 220 def write_svg(path, g): | |
| 221 """Write the glyph as SVG, one path element per contour group. | |
| 222 | |
| 223 OpenSCAD fills each path element by the even-odd rule and combines the | |
| 224 elements. Coordinates are mm, glyph origin at the SVG origin. The page | |
| 225 is the positive quadrant up to the glyph's extent; OpenSCAD maps an SVG | |
| 226 point (x, y) to (x, page height - y). | |
| 227 """ | |
| 228 _, _, xmax, ymax = g.bbox() | |
| 229 w, h = max(xmax, 1.0), max(ymax, 1.0) | |
| 230 paths = [] | |
| 231 for group in g.groups: | |
| 232 d = " ".join("M " + " L ".join(f"{x:.4f},{h - y:.4f}" for x, y in c) + " Z" | |
| 233 for c in group) | |
| 234 paths.append(f'<path d="{d}"/>') | |
| 235 with open(path, "w") as f: | |
| 236 f.write(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w:.4f}mm" ' | |
| 237 f'height="{h:.4f}mm" viewBox="0 0 {w:.4f} {h:.4f}">\n') | |
| 238 f.write("\n".join(paths)) | |
| 239 f.write("\n</svg>\n") | |
| 240 | |
| 241 | |
| 242 def write_check_image(path, res, args): | |
| 243 """Write an image of the hole placement: glyph grey, allowed area green, | |
| 244 axis blue, screw hole and countersink head red.""" | |
| 245 grid, mask, allowed = res["grid"], res["mask"], res["allowed"] | |
| 246 img = np.full(mask.shape + (3,), 255, dtype=np.uint8) | |
| 247 img[mask] = (190, 190, 190) | |
| 248 img[allowed] = (170, 220, 170) | |
| 249 im = Image.fromarray(img[::-1]) | |
| 250 d = ImageDraw.Draw(im) | |
| 251 | |
| 252 def px(x, y): | |
| 253 return ((x - grid.x0) / grid.step, grid.ny - 1 - (y - grid.y0) / grid.step) | |
| 254 | |
| 255 centre, axis, smin, smax = res["axis"] | |
| 256 d.line([px(*(centre + smin * axis)), px(*(centre + smax * axis))], | |
| 257 fill=(40, 80, 220), width=3) | |
| 258 for (x, y, r), fits in zip(res["holes"], res["fits"]): | |
| 259 cx, cy = px(x, y) | |
| 260 for rad, width in ((args.head_d / 2, 3), (res["r_req"], 1)): | |
| 261 rp = rad / grid.step | |
| 262 d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp), outline=(200, 30, 30), width=width) | |
| 263 rp = args.screw_d / 2 / grid.step | |
| 264 d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp), | |
| 265 fill=(200, 30, 30) if fits else (240, 140, 0)) | |
| 266 im.save(path, optimize=True) | |
| 267 | |
| 268 | |
| 269 def scad_str(s): | |
| 270 """OpenSCAD string literal.""" | |
| 271 return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"' | |
| 272 | |
| 273 | |
| 274 def scad_num(v): | |
| 275 """Number for OpenSCAD with 4 decimals, trailing zeros removed.""" | |
| 276 return f"{v:.4f}".rstrip("0").rstrip(".") | |
| 277 | |
| 278 | |
| 279 def scad_pts(pts): | |
| 280 """List of points for OpenSCAD.""" | |
| 281 return "[" + ", ".join(f"[{scad_num(x)}, {scad_num(y)}]" for x, y in pts) + "]" | |
| 282 | |
| 283 | |
| 284 # ------------------------------------------------------------------------ main | |
| 285 | |
| 286 def main(): | |
| 287 """Lay out the text, place the holes and write the output files.""" | |
| 288 logging.disable(logging.WARNING) | |
| 289 args = parse_args() | |
| 290 info = fl.find_face(args.font) | |
| 291 face = fl.Face(info) | |
| 292 missing = [c for c in args.text if ord(c) not in face.cmap] | |
| 293 if missing: | |
| 294 sys.exit(f"{info.psname} has no glyph for {''.join(missing)!r}") | |
| 295 placed = face.layout(args.text) | |
| 296 if all(g.empty for _, g in placed): | |
| 297 sys.exit("the text has no visible glyphs") | |
| 298 for _, g in placed: | |
| 299 if g.fill_error > 0.001: | |
| 300 warn(f"{g.char!r}: outline differs from the font's filling " | |
| 301 f"on {100 * g.fill_error:.1f}% of its area") | |
| 302 | |
| 303 usable = fl.usable_area(args.bed, args.margin, args.line_width) | |
| 304 sizes = fl.max_sizes(placed, usable) | |
| 305 angle = sizes[args.layout]["angle"] if args.angle < 0 else args.angle | |
| 306 size_max = fl.size_at(placed, usable, args.layout, angle) | |
| 307 size = args.size or size_max | |
| 308 if size > size_max + 1e-6: | |
| 309 warn(f"size {size:.1f} mm exceeds the maximum of {size_max:.1f} mm " | |
| 310 f"for the {args.layout} layout at {angle:g} degrees") | |
| 311 height = max(g.bbox()[3] - g.bbox()[1] for _, g in placed if not g.empty) | |
| 312 k = size / height | |
| 313 | |
| 314 name = f"{info.file_name}_{text_name(args.text)}" | |
| 315 outdir = os.path.join(args.out, name) | |
| 316 os.makedirs(outdir, exist_ok=True) | |
| 317 for f in os.listdir(outdir): | |
| 318 if f.endswith((".svg", ".png")): | |
| 319 os.remove(os.path.join(outdir, f)) | |
| 320 | |
| 321 print(f"font {info.psname} ({info.family} {info.style}), text {args.text!r}") | |
| 322 print(f"maximum size: text layout {sizes['text']['size0']:.1f} mm, " | |
| 323 f"best {sizes['text']['size']:.1f} mm at {sizes['text']['angle']} degrees; " | |
| 324 f"glyph layout {sizes['glyph']['size0']:.1f} mm, " | |
| 325 f"best {sizes['glyph']['size']:.1f} mm at {sizes['glyph']['angle']} degrees") | |
| 326 print(f"holes placed for size {size:.1f} mm") | |
| 327 | |
| 328 done, entries = {}, [] | |
| 329 for x, g in placed: | |
| 330 if g.empty: | |
| 331 continue | |
| 332 stem = f"u{ord(g.char):04x}" | |
| 333 if g.char not in done: | |
| 334 gm = g.scaled(k) | |
| 335 res = place_holes(gm, args) | |
| 336 count, labels = fl.part_count(gm.groups, res["group_masks"]) | |
| 337 back_r = backing_radius(gm, labels, count, args) | |
| 338 write_svg(os.path.join(outdir, stem + ".svg"), gm) | |
| 339 write_check_image(os.path.join(outdir, f"check_{stem}.png"), res, args) | |
| 340 hull = fl.convex_hull(np.concatenate(gm.contours)) | |
| 341 done[g.char] = (gm, res, count, back_r, hull) | |
| 342 for (hx, hy, r), fits, where in zip(res["holes"], res["fits"], ("top", "bottom")): | |
| 343 if not fits: | |
| 344 warn(f"{g.char!r}: no room for the countersink head at the {where} hole: " | |
| 345 f"largest circle radius {r:.1f} mm, needed {res['r_req']:.1f} mm") | |
| 346 if count > 1: | |
| 347 warn(f"{g.char!r} has {count} separate parts; print it with backing") | |
| 348 if back_r < 0: | |
| 349 warn(f"{g.char!r}: growing and shrinking does not connect the parts; " | |
| 350 f"the backing uses the convex hull") | |
| 351 print(f"{g.char!r}: holes " + ", ".join( | |
| 352 f"({hx:.1f}, {hy:.1f}) r {r:.1f}" for hx, hy, r in res["holes"]) | |
| 353 + (f", {count} parts, backing radius {back_r:.1f}" if count > 1 else "")) | |
| 354 gm, res, count, back_r, hull = done[g.char] | |
| 355 entries.append((g.char, f"{outdir}/{stem}.svg", x * k, gm.bbox(), hull, | |
| 356 res["holes"], count, back_r)) | |
| 357 | |
| 358 with open(args.data, "w") as f: | |
| 359 f.write(f"// generated by make_glyphs.py, do not edit\n" | |
| 360 f"// {shlex.join(['make_glyphs.py'] + sys.argv[1:])}\n\n") | |
| 361 f.write(f"g_font = {scad_str(info.psname)};\n") | |
| 362 f.write(f"g_text = {scad_str(args.text)};\n") | |
| 363 f.write(f"// font and text for file names\ng_name = {scad_str(name)};\n") | |
| 364 f.write(f"// height of the tallest glyph in mm; all lengths below are at this size\n" | |
| 365 f"g_size = {scad_num(size)};\n") | |
| 366 f.write(f"// placement parameters: head diameter, wall in line widths, line width\n" | |
| 367 f"g_placement = [{scad_num(args.head_d)}, {scad_num(args.wall_lines)}, " | |
| 368 f"{scad_num(args.line_width)}];\n") | |
| 369 f.write("// maximum sizes in mm: [size at 0 degrees, best angle, size at best angle]\n") | |
| 370 for layout in ("text", "glyph"): | |
| 371 m = sizes[layout] | |
| 372 f.write(f"g_max_{layout} = [{scad_num(m['size0'])}, {m['angle']}, " | |
| 373 f"{scad_num(m['size'])}];\n") | |
| 374 f.write("// glyphs without spaces: [character, svg file, x offset in the text,\n" | |
| 375 "// ink bounding box [xmin, ymin, xmax, ymax], convex hull,\n" | |
| 376 "// holes [[x, y, largest circle radius], ...] top first, parts,\n" | |
| 377 "// backing radius (0 one part, -1 convex hull)]\n") | |
| 378 f.write("g_glyphs = [\n") | |
| 379 for char, svg, off, bbox, hull, holes, count, back_r in entries: | |
| 380 f.write(f" [{scad_str(char)}, {scad_str(svg)}, {scad_num(off)},\n" | |
| 381 f" [{', '.join(scad_num(v) for v in bbox)}],\n" | |
| 382 f" {scad_pts(hull)},\n" | |
| 383 f" [{', '.join('[' + ', '.join(scad_num(v) for v in h) + ']' for h in holes)}]," | |
| 384 f" {count}, {scad_num(back_r)}],\n") | |
| 385 f.write("];\n") | |
| 386 print(f"wrote {outdir}/ and {args.data}") | |
| 387 | |
| 388 | |
| 389 if __name__ == "__main__": | |
| 390 main() |
