chiark / gitweb /
Add proper slicing order.
[cura.git] / Cura / util / sliceEngine.py
1 import subprocess
2 import time
3 import numpy
4 import os
5 import warnings
6 import threading
7 import traceback
8
9 from Cura.util import profile
10
11 def getEngineFilename():
12         if os.path.exists('C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'):
13                 return 'C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'
14         return 'SteamEngine'
15
16 def getTempFilename():
17         warnings.simplefilter('ignore')
18         ret = os.tempnam(None, "Cura_Tmp")
19         warnings.simplefilter('default')
20         return ret
21
22 class Slicer(object):
23         def __init__(self, progressCallback):
24                 self._process = None
25                 self._thread = None
26                 self._callback = progressCallback
27                 self._binaryStorageFilename = getTempFilename()
28                 self._exportFilename = getTempFilename()
29                 self._progressSteps = ['inset', 'skin', 'export']
30
31         def abortSlicer(self):
32                 if self._process is not None:
33                         self._process.terminate()
34                         self._thread.join()
35
36         def getGCodeFilename(self):
37                 return self._exportFilename
38
39         def runSlicer(self, scene):
40                 self.abortSlicer()
41                 self._callback(0.0, False)
42
43                 commandList = [getEngineFilename(), '-vv']
44                 for k, v in self._engineSettings().iteritems():
45                         commandList += ['-s', '%s=%s' % (k, str(v))]
46                 commandList += ['-o', self._exportFilename]
47                 commandList += ['-b', self._binaryStorageFilename]
48                 self._objCount = 0
49                 with open(self._binaryStorageFilename, "wb") as f:
50                         for n in scene.printOrder():
51                                 obj = scene.objects()[n]
52                                 for mesh in obj._meshList:
53                                         n = numpy.array(mesh.vertexCount, numpy.int32)
54                                         f.write(n.tostring())
55                                         f.write(mesh.vertexes.tostring())
56                                 pos = obj.getPosition() * 1000
57                                 pos += numpy.array([profile.getPreferenceFloat('machine_width') * 1000 / 2, profile.getPreferenceFloat('machine_depth') * 1000 / 2])
58                                 commandList += ['-m', ','.join(map(str, obj._matrix.getA().flatten()))]
59                                 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1]), '#']
60                                 self._objCount += 1
61                 if self._objCount > 0:
62                         print ' '.join(commandList)
63                         try:
64                                 self._process = self._runSliceProcess(commandList)
65                                 self._thread = threading.Thread(target=self._watchProcess)
66                                 self._thread.daemon = True
67                                 self._thread.start()
68                         except OSError:
69                                 traceback.print_exc()
70
71         def _watchProcess(self):
72                 self._callback(0.0, False)
73                 line = self._process.stdout.readline()
74                 while len(line):
75                         line = line.strip()
76                         if line.startswith('Progress:'):
77                                 line = line.split(':')
78                                 progressValue = float(line[2]) / float(line[3])
79                                 progressValue /= len(self._progressSteps)
80                                 progressValue += 1.0 / len(self._progressSteps) * self._progressSteps.index(line[1])
81                                 self._callback(progressValue, False)
82                         else:
83                                 print '#', line.strip()
84                         line = self._process.stdout.readline()
85                 for line in self._process.stderr:
86                         print line.strip()
87                 returnCode = self._process.wait()
88                 print returnCode
89                 if returnCode == 0:
90                         self._callback(1.0, True)
91                 else:
92                         self._callback(0.0, False)
93                 self._process = None
94
95         def _engineSettings(self):
96                 return {
97                         'layerThickness': int(profile.getProfileSettingFloat('layer_height') * 1000),
98                         'initialLayerThickness': int(profile.getProfileSettingFloat('bottom_thickness') * 1000),
99                         'filamentDiameter': int(profile.getProfileSettingFloat('filament_diameter') * 1000),
100                         'extrusionWidth': int(profile.calculateEdgeWidth() * 1000),
101                         'insetCount': int(profile.calculateLineCount()),
102                         'downSkinCount': int(profile.calculateSolidLayerCount()),
103                         'upSkinCount': int(profile.calculateSolidLayerCount()),
104                         'sparseInfillLineDistance': int(100 * profile.calculateEdgeWidth() * 1000 / profile.getProfileSettingFloat('fill_density')),
105                         'skirtDistance': int(profile.getProfileSettingFloat('skirt_gap') * 1000),
106                         'skirtLineCount': int(profile.getProfileSettingFloat('skirt_line_count')),
107                         'initialSpeedupLayers': int(4),
108                         'initialLayerSpeed': int(profile.getProfileSettingFloat('bottom_layer_speed')),
109                         'printSpeed': int(profile.getProfileSettingFloat('print_speed')),
110                         'moveSpeed': int(profile.getProfileSettingFloat('travel_speed')),
111                         'fanOnLayerNr': int(profile.getProfileSettingFloat('fan_layer')),
112                         'supportAngle': int(-1) if profile.getProfileSetting('support') == 'None' else int(60),
113                         'supportEverywhere': int(1) if profile.getProfileSetting('support') == 'Everywhere' else int(0),
114                         'retractionAmount': int(profile.getProfileSettingFloat('retraction_amount') * 1000),
115                         'retractionSpeed': int(profile.getProfileSettingFloat('retraction_speed')),
116                         'objectSink': int(profile.getProfileSettingFloat('object_sink') * 1000),
117                 }
118
119         def _runSliceProcess(self, cmdList):
120                 kwargs = {}
121                 if subprocess.mswindows:
122                         su = subprocess.STARTUPINFO()
123                         su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
124                         su.wShowWindow = subprocess.SW_HIDE
125                         kwargs['startupinfo'] = su
126                         kwargs['creationflags'] = 0x00004000 #BELOW_NORMAL_PRIORITY_CLASS
127                 return subprocess.Popen(cmdList, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)