9c0ec35573f4e084339f30bc0942642fa3058b1c
1 #!/usr/bin/env python
2 '''
3 Copyright (C) 2005,2007,2008 Aaron Spike, aaron@ekips.org
4 Copyright (C) 2008,2010 Alvin Penner, penner@vaxxine.com
6 - template dxf_outlines.dxf added Feb 2008 by Alvin Penner
7 - ROBO-Master output option added Aug 2008
8 - ROBO-Master multispline output added Sept 2008
9 - LWPOLYLINE output modification added Dec 2008
10 - toggle between LINE/LWPOLYLINE added Jan 2010
11 - support for transform elements added July 2010
12 - support for layers added July 2010
13 - support for rectangle added Dec 2010
15 This program is free software; you can redistribute it and/or modify
16 it under the terms of the GNU General Public License as published by
17 the Free Software Foundation; either version 2 of the License, or
18 (at your option) any later version.
20 This program is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 GNU General Public License for more details.
25 You should have received a copy of the GNU General Public License
26 along with this program; if not, write to the Free Software
27 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 '''
29 import inkex, simplestyle, simpletransform, cubicsuperpath, coloreffect, dxf_templates, math
30 import gettext
31 _ = gettext.gettext
33 try:
34 from numpy import *
35 from numpy.linalg import solve
36 except:
37 inkex.errormsg(_("Failed to import the numpy or numpy.linalg modules. These modules are required by this extension. Please install them and try again."))
38 inkex.sys.exit()
40 def pointdistance((x1,y1),(x2,y2)):
41 return math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
43 def get_fit(u, csp, col):
44 return (1-u)**3*csp[0][col] + 3*(1-u)**2*u*csp[1][col] + 3*(1-u)*u**2*csp[2][col] + u**3*csp[3][col]
46 def get_matrix(u, i, j):
47 if j == i + 2:
48 return (u[i]-u[i-1])*(u[i]-u[i-1])/(u[i+2]-u[i-1])/(u[i+1]-u[i-1])
49 elif j == i + 1:
50 return ((u[i]-u[i-1])*(u[i+2]-u[i])/(u[i+2]-u[i-1]) + (u[i+1]-u[i])*(u[i]-u[i-2])/(u[i+1]-u[i-2]))/(u[i+1]-u[i-1])
51 elif j == i:
52 return (u[i+1]-u[i])*(u[i+1]-u[i])/(u[i+1]-u[i-2])/(u[i+1]-u[i-1])
53 else:
54 return 0
56 class MyEffect(inkex.Effect):
57 def __init__(self):
58 inkex.Effect.__init__(self)
59 self.OptionParser.add_option("-R", "--ROBO", action="store", type="string", dest="ROBO")
60 self.OptionParser.add_option("-P", "--POLY", action="store", type="string", dest="POLY")
61 self.OptionParser.add_option("--tab", action="store", type="string", dest="tab")
62 self.OptionParser.add_option("--inputhelp", action="store", type="string", dest="inputhelp")
63 self.dxf = []
64 self.handle = 255 # handle for DXF ENTITY
65 self.layers = ['0']
66 self.layer = '0' # mandatory layer
67 self.csp_old = [[0.0,0.0]]*4 # previous spline
68 self.d = array([0], float) # knot vector
69 self.poly = [[0.0,0.0]] # LWPOLYLINE data
70 def output(self):
71 print ''.join(self.dxf)
72 def dxf_add(self, str):
73 self.dxf.append(str)
74 def dxf_line(self,csp):
75 self.handle += 1
76 self.dxf_add(" 0\nLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbLine\n" % (self.handle, self.layer, self.color))
77 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n 11\n%f\n 21\n%f\n 31\n0.0\n" % (csp[0][0],csp[0][1],csp[1][0],csp[1][1]))
78 def LWPOLY_line(self,csp):
79 if (abs(csp[0][0] - self.poly[-1][0]) > .0001
80 or abs(csp[0][1] - self.poly[-1][1]) > .0001):
81 self.LWPOLY_output() # terminate current polyline
82 self.poly = [csp[0]] # initiallize new polyline
83 self.color_LWPOLY = self.color
84 self.layer_LWPOLY = self.layer
85 self.poly.append(csp[1])
86 def LWPOLY_output(self):
87 if len(self.poly) == 1:
88 return
89 self.handle += 1
90 self.dxf_add(" 0\nLWPOLYLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbPolyline\n 90\n%d\n 70\n0\n" % (self.handle, self.layer_LWPOLY, self.color_LWPOLY, len(self.poly)))
91 for i in range(len(self.poly)):
92 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (self.poly[i][0],self.poly[i][1]))
93 def dxf_spline(self,csp):
94 knots = 8
95 ctrls = 4
96 self.handle += 1
97 self.dxf_add(" 0\nSPLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbSpline\n" % (self.handle, self.layer, self.color))
98 self.dxf_add(" 70\n8\n 71\n3\n 72\n%d\n 73\n%d\n 74\n0\n" % (knots, ctrls))
99 for i in range(2):
100 for j in range(4):
101 self.dxf_add(" 40\n%d\n" % i)
102 for i in csp:
103 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (i[0],i[1]))
104 def ROBO_spline(self,csp):
105 # this spline has zero curvature at the endpoints, as in ROBO-Master
106 if (abs(csp[0][0] - self.csp_old[3][0]) > .0001
107 or abs(csp[0][1] - self.csp_old[3][1]) > .0001
108 or abs((csp[1][1]-csp[0][1])*(self.csp_old[3][0]-self.csp_old[2][0]) - (csp[1][0]-csp[0][0])*(self.csp_old[3][1]-self.csp_old[2][1])) > .001):
109 self.ROBO_output() # terminate current spline
110 self.xfit = array([csp[0][0]], float) # initiallize new spline
111 self.yfit = array([csp[0][1]], float)
112 self.d = array([0], float)
113 self.color_ROBO = self.color
114 self.layer_ROBO = self.layer
115 self.xfit = concatenate((self.xfit, zeros((3)))) # append to current spline
116 self.yfit = concatenate((self.yfit, zeros((3))))
117 self.d = concatenate((self.d, zeros((3))))
118 for i in range(1, 4):
119 j = len(self.d) + i - 4
120 self.xfit[j] = get_fit(i/3.0, csp, 0)
121 self.yfit[j] = get_fit(i/3.0, csp, 1)
122 self.d[j] = self.d[j-1] + pointdistance((self.xfit[j-1],self.yfit[j-1]),(self.xfit[j],self.yfit[j]))
123 self.csp_old = csp
124 def ROBO_output(self):
125 if len(self.d) == 1:
126 return
127 fits = len(self.d)
128 ctrls = fits + 2
129 knots = ctrls + 4
130 self.xfit = concatenate((self.xfit, zeros((2)))) # pad with 2 endpoint constraints
131 self.yfit = concatenate((self.yfit, zeros((2)))) # pad with 2 endpoint constraints
132 self.d = concatenate((self.d, zeros((6)))) # pad with 3 duplicates at each end
133 self.d[fits+2] = self.d[fits+1] = self.d[fits] = self.d[fits-1]
134 solmatrix = zeros((ctrls,ctrls), dtype=float)
135 for i in range(fits):
136 solmatrix[i,i] = get_matrix(self.d, i, i)
137 solmatrix[i,i+1] = get_matrix(self.d, i, i+1)
138 solmatrix[i,i+2] = get_matrix(self.d, i, i+2)
139 solmatrix[fits, 0] = self.d[2]/self.d[fits-1] # curvature at start = 0
140 solmatrix[fits, 1] = -(self.d[1] + self.d[2])/self.d[fits-1]
141 solmatrix[fits, 2] = self.d[1]/self.d[fits-1]
142 solmatrix[fits+1, fits-1] = (self.d[fits-1] - self.d[fits-2])/self.d[fits-1] # curvature at end = 0
143 solmatrix[fits+1, fits] = (self.d[fits-3] + self.d[fits-2] - 2*self.d[fits-1])/self.d[fits-1]
144 solmatrix[fits+1, fits+1] = (self.d[fits-1] - self.d[fits-3])/self.d[fits-1]
145 xctrl = solve(solmatrix, self.xfit)
146 yctrl = solve(solmatrix, self.yfit)
147 self.handle += 1
148 self.dxf_add(" 0\nSPLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbSpline\n" % (self.handle, self.layer_ROBO, self.color_ROBO))
149 self.dxf_add(" 70\n0\n 71\n3\n 72\n%d\n 73\n%d\n 74\n%d\n" % (knots, ctrls, fits))
150 for i in range(knots):
151 self.dxf_add(" 40\n%f\n" % self.d[i-3])
152 for i in range(ctrls):
153 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (xctrl[i],yctrl[i]))
154 for i in range(fits):
155 self.dxf_add(" 11\n%f\n 21\n%f\n 31\n0.0\n" % (self.xfit[i],self.yfit[i]))
157 def process_path(self, node, mat):
158 rgb = (0,0,0)
159 style = node.get('style')
160 if style:
161 style = simplestyle.parseStyle(style)
162 if style.has_key('stroke'):
163 if style['stroke'] and style['stroke'] != 'none':
164 rgb = simplestyle.parseColor(style['stroke'])
165 hsl = coloreffect.ColorEffect.rgb_to_hsl(coloreffect.ColorEffect(),rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0)
166 self.color = 7 # default is black
167 if hsl[2]:
168 self.color = 1 + (int(6*hsl[0] + 0.5) % 6) # use 6 hues
169 if node.tag == inkex.addNS('path','svg'):
170 d = node.get('d')
171 if not d:
172 return
173 p = cubicsuperpath.parsePath(d)
174 elif node.tag == inkex.addNS('rect','svg'):
175 x = float(node.get('x'))
176 y = float(node.get('y'))
177 width = float(node.get('width'))
178 height = float(node.get('height'))
179 p = [[[x, y],[x, y],[x, y]]]
180 p.append([[x + width, y],[x + width, y],[x + width, y]])
181 p.append([[x + width, y + height],[x + width, y + height],[x + width, y + height]])
182 p.append([[x, y + height],[x, y + height],[x, y + height]])
183 p.append([[x, y],[x, y],[x, y]])
184 p = [p]
185 else:
186 return
187 trans = node.get('transform')
188 if trans:
189 mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
190 simpletransform.applyTransformToPath(mat, p)
191 for sub in p:
192 for i in range(len(sub)-1):
193 s = sub[i]
194 e = sub[i+1]
195 if s[1] == s[2] and e[0] == e[1]:
196 if (self.options.POLY == 'true'):
197 self.LWPOLY_line([s[1],e[1]])
198 else:
199 self.dxf_line([s[1],e[1]])
200 elif (self.options.ROBO == 'true'):
201 self.ROBO_spline([s[1],s[2],e[0],e[1]])
202 else:
203 self.dxf_spline([s[1],s[2],e[0],e[1]])
205 def process_group(self, group):
206 if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
207 layer = group.get(inkex.addNS('label', 'inkscape'))
208 layer = layer.replace(' ', '_')
209 if layer in self.layers:
210 self.layer = layer
211 trans = group.get('transform')
212 if trans:
213 self.groupmat.append(simpletransform.composeTransform(self.groupmat[-1], simpletransform.parseTransform(trans)))
214 for node in group:
215 if node.tag == inkex.addNS('g','svg'):
216 self.process_group(node)
217 else:
218 self.process_path(node, self.groupmat[-1])
219 if trans:
220 self.groupmat.pop()
222 def effect(self):
223 #References: Minimum Requirements for Creating a DXF File of a 3D Model By Paul Bourke
224 # NURB Curves: A Guide for the Uninitiated By Philip J. Schneider
225 # The NURBS Book By Les Piegl and Wayne Tiller (Springer, 1995)
226 self.dxf_add("999\nDXF created by Inkscape\n")
227 self.dxf_add(dxf_templates.r14_header)
228 for node in self.document.getroot().xpath('//svg:g', namespaces=inkex.NSS):
229 if node.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
230 layer = node.get(inkex.addNS('label', 'inkscape'))
231 layer = layer.replace(' ', '_')
232 if layer and not layer in self.layers:
233 self.layers.append(layer)
234 self.dxf_add(" 2\nLAYER\n 5\n2\n100\nAcDbSymbolTable\n 70\n%s\n" % len(self.layers))
235 for i in range(len(self.layers)):
236 self.dxf_add(" 0\nLAYER\n 5\n%x\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n%s\n 70\n0\n 6\nCONTINUOUS\n" % (i + 80, self.layers[i]))
237 self.dxf_add(dxf_templates.r14_style)
239 scale = 25.4/90.0
240 h = inkex.unittouu(self.document.getroot().xpath('@height', namespaces=inkex.NSS)[0])
241 self.groupmat = [[[scale, 0.0, 0.0], [0.0, -scale, h*scale]]]
242 doc = self.document.getroot()
243 self.process_group(doc)
244 if self.options.ROBO == 'true':
245 self.ROBO_output()
246 if self.options.POLY == 'true':
247 self.LWPOLY_output()
248 self.dxf_add(dxf_templates.r14_footer)
250 if __name__ == '__main__':
251 e = MyEffect()
252 e.affect()
255 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 fileencoding=utf-8 textwidth=99