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("--units", action="store", type="string", dest="units")
62 self.OptionParser.add_option("--tab", action="store", type="string", dest="tab")
63 self.OptionParser.add_option("--inputhelp", action="store", type="string", dest="inputhelp")
64 self.dxf = []
65 self.handle = 255 # handle for DXF ENTITY
66 self.layers = ['0']
67 self.layer = '0' # mandatory layer
68 self.csp_old = [[0.0,0.0]]*4 # previous spline
69 self.d = array([0], float) # knot vector
70 self.poly = [[0.0,0.0]] # LWPOLYLINE data
71 def output(self):
72 print ''.join(self.dxf)
73 def dxf_add(self, str):
74 self.dxf.append(str)
75 def dxf_line(self,csp):
76 self.handle += 1
77 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))
78 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]))
79 def LWPOLY_line(self,csp):
80 if (abs(csp[0][0] - self.poly[-1][0]) > .0001
81 or abs(csp[0][1] - self.poly[-1][1]) > .0001):
82 self.LWPOLY_output() # terminate current polyline
83 self.poly = [csp[0]] # initiallize new polyline
84 self.color_LWPOLY = self.color
85 self.layer_LWPOLY = self.layer
86 self.poly.append(csp[1])
87 def LWPOLY_output(self):
88 if len(self.poly) == 1:
89 return
90 self.handle += 1
91 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)))
92 for i in range(len(self.poly)):
93 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (self.poly[i][0],self.poly[i][1]))
94 def dxf_spline(self,csp):
95 knots = 8
96 ctrls = 4
97 self.handle += 1
98 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))
99 self.dxf_add(" 70\n8\n 71\n3\n 72\n%d\n 73\n%d\n 74\n0\n" % (knots, ctrls))
100 for i in range(2):
101 for j in range(4):
102 self.dxf_add(" 40\n%d\n" % i)
103 for i in csp:
104 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (i[0],i[1]))
105 def ROBO_spline(self,csp):
106 # this spline has zero curvature at the endpoints, as in ROBO-Master
107 if (abs(csp[0][0] - self.csp_old[3][0]) > .0001
108 or abs(csp[0][1] - self.csp_old[3][1]) > .0001
109 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):
110 self.ROBO_output() # terminate current spline
111 self.xfit = array([csp[0][0]], float) # initiallize new spline
112 self.yfit = array([csp[0][1]], float)
113 self.d = array([0], float)
114 self.color_ROBO = self.color
115 self.layer_ROBO = self.layer
116 self.xfit = concatenate((self.xfit, zeros((3)))) # append to current spline
117 self.yfit = concatenate((self.yfit, zeros((3))))
118 self.d = concatenate((self.d, zeros((3))))
119 for i in range(1, 4):
120 j = len(self.d) + i - 4
121 self.xfit[j] = get_fit(i/3.0, csp, 0)
122 self.yfit[j] = get_fit(i/3.0, csp, 1)
123 self.d[j] = self.d[j-1] + pointdistance((self.xfit[j-1],self.yfit[j-1]),(self.xfit[j],self.yfit[j]))
124 self.csp_old = csp
125 def ROBO_output(self):
126 if len(self.d) == 1:
127 return
128 fits = len(self.d)
129 ctrls = fits + 2
130 knots = ctrls + 4
131 self.xfit = concatenate((self.xfit, zeros((2)))) # pad with 2 endpoint constraints
132 self.yfit = concatenate((self.yfit, zeros((2)))) # pad with 2 endpoint constraints
133 self.d = concatenate((self.d, zeros((6)))) # pad with 3 duplicates at each end
134 self.d[fits+2] = self.d[fits+1] = self.d[fits] = self.d[fits-1]
135 solmatrix = zeros((ctrls,ctrls), dtype=float)
136 for i in range(fits):
137 solmatrix[i,i] = get_matrix(self.d, i, i)
138 solmatrix[i,i+1] = get_matrix(self.d, i, i+1)
139 solmatrix[i,i+2] = get_matrix(self.d, i, i+2)
140 solmatrix[fits, 0] = self.d[2]/self.d[fits-1] # curvature at start = 0
141 solmatrix[fits, 1] = -(self.d[1] + self.d[2])/self.d[fits-1]
142 solmatrix[fits, 2] = self.d[1]/self.d[fits-1]
143 solmatrix[fits+1, fits-1] = (self.d[fits-1] - self.d[fits-2])/self.d[fits-1] # curvature at end = 0
144 solmatrix[fits+1, fits] = (self.d[fits-3] + self.d[fits-2] - 2*self.d[fits-1])/self.d[fits-1]
145 solmatrix[fits+1, fits+1] = (self.d[fits-1] - self.d[fits-3])/self.d[fits-1]
146 xctrl = solve(solmatrix, self.xfit)
147 yctrl = solve(solmatrix, self.yfit)
148 self.handle += 1
149 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))
150 self.dxf_add(" 70\n0\n 71\n3\n 72\n%d\n 73\n%d\n 74\n%d\n" % (knots, ctrls, fits))
151 for i in range(knots):
152 self.dxf_add(" 40\n%f\n" % self.d[i-3])
153 for i in range(ctrls):
154 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (xctrl[i],yctrl[i]))
155 for i in range(fits):
156 self.dxf_add(" 11\n%f\n 21\n%f\n 31\n0.0\n" % (self.xfit[i],self.yfit[i]))
158 def process_path(self, node, mat):
159 rgb = (0,0,0)
160 style = node.get('style')
161 if style:
162 style = simplestyle.parseStyle(style)
163 if style.has_key('stroke'):
164 if style['stroke'] and style['stroke'] != 'none':
165 rgb = simplestyle.parseColor(style['stroke'])
166 hsl = coloreffect.ColorEffect.rgb_to_hsl(coloreffect.ColorEffect(),rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0)
167 self.color = 7 # default is black
168 if hsl[2]:
169 self.color = 1 + (int(6*hsl[0] + 0.5) % 6) # use 6 hues
170 if node.tag == inkex.addNS('path','svg'):
171 d = node.get('d')
172 if not d:
173 return
174 p = cubicsuperpath.parsePath(d)
175 elif node.tag == inkex.addNS('rect','svg'):
176 x = float(node.get('x'))
177 y = float(node.get('y'))
178 width = float(node.get('width'))
179 height = float(node.get('height'))
180 p = [[[x, y],[x, y],[x, y]]]
181 p.append([[x + width, y],[x + width, y],[x + width, y]])
182 p.append([[x + width, y + height],[x + width, y + height],[x + width, y + height]])
183 p.append([[x, y + height],[x, y + height],[x, y + height]])
184 p.append([[x, y],[x, y],[x, y]])
185 p = [p]
186 else:
187 return
188 trans = node.get('transform')
189 if trans:
190 mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
191 simpletransform.applyTransformToPath(mat, p)
192 for sub in p:
193 for i in range(len(sub)-1):
194 s = sub[i]
195 e = sub[i+1]
196 if s[1] == s[2] and e[0] == e[1]:
197 if (self.options.POLY == 'true'):
198 self.LWPOLY_line([s[1],e[1]])
199 else:
200 self.dxf_line([s[1],e[1]])
201 elif (self.options.ROBO == 'true'):
202 self.ROBO_spline([s[1],s[2],e[0],e[1]])
203 else:
204 self.dxf_spline([s[1],s[2],e[0],e[1]])
206 def process_group(self, group):
207 if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
208 layer = group.get(inkex.addNS('label', 'inkscape'))
209 layer = layer.replace(' ', '_')
210 if layer in self.layers:
211 self.layer = layer
212 trans = group.get('transform')
213 if trans:
214 self.groupmat.append(simpletransform.composeTransform(self.groupmat[-1], simpletransform.parseTransform(trans)))
215 for node in group:
216 if node.tag == inkex.addNS('g','svg'):
217 self.process_group(node)
218 else:
219 self.process_path(node, self.groupmat[-1])
220 if trans:
221 self.groupmat.pop()
223 def effect(self):
224 #References: Minimum Requirements for Creating a DXF File of a 3D Model By Paul Bourke
225 # NURB Curves: A Guide for the Uninitiated By Philip J. Schneider
226 # The NURBS Book By Les Piegl and Wayne Tiller (Springer, 1995)
227 self.dxf_add("999\nDXF created by Inkscape\n")
228 self.dxf_add(dxf_templates.r14_header)
229 for node in self.document.getroot().xpath('//svg:g', namespaces=inkex.NSS):
230 if node.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
231 layer = node.get(inkex.addNS('label', 'inkscape'))
232 layer = layer.replace(' ', '_')
233 if layer and not layer in self.layers:
234 self.layers.append(layer)
235 self.dxf_add(" 2\nLAYER\n 5\n2\n100\nAcDbSymbolTable\n 70\n%s\n" % len(self.layers))
236 for i in range(len(self.layers)):
237 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]))
238 self.dxf_add(dxf_templates.r14_style)
240 scale = eval(self.options.units)
241 if not scale:
242 scale = 25.4/90
243 h = inkex.unittouu(self.document.getroot().xpath('@height', namespaces=inkex.NSS)[0])
244 self.groupmat = [[[scale, 0.0, 0.0], [0.0, -scale, h*scale]]]
245 doc = self.document.getroot()
246 self.process_group(doc)
247 if self.options.ROBO == 'true':
248 self.ROBO_output()
249 if self.options.POLY == 'true':
250 self.LWPOLY_output()
251 self.dxf_add(dxf_templates.r14_footer)
253 if __name__ == '__main__':
254 e = MyEffect()
255 e.affect()
258 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 fileencoding=utf-8 textwidth=99