CuraEngineBackend.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Backend.Backend import Backend
  4. from UM.Application import Application
  5. from UM.Scene.SceneNode import SceneNode
  6. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  7. from UM.Preferences import Preferences
  8. from UM.Math.Vector import Vector
  9. from UM.Signal import Signal
  10. from UM.Logger import Logger
  11. from UM.Resources import Resources
  12. from UM.Settings.SettingOverrideDecorator import SettingOverrideDecorator
  13. from UM.Message import Message
  14. from cura.OneAtATimeIterator import OneAtATimeIterator
  15. from . import Cura_pb2
  16. from . import ProcessSlicedObjectListJob
  17. from . import ProcessGCodeJob
  18. from . import StartSliceJob
  19. import os
  20. import sys
  21. import numpy
  22. from PyQt5.QtCore import QTimer
  23. from UM.i18n import i18nCatalog
  24. catalog = i18nCatalog("cura")
  25. class CuraEngineBackend(Backend):
  26. def __init__(self):
  27. super().__init__()
  28. # Find out where the engine is located, and how it is called. This depends on how Cura is packaged and which OS we are running on.
  29. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  30. if hasattr(sys, "frozen"):
  31. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  32. if sys.platform == "win32":
  33. default_engine_location += ".exe"
  34. default_engine_location = os.path.abspath(default_engine_location)
  35. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  36. self._scene = Application.getInstance().getController().getScene()
  37. self._scene.sceneChanged.connect(self._onSceneChanged)
  38. # Workaround to disable layer view processing if layer view is not active.
  39. self._layer_view_active = False
  40. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  41. self._onActiveViewChanged()
  42. self._stored_layer_data = None
  43. Application.getInstance().getMachineManager().activeMachineInstanceChanged.connect(self._onChanged)
  44. self._profile = None
  45. Application.getInstance().getMachineManager().activeProfileChanged.connect(self._onActiveProfileChanged)
  46. self._onActiveProfileChanged()
  47. self._change_timer = QTimer()
  48. self._change_timer.setInterval(500)
  49. self._change_timer.setSingleShot(True)
  50. self._change_timer.timeout.connect(self.slice)
  51. self._message_handlers[Cura_pb2.SlicedObjectList] = self._onSlicedObjectListMessage
  52. self._message_handlers[Cura_pb2.Progress] = self._onProgressMessage
  53. self._message_handlers[Cura_pb2.GCodeLayer] = self._onGCodeLayerMessage
  54. self._message_handlers[Cura_pb2.GCodePrefix] = self._onGCodePrefixMessage
  55. self._message_handlers[Cura_pb2.ObjectPrintTime] = self._onObjectPrintTimeMessage
  56. self._slicing = False
  57. self._restart = False
  58. self._enabled = True
  59. self._always_restart = True
  60. self._message = None
  61. self.backendConnected.connect(self._onBackendConnected)
  62. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  63. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  64. Application.getInstance().getMachineManager().activeMachineInstanceChanged.connect(self._onInstanceChanged)
  65. ## Get the command that is used to call the engine.
  66. # This is usefull for debugging and used to actually start the engine
  67. # \return list of commands and args / parameters.
  68. def getEngineCommand(self):
  69. active_machine = Application.getInstance().getMachineManager().getActiveMachineInstance()
  70. if not active_machine:
  71. return None
  72. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", active_machine.getMachineDefinition().getPath(), "-vv"]
  73. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  74. # \param time The amount of time the print will take.
  75. # \param material_amount The amount of material the print will use.
  76. printDurationMessage = Signal()
  77. ## Emitted when the slicing process starts.
  78. slicingStarted = Signal()
  79. ## Emitted whne the slicing process is aborted forcefully.
  80. slicingCancelled = Signal()
  81. ## Perform a slice of the scene.
  82. def slice(self):
  83. if not self._enabled:
  84. return
  85. if self._slicing:
  86. self._slicing = False
  87. self._restart = True
  88. if self._process is not None:
  89. Logger.log("d", "Killing engine process")
  90. try:
  91. self._process.terminate()
  92. except: # terminating a process that is already terminating causes an exception, silently ignore this.
  93. pass
  94. if self._message:
  95. self._message.hide()
  96. self._message = None
  97. self.slicingCancelled.emit()
  98. return
  99. if self._profile.hasErrorValue():
  100. Logger.log("w", "Profile has error values. Aborting slicing")
  101. if self._message:
  102. self._message.hide()
  103. self._message = None
  104. self._message = Message(catalog.i18nc("@info:status", "Unable to slice. Please check your setting values for errors."))
  105. self._message.show()
  106. return #No slicing if we have error values since those are by definition illegal values.
  107. self.processingProgress.emit(0.0)
  108. if not self._message:
  109. self._message = Message(catalog.i18nc("@info:status", "Slicing..."), 0, False, -1)
  110. self._message.show()
  111. else:
  112. self._message.setProgress(-1)
  113. self._scene.gcode_list = []
  114. self._slicing = True
  115. job = StartSliceJob.StartSliceJob(self._profile, self._socket)
  116. job.start()
  117. job.finished.connect(self._onStartSliceCompleted)
  118. def _onStartSliceCompleted(self, job):
  119. if job.getError() or job.getResult() != True:
  120. if self._message:
  121. self._message.hide()
  122. self._message = None
  123. return
  124. def _onSceneChanged(self, source):
  125. if type(source) is not SceneNode:
  126. return
  127. if source is self._scene.getRoot():
  128. return
  129. if source.getMeshData() is None:
  130. return
  131. if source.getMeshData().getVertices() is None:
  132. return
  133. self._onChanged()
  134. def _onActiveProfileChanged(self):
  135. if self._profile:
  136. self._profile.settingValueChanged.disconnect(self._onSettingChanged)
  137. self._profile = Application.getInstance().getMachineManager().getActiveProfile()
  138. if self._profile:
  139. self._profile.settingValueChanged.connect(self._onSettingChanged)
  140. self._onChanged()
  141. def _onSettingChanged(self, setting):
  142. self._onChanged()
  143. def _onSlicedObjectListMessage(self, message):
  144. if self._layer_view_active:
  145. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(message)
  146. job.start()
  147. else :
  148. self._stored_layer_data = message
  149. def _onProgressMessage(self, message):
  150. if self._message:
  151. self._message.setProgress(round(message.amount * 100))
  152. self.processingProgress.emit(message.amount)
  153. def _onGCodeLayerMessage(self, message):
  154. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  155. def _onGCodePrefixMessage(self, message):
  156. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  157. def _onObjectPrintTimeMessage(self, message):
  158. self.printDurationMessage.emit(message.time, message.material_amount)
  159. self.processingProgress.emit(1.0)
  160. self._slicing = False
  161. if self._message:
  162. self._message.setProgress(100)
  163. self._message.hide()
  164. self._message = None
  165. if self._always_restart:
  166. try:
  167. self._process.terminate()
  168. self._createSocket()
  169. except: # terminating a process that is already terminating causes an exception, silently ignore this.
  170. pass
  171. def _createSocket(self):
  172. super()._createSocket()
  173. self._socket.registerMessageType(1, Cura_pb2.Slice)
  174. self._socket.registerMessageType(2, Cura_pb2.SlicedObjectList)
  175. self._socket.registerMessageType(3, Cura_pb2.Progress)
  176. self._socket.registerMessageType(4, Cura_pb2.GCodeLayer)
  177. self._socket.registerMessageType(5, Cura_pb2.ObjectPrintTime)
  178. self._socket.registerMessageType(6, Cura_pb2.SettingList)
  179. self._socket.registerMessageType(7, Cura_pb2.GCodePrefix)
  180. ## Manually triggers a reslice
  181. def forceSlice(self):
  182. self._change_timer.start()
  183. def _onChanged(self):
  184. if not self._profile:
  185. return
  186. self._change_timer.start()
  187. def _onBackendConnected(self):
  188. if self._restart:
  189. self._onChanged()
  190. self._restart = False
  191. def _onToolOperationStarted(self, tool):
  192. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  193. def _onToolOperationStopped(self, tool):
  194. self._enabled = True # Tool stop, start listening for changes again.
  195. self._onChanged()
  196. def _onActiveViewChanged(self):
  197. if Application.getInstance().getController().getActiveView():
  198. view = Application.getInstance().getController().getActiveView()
  199. if view.getPluginId() == "LayerView":
  200. self._layer_view_active = True
  201. if self._stored_layer_data:
  202. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(self._stored_layer_data)
  203. job.start()
  204. self._stored_layer_data = None
  205. else:
  206. self._layer_view_active = False
  207. def _onInstanceChanged(self):
  208. self._slicing = False
  209. self._restart = True
  210. if self._process is not None:
  211. Logger.log("d", "Killing engine process")
  212. try:
  213. self._process.terminate()
  214. except: # terminating a process that is already terminating causes an exception, silently ignore this.
  215. pass
  216. self.slicingCancelled.emit()