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