wobblyhead hg > 3dprints > house_number
comparison make_glyphs.py @ 4:4836a7408849
more elaborate hole finding
| author | ark |
|---|---|
| date | 2026-11-03 15:51 +0100 |
| parents | b5a96b547b01 |
| children |
comparison
equal
deleted
inserted
replaced
| 3:f5ff6f1a5454 | 4:4836a7408849 |
|---|---|
| 4 For one font and text, this writes an SVG file per glyph and a check image | 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, | 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 | 6 which main.scad includes. All sizes are in mm at the size the holes were |
| 7 placed for. | 7 placed for. |
| 8 | 8 |
| 9 Holes: per glyph one near the top and one near the bottom end, along the | 9 Holes: per glyph two, one near the top and one near the bottom end, along |
| 10 glyph's main axis, in the middle of the stroke and with room for the | 10 the glyph's main axis; or, with a maximum of three or more, as many as the |
| 11 countersink head plus a minimum wall. See place_holes(). | 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(). | |
| 12 """ | 13 """ |
| 13 | 14 |
| 14 import argparse | 15 import argparse |
| 16 import itertools | |
| 15 import logging | 17 import logging |
| 16 import math | 18 import math |
| 17 import os | 19 import os |
| 18 import re | 20 import re |
| 19 import shlex | 21 import shlex |
| 42 help="rotation on the bed in degrees, for the default size; " | 44 help="rotation on the bed in degrees, for the default size; " |
| 43 "-1 for the best angle (default: %(default)s)") | 45 "-1 for the best angle (default: %(default)s)") |
| 44 s.add_argument("--size", type=float, | 46 s.add_argument("--size", type=float, |
| 45 help="height of the tallest glyph in mm (default: the maximum)") | 47 help="height of the tallest glyph in mm (default: the maximum)") |
| 46 h = p.add_argument_group("holes") | 48 h = p.add_argument_group("holes") |
| 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)") | |
| 47 h.add_argument("--screw-d", type=float, default=4, | 53 h.add_argument("--screw-d", type=float, default=4, |
| 48 help="screw diameter in mm, for the check images (default: %(default)s)") | 54 help="screw diameter in mm, for the check images (default: %(default)s)") |
| 49 h.add_argument("--head-d", type=float, default=8, | 55 h.add_argument("--head-d", type=float, default=8, |
| 50 help="countersink head diameter in mm (default: %(default)s)") | 56 help="countersink head diameter in mm (default: %(default)s)") |
| 51 h.add_argument("--wall-lines", type=float, default=2, | 57 h.add_argument("--wall-lines", type=float, default=2, |
| 52 help="minimum wall around the head, in line widths (default: %(default)s)") | 58 help="minimum wall around the head, in line widths (default: %(default)s)") |
| 53 h.add_argument("--target", type=float, default=.85, | 59 h.add_argument("--target", type=float, default=.85, |
| 54 help="position of the top hole along the axis, 0 bottom to 1 top; " | 60 help="2 holes: position of the top hole along the axis, 0 bottom to 1 top; " |
| 55 "the bottom hole mirrors it (default: %(default)s)") | 61 "the bottom hole mirrors it (default: %(default)s)") |
| 56 h.add_argument("--side-weight", type=float, default=.5, | 62 h.add_argument("--side-weight", type=float, default=.5, |
| 57 help="penalty for sideways distance from the axis (default: %(default)s)") | 63 help="2 holes: penalty for sideways distance from the axis " |
| 64 "(default: %(default)s)") | |
| 58 h.add_argument("--centre-weight", type=float, default=.3, | 65 h.add_argument("--centre-weight", type=float, default=.3, |
| 59 help="reward for sitting in the middle of the stroke (default: %(default)s)") | 66 help="2 holes: reward for sitting in the middle of the stroke " |
| 67 "(default: %(default)s)") | |
| 60 h.add_argument("--vertical-axis", action="store_true", | 68 h.add_argument("--vertical-axis", action="store_true", |
| 61 help="use a vertical axis instead of the glyph's main axis") | 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)") | |
| 62 h.add_argument("--grid", type=float, default=.5, | 78 h.add_argument("--grid", type=float, default=.5, |
| 63 help="sample spacing in mm (default: %(default)s)") | 79 help="sample spacing in mm (default: %(default)s)") |
| 64 b = p.add_argument_group("printer") | 80 b = p.add_argument_group("printer") |
| 65 b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)") | 81 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, | 82 b.add_argument("--margin", type=float, default=10, |
| 67 help="bed margin in mm (default: %(default)s)") | 83 help="bed margin in mm (default: %(default)s)") |
| 68 b.add_argument("--line-width", type=float, default=.4, | 84 b.add_argument("--line-width", type=float, default=.4, |
| 69 help="line width in mm (default: %(default)s)") | 85 help="line width in mm (default: %(default)s)") |
| 70 return p.parse_args() | 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 | |
| 71 | 90 |
| 72 | 91 |
| 73 def warn(msg): | 92 def warn(msg): |
| 74 """Print a warning to stderr.""" | 93 """Print a warning to stderr.""" |
| 75 print(f"warning: {msg}", file=sys.stderr) | 94 print(f"warning: {msg}", file=sys.stderr) |
| 81 return "".join(c if re.fullmatch(r"[A-Za-z0-9]", c) else f"u{ord(c):04x}" for c in text) | 100 return "".join(c if re.fullmatch(r"[A-Za-z0-9]", c) else f"u{ord(c):04x}" for c in text) |
| 82 | 101 |
| 83 | 102 |
| 84 # --------------------------------------------------------------- hole placement | 103 # --------------------------------------------------------------- hole placement |
| 85 | 104 |
| 105 MAX_HOLES = 6 | |
| 106 # most hole combinations tried per glyph with 3 or more holes | |
| 107 MAX_COMBINATIONS = 200000 | |
| 108 | |
| 109 | |
| 86 def place_holes(g, args): | 110 def place_holes(g, args): |
| 87 """Find the two screw hole positions of a glyph. | 111 """Find the screw hole positions of a glyph. |
| 88 | 112 |
| 89 1. Distance from each inside grid point to the outline. | 113 1. Distance from each inside grid point to the outline. |
| 90 2. Allowed points: room for the countersink head plus the minimum wall. | 114 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. | 115 3. Centredness of each point: its distance to the outline relative to |
| 92 4. Each point gets a position along the axis, 0 at the lower end and 1 | 116 the largest distance nearby, 1 in the middle of the stroke. |
| 93 at the upper end, and a sideways distance from the axis. | 117 4. Two holes: see _holes_axis(). With a maximum of three or more, the |
| 94 5. In each half, the allowed point with the best score wins. The score | 118 fewest holes from 3 up that _holes_spread() can place, then one more |
| 95 rewards closeness to the target position, penalises sideways | 119 at a time while each raises the lever (the distance from the centre |
| 96 distance relative to the glyph length, and rewards being in the | 120 to the nearest side of the hole polygon) by --hole-gain. Two holes |
| 97 middle of the stroke: distance to the outline relative to the | 121 if not even 3 can be placed. At the default of 50%, in Futura Bold, |
| 98 largest distance nearby. | 122 "W", "M", "H" and "X" get four holes; round glyphs such as "D", "O" |
| 99 6. A half without allowed points gets its largest inscribed circle. | 123 and "0" stay at three, where a fourth hole adds 39 to 43%. |
| 100 | 124 |
| 101 Args: | 125 Args: |
| 102 g: Glyph in mm. | 126 g: Glyph in mm. |
| 103 args: command line arguments. | 127 args: command line arguments. |
| 104 | 128 |
| 105 Returns: | 129 Returns: |
| 106 dict with 'holes' ([[x, y, r], [x, y, r]], top first, r the radius of | 130 dict with 'holes' ([[x, y, r], ...], the top one first, then |
| 107 the largest circle that fits there), 'fits' (per hole), 'grid', | 131 counter-clockwise; r the radius of the largest circle that fits |
| 108 'mask', 'allowed', 'axis' (centre, direction, lower and upper end | 132 there), 'fits' (per hole), 'reason' (why fewer than the maximum |
| 109 along the axis), 'r_req' and 'group_masks'. | 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'. | |
| 110 """ | 136 """ |
| 111 r_req = args.head_d / 2 + args.wall_lines * args.line_width | 137 r_req = args.head_d / 2 + args.wall_lines * args.line_width |
| 112 grid = fl.Grid.around(g.bbox(), args.grid, 2 * args.grid) | 138 grid = fl.Grid.around(g.bbox(), args.grid, 2 * args.grid) |
| 113 mask, group_masks = fl.rasterise(g.groups, grid) | 139 mask, group_masks = fl.rasterise(g.groups, grid) |
| 114 pts = grid.points().reshape(grid.ny, grid.nx, 2) | 140 pts = grid.points().reshape(grid.ny, grid.nx, 2) |
| 115 a, b = fl.boundary_segments(g.groups, 1.0) | 141 a, b = fl.boundary_segments(g.groups, 1.0) |
| 116 d = np.zeros(mask.shape) | 142 d = np.zeros(mask.shape) |
| 117 d[mask] = fl.distance_to_segments(pts[mask], a, b) | 143 d[mask] = fl.distance_to_segments(pts[mask], a, b) |
| 118 | 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) | |
| 148 | |
| 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 """ | |
| 119 inside = pts[mask] | 196 inside = pts[mask] |
| 120 centre = inside.mean(axis=0) | |
| 121 if args.vertical_axis: | 197 if args.vertical_axis: |
| 122 axis = np.array([0.0, 1.0]) | 198 axis = np.array([0.0, 1.0]) |
| 123 else: | 199 else: |
| 124 evals, evecs = np.linalg.eigh(np.cov((inside - centre).T)) | 200 evals, evecs = np.linalg.eigh(np.cov((inside - centre).T)) |
| 125 axis = evecs[:, int(np.argmax(evals))] | 201 axis = evecs[:, int(np.argmax(evals))] |
| 130 u = (pts - centre) @ normal | 206 u = (pts - centre) @ normal |
| 131 smin, smax = s[mask].min(), s[mask].max() | 207 smin, smax = s[mask].min(), s[mask].max() |
| 132 length = smax - smin | 208 length = smax - smin |
| 133 t = (s - smin) / length | 209 t = (s - smin) / length |
| 134 | 210 |
| 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)) | 211 score = (-np.abs(t - np.where(t >= .5, args.target, 1 - args.target)) |
| 139 - args.side_weight * np.abs(u) / length | 212 - args.side_weight * np.abs(u) / length |
| 140 + args.centre_weight * centred) | 213 + args.centre_weight * centred) |
| 141 allowed = mask & (d >= r_req) | |
| 142 | 214 |
| 143 holes, fits = [], [] | 215 holes, fits = [], [] |
| 144 for half in (t >= .5, t <= .5): | 216 for half in (t >= .5, t <= .5): |
| 145 cand = allowed & half | 217 cand = allowed & half |
| 146 fits.append(bool(cand.any())) | 218 fits.append(bool(cand.any())) |
| 148 idx = np.unravel_index(np.argmax(np.where(cand, score, -np.inf)), mask.shape) | 220 idx = np.unravel_index(np.argmax(np.where(cand, score, -np.inf)), mask.shape) |
| 149 else: | 221 else: |
| 150 cand = mask & half | 222 cand = mask & half |
| 151 idx = np.unravel_index(np.argmax(np.where(cand, d, -np.inf)), mask.shape) | 223 idx = np.unravel_index(np.argmax(np.where(cand, d, -np.inf)), mask.shape) |
| 152 holes.append([*pts[idx], d[idx]]) | 224 holes.append([*pts[idx], d[idx]]) |
| 153 return {"holes": holes, "fits": fits, "grid": grid, "mask": mask, "allowed": allowed, | 225 return {"holes": holes, "fits": fits, "axis": (centre, axis, smin, smax)} |
| 154 "axis": (centre, axis, smin, smax), "r_req": r_req, "group_masks": group_masks} | 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 | |
| 155 | 370 |
| 156 | 371 |
| 157 # --------------------------------------------------------------------- backing | 372 # --------------------------------------------------------------------- backing |
| 158 | 373 |
| 159 def closing_connected(groups, radius, step): | 374 def closing_connected(groups, radius, step): |
| 239 f.write("\n</svg>\n") | 454 f.write("\n</svg>\n") |
| 240 | 455 |
| 241 | 456 |
| 242 def write_check_image(path, res, args): | 457 def write_check_image(path, res, args): |
| 243 """Write an image of the hole placement: glyph grey, allowed area green, | 458 """Write an image of the hole placement: glyph grey, allowed area green, |
| 244 axis blue, screw hole and countersink head red.""" | 459 axis or hole polygon and centre blue, screw hole and countersink head red.""" |
| 245 grid, mask, allowed = res["grid"], res["mask"], res["allowed"] | 460 grid, mask, allowed = res["grid"], res["mask"], res["allowed"] |
| 246 img = np.full(mask.shape + (3,), 255, dtype=np.uint8) | 461 img = np.full(mask.shape + (3,), 255, dtype=np.uint8) |
| 247 img[mask] = (190, 190, 190) | 462 img[mask] = (190, 190, 190) |
| 248 img[allowed] = (170, 220, 170) | 463 img[allowed] = (170, 220, 170) |
| 249 im = Image.fromarray(img[::-1]) | 464 im = Image.fromarray(img[::-1]) |
| 250 d = ImageDraw.Draw(im) | 465 d = ImageDraw.Draw(im) |
| 251 | 466 |
| 252 def px(x, y): | 467 def px(x, y): |
| 253 return ((x - grid.x0) / grid.step, grid.ny - 1 - (y - grid.y0) / grid.step) | 468 return ((x - grid.x0) / grid.step, grid.ny - 1 - (y - grid.y0) / grid.step) |
| 254 | 469 |
| 255 centre, axis, smin, smax = res["axis"] | 470 blue = (40, 80, 220) |
| 256 d.line([px(*(centre + smin * axis)), px(*(centre + smax * axis))], | 471 if res["axis"]: |
| 257 fill=(40, 80, 220), width=3) | 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) | |
| 258 for (x, y, r), fits in zip(res["holes"], res["fits"]): | 481 for (x, y, r), fits in zip(res["holes"], res["fits"]): |
| 259 cx, cy = px(x, y) | 482 cx, cy = px(x, y) |
| 260 for rad, width in ((args.head_d / 2, 3), (res["r_req"], 1)): | 483 for rad, width in ((args.head_d / 2, 3), (res["r_req"], 1)): |
| 261 rp = rad / grid.step | 484 rp = rad / grid.step |
| 262 d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp), outline=(200, 30, 30), width=width) | 485 d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp), outline=(200, 30, 30), width=width) |
| 337 back_r = backing_radius(gm, labels, count, args) | 560 back_r = backing_radius(gm, labels, count, args) |
| 338 write_svg(os.path.join(outdir, stem + ".svg"), gm) | 561 write_svg(os.path.join(outdir, stem + ".svg"), gm) |
| 339 write_check_image(os.path.join(outdir, f"check_{stem}.png"), res, args) | 562 write_check_image(os.path.join(outdir, f"check_{stem}.png"), res, args) |
| 340 hull = fl.convex_hull(np.concatenate(gm.contours)) | 563 hull = fl.convex_hull(np.concatenate(gm.contours)) |
| 341 done[g.char] = (gm, res, count, back_r, hull) | 564 done[g.char] = (gm, res, count, back_r, hull) |
| 342 for (hx, hy, r), fits, where in zip(res["holes"], res["fits"], ("top", "bottom")): | 565 for i, ((hx, hy, r), fits) in enumerate(zip(res["holes"], res["fits"])): |
| 343 if not fits: | 566 if not fits: |
| 344 warn(f"{g.char!r}: no room for the countersink head at the {where} hole: " | 567 warn(f"{g.char!r}: no room for the countersink head at hole {i + 1}: " |
| 345 f"largest circle radius {r:.1f} mm, needed {res['r_req']:.1f} mm") | 568 f"largest circle radius {r:.1f} mm, needed {res['r_req']:.1f} mm") |
| 346 if count > 1: | 569 if count > 1: |
| 347 warn(f"{g.char!r} has {count} separate parts; print it with backing") | 570 warn(f"{g.char!r} has {count} separate parts; print it with backing") |
| 348 if back_r < 0: | 571 if back_r < 0: |
| 349 warn(f"{g.char!r}: growing and shrinking does not connect the parts; " | 572 warn(f"{g.char!r}: growing and shrinking does not connect the parts; " |
| 350 f"the backing uses the convex hull") | 573 f"the backing uses the convex hull") |
| 351 print(f"{g.char!r}: holes " + ", ".join( | 574 print(f"{g.char!r}: {len(res['holes'])} holes" |
| 575 + (f" ({res['reason']})" if res["reason"] else "") + ": " + ", ".join( | |
| 352 f"({hx:.1f}, {hy:.1f}) r {r:.1f}" for hx, hy, r in res["holes"]) | 576 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 "")) | 577 + (f", {count} parts, backing radius {back_r:.1f}" if count > 1 else "")) |
| 354 gm, res, count, back_r, hull = done[g.char] | 578 gm, res, count, back_r, hull = done[g.char] |
| 355 entries.append((g.char, f"{outdir}/{stem}.svg", x * k, gm.bbox(), hull, | 579 entries.append((g.char, f"{outdir}/{stem}.svg", x * k, gm.bbox(), hull, |
| 356 res["holes"], count, back_r)) | 580 res["holes"], count, back_r)) |
| 364 f.write(f"// height of the tallest glyph in mm; all lengths below are at this size\n" | 588 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") | 589 f"g_size = {scad_num(size)};\n") |
| 366 f.write(f"// placement parameters: head diameter, wall in line widths, line width\n" | 590 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)}, " | 591 f"g_placement = [{scad_num(args.head_d)}, {scad_num(args.wall_lines)}, " |
| 368 f"{scad_num(args.line_width)}];\n") | 592 f"{scad_num(args.line_width)}];\n") |
| 593 f.write(f"// most holes per glyph\ng_holes = {args.holes};\n") | |
| 369 f.write("// maximum sizes in mm: [size at 0 degrees, best angle, size at best angle]\n") | 594 f.write("// maximum sizes in mm: [size at 0 degrees, best angle, size at best angle]\n") |
| 370 for layout in ("text", "glyph"): | 595 for layout in ("text", "glyph"): |
| 371 m = sizes[layout] | 596 m = sizes[layout] |
| 372 f.write(f"g_max_{layout} = [{scad_num(m['size0'])}, {m['angle']}, " | 597 f.write(f"g_max_{layout} = [{scad_num(m['size0'])}, {m['angle']}, " |
| 373 f"{scad_num(m['size'])}];\n") | 598 f"{scad_num(m['size'])}];\n") |
| 374 f.write("// glyphs without spaces: [character, svg file, x offset in the text,\n" | 599 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" | 600 "// ink bounding box [xmin, ymin, xmax, ymax], convex hull,\n" |
| 376 "// holes [[x, y, largest circle radius], ...] top first, parts,\n" | 601 "// holes [[x, y, largest circle radius], ...] top first, then\n" |
| 602 "// counter-clockwise, parts,\n" | |
| 377 "// backing radius (0 one part, -1 convex hull)]\n") | 603 "// backing radius (0 one part, -1 convex hull)]\n") |
| 378 f.write("g_glyphs = [\n") | 604 f.write("g_glyphs = [\n") |
| 379 for char, svg, off, bbox, hull, holes, count, back_r in entries: | 605 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" | 606 f.write(f" [{scad_str(char)}, {scad_str(svg)}, {scad_num(off)},\n" |
| 381 f" [{', '.join(scad_num(v) for v in bbox)}],\n" | 607 f" [{', '.join(scad_num(v) for v in bbox)}],\n" |
