-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGCodeReader.py
388 lines (268 loc) · 14.7 KB
/
GCodeReader.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
from ast import Param
import bpy
import sys
import math
import re
from numpy import number, var
moduleParentName = '.'.join(__name__.split('.')[:-1])
createProfile = sys.modules[moduleParentName + '.BevelShapeCreator'].createProfile
NoZPosMatch = sys.modules[moduleParentName + '.Exceptions'].NoZPosMatch
NoHeightMatch = sys.modules[moduleParentName + '.Exceptions'].NoHeightMatch
NoSuchPropertyException = sys.modules[moduleParentName + '.Exceptions'].NoSuchPropertyException
createEndPoints = sys.modules[moduleParentName + '.EndPointCreator'].createEndPoints
ImproperCruveException = sys.modules[moduleParentName + '.Exceptions'].ImproperCruveException
ParamNames = sys.modules[moduleParentName + '.Constants'].ParamNames
Coin = sys.modules[moduleParentName + '.Constants'].BiasedCoin
Keywords = sys.modules[moduleParentName + '.Constants'].Keywords
class Layer: #Class that stores information about the layer. Needs to change because there are different widths in the same layer as well
def __init__(self, zPos, height, layerNumber, gcodes) -> None:
self.zPos = zPos
self.layerNumber = layerNumber
self.height = height
self.gcodes = gcodes
def __str__(self) -> str:
return "zPos:{0} | height:{1} | {2}".format(self.zPos, self.height, self.gcodes)
#Reads the GCode Files, extracts only the G1 and G0 moves. Sorry no support for circular moves so far.
def gcodeParser(gcodeFilePath, params):
print(__file__)
file = open(gcodeFilePath, 'r')
lines = file.readlines()
numberOfLines = len(lines)
linesIterator = iter(lines)
listOfParsedLayers = []
gcodePattern = re.compile("(\s*G[01](?:\s+[XYZEF](?:[-+]?(?:\d*\.\d+|\d+)))+\s*)(?:;(.*))?$") #Pattern that matches G0 or G1 commands. To be noted, I don't see any G0 commansd in Prusa Slicer.
nonMovingGcodePattern = re.compile("\s*G[01](\s+[EF](?:[-+]?(?:\d*\.\d+|\d+)))+\s*$") #Matches the G0 or G1 commands that have no X,Y or Z components, thereby are not travel moves.
layerChangePattern = re.compile("\s*;LAYER_CHANGE\s*") #Detecting Layer change, I think this makes things incompatible with vase mode.
widthPattern = re.compile("\s*;WIDTH:([0-9]+(?:\.[0-9]+)?)\s*$") #Detecting a change in the width of print line
zPosPattern = re.compile("\s*;Z:([0-9]+(?:\.[0-9]+)?)\s*$")
heightPattern = re.compile("\s*;HEIGHT:([0-9]+(?:\.[0-9]+)?)\s*$")
typePattern = re.compile("\s*;TYPE:(.*)$")
firstPointPattern = re.compile("move to first")
prevLayerGcodes = [] #All GCodes that move the nozzle, with our without extrusion would be stored here and then popped when the next later starts
prevLayerZPos = 0 #Prusa Slicer Prints the Z position and layer height after each layer change
prevLayerHeight = 0
curLineNumber = 0 #For error tracing
curLayerNumber = 0
valueTacker = {'X':0, 'Y':0, 'Z':0, 'E':0, 'W':0.5, 'H':0.2, 'layerNumber':0, 'type':'Custom'} #E is extrusion; X, Y and Z are the coordinates; W is width of the print line
whPrecision = params[ParamNames.whPrecision]
precision = params[ParamNames.precision]
while True:
try:
line = next(linesIterator)
except StopIteration:
line = "!__end__!"
curLineNumber = curLineNumber + 1
if bool(gcodePattern.match(line)):
gcodePart = gcodePattern.search(line)[1].strip()
"""commentPart = "" ##Only needed if there is a need to process comments later
try:
commentPart = gcodePattern.search(line)[2].strip()
except (IndexError, AttributeError):
pass"""
separatedGcode = gcodePart.split()
tempDict = valueTacker.copy()
#Ignore any GCode G0/G1 command that doesn't move the extruder
if not bool(nonMovingGcodePattern.match(gcodePart)):
for term in separatedGcode:
tempDict[term[0]] = float(term[1:])
if term[0] in ['X', 'Y', 'Z']:
valueTacker[term[0]] = round(float(term[1:]), precision)
tempDict['lineNumber'] = curLineNumber
prevLayerGcodes.append(tempDict.copy())
#In case of layer change, push the accumulated GCodes of previous layer and start accumulating the next one.
elif bool(layerChangePattern.match(line)):
zPos = 0
height = 0
try:
line = next(linesIterator)
curLineNumber = curLineNumber + 1
zPos = float(zPosPattern.search(line)[1])
except (IndexError, TypeError):
raise NoZPosMatch(line, curLineNumber)
try:
line = next(linesIterator)
curLineNumber = curLineNumber + 1
height = round(float(heightPattern.search(line)[1]), whPrecision)
valueTacker['H'] = height
except (IndexError, TypeError):
raise NoHeightMatch(line, curLineNumber)
prevLayer = Layer(prevLayerZPos, prevLayerHeight, curLayerNumber, prevLayerGcodes)
listOfParsedLayers.append(prevLayer)
prevLayerGcodes = []
prevLayerZPos = zPos
prevLayerHeight = height
curLayerNumber = curLayerNumber + 1
elif bool(heightPattern.match(line)):
valueTacker['H'] = round(float(heightPattern.search(line)[1]), whPrecision)
elif bool(widthPattern.match(line)):
valueTacker['W'] = round(float(widthPattern.search(line)[1]), whPrecision)
elif bool(typePattern.match(line)):
curveType = typePattern.search(line)[1].strip()
valueTacker['type'] = re.sub(" |/","_", curveType)
elif line == "!__end__!":
prevLayer = Layer(prevLayerZPos, prevLayerHeight, curLayerNumber, prevLayerGcodes)
listOfParsedLayers.append(prevLayer)
break
else:
pass
print("Processing GCode File: {}/{}".format(curLineNumber, numberOfLines), end='\r', flush=True )
print("")
return listOfParsedLayers
def addVisibilityDriver(curveOB, drivenProperty="hide_viewport"):
try:
curveType = curveOB["type"]
except KeyError:
raise ImproperCruveException(curveOB)
driver = curveOB.driver_add(drivenProperty).driver
var0 = driver.variables.new()
var0.name = "var0"
var0.targets[0].id_type = 'SCENE'
var0.targets[0].id = bpy.context.scene
var0.targets[0].data_path = "Stitcher_Props.LayerIndexTop"
var1 = driver.variables.new()
var1.name = "var1"
var1.targets[0].id_type = 'SCENE'
var1.targets[0].id = bpy.context.scene
var1.targets[0].data_path = "Stitcher_Props." + curveType
var2 = driver.variables.new()
var2.name = "var2"
var2.targets[0].id = curveOB
var2.targets[0].data_path = '["layerNumber"]'
condition1 = var1.name #is the curve type checked in the visibility tab
condition2 = "({0} <= {1})".format(var2.name, var0.name) #is the layer suppored to be visible i.e. layer number <= layer top index
condition3 = "True" #is the parent visible
if (drivenProperty == "hide_render"):
var4 = driver.variables.new()
var4.name = "var4"
var4.targets[0].id_type = 'SCENE'
var4.targets[0].id = bpy.context.scene
var4.targets[0].data_path = "Stitcher_Props.ViewportOnly"
condition1 = "({0} or {1})".format(var1.name, var4.name)
##The rounded starting and end points would have a parent parameter that points to the curve they are placed on.
##It's import to tie their visbility to their parent
if ('parent' in curveOB.keys()):
var3 = driver.variables.new()
var3.name = "var3"
var3.targets[0].id = curveOB['parent']
var3.targets[0].data_path = drivenProperty
condition3 = "not ("+ var3.name +")"
driver.expression = "not ({0} and {1} and {2})".format(condition1, condition2, condition3)
#Apply modifier to smooth out overlap artefacts, only shows in renders
def addEnhancingModifiers(curveOB):
curveOB.modifiers.new('split', 'EDGE_SPLIT')
curveOB.modifiers.get('split').show_viewport = False
#Take the parsed GCode and finally make it into a curve that is beveled on blender
def placeCurve(coords, width, height, zPos, curveType, layerNumber, bevelSuffix, collection, params):
widthOffset = params[ParamNames.widthOffset]
heightOffset = params[ParamNames.heightOffset]
whPrecision = params[ParamNames.whPrecision]
lengthOfCurve = 0
if (len(coords) > 1):
#Create new curve data and set it's properties
#Dimensions are set to 3D because setting it to 2D produces weird bugs and artefacts
curveData = bpy.data.curves.new('myCurve', type='CURVE')
curveData.dimensions = '3D'
curveData.resolution_u = 1
curveData.render_resolution_u = 12
#It's not a polyline curve, it's a bezier curve being edited to emulate a polyline curve.
#A polyline curve was giving uneven thickness when beveled
polyline = curveData.splines.new('BEZIER')
bevelObject = None
prevCoord = coords[0]
x,y,z = prevCoord
polyline.bezier_points[0].co = (x, y, z)
polyline.bezier_points[0].handle_left = (x, y, z)
polyline.bezier_points[0].handle_right = (x, y, z)
for i, coord in enumerate(coords[1:]):
distFromPreviousCoord = math.dist(prevCoord, coord)
if (distFromPreviousCoord > 0):
polyline.bezier_points.add(1)
lengthOfCurve = lengthOfCurve + distFromPreviousCoord
x,y,z = coord
polyline.bezier_points[-1].co = (x, y, z)
polyline.bezier_points[-1].handle_left = (x, y, z)
polyline.bezier_points[-1].handle_right = (x, y, z)
prevCoord = coord
if lengthOfCurve == 0:
return None
curveOB = bpy.data.objects.new('myCurve', curveData)
#Properties for debugging and other uses
curveOB.data["zPos"] = zPos
curveOB["zPos"] = zPos
curveOB.data["type"] = curveType
curveOB["type"] = curveType
curveOB.data["lengthOfCurve"] = lengthOfCurve
curveOB.data["layerNumber"] = layerNumber
curveOB["layerNumber"] = layerNumber
curveOB.hide_viewport = True
bevelName = ("{:."+str(whPrecision)+"f}").format(width + widthOffset) + "_" + ("{:."+str(whPrecision)+"f}").format(height + heightOffset) + "_" + bevelSuffix
if bevelName in bpy.data.objects.keys():
bevelObject = bpy.data.objects.get(bevelName)
else:
createProfile(width+widthOffset, height+heightOffset, 1, bevelName)
bevelObject = bpy.data.objects.get(bevelName)
curveData.bevel_mode = "OBJECT"
curveData.bevel_object = bpy.data.objects.get(bevelName)
curveData.use_fill_caps = True
#Material was already imported from assets.blend file when the "Load GCode" button was pressed
mat = bpy.data.materials.get(Keywords.materialName)
if (len(curveOB.data.materials) == 0):
curveOB.data.materials.append(mat)
addEnhancingModifiers(curveOB)
#Change bevel mapping - this would be used for rounding the end points of the curve
curveOB.data.bevel_factor_mapping_start = 'SPLINE'
curveOB.data.bevel_factor_mapping_end = 'SPLINE'
collection.objects.link(curveOB)
return curveOB
def builder(gcodeFilePath, objectName="OBJECT", bevelSuffix="bevel", params = {}):
#print(params)
coin = Coin(params[ParamNames.seed])
listOfParsedLayers = gcodeParser(gcodeFilePath, params)
i = 0
parentCollection = bpy.data.collections.new(objectName)
bpy.context.scene.collection.children.link(parentCollection)
numberOfLayers = len(listOfParsedLayers) - 1
for currentLayer in listOfParsedLayers:
prevWidth = 0
prevType = "Custom"
prevHeight = 0
coords = []
layerCollection = bpy.data.collections.new("Layer " + str(currentLayer.layerNumber))
parentCollection.children.link(layerCollection)
#Below line is used for debugging particular lines of gcode
#currentLayer.gcodes = filter(lambda x: 73 < x['lineNumber'] and x['lineNumber'] <= 93 ,currentLayer.gcodes)
def placeCurveFunc(curveType):
curveOB = placeCurve(coords, prevWidth, prevHeight, currentLayer.zPos, prevType, currentLayer.layerNumber, bevelSuffix, layerCollection, params)
if (not curveOB == None):
addVisibilityDriver(curveOB, "hide_viewport")
addVisibilityDriver(curveOB, "hide_render")
if (curveType in ["External_perimeter", "Skirt_Brim", "Perimeter", "Top_solid_infill", "Overhang_perimeter"] and not curveOB == None ):
endPoint, startPoint = createEndPoints(curveOB, params, coin)
layerCollection.objects.link(endPoint)
layerCollection.objects.link(startPoint)
addVisibilityDriver(endPoint, "hide_viewport")
addVisibilityDriver(startPoint, "hide_viewport")
addVisibilityDriver(endPoint, "hide_render")
addVisibilityDriver(startPoint, "hide_render")
curveOB[Keywords.startPoint] = startPoint
curveOB[Keywords.endPoint] = startPoint
for elem in currentLayer.gcodes:
#print(elem)
if (elem["E"] > 0):
if (elem['W'] == prevWidth and elem['type'] == prevType and elem['H'] == prevHeight):
coords.append((elem['X'],elem['Y'],elem['Z']))
else:
placeCurveFunc(prevType)
prevWidth = elem['W']
prevType = elem['type']
prevHeight = elem['H']
coords = coords[-1:]
coords.append((elem['X'],elem['Y'],elem['Z']))
else:
placeCurveFunc(prevType)
coords = [(elem['X'],elem['Y'],elem['Z'])]
placeCurveFunc(prevType)
print("Layer Done: {}/{}".format(currentLayer.layerNumber, numberOfLayers), end='\r', flush=True)
i = i + 1
print("")
bpy.context.scene["Stitcher_Object_Collection"] = parentCollection