12 from Cura.util import profile
14 def getEngineFilename():
15 if platform.system() == 'Windows':
16 if os.path.exists('C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'):
17 return 'C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'
18 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'CuraEngine.exe'))
19 if hasattr(sys, 'frozen'):
20 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../..', 'CuraEngine'))
21 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'CuraEngine'))
23 def getTempFilename():
24 warnings.simplefilter('ignore')
25 ret = os.tempnam(None, "Cura_Tmp")
26 warnings.simplefilter('default')
30 def __init__(self, progressCallback):
33 self._callback = progressCallback
34 self._binaryStorageFilename = getTempFilename()
35 self._exportFilename = getTempFilename()
36 self._progressSteps = ['inset', 'skin', 'export']
39 self._printTimeSeconds = None
40 self._filamentMM = None
45 os.remove(self._binaryStorageFilename)
49 os.remove(self._exportFilename)
53 def abortSlicer(self):
54 if self._process is not None:
56 self._process.terminate()
61 def getGCodeFilename(self):
62 return self._exportFilename
64 def getSliceLog(self):
67 def getFilamentWeight(self):
68 #Calculates the weight of the filament in kg
69 radius = float(profile.getProfileSetting('filament_diameter')) / 2
70 volumeM3 = (self._filamentMM * (math.pi * radius * radius)) / (1000*1000*1000)
71 return volumeM3 * profile.getPreferenceFloat('filament_physical_density')
73 def getFilamentCost(self):
74 cost_kg = profile.getPreferenceFloat('filament_cost_kg')
75 cost_meter = profile.getPreferenceFloat('filament_cost_meter')
76 if cost_kg > 0.0 and cost_meter > 0.0:
77 return "%.2f / %.2f" % (self.getFilamentWeight() * cost_kg, self._filamentMM / 1000.0 * cost_meter)
79 return "%.2f" % (self.getFilamentWeight() * cost_kg)
80 elif cost_meter > 0.0:
81 return "%.2f" % (self._filamentMM / 1000.0 * cost_meter)
84 def getPrintTime(self):
85 return '%02d:%02d' % (int(self._printTimeSeconds / 60 / 60), int(self._printTimeSeconds / 60) % 60)
87 def getFilamentAmount(self):
88 return '%0.2fm %0.0fgram' % (float(self._filamentMM) / 1000.0, self.getFilamentWeight() * 1000.0)
90 def runSlicer(self, scene):
92 self._callback(-1.0, False)
94 commandList = [getEngineFilename(), '-vv']
95 for k, v in self._engineSettings().iteritems():
96 commandList += ['-s', '%s=%s' % (k, str(v))]
97 commandList += ['-o', self._exportFilename]
98 commandList += ['-b', self._binaryStorageFilename]
100 with open(self._binaryStorageFilename, "wb") as f:
101 order = scene.printOrder()
103 pos = numpy.array([profile.getPreferenceFloat('machine_width') * 1000 / 2, profile.getPreferenceFloat('machine_depth') * 1000 / 2])
104 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1])]
107 for obj in scene.objects():
108 if scene.checkPlatform(obj):
109 for mesh in obj._meshList:
110 vertexTotal += mesh.vertexCount
112 f.write(numpy.array([vertexTotal], numpy.int32).tostring())
113 for obj in scene.objects():
114 if scene.checkPlatform(obj):
115 for mesh in obj._meshList:
116 vertexes = (numpy.matrix(mesh.vertexes, copy = False) * numpy.matrix(obj._matrix, numpy.float32)).getA()
117 vertexes -= obj._drawOffset
118 vertexes += numpy.array([obj.getPosition()[0], obj.getPosition()[1], 0.0])
119 f.write(vertexes.tostring())
125 obj = scene.objects()[n]
126 for mesh in obj._meshList:
127 f.write(numpy.array([mesh.vertexCount], numpy.int32).tostring())
128 f.write(mesh.vertexes.tostring())
129 pos = obj.getPosition() * 1000
130 pos += numpy.array([profile.getPreferenceFloat('machine_width') * 1000 / 2, profile.getPreferenceFloat('machine_depth') * 1000 / 2])
131 commandList += ['-m', ','.join(map(str, obj._matrix.getA().flatten()))]
132 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1])]
133 commandList += ['#' * len(obj._meshList)]
135 if self._objCount > 0:
137 self._process = self._runSliceProcess(commandList)
138 self._thread = threading.Thread(target=self._watchProcess)
139 self._thread.daemon = True
142 traceback.print_exc()
144 def _watchProcess(self):
145 self._callback(0.0, False)
147 self._printTimeSeconds = None
148 self._filamentMM = None
150 line = self._process.stdout.readline()
154 if line.startswith('Progress:'):
155 line = line.split(':')
156 if line[1] == 'process':
158 elif line[1] in self._progressSteps:
159 progressValue = float(line[2]) / float(line[3])
160 progressValue /= len(self._progressSteps)
161 progressValue += 1.0 / len(self._progressSteps) * self._progressSteps.index(line[1])
163 progressValue /= self._objCount
164 progressValue += 1.0 / self._objCount * objectNr
166 self._callback(progressValue, False)
169 elif line.startswith('Print time:'):
170 self._printTimeSeconds = int(line.split(':')[1].strip())
171 elif line.startswith('Filament:'):
172 self._filamentMM = int(line.split(':')[1].strip())
174 self._sliceLog.append(line.strip())
175 line = self._process.stdout.readline()
176 for line in self._process.stderr:
177 self._sliceLog.append(line.strip())
178 returnCode = self._process.wait()
181 profile.runPostProcessingPlugins(self._exportFilename)
182 self._callback(1.0, True)
184 self._callback(-1.0, False)
189 def _engineSettings(self):
191 'layerThickness': int(profile.getProfileSettingFloat('layer_height') * 1000),
192 'initialLayerThickness': int(profile.getProfileSettingFloat('bottom_thickness') * 1000) if profile.getProfileSettingFloat('bottom_thickness') > 0.0 else int(profile.getProfileSettingFloat('layer_height') * 1000),
193 'filamentDiameter': int(profile.getProfileSettingFloat('filament_diameter') * 1000),
194 'filamentFlow': int(profile.getProfileSettingFloat('filament_flow')),
195 'extrusionWidth': int(profile.calculateEdgeWidth() * 1000),
196 'insetCount': int(profile.calculateLineCount()),
197 'downSkinCount': int(profile.calculateSolidLayerCount()) if profile.getProfileSetting('solid_bottom') == 'True' else 0,
198 'upSkinCount': int(profile.calculateSolidLayerCount()) if profile.getProfileSetting('solid_top') == 'True' else 0,
199 'sparseInfillLineDistance': int(100 * profile.calculateEdgeWidth() * 1000 / profile.getProfileSettingFloat('fill_density')) if profile.getProfileSettingFloat('fill_density') > 0 else -1,
200 'infillOverlap': int(profile.getProfileSettingFloat('fill_overlap')),
201 'initialSpeedupLayers': int(4),
202 'initialLayerSpeed': int(profile.getProfileSettingFloat('bottom_layer_speed')),
203 'printSpeed': int(profile.getProfileSettingFloat('print_speed')),
204 'infillSpeed': int(profile.getProfileSettingFloat('infill_speed')) if int(profile.getProfileSettingFloat('infill_speed')) > 0 else int(profile.getProfileSettingFloat('print_speed')),
205 'moveSpeed': int(profile.getProfileSettingFloat('travel_speed')),
206 'fanOnLayerNr': int(profile.getProfileSettingFloat('fan_layer')),
207 'fanSpeedMin': int(profile.getProfileSettingFloat('fan_speed')) if profile.getProfileSetting('fan_enabled') == 'True' else 0,
208 'fanSpeedMax': int(profile.getProfileSettingFloat('fan_speed_max')) if profile.getProfileSetting('fan_enabled') == 'True' else 0,
209 'supportAngle': int(-1) if profile.getProfileSetting('support') == 'None' else int(60),
210 'supportEverywhere': int(1) if profile.getProfileSetting('support') == 'Everywhere' else int(0),
211 'supportLineWidth': int(profile.getProfileSettingFloat('support_rate') * profile.calculateEdgeWidth() * 1000 / 100),
212 'retractionAmount': int(profile.getProfileSettingFloat('retraction_amount') * 1000),
213 'retractionSpeed': int(profile.getProfileSettingFloat('retraction_speed')),
214 'objectSink': int(profile.getProfileSettingFloat('object_sink') * 1000),
215 'minimalLayerTime': int(profile.getProfileSettingFloat('cool_min_layer_time')),
216 'minimalFeedrate': int(profile.getProfileSettingFloat('cool_min_feedrate')),
217 'coolHeadLift': 1 if profile.getProfileSetting('cool_head_lift') == 'True' else 0,
218 'startCode': profile.getAlterationFileContents('start.gcode'),
219 'endCode': profile.getAlterationFileContents('end.gcode'),
221 'extruderOffset[1].X': int(profile.getPreferenceFloat('extruder_offset_x1') * 1000),
222 'extruderOffset[1].Y': int(profile.getPreferenceFloat('extruder_offset_y1') * 1000),
223 'extruderOffset[2].X': int(profile.getPreferenceFloat('extruder_offset_x2') * 1000),
224 'extruderOffset[2].Y': int(profile.getPreferenceFloat('extruder_offset_y2') * 1000),
225 'extruderOffset[3].X': int(profile.getPreferenceFloat('extruder_offset_x3') * 1000),
226 'extruderOffset[3].Y': int(profile.getPreferenceFloat('extruder_offset_y3') * 1000),
228 if profile.getProfileSetting('platform_adhesion') == 'Brim':
229 settings['skirtDistance'] = 0
230 settings['skirtLineCount'] = int(profile.getProfileSettingFloat('brim_line_count'))
231 elif profile.getProfileSetting('platform_adhesion') == 'Raft':
232 settings['skirtDistance'] = 0
233 settings['skirtLineCount'] = 0
234 settings['raftMargin'] = int(profile.getProfileSettingFloat('raft_margin') * 1000);
235 settings['raftBaseThickness'] = int(profile.getProfileSettingFloat('raft_base_thickness') * 1000);
236 settings['raftBaseLinewidth'] = int(profile.getProfileSettingFloat('raft_base_linewidth') * 1000);
237 settings['raftInterfaceThickness'] = int(profile.getProfileSettingFloat('raft_interface_thickness') * 1000);
238 settings['raftInterfaceLinewidth'] = int(profile.getProfileSettingFloat('raft_interface_linewidth') * 1000);
240 settings['skirtDistance'] = int(profile.getProfileSettingFloat('skirt_gap') * 1000)
241 settings['skirtLineCount'] = int(profile.getProfileSettingFloat('skirt_line_count'))
242 if settings['layerThickness'] <= 0:
243 settings['layerThickness'] = 1000
246 def _runSliceProcess(self, cmdList):
248 if subprocess.mswindows:
249 su = subprocess.STARTUPINFO()
250 su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
251 su.wShowWindow = subprocess.SW_HIDE
252 kwargs['startupinfo'] = su
253 kwargs['creationflags'] = 0x00004000 #BELOW_NORMAL_PRIORITY_CLASS
254 return subprocess.Popen(cmdList, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)