wobblyhead hg > 3dprints > house_number
comparison fontlib.py @ 0:b5a96b547b01
initial public version
| author | ark |
|---|---|
| date | 2026-11-03 01:29 +0100 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:b5a96b547b01 |
|---|---|
| 1 """Font lookup, glyph outlines and geometry helpers for the house number scripts. | |
| 2 | |
| 3 Shared by make_preview.py and make_glyphs.py. Fonts are found through | |
| 4 fontconfig (fc-list) and read with fontTools. Glyph outlines are flattened | |
| 5 into polygons, so the preview, the hole calculation and the OpenSCAD model | |
| 6 all use the same shapes. | |
| 7 | |
| 8 Coordinates are in font units until a script scales them to mm. The y axis | |
| 9 points up. | |
| 10 """ | |
| 11 | |
| 12 import math | |
| 13 import os | |
| 14 import subprocess | |
| 15 from collections import deque | |
| 16 from dataclasses import dataclass, field | |
| 17 | |
| 18 import numpy as np | |
| 19 from fontTools.pens.basePen import BasePen | |
| 20 from fontTools.ttLib import TTFont | |
| 21 | |
| 22 FC_FORMAT = ("%{file}\t%{index}\t%{postscriptname}\t%{family[0]}\t" | |
| 23 "%{style[0]}\t%{slant}\t%{spacing}\t%{variable}\n") | |
| 24 | |
| 25 | |
| 26 # ---------------------------------------------------------------- font lookup | |
| 27 | |
| 28 @dataclass | |
| 29 class FaceInfo: | |
| 30 """One font face as listed by fontconfig. | |
| 31 | |
| 32 Attributes: | |
| 33 file: path of the font file. | |
| 34 index: fontconfig index. The lower 16 bits are the face number in a | |
| 35 collection, the upper 16 bits the 1-based named instance of a | |
| 36 variable font (0 for the default instance). | |
| 37 psname: PostScript name, used as the identifier of the face. | |
| 38 family: family name. | |
| 39 style: style name. | |
| 40 italic: true for italic and oblique faces. | |
| 41 mono: true for monospaced faces. | |
| 42 """ | |
| 43 file: str | |
| 44 index: int | |
| 45 psname: str | |
| 46 family: str | |
| 47 style: str | |
| 48 italic: bool | |
| 49 mono: bool | |
| 50 | |
| 51 @property | |
| 52 def file_name(self): | |
| 53 """File name stem for this face: the PostScript name without a | |
| 54 leading dot, so the files of Apple's system fonts are not hidden.""" | |
| 55 return self.psname.lstrip(".") | |
| 56 | |
| 57 | |
| 58 def list_faces(): | |
| 59 """List the font faces known to fontconfig. | |
| 60 | |
| 61 Variable font entries that stand for the whole variable font are left | |
| 62 out; their named instances are listed separately. Faces without a | |
| 63 PostScript name are left out. When several faces share a PostScript | |
| 64 name, the first one is kept. | |
| 65 | |
| 66 Returns: | |
| 67 list of FaceInfo, sorted by file name stem. | |
| 68 """ | |
| 69 out = subprocess.run(["fc-list", "--format", FC_FORMAT], | |
| 70 capture_output=True, text=True, check=True).stdout | |
| 71 faces = {} | |
| 72 for line in out.splitlines(): | |
| 73 parts = line.split("\t") | |
| 74 if len(parts) != 8: | |
| 75 continue | |
| 76 file, index, psname, family, style, slant, spacing, variable = parts | |
| 77 if variable == "True" or not psname: | |
| 78 continue | |
| 79 if not file.lower().endswith((".ttf", ".otf", ".ttc", ".otc")): | |
| 80 continue | |
| 81 info = FaceInfo(file=file, index=int(index), psname=psname, | |
| 82 family=family, style=style, | |
| 83 italic=float(slant or 0) > 0, | |
| 84 mono=spacing == "100") | |
| 85 faces.setdefault(info.file_name, info) | |
| 86 return [faces[k] for k in sorted(faces, key=str.lower)] | |
| 87 | |
| 88 | |
| 89 def find_face(name): | |
| 90 """Find a face by PostScript name or by the path of its preview PNG. | |
| 91 | |
| 92 Args: | |
| 93 name: PostScript name, with or without leading dot, or a path whose | |
| 94 file name stem is the name (such as preview/Helvetica-Bold.png). | |
| 95 | |
| 96 Returns: | |
| 97 the FaceInfo. | |
| 98 | |
| 99 Raises: | |
| 100 LookupError: no face of that name. | |
| 101 """ | |
| 102 stem = os.path.basename(name) | |
| 103 if stem.lower().endswith(".png"): | |
| 104 stem = stem[:-4] | |
| 105 stem = stem.lstrip(".") | |
| 106 for face in list_faces(): | |
| 107 if face.file_name == stem: | |
| 108 return face | |
| 109 raise LookupError(f"no font with PostScript name {stem!r}") | |
| 110 | |
| 111 | |
| 112 # ------------------------------------------------------------------ outlines | |
| 113 | |
| 114 class _FlattenPen(BasePen): | |
| 115 """Pen that turns glyph outlines into closed polygons. | |
| 116 | |
| 117 Curves are split into straight segments so that no point of a segment | |
| 118 is further than the tolerance from the curve. | |
| 119 """ | |
| 120 | |
| 121 def __init__(self, glyphset, tolerance): | |
| 122 """Args: | |
| 123 glyphset: glyph set, used to draw components. | |
| 124 tolerance: largest distance between curve and segments, in font | |
| 125 units. | |
| 126 """ | |
| 127 super().__init__(glyphset) | |
| 128 self.tolerance = tolerance | |
| 129 self.contours = [] | |
| 130 self._cur = [] | |
| 131 | |
| 132 def _segments(self, second_diff): | |
| 133 """Number of segments for a curve whose largest second difference of | |
| 134 control points is second_diff.""" | |
| 135 return max(1, math.ceil(math.sqrt(second_diff / (4 * self.tolerance)))) | |
| 136 | |
| 137 def _moveTo(self, pt): | |
| 138 self._cur = [pt] | |
| 139 | |
| 140 def _lineTo(self, pt): | |
| 141 self._cur.append(pt) | |
| 142 | |
| 143 def _curveToOne(self, p1, p2, p3): | |
| 144 p0 = self._getCurrentPoint() | |
| 145 dd = max(math.dist((p0[0] - 2 * p1[0] + p2[0], p0[1] - 2 * p1[1] + p2[1]), (0, 0)), | |
| 146 math.dist((p1[0] - 2 * p2[0] + p3[0], p1[1] - 2 * p2[1] + p3[1]), (0, 0))) | |
| 147 n = self._segments(3 * dd) | |
| 148 for i in range(1, n + 1): | |
| 149 t = i / n | |
| 150 a, b, c, d = (1 - t) ** 3, 3 * t * (1 - t) ** 2, 3 * t * t * (1 - t), t ** 3 | |
| 151 self._cur.append((a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], | |
| 152 a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1])) | |
| 153 | |
| 154 def _qCurveToOne(self, p1, p2): | |
| 155 p0 = self._getCurrentPoint() | |
| 156 dd = math.dist((p0[0] - 2 * p1[0] + p2[0], p0[1] - 2 * p1[1] + p2[1]), (0, 0)) | |
| 157 n = self._segments(dd) | |
| 158 for i in range(1, n + 1): | |
| 159 t = i / n | |
| 160 a, b, c = (1 - t) ** 2, 2 * t * (1 - t), t * t | |
| 161 self._cur.append((a * p0[0] + b * p1[0] + c * p2[0], | |
| 162 a * p0[1] + b * p1[1] + c * p2[1])) | |
| 163 | |
| 164 def _closePath(self): | |
| 165 pts = np.array(self._cur, dtype=float) | |
| 166 self._cur = [] | |
| 167 if len(pts) and np.allclose(pts[0], pts[-1]): | |
| 168 pts = pts[:-1] | |
| 169 if len(pts) >= 3: | |
| 170 # drop repeated points | |
| 171 keep = np.any(np.diff(pts, axis=0, append=pts[:1]) != 0, axis=1) | |
| 172 pts = pts[keep] | |
| 173 if len(pts) >= 3: | |
| 174 self.contours.append(pts) | |
| 175 | |
| 176 def _endPath(self): | |
| 177 # open contours do not occur in fonts; close them anyway | |
| 178 self._closePath() | |
| 179 | |
| 180 | |
| 181 @dataclass | |
| 182 class Glyph: | |
| 183 """Outline of one character. | |
| 184 | |
| 185 Attributes: | |
| 186 char: the character. | |
| 187 advance: advance width in font units. | |
| 188 contours: closed polygons as (n, 2) arrays, font units. | |
| 189 groups: contours grouped for filling, see group_contours(). | |
| 190 fill_error: fraction of the glyph area where the grouped outline | |
| 191 differs from the font's intended filling, see fill_error(). | |
| 192 """ | |
| 193 char: str | |
| 194 advance: float | |
| 195 contours: list | |
| 196 groups: list = field(default_factory=list) | |
| 197 fill_error: float = 0.0 | |
| 198 | |
| 199 @property | |
| 200 def empty(self): | |
| 201 """True for glyphs without outline, such as a space.""" | |
| 202 return not self.contours | |
| 203 | |
| 204 def bbox(self): | |
| 205 """Ink bounding box as (xmin, ymin, xmax, ymax).""" | |
| 206 pts = np.concatenate(self.contours) | |
| 207 return (*pts.min(axis=0), *pts.max(axis=0)) | |
| 208 | |
| 209 def scaled(self, k, dx=0.0): | |
| 210 """Copy with all coordinates multiplied by k and shifted by dx.""" | |
| 211 off = np.array([dx, 0.0]) | |
| 212 return Glyph(self.char, self.advance * k, | |
| 213 [c * k + off for c in self.contours], | |
| 214 [[c * k + off for c in g] for g in self.groups]) | |
| 215 | |
| 216 | |
| 217 class Face: | |
| 218 """An opened font face, positioned at its named instance if it has one. | |
| 219 | |
| 220 Attributes: | |
| 221 info: the FaceInfo. | |
| 222 font: the fontTools TTFont. | |
| 223 upm: units per em. | |
| 224 location: axis coordinates of the named instance, or None. | |
| 225 """ | |
| 226 | |
| 227 def __init__(self, info): | |
| 228 """Open the face. | |
| 229 | |
| 230 Args: | |
| 231 info: FaceInfo from list_faces() or find_face(). | |
| 232 """ | |
| 233 self.info = info | |
| 234 self.font = TTFont(info.file, fontNumber=info.index & 0xFFFF, lazy=True) | |
| 235 self.upm = self.font["head"].unitsPerEm | |
| 236 self.location = None | |
| 237 instance = info.index >> 16 | |
| 238 if instance and "fvar" in self.font: | |
| 239 self.location = dict(self.font["fvar"].instances[instance - 1].coordinates) | |
| 240 self.glyphset = self.font.getGlyphSet(location=self.location) | |
| 241 self.cmap = self.font.getBestCmap() or {} | |
| 242 | |
| 243 @property | |
| 244 def weight(self): | |
| 245 """Weight on the 100 to 900 scale of the OS/2 table.""" | |
| 246 if self.location and "wght" in self.location: | |
| 247 return round(self.location["wght"]) | |
| 248 if "fvar" in self.font: | |
| 249 for axis in self.font["fvar"].axes: | |
| 250 if axis.axisTag == "wght": | |
| 251 return round(axis.defaultValue) | |
| 252 if "OS/2" in self.font: | |
| 253 return self.font["OS/2"].usWeightClass | |
| 254 return 400 | |
| 255 | |
| 256 @property | |
| 257 def classification(self): | |
| 258 """'serif' or 'sans' from the PANOSE data of the OS/2 table, or None | |
| 259 when the font does not classify itself as Latin text.""" | |
| 260 if "OS/2" not in self.font: | |
| 261 return None | |
| 262 panose = self.font["OS/2"].panose | |
| 263 if panose.bFamilyType != 2: | |
| 264 return None | |
| 265 if 2 <= panose.bSerifStyle <= 10: | |
| 266 return "serif" | |
| 267 if 11 <= panose.bSerifStyle <= 13: | |
| 268 return "sans" | |
| 269 return None | |
| 270 | |
| 271 @property | |
| 272 def mono(self): | |
| 273 """True for monospaced faces.""" | |
| 274 return self.info.mono or bool(getattr(self.font.get("post"), "isFixedPitch", 0)) | |
| 275 | |
| 276 def has_chars(self, text): | |
| 277 """True if the face has a glyph for every character of text.""" | |
| 278 return all(ord(c) in self.cmap for c in text) | |
| 279 | |
| 280 def glyph(self, char, tolerance=None): | |
| 281 """Outline of one character. | |
| 282 | |
| 283 Args: | |
| 284 char: the character. | |
| 285 tolerance: flattening tolerance in font units. Default: 1/10000 | |
| 286 of the em, about 0.04 mm for a 280 mm digit. | |
| 287 | |
| 288 Returns: | |
| 289 Glyph with contours and fill groups. | |
| 290 | |
| 291 Raises: | |
| 292 KeyError: the face has no glyph for the character. | |
| 293 """ | |
| 294 name = self.cmap.get(ord(char)) | |
| 295 if name is None: | |
| 296 raise KeyError(f"{self.info.psname} has no glyph for {char!r}") | |
| 297 pen = _FlattenPen(self.glyphset, tolerance or self.upm / 10000) | |
| 298 g = self.glyphset[name] | |
| 299 g.draw(pen) | |
| 300 glyph = Glyph(char, g.width, pen.contours) | |
| 301 if glyph.contours: | |
| 302 glyph.groups = group_contours(glyph.contours) | |
| 303 glyph.fill_error = fill_error(glyph.contours, glyph.groups) | |
| 304 return glyph | |
| 305 | |
| 306 def layout(self, text): | |
| 307 """Outlines of the characters of text, placed as the font spaces | |
| 308 them on one line. | |
| 309 | |
| 310 Args: | |
| 311 text: the text. | |
| 312 | |
| 313 Returns: | |
| 314 list of (x offset in font units, Glyph), one per character, | |
| 315 spaces included. | |
| 316 """ | |
| 317 x, out = 0.0, [] | |
| 318 for char in text: | |
| 319 glyph = self.glyph(char) | |
| 320 out.append((x, glyph)) | |
| 321 x += glyph.advance | |
| 322 return out | |
| 323 | |
| 324 | |
| 325 # --------------------------------------------------------------- polygons | |
| 326 | |
| 327 def signed_area(poly): | |
| 328 """Signed area of a polygon, positive for counter-clockwise order.""" | |
| 329 x, y = poly[:, 0], poly[:, 1] | |
| 330 return 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(np.roll(x, -1), y)) | |
| 331 | |
| 332 | |
| 333 def points_in_polygon(points, poly): | |
| 334 """Even-odd inside test of points against one polygon. | |
| 335 | |
| 336 Args: | |
| 337 points: (n, 2) array. | |
| 338 poly: (m, 2) array, closed implicitly. | |
| 339 | |
| 340 Returns: | |
| 341 bool array of length n. | |
| 342 """ | |
| 343 inside = np.zeros(len(points), dtype=bool) | |
| 344 px, py = points[:, 0], points[:, 1] | |
| 345 ax, ay = poly[:, 0], poly[:, 1] | |
| 346 bx, by = np.roll(ax, -1), np.roll(ay, -1) | |
| 347 for i in range(len(poly)): | |
| 348 crosses = (ay[i] > py) != (by[i] > py) | |
| 349 if not crosses.any(): | |
| 350 continue | |
| 351 xc = ax[i] + (py - ay[i]) * (bx[i] - ax[i]) / (by[i] - ay[i] + (by[i] == ay[i])) | |
| 352 inside ^= crosses & (px < xc) | |
| 353 return inside | |
| 354 | |
| 355 | |
| 356 def split_self_intersections(contour): | |
| 357 """Split a contour that crosses itself into loops that do not. | |
| 358 | |
| 359 The crossing points are inserted on both segments. Then, as long as a | |
| 360 crossing point occurs twice in the point sequence, the part between the | |
| 361 two occurrences is cut off as a separate loop. | |
| 362 | |
| 363 Args: | |
| 364 contour: (n, 2) array. | |
| 365 | |
| 366 Returns: | |
| 367 list of (k, 2) arrays. Loops of negligible area are dropped. | |
| 368 """ | |
| 369 n = len(contour) | |
| 370 a, b = contour, np.roll(contour, -1, axis=0) | |
| 371 d = b - a | |
| 372 cuts = [[] for _ in range(n)] | |
| 373 label = 0 | |
| 374 for i in range(n - 2): | |
| 375 j = np.arange(i + 2, n if i else n - 1) | |
| 376 if not len(j): | |
| 377 continue | |
| 378 den = d[i, 0] * d[j, 1] - d[i, 1] * d[j, 0] | |
| 379 ok = np.abs(den) > 1e-12 | |
| 380 den = np.where(ok, den, 1) | |
| 381 w = a[j] - a[i] | |
| 382 t = (w[:, 0] * d[j, 1] - w[:, 1] * d[j, 0]) / den | |
| 383 u = (w[:, 0] * d[i, 1] - w[:, 1] * d[i, 0]) / den | |
| 384 hit = ok & (t > 1e-9) & (t < 1 - 1e-9) & (u > 1e-9) & (u < 1 - 1e-9) | |
| 385 for k in np.nonzero(hit)[0]: | |
| 386 pt = a[i] + t[k] * d[i] | |
| 387 cuts[i].append((t[k], label, pt)) | |
| 388 cuts[j[k]].append((u[k], label, pt)) | |
| 389 label += 1 | |
| 390 if not label: | |
| 391 return [contour] | |
| 392 seq = [] | |
| 393 for i in range(n): | |
| 394 seq.append((-1, a[i])) | |
| 395 seq.extend((lab, pt) for _, lab, pt in sorted(cuts[i], key=lambda c: c[0])) | |
| 396 loops, todo = [], [seq] | |
| 397 while todo: | |
| 398 cur = todo.pop() | |
| 399 first = {} | |
| 400 for pos, (lab, _) in enumerate(cur): | |
| 401 if lab < 0: | |
| 402 continue | |
| 403 if lab in first: | |
| 404 p, q = first[lab], pos | |
| 405 todo.append([(-1, pt) for _, pt in cur[p:q]]) | |
| 406 todo.append(cur[:p] + [(-1, cur[q][1])] + cur[q + 1:]) | |
| 407 break | |
| 408 first[lab] = pos | |
| 409 else: | |
| 410 loops.append(np.array([pt for _, pt in cur])) | |
| 411 scale = abs(signed_area(contour)) or 1 | |
| 412 return [lp for lp in loops if len(lp) >= 3 and abs(signed_area(lp)) > 1e-6 * scale] | |
| 413 | |
| 414 | |
| 415 def group_contours(contours): | |
| 416 """Group contours so that even-odd filling of each group, combined by | |
| 417 union, gives the non-zero filling the font intends. | |
| 418 | |
| 419 Contours that cross themselves are split into simple loops first. Each | |
| 420 group is one outer contour followed by the holes inside it. Outer | |
| 421 contours turn the same way as the largest contour; the others are | |
| 422 holes. A hole is given to the smallest outer contour that contains all | |
| 423 its points. A hole inside no outer contour is filled under the non-zero | |
| 424 rule, so it becomes an outer contour itself. Outer contours come out | |
| 425 counter-clockwise, holes clockwise. | |
| 426 | |
| 427 Args: | |
| 428 contours: list of (n, 2) arrays. | |
| 429 | |
| 430 Returns: | |
| 431 list of groups, each a list of (n, 2) arrays, outer contour first. | |
| 432 """ | |
| 433 contours = [lp for c in contours for lp in split_self_intersections(c)] | |
| 434 areas = [signed_area(c) for c in contours] | |
| 435 outer_sign = math.copysign(1, areas[int(np.argmax(np.abs(areas)))]) | |
| 436 outers = [i for i, a in enumerate(areas) if math.copysign(1, a) == outer_sign] | |
| 437 holes = {} | |
| 438 for i, a in enumerate(areas): | |
| 439 if i in outers: | |
| 440 continue | |
| 441 best = None | |
| 442 for j in outers: | |
| 443 if abs(areas[j]) > abs(a) and points_in_polygon(contours[i], contours[j]).all(): | |
| 444 if best is None or abs(areas[j]) < abs(areas[best]): | |
| 445 best = j | |
| 446 holes.setdefault(best, []).append(i) | |
| 447 ccw = [c if signed_area(c) > 0 else c[::-1] for c in contours] | |
| 448 groups = [[ccw[i]] + [ccw[h][::-1] for h in holes.get(i, [])] for i in outers] | |
| 449 groups += [[ccw[h]] for h in holes.get(None, [])] | |
| 450 return groups | |
| 451 | |
| 452 | |
| 453 def fill_error(contours, groups, cells=250): | |
| 454 """Compare the union of even-odd filled groups with the non-zero filling | |
| 455 of the original contours, on a coarse grid. | |
| 456 | |
| 457 Args: | |
| 458 contours: original contours. | |
| 459 groups: result of group_contours(). | |
| 460 cells: grid cells along the longer side of the bounding box. | |
| 461 | |
| 462 Returns: | |
| 463 mismatching cells as a fraction of the non-zero filled cells. | |
| 464 """ | |
| 465 pts = np.concatenate(contours) | |
| 466 lo, hi = pts.min(axis=0), pts.max(axis=0) | |
| 467 step = max(hi - lo) / cells | |
| 468 grid = Grid.around((*lo, *hi), step, 2 * step) | |
| 469 nonzero = rasterise_winding(contours, grid) | |
| 470 grouped, _ = rasterise(groups, grid) | |
| 471 return float((nonzero != grouped).sum()) / max(1, int(nonzero.sum())) | |
| 472 | |
| 473 | |
| 474 def densify(contour, max_len): | |
| 475 """Contour with long segments split so none is longer than max_len.""" | |
| 476 a, b = contour, np.roll(contour, -1, axis=0) | |
| 477 n = np.maximum(1, np.ceil(np.linalg.norm(b - a, axis=1) / max_len).astype(int)) | |
| 478 if (n == 1).all(): | |
| 479 return contour | |
| 480 out = [a[i] + (b[i] - a[i]) * (k / n[i]) for i in range(len(a)) for k in range(n[i])] | |
| 481 return np.array(out) | |
| 482 | |
| 483 | |
| 484 def visible_runs(groups, max_len): | |
| 485 """Polylines along the outline of the union of all groups. | |
| 486 | |
| 487 Parts of a contour that lie inside another group are hidden by the | |
| 488 union and left out. Contours are first split into segments no longer | |
| 489 than max_len; each segment is kept or dropped by its midpoint. | |
| 490 | |
| 491 Args: | |
| 492 groups: contour groups from group_contours(). | |
| 493 max_len: longest segment for the visibility test. | |
| 494 | |
| 495 Returns: | |
| 496 list of (k, 2) arrays. A fully visible contour comes out closed, | |
| 497 with its first point repeated at the end. | |
| 498 """ | |
| 499 runs = [] | |
| 500 for gi, group in enumerate(groups): | |
| 501 others = [g for gj, g in enumerate(groups) if gj != gi] | |
| 502 for c in group: | |
| 503 if not others: | |
| 504 runs.append(np.vstack([c, c[:1]])) | |
| 505 continue | |
| 506 c = densify(c, max_len) | |
| 507 a, b = c, np.roll(c, -1, axis=0) | |
| 508 mid = (a + b) / 2 | |
| 509 hidden = np.zeros(len(c), dtype=bool) | |
| 510 for o in others: | |
| 511 hidden |= inside_group(mid, o) | |
| 512 if not hidden.any(): | |
| 513 runs.append(np.vstack([c, c[:1]])) | |
| 514 continue | |
| 515 # start at a hidden segment so every visible run is contiguous | |
| 516 run = [] | |
| 517 for k in np.roll(np.arange(len(c)), -int(np.argmax(hidden))): | |
| 518 if hidden[k]: | |
| 519 if run: | |
| 520 runs.append(np.array(run)) | |
| 521 run = [] | |
| 522 else: | |
| 523 if not run: | |
| 524 run.append(a[k]) | |
| 525 run.append(b[k]) | |
| 526 if run: | |
| 527 runs.append(np.array(run)) | |
| 528 return runs | |
| 529 | |
| 530 | |
| 531 def boundary_segments(groups, max_len): | |
| 532 """Segments of the outline of the union of all groups, see | |
| 533 visible_runs(). | |
| 534 | |
| 535 Returns: | |
| 536 (a, b): (m, 2) arrays of segment start and end points. | |
| 537 """ | |
| 538 runs = visible_runs(groups, max_len) | |
| 539 return (np.concatenate([r[:-1] for r in runs]), | |
| 540 np.concatenate([r[1:] for r in runs])) | |
| 541 | |
| 542 | |
| 543 def inside_group(points, group): | |
| 544 """Even-odd inside test of points against one contour group.""" | |
| 545 inside = np.zeros(len(points), dtype=bool) | |
| 546 for c in group: | |
| 547 inside ^= points_in_polygon(points, c) | |
| 548 return inside | |
| 549 | |
| 550 | |
| 551 def convex_hull(points): | |
| 552 """Convex hull by the monotone chain method. | |
| 553 | |
| 554 Args: | |
| 555 points: (n, 2) array. | |
| 556 | |
| 557 Returns: | |
| 558 (k, 2) array, counter-clockwise. | |
| 559 """ | |
| 560 pts = sorted(map(tuple, np.unique(points, axis=0))) | |
| 561 if len(pts) < 3: | |
| 562 return np.array(pts) | |
| 563 | |
| 564 def half(seq): | |
| 565 out = [] | |
| 566 for p in seq: | |
| 567 while len(out) >= 2 and ((out[-1][0] - out[-2][0]) * (p[1] - out[-2][1]) | |
| 568 - (out[-1][1] - out[-2][1]) * (p[0] - out[-2][0])) <= 0: | |
| 569 out.pop() | |
| 570 out.append(p) | |
| 571 return out | |
| 572 | |
| 573 lower, upper = half(pts), half(reversed(pts)) | |
| 574 return np.array(lower[:-1] + upper[:-1]) | |
| 575 | |
| 576 | |
| 577 def rotated_extent(points, angle): | |
| 578 """Width and height of the bounding box of points rotated by angle | |
| 579 degrees counter-clockwise.""" | |
| 580 a = math.radians(angle) | |
| 581 rot = np.array([[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]]) | |
| 582 r = points @ rot.T | |
| 583 return np.ptp(r[:, 0]), np.ptp(r[:, 1]) | |
| 584 | |
| 585 | |
| 586 # ------------------------------------------------------------- size fitting | |
| 587 | |
| 588 def usable_area(bed, margin, line_width): | |
| 589 """Side of the square available for glyphs: the bed minus its margin, | |
| 590 minus frame and frame gap of one line width each on both sides.""" | |
| 591 return bed - 2 * margin - 4 * line_width | |
| 592 | |
| 593 | |
| 594 def _fit_shapes(placed): | |
| 595 """Convex hulls to fit on the bed and the tallest ink height. | |
| 596 | |
| 597 Returns: | |
| 598 (height, {'text': [hull of the whole text], 'glyph': [hull per glyph]}) | |
| 599 """ | |
| 600 inked = [(x, g) for x, g in placed if not g.empty] | |
| 601 height = max(g.bbox()[3] - g.bbox()[1] for _, g in inked) | |
| 602 hulls = [convex_hull(np.concatenate(g.contours)) for _, g in inked] | |
| 603 text_hull = convex_hull(np.concatenate([h + [x, 0] for (x, _), h in zip(inked, hulls)])) | |
| 604 return height, {"text": [text_hull], "glyph": hulls} | |
| 605 | |
| 606 | |
| 607 def size_at(placed, usable, layout, angle): | |
| 608 """Largest print size for one layout and angle. | |
| 609 | |
| 610 Size is the height of the tallest glyph's ink. In the text layout the | |
| 611 whole text has to fit the usable square; in the glyph layout every glyph | |
| 612 on its own, all at the same scale. | |
| 613 | |
| 614 Args: | |
| 615 placed: result of Face.layout(), or the same structure in mm. | |
| 616 usable: side of the usable square in mm. | |
| 617 layout: 'text' or 'glyph'. | |
| 618 angle: rotation on the bed in degrees. | |
| 619 | |
| 620 Returns: | |
| 621 size in mm. | |
| 622 """ | |
| 623 height, shapes = _fit_shapes(placed) | |
| 624 extent = max(max(rotated_extent(h, angle)) for h in shapes[layout]) | |
| 625 return usable / extent * height | |
| 626 | |
| 627 | |
| 628 def max_sizes(placed, usable): | |
| 629 """Largest print size for both layouts, at 0 degrees and at the best | |
| 630 angle. Angles from 0 to 90 degrees in 1 degree steps are tried. | |
| 631 | |
| 632 Args: | |
| 633 placed: result of Face.layout(), or the same structure in mm. | |
| 634 usable: side of the usable square in mm. | |
| 635 | |
| 636 Returns: | |
| 637 dict with keys 'text' and 'glyph', each a dict with 'size0' (size at | |
| 638 0 degrees), 'angle' (best angle) and 'size' (size at that angle), in | |
| 639 mm. See size_at(). | |
| 640 """ | |
| 641 height, shapes = _fit_shapes(placed) | |
| 642 result = {} | |
| 643 for layout, hulls in shapes.items(): | |
| 644 sizes = [usable / max(max(rotated_extent(h, a)) for h in hulls) * height | |
| 645 for a in range(91)] | |
| 646 best = int(np.argmax(sizes)) | |
| 647 result[layout] = {"size0": sizes[0], "angle": best, "size": sizes[best]} | |
| 648 return result | |
| 649 | |
| 650 | |
| 651 # ------------------------------------------------------------------ rasters | |
| 652 | |
| 653 @dataclass | |
| 654 class Grid: | |
| 655 """Regular grid of sample points. | |
| 656 | |
| 657 Point (i, j) lies at (x0 + i * step, y0 + j * step). Arrays over the | |
| 658 grid have shape (ny, nx), row j and column i. | |
| 659 """ | |
| 660 x0: float | |
| 661 y0: float | |
| 662 step: float | |
| 663 nx: int | |
| 664 ny: int | |
| 665 | |
| 666 @classmethod | |
| 667 def around(cls, bbox, step, pad): | |
| 668 """Grid covering bbox = (xmin, ymin, xmax, ymax) plus pad on all | |
| 669 sides.""" | |
| 670 x0, y0 = bbox[0] - pad, bbox[1] - pad | |
| 671 nx = int(math.ceil((bbox[2] + pad - x0) / step)) + 1 | |
| 672 ny = int(math.ceil((bbox[3] + pad - y0) / step)) + 1 | |
| 673 return cls(x0, y0, step, nx, ny) | |
| 674 | |
| 675 def points(self): | |
| 676 """All grid points as an (ny * nx, 2) array, row by row.""" | |
| 677 xs = self.x0 + np.arange(self.nx) * self.step | |
| 678 ys = self.y0 + np.arange(self.ny) * self.step | |
| 679 gx, gy = np.meshgrid(xs, ys) | |
| 680 return np.stack([gx.ravel(), gy.ravel()], axis=1) | |
| 681 | |
| 682 | |
| 683 def _scanline_toggles(contours, grid, signed): | |
| 684 """Crossings of contour edges with the grid rows. | |
| 685 | |
| 686 Each crossing is counted at the first grid point to its right. With | |
| 687 signed set, upward edges count +1 and downward edges -1; otherwise all | |
| 688 count 1. | |
| 689 | |
| 690 Returns: | |
| 691 int array of shape (grid.ny, grid.nx + 1). Its cumulative sum along | |
| 692 the rows gives the crossing count left of each point. | |
| 693 """ | |
| 694 toggles = np.zeros((grid.ny, grid.nx + 1), dtype=np.int32) | |
| 695 for c in contours: | |
| 696 a, b = c, np.roll(c, -1, axis=0) | |
| 697 ya, yb = a[:, 1], b[:, 1] | |
| 698 lo, hi = np.minimum(ya, yb), np.maximum(ya, yb) | |
| 699 # rows whose y lies in [lo, hi) | |
| 700 j0 = np.clip(np.ceil((lo - grid.y0) / grid.step).astype(int), 0, grid.ny) | |
| 701 j1 = np.clip(np.ceil((hi - grid.y0) / grid.step).astype(int), 0, grid.ny) | |
| 702 counts = np.maximum(j1 - j0, 0) | |
| 703 total = int(counts.sum()) | |
| 704 if not total: | |
| 705 continue | |
| 706 edge = np.repeat(np.arange(len(c)), counts) | |
| 707 rows = np.repeat(j0, counts) + (np.arange(total) | |
| 708 - np.repeat(np.cumsum(counts) - counts, counts)) | |
| 709 y = grid.y0 + rows * grid.step | |
| 710 t = (y - ya[edge]) / (yb[edge] - ya[edge]) | |
| 711 x = a[edge, 0] + t * (b[edge, 0] - a[edge, 0]) | |
| 712 col = np.clip(np.floor((x - grid.x0) / grid.step).astype(int) + 1, 0, grid.nx) | |
| 713 weight = np.where(yb[edge] > ya[edge], 1, -1) if signed else 1 | |
| 714 np.add.at(toggles, (rows, col), weight) | |
| 715 return toggles | |
| 716 | |
| 717 | |
| 718 def rasterise_group(group, grid): | |
| 719 """Even-odd inside test of all grid points against one contour group. | |
| 720 | |
| 721 Returns: | |
| 722 bool array of shape (grid.ny, grid.nx). | |
| 723 """ | |
| 724 toggles = _scanline_toggles(group, grid, signed=False) | |
| 725 return (np.cumsum(toggles, axis=1)[:, :grid.nx] % 2).astype(bool) | |
| 726 | |
| 727 | |
| 728 def rasterise_winding(contours, grid): | |
| 729 """Non-zero inside test of all grid points against a set of contours. | |
| 730 | |
| 731 Returns: | |
| 732 bool array of shape (grid.ny, grid.nx). | |
| 733 """ | |
| 734 toggles = _scanline_toggles(contours, grid, signed=True) | |
| 735 return np.cumsum(toggles, axis=1)[:, :grid.nx] != 0 | |
| 736 | |
| 737 | |
| 738 def rasterise(groups, grid): | |
| 739 """Inside test of all grid points against the union of contour groups. | |
| 740 | |
| 741 Returns: | |
| 742 (mask, group_masks): bool array of shape (grid.ny, grid.nx) and the | |
| 743 list of masks of the single groups. | |
| 744 """ | |
| 745 masks = [rasterise_group(g, grid) for g in groups] | |
| 746 return np.logical_or.reduce(masks), masks | |
| 747 | |
| 748 | |
| 749 def distance_to_segments(points, a, b, chunk=2048): | |
| 750 """Distance from each point to the nearest of a set of segments. | |
| 751 | |
| 752 Args: | |
| 753 points: (n, 2) array. | |
| 754 a, b: (m, 2) arrays of segment start and end points. | |
| 755 chunk: points handled per step, to limit memory use. | |
| 756 | |
| 757 Returns: | |
| 758 (n,) array. | |
| 759 """ | |
| 760 # float32 and separate x and y arrays: about 3 times faster than | |
| 761 # float64 arrays with a coordinate axis | |
| 762 a = np.asarray(a, dtype=np.float32) | |
| 763 ab = np.asarray(b, dtype=np.float32) - a | |
| 764 inv = 1 / np.maximum((ab ** 2).sum(axis=1), 1e-12) | |
| 765 ax, ay, abx, aby = a[:, 0], a[:, 1], ab[:, 0], ab[:, 1] | |
| 766 pts = np.asarray(points, dtype=np.float32) | |
| 767 out = np.empty(len(points)) | |
| 768 for s in range(0, len(points), chunk): | |
| 769 dx = pts[s:s + chunk, 0:1] - ax | |
| 770 dy = pts[s:s + chunk, 1:2] - ay | |
| 771 t = np.clip((dx * abx + dy * aby) * inv, 0, 1) | |
| 772 dx -= t * abx | |
| 773 dy -= t * aby | |
| 774 out[s:s + chunk] = np.sqrt((dx * dx + dy * dy).min(axis=1)) | |
| 775 return out | |
| 776 | |
| 777 | |
| 778 def max_filter(arr, radius): | |
| 779 """Largest value within a square window of radius cells around each | |
| 780 cell, computed with doubling shifts along both axes.""" | |
| 781 out = arr | |
| 782 for axis in (0, 1): | |
| 783 out = _max_1d(out, radius, axis) | |
| 784 return out | |
| 785 | |
| 786 | |
| 787 def _max_1d(arr, radius, axis): | |
| 788 """Largest value within radius cells along one axis.""" | |
| 789 width = 2 * radius + 1 | |
| 790 pad = [(0, 0), (0, 0)] | |
| 791 pad[axis] = (radius, radius + width) | |
| 792 a = np.pad(arr, pad, constant_values=-np.inf) | |
| 793 span, cur = 1, a | |
| 794 # cur holds the maximum over windows of length span | |
| 795 while span * 2 <= width: | |
| 796 cur = np.maximum(cur, np.roll(cur, -span, axis=axis)) | |
| 797 span *= 2 | |
| 798 res = np.maximum(cur, np.roll(cur, -(width - span), axis=axis)) | |
| 799 n = arr.shape[axis] | |
| 800 return np.take(res, np.arange(n), axis=axis) | |
| 801 | |
| 802 | |
| 803 def components(mask): | |
| 804 """Number of 4-connected components of a bool mask.""" | |
| 805 seen = np.zeros_like(mask) | |
| 806 ny, nx = mask.shape | |
| 807 count = 0 | |
| 808 for start in zip(*np.nonzero(mask)): | |
| 809 if seen[start]: | |
| 810 continue | |
| 811 count += 1 | |
| 812 seen[start] = True | |
| 813 queue = deque([start]) | |
| 814 while queue: | |
| 815 j, i = queue.popleft() | |
| 816 for dj, di in ((1, 0), (-1, 0), (0, 1), (0, -1)): | |
| 817 q = (j + dj, i + di) | |
| 818 if 0 <= q[0] < ny and 0 <= q[1] < nx and mask[q] and not seen[q]: | |
| 819 seen[q] = True | |
| 820 queue.append(q) | |
| 821 return count | |
| 822 | |
| 823 | |
| 824 def part_count(groups, group_masks): | |
| 825 """Number of separate parts of a glyph: groups that overlap or touch | |
| 826 form one part. | |
| 827 | |
| 828 Args: | |
| 829 groups: contour groups. | |
| 830 group_masks: their masks from rasterise(). | |
| 831 | |
| 832 Returns: | |
| 833 (count, labels): number of parts and the part number of each group. | |
| 834 """ | |
| 835 n = len(groups) | |
| 836 parent = list(range(n)) | |
| 837 | |
| 838 def root(i): | |
| 839 while parent[i] != i: | |
| 840 parent[i] = parent[parent[i]] | |
| 841 i = parent[i] | |
| 842 return i | |
| 843 | |
| 844 grown = [grow1(m) for m in group_masks] | |
| 845 for i in range(n): | |
| 846 for j in range(i + 1, n): | |
| 847 if (grown[i] & group_masks[j]).any(): | |
| 848 parent[root(i)] = root(j) | |
| 849 roots = sorted({root(i) for i in range(n)}) | |
| 850 labels = [roots.index(root(i)) for i in range(n)] | |
| 851 return len(roots), labels | |
| 852 | |
| 853 | |
| 854 def grow1(mask): | |
| 855 """Mask grown by one cell in the four axis directions.""" | |
| 856 out = mask.copy() | |
| 857 out[1:] |= mask[:-1] | |
| 858 out[:-1] |= mask[1:] | |
| 859 out[:, 1:] |= mask[:, :-1] | |
| 860 out[:, :-1] |= mask[:, 1:] | |
| 861 return out |
