chiark / gitweb /
2d92e9fc7f06da6c5573a6077bf40c570fa9d294
[cura.git] / Cura / util / gcodeInterpreter.py
1 import sys
2 import math
3 import re
4 import os
5
6 import util3d
7 import profile
8
9 class gcodePath(object):
10         def __init__(self, newType, pathType, layerThickness, startPoint):
11                 self.type = newType
12                 self.pathType = pathType
13                 self.layerThickness = layerThickness
14                 self.list = [startPoint]
15
16 class gcode(object):
17         def __init__(self):
18                 self.regMatch = {}
19                 self.layerList = []
20                 self.extrusionAmount = 0
21                 self.totalMoveTimeMinute = 0
22                 self.progressCallback = None
23         
24         def load(self, filename):
25                 if os.path.isfile(filename):
26                         self._fileSize = os.stat(filename).st_size
27                         gcodeFile = open(filename, 'r')
28                         self._load(gcodeFile)
29                         gcodeFile.close()
30         
31         def loadList(self, l):
32                 self._load(l)
33         
34         def calculateWeight(self):
35                 #Calculates the weight of the filament in kg
36                 radius = float(profile.getProfileSetting('filament_diameter')) / 2
37                 volumeM3 = (self.extrusionAmount * (math.pi * radius * radius)) / (1000*1000*1000)
38                 return volumeM3 * profile.getPreferenceFloat('filament_density')
39         
40         def calculateCost(self):
41                 cost_kg = profile.getPreferenceFloat('filament_cost_kg')
42                 cost_meter = profile.getPreferenceFloat('filament_cost_meter')
43                 if cost_kg > 0.0 and cost_meter > 0.0:
44                         return "%.2f / %.2f" % (self.calculateWeight() * cost_kg, self.extrusionAmount / 1000 * cost_meter)
45                 elif cost_kg > 0.0:
46                         return "%.2f" % (self.calculateWeight() * cost_kg)
47                 elif cost_meter > 0.0:
48                         return "%.2f" % (self.extrusionAmount / 1000 * cost_meter)
49                 return False
50         
51         def _load(self, gcodeFile):
52                 filePos = 0
53                 pos = util3d.Vector3()
54                 posOffset = util3d.Vector3()
55                 currentE = 0.0
56                 totalExtrusion = 0.0
57                 maxExtrusion = 0.0
58                 currentExtruder = 0
59                 totalMoveTimeMinute = 0.0
60                 scale = 1.0
61                 posAbs = True
62                 feedRate = 3600
63                 layerThickness = 0.1
64                 pathType = 'CUSTOM';
65                 startCodeDone = False
66                 currentLayer = []
67                 currentPath = gcodePath('move', pathType, layerThickness, pos.copy())
68                 currentPath.list[0].e = totalExtrusion
69                 currentLayer.append(currentPath)
70                 for line in gcodeFile:
71                         if self.progressCallback != None:
72                                 if filePos != gcodeFile.tell():
73                                         filePos = gcodeFile.tell()
74                                         self.progressCallback(float(filePos) / float(self._fileSize))
75                         
76                         #Parse Cura_SF comments
77                         if line.startswith(';TYPE:'):
78                                 pathType = line[6:].strip()
79                                 if pathType != "CUSTOM":
80                                         startCodeDone = True
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                                         currentLayer = []
94                                 if pathType != "CUSTOM":
95                                         startCodeDone = True
96                                 line = line[0:line.find(';')]
97                         T = self.getCodeInt(line, 'T')
98                         if T is not None:
99                                 if currentExtruder > 0:
100                                         posOffset.x -= profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
101                                         posOffset.y -= profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
102                                 currentExtruder = T
103                                 if currentExtruder > 0:
104                                         posOffset.x += profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
105                                         posOffset.y += profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
106                         
107                         G = self.getCodeInt(line, 'G')
108                         if G is not None:
109                                 if G == 0 or G == 1:    #Move
110                                         x = self.getCodeFloat(line, 'X')
111                                         y = self.getCodeFloat(line, 'Y')
112                                         z = self.getCodeFloat(line, 'Z')
113                                         e = self.getCodeFloat(line, 'E')
114                                         f = self.getCodeFloat(line, 'F')
115                                         oldPos = pos.copy()
116                                         if x is not None:
117                                                 if posAbs:
118                                                         pos.x = x * scale + posOffset.x
119                                                 else:
120                                                         pos.x += x * scale
121                                         if y is not None:
122                                                 if posAbs:
123                                                         pos.y = y * scale + posOffset.y
124                                                 else:
125                                                         pos.y += y * scale
126                                         if z is not None:
127                                                 if posAbs:
128                                                         pos.z = z * scale + posOffset.z
129                                                 else:
130                                                         pos.z += z * scale
131                                         if f is not None:
132                                                 feedRate = f
133                                         if x is not None or y is not None or z is not None:
134                                                 totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate
135                                         moveType = 'move'
136                                         if e is not None:
137                                                 if posAbs:
138                                                         if e > currentE:
139                                                                 moveType = 'extrude'
140                                                         if e < currentE:
141                                                                 moveType = 'retract'
142                                                         totalExtrusion += e - currentE
143                                                         currentE = e
144                                                 else:
145                                                         if e > 0:
146                                                                 moveType = 'extrude'
147                                                         if e < 0:
148                                                                 moveType = 'retract'
149                                                         totalExtrusion += e
150                                                         currentE += e
151                                                 if totalExtrusion > maxExtrusion:
152                                                         maxExtrusion = totalExtrusion
153                                         if moveType == 'move' and oldPos.z != pos.z:
154                                                 layerThickness = abs(oldPos.z - pos.z)
155                                         if currentPath.type != moveType or currentPath.pathType != pathType:
156                                                 currentPath = gcodePath(moveType, pathType, layerThickness, currentPath.list[-1])
157                                                 currentLayer.append(currentPath)
158                                         newPos = pos.copy()
159                                         newPos.e = totalExtrusion
160                                         currentPath.list.append(newPos)
161                                 elif G == 4:    #Delay
162                                         S = self.getCodeFloat(line, 'S')
163                                         if S is not None:
164                                                 totalMoveTimeMinute += S / 60
165                                         P = self.getCodeFloat(line, 'P')
166                                         if P is not None:
167                                                 totalMoveTimeMinute += P / 60 / 1000
168                                 elif G == 20:   #Units are inches
169                                         scale = 25.4
170                                 elif G == 21:   #Units are mm
171                                         scale = 1.0
172                                 elif G == 28:   #Home
173                                         x = self.getCodeFloat(line, 'X')
174                                         y = self.getCodeFloat(line, 'Y')
175                                         z = self.getCodeFloat(line, 'Z')
176                                         if x is None and y is None and z is None:
177                                                 pos = util3d.Vector3()
178                                         else:
179                                                 if x is not None:
180                                                         pos.x = 0.0
181                                                 if y is not None:
182                                                         pos.y = 0.0
183                                                 if z is not None:
184                                                         pos.z = 0.0
185                                 elif G == 90:   #Absolute position
186                                         posAbs = True
187                                 elif G == 91:   #Relative position
188                                         posAbs = False
189                                 elif G == 92:
190                                         x = self.getCodeFloat(line, 'X')
191                                         y = self.getCodeFloat(line, 'Y')
192                                         z = self.getCodeFloat(line, 'Z')
193                                         e = self.getCodeFloat(line, 'E')
194                                         if e is not None:
195                                                 currentE = e
196                                         if x is not None:
197                                                 posOffset.x = pos.x + x
198                                         if y is not None:
199                                                 posOffset.y = pos.y + y
200                                         if z is not None:
201                                                 posOffset.z = pos.z + z
202                                 else:
203                                         print "Unknown G code:" + str(G)
204                         else:
205                                 M = self.getCodeInt(line, 'M')
206                                 if M is not None:
207                                         if M == 1:      #Message with possible wait (ignored)
208                                                 pass
209                                         elif M == 84:   #Disable step drivers
210                                                 pass
211                                         elif M == 92:   #Set steps per unit
212                                                 pass
213                                         elif M == 104:  #Set temperature, no wait
214                                                 pass
215                                         elif M == 105:  #Get temperature
216                                                 pass
217                                         elif M == 106:  #Enable fan
218                                                 pass
219                                         elif M == 107:  #Disable fan
220                                                 pass
221                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
222                                                 pass
223                                         elif M == 109:  #Set temperature, wait
224                                                 pass
225                                         elif M == 110:  #Reset N counter
226                                                 pass
227                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
228                                                 pass
229                                         else:
230                                                 print "Unknown M code:" + str(M)
231                 self.layerList.append(currentLayer)
232                 self.extrusionAmount = maxExtrusion
233                 self.totalMoveTimeMinute = totalMoveTimeMinute
234                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
235                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
236
237         def getCodeInt(self, line, code):
238                 if code not in self.regMatch:
239                         self.regMatch[code] = re.compile(code + '([^\s]+)')
240                 m = self.regMatch[code].search(line)
241                 if m == None:
242                         return None
243                 try:
244                         return int(m.group(1))
245                 except:
246                         return None
247
248         def getCodeFloat(self, line, code):
249                 if code not in self.regMatch:
250                         self.regMatch[code] = re.compile(code + '([^\s]+)')
251                 m = self.regMatch[code].search(line)
252                 if m == None:
253                         return None
254                 try:
255                         return float(m.group(1))
256                 except:
257                         return None
258
259 if __name__ == '__main__':
260         for filename in sys.argv[1:]:
261                 gcode().load(filename)
262