chiark / gitweb /
Merge branch 'master' of github.com:daid/Cura
[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 == 20:   #Units are inches
162                                         scale = 25.4
163                                 elif G == 21:   #Units are mm
164                                         scale = 1.0
165                                 elif G == 28:   #Home
166                                         x = self.getCodeFloat(line, 'X')
167                                         y = self.getCodeFloat(line, 'Y')
168                                         z = self.getCodeFloat(line, 'Z')
169                                         if x is None and y is None and z is None:
170                                                 pos = util3d.Vector3()
171                                         else:
172                                                 if x is not None:
173                                                         pos.x = 0.0
174                                                 if y is not None:
175                                                         pos.y = 0.0
176                                                 if z is not None:
177                                                         pos.z = 0.0
178                                 elif G == 90:   #Absolute position
179                                         posAbs = True
180                                 elif G == 91:   #Relative position
181                                         posAbs = False
182                                 elif G == 92:
183                                         x = self.getCodeFloat(line, 'X')
184                                         y = self.getCodeFloat(line, 'Y')
185                                         z = self.getCodeFloat(line, 'Z')
186                                         e = self.getCodeFloat(line, 'E')
187                                         if e is not None:
188                                                 currentE = e
189                                         if x is not None:
190                                                 posOffset.x = pos.x + x
191                                         if y is not None:
192                                                 posOffset.y = pos.y + y
193                                         if z is not None:
194                                                 posOffset.z = pos.z + z
195                                 else:
196                                         print "Unknown G code:" + str(G)
197                         else:
198                                 M = self.getCodeInt(line, 'M')
199                                 if M is not None:
200                                         if M == 1:      #Message with possible wait (ignored)
201                                                 pass
202                                         elif M == 84:   #Disable step drivers
203                                                 pass
204                                         elif M == 92:   #Set steps per unit
205                                                 pass
206                                         elif M == 104:  #Set temperature, no wait
207                                                 pass
208                                         elif M == 105:  #Get temperature
209                                                 pass
210                                         elif M == 106:  #Enable fan
211                                                 pass
212                                         elif M == 107:  #Disable fan
213                                                 pass
214                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
215                                                 pass
216                                         elif M == 109:  #Set temperature, wait
217                                                 pass
218                                         elif M == 110:  #Reset N counter
219                                                 pass
220                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
221                                                 pass
222                                         else:
223                                                 print "Unknown M code:" + str(M)
224                 self.layerList.append(currentLayer)
225                 self.extrusionAmount = maxExtrusion
226                 self.totalMoveTimeMinute = totalMoveTimeMinute
227                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
228                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
229
230         def getCodeInt(self, line, code):
231                 if code not in self.regMatch:
232                         self.regMatch[code] = re.compile(code + '([^\s]+)')
233                 m = self.regMatch[code].search(line)
234                 if m == None:
235                         return None
236                 try:
237                         return int(m.group(1))
238                 except:
239                         return None
240
241         def getCodeFloat(self, line, code):
242                 if code not in self.regMatch:
243                         self.regMatch[code] = re.compile(code + '([^\s]+)')
244                 m = self.regMatch[code].search(line)
245                 if m == None:
246                         return None
247                 try:
248                         return float(m.group(1))
249                 except:
250                         return None
251
252 if __name__ == '__main__':
253         for filename in sys.argv[1:]:
254                 gcode().load(filename)
255