chiark / gitweb /
Fix the speed rate modify in the printing interface.
[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 type(line) is tuple:
72                                 line = line[0]
73                         if self.progressCallback != None:
74                                 if filePos != gcodeFile.tell():
75                                         filePos = gcodeFile.tell()
76                                         self.progressCallback(float(filePos) / float(self._fileSize))
77                         
78                         #Parse Cura_SF comments
79                         if line.startswith(';TYPE:'):
80                                 pathType = line[6:].strip()
81                                 if pathType != "CUSTOM":
82                                         startCodeDone = True
83                                         
84                         if ';' in line:
85                                 #Slic3r GCode comment parser
86                                 comment = line[line.find(';')+1:].strip()
87                                 if comment == 'fill':
88                                         pathType = 'FILL'
89                                 elif comment == 'perimeter':
90                                         pathType = 'WALL-INNER'
91                                 elif comment == 'skirt':
92                                         pathType = 'SKIRT'
93                                 if comment.startswith('LAYER:'):
94                                         self.layerList.append(currentLayer)
95                                         currentLayer = []
96                                 if pathType != "CUSTOM":
97                                         startCodeDone = True
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 += (oldPos - pos).vsize() / feedRate
137                                         moveType = 'move'
138                                         if e is not None:
139                                                 if posAbs:
140                                                         if e > currentE:
141                                                                 moveType = 'extrude'
142                                                         if e < currentE:
143                                                                 moveType = 'retract'
144                                                         totalExtrusion += e - currentE
145                                                         currentE = e
146                                                 else:
147                                                         if e > 0:
148                                                                 moveType = 'extrude'
149                                                         if e < 0:
150                                                                 moveType = 'retract'
151                                                         totalExtrusion += e
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                                         currentPath.list.append(newPos)
165                                 elif G == 4:    #Delay
166                                         S = self.getCodeFloat(line, 'S')
167                                         if S is not None:
168                                                 totalMoveTimeMinute += S / 60
169                                         P = self.getCodeFloat(line, 'P')
170                                         if P is not None:
171                                                 totalMoveTimeMinute += P / 60 / 1000
172                                 elif G == 20:   #Units are inches
173                                         scale = 25.4
174                                 elif G == 21:   #Units are mm
175                                         scale = 1.0
176                                 elif G == 28:   #Home
177                                         x = self.getCodeFloat(line, 'X')
178                                         y = self.getCodeFloat(line, 'Y')
179                                         z = self.getCodeFloat(line, 'Z')
180                                         if x is None and y is None and z is None:
181                                                 pos = util3d.Vector3()
182                                         else:
183                                                 if x is not None:
184                                                         pos.x = 0.0
185                                                 if y is not None:
186                                                         pos.y = 0.0
187                                                 if z is not None:
188                                                         pos.z = 0.0
189                                 elif G == 90:   #Absolute position
190                                         posAbs = True
191                                 elif G == 91:   #Relative position
192                                         posAbs = False
193                                 elif G == 92:
194                                         x = self.getCodeFloat(line, 'X')
195                                         y = self.getCodeFloat(line, 'Y')
196                                         z = self.getCodeFloat(line, 'Z')
197                                         e = self.getCodeFloat(line, 'E')
198                                         if e is not None:
199                                                 currentE = e
200                                         if x is not None:
201                                                 posOffset.x = pos.x - x
202                                         if y is not None:
203                                                 posOffset.y = pos.y - y
204                                         if z is not None:
205                                                 posOffset.z = pos.z - z
206                                 else:
207                                         print "Unknown G code:" + str(G)
208                         else:
209                                 M = self.getCodeInt(line, 'M')
210                                 if M is not None:
211                                         if M == 1:      #Message with possible wait (ignored)
212                                                 pass
213                                         elif M == 80:   #Enable power supply
214                                                 pass
215                                         elif M == 81:   #Suicide/disable power supply
216                                                 pass
217                                         elif M == 84:   #Disable step drivers
218                                                 pass
219                                         elif M == 92:   #Set steps per unit
220                                                 pass
221                                         elif M == 104:  #Set temperature, no wait
222                                                 pass
223                                         elif M == 105:  #Get temperature
224                                                 pass
225                                         elif M == 106:  #Enable fan
226                                                 pass
227                                         elif M == 107:  #Disable fan
228                                                 pass
229                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
230                                                 pass
231                                         elif M == 109:  #Set temperature, wait
232                                                 pass
233                                         elif M == 110:  #Reset N counter
234                                                 pass
235                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
236                                                 pass
237                                         elif M == 140:  #Set bed temperature
238                                                 pass
239                                         elif M == 190:  #Set bed temperature & wait
240                                                 pass
241                                         else:
242                                                 print "Unknown M code:" + str(M)
243                 self.layerList.append(currentLayer)
244                 self.extrusionAmount = maxExtrusion
245                 self.totalMoveTimeMinute = totalMoveTimeMinute
246                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
247                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
248
249         def getCodeInt(self, line, code):
250                 if code not in self.regMatch:
251                         self.regMatch[code] = re.compile(code + '([^\s]+)')
252                 m = self.regMatch[code].search(line)
253                 if m == None:
254                         return None
255                 try:
256                         return int(m.group(1))
257                 except:
258                         return None
259
260         def getCodeFloat(self, line, code):
261                 if code not in self.regMatch:
262                         self.regMatch[code] = re.compile(code + '([^\s]+)')
263                 m = self.regMatch[code].search(line)
264                 if m == None:
265                         return None
266                 try:
267                         return float(m.group(1))
268                 except:
269                         return None
270
271 if __name__ == '__main__':
272         for filename in sys.argv[1:]:
273                 gcode().load(filename)
274