Strip extra spaces from code.
[voro++.git] / branches / 2d / boundary / svg2bnd.py
blobff1e03cb9caa220fc92c8b7ca5fe6bab6a8ce220
1 #!/usr/bin/python
2 """svg2bnd.py -- Converts a path in an SVG file to a boundary for Voro++."""
4 import sys,re
5 from svgfig import svg, pathdata
6 from math import sqrt
8 if len(sys.argv) < 2:
9 print 'Usage: svg2bnd <file>'
10 sys.exit(0)
11 stage = 0
12 count = 0
13 obj = svg.load(sys.argv[1])
14 semitotal = 0
15 for key, elem in obj.walk():
16 if isinstance(elem, svg.SVG):
17 if elem.tag == 'path':
18 print '# Start'
19 redo = 0
20 commandStr = elem[u'd']
21 commandStr = re.sub('([0-9])-', ' -', commandStr)
22 # HACK: Add some spaces to ease along parsing.
23 commands = pathdata.parse(commandStr)
24 lx, ly = 0.0, 0.0
25 x, y = 0.0, 0.0
26 xs = []
27 ys = []
28 for c in commands:
29 d = c[0]
31 if d == u'L' or d == u'M': # Absolute position line
32 x, y = c[1], c[2]
33 elif d == u'l' or d == u'm': # Relative position line
34 dx, dy = c[1], c[2]
35 x += dx
36 y += dy
37 elif d == u'H': # Absolute position horizontal motion
38 x = c[1]
39 elif d == u'h': # Relative position horizontal motion
40 x += c[1]
41 elif d == u'V': # Absolute position vertical motion
42 y = c[1]
43 elif d == u'v': # Relative position vertical motion
44 y += c[1]
45 if (redo == 0 or (sqrt((x-xs[-1])**2+(y-ys[-1])**2) > 1e-5)):
46 xs.append(x)
47 ys.append(y)
48 count = count + 1
49 redo = redo + 1
50 if sqrt((xs[-1]-xs[0])**2+(ys[-1]-ys[0])**2) < 1e-5:
51 xs = xs[:-1]
52 ys = ys[:-1]
53 count = count - 1
54 for i in xrange(len(xs)):
55 print i+semitotal, xs[i], ys[i]
57 print '# End'
58 semitotal = count
59 elif elem.tag == 'polygon':
60 redo = 0
61 print '# Start'
62 pointsStr = elem['points']
63 pointses = pointsStr.split()
64 xs = []
65 ys = []
66 for p in pointses:
67 x,y = p.split(u',')
68 if (redo ==0 or (sqrt((x-xs[-1])**2+(y-ys[-1])**2) > 1e-5)):
69 xs.append(x)
70 ys.append(y)
71 count = count + 1
72 redo = redo + 1
73 if sqrt((xs[-1]-xs[0])**2+(ys[-1]-ys[0])**2) < 1e-5:
74 xs = xs[:-1]
75 ys = ys[:-1]
76 count = count - 1
77 for i in xrange(len(xs)):
78 print i + semitotal, xs[i], ys[i]
80 print '# End'
81 semittotal=count
82 # else:
83 # print 'Unsupported element tag: %s'%elem.tag