chiark / gitweb /
Merge commit '96d014b2c4cef94dbbe4c3adc1c8d7a8ce929ad2'
[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():
13         def __init__(self, newType, pathType, startPoint):
14                 self.type = newType
15                 self.pathType = pathType
16                 self.list = [startPoint]
17
18 class gcode():
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 * float(profile.getPreference('filament_density'))
40         
41         def _load(self, gcodeFile):
42                 filePos = 0
43                 pos = util3d.Vector3()
44                 posOffset = util3d.Vector3()
45                 currentE = 0.0
46                 totalExtrusion = 0.0
47                 maxExtrusion = 0.0
48                 totalMoveTimeMinute = 0.0
49                 scale = 1.0
50                 posAbs = True
51                 feedRate = 3600
52                 pathType = 'CUSTOM';
53                 startCodeDone = False
54                 currentLayer = []
55                 currentPath = gcodePath('move', pathType, pos.copy())
56                 currentPath.list[0].e = totalExtrusion
57                 currentLayer.append(currentPath)
58                 for line in gcodeFile:
59                         if self.progressCallback != None:
60                                 if filePos != gcodeFile.tell():
61                                         filePos = gcodeFile.tell()
62                                         self.progressCallback(float(filePos) / float(self._fileSize))
63                         
64                         #Parse Cura_SF comments
65                         if line.startswith(';TYPE:'):
66                                 pathType = line[6:].strip()
67                                 if pathType != "CUSTOM":
68                                         startCodeDone = True
69                                         
70                         if ';' in line:
71                                 #Slic3r GCode comment parser
72                                 comment = line[line.find(';')+1:].strip()
73                                 if comment == 'fill':
74                                         pathType = 'FILL'
75                                 elif comment == 'perimeter':
76                                         pathType = 'WALL-INNER'
77                                 elif comment == 'skirt':
78                                         pathType = 'SKIRT'
79                                 if pathType != "CUSTOM":
80                                         startCodeDone = True
81                                 line = line[0:line.find(';')]
82                         
83                         G = self.getCodeInt(line, 'G')
84                         if G is not None:
85                                 if G == 0 or G == 1:    #Move
86                                         x = self.getCodeFloat(line, 'X')
87                                         y = self.getCodeFloat(line, 'Y')
88                                         z = self.getCodeFloat(line, 'Z')
89                                         e = self.getCodeFloat(line, 'E')
90                                         f = self.getCodeFloat(line, 'F')
91                                         oldPos = pos.copy()
92                                         if x is not None:
93                                                 if posAbs:
94                                                         pos.x = x * scale
95                                                 else:
96                                                         pos.x += x * scale
97                                         if y is not None:
98                                                 if posAbs:
99                                                         pos.y = y * scale
100                                                 else:
101                                                         pos.y += y * scale
102                                         if z is not None:
103                                                 if posAbs:
104                                                         pos.z = z * scale
105                                                 else:
106                                                         pos.z += z * scale
107                                                 #Check if we have a new layer.
108                                                 if oldPos.z != pos.z and startCodeDone:
109                                                         self.layerList.append(currentLayer)
110                                                         currentLayer = []
111                                         if f is not None:
112                                                 feedRate = f
113                                         if x is not None or y is not None or z is not None:
114                                                 totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate
115                                         moveType = 'move'
116                                         if e is not None:
117                                                 if posAbs:
118                                                         if e > currentE:
119                                                                 moveType = 'extrude'
120                                                         if e < currentE:
121                                                                 moveType = 'retract'
122                                                         totalExtrusion += e - currentE
123                                                         currentE = e
124                                                 else:
125                                                         if e > 0:
126                                                                 moveType = 'extrude'
127                                                         if e < 0:
128                                                                 moveType = 'retract'
129                                                         totalExtrusion += e
130                                                         currentE += e
131                                                 if totalExtrusion > maxExtrusion:
132                                                         maxExtrusion = totalExtrusion
133                                         if currentPath.type != moveType or currentPath.pathType != pathType:
134                                                 currentPath = gcodePath(moveType, pathType, currentPath.list[-1])
135                                                 currentLayer.append(currentPath)
136                                         newPos = pos.copy()
137                                         newPos.e = totalExtrusion
138                                         currentPath.list.append(newPos)
139                                 elif G == 20:   #Units are inches
140                                         scale = 25.4
141                                 elif G == 21:   #Units are mm
142                                         scale = 1.0
143                                 elif G == 28:   #Home
144                                         x = self.getCodeFloat(line, 'X')
145                                         y = self.getCodeFloat(line, 'Y')
146                                         z = self.getCodeFloat(line, 'Z')
147                                         if x is None and y is None and z is None:
148                                                 pos = util3d.Vector3()
149                                         else:
150                                                 if x is not None:
151                                                         pos.x = 0.0
152                                                 if y is not None:
153                                                         pos.y = 0.0
154                                                 if z is not None:
155                                                         pos.z = 0.0
156                                 elif G == 90:   #Absolute position
157                                         posAbs = True
158                                 elif G == 91:   #Relative position
159                                         posAbs = False
160                                 elif G == 92:
161                                         x = self.getCodeFloat(line, 'X')
162                                         y = self.getCodeFloat(line, 'Y')
163                                         z = self.getCodeFloat(line, 'Z')
164                                         e = self.getCodeFloat(line, 'E')
165                                         if e is not None:
166                                                 currentE = e
167                                         if x is not None:
168                                                 posOffset.x = pos.x + x
169                                         if y is not None:
170                                                 posOffset.y = pos.y + y
171                                         if z is not None:
172                                                 posOffset.z = pos.z + z
173                                 else:
174                                         print "Unknown G code:" + str(G)
175                         else:
176                                 M = self.getCodeInt(line, 'M')
177                                 if M is not None:
178                                         if M == 1:      #Message with possible wait (ignored)
179                                                 pass
180                                         elif M == 84:   #Disable step drivers
181                                                 pass
182                                         elif M == 92:   #Set steps per unit
183                                                 pass
184                                         elif M == 104:  #Set temperature, no wait
185                                                 pass
186                                         elif M == 105:  #Get temperature
187                                                 pass
188                                         elif M == 106:  #Enable fan
189                                                 pass
190                                         elif M == 107:  #Disable fan
191                                                 pass
192                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
193                                                 pass
194                                         elif M == 109:  #Set temperature, wait
195                                                 pass
196                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
197                                                 pass
198                                         else:
199                                                 print "Unknown M code:" + str(M)
200                 self.layerList.append(currentLayer)
201                 self.extrusionAmount = maxExtrusion
202                 self.totalMoveTimeMinute = totalMoveTimeMinute
203                 print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
204                 print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
205
206         def getCodeInt(self, line, code):
207                 if code not in self.regMatch:
208                         self.regMatch[code] = re.compile(code + '([^\s]+)')
209                 m = self.regMatch[code].search(line)
210                 if m == None:
211                         return None
212                 try:
213                         return int(m.group(1))
214                 except:
215                         return None
216
217         def getCodeFloat(self, line, code):
218                 if code not in self.regMatch:
219                         self.regMatch[code] = re.compile(code + '([^\s]+)')
220                 m = self.regMatch[code].search(line)
221                 if m == None:
222                         return None
223                 try:
224                         return float(m.group(1))
225                 except:
226                         return None
227
228 if __name__ == '__main__':
229         for filename in sys.argv[1:]:
230                 gcode().load(filename)
231