qu2cu.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. # cython: language_level=3
  2. # distutils: define_macros=CYTHON_TRACE_NOGIL=1
  3. # Copyright 2023 Google Inc. All Rights Reserved.
  4. # Copyright 2023 Behdad Esfahbod. All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. try:
  18. import cython
  19. except (AttributeError, ImportError):
  20. # if cython not installed, use mock module with no-op decorators and types
  21. from fontTools.misc import cython
  22. COMPILED = cython.compiled
  23. from fontTools.misc.bezierTools import splitCubicAtTC
  24. from collections import namedtuple
  25. import math
  26. from typing import (
  27. List,
  28. Tuple,
  29. Union,
  30. )
  31. __all__ = ["quadratic_to_curves"]
  32. # Copied from cu2qu
  33. @cython.cfunc
  34. @cython.returns(cython.int)
  35. @cython.locals(
  36. tolerance=cython.double,
  37. p0=cython.complex,
  38. p1=cython.complex,
  39. p2=cython.complex,
  40. p3=cython.complex,
  41. )
  42. @cython.locals(mid=cython.complex, deriv3=cython.complex)
  43. def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
  44. """Check if a cubic Bezier lies within a given distance of the origin.
  45. "Origin" means *the* origin (0,0), not the start of the curve. Note that no
  46. checks are made on the start and end positions of the curve; this function
  47. only checks the inside of the curve.
  48. Args:
  49. p0 (complex): Start point of curve.
  50. p1 (complex): First handle of curve.
  51. p2 (complex): Second handle of curve.
  52. p3 (complex): End point of curve.
  53. tolerance (double): Distance from origin.
  54. Returns:
  55. bool: True if the cubic Bezier ``p`` entirely lies within a distance
  56. ``tolerance`` of the origin, False otherwise.
  57. """
  58. # First check p2 then p1, as p2 has higher error early on.
  59. if abs(p2) <= tolerance and abs(p1) <= tolerance:
  60. return True
  61. # Split.
  62. mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
  63. if abs(mid) > tolerance:
  64. return False
  65. deriv3 = (p3 + p2 - p1 - p0) * 0.125
  66. return cubic_farthest_fit_inside(
  67. p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance
  68. ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance)
  69. @cython.locals(
  70. p0=cython.complex,
  71. p1=cython.complex,
  72. p2=cython.complex,
  73. p1_2_3=cython.complex,
  74. )
  75. def elevate_quadratic(p0, p1, p2):
  76. """Given a quadratic bezier curve, return its degree-elevated cubic."""
  77. # https://pomax.github.io/bezierinfo/#reordering
  78. p1_2_3 = p1 * (2 / 3)
  79. return (
  80. p0,
  81. (p0 * (1 / 3) + p1_2_3),
  82. (p2 * (1 / 3) + p1_2_3),
  83. p2,
  84. )
  85. @cython.cfunc
  86. @cython.locals(
  87. start=cython.int,
  88. n=cython.int,
  89. k=cython.int,
  90. prod_ratio=cython.double,
  91. sum_ratio=cython.double,
  92. ratio=cython.double,
  93. t=cython.double,
  94. p0=cython.complex,
  95. p1=cython.complex,
  96. p2=cython.complex,
  97. p3=cython.complex,
  98. )
  99. def merge_curves(curves, start, n):
  100. """Give a cubic-Bezier spline, reconstruct one cubic-Bezier
  101. that has the same endpoints and tangents and approxmates
  102. the spline."""
  103. # Reconstruct the t values of the cut segments
  104. prod_ratio = 1.0
  105. sum_ratio = 1.0
  106. ts = [1]
  107. for k in range(1, n):
  108. ck = curves[start + k]
  109. c_before = curves[start + k - 1]
  110. # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio
  111. assert ck[0] == c_before[3]
  112. ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2])
  113. prod_ratio *= ratio
  114. sum_ratio += prod_ratio
  115. ts.append(sum_ratio)
  116. # (t(n) - t(n - 1)) / (t_(1) - t(0)) = prod_ratio
  117. ts = [t / sum_ratio for t in ts[:-1]]
  118. p0 = curves[start][0]
  119. p1 = curves[start][1]
  120. p2 = curves[start + n - 1][2]
  121. p3 = curves[start + n - 1][3]
  122. # Build the curve by scaling the control-points.
  123. p1 = p0 + (p1 - p0) / (ts[0] if ts else 1)
  124. p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1)
  125. curve = (p0, p1, p2, p3)
  126. return curve, ts
  127. @cython.locals(
  128. count=cython.int,
  129. num_offcurves=cython.int,
  130. i=cython.int,
  131. off1=cython.complex,
  132. off2=cython.complex,
  133. on=cython.complex,
  134. )
  135. def add_implicit_on_curves(p):
  136. q = list(p)
  137. count = 0
  138. num_offcurves = len(p) - 2
  139. for i in range(1, num_offcurves):
  140. off1 = p[i]
  141. off2 = p[i + 1]
  142. on = off1 + (off2 - off1) * 0.5
  143. q.insert(i + 1 + count, on)
  144. count += 1
  145. return q
  146. Point = Union[Tuple[float, float], complex]
  147. @cython.locals(
  148. cost=cython.int,
  149. is_complex=cython.int,
  150. )
  151. def quadratic_to_curves(
  152. quads: List[List[Point]],
  153. max_err: float = 0.5,
  154. all_cubic: bool = False,
  155. ) -> List[Tuple[Point, ...]]:
  156. """Converts a connecting list of quadratic splines to a list of quadratic
  157. and cubic curves.
  158. A quadratic spline is specified as a list of points. Either each point is
  159. a 2-tuple of X,Y coordinates, or each point is a complex number with
  160. real/imaginary components representing X,Y coordinates.
  161. The first and last points are on-curve points and the rest are off-curve
  162. points, with an implied on-curve point in the middle between every two
  163. consequtive off-curve points.
  164. Returns:
  165. The output is a list of tuples of points. Points are represented
  166. in the same format as the input, either as 2-tuples or complex numbers.
  167. Each tuple is either of length three, for a quadratic curve, or four,
  168. for a cubic curve. Each curve's last point is the same as the next
  169. curve's first point.
  170. Args:
  171. quads: quadratic splines
  172. max_err: absolute error tolerance; defaults to 0.5
  173. all_cubic: if True, only cubic curves are generated; defaults to False
  174. """
  175. is_complex = type(quads[0][0]) is complex
  176. if not is_complex:
  177. quads = [[complex(x, y) for (x, y) in p] for p in quads]
  178. q = [quads[0][0]]
  179. costs = [1]
  180. cost = 1
  181. for p in quads:
  182. assert q[-1] == p[0]
  183. for i in range(len(p) - 2):
  184. cost += 1
  185. costs.append(cost)
  186. costs.append(cost)
  187. qq = add_implicit_on_curves(p)[1:]
  188. costs.pop()
  189. q.extend(qq)
  190. cost += 1
  191. costs.append(cost)
  192. curves = spline_to_curves(q, costs, max_err, all_cubic)
  193. if not is_complex:
  194. curves = [tuple((c.real, c.imag) for c in curve) for curve in curves]
  195. return curves
  196. Solution = namedtuple("Solution", ["num_points", "error", "start_index", "is_cubic"])
  197. @cython.locals(
  198. i=cython.int,
  199. j=cython.int,
  200. k=cython.int,
  201. start=cython.int,
  202. i_sol_count=cython.int,
  203. j_sol_count=cython.int,
  204. this_sol_count=cython.int,
  205. tolerance=cython.double,
  206. err=cython.double,
  207. error=cython.double,
  208. i_sol_error=cython.double,
  209. j_sol_error=cython.double,
  210. all_cubic=cython.int,
  211. is_cubic=cython.int,
  212. count=cython.int,
  213. p0=cython.complex,
  214. p1=cython.complex,
  215. p2=cython.complex,
  216. p3=cython.complex,
  217. v=cython.complex,
  218. u=cython.complex,
  219. )
  220. def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False):
  221. """
  222. q: quadratic spline with alternating on-curve / off-curve points.
  223. costs: cumulative list of encoding cost of q in terms of number of
  224. points that need to be encoded. Implied on-curve points do not
  225. contribute to the cost. If all points need to be encoded, then
  226. costs will be range(1, len(q)+1).
  227. """
  228. assert len(q) >= 3, "quadratic spline requires at least 3 points"
  229. # Elevate quadratic segments to cubic
  230. elevated_quadratics = [
  231. elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2)
  232. ]
  233. # Find sharp corners; they have to be oncurves for sure.
  234. forced = set()
  235. for i in range(1, len(elevated_quadratics)):
  236. p0 = elevated_quadratics[i - 1][2]
  237. p1 = elevated_quadratics[i][0]
  238. p2 = elevated_quadratics[i][1]
  239. if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0):
  240. forced.add(i)
  241. # Dynamic-Programming to find the solution with fewest number of
  242. # cubic curves, and within those the one with smallest error.
  243. sols = [Solution(0, 0, 0, False)]
  244. impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False)
  245. start = 0
  246. for i in range(1, len(elevated_quadratics) + 1):
  247. best_sol = impossible
  248. for j in range(start, i):
  249. j_sol_count, j_sol_error = sols[j].num_points, sols[j].error
  250. if not all_cubic:
  251. # Solution with quadratics between j:i
  252. this_count = costs[2 * i - 1] - costs[2 * j] + 1
  253. i_sol_count = j_sol_count + this_count
  254. i_sol_error = j_sol_error
  255. i_sol = Solution(i_sol_count, i_sol_error, i - j, False)
  256. if i_sol < best_sol:
  257. best_sol = i_sol
  258. if this_count <= 3:
  259. # Can't get any better than this in the path below
  260. continue
  261. # Fit elevated_quadratics[j:i] into one cubic
  262. try:
  263. curve, ts = merge_curves(elevated_quadratics, j, i - j)
  264. except ZeroDivisionError:
  265. continue
  266. # Now reconstruct the segments from the fitted curve
  267. reconstructed_iter = splitCubicAtTC(*curve, *ts)
  268. reconstructed = []
  269. # Knot errors
  270. error = 0
  271. for k, reconst in enumerate(reconstructed_iter):
  272. orig = elevated_quadratics[j + k]
  273. err = abs(reconst[3] - orig[3])
  274. error = max(error, err)
  275. if error > tolerance:
  276. break
  277. reconstructed.append(reconst)
  278. if error > tolerance:
  279. # Not feasible
  280. continue
  281. # Interior errors
  282. for k, reconst in enumerate(reconstructed):
  283. orig = elevated_quadratics[j + k]
  284. p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig))
  285. if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
  286. error = tolerance + 1
  287. break
  288. if error > tolerance:
  289. # Not feasible
  290. continue
  291. # Save best solution
  292. i_sol_count = j_sol_count + 3
  293. i_sol_error = max(j_sol_error, error)
  294. i_sol = Solution(i_sol_count, i_sol_error, i - j, True)
  295. if i_sol < best_sol:
  296. best_sol = i_sol
  297. if i_sol_count == 3:
  298. # Can't get any better than this
  299. break
  300. sols.append(best_sol)
  301. if i in forced:
  302. start = i
  303. # Reconstruct solution
  304. splits = []
  305. cubic = []
  306. i = len(sols) - 1
  307. while i:
  308. count, is_cubic = sols[i].start_index, sols[i].is_cubic
  309. splits.append(i)
  310. cubic.append(is_cubic)
  311. i -= count
  312. curves = []
  313. j = 0
  314. for i, is_cubic in reversed(list(zip(splits, cubic))):
  315. if is_cubic:
  316. curves.append(merge_curves(elevated_quadratics, j, i - j)[0])
  317. else:
  318. for k in range(j, i):
  319. curves.append(q[k * 2 : k * 2 + 3])
  320. j = i
  321. return curves
  322. def main():
  323. from fontTools.cu2qu.benchmark import generate_curve
  324. from fontTools.cu2qu import curve_to_quadratic
  325. tolerance = 0.05
  326. reconstruct_tolerance = tolerance * 1
  327. curve = generate_curve()
  328. quadratics = curve_to_quadratic(curve, tolerance)
  329. print(
  330. "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance)
  331. )
  332. print("One random cubic turned into %d quadratics." % len(quadratics))
  333. curves = quadratic_to_curves([quadratics], reconstruct_tolerance)
  334. print("Those quadratics turned back into %d cubics. " % len(curves))
  335. print("Original curve:", curve)
  336. print("Reconstructed curve(s):", curves)
  337. if __name__ == "__main__":
  338. main()