fontlab-python-pens 1.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,423 @@
1
+ # this_file: src/fontlab_pens/measure.py
2
+ # Derived from fontTools Lib/fontTools/pens/boundsPen.py, areaPen.py, pointInsidePen.py
3
+ # and helpers of Lib/fontTools/misc/arrayTools.py and bezierTools.py
4
+ # (MIT, (c) Just van Rossum; see NOTICE)
5
+ """Measuring pens: control bounds, exact bounds, signed area, point-inside.
6
+
7
+ Only the array and bezier helpers these pens need are ported, with fontTools'
8
+ constants (`epsilon = 1e-10`, `epsilonDigits = 6`) so results match.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Mapping, Sequence
14
+ from math import acos, cos, pi, sqrt
15
+ from typing import Any
16
+
17
+ from fontlab_pens.base import BasePen
18
+
19
+ __all__ = [
20
+ "AreaPen",
21
+ "BoundsPen",
22
+ "ControlBoundsPen",
23
+ "PointInsidePen",
24
+ "calcCubicBounds",
25
+ "calcQuadraticBounds",
26
+ ]
27
+
28
+ Point = tuple[float, float]
29
+ Rect = tuple[float, float, float, float]
30
+
31
+ epsilonDigits = 6
32
+ epsilon = 1e-10
33
+
34
+
35
+ def _calcBounds(array: Sequence[Point]) -> Rect:
36
+ if not array:
37
+ return 0, 0, 0, 0
38
+ xs = [x for x, y in array]
39
+ ys = [y for x, y in array]
40
+ return min(xs), min(ys), max(xs), max(ys)
41
+
42
+
43
+ def _updateBounds(bounds: Rect | None, p: Point) -> Rect:
44
+ x, y = p
45
+ if bounds is None:
46
+ return x, y, x, y
47
+ xMin, yMin, xMax, yMax = bounds
48
+ return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y)
49
+
50
+
51
+ def _pointInRect(p: Point, rect: Rect) -> bool:
52
+ x, y = p
53
+ xMin, yMin, xMax, yMax = rect
54
+ return (xMin <= x <= xMax) and (yMin <= y <= yMax)
55
+
56
+
57
+ def _unionRect(rect1: Rect, rect2: Rect) -> Rect:
58
+ xMin1, yMin1, xMax1, yMax1 = rect1
59
+ xMin2, yMin2, xMax2, yMax2 = rect2
60
+ return (min(xMin1, xMin2), min(yMin1, yMin2), max(xMax1, xMax2), max(yMax1, yMax2))
61
+
62
+
63
+ def _solveQuadratic(a: float, b: float, c: float) -> list[float]:
64
+ """Real roots of a*x*x + b*x + c = 0 (unsorted, possibly repeated)."""
65
+ if abs(a) < epsilon:
66
+ if abs(b) < epsilon:
67
+ return []
68
+ return [-c / b]
69
+ DD = b * b - 4.0 * a * c
70
+ if DD >= 0.0:
71
+ rDD = sqrt(DD)
72
+ return [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a]
73
+ return []
74
+
75
+
76
+ def _solveCubic(a: float, b: float, c: float, d: float) -> list[float]:
77
+ """Real roots of a*x^3 + b*x^2 + c*x + d = 0 (after Ross Cottrell's CUBIC.C)."""
78
+ if abs(a) < epsilon:
79
+ # Tiny 'a' makes the cubic formula unreliable; fall back to quadratic.
80
+ return _solveQuadratic(b, c, d)
81
+ a = float(a)
82
+ a1 = b / a
83
+ a2 = c / a
84
+ a3 = d / a
85
+
86
+ Q = (a1 * a1 - 3.0 * a2) / 9.0
87
+ R = (2.0 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0
88
+
89
+ R2 = R * R
90
+ Q3 = Q * Q * Q
91
+ R2 = 0 if R2 < epsilon else R2
92
+ Q3 = 0 if abs(Q3) < epsilon else Q3
93
+
94
+ R2_Q3 = R2 - Q3
95
+
96
+ if R2 == 0.0 and Q3 == 0.0:
97
+ x = round(-a1 / 3.0, epsilonDigits)
98
+ return [x, x, x]
99
+ if R2_Q3 <= epsilon * 0.5:
100
+ theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0))
101
+ rQ2 = -2.0 * sqrt(Q)
102
+ a1_3 = a1 / 3.0
103
+ x0 = rQ2 * cos(theta / 3.0) - a1_3
104
+ x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3
105
+ x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3
106
+ x0, x1, x2 = sorted([x0, x1, x2])
107
+ if x1 - x0 < epsilon and x2 - x1 < epsilon:
108
+ x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits)
109
+ elif x1 - x0 < epsilon:
110
+ x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits)
111
+ x2 = round(x2, epsilonDigits)
112
+ elif x2 - x1 < epsilon:
113
+ x0 = round(x0, epsilonDigits)
114
+ x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits)
115
+ else:
116
+ x0 = round(x0, epsilonDigits)
117
+ x1 = round(x1, epsilonDigits)
118
+ x2 = round(x2, epsilonDigits)
119
+ return [x0, x1, x2]
120
+ x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0)
121
+ x = x + Q / x
122
+ if R >= 0.0:
123
+ x = -x
124
+ return [round(x - a1 / 3.0, epsilonDigits)]
125
+
126
+
127
+ def calcQuadraticBounds(pt1: Point, pt2: Point, pt3: Point) -> Rect:
128
+ """Exact bounding box of a quadratic bezier segment."""
129
+ x2, y2 = pt2
130
+ x3, y3 = pt3
131
+ cx, cy = pt1
132
+ bx = (x2 - cx) * 2.0
133
+ by = (y2 - cy) * 2.0
134
+ ax = x3 - cx - bx
135
+ ay = y3 - cy - by
136
+ ax2 = ax * 2.0
137
+ ay2 = ay * 2.0
138
+ roots = []
139
+ if ax2 != 0:
140
+ roots.append(-bx / ax2)
141
+ if ay2 != 0:
142
+ roots.append(-by / ay2)
143
+ points = [
144
+ (ax * t * t + bx * t + cx, ay * t * t + by * t + cy) for t in roots if 0 <= t < 1
145
+ ] + [pt1, pt3]
146
+ return _calcBounds(points)
147
+
148
+
149
+ def calcCubicBounds(pt1: Point, pt2: Point, pt3: Point, pt4: Point) -> Rect:
150
+ """Exact bounding box of a cubic bezier segment."""
151
+ x2, y2 = pt2
152
+ x3, y3 = pt3
153
+ x4, y4 = pt4
154
+ dx, dy = pt1
155
+ cx = (x2 - dx) * 3.0
156
+ cy = (y2 - dy) * 3.0
157
+ bx = (x3 - x2) * 3.0 - cx
158
+ by = (y3 - y2) * 3.0 - cy
159
+ ax = x4 - dx - cx - bx
160
+ ay = y4 - dy - cy - by
161
+ xRoots = [t for t in _solveQuadratic(ax * 3.0, bx * 2.0, cx) if 0 <= t < 1]
162
+ yRoots = [t for t in _solveQuadratic(ay * 3.0, by * 2.0, cy) if 0 <= t < 1]
163
+ points = [
164
+ (
165
+ ax * t * t * t + bx * t * t + cx * t + dx,
166
+ ay * t * t * t + by * t * t + cy * t + dy,
167
+ )
168
+ for t in xRoots + yRoots
169
+ ] + [pt1, pt4]
170
+ return _calcBounds(points)
171
+
172
+
173
+ class ControlBoundsPen(BasePen):
174
+ """Bounding box of all points, off-curves included, in `bounds` (or None).
175
+
176
+ With `ignoreSinglePoints`, lone moveTo points (e.g. anchors) are skipped.
177
+ """
178
+
179
+ def __init__(self, glyphSet: Mapping[str, Any] | None, ignoreSinglePoints: bool = False) -> None:
180
+ BasePen.__init__(self, glyphSet)
181
+ self.ignoreSinglePoints = ignoreSinglePoints
182
+ self.init()
183
+
184
+ def init(self) -> None:
185
+ """Reset the pen so it can measure another outline."""
186
+ self.bounds: Rect | None = None
187
+ self._start: Point | None = None
188
+
189
+ def _moveTo(self, pt):
190
+ self._start = pt
191
+ if not self.ignoreSinglePoints:
192
+ self._addMoveTo()
193
+
194
+ def _addMoveTo(self):
195
+ if self._start is None:
196
+ return
197
+ if self.bounds:
198
+ self.bounds = _updateBounds(self.bounds, self._start)
199
+ else:
200
+ x, y = self._start
201
+ self.bounds = (x, y, x, y)
202
+ self._start = None
203
+
204
+ def _lineTo(self, pt):
205
+ self._addMoveTo()
206
+ self.bounds = _updateBounds(self.bounds, pt)
207
+
208
+ def _curveToOne(self, bcp1, bcp2, pt):
209
+ self._addMoveTo()
210
+ bounds = _updateBounds(self.bounds, bcp1)
211
+ bounds = _updateBounds(bounds, bcp2)
212
+ self.bounds = _updateBounds(bounds, pt)
213
+
214
+ def _qCurveToOne(self, bcp, pt):
215
+ self._addMoveTo()
216
+ bounds = _updateBounds(self.bounds, bcp)
217
+ self.bounds = _updateBounds(bounds, pt)
218
+
219
+
220
+ class BoundsPen(ControlBoundsPen):
221
+ """Exact bounding box of the outline (curve extrema included), in `bounds`."""
222
+
223
+ def _curveToOne(self, bcp1, bcp2, pt):
224
+ self._addMoveTo()
225
+ bounds = _updateBounds(self.bounds, pt)
226
+ if not _pointInRect(bcp1, bounds) or not _pointInRect(bcp2, bounds):
227
+ bounds = _unionRect(
228
+ bounds, calcCubicBounds(self._getCurrentPoint(), bcp1, bcp2, pt)
229
+ )
230
+ self.bounds = bounds
231
+
232
+ def _qCurveToOne(self, bcp, pt):
233
+ self._addMoveTo()
234
+ bounds = _updateBounds(self.bounds, pt)
235
+ if not _pointInRect(bcp, bounds):
236
+ bounds = _unionRect(bounds, calcQuadraticBounds(self._getCurrentPoint(), bcp, pt))
237
+ self.bounds = bounds
238
+
239
+
240
+ class AreaPen(BasePen):
241
+ """Signed area in `value`: negative for clockwise (PostScript) contours.
242
+
243
+ Open contours raise `NotImplementedError` unless they end where they start.
244
+ """
245
+
246
+ def __init__(self, glyphset: Mapping[str, Any] | None = None) -> None:
247
+ BasePen.__init__(self, glyphset)
248
+ self.value = 0
249
+
250
+ def _moveTo(self, p0):
251
+ self._p0 = self._startPoint = p0
252
+
253
+ def _lineTo(self, p1):
254
+ x0, y0 = self._p0
255
+ x1, y1 = p1
256
+ self.value -= (x1 - x0) * (y1 + y0) * 0.5
257
+ self._p0 = p1
258
+
259
+ def _qCurveToOne(self, p1, p2):
260
+ # https://github.com/Pomax/bezierinfo/issues/44
261
+ p0 = self._p0
262
+ x0, y0 = p0[0], p0[1]
263
+ x1, y1 = p1[0] - x0, p1[1] - y0
264
+ x2, y2 = p2[0] - x0, p2[1] - y0
265
+ self.value -= (x2 * y1 - x1 * y2) / 3
266
+ self._lineTo(p2)
267
+ self._p0 = p2
268
+
269
+ def _curveToOne(self, p1, p2, p3):
270
+ # https://github.com/Pomax/bezierinfo/issues/44
271
+ p0 = self._p0
272
+ x0, y0 = p0[0], p0[1]
273
+ x1, y1 = p1[0] - x0, p1[1] - y0
274
+ x2, y2 = p2[0] - x0, p2[1] - y0
275
+ x3, y3 = p3[0] - x0, p3[1] - y0
276
+ self.value -= (x1 * (-y2 - y3) + x2 * (y1 - 2 * y3) + x3 * (y1 + 2 * y2)) * 0.15
277
+ self._lineTo(p3)
278
+ self._p0 = p3
279
+
280
+ def _closePath(self):
281
+ self._lineTo(self._startPoint)
282
+ del self._p0, self._startPoint
283
+
284
+ def _endPath(self):
285
+ if self._p0 != self._startPoint:
286
+ raise NotImplementedError("Area is not defined for open contours.")
287
+ del self._p0, self._startPoint
288
+
289
+
290
+ class PointInsidePen(BasePen):
291
+ """Tests whether `testPoint` lies inside the drawn outline.
292
+
293
+ Shoots a ray to +x and counts crossings: non-zero winding by default,
294
+ even-odd with `evenOdd=True`. Reuse via `setTestPoint` before drawing.
295
+ Quadratics are measured through BasePen's cubic elevation.
296
+ """
297
+
298
+ def __init__(
299
+ self, glyphSet: Mapping[str, Any] | None, testPoint: Point, evenOdd: bool = False
300
+ ) -> None:
301
+ BasePen.__init__(self, glyphSet)
302
+ self.setTestPoint(testPoint, evenOdd)
303
+
304
+ def setTestPoint(self, testPoint: Point, evenOdd: bool = False) -> None:
305
+ """Set the point to test; call before the outline is drawn."""
306
+ self.testPoint = testPoint
307
+ self.evenOdd = evenOdd
308
+ self.firstPoint = None
309
+ self.intersectionCount = 0
310
+
311
+ def getWinding(self) -> int:
312
+ """Return the winding number (closing any open sub path first)."""
313
+ if self.firstPoint is not None:
314
+ self.closePath()
315
+ return self.intersectionCount
316
+
317
+ def getResult(self) -> bool:
318
+ """Return True if the test point is inside the shape."""
319
+ winding = self.getWinding()
320
+ if self.evenOdd:
321
+ return bool(winding % 2)
322
+ return self.intersectionCount != 0
323
+
324
+ def _addIntersection(self, goingUp):
325
+ if self.evenOdd or goingUp:
326
+ self.intersectionCount += 1
327
+ else:
328
+ self.intersectionCount -= 1
329
+
330
+ def _moveTo(self, point):
331
+ if self.firstPoint is not None:
332
+ # The algorithm only works for closed paths.
333
+ self.closePath()
334
+ self.firstPoint = point
335
+
336
+ def _lineTo(self, point):
337
+ x, y = self.testPoint
338
+ x1, y1 = self._getCurrentPoint()
339
+ x2, y2 = point
340
+
341
+ if x1 < x and x2 < x:
342
+ return
343
+ if y1 < y and y2 < y:
344
+ return
345
+ if y1 >= y and y2 >= y:
346
+ return
347
+
348
+ dx = x2 - x1
349
+ dy = y2 - y1
350
+ t = (y - y1) / dy
351
+ ix = dx * t + x1
352
+ if ix < x:
353
+ return
354
+ self._addIntersection(y2 > y1)
355
+
356
+ def _curveToOne(self, bcp1, bcp2, point):
357
+ x, y = self.testPoint
358
+ x1, y1 = self._getCurrentPoint()
359
+ x2, y2 = bcp1
360
+ x3, y3 = bcp2
361
+ x4, y4 = point
362
+
363
+ if x1 < x and x2 < x and x3 < x and x4 < x:
364
+ return
365
+ if y1 < y and y2 < y and y3 < y and y4 < y:
366
+ return
367
+ if y1 >= y and y2 >= y and y3 >= y and y4 >= y:
368
+ return
369
+
370
+ dy = y1
371
+ cy = (y2 - dy) * 3.0
372
+ by = (y3 - y2) * 3.0 - cy
373
+ ay = y4 - dy - cy - by
374
+ solutions = sorted(_solveCubic(ay, by, cy, dy - y))
375
+ solutions = [t for t in solutions if -0.0 <= t <= 1.0]
376
+ if not solutions:
377
+ return
378
+
379
+ dx = x1
380
+ cx = (x2 - dx) * 3.0
381
+ bx = (x3 - x2) * 3.0 - cx
382
+ ax = x4 - dx - cx - bx
383
+
384
+ lastT = None
385
+ for t in solutions:
386
+ if t == lastT:
387
+ continue
388
+ lastT = t
389
+ t2 = t * t
390
+ t3 = t2 * t
391
+
392
+ direction = 3 * ay * t2 + 2 * by * t + cy
393
+ incomingGoingUp = outgoingGoingUp = direction > 0.0
394
+ if direction == 0.0:
395
+ direction = 6 * ay * t + 2 * by
396
+ outgoingGoingUp = direction > 0.0
397
+ incomingGoingUp = not outgoingGoingUp
398
+ if direction == 0.0:
399
+ direction = ay
400
+ incomingGoingUp = outgoingGoingUp = direction > 0.0
401
+
402
+ xt = ax * t3 + bx * t2 + cx * t + dx
403
+ if xt < x:
404
+ continue
405
+
406
+ if t in (0.0, -0.0):
407
+ if not outgoingGoingUp:
408
+ self._addIntersection(outgoingGoingUp)
409
+ elif t == 1.0:
410
+ if incomingGoingUp:
411
+ self._addIntersection(incomingGoingUp)
412
+ elif incomingGoingUp == outgoingGoingUp:
413
+ # Otherwise the curve merely touches the ray.
414
+ self._addIntersection(outgoingGoingUp)
415
+
416
+ def _closePath(self):
417
+ if self._getCurrentPoint() != self.firstPoint:
418
+ self.lineTo(self.firstPoint)
419
+ self.firstPoint = None
420
+
421
+ def _endPath(self):
422
+ """Insideness is not defined for open contours."""
423
+ raise NotImplementedError