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 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_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 = 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                 currentLayer = []
69                 currentPath = gcodePath('move', pathType, layerThickness, pos.copy())
70                 currentPath.extruder = currentExtruder
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 += math.sqrt((oldPos.x - pos.x) * (oldPos.x - pos.x) + (oldPos.y - pos.y) * (oldPos.y - pos.y)) / 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                                                 currentPath.extruder = currentExtruder
163                                                 currentLayer.append(currentPath)
164                                         newPos = pos.copy()
165                                         newPos.e = totalExtrusion
166                                         newPos.extrudeAmountMultiply = extrudeAmountMultiply
167                                         currentPath.list.append(newPos)
168                                 elif G == 4:    #Delay
169                                         S = self.getCodeFloat(line, 'S')
170                                         if S is not None:
171                                                 totalMoveTimeMinute += S / 60
172                                         P = self.getCodeFloat(line, 'P')
173                                         if P is not None:
174                                                 totalMoveTimeMinute += P / 60 / 1000
175                                 elif G == 20:   #Units are inches
176                                         scale = 25.4
177                                 elif G == 21:   #Units are mm
178                                         scale = 1.0
179                                 elif G == 28:   #Home
180                                         x = self.getCodeFloat(line, 'X')
181                                         y = self.getCodeFloat(line, 'Y')
182                                         z = self.getCodeFloat(line, 'Z')
183                                         if x is None and y is None and z is None:
184                                                 pos = util3d.Vector3()
185                                         else:
186                                                 if x is not None:
187                                                         pos.x = 0.0
188                                                 if y is not None:
189                                                         pos.y = 0.0
190                                                 if z is not None:
191                                                         pos.z = 0.0
192                                 elif G == 90:   #Absolute position
193                                         posAbs = True
194                                 elif G == 91:   #Relative position
195                                         posAbs = False
196                                 elif G == 92:
197                                         x = self.getCodeFloat(line, 'X')
198                                         y = self.getCodeFloat(line, 'Y')
199                                         z = self.getCodeFloat(line, 'Z')
200                                         e = self.getCodeFloat(line, 'E')
201                                         if e is not None:
202                                                 currentE = e
203                                         if x is not None:
204                                                 posOffset.x = pos.x - x
205                                         if y is not None:
206                                                 posOffset.y = pos.y - y
207                                         if z is not None:
208                                                 posOffset.z = pos.z - z
209                                 else:
210                                         print "Unknown G code:" + str(G)
211                         else:
212                                 M = self.getCodeInt(line, 'M')
213                                 if M is not None:
214                                         if M == 0:      #Message with possible wait (ignored)
215                                                 pass
216                                         elif M == 1:    #Message with possible wait (ignored)
217                                                 pass
218                                         elif M == 80:   #Enable power supply
219                                                 pass
220                                         elif M == 81:   #Suicide/disable power supply
221                                                 pass
222                                         elif M == 82:   #Absolute E
223                                                 absoluteE = True
224                                         elif M == 83:   #Relative E
225                                                 absoluteE = False
226                                         elif M == 84:   #Disable step drivers
227                                                 pass
228                                         elif M == 92:   #Set steps per unit
229                                                 pass
230                                         elif M == 101:  #Enable extruder
231                                                 pass
232                                         elif M == 103:  #Disable extruder
233                                                 pass
234                                         elif M == 104:  #Set temperature, no wait
235                                                 pass
236                                         elif M == 105:  #Get temperature
237                                                 pass
238                                         elif M == 106:  #Enable fan
239                                                 pass
240                                         elif M == 107:  #Disable fan
241                                                 pass
242                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
243                                                 pass
244                                         elif M == 109:  #Set temperature, wait
245                                                 pass
246                                         elif M == 110:  #Reset N counter
247                                                 pass
248                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
249                                                 pass
250                                         elif M == 117:  #LCD message
251                                                 pass
252                                         elif M == 140:  #Set bed temperature
253                                                 pass
254                                         elif M == 190:  #Set bed temperature & wait
255                                                 pass
256                                         elif M == 221:  #Extrude amount multiplier
257                                                 s = self.getCodeFloat(line, 'S')
258                                                 if s != None:
259                                                         extrudeAmountMultiply = s / 100.0
260                                         else:
261                                                 print "Unknown M code:" + str(M)
262                 self.layerList.append(currentLayer)
263                 if self.progressCallback is not None and self._fileSize > 0:
264                         self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize))
265                 self.extrusionAmount = maxExtrusion
266                 self.totalMoveTimeMinute = totalMoveTimeMinute
267                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
268                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
269
270         def getCodeInt(self, line, code):
271                 n = line.find(code) + 1
272                 if n < 1:
273                         return None
274                 m = line.find(' ', n)
275                 try:
276                         if m < 0:
277                                 return int(line[n:])
278                         return int(line[n:m])
279                 except:
280                         return None
281
282         def getCodeFloat(self, line, code):
283                 n = line.find(code) + 1
284                 if n < 1:
285                         return None
286                 m = line.find(' ', n)
287                 try:
288                         if m < 0:
289                                 return float(line[n:])
290                         return float(line[n:m])
291                 except:
292                         return None
293
294 if __name__ == '__main__':
295         t = time.time()
296         for filename in sys.argv[1:]:
297                 g = gcode()
298                 g.load(filename)
299                 print g.totalMoveTimeMinute
300         print time.time() - t
301