Fri, 03 Jun 2016 09:42:44 +0200
Implemented svg, png and hpgl compilers to pronterface
16 | 1 | """ |
2 | Lasercutter library | |
3 | 2015/2016 by NeoSoft, Malte Bayer | |
4 | Intended to use standalone or implemented in Pronterface/Printrun | |
5 | """ | |
6 | ||
7 | """ | |
8 | LASERCUT SETTINGS | |
9 | TODO: move to printrun settings | |
10 | """ | |
11 | ENGRAVE_SPEED = 40 * 60 # mm/min | |
12 | # 30mm/min works for wood (regulate the output power to something between 10-30%) | |
13 | # 30mm/min for black anodized aluminum to get a light engraving @ 100% power | |
14 | # 10mm/min for black anodized aluminum to get more "silver" @ 100% power | |
15 | ||
16 | TRAVEL_SPEED = 60 * 60 | |
17 | E_FACTOR = 0.1 | |
18 | ||
19 | # BITMAP: | |
20 | DPI = 300 | |
21 | GREY_THRESHOLD = 0 | |
22 | CHANGE_DIRECTION = True | |
23 | INVERT_CUT = True | |
24 | ||
25 | """ | |
26 | STATIC DEFINITIONS | |
27 | DO NOT CHANGE WORLD's RULES! | |
28 | """ | |
29 | INCH = 25.4 # mm | |
30 | MM_PIXEL = round(INCH / DPI, 4) | |
31 | STEPS_PIXEL = MM_PIXEL * 80 # mine is 80 steps/mm on XY | |
32 | ||
33 | # FOR HPGL: | |
34 | SCALE_FACTOR = 1.0 / 40.0 # 40 plotter units | |
35 | ||
36 | ||
37 | from PIL import Image | |
38 | import sys | |
39 | ||
40 | # Imports for SVG | |
41 | import xml.etree.ElementTree as ET | |
42 | import math | |
43 | from svg2gcode import shapes as shapes_pkg | |
44 | from svg2gcode.shapes import point_generator | |
45 | ||
46 | ||
47 | class Lasercutter: | |
48 | """ | |
49 | Lasercutter methods | |
50 | parameters: log = logger function (accepts a string) | |
51 | """ | |
52 | def __init__(self, pronterwindow = None): | |
53 | if pronterwindow: | |
54 | self.pronterwindow = pronterwindow | |
55 | self.log = pronterwindow.log | |
56 | else: | |
57 | self.pronterwindow = None | |
58 | self.log = lambda : None | |
59 | self.log("\nLasercutter library initialized resolution: %f mm per pixel" % MM_PIXEL) | |
60 | if STEPS_PIXEL <= 5: | |
61 | self.log("WARNING: STEPS PER PIXEL NEEDS TO BE > 5 (otherwise marlin joins lines): %f" % STEPS_PIXEL) | |
62 | ||
63 | ||
64 | def pixel2bit(self, pixel, threshold=128): | |
65 | """Convert the pixel value to a bit.""" | |
66 | # some really weird stuff here ;-P | |
67 | ||
68 | # RGB to greyscale | |
69 | #print pixel | |
70 | #print type(pixel) | |
71 | if isinstance(pixel, tuple): | |
72 | #rgb | |
73 | pixel = pixel[0]*0.2989 + pixel[1]*0.5870 + pixel[2]*0.1140 | |
74 | threshold = 128 | |
75 | if pixel > threshold: | |
76 | return 1 | |
77 | else: | |
78 | return 0 | |
79 | ||
80 | # color palette | |
81 | if pixel <= threshold: | |
82 | return 1 | |
83 | else: | |
84 | return 0 | |
85 | ||
86 | def image2gcode(self, filename): | |
87 | """ | |
88 | Open a image file and get the basic information about it. | |
89 | Then convert it to gcode (replacing the existing gcode buffer contents) | |
90 | """ | |
91 | try: | |
92 | im = Image.open(filename) | |
93 | except: | |
94 | self.log("Unable to open %s" % filename) | |
95 | return False | |
96 | ||
97 | self.log("Converting Image for lasercut:") | |
98 | self.log("File: %s" % filename) | |
99 | self.log("format: %s, mode: %s" % (im.format, im.mode)) | |
100 | width,height = im.size | |
101 | self.log("size: %d x %d pixels" % im.size) | |
102 | ||
103 | pix = im.load() | |
104 | ||
105 | fo = open(filename + ".g", "w") | |
106 | fo.write(""" | |
107 | ; Filename: %s | |
108 | ; GCode generated by bitplotter one-night-quick-hack script (marlin code flavour) | |
109 | ; 2015/2016 by NeoSoft - Malte Bayer | |
110 | ||
111 | G21 ; Metric | |
112 | ; We assume Z is in focus height and laser head is focus at bottom left of image! | |
113 | G92 X0 Y0 E0; set zero position - new origin | |
114 | G90 ; absolute positioning | |
115 | M82 ; Set extruder (laser) to absolute positioning | |
116 | M201 X1000 Y1000 E500 ; Set acceleration | |
117 | M203 X1000 Y1000 Z4 E10 ; Set max feedrate | |
118 | M209 S0 ; disable firmware retraction, we dont want to burn holes... | |
119 | M302 ; Allow cold extrudes - doesnt matter because we hack the extruder physically off with the M571 E mod | |
120 | M571 S1 E1 ; Activate Laser output on extrusion, but block real motor movement! | |
121 | G0 X0 Y0 F%d ; Set moving speed TRAVEL_SPEED | |
122 | G1 X0 Y0 F%d ; Set linear engraving speed ENGRAVE_SPEED | |
123 | ||
124 | """ % (filename, TRAVEL_SPEED, ENGRAVE_SPEED) ) | |
125 | self.log("Travel/Engrave speed: %d mm/sec, %d mm/sec" % ( | |
126 | TRAVEL_SPEED / 60, ENGRAVE_SPEED / 60) ) | |
127 | ||
128 | fo.write(";Start engraving the raster image: %dx%d points @ %d DPI = %.0fx%.0f mm\n\n" % ( | |
129 | im.size[0], im.size[1], DPI, im.size[0]*MM_PIXEL, im.size[1]*MM_PIXEL) ) | |
130 | ||
131 | INVERT_Y = MM_PIXEL * (im.size[1] -1) * (-1) | |
132 | DIR = 1 | |
133 | for X in range(im.size[0]): | |
134 | fo.write("; X=%d printing row: direction %i\n" % (X, DIR)) | |
135 | fo.write("G92 E0\n") | |
136 | E = 0 | |
137 | last_bit = 1 # we engrave on black pixel = 0 | |
138 | START_Y = 0 | |
139 | if DIR > 0: | |
140 | range_start = 0 | |
141 | range_stop = im.size[1] | |
142 | else: | |
143 | range_start = im.size[1] -1 | |
144 | range_stop = -1 | |
145 | ||
146 | for Y in range(range_start, range_stop, DIR): | |
147 | YMM = abs((Y * MM_PIXEL) + INVERT_Y) | |
148 | XMM = X * MM_PIXEL | |
149 | #print "X %d Y %d" % (X, Y) | |
150 | bit = self.pixel2bit(pix[X, Y], GREY_THRESHOLD) | |
151 | if INVERT_CUT: | |
152 | if bit == 0: | |
153 | bit = 1 | |
154 | else: | |
155 | bit = 0 | |
156 | if last_bit == bit: | |
157 | if bit == 1: | |
158 | # nothing to do, | |
159 | continue | |
160 | else: | |
161 | # are we at the end of Y range? | |
162 | #print Y | |
163 | if (Y == (im.size[1] - 1)) or (Y == 0): | |
164 | # draw line | |
165 | if DIR > 0: | |
166 | E = E + MM_PIXEL * (Y - START_Y) | |
167 | else: | |
168 | E = E + MM_PIXEL * (START_Y - Y) | |
169 | fo.write("G1 X%.4f Y%.4f E%.4f\n" % (XMM, YMM, E * E_FACTOR)) | |
170 | else: | |
171 | # bit value has changed! | |
172 | if bit == 0: | |
173 | # jump to start of line to write | |
174 | START_Y = Y | |
175 | fo.write("G0 X%.4f Y%.4f\n" % (XMM, YMM)) | |
176 | else: | |
177 | # end of line to write | |
178 | if DIR > 0: | |
179 | E = E + (MM_PIXEL * (Y - START_Y)) | |
180 | else: | |
181 | E = E + (MM_PIXEL * (START_Y - Y)) | |
182 | fo.write("G1 X%.4f Y%.4f E%.4f\n" % (XMM, YMM, E * E_FACTOR)) | |
183 | last_bit = bit | |
184 | if CHANGE_DIRECTION: | |
185 | DIR = DIR * (-1) # change y direction on every X | |
186 | ||
187 | fo.write("M571 S0 E0\n") | |
188 | fo.write("M501 ; undo all settings made\n") | |
189 | #fo.write("G28 X0 Y0 ; Home position\n") | |
190 | ||
191 | fo.close() | |
192 | ||
193 | if self.pronterwindow: | |
194 | self.log("") | |
195 | self.pronterwindow.load_gcode_async(filename + '.g') | |
196 | ||
197 | def hpgl2gcode(self, filename): | |
198 | OFFSET_X = 0.0 | |
199 | OFFSET_Y = 0.0 | |
200 | ||
201 | self.log("Converting HPGL plot for lasercut:") | |
202 | self.log("File: %s" % filename) | |
203 | ||
204 | fi = open(filename, "r") | |
205 | fo = open(filename + ".g", "w") | |
206 | ||
207 | ||
208 | fo.write(""" | |
209 | ; Filename: %s | |
210 | ; GCode generated by hpglplotter (marlin code flavour) | |
211 | ||
212 | G21 ; Metric | |
213 | ; We assume Z is in focus height and laser head is focus at bottom left of image! | |
214 | G92 X0 Y0 E0; set zero position - new origin | |
215 | G90 ; absolute positioning | |
216 | M82 ; Set extruder (laser) to absolute positioning | |
217 | M201 X1000 Y1000 E500 ; Set acceleration | |
218 | M203 X1000 Y1000 Z4 E10 ; Set max feedrate | |
219 | M209 S0 ; disable firmware retraction, we dont want to burn holes... | |
220 | M302 ; Allow cold extrudes - doesnt matter because we hack the extruder physically off with the M571 E mod | |
221 | M571 S1 E1 ; Activate Laser output on extrusion, but block real motor movement! | |
222 | G0 X0 Y0 F%d ; Set moving speed TRAVEL_SPEED | |
223 | G1 X0 Y0 F%d ; Set linear engraving speed ENGRAVE_SPEED | |
224 | ||
225 | """ % (filename, TRAVEL_SPEED, ENGRAVE_SPEED) ) | |
226 | ||
227 | G = "0" | |
228 | LASER_STATE = 0 | |
229 | last_coord = [0.0,0.0] | |
230 | last_cmd = "" | |
231 | ||
232 | for line in fi.readlines(): | |
233 | for action in line.split(";"): | |
234 | action = action.strip() | |
235 | if action != "": | |
236 | cmd = action[:2] | |
237 | if cmd == "PD": | |
238 | LASER_STATE = 1 | |
239 | elif cmd == "PU": | |
240 | LASER_STATE = 0 | |
241 | if last_cmd == "PD": | |
242 | OFFSET_X = coord[0] * -1 | |
243 | OFFSET_Y = coord[1] * -1 | |
244 | fo.write("; PD PU detected, set coord offset %.4f x %.4f mm\n" % (OFFSET_X, OFFSET_Y)) | |
245 | elif cmd == "PA" or cmd == "PR": | |
246 | # TODO: convert relative coordinates to absolute here! | |
247 | coord = action[2:].split(",") | |
248 | coord[0] = (float(coord[0]) + OFFSET_X) * SCALE_FACTOR | |
249 | coord[1] = (float(coord[1]) + OFFSET_Y) * SCALE_FACTOR | |
250 | if LASER_STATE: | |
251 | EN = " E%.4f F%.4f" % ( | |
252 | E_FACTOR * math.hypot(coord[0] - last_coord[0], coord[1] - last_coord[1]), | |
253 | ENGRAVE_SPEED) | |
254 | else: | |
255 | EN = " F%.4f" % TRAVEL_SPEED | |
256 | ||
257 | fo.write("G%d X%.4f Y%.4f%s\n" % ( | |
258 | LASER_STATE, coord[0], coord[1], EN) ) | |
259 | last_coord = coord | |
260 | elif cmd == "IN": | |
261 | pass | |
262 | elif cmd == "PT": | |
263 | print "Ignoring pen thickness" | |
264 | else: | |
265 | print "UNKNOWN: %s" % action | |
266 | last_cmd = cmd | |
267 | ||
268 | ||
269 | fo.write("M571 S0 E0\n") | |
270 | fo.write("M501 ; undo all settings made\n") | |
271 | #fo.write("G28 X0 Y0 ; Home position\n") | |
272 | ||
273 | fi.close() | |
274 | fo.close() | |
275 | ||
276 | if self.pronterwindow: | |
277 | self.log("") | |
278 | self.pronterwindow.load_gcode_async(filename + '.g') | |
279 | ||
280 | ||
281 | def svg2gcode(self, filename, bed_max_x = 200, bed_max_y = 200, smoothness = 0.2): | |
282 | self.log("Generating paths from SVG...") | |
283 | ||
284 | preamble = "" | |
285 | postamble = "" | |
286 | shape_preamble = "G92 E0\n" | |
287 | shape_postamble = "" | |
288 | ||
289 | """ | |
290 | Used to control the smoothness/sharpness of the curves. | |
291 | Smaller the value greater the sharpness. Make sure the | |
292 | value is greater than 0.1 | |
293 | """ | |
294 | if smoothness < 0.1: smoothness = 0.1 | |
295 | ||
296 | svg_shapes = set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) | |
297 | ||
298 | tree = ET.parse(filename) | |
299 | root = tree.getroot() | |
300 | ||
301 | width = root.get('width') | |
302 | height = root.get('height') | |
303 | if width == None or height == None: | |
304 | viewbox = root.get('viewBox') | |
305 | if viewbox: | |
306 | _, _, width, height = viewbox.split() | |
307 | ||
308 | if width == None or height == None: | |
309 | self.log("Unable to get width and height for the svg!") | |
310 | return False | |
311 | ||
312 | width = float(width.replace("px", "")) | |
313 | height = float(height.replace("px", "")) | |
314 | ||
315 | scale_x = bed_max_x / max(width, height) | |
316 | scale_y = bed_max_y / max(width, height) | |
317 | ||
318 | self.log("Scaling factor: %.2f, %.2f" % (scale_x,scale_y)) | |
319 | ||
320 | fo = open(filename + ".g", "w") | |
321 | fo.write(preamble) | |
322 | ||
323 | for elem in root.iter(): | |
324 | try: | |
325 | _, tag_suffix = elem.tag.split('}') | |
326 | except ValueError: | |
327 | continue | |
328 | ||
329 | if tag_suffix in svg_shapes: | |
330 | shape_class = getattr(shapes_pkg, tag_suffix) | |
331 | shape_obj = shape_class(elem) | |
332 | d = shape_obj.d_path() | |
333 | m = shape_obj.transformation_matrix() | |
334 | ||
335 | if d: | |
336 | fo.write("; printing shape: %s\n" % (tag_suffix)) | |
337 | E = 0 | |
338 | xo = 0 | |
339 | yo = 0 | |
340 | fo.write(shape_preamble) | |
341 | p = point_generator(d, m, smoothness) | |
342 | start = True | |
343 | for x,y,pen in p: | |
344 | y = height - y | |
345 | xs = scale_x * x | |
346 | ys = scale_y * y | |
347 | if not pen: start = True | |
348 | if xs >= 0 and xs <= bed_max_x and ys >= 0 and ys <= bed_max_y: | |
349 | if start: | |
350 | fo.write("G0 X%0.2f Y%0.2f ; Move to start of shape\n" % (xs, ys)) | |
351 | start = False | |
352 | xo = xs | |
353 | yo = ys | |
354 | else: | |
355 | e_distance = math.hypot(xs - xo, ys - yo) | |
356 | xo = xs | |
357 | yo = ys | |
358 | E = E + (MM_PIXEL * e_distance) | |
359 | fo.write("G1 X%0.2f Y%0.2f E%.4f\n" % (xs, ys, E * E_FACTOR)) | |
360 | else: | |
361 | self.log("Position outside print dimension: %d, %d" % (xs, ys)) | |
362 | fo.write(shape_postamble) | |
363 | ||
364 | fo.write(postamble) | |
365 | fo.close() | |
366 | ||
367 | if self.pronterwindow: | |
368 | self.log("") | |
369 | self.pronterwindow.load_gcode_async(filename + '.g') | |
370 |