chiark / gitweb /
Fix for the pauze at Z plugin, when using multiple pauses below 15mm it was seeing...
[cura.git] / Cura / util / gcodeInterpreter.py
1 from __future__ import absolute_import
2
3 import sys
4 import math
5 import re
6 import os
7
8 from Cura.util import util3d
9 from Cura.util import profile
10
11 class gcodePath(object):
12         def __init__(self, newType, pathType, layerThickness, startPoint):
13                 self.type = newType
14                 self.pathType = pathType
15                 self.layerThickness = layerThickness
16                 self.list = [startPoint]
17
18 class gcode(object):
19         def __init__(self):
20                 self.regMatch = {}
21                 self.layerList = []
22                 self.extrusionAmount = 0
23                 self.totalMoveTimeMinute = 0
24                 self.progressCallback = None
25         
26         def load(self, filename):
27                 if os.path.isfile(filename):
28                         self._fileSize = os.stat(filename).st_size
29                         gcodeFile = open(filename, 'r')
30                         self._load(gcodeFile)
31                         gcodeFile.close()
32         
33         def loadList(self, l):
34                 self._load(l)
35         
36         def calculateWeight(self):
37                 #Calculates the weight of the filament in kg
38                 radius = float(profile.getProfileSetting('filament_diameter')) / 2
39                 volumeM3 = (self.extrusionAmount * (math.pi * radius * radius)) / (1000*1000*1000)
40                 return volumeM3 * profile.getPreferenceFloat('filament_density')
41         
42         def calculateCost(self):
43                 cost_kg = profile.getPreferenceFloat('filament_cost_kg')
44                 cost_meter = profile.getPreferenceFloat('filament_cost_meter')
45                 if cost_kg > 0.0 and cost_meter > 0.0:
46                         return "%.2f / %.2f" % (self.calculateWeight() * cost_kg, self.extrusionAmount / 1000 * cost_meter)
47                 elif cost_kg > 0.0:
48                         return "%.2f" % (self.calculateWeight() * cost_kg)
49                 elif cost_meter > 0.0:
50                         return "%.2f" % (self.extrusionAmount / 1000 * cost_meter)
51                 return None
52         
53         def _load(self, gcodeFile):
54                 pos = util3d.Vector3()
55                 posOffset = util3d.Vector3()
56                 currentE = 0.0
57                 totalExtrusion = 0.0
58                 maxExtrusion = 0.0
59                 currentExtruder = 0
60                 extrudeAmountMultiply = 1.0
61                 totalMoveTimeMinute = 0.0
62                 absoluteE = True
63                 scale = 1.0
64                 posAbs = True
65                 feedRate = 3600
66                 layerThickness = 0.1
67                 pathType = 'CUSTOM';
68                 startCodeDone = False
69                 currentLayer = []
70                 currentPath = gcodePath('move', pathType, layerThickness, pos.copy())
71                 currentPath.list[0].e = totalExtrusion
72                 currentPath.list[0].extrudeAmountMultiply = extrudeAmountMultiply
73                 currentLayer.append(currentPath)
74                 for line in gcodeFile:
75                         if type(line) is tuple:
76                                 line = line[0]
77
78                         #Parse Cura_SF comments
79                         if line.startswith(';TYPE:'):
80                                 pathType = line[6:].strip()
81                                 if pathType != "CUSTOM":
82                                         startCodeDone = True
83                                         
84                         if ';' in line:
85                                 #Slic3r GCode comment parser
86                                 comment = line[line.find(';')+1:].strip()
87                                 if comment == 'fill':
88                                         pathType = 'FILL'
89                                 elif comment == 'perimeter':
90                                         pathType = 'WALL-INNER'
91                                 elif comment == 'skirt':
92                                         pathType = 'SKIRT'
93                                 if comment.startswith('LAYER:'):
94                                         self.layerList.append(currentLayer)
95                                         if self.progressCallback is not None:
96                                                 if self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize)):
97                                                         #Abort the loading, we can safely return as the results here will be discarded
98                                                         gcodeFile.close()
99                                                         return
100                                         currentLayer = []
101                                 if pathType != "CUSTOM":
102                                         startCodeDone = True
103                                 line = line[0:line.find(';')]
104                         T = self.getCodeInt(line, 'T')
105                         if T is not None:
106                                 if currentExtruder > 0:
107                                         posOffset.x -= profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
108                                         posOffset.y -= profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
109                                 currentExtruder = T
110                                 if currentExtruder > 0:
111                                         posOffset.x += profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
112                                         posOffset.y += profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
113                         
114                         G = self.getCodeInt(line, 'G')
115                         if G is not None:
116                                 if G == 0 or G == 1:    #Move
117                                         x = self.getCodeFloat(line, 'X')
118                                         y = self.getCodeFloat(line, 'Y')
119                                         z = self.getCodeFloat(line, 'Z')
120                                         e = self.getCodeFloat(line, 'E')
121                                         f = self.getCodeFloat(line, 'F')
122                                         oldPos = pos.copy()
123                                         if x is not None:
124                                                 if posAbs:
125                                                         pos.x = x * scale + posOffset.x
126                                                 else:
127                                                         pos.x += x * scale
128                                         if y is not None:
129                                                 if posAbs:
130                                                         pos.y = y * scale + posOffset.y
131                                                 else:
132                                                         pos.y += y * scale
133                                         if z is not None:
134                                                 if posAbs:
135                                                         pos.z = z * scale + posOffset.z
136                                                 else:
137                                                         pos.z += z * scale
138                                         if f is not None:
139                                                 feedRate = f
140                                         if x is not None or y is not None or z is not None:
141                                                 totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate
142                                         moveType = 'move'
143                                         if e is not None:
144                                                 if not absoluteE:
145                                                         e += currentE
146                                                 if posAbs:
147                                                         if e > currentE:
148                                                                 moveType = 'extrude'
149                                                         if e < currentE:
150                                                                 moveType = 'retract'
151                                                 else:
152                                                         if e > 0:
153                                                                 moveType = 'extrude'
154                                                         if e < 0:
155                                                                 moveType = 'retract'
156                                                 totalExtrusion += e - currentE
157                                                 currentE = e
158                                                 if totalExtrusion > maxExtrusion:
159                                                         maxExtrusion = totalExtrusion
160                                         if moveType == 'move' and oldPos.z != pos.z:
161                                                 if oldPos.z > pos.z and abs(oldPos.z - pos.z) > 5.0 and pos.z < 1.0:
162                                                         oldPos.z = 0.0
163                                                 layerThickness = abs(oldPos.z - pos.z)
164                                         if currentPath.type != moveType or currentPath.pathType != pathType:
165                                                 currentPath = gcodePath(moveType, pathType, layerThickness, currentPath.list[-1])
166                                                 currentLayer.append(currentPath)
167                                         newPos = pos.copy()
168                                         newPos.e = totalExtrusion
169                                         newPos.extrudeAmountMultiply = extrudeAmountMultiply
170                                         currentPath.list.append(newPos)
171                                 elif G == 4:    #Delay
172                                         S = self.getCodeFloat(line, 'S')
173                                         if S is not None:
174                                                 totalMoveTimeMinute += S / 60
175                                         P = self.getCodeFloat(line, 'P')
176                                         if P is not None:
177                                                 totalMoveTimeMinute += P / 60 / 1000
178                                 elif G == 20:   #Units are inches
179                                         scale = 25.4
180                                 elif G == 21:   #Units are mm
181                                         scale = 1.0
182                                 elif G == 28:   #Home
183                                         x = self.getCodeFloat(line, 'X')
184                                         y = self.getCodeFloat(line, 'Y')
185                                         z = self.getCodeFloat(line, 'Z')
186                                         if x is None and y is None and z is None:
187                                                 pos = util3d.Vector3()
188                                         else:
189                                                 if x is not None:
190                                                         pos.x = 0.0
191                                                 if y is not None:
192                                                         pos.y = 0.0
193                                                 if z is not None:
194                                                         pos.z = 0.0
195                                 elif G == 90:   #Absolute position
196                                         posAbs = True
197                                 elif G == 91:   #Relative position
198                                         posAbs = False
199                                 elif G == 92:
200                                         x = self.getCodeFloat(line, 'X')
201                                         y = self.getCodeFloat(line, 'Y')
202                                         z = self.getCodeFloat(line, 'Z')
203                                         e = self.getCodeFloat(line, 'E')
204                                         if e is not None:
205                                                 currentE = e
206                                         if x is not None:
207                                                 posOffset.x = pos.x - x
208                                         if y is not None:
209                                                 posOffset.y = pos.y - y
210                                         if z is not None:
211                                                 posOffset.z = pos.z - z
212                                 else:
213                                         print "Unknown G code:" + str(G)
214                         else:
215                                 M = self.getCodeInt(line, 'M')
216                                 if M is not None:
217                                         if M == 0:      #Message with possible wait (ignored)
218                                                 pass
219                                         elif M == 1:    #Message with possible wait (ignored)
220                                                 pass
221                                         elif M == 80:   #Enable power supply
222                                                 pass
223                                         elif M == 81:   #Suicide/disable power supply
224                                                 pass
225                                         elif M == 82:   #Absolute E
226                                                 absoluteE = True
227                                         elif M == 83:   #Relative E
228                                                 absoluteE = False
229                                         elif M == 84:   #Disable step drivers
230                                                 pass
231                                         elif M == 92:   #Set steps per unit
232                                                 pass
233                                         elif M == 101:  #Enable extruder
234                                                 pass
235                                         elif M == 103:  #Disable extruder
236                                                 pass
237                                         elif M == 104:  #Set temperature, no wait
238                                                 pass
239                                         elif M == 105:  #Get temperature
240                                                 pass
241                                         elif M == 106:  #Enable fan
242                                                 pass
243                                         elif M == 107:  #Disable fan
244                                                 pass
245                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
246                                                 pass
247                                         elif M == 109:  #Set temperature, wait
248                                                 pass
249                                         elif M == 110:  #Reset N counter
250                                                 pass
251                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
252                                                 pass
253                                         elif M == 117:  #LCD message
254                                                 pass
255                                         elif M == 140:  #Set bed temperature
256                                                 pass
257                                         elif M == 190:  #Set bed temperature & wait
258                                                 pass
259                                         elif M == 221:  #Extrude amount multiplier
260                                                 s = self.getCodeFloat(line, 'S')
261                                                 if s != None:
262                                                         extrudeAmountMultiply = s / 100.0
263                                         else:
264                                                 print "Unknown M code:" + str(M)
265                 self.layerList.append(currentLayer)
266                 if self.progressCallback is not None and self._fileSize > 0:
267                         self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize))
268                 self.extrusionAmount = maxExtrusion
269                 self.totalMoveTimeMinute = totalMoveTimeMinute
270                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
271                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
272
273         def getCodeInt(self, line, code):
274                 if code not in self.regMatch:
275                         self.regMatch[code] = re.compile(code + '([^\s]+)')
276                 m = self.regMatch[code].search(line)
277                 if m is None:
278                         return None
279                 try:
280                         return int(m.group(1))
281                 except:
282                         return None
283
284         def getCodeFloat(self, line, code):
285                 if code not in self.regMatch:
286                         self.regMatch[code] = re.compile(code + '([^\s]+)')
287                 m = self.regMatch[code].search(line)
288                 if m is None:
289                         return None
290                 try:
291                         return float(m.group(1))
292                 except:
293                         return None
294
295 if __name__ == '__main__':
296         for filename in sys.argv[1:]:
297                 gcode().load(filename)
298