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