chiark / gitweb /
Fix for gcode preview, was showing very thin lines because of the new start code.
[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                                                 if oldPos.z > pos.z and abs(oldPos.z - pos.z) > 5.0 and pos.z < 1.0:
155                                                         oldPos.z = 0.0
156                                                 layerThickness = abs(oldPos.z - pos.z)
157                                         if currentPath.type != moveType or currentPath.pathType != pathType:
158                                                 currentPath = gcodePath(moveType, pathType, layerThickness, currentPath.list[-1])
159                                                 currentLayer.append(currentPath)
160                                         newPos = pos.copy()
161                                         newPos.e = totalExtrusion
162                                         currentPath.list.append(newPos)
163                                 elif G == 4:    #Delay
164                                         S = self.getCodeFloat(line, 'S')
165                                         if S is not None:
166                                                 totalMoveTimeMinute += S / 60
167                                         P = self.getCodeFloat(line, 'P')
168                                         if P is not None:
169                                                 totalMoveTimeMinute += P / 60 / 1000
170                                 elif G == 20:   #Units are inches
171                                         scale = 25.4
172                                 elif G == 21:   #Units are mm
173                                         scale = 1.0
174                                 elif G == 28:   #Home
175                                         x = self.getCodeFloat(line, 'X')
176                                         y = self.getCodeFloat(line, 'Y')
177                                         z = self.getCodeFloat(line, 'Z')
178                                         if x is None and y is None and z is None:
179                                                 pos = util3d.Vector3()
180                                         else:
181                                                 if x is not None:
182                                                         pos.x = 0.0
183                                                 if y is not None:
184                                                         pos.y = 0.0
185                                                 if z is not None:
186                                                         pos.z = 0.0
187                                 elif G == 90:   #Absolute position
188                                         posAbs = True
189                                 elif G == 91:   #Relative position
190                                         posAbs = False
191                                 elif G == 92:
192                                         x = self.getCodeFloat(line, 'X')
193                                         y = self.getCodeFloat(line, 'Y')
194                                         z = self.getCodeFloat(line, 'Z')
195                                         e = self.getCodeFloat(line, 'E')
196                                         if e is not None:
197                                                 currentE = e
198                                         if x is not None:
199                                                 posOffset.x = pos.x - x
200                                         if y is not None:
201                                                 posOffset.y = pos.y - y
202                                         if z is not None:
203                                                 posOffset.z = pos.z - z
204                                 else:
205                                         print "Unknown G code:" + str(G)
206                         else:
207                                 M = self.getCodeInt(line, 'M')
208                                 if M is not None:
209                                         if M == 1:      #Message with possible wait (ignored)
210                                                 pass
211                                         elif M == 80:   #Enable power supply
212                                                 pass
213                                         elif M == 81:   #Suicide/disable power supply
214                                                 pass
215                                         elif M == 84:   #Disable step drivers
216                                                 pass
217                                         elif M == 92:   #Set steps per unit
218                                                 pass
219                                         elif M == 104:  #Set temperature, no wait
220                                                 pass
221                                         elif M == 105:  #Get temperature
222                                                 pass
223                                         elif M == 106:  #Enable fan
224                                                 pass
225                                         elif M == 107:  #Disable fan
226                                                 pass
227                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
228                                                 pass
229                                         elif M == 109:  #Set temperature, wait
230                                                 pass
231                                         elif M == 110:  #Reset N counter
232                                                 pass
233                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
234                                                 pass
235                                         elif M == 140:  #Set bed temperature
236                                                 pass
237                                         elif M == 190:  #Set bed temperature & wait
238                                                 pass
239                                         else:
240                                                 print "Unknown M code:" + str(M)
241                 self.layerList.append(currentLayer)
242                 self.extrusionAmount = maxExtrusion
243                 self.totalMoveTimeMinute = totalMoveTimeMinute
244                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
245                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
246
247         def getCodeInt(self, line, code):
248                 if code not in self.regMatch:
249                         self.regMatch[code] = re.compile(code + '([^\s]+)')
250                 m = self.regMatch[code].search(line)
251                 if m == None:
252                         return None
253                 try:
254                         return int(m.group(1))
255                 except:
256                         return None
257
258         def getCodeFloat(self, line, code):
259                 if code not in self.regMatch:
260                         self.regMatch[code] = re.compile(code + '([^\s]+)')
261                 m = self.regMatch[code].search(line)
262                 if m == None:
263                         return None
264                 try:
265                         return float(m.group(1))
266                 except:
267                         return None
268
269 if __name__ == '__main__':
270         for filename in sys.argv[1:]:
271                 gcode().load(filename)
272