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