chiark / gitweb /
Some cleanup and preperation for better packaging.
[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                 self._fileSize = os.stat(filename).st_size
26                 gcodeFile = open(filename, 'r')
27                 self._load(gcodeFile)
28                 gcodeFile.close()
29         
30         def loadList(self, l):
31                 self._load(l)
32         
33         def calculateWeight(self):
34                 #Calculates the weight of the filament in kg
35                 radius = float(profile.getProfileSetting('filament_diameter')) / 2
36                 volumeM3 = (self.extrusionAmount * (math.pi * radius * radius)) / (1000*1000*1000)
37                 return volumeM3 * profile.getPreferenceFloat('filament_density')
38         
39         def calculateCost(self):
40                 cost_kg = profile.getPreferenceFloat('filament_cost_kg')
41                 cost_meter = profile.getPreferenceFloat('filament_cost_meter')
42                 if cost_kg > 0.0 and cost_meter > 0.0:
43                         return "%.2f / %.2f" % (self.calculateWeight() * cost_kg, self.extrusionAmount / 1000 * cost_meter)
44                 elif cost_kg > 0.0:
45                         return "%.2f" % (self.calculateWeight() * cost_kg)
46                 elif cost_meter > 0.0:
47                         return "%.2f" % (self.extrusionAmount / 1000 * cost_meter)
48                 return False
49         
50         def _load(self, gcodeFile):
51                 filePos = 0
52                 pos = util3d.Vector3()
53                 posOffset = util3d.Vector3()
54                 currentE = 0.0
55                 totalExtrusion = 0.0
56                 maxExtrusion = 0.0
57                 currentExtruder = 0
58                 totalMoveTimeMinute = 0.0
59                 scale = 1.0
60                 posAbs = True
61                 feedRate = 3600
62                 layerThickness = 0.1
63                 pathType = 'CUSTOM';
64                 startCodeDone = False
65                 currentLayer = []
66                 currentPath = gcodePath('move', pathType, layerThickness, pos.copy())
67                 currentPath.list[0].e = totalExtrusion
68                 currentLayer.append(currentPath)
69                 for line in gcodeFile:
70                         if self.progressCallback != None:
71                                 if filePos != gcodeFile.tell():
72                                         filePos = gcodeFile.tell()
73                                         self.progressCallback(float(filePos) / float(self._fileSize))
74                         
75                         #Parse Cura_SF comments
76                         if line.startswith(';TYPE:'):
77                                 pathType = line[6:].strip()
78                                 if pathType != "CUSTOM":
79                                         startCodeDone = True
80                                         
81                         if ';' in line:
82                                 #Slic3r GCode comment parser
83                                 comment = line[line.find(';')+1:].strip()
84                                 if comment == 'fill':
85                                         pathType = 'FILL'
86                                 elif comment == 'perimeter':
87                                         pathType = 'WALL-INNER'
88                                 elif comment == 'skirt':
89                                         pathType = 'SKIRT'
90                                 if comment.startswith('LAYER:'):
91                                         self.layerList.append(currentLayer)
92                                         currentLayer = []
93                                 if pathType != "CUSTOM":
94                                         startCodeDone = True
95                                 line = line[0:line.find(';')]
96                         T = self.getCodeInt(line, 'T')
97                         if T is not None:
98                                 if currentExtruder > 0:
99                                         posOffset.x -= profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
100                                         posOffset.y -= profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
101                                 currentExtruder = T
102                                 if currentExtruder > 0:
103                                         posOffset.x += profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
104                                         posOffset.y += profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
105                         
106                         G = self.getCodeInt(line, 'G')
107                         if G is not None:
108                                 if G == 0 or G == 1:    #Move
109                                         x = self.getCodeFloat(line, 'X')
110                                         y = self.getCodeFloat(line, 'Y')
111                                         z = self.getCodeFloat(line, 'Z')
112                                         e = self.getCodeFloat(line, 'E')
113                                         f = self.getCodeFloat(line, 'F')
114                                         oldPos = pos.copy()
115                                         if x is not None:
116                                                 if posAbs:
117                                                         pos.x = x * scale + posOffset.x
118                                                 else:
119                                                         pos.x += x * scale
120                                         if y is not None:
121                                                 if posAbs:
122                                                         pos.y = y * scale + posOffset.y
123                                                 else:
124                                                         pos.y += y * scale
125                                         if z is not None:
126                                                 if posAbs:
127                                                         pos.z = z * scale + posOffset.z
128                                                 else:
129                                                         pos.z += z * scale
130                                         if f is not None:
131                                                 feedRate = f
132                                         if x is not None or y is not None or z is not None:
133                                                 totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate
134                                         moveType = 'move'
135                                         if e is not None:
136                                                 if posAbs:
137                                                         if e > currentE:
138                                                                 moveType = 'extrude'
139                                                         if e < currentE:
140                                                                 moveType = 'retract'
141                                                         totalExtrusion += e - currentE
142                                                         currentE = e
143                                                 else:
144                                                         if e > 0:
145                                                                 moveType = 'extrude'
146                                                         if e < 0:
147                                                                 moveType = 'retract'
148                                                         totalExtrusion += e
149                                                         currentE += e
150                                                 if totalExtrusion > maxExtrusion:
151                                                         maxExtrusion = totalExtrusion
152                                         if moveType == 'move' and oldPos.z != pos.z:
153                                                 layerThickness = abs(oldPos.z - pos.z)
154                                         if currentPath.type != moveType or currentPath.pathType != pathType:
155                                                 currentPath = gcodePath(moveType, pathType, layerThickness, 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