-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaser.py
474 lines (376 loc) · 16.4 KB
/
laser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import time
import math
import os, sys
import screeninfo
import numpy as np
from svgByStyle import svgStyleGroupedPaths, mapToSVG
from pathlib import Path as Pith
import svg as ssvg
import svgPanel
import svgelements
import wx
from svgByStyle import uint32_to_color
import wx.adv
import svgpathtools
from svgpathtools import Document, Path, Line, svg2paths, svg2paths2
import drawsvg
rebuiltDoc = drawsvg.Drawing(1000, 1000, origin='center', displayInline=False)
#import matplotlib.path as mpltPath
def notify(msg):
n = wx.adv.NotificationMessage()
n.SetMessage(msg)
n.Show( timeout = 4000 )
class Point:
__slots__ = 'x', 'y'
def __init__(self, x, y):
self.x = x
self.y = y
class geeCode:
__slots__ = 'position','rate','power','x','y','z','dx','dy','dz','laser_state'
def __init__(self):
self.laser_state = False
self.rate = 1000 #
p=0.0
self.x,self.y,self.z=(p,p,p)
self.dx,self.dy,self.dz=(False,False,False)
#codes = ['G90'] ''Sharp Corners, contra to the shape of 9
return
def updatepos(self,point):
(x,y,z)=point.real,point.imag,0
self.dx=not(self.x==x)
self.dy=not(self.y==y)
self.dz=not(self.z==z)
self.x,self.y,self.z = x,y,z
return (x,y,z)
def gxyz(self,point):
(x,y,z)=point.real,point.imag,0
code = ""
if self.dx:
code = f"X{x}"
if self.dy:
code = f"{code} Y{y}"
return code
def set_laser(self,power):
power = max(min(float(power),1000),0)
self.laser_state = power>0
return [f"S{power}"]
def linear_feed(self, point, rate):
code = f"G01 {self.gxyz(point)}"
if not rate == self.rate:
code = f"{code} F{rate}"
self.rate = rate
(x,y,z)=self.updatepos(point)
return [code]
def linear(self, point):
code = f"G00 {self.gxyz(point)}"
(x,y,z)=self.updatepos(point)
return [code]
class powerPanel(wx.Panel):
defaults = {'rate':300, 'power': 1000 }
def __init__(self, parent, pos=(0,0), levels=[]):
super(powerPanel, self).__init__(parent, size=(400, 600), pos=pos)
self.levels = {}
self.powerLevels = levels
sizer = wx.BoxSizer(wx.VERTICAL)
if len(self.powerLevels) < 1:
return
power=1000/len(self.powerLevels)
pow = power
row = 0
wx.StaticText(self,label="Rate",pos=(10,10))
wx.StaticText(self,label="Power",pos=(200,10))
default_rate = self.defaults['rate']
for key in self.powerLevels:
row=row+1
colorfromkey = uint32_to_color(key)
# label = wx.StaticText(self, label=f"{colorfromkey}:")
# label.SetForegroundColour( colorfromkey )
# hbox.Add(label, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5)
text_power = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER,size=(40,40),pos=(10,row*40))
slider_power = wx.Slider(self, minValue=0, maxValue=1000,size=(60,40),pos=(50,row*40) ,style=wx.SL_HORIZONTAL, value=int(power))
text_rate = wx.TextCtrl(self,value = f"{self.defaults['rate']}",size=(40,40),pos=(110,40*row))
slider_rate = wx.Slider(self, minValue=0, maxValue=1000,size=(60,40),pos=(150,row*40),style=wx.SL_HORIZONTAL, value=int(default_rate))
text_power.SetValue(f"{power}")
text_power.SetForegroundColour(colorfromkey)
text_rate.SetForegroundColour(colorfromkey)
text_power.Bind(wx.EVT_TEXT, lambda event, k=key: self.on_power_text(event, k))
slider_power.Bind(wx.EVT_SLIDER, lambda event, k=key: self.on_power_slider(event, k))
text_rate.Bind(wx.EVT_TEXT, lambda event, k=key: self.on_rate_text(event, k))
slider_rate.Bind(wx.EVT_SLIDER, lambda event, k=key: self.on_rate_slider(event, k))
self.levels[key] = (text_rate, slider_rate, text_power, slider_power)
#sizer.Add(text_power)
#sizer.Add(text_rate)
#btn = wx.Button(self,label="Generate GCODE",pos=(0,400))
#btn.EvendtHandler(gcodeify)
def gcodeify(self,event):
gc = geeCode()
return
def on_power_text(self, event, key):
rate, rate_slider, power, power_slider = self.levels[key]
try:
value = int(power.GetValue())
value = max(0, min(1000, value))
power_slider.SetValue(value)
except ValueError:
pass
def on_rate_text(self, event, key):
rate, rate_slider, power, power_slider = self.levels[key]
try:
value = int(rate.GetValue())
value = max(0, min(1000, value))
rate_slider.SetValue(value)
except ValueError:
pass
def on_rate_slider(self, event, key):
rate, rate_slider, power, power_slider = self.levels[key]
value = rate_slider.GetValue()
rate.SetValue(str(value))
def on_power_slider(self, event, key):
rate, rate_slider, power, power_slider = self.levels[key]
value = power_slider.GetValue()
power.SetValue(str(value))
class appFrame(wx.Frame):
__slots__ = ['app','svgViewer','powerPanel','GcodeVec']
def __init__(self, parent, id = -1, title = "laSer"):
scr = screeninfo.get_monitors()[0]
screenSize = ( int(scr.width), int(scr.height) )
super(appFrame, self).__init__( parent, id= id, title = title, size = screenSize)
mainPanel = wx.Panel(self,size=(800,32),pos=(10,0))
if len(sys.argv)>1:
filename = sys.argv[1]
self.initSvg(filename)
self.initSvg("drawing.svg")
b1=wx.Button(mainPanel,pos=(0,0),size=(100,30),label="Generate")
b2=wx.Button(mainPanel,pos=(100,0),size=(100,30),label="Connect")
self.pointDensity = wx.TextCtrl(mainPanel,pos = (200,0), value="1" )
b1.Bind(wx.EVT_BUTTON, self.generateGCODE)
sizer=wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(b2)
sizer.Add(b1)
menu = wx.Menu()
menu.Append(101,"Open File")
menu.Append(102,"Save GCode")
menu.Append(103,"Preferences")
menu.Append(104,"Exit")
menuBar = wx.MenuBar()
menuBar.Append(menu,"File")
self.Bind(wx.EVT_MENU, self.menuhandler)
self.SetMenuBar(menuBar)
self.Show()
def sort_paths_radially(self, paths):
# Calculate centroids and distances for each path
path_info = []
for path in paths:
# Calculate centroid using path's bounds
bounds = path.bbox()
if bounds:
centroid = complex((bounds[0] + bounds[2])/2, (bounds[1] + bounds[3])/2)
# Calculate distance from origin
distance = abs(centroid)
path_info.append((distance, path))
# Sort paths by distance from origin
sorted_paths = [p for _, p in sorted(path_info, key=lambda x: x[0])]
return sorted_paths
# def sort_paths_radially(self,paths):
# # Calculate centroids for each path
# centroids = []
# print( len(paths),' paths to sort' )
# for path in paths:
# x_sum = sum(point.real for point in path)
# y_sum = sum(point.imag for point in path)
# centroid = complex(x_sum/len(path), y_sum/len(path))
# centroids.append((centroid, path))
# print( len(centroids),' centroids' )
# # Sort paths based on distance from origin to centroid
# sorted_paths = [path for _, path in sorted(centroids, key=lambda x: abs(x[0]))]
# return sorted_paths
def initSvg(self,svgFile):
(svgDoc,svgGroups) = svgStyleGroupedPaths(svgFile)
self.svgGroups = svgGroups #required to load the power panel
self.powerPanel = powerPanel(parent = self,pos=(820,50),levels=svgGroups.keys())
self.powerPanel.Show()
containedPaths, containerPaths = {},{}
svgGrpFile = ".tmp.grp.svg"
svgDoc.save(svgGrpFile)
self.groupedPaths, self.groupedProp, self.groupedAttr = svg2paths2(svgGrpFile, return_svg_attributes = True)
rebuiltDoc = Document()
svg_paths = self.groupedPaths
svg_paths = self.sort_paths_radially(svg_paths)
# Build proximity index
path_distances = []
density = 1
for i, path1 in enumerate(svg_paths):
# Get centroid of path1
point_range = int(path1.length() * density)
path1_points = []
for r in range(1,point_range):
point = path1.point(1/r)
path1_points.append(point)
# Get centroid of path2
x1_sum = sum(point.real for point in path1_points)
y1_sum = sum(point.imag for point in path1_points)
centroid1 = complex(x1_sum/len(path1), y1_sum/len(path1))
# Calculate distances to all other paths
distances = []
path2_points = []
for r in range(1, point_range):
point = path1.point(1/r)
path2_points.append(point)
for j, path2 in enumerate(svg_paths):
if i != j:
x2_sum = sum(point.real for point in path2_points)
y2_sum = sum(point.imag for point in path2_points)
centroid2 = complex(x2_sum/len(path2), y2_sum/len(path2))
distance = abs(centroid2 - centroid1)
distances.append((j, distance))
# Sort paths by proximity to current path
sorted_distances = sorted(distances, key=lambda x: x[1])
path_distances.append((i, sorted_distances))
svg = svgelements.SVG()
# Add paths to document with colors based on proximity
for i, path_info in enumerate(path_distances):
svg_path = svg_paths[path_info[0]]
print(path_info)
# Use color gradient based on proximity index
hue = (i / len(svg_paths)) * 360
color = f"hsl({hue}, 100%, 50%)"
# dwg.append( drawsvg.Path( path, fill="none", stroke="red", stroke_width="hairline") )
#rebuiltDoc.add_path(Path(*path, style=f'fill:none;stroke:{color};stroke-width:hairline;', stroke='hairline', stroke_color=color, fill='none'))
path = svgelements.Path(svg_path.d(),fill='none',stroke = color,stroke_width="hairline")
svg.append(path)
svgDocFile = ".tmp.display.svg"
svg.write_xml(svgDocFile)
# print(svg.string_xml())
self.svgframe = svgPanel.svg()(parent=self,svg_file=svgDocFile,pos=(10,50))
cut = True
pointDensity = 1
points = []
def generateGCODE(self,svgDoc=None):
return
pointDensity = 1
points = [None]
paths,props,attrs = svg2paths2('.tmp.rebuilt.svg', return_svg_attributes=True)
gv = geeCode()
motion_attr = []
linear, linear_feed = [], []
place = (None,None)
for key,path in enumerate(paths):
group = props[key].get('group')
rate = self.powerPanel.levels[group][0].GetValue()
power = self.powerPanel.levels[group][2].GetValue()
for segment in path:
#print(path)
num_points = max(2, int(segment.length()) * pointDensity ) # Adjust the divisor to control point density
for t in np.linspace(0, 1, num_points):
point = segment.point(t)
points.append(point)
points.append(None)
laser_on = False
codes = []
useg01 = False
def routeCodes(codes):
for code in codes:
print(code)
for point in points:
#print(point)
if point is None:
if laser_on:
codes=gv.set_laser(0)
laser_on = False
useg01 = False
routeCodes(codes)
continue
if useg01:
if not laser_on:
codes=gv.set_laser(power)
laser_on = True
else:
codes = []
codes.extend(gv.linear_feed(point,rate))
routeCodes(codes)
else:
codes = gv.linear(point)
routeCodes(codes)
useg01 = True
def mapToPathPoints(self,map,key = None, pointDensity = 1):
"""
Converts a dictionary of SVG path data into a list of (x, y) coordinate points.
Args:
map (dict): A dictionary where the keys are group names and the values are lists of SVG path data.
key (str, optional): The key in the `map` dictionary to extract path data from. If `None`, the function will recursively process all keys in the dictionary.
Returns:
list: A list of (x, y) coordinate tuples representing the points along the SVG paths.
"""
points = []
if key is None:
for key in map.keys():
points.extend(self.mapToPathPoints(map,key))
return points
doc = Document()
group = doc.add_group({'name':f"group_{key}"})
paths = []
for path in map[key]:
doc.add_path(path['path'],{'style':path['attr'].get('style')},group)
paths.append(path['path'])
points = {}
path_points = []
npath = 0
for path in paths:
npath = npath + 1
points[npath]=[]
for segment in path:
num_points = max(2, int(segment.length()) * pointDensity ) # Adjust the divisor to control point density
for t in np.linspace(0, 1, num_points):
point = segment.point(t)
points[npath].append( (point.real, point.imag) )
#self.svgframe.lines.append((point.real, point.imag))
return points
def menuhandler(self,event):
id = event.GetId()
if id == 101:
with wx.FileDialog(self,"Open" ,style=wx.FD_OPEN) as fd:
fd.ShowModal()
path = fd.GetPath()
if path:
p = Pith(path)
if not p.is_file():
notify(f"{path} file non-existant")
return
os.execl(sys.executable,'python','laser.py ', f"{path}")
return
def remove_duplicate_paths(self,paths, tolerance=1e-6):
"""
Remove duplicate SVG paths from a list of paths.
Args:
paths (list): List of SVG paths
tolerance (float): Tolerance for comparing path coordinates
Returns:
list: List of unique paths
"""
unique_paths = []
seen_paths = set()
for path in paths:
# Convert path to a hashable representation
path_points = []
for segment in path:
# Sample points along segment to compare
num_points = max(2, int(segment.length() * 10))
for t in np.linspace(0, 1, num_points):
point = segment.point(t)
# Round coordinates to handle floating point comparison
x = round(point.real / tolerance) * tolerance
y = round(point.imag / tolerance) * tolerance
path_points.append((x, y))
# Convert points to tuple for hashing
path_key = tuple(path_points)
if path_key not in seen_paths:
seen_paths.add(path_key)
unique_paths.append(path)
return unique_paths
class laserApp(wx.App):
def OnInit(self):
frm = appFrame(None)
return True
if __name__ == '__main__':
ape = laserApp()
ape.MainLoop()