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