svgparse.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 12/18/2015 #
  6. # MIT Licence #
  7. # #
  8. # SVG Features supported: #
  9. # * Groups #
  10. # * Rectangles (w/ rounded corners) #
  11. # * Circles #
  12. # * Ellipses #
  13. # * Polygons #
  14. # * Polylines #
  15. # * Lines #
  16. # * Paths #
  17. # * All transformations #
  18. # #
  19. # Reference: www.w3.org/TR/SVG/Overview.html #
  20. ############################################################
  21. import xml.etree.ElementTree as ET
  22. import re
  23. import itertools
  24. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  25. from shapely.geometry import LinearRing, LineString, Point
  26. from shapely.affinity import translate, rotate, scale, skew, affine_transform
  27. import numpy as np
  28. import logging
  29. log = logging.getLogger('base2')
  30. def svgparselength(lengthstr):
  31. """
  32. Parse an SVG length string into a float and a units
  33. string, if any.
  34. :param lengthstr: SVG length string.
  35. :return: Number and units pair.
  36. :rtype: tuple(float, str|None)
  37. """
  38. integer_re_str = r'[+-]?[0-9]+'
  39. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  40. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  41. length_re_str = r'(' + number_re_str + r')(em|ex|px|in|cm|mm|pt|pc|%)?'
  42. match = re.search(length_re_str, lengthstr)
  43. if match:
  44. return float(match.group(1)), match.group(2)
  45. raise Exception('Cannot parse SVG length: %s' % lengthstr)
  46. def path2shapely(path, res=1.0):
  47. """
  48. Converts an svg.path.Path into a Shapely
  49. LinearRing or LinearString.
  50. :rtype : LinearRing
  51. :rtype : LineString
  52. :param path: svg.path.Path instance
  53. :param res: Resolution (minimum step along path)
  54. :return: Shapely geometry object
  55. """
  56. points = []
  57. for component in path:
  58. # Line
  59. if isinstance(component, Line):
  60. start = component.start
  61. x, y = start.real, start.imag
  62. if len(points) == 0 or points[-1] != (x, y):
  63. points.append((x, y))
  64. end = component.end
  65. points.append((end.real, end.imag))
  66. continue
  67. # Arc, CubicBezier or QuadraticBezier
  68. if isinstance(component, Arc) or \
  69. isinstance(component, CubicBezier) or \
  70. isinstance(component, QuadraticBezier):
  71. # How many points to use in the dicrete representation.
  72. length = component.length(res / 10.0)
  73. steps = int(length / res + 0.5)
  74. frac = 1.0 / steps
  75. # print length, steps, frac
  76. for i in range(steps):
  77. point = component.point(i * frac)
  78. x, y = point.real, point.imag
  79. if len(points) == 0 or points[-1] != (x, y):
  80. points.append((x, y))
  81. end = component.point(1.0)
  82. points.append((end.real, end.imag))
  83. continue
  84. log.warning("I don't know what this is:", component)
  85. continue
  86. if path.closed:
  87. return LinearRing(points)
  88. else:
  89. return LineString(points)
  90. def svgrect2shapely(rect, n_points=32):
  91. """
  92. Converts an SVG rect into Shapely geometry.
  93. :param rect: Rect Element
  94. :type rect: xml.etree.ElementTree.Element
  95. :return: shapely.geometry.polygon.LinearRing
  96. """
  97. w = svgparselength(rect.get('width'))[0]
  98. h = svgparselength(rect.get('height'))[0]
  99. x = svgparselength(rect.get('x'))[0]
  100. y = svgparselength(rect.get('y'))[0]
  101. rxstr = rect.get('rx')
  102. rystr = rect.get('ry')
  103. if rxstr is None and rystr is None: # Sharp corners
  104. pts = [
  105. (x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)
  106. ]
  107. else: # Rounded corners
  108. rx = 0.0 if rxstr is None else svgparselength(rxstr)[0]
  109. ry = 0.0 if rystr is None else svgparselength(rystr)[0]
  110. n_points = int(n_points / 4 + 0.5)
  111. t = np.arange(n_points, dtype=float) / n_points / 4
  112. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * (t + 0.75))
  113. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.75))
  114. lower_right = [(x_[i], y_[i]) for i in range(n_points)]
  115. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * t)
  116. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * t)
  117. upper_right = [(x_[i], y_[i]) for i in range(n_points)]
  118. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.25))
  119. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * (t + 0.25))
  120. upper_left = [(x_[i], y_[i]) for i in range(n_points)]
  121. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.5))
  122. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.5))
  123. lower_left = [(x_[i], y_[i]) for i in range(n_points)]
  124. pts = [(x + rx, y), (x - rx + w, y)] + \
  125. lower_right + \
  126. [(x + w, y + ry), (x + w, y + h - ry)] + \
  127. upper_right + \
  128. [(x + w - rx, y + h), (x + rx, y + h)] + \
  129. upper_left + \
  130. [(x, y + h - ry), (x, y + ry)] + \
  131. lower_left
  132. return LinearRing(pts)
  133. def svgcircle2shapely(circle):
  134. """
  135. Converts an SVG circle into Shapely geometry.
  136. :param circle: Circle Element
  137. :type circle: xml.etree.ElementTree.Element
  138. :return: Shapely representation of the circle.
  139. :rtype: shapely.geometry.polygon.LinearRing
  140. """
  141. # cx = float(circle.get('cx'))
  142. # cy = float(circle.get('cy'))
  143. # r = float(circle.get('r'))
  144. cx = svgparselength(circle.get('cx'))[0] # TODO: No units support yet
  145. cy = svgparselength(circle.get('cy'))[0] # TODO: No units support yet
  146. r = svgparselength(circle.get('r'))[0] # TODO: No units support yet
  147. # TODO: No resolution specified.
  148. return Point(cx, cy).buffer(r)
  149. def svgellipse2shapely(ellipse, n_points=64):
  150. """
  151. Converts an SVG ellipse into Shapely geometry
  152. :param ellipse: Ellipse Element
  153. :type ellipse: xml.etree.ElementTree.Element
  154. :param n_points: Number of discrete points in output.
  155. :return: Shapely representation of the ellipse.
  156. :rtype: shapely.geometry.polygon.LinearRing
  157. """
  158. cx = svgparselength(ellipse.get('cx'))[0] # TODO: No units support yet
  159. cy = svgparselength(ellipse.get('cy'))[0] # TODO: No units support yet
  160. rx = svgparselength(ellipse.get('rx'))[0] # TODO: No units support yet
  161. ry = svgparselength(ellipse.get('ry'))[0] # TODO: No units support yet
  162. t = np.arange(n_points, dtype=float) / n_points
  163. x = cx + rx * np.cos(2 * np.pi * t)
  164. y = cy + ry * np.sin(2 * np.pi * t)
  165. pts = [(x[i], y[i]) for i in range(n_points)]
  166. return LinearRing(pts)
  167. def svgline2shapely(line):
  168. """
  169. :param line: Line element
  170. :type line: xml.etree.ElementTree.Element
  171. :return: Shapely representation on the line.
  172. :rtype: shapely.geometry.polygon.LinearRing
  173. """
  174. x1 = svgparselength(line.get('x1'))[0]
  175. y1 = svgparselength(line.get('y1'))[0]
  176. x2 = svgparselength(line.get('x2'))[0]
  177. y2 = svgparselength(line.get('y2'))[0]
  178. return LineString([(x1, y1), (x2, y2)])
  179. def svgpolyline2shapely(polyline):
  180. ptliststr = polyline.get('points')
  181. points = parse_svg_point_list(ptliststr)
  182. return LineString(points)
  183. def svgpolygon2shapely(polygon):
  184. ptliststr = polygon.get('points')
  185. points = parse_svg_point_list(ptliststr)
  186. return LinearRing(points)
  187. def getsvggeo(node):
  188. """
  189. Extracts and flattens all geometry from an SVG node
  190. into a list of Shapely geometry.
  191. :param node: xml.etree.ElementTree.Element
  192. :return: List of Shapely geometry
  193. :rtype: list
  194. """
  195. kind = re.search('(?:\{.*\})?(.*)$', node.tag).group(1)
  196. geo = []
  197. # Recurse
  198. if len(node) > 0:
  199. for child in node:
  200. subgeo = getsvggeo(child)
  201. if subgeo is not None:
  202. geo += subgeo
  203. # Parse
  204. elif kind == 'path':
  205. log.debug("***PATH***")
  206. P = parse_path(node.get('d'))
  207. P = path2shapely(P)
  208. geo = [P]
  209. elif kind == 'rect':
  210. log.debug("***RECT***")
  211. R = svgrect2shapely(node)
  212. geo = [R]
  213. elif kind == 'circle':
  214. log.debug("***CIRCLE***")
  215. C = svgcircle2shapely(node)
  216. geo = [C]
  217. elif kind == 'ellipse':
  218. log.debug("***ELLIPSE***")
  219. E = svgellipse2shapely(node)
  220. geo = [E]
  221. elif kind == 'polygon':
  222. log.debug("***POLYGON***")
  223. poly = svgpolygon2shapely(node)
  224. geo = [poly]
  225. elif kind == 'line':
  226. log.debug("***LINE***")
  227. line = svgline2shapely(node)
  228. geo = [line]
  229. elif kind == 'polyline':
  230. log.debug("***POLYLINE***")
  231. pline = svgpolyline2shapely(node)
  232. geo = [pline]
  233. else:
  234. log.warning("Unknown kind: " + kind)
  235. geo = None
  236. # Transformations
  237. if 'transform' in node.attrib:
  238. trstr = node.get('transform')
  239. trlist = parse_svg_transform(trstr)
  240. #log.debug(trlist)
  241. # Transformations are applied in reverse order
  242. for tr in trlist[::-1]:
  243. if tr[0] == 'translate':
  244. geo = [translate(geoi, tr[1], tr[2]) for geoi in geo]
  245. elif tr[0] == 'scale':
  246. geo = [scale(geoi, tr[0], tr[1], origin=(0, 0))
  247. for geoi in geo]
  248. elif tr[0] == 'rotate':
  249. geo = [rotate(geoi, tr[1], origin=(tr[2], tr[3]))
  250. for geoi in geo]
  251. elif tr[0] == 'skew':
  252. geo = [skew(geoi, tr[1], tr[2], origin=(0, 0))
  253. for geoi in geo]
  254. elif tr[0] == 'matrix':
  255. geo = [affine_transform(geoi, tr[1:]) for geoi in geo]
  256. else:
  257. raise Exception('Unknown transformation: %s', tr)
  258. return geo
  259. def parse_svg_point_list(ptliststr):
  260. """
  261. Returns a list of coordinate pairs extracted from the "points"
  262. attribute in SVG polygons and polylines.
  263. :param ptliststr: "points" attribute string in polygon or polyline.
  264. :return: List of tuples with coordinates.
  265. """
  266. pairs = []
  267. last = None
  268. pos = 0
  269. i = 0
  270. for match in re.finditer(r'(\s*,\s*)|(\s+)', ptliststr):
  271. val = float(ptliststr[pos:match.start()])
  272. if i % 2 == 1:
  273. pairs.append((last, val))
  274. else:
  275. last = val
  276. pos = match.end()
  277. i += 1
  278. # Check for last element
  279. val = float(ptliststr[pos:])
  280. if i % 2 == 1:
  281. pairs.append((last, val))
  282. else:
  283. log.warning("Incomplete coordinates.")
  284. return pairs
  285. def parse_svg_transform(trstr):
  286. """
  287. Parses an SVG transform string into a list
  288. of transform names and their parameters.
  289. Possible transformations are:
  290. * Translate: translate(<tx> [<ty>]), which specifies
  291. a translation by tx and ty. If <ty> is not provided,
  292. it is assumed to be zero. Result is
  293. ['translate', tx, ty]
  294. * Scale: scale(<sx> [<sy>]), which specifies a scale operation
  295. by sx and sy. If <sy> is not provided, it is assumed to be
  296. equal to <sx>. Result is: ['scale', sx, sy]
  297. * Rotate: rotate(<rotate-angle> [<cx> <cy>]), which specifies
  298. a rotation by <rotate-angle> degrees about a given point.
  299. If optional parameters <cx> and <cy> are not supplied,
  300. the rotate is about the origin of the current user coordinate
  301. system. Result is: ['rotate', rotate-angle, cx, cy]
  302. * Skew: skewX(<skew-angle>), which specifies a skew
  303. transformation along the x-axis. skewY(<skew-angle>), which
  304. specifies a skew transformation along the y-axis.
  305. Result is ['skew', angle-x, angle-y]
  306. * Matrix: matrix(<a> <b> <c> <d> <e> <f>), which specifies a
  307. transformation in the form of a transformation matrix of six
  308. values. matrix(a,b,c,d,e,f) is equivalent to applying the
  309. transformation matrix [a b c d e f]. Result is
  310. ['matrix', a, b, c, d, e, f]
  311. Note: All parameters to the transformations are "numbers",
  312. i.e. no units present.
  313. :param trstr: SVG transform string.
  314. :type trstr: str
  315. :return: List of transforms.
  316. :rtype: list
  317. """
  318. trlist = []
  319. assert isinstance(trstr, str)
  320. trstr = trstr.strip(' ')
  321. integer_re_str = r'[+-]?[0-9]+'
  322. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  323. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  324. # num_re_str = r'[\+\-]?[0-9\.e]+' # TODO: Negative exponents missing
  325. comma_or_space_re_str = r'(?:(?:\s+)|(?:\s*,\s*))'
  326. translate_re_str = r'translate\s*\(\s*(' + \
  327. number_re_str + r')(?:' + \
  328. comma_or_space_re_str + \
  329. r'(' + number_re_str + r'))?\s*\)'
  330. scale_re_str = r'scale\s*\(\s*(' + \
  331. number_re_str + r')' + \
  332. r'(?:' + comma_or_space_re_str + \
  333. r'(' + number_re_str + r'))?\s*\)'
  334. skew_re_str = r'skew([XY])\s*\(\s*(' + \
  335. number_re_str + r')\s*\)'
  336. rotate_re_str = r'rotate\s*\(\s*(' + \
  337. number_re_str + r')' + \
  338. r'(?:' + comma_or_space_re_str + \
  339. r'(' + number_re_str + r')' + \
  340. comma_or_space_re_str + \
  341. r'(' + number_re_str + r'))?\*\)'
  342. matrix_re_str = r'matrix\s*\(\s*' + \
  343. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  344. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  345. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  346. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  347. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  348. r'(' + number_re_str + r')\s*\)'
  349. while len(trstr) > 0:
  350. match = re.search(r'^' + translate_re_str, trstr)
  351. if match:
  352. trlist.append([
  353. 'translate',
  354. float(match.group(1)),
  355. float(match.group(2)) if match.group else 0.0
  356. ])
  357. trstr = trstr[len(match.group(0)):].strip(' ')
  358. continue
  359. match = re.search(r'^' + scale_re_str, trstr)
  360. if match:
  361. trlist.append([
  362. 'translate',
  363. float(match.group(1)),
  364. float(match.group(2)) if match.group else float(match.group(1))
  365. ])
  366. trstr = trstr[len(match.group(0)):].strip(' ')
  367. continue
  368. match = re.search(r'^' + skew_re_str, trstr)
  369. if match:
  370. trlist.append([
  371. 'skew',
  372. float(match.group(2)) if match.group(1) == 'X' else 0.0,
  373. float(match.group(2)) if match.group(1) == 'Y' else 0.0
  374. ])
  375. trstr = trstr[len(match.group(0)):].strip(' ')
  376. continue
  377. match = re.search(r'^' + rotate_re_str, trstr)
  378. if match:
  379. trlist.append([
  380. 'rotate',
  381. float(match.group(1)),
  382. float(match.group(2)) if match.group(2) else 0.0,
  383. float(match.group(3)) if match.group(3) else 0.0
  384. ])
  385. trstr = trstr[len(match.group(0)):].strip(' ')
  386. continue
  387. match = re.search(r'^' + matrix_re_str, trstr)
  388. if match:
  389. trlist.append(['matrix'] + [float(x) for x in match.groups()])
  390. trstr = trstr[len(match.group(0)):].strip(' ')
  391. continue
  392. raise Exception("Don't know how to parse: %s" % trstr)
  393. return trlist
  394. if __name__ == "__main__":
  395. tree = ET.parse('tests/svg/drawing.svg')
  396. root = tree.getroot()
  397. ns = re.search(r'\{(.*)\}', root.tag).group(1)
  398. print ns
  399. for geo in getsvggeo(root):
  400. print geo