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