Debian Codegraph @

svglib/utils.py

raw symbols SCIP
1 """
2 This is a collection of utilities used by the ``svglib`` code module.
3 """
4
5 import re
6 from math import acos, ceil, copysign, cos, degrees, fabs, hypot, radians, sin, sqrt
7
8 from reportlab.graphics.shapes import mmult, rotate, translate, transformPoint
9
10
11 def split_floats(op, min_num, value):
12 """Split `value`, a list of numbers as a string, to a list of float numbers.
13
14 Also optionally insert a `l` or `L` operation depending on the operation
15 and the length of values.
16 Example: with op='m' and value='10,20 30,40,' the returned value will be
17 ['m', [10.0, 20.0], 'l', [30.0, 40.0]]
18 """
19 floats = [float(seq) for seq in re.findall(r'(-?\d*\.?\d*(?:[eE][+-]?\d+)?)', value) if seq]
20 res = []
21 for i in range(0, len(floats), min_num):
22 if i > 0 and op in {'m', 'M'}:
23 op = 'l' if op == 'm' else 'L'
24 res.extend([op, floats[i:i + min_num]])
25 return res
26
27
28 def split_arc_values(op, value):
29 float_re = r'(-?\d*\.?\d*(?:[eE][+-]?\d+)?)'
30 flag_re = r'([1|0])'
31 # 3 numb, 2 flags, 1 coord pair
32 a_seq_re = r'[\s,]*'.join([
33 float_re, float_re, float_re, flag_re, flag_re, float_re, float_re
34 ]) + r'[\s,]*'
35 res = []
36 for seq in re.finditer(a_seq_re, value.strip()):
37 res.extend([op, [float(num) for num in seq.groups()]])
38 return res
39
40
41 def normalise_svg_path(attr):
42 """Normalise SVG path.
43
44 This basically introduces operator codes for multi-argument
45 parameters. Also, it fixes sequences of consecutive M or m
46 operators to MLLL... and mlll... operators. It adds an empty
47 list as argument for Z and z only in order to make the resul-
48 ting list easier to iterate over.
49
50 E.g. "M 10 20, M 20 20, L 30 40, 40 40, Z"
51 -> ['M', [10, 20], 'L', [20, 20], 'L', [30, 40], 'L', [40, 40], 'Z', []]
52 """
53
54 # operator codes mapped to the minimum number of expected arguments
55 ops = {
56 'A': 7, 'a': 7,
57 'Q': 4, 'q': 4, 'T': 2, 't': 2, 'S': 4, 's': 4,
58 'M': 2, 'L': 2, 'm': 2, 'l': 2, 'H': 1, 'V': 1,
59 'h': 1, 'v': 1, 'C': 6, 'c': 6, 'Z': 0, 'z': 0,
60 }
61 op_keys = ops.keys()
62
63 # do some preprocessing
64 result = []
65 groups = re.split('([achlmqstvz])', attr.strip(), flags=re.I)
66 op = None
67 for item in groups:
68 if item.strip() == '':
69 continue
70 if item in op_keys:
71 # fix sequences of M to one M plus a sequence of L operators,
72 # same for m and l.
73 if item == 'M' and item == op:
74 op = 'L'
75 elif item == 'm' and item == op:
76 op = 'l'
77 else:
78 op = item
79 if ops[op] == 0: # Z, z
80 result.extend([op, []])
81 else:
82 if op.lower() == 'a':
83 result.extend(split_arc_values(op, item))
84 else:
85 result.extend(split_floats(op, ops[op], item))
86 op = result[-2] # Remember last op
87
88 return result
89
90
91 def convert_quadratic_to_cubic_path(q0, q1, q2):
92 """
93 Convert a quadratic Bezier curve through q0, q1, q2 to a cubic one.
94 """
95 c0 = q0
96 c1 = (q0[0] + 2 / 3 * (q1[0] - q0[0]), q0[1] + 2 / 3 * (q1[1] - q0[1]))
97 c2 = (c1[0] + 1 / 3 * (q2[0] - q0[0]), c1[1] + 1 / 3 * (q2[1] - q0[1]))
98 c3 = q2
99 return c0, c1, c2, c3
100
101
102 # ***********************************************
103 # Helper functions for elliptical arc conversion.
104 # ***********************************************
105
106 def vector_angle(u, v):
107 d = hypot(*u) * hypot(*v)
108 if d == 0:
109 return 0
110 c = (u[0] * v[0] + u[1] * v[1]) / d
111 if c < -1:
112 c = -1
113 elif c > 1:
114 c = 1
115 s = u[0] * v[1] - u[1] * v[0]
116 return degrees(copysign(acos(c), s))
117
118
119 def end_point_to_center_parameters(x1, y1, x2, y2, fA, fS, rx, ry, phi=0):
120 '''
121 See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5
122 note that we reduce phi to zero outside this routine
123 '''
124 rx = fabs(rx)
125 ry = fabs(ry)
126
127 # step 1
128 if phi:
129 phi_rad = radians(phi)
130 sin_phi = sin(phi_rad)
131 cos_phi = cos(phi_rad)
132 tx = 0.5 * (x1 - x2)
133 ty = 0.5 * (y1 - y2)
134 x1d = cos_phi * tx - sin_phi * ty
135 y1d = sin_phi * tx + cos_phi * ty
136 else:
137 x1d = 0.5 * (x1 - x2)
138 y1d = 0.5 * (y1 - y2)
139
140 # step 2
141 # we need to calculate
142 # (rx*rx*ry*ry-rx*rx*y1d*y1d-ry*ry*x1d*x1d)
143 # -----------------------------------------
144 # (rx*rx*y1d*y1d+ry*ry*x1d*x1d)
145 #
146 # that is equivalent to
147 #
148 # rx*rx*ry*ry
149 # = ----------------------------- - 1
150 # (rx*rx*y1d*y1d+ry*ry*x1d*x1d)
151 #
152 # 1
153 # = -------------------------------- - 1
154 # x1d*x1d/(rx*rx) + y1d*y1d/(ry*ry)
155 #
156 # = 1/r - 1
157 #
158 # it turns out r is what they recommend checking
159 # for the negative radicand case
160 r = x1d * x1d / (rx * rx) + y1d * y1d / (ry * ry)
161 if r > 1:
162 rr = sqrt(r)
163 rx *= rr
164 ry *= rr
165 r = x1d * x1d / (rx * rx) + y1d * y1d / (ry * ry)
166 r = 1 / r - 1
167 elif r != 0:
168 r = 1 / r - 1
169 if -1e-10 < r < 0:
170 r = 0
171 r = sqrt(r)
172 if fA == fS:
173 r = -r
174 cxd = (r * rx * y1d) / ry
175 cyd = -(r * ry * x1d) / rx
176
177 # step 3
178 if phi:
179 cx = cos_phi * cxd - sin_phi * cyd + 0.5 * (x1 + x2)
180 cy = sin_phi * cxd + cos_phi * cyd + 0.5 * (y1 + y2)
181 else:
182 cx = cxd + 0.5 * (x1 + x2)
183 cy = cyd + 0.5 * (y1 + y2)
184
185 # step 4
186 theta1 = vector_angle((1, 0), ((x1d - cxd) / rx, (y1d - cyd) / ry))
187 dtheta = vector_angle(
188 ((x1d - cxd) / rx, (y1d - cyd) / ry),
189 ((-x1d - cxd) / rx, (-y1d - cyd) / ry)
190 ) % 360
191 if fS == 0 and dtheta > 0:
192 dtheta -= 360
193 elif fS == 1 and dtheta < 0:
194 dtheta += 360
195 return cx, cy, rx, ry, -theta1, -dtheta
196
197
198 def bezier_arc_from_centre(cx, cy, rx, ry, start_ang=0, extent=90):
199 if abs(extent) <= 90:
200 nfrag = 1
201 frag_angle = extent
202 else:
203 nfrag = ceil(abs(extent) / 90)
204 frag_angle = extent / nfrag
205 if frag_angle == 0:
206 return []
207
208 frag_rad = radians(frag_angle)
209 half_rad = frag_rad * 0.5
210 kappa = abs(4 / 3 * (1 - cos(half_rad)) / sin(half_rad))
211
212 if frag_angle < 0:
213 kappa = -kappa
214
215 point_list = []
216 theta1 = radians(start_ang)
217 start_rad = theta1 + frag_rad
218
219 c1 = cos(theta1)
220 s1 = sin(theta1)
221 for i in range(nfrag):
222 c0 = c1
223 s0 = s1
224 theta1 = start_rad + i * frag_rad
225 c1 = cos(theta1)
226 s1 = sin(theta1)
227 point_list.append((cx + rx * c0,
228 cy - ry * s0,
229 cx + rx * (c0 - kappa * s0),
230 cy - ry * (s0 + kappa * c0),
231 cx + rx * (c1 + kappa * s1),
232 cy - ry * (s1 - kappa * c1),
233 cx + rx * c1,
234 cy - ry * s1))
235 return point_list
236
237
238 def bezier_arc_from_end_points(x1, y1, rx, ry, phi, fA, fS, x2, y2):
239 if (x1 == x2 and y1 == y2):
240 # From https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes:
241 # If the endpoints (x1, y1) and (x2, y2) are identical, then this is
242 # equivalent to omitting the elliptical arc segment entirely.
243 return []
244 if phi:
245 # Our box bezier arcs can't handle rotations directly
246 # move to a well known point, eliminate phi and transform the other point
247 mx = mmult(rotate(-phi), translate(-x1, -y1))
248 tx2, ty2 = transformPoint(mx, (x2, y2))
249 # Convert to box form in unrotated coords
250 cx, cy, rx, ry, start_ang, extent = end_point_to_center_parameters(
251 0, 0, tx2, ty2, fA, fS, rx, ry
252 )
253 bp = bezier_arc_from_centre(cx, cy, rx, ry, start_ang, extent)
254 # Re-rotate by the desired angle and add back the translation
255 mx = mmult(translate(x1, y1), rotate(phi))
256 res = []
257 for x1, y1, x2, y2, x3, y3, x4, y4 in bp:
258 res.append(
259 transformPoint(mx, (x1, y1)) + transformPoint(mx, (x2, y2)) +
260 transformPoint(mx, (x3, y3)) + transformPoint(mx, (x4, y4))
261 )
262 return res
263 else:
264 cx, cy, rx, ry, start_ang, extent = end_point_to_center_parameters(
265 x1, y1, x2, y2, fA, fS, rx, ry
266 )
267 return bezier_arc_from_centre(cx, cy, rx, ry, start_ang, extent)