|
0
|
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
|
|
4
|
9 Holes: per glyph two, one near the top and one near the bottom end, along
|
|
|
10 the glyph's main axis; or, with a maximum of three or more, as many as the
|
|
|
11 glyph benefits from, spread around its centre of area. Always in the middle of the stroke and with room for the countersink
|
|
|
12 head plus a minimum wall. See place_holes().
|
|
0
|
13 """
|
|
|
14
|
|
|
15 import argparse
|
|
4
|
16 import itertools
|
|
0
|
17 import logging
|
|
|
18 import math
|
|
|
19 import os
|
|
|
20 import re
|
|
|
21 import shlex
|
|
|
22 import sys
|
|
|
23
|
|
|
24 import numpy as np
|
|
|
25 from PIL import Image, ImageDraw
|
|
|
26
|
|
|
27 import fontlib as fl
|
|
|
28
|
|
|
29
|
|
|
30 def parse_args():
|
|
|
31 """Parse the command line."""
|
|
|
32 p = argparse.ArgumentParser(description=__doc__,
|
|
|
33 formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
|
34 p.add_argument("font", help="PostScript name of the font, or the path of its preview PNG")
|
|
|
35 p.add_argument("text", help="the text, one line")
|
|
|
36 p.add_argument("--out", default="generated",
|
|
|
37 help="directory for the glyph directories (default: %(default)s)")
|
|
|
38 p.add_argument("--data", default="glyphs.scad",
|
|
|
39 help="data file for main.scad (default: %(default)s)")
|
|
|
40 s = p.add_argument_group("size")
|
|
|
41 s.add_argument("--layout", choices=["text", "glyph"], default="glyph",
|
|
|
42 help="layout whose maximum size is the default size (default: %(default)s)")
|
|
|
43 s.add_argument("--angle", type=float, default=0,
|
|
|
44 help="rotation on the bed in degrees, for the default size; "
|
|
|
45 "-1 for the best angle (default: %(default)s)")
|
|
|
46 s.add_argument("--size", type=float,
|
|
|
47 help="height of the tallest glyph in mm (default: the maximum)")
|
|
|
48 h = p.add_argument_group("holes")
|
|
4
|
49 h.add_argument("--holes", type=int, default=2, choices=range(2, MAX_HOLES + 1),
|
|
|
50 metavar="N",
|
|
|
51 help=f"most holes per glyph, 2 to {MAX_HOLES}: 2 along the main axis, "
|
|
|
52 "more spread around the centre (default: %(default)s)")
|
|
0
|
53 h.add_argument("--screw-d", type=float, default=4,
|
|
|
54 help="screw diameter in mm, for the check images (default: %(default)s)")
|
|
|
55 h.add_argument("--head-d", type=float, default=8,
|
|
|
56 help="countersink head diameter in mm (default: %(default)s)")
|
|
|
57 h.add_argument("--wall-lines", type=float, default=2,
|
|
|
58 help="minimum wall around the head, in line widths (default: %(default)s)")
|
|
|
59 h.add_argument("--target", type=float, default=.85,
|
|
4
|
60 help="2 holes: position of the top hole along the axis, 0 bottom to 1 top; "
|
|
0
|
61 "the bottom hole mirrors it (default: %(default)s)")
|
|
|
62 h.add_argument("--side-weight", type=float, default=.5,
|
|
4
|
63 help="2 holes: penalty for sideways distance from the axis "
|
|
|
64 "(default: %(default)s)")
|
|
0
|
65 h.add_argument("--centre-weight", type=float, default=.3,
|
|
4
|
66 help="2 holes: reward for sitting in the middle of the stroke "
|
|
|
67 "(default: %(default)s)")
|
|
0
|
68 h.add_argument("--vertical-axis", action="store_true",
|
|
4
|
69 help="2 holes: use a vertical axis instead of the glyph's main axis")
|
|
|
70 h.add_argument("--hole-gain", type=float, default=.5,
|
|
|
71 help="3 or more holes: a further hole is used only if it moves the "
|
|
|
72 "nearest side of the hole polygon this share further from the "
|
|
|
73 "centre (default: %(default)s)")
|
|
|
74 h.add_argument("--ridge", type=float, default=.8,
|
|
|
75 help="3 or more holes: how close to the middle of the stroke a hole must "
|
|
|
76 "be, as a share of the largest distance to the outline nearby "
|
|
|
77 "(default: %(default)s)")
|
|
0
|
78 h.add_argument("--grid", type=float, default=.5,
|
|
|
79 help="sample spacing in mm (default: %(default)s)")
|
|
|
80 b = p.add_argument_group("printer")
|
|
|
81 b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)")
|
|
|
82 b.add_argument("--margin", type=float, default=10,
|
|
|
83 help="bed margin in mm (default: %(default)s)")
|
|
|
84 b.add_argument("--line-width", type=float, default=.4,
|
|
|
85 help="line width in mm (default: %(default)s)")
|
|
4
|
86 args = p.parse_args()
|
|
|
87 if not 0 <= args.ridge <= 1:
|
|
|
88 p.error("--ridge must be between 0 and 1")
|
|
|
89 return args
|
|
0
|
90
|
|
|
91
|
|
|
92 def warn(msg):
|
|
|
93 """Print a warning to stderr."""
|
|
|
94 print(f"warning: {msg}", file=sys.stderr)
|
|
|
95
|
|
|
96
|
|
|
97 def text_name(text):
|
|
|
98 """Text as a file name part: letters and digits kept, other characters
|
|
|
99 as u and their hexadecimal code point."""
|
|
|
100 return "".join(c if re.fullmatch(r"[A-Za-z0-9]", c) else f"u{ord(c):04x}" for c in text)
|
|
|
101
|
|
|
102
|
|
|
103 # --------------------------------------------------------------- hole placement
|
|
|
104
|
|
4
|
105 MAX_HOLES = 6
|
|
|
106 # most hole combinations tried per glyph with 3 or more holes
|
|
|
107 MAX_COMBINATIONS = 200000
|
|
|
108
|
|
|
109
|
|
0
|
110 def place_holes(g, args):
|
|
4
|
111 """Find the screw hole positions of a glyph.
|
|
0
|
112
|
|
|
113 1. Distance from each inside grid point to the outline.
|
|
|
114 2. Allowed points: room for the countersink head plus the minimum wall.
|
|
4
|
115 3. Centredness of each point: its distance to the outline relative to
|
|
|
116 the largest distance nearby, 1 in the middle of the stroke.
|
|
|
117 4. Two holes: see _holes_axis(). With a maximum of three or more, the
|
|
|
118 fewest holes from 3 up that _holes_spread() can place, then one more
|
|
|
119 at a time while each raises the lever (the distance from the centre
|
|
|
120 to the nearest side of the hole polygon) by --hole-gain. Two holes
|
|
|
121 if not even 3 can be placed. At the default of 50%, in Futura Bold,
|
|
|
122 "W", "M", "H" and "X" get four holes; round glyphs such as "D", "O"
|
|
|
123 and "0" stay at three, where a fourth hole adds 39 to 43%.
|
|
0
|
124
|
|
|
125 Args:
|
|
|
126 g: Glyph in mm.
|
|
|
127 args: command line arguments.
|
|
|
128
|
|
|
129 Returns:
|
|
4
|
130 dict with 'holes' ([[x, y, r], ...], the top one first, then
|
|
|
131 counter-clockwise; r the radius of the largest circle that fits
|
|
|
132 there), 'fits' (per hole), 'reason' (why fewer than the maximum
|
|
|
133 holes, else None), 'grid', 'mask', 'allowed', 'centre' (of
|
|
|
134 the inked area), 'axis' (two holes: centre, direction, lower and
|
|
|
135 upper end along the axis; else None), 'r_req' and 'group_masks'.
|
|
0
|
136 """
|
|
|
137 r_req = args.head_d / 2 + args.wall_lines * args.line_width
|
|
|
138 grid = fl.Grid.around(g.bbox(), args.grid, 2 * args.grid)
|
|
|
139 mask, group_masks = fl.rasterise(g.groups, grid)
|
|
|
140 pts = grid.points().reshape(grid.ny, grid.nx, 2)
|
|
|
141 a, b = fl.boundary_segments(g.groups, 1.0)
|
|
|
142 d = np.zeros(mask.shape)
|
|
|
143 d[mask] = fl.distance_to_segments(pts[mask], a, b)
|
|
4
|
144 centre = pts[mask].mean(axis=0)
|
|
|
145 radius = max(1, int(math.ceil(d.max() / grid.step)))
|
|
|
146 centred = d / np.maximum(fl.max_filter(d, radius), 1e-9)
|
|
|
147 allowed = mask & (d >= r_req)
|
|
0
|
148
|
|
4
|
149 res = {"grid": grid, "mask": mask, "allowed": allowed, "centre": centre, "axis": None,
|
|
|
150 "reason": None, "r_req": r_req, "group_masks": group_masks}
|
|
|
151 best = None
|
|
|
152 for n in range(3, args.holes + 1):
|
|
|
153 r = _holes_spread(pts, mask, d, centred, allowed, centre, r_req, n, args)
|
|
|
154 if r is None:
|
|
|
155 if best is None:
|
|
|
156 continue
|
|
|
157 res["reason"] = f"{n} holes would be too close together or in a line"
|
|
|
158 break
|
|
|
159 if best is not None and r["lever"] < (1 + args.hole_gain) * best["lever"]:
|
|
|
160 gain = 100 * (r["lever"] / best["lever"] - 1)
|
|
|
161 res["reason"] = (f"{n} holes would raise the lever by only {gain:.0f}%"
|
|
|
162 if gain >= .5 else f"{n} holes would not raise the lever")
|
|
|
163 break
|
|
|
164 best = r
|
|
|
165 if best is None:
|
|
|
166 res.update(_holes_axis(pts, mask, d, centred, allowed, centre, r_req, args))
|
|
|
167 if args.holes > 2:
|
|
|
168 res["reason"] = "3 holes would be too close together or in a line"
|
|
|
169 else:
|
|
|
170 res.update(best)
|
|
|
171 return res
|
|
|
172
|
|
|
173
|
|
|
174 def _holes_axis(pts, mask, d, centred, allowed, centre, r_req, args):
|
|
|
175 """Two holes along the glyph's main axis.
|
|
|
176
|
|
|
177 1. Axis: main axis of the inked area (or vertical), pointing up. It
|
|
|
178 follows the slant of italic and script fonts and turns sideways for
|
|
|
179 wide glyphs.
|
|
|
180 2. Each point gets a position along the axis, 0 at the lower end and 1
|
|
|
181 at the upper end, and a sideways distance from the axis.
|
|
|
182 3. In each half, the allowed point with the best score wins. The score
|
|
|
183 rewards closeness to the target position, penalises sideways
|
|
|
184 distance relative to the glyph length, and rewards centredness.
|
|
|
185 4. A half without allowed points gets its largest inscribed circle.
|
|
|
186
|
|
|
187 Args:
|
|
|
188 pts: grid points, shape (ny, nx, 2). mask: inside points.
|
|
|
189 d: distance to the outline. centred: centredness.
|
|
|
190 allowed: points with room for the head. centre: of the inked area.
|
|
|
191 r_req: head radius plus wall. args: command line arguments.
|
|
|
192
|
|
|
193 Returns:
|
|
|
194 dict with 'holes' (top first), 'fits' and 'axis', see place_holes().
|
|
|
195 """
|
|
0
|
196 inside = pts[mask]
|
|
|
197 if args.vertical_axis:
|
|
|
198 axis = np.array([0.0, 1.0])
|
|
|
199 else:
|
|
|
200 evals, evecs = np.linalg.eigh(np.cov((inside - centre).T))
|
|
|
201 axis = evecs[:, int(np.argmax(evals))]
|
|
|
202 if axis[1] < 0 or (axis[1] == 0 and axis[0] < 0):
|
|
|
203 axis = -axis
|
|
|
204 normal = np.array([-axis[1], axis[0]])
|
|
|
205 s = (pts - centre) @ axis
|
|
|
206 u = (pts - centre) @ normal
|
|
|
207 smin, smax = s[mask].min(), s[mask].max()
|
|
|
208 length = smax - smin
|
|
|
209 t = (s - smin) / length
|
|
|
210
|
|
|
211 score = (-np.abs(t - np.where(t >= .5, args.target, 1 - args.target))
|
|
|
212 - args.side_weight * np.abs(u) / length
|
|
|
213 + args.centre_weight * centred)
|
|
|
214
|
|
|
215 holes, fits = [], []
|
|
|
216 for half in (t >= .5, t <= .5):
|
|
|
217 cand = allowed & half
|
|
|
218 fits.append(bool(cand.any()))
|
|
|
219 if cand.any():
|
|
|
220 idx = np.unravel_index(np.argmax(np.where(cand, score, -np.inf)), mask.shape)
|
|
|
221 else:
|
|
|
222 cand = mask & half
|
|
|
223 idx = np.unravel_index(np.argmax(np.where(cand, d, -np.inf)), mask.shape)
|
|
|
224 holes.append([*pts[idx], d[idx]])
|
|
4
|
225 return {"holes": holes, "fits": fits, "axis": (centre, axis, smin, smax)}
|
|
|
226
|
|
|
227
|
|
|
228 def _holes_spread(pts, mask, d, centred, allowed, centre, r_req, n, args):
|
|
|
229 """Three or more holes spread around the centre of the inked area.
|
|
|
230
|
|
|
231 1. Candidates: allowed points with a centredness of at least --ridge;
|
|
|
232 if their convex hull has fewer than 3 corners, all allowed points.
|
|
|
233 2. Points to choose from: candidates on the convex hull of the
|
|
|
234 candidates, see _hull_points(), as many as keep all combinations of
|
|
|
235 them below MAX_COMBINATIONS.
|
|
|
236 3. Combinations whose holes are closer together than head and wall, or
|
|
|
237 a third of the hull perimeter divided by the number of holes, are
|
|
|
238 left out.
|
|
|
239 4. Of the remaining combinations, the one whose polygon keeps the
|
|
|
240 centre furthest inside: the largest lever, the smallest distance
|
|
|
241 from the centre to a side. If that is less than the head diameter,
|
|
|
242 the holes are close to a line and none are placed. Of the
|
|
|
243 combinations within 10% of the largest lever, or one grid step, the
|
|
|
244 one with the largest area wins.
|
|
|
245
|
|
|
246 Args:
|
|
|
247 as for _holes_axis(); n: number of holes.
|
|
|
248
|
|
|
249 Returns:
|
|
|
250 dict with 'holes' (top first, then counter-clockwise), 'fits' and
|
|
|
251 'lever', see place_holes(); None if n holes cannot be placed.
|
|
|
252 """
|
|
|
253 step = pts[0, 1, 0] - pts[0, 0, 0]
|
|
|
254 for cand in (allowed & (centred >= args.ridge), allowed):
|
|
|
255 cpts = pts[cand]
|
|
|
256 hull = fl.convex_hull(cpts) if len(cpts) else cpts
|
|
|
257 if len(hull) >= 3:
|
|
|
258 break
|
|
|
259 else:
|
|
|
260 return None
|
|
|
261
|
|
|
262 h = n
|
|
|
263 while h < len(cpts) and math.comb(h + 1, n) <= MAX_COMBINATIONS:
|
|
|
264 h += 1
|
|
|
265 corners = _hull_points(hull, cpts, h, step)
|
|
|
266 if len(corners) < n:
|
|
|
267 return None
|
|
|
268 combo = np.array(list(itertools.combinations(range(len(corners)), n)))
|
|
|
269 poly = corners[combo] # (combinations, n, 2), counter-clockwise
|
|
|
270 lever = _lever(poly, centre)
|
|
|
271 area = (poly[..., 0] * np.roll(poly[..., 1], -1, axis=1)
|
|
|
272 - np.roll(poly[..., 0], -1, axis=1) * poly[..., 1]).sum(axis=1) / 2
|
|
|
273 i, j = np.triu_indices(n, 1)
|
|
|
274 gap = np.linalg.norm(poly[:, i] - poly[:, j], axis=2).min(axis=1)
|
|
|
275 perimeter = np.linalg.norm(np.roll(hull, -1, axis=0) - hull, axis=1).sum()
|
|
|
276 spaced = gap >= max(2 * r_req, perimeter / (3 * n))
|
|
|
277 if not spaced.any():
|
|
|
278 return None
|
|
|
279 top = lever[spaced].max()
|
|
|
280 if top < args.head_d:
|
|
|
281 return None
|
|
|
282 near = spaced & (lever >= top - max(step, .1 * top))
|
|
|
283 best = int(np.argmax(np.where(near, area, -np.inf)))
|
|
|
284 chosen = np.roll(poly[best], -int(np.argmax(poly[best][:, 1])), axis=0)
|
|
|
285
|
|
|
286 # back to grid indices for the distance to the outline
|
|
|
287 flat = pts.reshape(-1, 2)
|
|
|
288 holes, fits = [], []
|
|
|
289 for c in chosen:
|
|
|
290 idx = np.unravel_index(np.argmin(np.linalg.norm(flat - c, axis=1)), mask.shape)
|
|
|
291 holes.append([*pts[idx], d[idx]])
|
|
|
292 fits.append(bool(allowed[idx]))
|
|
|
293 return {"holes": holes, "fits": fits, "lever": float(lever[best])}
|
|
|
294
|
|
|
295
|
|
|
296 def _lever(poly, centre):
|
|
|
297 """Signed distance from the centre to the nearest side of each polygon,
|
|
|
298 positive inside.
|
|
|
299
|
|
|
300 Args:
|
|
|
301 poly: (..., n, 2) array of counter-clockwise polygons. centre: point.
|
|
|
302
|
|
|
303 Returns:
|
|
|
304 array of the leading shape of poly.
|
|
|
305 """
|
|
|
306 edge = np.roll(poly, -1, axis=-2) - poly
|
|
|
307 to_c = centre - poly
|
|
|
308 cross = edge[..., 0] * to_c[..., 1] - edge[..., 1] * to_c[..., 0]
|
|
|
309 return (cross / np.maximum(np.linalg.norm(edge, axis=-1), 1e-9)).min(axis=-1)
|
|
|
310
|
|
|
311
|
|
|
312 def _hull_points(hull, cpts, count, step):
|
|
|
313 """Points on the convex hull of the candidates, spread along it.
|
|
|
314
|
|
|
315 Up to half the points are hull corners, those that shape the hull
|
|
|
316 most. The rest are candidates on the hull's sides, each time the one
|
|
|
317 furthest along the perimeter from the points already taken.
|
|
|
318
|
|
|
319 Args:
|
|
|
320 hull: (k, 2) array, counter-clockwise. cpts: candidate points.
|
|
|
321 count: number of points. step: grid step.
|
|
|
322
|
|
|
323 Returns:
|
|
|
324 (at most count, 2) array, counter-clockwise.
|
|
|
325 """
|
|
|
326 edge = np.roll(hull, -1, axis=0) - hull
|
|
|
327 length = np.linalg.norm(edge, axis=1)
|
|
|
328 start = np.concatenate([[0], np.cumsum(length)[:-1]])
|
|
|
329 perimeter = length.sum()
|
|
|
330 # position along the perimeter of candidates within 1.5 steps of a side
|
|
|
331 rel = cpts[:, None, :] - hull[None, :, :]
|
|
|
332 t = np.clip((rel * edge).sum(axis=2) / np.maximum(length, 1e-9) ** 2, 0, 1)
|
|
|
333 dist = np.linalg.norm(rel - t[..., None] * edge, axis=2)
|
|
|
334 side = dist.argmin(axis=1)
|
|
|
335 on = dist.min(axis=1) <= 1.5 * step
|
|
|
336 pool_pts = cpts[on]
|
|
|
337 pool_pos = (start[side] + t[np.arange(len(cpts)), side] * length[side])[on]
|
|
|
338
|
|
|
339 keep = _thin_polygon(hull, min(len(hull), max(3, count // 2)))
|
|
|
340 pts, pos = list(hull[keep]), list(start[keep])
|
|
|
341 while len(pts) < count and len(pool_pts):
|
|
|
342 gap = np.abs(pool_pos[:, None] - np.array(pos)[None, :])
|
|
|
343 gap = np.minimum(gap, perimeter - gap).min(axis=1)
|
|
|
344 best = int(np.argmax(gap))
|
|
|
345 if gap[best] < step:
|
|
|
346 break
|
|
|
347 pts.append(pool_pts[best])
|
|
|
348 pos.append(pool_pos[best])
|
|
|
349 return np.array(pts)[np.argsort(pos)]
|
|
|
350
|
|
|
351
|
|
|
352 def _thin_polygon(poly, count):
|
|
|
353 """Reduce a convex polygon to count corners by repeatedly removing the
|
|
|
354 corner whose triangle with its neighbours has the smallest area.
|
|
|
355
|
|
|
356 Args:
|
|
|
357 poly: (k, 2) array, counter-clockwise. count: corners to keep.
|
|
|
358
|
|
|
359 Returns:
|
|
|
360 indices of the kept corners, in the original order.
|
|
|
361 """
|
|
|
362 keep = list(range(len(poly)))
|
|
|
363 while len(keep) > count:
|
|
|
364 p = poly[keep]
|
|
|
365 prev, nxt = np.roll(p, 1, axis=0), np.roll(p, -1, axis=0)
|
|
|
366 tri = np.abs((p[:, 0] - prev[:, 0]) * (nxt[:, 1] - prev[:, 1])
|
|
|
367 - (nxt[:, 0] - prev[:, 0]) * (p[:, 1] - prev[:, 1]))
|
|
|
368 del keep[int(np.argmin(tri))]
|
|
|
369 return keep
|
|
0
|
370
|
|
|
371
|
|
|
372 # --------------------------------------------------------------------- backing
|
|
|
373
|
|
|
374 def closing_connected(groups, radius, step):
|
|
|
375 """True if growing the outline by radius and shrinking it back gives a
|
|
|
376 single piece. Checked on a grid of the given step."""
|
|
|
377 pts_all = np.concatenate([c for grp in groups for c in grp])
|
|
|
378 bbox = (*pts_all.min(axis=0), *pts_all.max(axis=0))
|
|
|
379 grid = fl.Grid.around(bbox, step, radius + 3 * step)
|
|
|
380 mask, _ = fl.rasterise(groups, grid)
|
|
|
381 pts = grid.points()
|
|
|
382 flat = mask.ravel()
|
|
|
383 a, b = fl.boundary_segments(groups, 1.0)
|
|
|
384 d_out = np.full(len(pts), np.inf)
|
|
|
385 d_out[~flat] = fl.distance_to_segments(pts[~flat], a, b)
|
|
|
386 grown = mask | (d_out.reshape(mask.shape) <= radius)
|
|
|
387 # shrink: keep points at least radius from the cells outside the grown shape
|
|
|
388 edge = ~grown & fl.grow1(grown)
|
|
|
389 q = pts[edge.ravel()]
|
|
|
390 keep = np.zeros(len(pts), dtype=bool)
|
|
|
391 gflat = grown.ravel()
|
|
|
392 keep[gflat] = fl.distance_to_segments(pts[gflat], q, q) >= radius - step / 2
|
|
|
393 closed = mask | keep.reshape(mask.shape)
|
|
|
394 return fl.components(closed) == 1
|
|
|
395
|
|
|
396
|
|
|
397 def backing_radius(g, labels, count, args):
|
|
|
398 """Radius for growing and shrinking the outline so that the backing
|
|
|
399 connects all parts of a glyph.
|
|
|
400
|
|
|
401 The gaps between parts are measured, and the largest gap needed to
|
|
|
402 connect them all is found (largest edge of a minimum spanning tree).
|
|
|
403 Radii from half that gap upwards are tried until the result is one
|
|
|
404 piece.
|
|
|
405
|
|
|
406 Returns:
|
|
|
407 the radius in mm, 0 for a glyph of one part, -1 if no tried radius
|
|
|
408 connects the parts (the backing then uses the convex hull).
|
|
|
409 """
|
|
|
410 if count == 1:
|
|
|
411 return 0.0
|
|
|
412 parts = [[grp for grp, lab in zip(g.groups, labels) if lab == p] for p in range(count)]
|
|
|
413 segs = [fl.boundary_segments(pg, 1.0) for pg in parts]
|
|
|
414 gap = np.zeros((count, count))
|
|
|
415 for i in range(count):
|
|
|
416 for j in range(count):
|
|
|
417 if i != j:
|
|
|
418 gap[i, j] = fl.distance_to_segments(segs[i][0], *segs[j]).min()
|
|
|
419 gap = np.minimum(gap, gap.T)
|
|
|
420 # Prim's algorithm for the minimum spanning tree
|
|
|
421 in_tree, worst = {0}, 0.0
|
|
|
422 while len(in_tree) < count:
|
|
|
423 best = min((gap[i, j], j) for i in in_tree for j in range(count) if j not in in_tree)
|
|
|
424 worst = max(worst, best[0])
|
|
|
425 in_tree.add(best[1])
|
|
|
426 for radius in (worst / 2 + args.line_width, worst, 1.5 * worst, 2 * worst):
|
|
|
427 step = max(args.grid, min(1.0, radius / 3))
|
|
|
428 if closing_connected(g.groups, radius, step):
|
|
|
429 return radius
|
|
|
430 return -1.0
|
|
|
431
|
|
|
432
|
|
|
433 # ---------------------------------------------------------------------- output
|
|
|
434
|
|
|
435 def write_svg(path, g):
|
|
|
436 """Write the glyph as SVG, one path element per contour group.
|
|
|
437
|
|
|
438 OpenSCAD fills each path element by the even-odd rule and combines the
|
|
|
439 elements. Coordinates are mm, glyph origin at the SVG origin. The page
|
|
|
440 is the positive quadrant up to the glyph's extent; OpenSCAD maps an SVG
|
|
|
441 point (x, y) to (x, page height - y).
|
|
|
442 """
|
|
|
443 _, _, xmax, ymax = g.bbox()
|
|
|
444 w, h = max(xmax, 1.0), max(ymax, 1.0)
|
|
|
445 paths = []
|
|
|
446 for group in g.groups:
|
|
|
447 d = " ".join("M " + " L ".join(f"{x:.4f},{h - y:.4f}" for x, y in c) + " Z"
|
|
|
448 for c in group)
|
|
|
449 paths.append(f'<path d="{d}"/>')
|
|
|
450 with open(path, "w") as f:
|
|
|
451 f.write(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w:.4f}mm" '
|
|
|
452 f'height="{h:.4f}mm" viewBox="0 0 {w:.4f} {h:.4f}">\n')
|
|
|
453 f.write("\n".join(paths))
|
|
|
454 f.write("\n</svg>\n")
|
|
|
455
|
|
|
456
|
|
|
457 def write_check_image(path, res, args):
|
|
|
458 """Write an image of the hole placement: glyph grey, allowed area green,
|
|
4
|
459 axis or hole polygon and centre blue, screw hole and countersink head red."""
|
|
0
|
460 grid, mask, allowed = res["grid"], res["mask"], res["allowed"]
|
|
|
461 img = np.full(mask.shape + (3,), 255, dtype=np.uint8)
|
|
|
462 img[mask] = (190, 190, 190)
|
|
|
463 img[allowed] = (170, 220, 170)
|
|
|
464 im = Image.fromarray(img[::-1])
|
|
|
465 d = ImageDraw.Draw(im)
|
|
|
466
|
|
|
467 def px(x, y):
|
|
|
468 return ((x - grid.x0) / grid.step, grid.ny - 1 - (y - grid.y0) / grid.step)
|
|
|
469
|
|
4
|
470 blue = (40, 80, 220)
|
|
|
471 if res["axis"]:
|
|
|
472 centre, axis, smin, smax = res["axis"]
|
|
|
473 d.line([px(*(centre + smin * axis)), px(*(centre + smax * axis))], fill=blue, width=3)
|
|
|
474 else:
|
|
|
475 corners = [px(x, y) for x, y, _ in res["holes"]]
|
|
|
476 d.line(corners + corners[:1], fill=blue, width=3)
|
|
|
477 cx, cy = px(*res["centre"])
|
|
|
478 rp = args.head_d / 2 / grid.step
|
|
|
479 d.line([(cx - rp, cy), (cx + rp, cy)], fill=blue, width=3)
|
|
|
480 d.line([(cx, cy - rp), (cx, cy + rp)], fill=blue, width=3)
|
|
0
|
481 for (x, y, r), fits in zip(res["holes"], res["fits"]):
|
|
|
482 cx, cy = px(x, y)
|
|
|
483 for rad, width in ((args.head_d / 2, 3), (res["r_req"], 1)):
|
|
|
484 rp = rad / grid.step
|
|
|
485 d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp), outline=(200, 30, 30), width=width)
|
|
|
486 rp = args.screw_d / 2 / grid.step
|
|
|
487 d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp),
|
|
|
488 fill=(200, 30, 30) if fits else (240, 140, 0))
|
|
|
489 im.save(path, optimize=True)
|
|
|
490
|
|
|
491
|
|
|
492 def scad_str(s):
|
|
|
493 """OpenSCAD string literal."""
|
|
|
494 return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
|
495
|
|
|
496
|
|
|
497 def scad_num(v):
|
|
|
498 """Number for OpenSCAD with 4 decimals, trailing zeros removed."""
|
|
|
499 return f"{v:.4f}".rstrip("0").rstrip(".")
|
|
|
500
|
|
|
501
|
|
|
502 def scad_pts(pts):
|
|
|
503 """List of points for OpenSCAD."""
|
|
|
504 return "[" + ", ".join(f"[{scad_num(x)}, {scad_num(y)}]" for x, y in pts) + "]"
|
|
|
505
|
|
|
506
|
|
|
507 # ------------------------------------------------------------------------ main
|
|
|
508
|
|
|
509 def main():
|
|
|
510 """Lay out the text, place the holes and write the output files."""
|
|
|
511 logging.disable(logging.WARNING)
|
|
|
512 args = parse_args()
|
|
|
513 info = fl.find_face(args.font)
|
|
|
514 face = fl.Face(info)
|
|
|
515 missing = [c for c in args.text if ord(c) not in face.cmap]
|
|
|
516 if missing:
|
|
|
517 sys.exit(f"{info.psname} has no glyph for {''.join(missing)!r}")
|
|
|
518 placed = face.layout(args.text)
|
|
|
519 if all(g.empty for _, g in placed):
|
|
|
520 sys.exit("the text has no visible glyphs")
|
|
|
521 for _, g in placed:
|
|
|
522 if g.fill_error > 0.001:
|
|
|
523 warn(f"{g.char!r}: outline differs from the font's filling "
|
|
|
524 f"on {100 * g.fill_error:.1f}% of its area")
|
|
|
525
|
|
|
526 usable = fl.usable_area(args.bed, args.margin, args.line_width)
|
|
|
527 sizes = fl.max_sizes(placed, usable)
|
|
|
528 angle = sizes[args.layout]["angle"] if args.angle < 0 else args.angle
|
|
|
529 size_max = fl.size_at(placed, usable, args.layout, angle)
|
|
|
530 size = args.size or size_max
|
|
|
531 if size > size_max + 1e-6:
|
|
|
532 warn(f"size {size:.1f} mm exceeds the maximum of {size_max:.1f} mm "
|
|
|
533 f"for the {args.layout} layout at {angle:g} degrees")
|
|
|
534 height = max(g.bbox()[3] - g.bbox()[1] for _, g in placed if not g.empty)
|
|
|
535 k = size / height
|
|
|
536
|
|
|
537 name = f"{info.file_name}_{text_name(args.text)}"
|
|
|
538 outdir = os.path.join(args.out, name)
|
|
|
539 os.makedirs(outdir, exist_ok=True)
|
|
|
540 for f in os.listdir(outdir):
|
|
|
541 if f.endswith((".svg", ".png")):
|
|
|
542 os.remove(os.path.join(outdir, f))
|
|
|
543
|
|
|
544 print(f"font {info.psname} ({info.family} {info.style}), text {args.text!r}")
|
|
|
545 print(f"maximum size: text layout {sizes['text']['size0']:.1f} mm, "
|
|
|
546 f"best {sizes['text']['size']:.1f} mm at {sizes['text']['angle']} degrees; "
|
|
|
547 f"glyph layout {sizes['glyph']['size0']:.1f} mm, "
|
|
|
548 f"best {sizes['glyph']['size']:.1f} mm at {sizes['glyph']['angle']} degrees")
|
|
|
549 print(f"holes placed for size {size:.1f} mm")
|
|
|
550
|
|
|
551 done, entries = {}, []
|
|
|
552 for x, g in placed:
|
|
|
553 if g.empty:
|
|
|
554 continue
|
|
|
555 stem = f"u{ord(g.char):04x}"
|
|
|
556 if g.char not in done:
|
|
|
557 gm = g.scaled(k)
|
|
|
558 res = place_holes(gm, args)
|
|
|
559 count, labels = fl.part_count(gm.groups, res["group_masks"])
|
|
|
560 back_r = backing_radius(gm, labels, count, args)
|
|
|
561 write_svg(os.path.join(outdir, stem + ".svg"), gm)
|
|
|
562 write_check_image(os.path.join(outdir, f"check_{stem}.png"), res, args)
|
|
|
563 hull = fl.convex_hull(np.concatenate(gm.contours))
|
|
|
564 done[g.char] = (gm, res, count, back_r, hull)
|
|
4
|
565 for i, ((hx, hy, r), fits) in enumerate(zip(res["holes"], res["fits"])):
|
|
0
|
566 if not fits:
|
|
4
|
567 warn(f"{g.char!r}: no room for the countersink head at hole {i + 1}: "
|
|
0
|
568 f"largest circle radius {r:.1f} mm, needed {res['r_req']:.1f} mm")
|
|
|
569 if count > 1:
|
|
|
570 warn(f"{g.char!r} has {count} separate parts; print it with backing")
|
|
|
571 if back_r < 0:
|
|
|
572 warn(f"{g.char!r}: growing and shrinking does not connect the parts; "
|
|
|
573 f"the backing uses the convex hull")
|
|
4
|
574 print(f"{g.char!r}: {len(res['holes'])} holes"
|
|
|
575 + (f" ({res['reason']})" if res["reason"] else "") + ": " + ", ".join(
|
|
0
|
576 f"({hx:.1f}, {hy:.1f}) r {r:.1f}" for hx, hy, r in res["holes"])
|
|
|
577 + (f", {count} parts, backing radius {back_r:.1f}" if count > 1 else ""))
|
|
|
578 gm, res, count, back_r, hull = done[g.char]
|
|
|
579 entries.append((g.char, f"{outdir}/{stem}.svg", x * k, gm.bbox(), hull,
|
|
|
580 res["holes"], count, back_r))
|
|
|
581
|
|
|
582 with open(args.data, "w") as f:
|
|
|
583 f.write(f"// generated by make_glyphs.py, do not edit\n"
|
|
|
584 f"// {shlex.join(['make_glyphs.py'] + sys.argv[1:])}\n\n")
|
|
|
585 f.write(f"g_font = {scad_str(info.psname)};\n")
|
|
|
586 f.write(f"g_text = {scad_str(args.text)};\n")
|
|
|
587 f.write(f"// font and text for file names\ng_name = {scad_str(name)};\n")
|
|
|
588 f.write(f"// height of the tallest glyph in mm; all lengths below are at this size\n"
|
|
|
589 f"g_size = {scad_num(size)};\n")
|
|
|
590 f.write(f"// placement parameters: head diameter, wall in line widths, line width\n"
|
|
|
591 f"g_placement = [{scad_num(args.head_d)}, {scad_num(args.wall_lines)}, "
|
|
|
592 f"{scad_num(args.line_width)}];\n")
|
|
4
|
593 f.write(f"// most holes per glyph\ng_holes = {args.holes};\n")
|
|
0
|
594 f.write("// maximum sizes in mm: [size at 0 degrees, best angle, size at best angle]\n")
|
|
|
595 for layout in ("text", "glyph"):
|
|
|
596 m = sizes[layout]
|
|
|
597 f.write(f"g_max_{layout} = [{scad_num(m['size0'])}, {m['angle']}, "
|
|
|
598 f"{scad_num(m['size'])}];\n")
|
|
|
599 f.write("// glyphs without spaces: [character, svg file, x offset in the text,\n"
|
|
|
600 "// ink bounding box [xmin, ymin, xmax, ymax], convex hull,\n"
|
|
4
|
601 "// holes [[x, y, largest circle radius], ...] top first, then\n"
|
|
|
602 "// counter-clockwise, parts,\n"
|
|
0
|
603 "// backing radius (0 one part, -1 convex hull)]\n")
|
|
|
604 f.write("g_glyphs = [\n")
|
|
|
605 for char, svg, off, bbox, hull, holes, count, back_r in entries:
|
|
|
606 f.write(f" [{scad_str(char)}, {scad_str(svg)}, {scad_num(off)},\n"
|
|
|
607 f" [{', '.join(scad_num(v) for v in bbox)}],\n"
|
|
|
608 f" {scad_pts(hull)},\n"
|
|
|
609 f" [{', '.join('[' + ', '.join(scad_num(v) for v in h) + ']' for h in holes)}],"
|
|
|
610 f" {count}, {scad_num(back_r)}],\n")
|
|
|
611 f.write("];\n")
|
|
|
612 print(f"wrote {outdir}/ and {args.data}")
|
|
|
613
|
|
|
614
|
|
|
615 if __name__ == "__main__":
|
|
|
616 main()
|