CuraEngineBackend.py 9.8 KB

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