chiark / gitweb /
Merge pull request #575 from ad1217/SteamEngine
[cura.git] / Cura / util / svg.py
1 from __future__ import absolute_import
2 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
3
4 import math
5 import re
6 import sys
7 import numpy
8 from xml.etree import ElementTree
9
10 def applyTransformString(matrix, transform):
11         while transform != '':
12                 if transform[0] == ',':
13                         transform = transform[1:].strip()
14                 s = transform.find('(')
15                 e = transform.find(')')
16                 if s < 0 or e < 0:
17                         print 'Unknown transform: %s' % (transform)
18                         return matrix
19                 tag = transform[:s]
20                 data = map(float, re.split('[ \t,]+', transform[s+1:e].strip()))
21                 if tag == 'matrix' and len(data) == 6:
22                         matrix = numpy.matrix([[data[0],data[1],0],[data[2],data[3],0],[data[4],data[5],1]], numpy.float64) * matrix
23                 elif tag == 'translate' and len(data) == 1:
24                         matrix = numpy.matrix([[1,0,data[0]],[0,1,0],[0,0,1]], numpy.float64) * matrix
25                 elif tag == 'translate' and len(data) == 2:
26                         matrix = numpy.matrix([[1,0,0],[0,1,0],[data[0],data[1],1]], numpy.float64) * matrix
27                 elif tag == 'scale' and len(data) == 1:
28                         matrix = numpy.matrix([[data[0],0,0],[0,data[0],0],[0,0,1]], numpy.float64) * matrix
29                 elif tag == 'scale' and len(data) == 2:
30                         matrix = numpy.matrix([[data[0],0,0],[0,data[1],0],[0,0,1]], numpy.float64) * matrix
31                 elif tag == 'rotate' and len(data) == 1:
32                         r = math.radians(data[0])
33                         matrix = numpy.matrix([[math.cos(r),math.sin(r),0],[-math.sin(r),math.cos(r),0],[0,0,1]], numpy.float64) * matrix
34                 elif tag == 'rotate' and len(data) == 3:
35                         matrix = numpy.matrix([[1,0,0],[0,1,0],[data[1],data[2],1]], numpy.float64) * matrix
36                         r = math.radians(data[0])
37                         matrix = numpy.matrix([[math.cos(r),math.sin(r),0],[-math.sin(r),math.cos(r),0],[0,0,1]], numpy.float64) * matrix
38                         matrix = numpy.matrix([[1,0,0],[0,1,0],[-data[1],-data[2],1]], numpy.float64) * matrix
39                 elif tag == 'skewX' and len(data) == 1:
40                         matrix = numpy.matrix([[1,0,0],[math.tan(data[0]),1,0],[0,0,1]], numpy.float64) * matrix
41                 elif tag == 'skewY' and len(data) == 1:
42                         matrix = numpy.matrix([[1,math.tan(data[0]),0],[0,1,0],[0,0,1]], numpy.float64) * matrix
43                 else:
44                         print 'Unknown transform: %s' % (transform)
45                         return matrix
46                 transform = transform[e+1:].strip()
47         return matrix
48
49 def toFloat(f):
50         f = re.search('^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?', f).group(0)
51         return float(f)
52
53 class Path(object):
54         LINE = 0
55         ARC = 1
56         CURVE = 2
57
58         def __init__(self, x, y, matrix):
59                 self._matrix = matrix
60                 self._relMatrix = numpy.matrix([[matrix[0,0],matrix[0,1]], [matrix[1,0],matrix[1,1]]])
61                 self._startPoint = complex(x, y)
62                 self._points = []
63
64         def addLineTo(self, x, y):
65                 self._points.append({'type': Path.LINE, 'p': complex(x, y)})
66
67         def addArcTo(self, x, y, rot, rx, ry, large, sweep):
68                 self._points.append({
69                         'type': Path.ARC,
70                         'p': complex(x, y),
71                         'rot': rot,
72                         'radius': complex(rx, ry),
73                         'large': large,
74                         'sweep': sweep
75                 })
76
77         def addCurveTo(self, x, y, cp1x, cp1y, cp2x, cp2y):
78                 self._points.append({
79                         'type': Path.CURVE,
80                         'p': complex(x, y),
81                         'cp1': complex(cp1x, cp1y),
82                         'cp2': complex(cp2x, cp2y)
83                 })
84
85         def closePath(self):
86                 self._points.append({'type': Path.LINE, 'p': self._startPoint})
87
88         def getPoints(self, accuracy = 1):
89                 pointList = [self._m(self._startPoint)]
90                 p1 = self._startPoint
91                 for p in self._points:
92                         if p['type'] == Path.LINE:
93                                 p1 = p['p']
94                                 pointList.append(self._m(p1))
95                         elif p['type'] == Path.ARC:
96                                 p2 = p['p']
97                                 rot = math.radians(p['rot'])
98                                 r = p['radius']
99
100                                 #http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
101                                 diff = (p1 - p2) / 2
102                                 p1alt = diff #TODO: apply rot
103                                 p2alt = -diff #TODO: apply rot
104                                 rx2 = r.real*r.real
105                                 ry2 = r.imag*r.imag
106                                 x1alt2 = p1alt.real*p1alt.real
107                                 y1alt2 = p1alt.imag*p1alt.imag
108
109                                 f = x1alt2 / rx2 + y1alt2 / ry2
110                                 if f >= 1.0:
111                                         r *= math.sqrt(f+0.000001)
112                                         rx2 = r.real*r.real
113                                         ry2 = r.imag*r.imag
114
115                                 f = math.sqrt((rx2*ry2 - rx2*y1alt2 - ry2*x1alt2) / (rx2*y1alt2+ry2*x1alt2))
116                                 if p['large'] == p['sweep']:
117                                         f = -f
118                                 cAlt = f * complex(r.real*p1alt.imag/r.imag, -r.imag*p1alt.real/r.real)
119
120                                 c = cAlt + (p1 + p2) / 2 #TODO: apply rot
121
122                                 a1 = math.atan2((p1alt.imag - cAlt.imag) / r.imag, (p1alt.real - cAlt.real) / r.real)
123                                 a2 = math.atan2((p2alt.imag - cAlt.imag) / r.imag, (p2alt.real - cAlt.real) / r.real)
124
125                                 large = abs(a2 - a1) > math.pi
126                                 if large != p['large']:
127                                         if a1 < a2:
128                                                 a1 += math.pi * 2
129                                         else:
130                                                 a2 += math.pi * 2
131
132                                 pCenter = self._m(c + complex(math.cos(a1 + 0.5*(a2-a1)) * r.real, math.sin(a1 + 0.5*(a2-a1)) * r.imag))
133                                 dist = abs(pCenter - self._m(p1)) + abs(pCenter - self._m(p2))
134                                 segments = int(dist / accuracy) + 1
135                                 for n in xrange(1, segments):
136                                         pointList.append(self._m(c + complex(math.cos(a1 + n*(a2-a1)/segments) * r.real, math.sin(a1 + n*(a2-a1)/segments) * r.imag)))
137
138                                 pointList.append(self._m(p2))
139                                 p1 = p2
140                         elif p['type'] == Path.CURVE:
141                                 p1_ = self._m(p1)
142                                 p2 = self._m(p['p'])
143                                 cp1 = self._m(p['cp1'])
144                                 cp2 = self._m(p['cp2'])
145
146                                 pCenter = p1_*0.5*0.5*0.5 + cp1*3.0*0.5*0.5*0.5 + cp2*3.0*0.5*0.5*0.5 + p2*0.5*0.5*0.5
147                                 dist = abs(pCenter - p1_) + abs(pCenter - p2)
148                                 segments = int(dist / accuracy) + 1
149                                 for n in xrange(1, segments):
150                                         f = n / float(segments)
151                                         g = 1.0-f
152                                         point = p1_*g*g*g + cp1*3.0*g*g*f + cp2*3.0*g*f*f + p2*f*f*f
153                                         pointList.append(point)
154
155                                 pointList.append(p2)
156                                 p1 = p['p']
157
158                 return pointList
159
160         def getSVGPath(self):
161                 p0 = self._m(self._startPoint)
162                 ret = 'M %f %f ' % (p0.real, p0.imag)
163                 for p in self._points:
164                         if p['type'] == Path.LINE:
165                                 p0 = self._m(p['p'])
166                                 ret += 'L %f %f' % (p0.real, p0.imag)
167                         elif p['type'] == Path.ARC:
168                                 p0 = self._m(p['p'])
169                                 radius = p['radius']
170                                 ret += 'A %f %f 0 %d %d %f %f' % (radius.real, radius.imag, 1 if p['large'] else 0, 1 if p['sweep'] else 0, p0.real, p0.imag)
171                         elif p['type'] == Path.CURVE:
172                                 p0 = self._m(p['p'])
173                                 cp1 = self._m(p['cp1'])
174                                 cp2 = self._m(p['cp2'])
175                                 ret += 'C %f %f %f %f %f %f' % (cp1.real, cp1.imag, cp2.real, cp2.imag, p0.real, p0.imag)
176
177                 return ret
178
179         def _m(self, p):
180                 tmp = numpy.matrix([p.real, p.imag, 1], numpy.float64) * self._matrix
181                 return complex(tmp[0,0], tmp[0,1])
182         def _r(self, p):
183                 tmp = numpy.matrix([p.real, p.imag], numpy.float64) * self._relMatrix
184                 return complex(tmp[0,0], tmp[0,1])
185
186 class SVG(object):
187         def __init__(self, filename):
188                 self.tagProcess = {}
189                 self.tagProcess['rect'] = self._processRectTag
190                 self.tagProcess['line'] = self._processLineTag
191                 self.tagProcess['polyline'] = self._processPolylineTag
192                 self.tagProcess['polygon'] = self._processPolygonTag
193                 self.tagProcess['elipse'] = self._processPolygonTag
194                 self.tagProcess['circle'] = self._processCircleTag
195                 self.tagProcess['ellipse'] = self._processEllipseTag
196                 self.tagProcess['path'] = self._processPathTag
197                 self.tagProcess['use'] = self._processUseTag
198                 self.tagProcess['g'] = self._processGTag
199                 self.tagProcess['a'] = self._processGTag
200                 self.tagProcess['svg'] = self._processGTag
201                 self.tagProcess['text'] = None #No text implementation yet
202                 self.tagProcess['image'] = None
203                 self.tagProcess['metadata'] = None
204                 self.tagProcess['defs'] = None
205                 self.tagProcess['style'] = None
206                 self.tagProcess['marker'] = None
207                 self.tagProcess['desc'] = None
208                 self.tagProcess['filter'] = None
209                 self.tagProcess['linearGradient'] = None
210                 self.tagProcess['radialGradient'] = None
211                 self.tagProcess['pattern'] = None
212                 self.tagProcess['title'] = None
213                 self.tagProcess['animate'] = None
214                 self.tagProcess['animateColor'] = None
215                 self.tagProcess['animateTransform'] = None
216                 self.tagProcess['set'] = None
217                 self.tagProcess['script'] = None
218
219                 #From Inkscape
220                 self.tagProcess['namedview'] = None
221                 #From w3c testsuite
222                 self.tagProcess['SVGTestCase'] = None
223
224                 self.paths = []
225                 f = open(filename, "r")
226                 self._xml = ElementTree.parse(f)
227                 self._recursiveCount = 0
228                 self._processGTag(self._xml.getroot(), numpy.matrix(numpy.identity(3, numpy.float64)))
229                 self._xml = None
230                 f.close()
231
232         def _processGTag(self, tag, baseMatrix):
233                 for e in tag:
234                         if e.get('transform') is None:
235                                 matrix = baseMatrix
236                         else:
237                                 matrix = applyTransformString(baseMatrix, e.get('transform'))
238                         tagName = e.tag[e.tag.find('}')+1:]
239                         if not tagName in self.tagProcess:
240                                 print 'unknown tag: %s' % (tagName)
241                         elif self.tagProcess[tagName] is not None:
242                                 self.tagProcess[tagName](e, matrix)
243
244         def _processUseTag(self, tag, baseMatrix):
245                 if self._recursiveCount > 16:
246                         return
247                 self._recursiveCount += 1
248                 id = tag.get('{http://www.w3.org/1999/xlink}href')
249                 if id[0] == '#':
250                         for e in self._xml.findall(".//*[@id='%s']" % (id[1:])):
251                                 if e.get('transform') is None:
252                                         matrix = baseMatrix
253                                 else:
254                                         matrix = applyTransformString(baseMatrix, e.get('transform'))
255                                 tagName = e.tag[e.tag.find('}')+1:]
256                                 if not tagName in self.tagProcess:
257                                         print 'unknown tag: %s' % (tagName)
258                                 elif self.tagProcess[tagName] is not None:
259                                         self.tagProcess[tagName](e, matrix)
260                 self._recursiveCount -= 1
261
262         def _processLineTag(self, tag, matrix):
263                 x1 = toFloat(tag.get('x1', '0'))
264                 y1 = toFloat(tag.get('y1', '0'))
265                 x2 = toFloat(tag.get('x2', '0'))
266                 y2 = toFloat(tag.get('y2', '0'))
267                 p = Path(x1, y1, matrix)
268                 p.addLineTo(x2, y2)
269                 self.paths.append(p)
270
271         def _processPolylineTag(self, tag, matrix):
272                 values = map(toFloat, re.split('[, \t]+', tag.get('points', '').strip()))
273                 p = Path(values[0], values[1], matrix)
274                 for n in xrange(2, len(values)-1, 2):
275                         p.addLineTo(values[n], values[n+1])
276                 self.paths.append(p)
277
278         def _processPolygonTag(self, tag, matrix):
279                 values = map(toFloat, re.split('[, \t]+', tag.get('points', '').strip()))
280                 p = Path(values[0], values[1], matrix)
281                 for n in xrange(2, len(values)-1, 2):
282                         p.addLineTo(values[n], values[n+1])
283                 p.closePath()
284                 self.paths.append(p)
285
286         def _processCircleTag(self, tag, matrix):
287                 cx = toFloat(tag.get('cx', '0'))
288                 cy = toFloat(tag.get('cy', '0'))
289                 r = toFloat(tag.get('r', '0'))
290                 p = Path(cx-r, cy, matrix)
291                 p.addArcTo(cx+r, cy, 0, r, r, False, False)
292                 p.addArcTo(cx-r, cy, 0, r, r, False, False)
293                 self.paths.append(p)
294
295         def _processEllipseTag(self, tag, matrix):
296                 cx = toFloat(tag.get('cx', '0'))
297                 cy = toFloat(tag.get('cy', '0'))
298                 rx = toFloat(tag.get('rx', '0'))
299                 ry = toFloat(tag.get('rx', '0'))
300                 p = Path(cx-rx, cy, matrix)
301                 p.addArcTo(cx+rx, cy, 0, rx, ry, False, False)
302                 p.addArcTo(cx-rx, cy, 0, rx, ry, False, False)
303                 self.paths.append(p)
304
305         def _processRectTag(self, tag, matrix):
306                 x = toFloat(tag.get('x', '0'))
307                 y = toFloat(tag.get('y', '0'))
308                 width = toFloat(tag.get('width', '0'))
309                 height = toFloat(tag.get('height', '0'))
310                 if width <= 0 or height <= 0:
311                         return
312                 rx = tag.get('rx')
313                 ry = tag.get('ry')
314                 if rx is not None or ry is not None:
315                         if ry is None:
316                                 ry = rx
317                         if rx is None:
318                                 rx = ry
319                         rx = float(rx)
320                         ry = float(ry)
321                         if rx > width / 2:
322                                 rx = width / 2
323                         if ry > height / 2:
324                                 ry = height / 2
325                 else:
326                         rx = 0.0
327                         ry = 0.0
328
329                 if rx > 0 and ry > 0:
330                         p = Path(x+rx, y, matrix)
331                         p.addLineTo(x+width-rx, y)
332                         p.addArcTo(x+width,y+ry, 0, rx, ry, False, True)
333                         p.addLineTo(x+width, y+height-ry)
334                         p.addArcTo(x+width-rx,y+height, 0, rx, ry, False, True)
335                         p.addLineTo(x+rx, y+height)
336                         p.addArcTo(x,y+height-ry, 0, rx, ry, False, True)
337                         p.addLineTo(x, y+ry)
338                         p.addArcTo(x+rx,y, 0, rx, ry, False, True)
339                         self.paths.append(p)
340                 else:
341                         p = Path(x, y, matrix)
342                         p.addLineTo(x,y+height)
343                         p.addLineTo(x+width,y+height)
344                         p.addLineTo(x+width,y)
345                         p.closePath()
346                         self.paths.append(p)
347
348         def _processPathTag(self, tag, matrix):
349                 pathString = tag.get('d', '').replace(',', ' ')
350                 x = 0
351                 y = 0
352                 c2x = 0
353                 c2y = 0
354                 path = None
355                 for command in re.findall('[a-df-zA-DF-Z][^a-df-zA-DF-Z]*', pathString):
356                         params = re.split(' +', command[1:].strip())
357                         if len(params) > 0 and params[0] == '':
358                                 params = params[1:]
359                         if len(params) > 0 and params[-1] == '':
360                                 params = params[:-1]
361                         params = map(toFloat, params)
362                         command = command[0]
363
364                         if command == 'm':
365                                 x += params[0]
366                                 y += params[1]
367                                 path = Path(x, y, matrix)
368                                 self.paths.append(path)
369                                 params = params[2:]
370                                 while len(params) > 1:
371                                         x += params[0]
372                                         y += params[1]
373                                         params = params[2:]
374                                         path.addLineTo(x, y)
375                                 c2x, c2y = x, y
376                         elif command == 'M':
377                                 x = params[0]
378                                 y = params[1]
379                                 path = Path(x, y, matrix)
380                                 self.paths.append(path)
381                                 params = params[2:]
382                                 while len(params) > 1:
383                                         x = params[0]
384                                         y = params[1]
385                                         params = params[2:]
386                                         path.addLineTo(x, y)
387                                 c2x, c2y = x, y
388                         elif command == 'l':
389                                 while len(params) > 1:
390                                         x += params[0]
391                                         y += params[1]
392                                         params = params[2:]
393                                         path.addLineTo(x, y)
394                                 c2x, c2y = x, y
395                         elif command == 'L':
396                                 while len(params) > 1:
397                                         x = params[0]
398                                         y = params[1]
399                                         params = params[2:]
400                                         path.addLineTo(x, y)
401                                 c2x, c2y = x, y
402                         elif command == 'h':
403                                 x += params[0]
404                                 path.addLineTo(x, y)
405                                 c2x, c2y = x, y
406                         elif command == 'H':
407                                 x = params[0]
408                                 path.addLineTo(x, y)
409                                 c2x, c2y = x, y
410                         elif command == 'v':
411                                 y += params[0]
412                                 path.addLineTo(x, y)
413                                 c2x, c2y = x, y
414                         elif command == 'V':
415                                 y = params[0]
416                                 path.addLineTo(x, y)
417                                 c2x, c2y = x, y
418                         elif command == 'a':
419                                 while len(params) > 6:
420                                         x += params[5]
421                                         y += params[6]
422                                         path.addArcTo(x, y, params[2], params[0], params[1], params[3] > 0, params[4] > 0)
423                                         params = params[7:]
424                                 c2x, c2y = x, y
425                         elif command == 'A':
426                                 while len(params) > 6:
427                                         x = params[5]
428                                         y = params[6]
429                                         path.addArcTo(x, y, params[2], params[0], params[1], params[3] > 0, params[4] > 0)
430                                         params = params[7:]
431                                 c2x, c2y = x, y
432                         elif command == 'c':
433                                 while len(params) > 5:
434                                         c1x = x + params[0]
435                                         c1y = y + params[1]
436                                         c2x = x + params[2]
437                                         c2y = y + params[3]
438                                         x += params[4]
439                                         y += params[5]
440                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
441                                         params = params[6:]
442                         elif command == 'C':
443                                 while len(params) > 5:
444                                         c1x = params[0]
445                                         c1y = params[1]
446                                         c2x = params[2]
447                                         c2y = params[3]
448                                         x = params[4]
449                                         y = params[5]
450                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
451                                         params = params[6:]
452                         elif command == 's':
453                                 while len(params) > 3:
454                                         c1x = x - (c2x - x)
455                                         c1y = y - (c2y - y)
456                                         c2x = x + params[0]
457                                         c2y = y + params[1]
458                                         x += params[2]
459                                         y += params[3]
460                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
461                                         params = params[4:]
462                         elif command == 'S':
463                                 while len(params) > 3:
464                                         c1x = x - (c2x - x)
465                                         c1y = y - (c2y - y)
466                                         c2x = params[0]
467                                         c2y = params[1]
468                                         x = params[2]
469                                         y = params[3]
470                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
471                                         params = params[4:]
472                         elif command == 'q':
473                                 while len(params) > 3:
474                                         c1x = x + params[0]
475                                         c1y = y + params[1]
476                                         c2x = c1x
477                                         c2y = c1y
478                                         x += params[2]
479                                         y += params[3]
480                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
481                                         params = params[4:]
482                         elif command == 'Q':
483                                 while len(params) > 3:
484                                         c1x = params[0]
485                                         c1y = params[1]
486                                         c2x = c1x
487                                         c2y = c1y
488                                         x = params[2]
489                                         y = params[3]
490                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
491                                         params = params[4:]
492                         elif command == 't':
493                                 while len(params) > 1:
494                                         c1x = x - (c2x - x)
495                                         c1y = y - (c2y - y)
496                                         c2x = c1x
497                                         c2y = c1y
498                                         x += params[0]
499                                         y += params[1]
500                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
501                                         params = params[2:]
502                         elif command == 'T':
503                                 while len(params) > 1:
504                                         c1x = x - (c2x - x)
505                                         c1y = y - (c2y - y)
506                                         c2x = c1x
507                                         c2y = c1y
508                                         x = params[0]
509                                         y = params[1]
510                                         path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
511                                         params = params[2:]
512                         elif command == 'z' or command == 'Z':
513                                 path.closePath()
514                                 x = path._startPoint.real
515                                 y = path._startPoint.imag
516                         else:
517                                 print 'Unknown path command:', command, params
518
519
520 if __name__ == '__main__':
521         for n in xrange(1, len(sys.argv)):
522                 print 'File: %s' % (sys.argv[n])
523                 svg = SVG(sys.argv[n])
524
525         f = open("test_export.html", "w")
526
527         f.write("<!DOCTYPE html><html><body>\n")
528         f.write("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style='width:%dpx;height:%dpx'>\n" % (1000, 1000))
529         f.write("<g fill-rule='evenodd' style=\"fill: gray; stroke:black;stroke-width:2\">\n")
530         f.write("<path d=\"")
531         for path in svg.paths:
532                 points = path.getPoints()
533                 f.write("M %f %f " % (points[0].real, points[0].imag))
534                 for point in points[1:]:
535                         f.write("L %f %f " % (point.real, point.imag))
536         f.write("\"/>")
537         f.write("</g>\n")
538
539         f.write("<g style=\"fill: none; stroke:red;stroke-width:1\">\n")
540         f.write("<path d=\"")
541         for path in svg.paths:
542                 f.write(path.getSVGPath())
543         f.write("\"/>")
544         f.write("</g>\n")
545
546         f.write("</svg>\n")
547         f.write("</body></html>")
548         f.close()
549