1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
16 from Cura.util import profile
17 from Cura.util import version
19 def getEngineFilename():
20 if platform.system() == 'Windows':
21 if os.path.exists('C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'):
22 return 'C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'
23 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'CuraEngine.exe'))
24 if hasattr(sys, 'frozen'):
25 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../..', 'CuraEngine'))
26 if os.path.isfile('/usr/bin/CuraEngine'):
27 return '/usr/bin/CuraEngine'
28 if os.path.isfile('/usr/local/bin/CuraEngine'):
29 return '/usr/local/bin/CuraEngine'
30 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'CuraEngine'))
32 def getTempFilename():
33 warnings.simplefilter('ignore')
34 ret = os.tempnam(None, "Cura_Tmp")
35 warnings.simplefilter('default')
39 def __init__(self, progressCallback):
42 self._callback = progressCallback
43 self._binaryStorageFilename = getTempFilename()
44 self._exportFilename = getTempFilename()
45 self._progressSteps = ['inset', 'skin', 'export']
48 self._printTimeSeconds = None
49 self._filamentMM = None
50 self._modelHash = None
56 os.remove(self._binaryStorageFilename)
60 os.remove(self._exportFilename)
64 def abortSlicer(self):
65 if self._process is not None:
67 self._process.terminate()
74 if self._thread is not None:
77 def getGCodeFilename(self):
78 return self._exportFilename
80 def getSliceLog(self):
86 def getFilamentWeight(self):
87 #Calculates the weight of the filament in kg
88 radius = float(profile.getProfileSetting('filament_diameter')) / 2
89 volumeM3 = (self._filamentMM * (math.pi * radius * radius)) / (1000*1000*1000)
90 return volumeM3 * profile.getPreferenceFloat('filament_physical_density')
92 def getFilamentCost(self):
93 cost_kg = profile.getPreferenceFloat('filament_cost_kg')
94 cost_meter = profile.getPreferenceFloat('filament_cost_meter')
95 if cost_kg > 0.0 and cost_meter > 0.0:
96 return "%.2f / %.2f" % (self.getFilamentWeight() * cost_kg, self._filamentMM / 1000.0 * cost_meter)
98 return "%.2f" % (self.getFilamentWeight() * cost_kg)
99 elif cost_meter > 0.0:
100 return "%.2f" % (self._filamentMM / 1000.0 * cost_meter)
103 def getPrintTime(self):
104 if int(self._printTimeSeconds / 60 / 60) < 1:
105 return '%d minutes' % (int(self._printTimeSeconds / 60) % 60)
106 if int(self._printTimeSeconds / 60 / 60) == 1:
107 return '%d hour %d minutes' % (int(self._printTimeSeconds / 60 / 60), int(self._printTimeSeconds / 60) % 60)
108 return '%d hours %d minutes' % (int(self._printTimeSeconds / 60 / 60), int(self._printTimeSeconds / 60) % 60)
110 def getFilamentAmount(self):
111 return '%0.2f meter %0.0f gram' % (float(self._filamentMM) / 1000.0, self.getFilamentWeight() * 1000.0)
113 def runSlicer(self, scene):
115 for obj in scene.objects():
116 if scene.checkPlatform(obj):
117 extruderCount = max(extruderCount, len(obj._meshList))
119 commandList = [getEngineFilename(), '-vv']
120 for k, v in self._engineSettings(extruderCount).iteritems():
121 commandList += ['-s', '%s=%s' % (k, str(v))]
122 commandList += ['-o', self._exportFilename]
123 commandList += ['-b', self._binaryStorageFilename]
125 with open(self._binaryStorageFilename, "wb") as f:
126 hash = hashlib.sha512()
127 order = scene.printOrder()
129 pos = numpy.array(profile.getMachineCenterCoords()) * 1000
130 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1])]
133 for obj in scene.objects():
134 if scene.checkPlatform(obj):
135 for mesh in obj._meshList:
136 vertexTotal += mesh.vertexCount
138 f.write(numpy.array([vertexTotal], numpy.int32).tostring())
139 for obj in scene.objects():
140 if scene.checkPlatform(obj):
141 for mesh in obj._meshList:
142 vertexes = (numpy.matrix(mesh.vertexes, copy = False) * numpy.matrix(obj._matrix, numpy.float32)).getA()
143 vertexes -= obj._drawOffset
144 vertexes += numpy.array([obj.getPosition()[0], obj.getPosition()[1], 0.0])
145 f.write(vertexes.tostring())
146 hash.update(mesh.vertexes.tostring())
152 obj = scene.objects()[n]
153 for mesh in obj._meshList:
154 f.write(numpy.array([mesh.vertexCount], numpy.int32).tostring())
155 s = mesh.vertexes.tostring()
158 pos = obj.getPosition() * 1000
159 pos += numpy.array(profile.getMachineCenterCoords()) * 1000
160 commandList += ['-m', ','.join(map(str, obj._matrix.getA().flatten()))]
161 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1])]
162 commandList += ['#' * len(obj._meshList)]
164 self._modelHash = hash.hexdigest()
165 if self._objCount > 0:
166 self._thread = threading.Thread(target=self._watchProcess, args=(commandList, self._thread))
167 self._thread.daemon = True
170 def _watchProcess(self, commandList, oldThread):
171 if oldThread is not None:
172 if self._process is not None:
173 self._process.terminate()
176 self._callback(-1.0, False)
178 self._process = self._runSliceProcess(commandList)
180 traceback.print_exc()
182 if self._thread != threading.currentThread():
183 self._process.terminate()
184 self._callback(0.0, False)
186 self._printTimeSeconds = None
187 self._filamentMM = None
189 line = self._process.stdout.readline()
193 if line.startswith('Progress:'):
194 line = line.split(':')
195 if line[1] == 'process':
197 elif line[1] in self._progressSteps:
198 progressValue = float(line[2]) / float(line[3])
199 progressValue /= len(self._progressSteps)
200 progressValue += 1.0 / len(self._progressSteps) * self._progressSteps.index(line[1])
202 progressValue /= self._objCount
203 progressValue += 1.0 / self._objCount * objectNr
205 self._callback(progressValue, False)
208 elif line.startswith('Print time:'):
209 self._printTimeSeconds = int(line.split(':')[1].strip())
210 elif line.startswith('Filament:'):
211 self._filamentMM = int(line.split(':')[1].strip())
213 self._sliceLog.append(line.strip())
214 line = self._process.stdout.readline()
215 for line in self._process.stderr:
216 self._sliceLog.append(line.strip())
217 returnCode = self._process.wait()
220 pluginError = profile.runPostProcessingPlugins(self._exportFilename)
221 if pluginError is not None:
223 self._sliceLog.append(pluginError)
224 self._callback(1.0, True)
226 for line in self._sliceLog:
228 self._callback(-1.0, False)
233 def _engineSettings(self, extruderCount):
235 'layerThickness': int(profile.getProfileSettingFloat('layer_height') * 1000),
236 'initialLayerThickness': int(profile.getProfileSettingFloat('bottom_thickness') * 1000) if profile.getProfileSettingFloat('bottom_thickness') > 0.0 else int(profile.getProfileSettingFloat('layer_height') * 1000),
237 'filamentDiameter': int(profile.getProfileSettingFloat('filament_diameter') * 1000),
238 'filamentFlow': int(profile.getProfileSettingFloat('filament_flow')),
239 'extrusionWidth': int(profile.calculateEdgeWidth() * 1000),
240 'insetCount': int(profile.calculateLineCount()),
241 'downSkinCount': int(profile.calculateSolidLayerCount()) if profile.getProfileSetting('solid_bottom') == 'True' else 0,
242 'upSkinCount': int(profile.calculateSolidLayerCount()) if profile.getProfileSetting('solid_top') == 'True' else 0,
243 'sparseInfillLineDistance': int(100 * profile.calculateEdgeWidth() * 1000 / profile.getProfileSettingFloat('fill_density')) if profile.getProfileSettingFloat('fill_density') > 0 else -1,
244 'infillOverlap': int(profile.getProfileSettingFloat('fill_overlap')),
245 'initialSpeedupLayers': int(4),
246 'initialLayerSpeed': int(profile.getProfileSettingFloat('bottom_layer_speed')),
247 'printSpeed': int(profile.getProfileSettingFloat('print_speed')),
248 'infillSpeed': int(profile.getProfileSettingFloat('infill_speed')) if int(profile.getProfileSettingFloat('infill_speed')) > 0 else int(profile.getProfileSettingFloat('print_speed')),
249 'moveSpeed': int(profile.getProfileSettingFloat('travel_speed')),
250 'fanOnLayerNr': int(profile.getProfileSettingFloat('fan_layer')),
251 'fanSpeedMin': int(profile.getProfileSettingFloat('fan_speed')) if profile.getProfileSetting('fan_enabled') == 'True' else 0,
252 'fanSpeedMax': int(profile.getProfileSettingFloat('fan_speed_max')) if profile.getProfileSetting('fan_enabled') == 'True' else 0,
253 'supportAngle': int(-1) if profile.getProfileSetting('support') == 'None' else int(60),
254 'supportEverywhere': int(1) if profile.getProfileSetting('support') == 'Everywhere' else int(0),
255 'supportLineWidth': int(profile.getProfileSettingFloat('support_rate') * profile.calculateEdgeWidth() * 1000 / 100),
256 'supportExtruder': -1 if profile.getProfileSetting('support_dual_extrusion') == 'Both' else (0 if profile.getProfileSetting('support_dual_extrusion') == 'First extruder' else 1),
257 'retractionAmount': int(profile.getProfileSettingFloat('retraction_amount') * 1000) if profile.getProfileSetting('retraction_enable') == 'True' else 0,
258 'retractionSpeed': int(profile.getProfileSettingFloat('retraction_speed')),
259 'retractionMinimalDistance': int(profile.getProfileSettingFloat('retraction_min_travel') * 1000),
260 'retractionAmountExtruderSwitch': int(profile.getProfileSettingFloat('retraction_dual_amount') * 1000),
261 'minimalExtrusionBeforeRetraction': int(profile.getProfileSettingFloat('retraction_minimal_extrusion') * 1000),
262 'enableCombing': 1 if profile.getProfileSetting('retraction_combing') == 'True' else 0,
263 'multiVolumeOverlap': int(profile.getProfileSettingFloat('overlap_dual') * 1000),
264 'objectSink': int(profile.getProfileSettingFloat('object_sink') * 1000),
265 'minimalLayerTime': int(profile.getProfileSettingFloat('cool_min_layer_time')),
266 'minimalFeedrate': int(profile.getProfileSettingFloat('cool_min_feedrate')),
267 'coolHeadLift': 1 if profile.getProfileSetting('cool_head_lift') == 'True' else 0,
268 'startCode': profile.getAlterationFileContents('start.gcode', extruderCount),
269 'endCode': profile.getAlterationFileContents('end.gcode', extruderCount),
271 'extruderOffset[1].X': int(profile.getPreferenceFloat('extruder_offset_x1') * 1000),
272 'extruderOffset[1].Y': int(profile.getPreferenceFloat('extruder_offset_y1') * 1000),
273 'extruderOffset[2].X': int(profile.getPreferenceFloat('extruder_offset_x2') * 1000),
274 'extruderOffset[2].Y': int(profile.getPreferenceFloat('extruder_offset_y2') * 1000),
275 'extruderOffset[3].X': int(profile.getPreferenceFloat('extruder_offset_x3') * 1000),
276 'extruderOffset[3].Y': int(profile.getPreferenceFloat('extruder_offset_y3') * 1000),
279 if profile.getProfileSetting('platform_adhesion') == 'Brim':
280 settings['skirtDistance'] = 0
281 settings['skirtLineCount'] = int(profile.getProfileSettingFloat('brim_line_count'))
282 elif profile.getProfileSetting('platform_adhesion') == 'Raft':
283 settings['skirtDistance'] = 0
284 settings['skirtLineCount'] = 0
285 settings['raftMargin'] = int(profile.getProfileSettingFloat('raft_margin') * 1000)
286 settings['raftBaseThickness'] = int(profile.getProfileSettingFloat('raft_base_thickness') * 1000)
287 settings['raftBaseLinewidth'] = int(profile.getProfileSettingFloat('raft_base_linewidth') * 1000)
288 settings['raftInterfaceThickness'] = int(profile.getProfileSettingFloat('raft_interface_thickness') * 1000)
289 settings['raftInterfaceLinewidth'] = int(profile.getProfileSettingFloat('raft_interface_linewidth') * 1000)
291 settings['skirtDistance'] = int(profile.getProfileSettingFloat('skirt_gap') * 1000)
292 settings['skirtLineCount'] = int(profile.getProfileSettingFloat('skirt_line_count'))
293 settings['skirtMinLenght'] = int(profile.getProfileSettingFloat('skirt_minimal_length') * 1000)
295 if profile.getProfileSetting('fix_horrible_union_all_type_a') == 'True':
296 settings['fixHorrible'] |= 0x01
297 if profile.getProfileSetting('fix_horrible_union_all_type_b') == 'True':
298 settings['fixHorrible'] |= 0x02
299 if profile.getProfileSetting('fix_horrible_use_open_bits') == 'True':
300 settings['fixHorrible'] |= 0x10
301 if profile.getProfileSetting('fix_horrible_extensive_stitching') == 'True':
302 settings['fixHorrible'] |= 0x04
304 if settings['layerThickness'] <= 0:
305 settings['layerThickness'] = 1000
306 if profile.getPreference('gcode_flavor') == 'UltiGCode':
307 settings['gcodeFlavor'] = 1
310 def _runSliceProcess(self, cmdList):
312 if subprocess.mswindows:
313 su = subprocess.STARTUPINFO()
314 su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
315 su.wShowWindow = subprocess.SW_HIDE
316 kwargs['startupinfo'] = su
317 kwargs['creationflags'] = 0x00004000 #BELOW_NORMAL_PRIORITY_CLASS
318 return subprocess.Popen(cmdList, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
320 def submitSliceInfoOnline(self):
321 if profile.getPreference('submit_slice_information') != 'True':
323 if version.isDevVersion():
326 'processor': platform.processor(),
327 'machine': platform.machine(),
328 'platform': platform.platform(),
329 'profile': profile.getGlobalProfileString(),
330 'preferences': profile.getGlobalPreferencesString(),
331 'modelhash': self._modelHash,
332 'version': version.getVersion(),
335 f = urllib2.urlopen("http://www.youmagine.com/curastats/", data = urllib.urlencode(data), timeout = 1)