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