-
Notifications
You must be signed in to change notification settings - Fork 1
/
layerparser.py
372 lines (267 loc) · 9.46 KB
/
layerparser.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
import rhinoscriptsyntax as rs
import Rhino
import scriptcontext as sc
import math
import time
import re
# V0.1
# to install as command (alias) or keyboard shortcut, use line below and change to your script file path
# '_-runPythonScript "/Users/timcastelijn/Documents/programming/rhinoscript/checkAndExport.py"
# '_-runPythonScript "E:/checkAndExport.py"
# function to reverse a curve if the normal points downwards in Z-dir
# assumed is that only closed curves can have inside or outside
def setCurveDir(objs):
count = 0
for obj in objs:
# if rs.IsCurve(obj) and rs.IsCurvePlanar(obj):
if rs.IsCurve(obj):
normal = rs.CurveNormal(obj)
if normal and normal[2] < 0:
count += 1
rs.ReverseCurve(obj)
# print "Curve {} flipped {}{}".format(obj, normal, normal2)
print "reversed " + str(count) + " curves"
# rs.SelectObjects(objs)
# rs.Command("Dir")
def isCurveOnCPlane(obj):
data = rs.CurvePoints(obj)
for pt in data:
if(math.fabs( pt.Z )> 1e-6 ):
return False
return True
def isPointOnCplane(obj):
return (math.fabs( rs.PointCoordinates(obj)[2] ) < 1e-6)
def appendLayer(layers, obj):
layer = rs.ObjectLayer(obj)
try:
layers.index(layer)
pass
except Exception as e:
layers.append( rs.ObjectLayer(obj) )
def checkCurvePosition(objs):
layers = []
selection = []
delete_objs = []
for i, obj in enumerate(objs):
if rs.IsCurve(obj):
if not isCurveOnCPlane(obj):
# print "Curve {} not on Cplane".format(obj)
selection.append(obj)
appendLayer(layers, obj)
else:
# must be point rs.IsPoint(obj):
if not isPointOnCplane(obj):
# print "Curve {} not on Cplane".format(obj)
# rs.SelectObject(obj)
selection.append(obj)
appendLayer(layers, obj)
if len(selection) > 0:
rs.SelectObjects(selection)
rs.EnableRedraw(True)
rs.EnableRedraw(False)
# when an object is found on > 0 layers, prompt for proceed
if len(layers) > 0:
msg = "there were non-planar or elevated curves found on layers:\n"
for layer in layers:
msg = msg + "- " + layer + " \n"
msg = msg + '\n Do you want to proceed?'
if rs.MessageBox(msg, 1) != 1:
# do not proceed with export
return False
# else
return True
def moveToOrigin(objs):
#get left bottom
rs.EnableRedraw(True)
selection_base = rs.GetPoint("Pick export base point")
rs.EnableRedraw(False)
#box = rs.BoundingBox(objs)
if selection_base:
#selection_base = [box[0].X, box[0].Y, box[0].Z]
vector = rs.VectorSubtract( selection_base, [0,0,0])
objs = rs.MoveObjects(objs, rs.VectorReverse(vector))
return True
else:
return False
# explode text objects into curves
def explodeTextObjects(objs):
new_list = []
for obj in objs:
if rs.IsText(obj):
# rs.GetBoolean(text, "get", True)
# result = rs.TextObjectFont(obj, "MecSoft_Font-1")
polylines = rs.ExplodeText(obj, True)
for polyline in polylines:
new_list.append(polyline)
else:
new_list.append(obj)
return new_list
# recurcive explode of blocks
def explodeBlock(objects):
def explode(objs, li):
for obj in objs:
if rs.IsBlockInstance(obj):
temp_objs = rs.ExplodeBlockInstance(obj)
explode(temp_objs, li)
else:
li.append(obj)
return li
#create empty list
li = []
#redeclare objects list with content of exploded blocks
return explode(objects, li)
def filterObjects(objs):
new_list = []
for obj in objs:
if rs.IsCurve(obj) or rs.IsPoint(obj):
new_list.append(obj)
else:
# remove from obj list
rs.DeleteObject(obj)
return new_list
def simplify(objs):
for obj in objs:
if rs.IsCurve(obj):
rs.SimplifyCurve(obj)
def createBiesseLayer(m):
tool_table = importTools("tool_table.txt")
if not tool_table:
print 'tool table invalid, abort'
return False
tool_id = m.group(1)
operation = m.group(2)
z_pos = m.group(3)
str = 'TCH'
if operation=="Drill":
str += '[BG]'
elif operation=="Saw-X" or operation=="Saw-Y":
str += '[CUT_G]'
else:
str += '[ROUT]'
# workpiece side parameter, 0 by default
str += '(SIDE)0'
# side of curve parameter CRC
# 0=center, 1=left, 2 = right, curve direction is always CCW so inside is left
str += '(CRC)'
str += {
'Pocket': "1",
'Inner contour': "1",
'Outer contour': "2",
'Engrave': "0",
'Drill': "0",
'Saw-X': "0",
'Saw-Y': "0",
}[operation]
# if operation == 'Pocket':
# parameters['method'] = 'remove_all'
# depth parameter
depth = re.search( 'd(\d+\.?\d*)', z_pos)
if depth:
# workpiece top -depth, set parameter "TH" to workpiece height and use z_pos as depth
if not workpiece_thickness:
workpiece_thickness = rs.GetReal('Please ener the workpiece thickness (TH), to create depth operation')
if workpiece_thickness:
str += '(DP)' + depth.group(1)
str += '(TH)' + workpiece_thickness
else:
print 'abort'
return False
else:
# workpiece bottom +depth, parameter "TH" is 0 by default and use z_pos as depth from bottom
str += '(DP)-' + z_pos
# tool name paramter
if tool_table[tool_id] and tool_table[tool_id]["TNM"]:
str += '(TNM)$%s$' % tool_table[tool_id]["TNM"]
else:
msg += 'tool_id %s not in tool table file or TNM not formatted correctly' % tool_id
# diameter parameter
# todo: is this required??
if tool_table[tool_id]["DIA"] and tool_table[tool_id]["DIA"]:
str += '(DIA)' + tool_table[tool_id]["DIA"]
else:
msg += 'tool_id %s not in tool table file or DIA not formatted correctly' % tool_id
return str
def convertLayers( objs ):
# first find relevant layers
layers = []
for obj in objs:
layer_name = rs.ObjectLayer(obj)
if layer_name not in layers:
layers.append(layer_name)
# get all layers
workpiece_thickness = None
invalid_lines = ''
for layer in layers:
# todo's
# - add drill
# - add saw blade
m = re.search( '(\d\d.\d\d)\s'+
'.+(Pocket|Engrave|Inner contour|Outer contour|Drill|Saw-X|Saw-Y).+'+
# '-\s(.*)\s\S*'+
'((?<=\s\+)\d+\.?\d*|(?<=\s)d\d+\.?\d*)'
, layer)
if m and len(m.groups()) == 3:
biesselayer = rs.AddLayer( createBiesseLayer(m) )
for obj in objs:
if rs.ObjectLayer(obj) == layer:
rs.ObjectLayer(obj, biesselayer)
else:
invalid_lines += '- ' + layer + '\n'
if len(invalid_lines)>0:
rs.MessageBox('layers have incorrect format and will not be exported:\n' + invalid_lines + '')
return False
def importTools(filename):
tool_table={}
invalid_lines =''
with open(filename) as fp:
# read header
line = fp.readline()
# read first line
line = fp.readline()
cnt = 1
while line:
# print line
m = re.search( '(\d\d.\d\d)\t'+
'(.+)\t'+
'(.+)'
, line)
if m and len(m.groups())>=3:
tool_table[m.group(1)] = {"TNM":m.group(2), "DIA":m.group(3)}
else:
invalid_lines += line +'\n'
line = fp.readline()
cnt += 1
if len(invalid_lines)>0:
rs.MessageBox('lines could not be read, please check the tool table file:\n' + invalid_lines + '')
return False
return tool_table
# main script
def main():
# open the file
# filename = rs.OpenFileName()
# if filename:
# with open(filename) as f:
# lines = f.readlines()
# copies = []
objs = rs.GetObjects("select objects to export", 0, True, True)
if not objs: print "checkAndExport aborted"; return
convertLayers( objs)
print 'done'
print "\n"
# copies = explodeBlock(copies)
# copies = explodeTextObjects(copies)
# copies = filterObjects(copies)
# proceed = checkCurvePosition(copies);
# if proceed:
# simplify(copies)
# setCurveDir(copies);
# result = moveToOrigin(copies);
# if result:
# rs.SelectObjects(copies)
# result = rs.Command("Export")
# if result: print 'exported succesfully'
# return True
# rs.DeleteObjects(copies)
# rs.EnableRedraw(True)
if __name__ == "__main__":
main();