Sat, 07 Nov 2015 20:50:55 +0100
finished refactoring
4 | 1 | #!/usr/bin/env python |
5 | 2 | # -*- coding: utf-8 -*- |
3 | ||
10 | 4 | import svg, sys, math |
4 | 5 | from gcode import Gcode |
6 | from optparse import OptionParser | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
7 | from tinycss import CSS21Parser |
4 | 8 | |
8 | 9 | from shapely.geometry import box, MultiLineString, Polygon |
5 | 10 | from shapely.affinity import rotate |
11 | from shapely import speedups | |
12 | from math import sqrt | |
13 | ||
14 | # enable Shapely speedups, if possible | |
15 | if speedups.available: | |
16 | speedups.enable() | |
17 | ||
18 | def hatchbox(rect, angle, spacing): | |
19 | """ | |
20 | returns a Shapely geometry (MULTILINESTRING, or more rarely, | |
21 | GEOMETRYCOLLECTION) for a simple hatched rectangle. | |
22 | ||
23 | args: | |
24 | rect - a Shapely geometry for the outer boundary of the hatch | |
25 | Likely most useful if it really is a rectangle | |
26 | ||
27 | angle - angle of hatch lines, conventional anticlockwise -ve | |
28 | ||
29 | spacing - spacing between hatch lines | |
30 | ||
31 | GEOMETRYCOLLECTION case occurs when a hatch line intersects with | |
32 | the corner of the clipping rectangle, which produces a point | |
33 | along with the usual lines. | |
34 | """ | |
35 | ||
36 | (llx, lly, urx, ury) = rect.bounds | |
37 | centre_x = (urx + llx) / 2 | |
38 | centre_y = (ury + lly) / 2 | |
39 | diagonal_length = sqrt((urx - llx) ** 2 + (ury - lly) ** 2) | |
40 | number_of_lines = 2 + int(diagonal_length / spacing) | |
41 | hatch_length = spacing * (number_of_lines - 1) | |
42 | ||
43 | # build a square (of side hatch_length) horizontal lines | |
44 | # centred on centroid of the bounding box, 'spacing' units apart | |
45 | coords = [] | |
46 | for i in range(number_of_lines): | |
47 | # alternate lines l2r and r2l to keep HP-7470A plotter happy ☺ | |
48 | if i % 2: | |
8 | 49 | coords.extend([(( |
50 | centre_x - hatch_length / 2, \ | |
51 | centre_y - hatch_length / 2 + i * spacing), ( | |
52 | centre_x + hatch_length / 2, \ | |
53 | centre_y - hatch_length / 2 + i * spacing))]) | |
5 | 54 | else: |
8 | 55 | coords.extend([(( \ |
56 | centre_x + hatch_length / 2, \ | |
57 | centre_y - hatch_length / 2 + i * spacing), ( | |
58 | centre_x - hatch_length / 2, \ | |
59 | centre_y - hatch_length / 2 + i * spacing))]) | |
5 | 60 | # turn array into Shapely object |
61 | lines = MultiLineString(coords) | |
62 | # Rotate by angle around box centre | |
63 | lines = rotate(lines, angle, origin='centroid', use_radians=False) | |
64 | # return clipped array | |
65 | return rect.intersection(lines) | |
66 | ||
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
67 | def parse_style(stylestr): |
10 | 68 | """ |
69 | Parse the given string containing CSS2.1 syntax | |
70 | Returns a dict with the keys/values | |
71 | """ | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
72 | if stylestr.strip() == '': |
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
73 | return None |
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
74 | parser = CSS21Parser() |
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
75 | style = parser.parse_style_attr(stylestr) |
10 | 76 | data = {} |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
77 | for obj in style[0]: |
10 | 78 | data[obj.name] = obj.value[0].value |
79 | return data | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
80 | |
9 | 81 | class Image(object): |
10 | 82 | """ |
83 | SVG Image handler class | |
84 | """ | |
9 | 85 | def __init__(self, filename, options, gcoder): |
86 | self.gcoder = gcoder | |
87 | self.options = options | |
88 | self.svg = svg.parse(filename) | |
89 | self.bb1, self.bb2 = self.svg.bbox() | |
90 | self.width, self.height = self.bb2.coord() | |
91 | self.infill = None | |
8 | 92 | |
9 | 93 | self._check_dimensions() |
94 | self._generate_infill() | |
95 | ||
96 | def _check_dimensions(self): | |
10 | 97 | """ |
98 | Output image dimensions/scaling to console and gcode | |
99 | """ | |
9 | 100 | msg = "Original dimension: %.2f x %.2f" % (self.width, self.height) |
101 | print msg | |
102 | self.gcoder.comment(msg) | |
10 | 103 | self.gcoder.comment("Scale: %.2f" % (self.options.scale)) |
9 | 104 | width = self.width * self.gcoder.mm_pixel * self.options.scale |
105 | height = self.height * self.gcoder.mm_pixel * self.options.scale | |
106 | msg = "Print dimension: %.2fmm x %.2fmm" % (width, height) | |
107 | print msg | |
108 | self.gcoder.comment(msg) | |
8 | 109 | |
9 | 110 | def _generate_infill(self): |
10 | 111 | """ |
112 | Generates infill pattern image for later use | |
113 | """ | |
9 | 114 | b1x, b1y = self.bb1.coord() |
115 | b2x, b2y = self.bb2.coord() | |
116 | page = box(b1x, b1y, b2x, b2y) | |
117 | # TODO: Infill spacing needs to be calculated with proper scaling and gcode MM dimensions | |
118 | # TODO: Make infill angle 0, 45 or 90 degrees configurable to options parser (0° = X, 90° = Y, 45° = X and Y but half the speed/accel needed!) | |
119 | self.infill = hatchbox(page, 0, 2) | |
4 | 120 | |
9 | 121 | def normalize(self, coord): |
10 | 122 | """ |
123 | Normalize X / Y Axis of coordinates | |
124 | At the moment only Y gets flipped to match Reprap coordinate system (0,0 is bottom left instead top left on SVG) | |
125 | """ | |
9 | 126 | c_x = coord[0] |
127 | c_y = coord[1] | |
128 | # flip y | |
129 | c_y = (self.height - c_y) | |
130 | return (c_x, c_y) | |
4 | 131 | |
9 | 132 | def get_drawings(self): |
133 | """ | |
134 | Returns a list of all svg drawings with segments attribute | |
135 | """ | |
136 | data = [] | |
137 | for dwg in self.svg.flatten(): | |
138 | if hasattr(dwg, "segments"): | |
139 | data.append(dwg) | |
140 | return data | |
141 | ||
142 | def svg2gcode(options, gcoder): | |
143 | image = Image(options.filename, options, gcoder) | |
8 | 144 | |
9 | 145 | for dwg in image.get_drawings(): |
146 | for l in dwg.segments(1): | |
147 | # THE OUTLINE | |
148 | coord = image.normalize(l[0].coord()) | |
149 | gcoder.move(coord[0], coord[1]) | |
150 | for pt in l[1:]: | |
151 | coord = image.normalize(pt.coord()) | |
152 | gcoder.engrave(coord[0], coord[1]) | |
8 | 153 | |
9 | 154 | if options.outline: |
155 | continue | |
156 | ||
157 | if isinstance(dwg, svg.Polygon) or isinstance(dwg, svg.Path): | |
158 | #check if we should infill? | |
159 | style = parse_style(dwg.style) | |
160 | if not style: | |
161 | continue | |
162 | if not 'fill' in style.keys(): | |
163 | continue | |
164 | if style['fill'] == 'none': | |
165 | continue | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
166 | |
9 | 167 | # try to generate the infill poly complex |
168 | poly = None | |
169 | for l in dwg.segments(1): | |
170 | segments = [] | |
171 | for pnt in l: | |
172 | segments.append(pnt.coord()) | |
173 | shape = Polygon(segments) | |
174 | if shape.is_valid: | |
175 | if not poly: | |
176 | poly = shape | |
177 | else: | |
178 | if shape.within(poly): | |
179 | poly = poly.difference(shape) | |
8 | 180 | else: |
9 | 181 | poly = poly.union(shape) |
8 | 182 | |
9 | 183 | lines = poly.intersection(image.infill) |
184 | if lines: | |
185 | # THE INFILL | |
10 | 186 | prev_end = None |
9 | 187 | for line in lines: |
10 | 188 | coords = [ |
189 | image.normalize((line.coords[0][0], line.coords[0][1])), | |
190 | image.normalize((line.coords[1][0], line.coords[1][1])) | |
191 | ] | |
192 | if prev_end: | |
193 | # calculate distances to previous end, swap if current end is nearest | |
194 | dist = [ | |
195 | abs(math.hypot(coords[0][0] - prev_end[0], coords[0][1] - prev_end[1])), | |
196 | abs(math.hypot(coords[1][0] - prev_end[0], coords[1][1] - prev_end[1])) | |
197 | ] | |
198 | if dist[0] > dist[1]: | |
199 | coords = list(reversed(coords)) | |
200 | prev_end = coords[1] | |
201 | gcoder.move(coords[0][0], coords[0][1]) | |
202 | gcoder.engrave(coords[1][0], coords[1][1]) | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
203 | |
9 | 204 | def init_options(): |
8 | 205 | parser = OptionParser() |
206 | parser.add_option("-f", "--file", dest="filename", default=None, | |
207 | help="Load SVG file", metavar="FILE") | |
208 | parser.add_option("-s", "--scale", | |
209 | dest="scale", type="float", default=1.0, | |
210 | help="set scale factor (default 1.0)") | |
211 | parser.add_option("-e", "", | |
212 | dest="engrave_speed", type="float", default=20, | |
213 | help="engrave speed mm/sec (default 20)") | |
214 | parser.add_option("-t", "", | |
215 | dest="travel_speed", type="float", default=130, | |
216 | help="travel speed mm/sec (default 130)") | |
217 | parser.add_option("-o", "--outline", action="store_true", | |
218 | dest="outline", default=False, | |
219 | help="no infill, only outlines") | |
9 | 220 | return parser.parse_args() |
7 | 221 | |
9 | 222 | if __name__ == "__main__": |
223 | (OPTIONS, ARGS) = init_options() | |
224 | if not OPTIONS.filename: | |
8 | 225 | print "no filename given!" |
226 | sys.exit(1) | |
5 | 227 | |
8 | 228 | # initialize gcode worker |
9 | 229 | GCODER = Gcode(scale=OPTIONS.scale, travel_speed=OPTIONS.travel_speed, engrave_speed=OPTIONS.engrave_speed) |
8 | 230 | |
231 | # processing | |
9 | 232 | svg2gcode(OPTIONS, GCODER) |
8 | 233 | |
234 | # write gcode file | |
9 | 235 | GCODER.write(OPTIONS.filename + ".g") |