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