chiark / gitweb /
Merge branch 'master' into SteamEngine
[cura.git] / Cura / util / gcodeInterpreter.py
1 from __future__ import absolute_import
2
3 import sys
4 import math
5 import os
6 import time
7
8 from Cura.util import profile
9
10 class gcodePath(object):
11         def __init__(self, newType, pathType, layerThickness, startPoint):
12                 self.type = newType
13                 self.pathType = pathType
14                 self.layerThickness = layerThickness
15                 self.points = [startPoint]
16                 self.extrusion = [0]
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_physical_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 = [0.0, 0.0, 0.0]
55                 posOffset = [0.0, 0.0, 0.0]
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.0
66                 layerThickness = 0.1
67                 pathType = 'CUSTOM';
68                 currentLayer = []
69                 currentPath = gcodePath('move', pathType, layerThickness, pos[:])
70                 currentPath.extruder = currentExtruder
71
72                 currentLayer.append(currentPath)
73                 for line in gcodeFile:
74                         if type(line) is tuple:
75                                 line = line[0]
76
77                         #Parse Cura_SF comments
78                         if line.startswith(';TYPE:'):
79                                 pathType = line[6:].strip()
80
81                         if ';' in line:
82                                 #Slic3r GCode comment parser
83                                 comment = line[line.find(';')+1:].strip()
84                                 if comment == 'fill':
85                                         pathType = 'FILL'
86                                 elif comment == 'perimeter':
87                                         pathType = 'WALL-INNER'
88                                 elif comment == 'skirt':
89                                         pathType = 'SKIRT'
90                                 if comment.startswith('LAYER:'):
91                                         self.layerList.append(currentLayer)
92                                         if self.progressCallback is not None:
93                                                 if self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize)):
94                                                         #Abort the loading, we can safely return as the results here will be discarded
95                                                         gcodeFile.close()
96                                                         return
97                                         currentLayer = []
98                                 line = line[0:line.find(';')]
99                         T = getCodeInt(line, 'T')
100                         if T is not None:
101                                 if currentExtruder > 0:
102                                         posOffset[0] -= profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
103                                         posOffset[1] -= profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
104                                 currentExtruder = T
105                                 if currentExtruder > 0:
106                                         posOffset[0] += profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
107                                         posOffset[1] += profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
108                         
109                         G = getCodeInt(line, 'G')
110                         if G is not None:
111                                 if G == 0 or G == 1:    #Move
112                                         x = getCodeFloat(line, 'X')
113                                         y = getCodeFloat(line, 'Y')
114                                         z = getCodeFloat(line, 'Z')
115                                         e = getCodeFloat(line, 'E')
116                                         f = getCodeFloat(line, 'F')
117                                         oldPos = pos[:]
118                                         if posAbs:
119                                                 if x is not None:
120                                                         pos[0] = x * scale + posOffset[0]
121                                                 if y is not None:
122                                                         pos[1] = y * scale + posOffset[1]
123                                                 if z is not None:
124                                                         pos[2] = z * scale + posOffset[2]
125                                         else:
126                                                 if x is not None:
127                                                         pos[0] += x * scale
128                                                 if y is not None:
129                                                         pos[1] += y * scale
130                                                 if z is not None:
131                                                         pos[2] += z * scale
132                                         if f is not None:
133                                                 feedRate = f
134                                         #if x is not None or y is not None or z is not None:
135                                         #       diffX = oldPos[0] - pos[0]
136                                         #       diffY = oldPos[1] - pos[1]
137                                         #       totalMoveTimeMinute += math.sqrt(diffX * diffX + diffY * diffY) / feedRate
138                                         moveType = 'move'
139                                         if e is not None:
140                                                 if absoluteE:
141                                                         e -= currentE
142                                                 if e > 0:
143                                                         moveType = 'extrude'
144                                                 if e < 0:
145                                                         moveType = 'retract'
146                                                 totalExtrusion += e
147                                                 currentE += e
148                                                 if totalExtrusion > maxExtrusion:
149                                                         maxExtrusion = totalExtrusion
150                                         else:
151                                                 e = 0.0
152                                         if moveType == 'move' and oldPos[2] != pos[2]:
153                                                 if oldPos[2] > pos[2] and abs(oldPos[2] - pos[2]) > 5.0 and pos[2] < 1.0:
154                                                         oldPos[2] = 0.0
155                                                 layerThickness = abs(oldPos[2] - pos[2])
156                                         if currentPath.type != moveType or currentPath.pathType != pathType:
157                                                 currentPath = gcodePath(moveType, pathType, layerThickness, currentPath.points[-1])
158                                                 currentPath.extruder = currentExtruder
159                                                 currentLayer.append(currentPath)
160
161                                         currentPath.points.append(pos[:])
162                                         currentPath.extrusion.append(e * extrudeAmountMultiply)
163                                 elif G == 4:    #Delay
164                                         S = getCodeFloat(line, 'S')
165                                         if S is not None:
166                                                 totalMoveTimeMinute += S / 60.0
167                                         P = getCodeFloat(line, 'P')
168                                         if P is not None:
169                                                 totalMoveTimeMinute += P / 60.0 / 1000.0
170                                 elif G == 20:   #Units are inches
171                                         scale = 25.4
172                                 elif G == 21:   #Units are mm
173                                         scale = 1.0
174                                 elif G == 28:   #Home
175                                         x = getCodeFloat(line, 'X')
176                                         y = getCodeFloat(line, 'Y')
177                                         z = getCodeFloat(line, 'Z')
178                                         if x is None and y is None and z is None:
179                                                 pos = [0.0,0.0,0.0]
180                                         else:
181                                                 if x is not None:
182                                                         pos[0] = 0.0
183                                                 if y is not None:
184                                                         pos[0] = 0.0
185                                                 if z is not None:
186                                                         pos[0] = 0.0
187                                 elif G == 90:   #Absolute position
188                                         posAbs = True
189                                 elif G == 91:   #Relative position
190                                         posAbs = False
191                                 elif G == 92:
192                                         x = getCodeFloat(line, 'X')
193                                         y = getCodeFloat(line, 'Y')
194                                         z = getCodeFloat(line, 'Z')
195                                         e = getCodeFloat(line, 'E')
196                                         if e is not None:
197                                                 currentE = e
198                                         if x is not None:
199                                                 posOffset[0] = pos[0] - x
200                                         if y is not None:
201                                                 posOffset[1] = pos[1] - y
202                                         if z is not None:
203                                                 posOffset[2] = pos[2] - z
204                                 else:
205                                         print "Unknown G code:" + str(G)
206                         else:
207                                 M = getCodeInt(line, 'M')
208                                 if M is not None:
209                                         if M == 0:      #Message with possible wait (ignored)
210                                                 pass
211                                         elif M == 1:    #Message with possible wait (ignored)
212                                                 pass
213                                         elif M == 80:   #Enable power supply
214                                                 pass
215                                         elif M == 81:   #Suicide/disable power supply
216                                                 pass
217                                         elif M == 82:   #Absolute E
218                                                 absoluteE = True
219                                         elif M == 83:   #Relative E
220                                                 absoluteE = False
221                                         elif M == 84:   #Disable step drivers
222                                                 pass
223                                         elif M == 92:   #Set steps per unit
224                                                 pass
225                                         elif M == 101:  #Enable extruder
226                                                 pass
227                                         elif M == 103:  #Disable extruder
228                                                 pass
229                                         elif M == 104:  #Set temperature, no wait
230                                                 pass
231                                         elif M == 105:  #Get temperature
232                                                 pass
233                                         elif M == 106:  #Enable fan
234                                                 pass
235                                         elif M == 107:  #Disable fan
236                                                 pass
237                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
238                                                 pass
239                                         elif M == 109:  #Set temperature, wait
240                                                 pass
241                                         elif M == 110:  #Reset N counter
242                                                 pass
243                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
244                                                 pass
245                                         elif M == 117:  #LCD message
246                                                 pass
247                                         elif M == 140:  #Set bed temperature
248                                                 pass
249                                         elif M == 190:  #Set bed temperature & wait
250                                                 pass
251                                         elif M == 221:  #Extrude amount multiplier
252                                                 s = getCodeFloat(line, 'S')
253                                                 if s is not None:
254                                                         extrudeAmountMultiply = s / 100.0
255                                         else:
256                                                 print "Unknown M code:" + str(M)
257                 self.layerList.append(currentLayer)
258                 if self.progressCallback is not None and self._fileSize > 0:
259                         self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize))
260                 self.extrusionAmount = maxExtrusion
261                 self.totalMoveTimeMinute = totalMoveTimeMinute
262                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
263                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
264
265 def getCodeInt(line, code):
266         n = line.find(code) + 1
267         if n < 1:
268                 return None
269         m = line.find(' ', n)
270         try:
271                 if m < 0:
272                         return int(line[n:])
273                 return int(line[n:m])
274         except:
275                 return None
276
277 def getCodeFloat(line, code):
278         n = line.find(code) + 1
279         if n < 1:
280                 return None
281         m = line.find(' ', n)
282         try:
283                 if m < 0:
284                         return float(line[n:])
285                 return float(line[n:m])
286         except:
287                 return None
288
289 if __name__ == '__main__':
290         t = time.time()
291         for filename in sys.argv[1:]:
292                 g = gcode()
293                 g.load(filename)
294                 print g.totalMoveTimeMinute
295         print time.time() - t
296