CuraEngineBackend.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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, BackendState
  4. from UM.Application import Application
  5. from UM.Scene.SceneNode import SceneNode
  6. from UM.Preferences import Preferences
  7. from UM.Signal import Signal
  8. from UM.Logger import Logger
  9. from UM.Message import Message
  10. from UM.PluginRegistry import PluginRegistry
  11. from UM.Resources import Resources
  12. from UM.Settings.Validator import ValidatorState #To find if a setting is in an error state. We can't slice then.
  13. from UM.Platform import Platform
  14. import cura.Settings
  15. from cura.OneAtATimeIterator import OneAtATimeIterator
  16. from . import ProcessSlicedLayersJob
  17. from . import ProcessGCodeJob
  18. from . import StartSliceJob
  19. import os
  20. import sys
  21. from PyQt5.QtCore import QTimer
  22. import Arcus
  23. from UM.i18n import i18nCatalog
  24. catalog = i18nCatalog("cura")
  25. class CuraEngineBackend(Backend):
  26. ## Starts the back-end plug-in.
  27. #
  28. # This registers all the signal listeners and prepares for communication
  29. # with the back-end in general.
  30. def __init__(self):
  31. super().__init__()
  32. # 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.
  33. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  34. if hasattr(sys, "frozen"):
  35. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  36. if Platform.isWindows():
  37. default_engine_location += ".exe"
  38. default_engine_location = os.path.abspath(default_engine_location)
  39. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  40. self._scene = Application.getInstance().getController().getScene()
  41. self._scene.sceneChanged.connect(self._onSceneChanged)
  42. # Workaround to disable layer view processing if layer view is not active.
  43. self._layer_view_active = False
  44. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  45. self._onActiveViewChanged()
  46. self._stored_layer_data = []
  47. self._stored_optimized_layer_data = []
  48. #Triggers for when to (re)start slicing:
  49. self._global_container_stack = None
  50. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  51. self._onGlobalStackChanged()
  52. self._active_extruder_stack = None
  53. cura.Settings.ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
  54. self._onActiveExtruderChanged()
  55. #When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  56. #This timer will group them up, and only slice for the last setting changed signal.
  57. #TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  58. self._change_timer = QTimer()
  59. self._change_timer.setInterval(500)
  60. self._change_timer.setSingleShot(True)
  61. self._change_timer.timeout.connect(self.slice)
  62. #Listeners for receiving messages from the back-end.
  63. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  64. self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
  65. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  66. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  67. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  68. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  69. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  70. self._start_slice_job = None
  71. self._slicing = False #Are we currently slicing?
  72. self._restart = False #Back-end is currently restarting?
  73. self._enabled = True #Should we be slicing? Slicing might be paused when, for instance, the user is dragging the mesh around.
  74. self._always_restart = True #Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  75. self._process_layers_job = None #The currently active job to process layers, or None if it is not processing layers.
  76. self._error_message = None #Pop-up message that shows errors.
  77. self.backendQuit.connect(self._onBackendQuit)
  78. self.backendConnected.connect(self._onBackendConnected)
  79. #When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  80. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  81. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  82. ## Called when closing the application.
  83. #
  84. # This function should terminate the engine process.
  85. def close(self):
  86. # Terminate CuraEngine if it is still running at this point
  87. self._terminate()
  88. super().close()
  89. ## Get the command that is used to call the engine.
  90. # This is useful for debugging and used to actually start the engine.
  91. # \return list of commands and args / parameters.
  92. def getEngineCommand(self):
  93. json_path = Resources.getPath(Resources.DefinitionContainers, "fdmprinter.def.json")
  94. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", json_path, "-vv"]
  95. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  96. # \param time The amount of time the print will take.
  97. # \param material_amount The amount of material the print will use.
  98. printDurationMessage = Signal()
  99. ## Emitted when the slicing process starts.
  100. slicingStarted = Signal()
  101. ## Emitted when the slicing process is aborted forcefully.
  102. slicingCancelled = Signal()
  103. ## Perform a slice of the scene.
  104. def slice(self):
  105. if not self._enabled or not self._global_container_stack: #We shouldn't be slicing.
  106. # try again in a short time
  107. self._change_timer.start()
  108. return
  109. self.printDurationMessage.emit(0, [0])
  110. self._stored_layer_data = []
  111. self._stored_optimized_layer_data = []
  112. if self._slicing: #We were already slicing. Stop the old job.
  113. self._terminate()
  114. if self._process_layers_job: #We were processing layers. Stop that, the layers are going to change soon.
  115. self._process_layers_job.abort()
  116. self._process_layers_job = None
  117. if self._error_message:
  118. self._error_message.hide()
  119. self.processingProgress.emit(0.0)
  120. self.backendStateChange.emit(BackendState.NotStarted)
  121. self._scene.gcode_list = []
  122. self._slicing = True
  123. self.slicingStarted.emit()
  124. slice_message = self._socket.createMessage("cura.proto.Slice")
  125. self._start_slice_job = StartSliceJob.StartSliceJob(slice_message)
  126. self._start_slice_job.start()
  127. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  128. ## Terminate the engine process.
  129. def _terminate(self):
  130. self._slicing = False
  131. self._restart = True
  132. self._stored_layer_data = []
  133. self._stored_optimized_layer_data = []
  134. if self._start_slice_job is not None:
  135. self._start_slice_job.cancel()
  136. self.slicingCancelled.emit()
  137. self.processingProgress.emit(0)
  138. Logger.log("d", "Attempting to kill the engine process")
  139. if self._process is not None:
  140. Logger.log("d", "Killing engine process")
  141. try:
  142. self._process.terminate()
  143. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait())
  144. self._process = None
  145. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  146. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  147. ## Event handler to call when the job to initiate the slicing process is
  148. # completed.
  149. #
  150. # When the start slice job is successfully completed, it will be happily
  151. # slicing. This function handles any errors that may occur during the
  152. # bootstrapping of a slice job.
  153. #
  154. # \param job The start slice job that was just finished.
  155. def _onStartSliceCompleted(self, job):
  156. # Note that cancelled slice jobs can still call this method.
  157. if self._start_slice_job is job:
  158. self._start_slice_job = None
  159. if job.isCancelled() or job.getError() or job.getResult() == StartSliceJob.StartJobResult.Error:
  160. return
  161. if job.getResult() == StartSliceJob.StartJobResult.SettingError:
  162. if Application.getInstance().getPlatformActivity:
  163. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice. Please check your setting values for errors."), lifetime = 10)
  164. self._error_message.show()
  165. self.backendStateChange.emit(BackendState.Error)
  166. else:
  167. self.backendStateChange.emit(BackendState.NotStarted)
  168. return
  169. if job.getResult() == StartSliceJob.StartJobResult.NothingToSlice:
  170. if Application.getInstance().getPlatformActivity:
  171. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice. No suitable objects found."), lifetime = 10)
  172. self._error_message.show()
  173. self.backendStateChange.emit(BackendState.Error)
  174. else:
  175. self.backendStateChange.emit(BackendState.NotStarted)
  176. return
  177. # Preparation completed, send it to the backend.
  178. self._socket.sendMessage(job.getSliceMessage())
  179. ## Listener for when the scene has changed.
  180. #
  181. # This should start a slice if the scene is now ready to slice.
  182. #
  183. # \param source The scene node that was changed.
  184. def _onSceneChanged(self, source):
  185. if type(source) is not SceneNode:
  186. return
  187. if source is self._scene.getRoot():
  188. return
  189. if source.getMeshData() is None:
  190. return
  191. if source.getMeshData().getVertices() is None:
  192. return
  193. self._onChanged()
  194. ## Called when an error occurs in the socket connection towards the engine.
  195. #
  196. # \param error The exception that occurred.
  197. def _onSocketError(self, error):
  198. if Application.getInstance().isShuttingDown():
  199. return
  200. super()._onSocketError(error)
  201. self._terminate()
  202. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  203. Logger.log("e", "A socket error caused the connection to be reset")
  204. ## A setting has changed, so check if we must reslice.
  205. #
  206. # \param instance The setting instance that has changed.
  207. # \param property The property of the setting instance that has changed.
  208. def _onSettingChanged(self, instance, property):
  209. if property == "value": #Only reslice if the value has changed.
  210. self._onChanged()
  211. ## Called when a sliced layer data message is received from the engine.
  212. #
  213. # \param message The protobuf message containing sliced layer data.
  214. def _onLayerMessage(self, message):
  215. self._stored_layer_data.append(message)
  216. ## Called when an optimized sliced layer data message is received from the engine.
  217. #
  218. # \param message The protobuf message containing sliced layer data.
  219. def _onOptimizedLayerMessage(self, message):
  220. self._stored_optimized_layer_data.append(message)
  221. ## Called when a progress message is received from the engine.
  222. #
  223. # \param message The protobuf message containing the slicing progress.
  224. def _onProgressMessage(self, message):
  225. self.processingProgress.emit(message.amount)
  226. self.backendStateChange.emit(BackendState.Processing)
  227. ## Called when the engine sends a message that slicing is finished.
  228. #
  229. # \param message The protobuf message signalling that slicing is finished.
  230. def _onSlicingFinishedMessage(self, message):
  231. self.backendStateChange.emit(BackendState.Done)
  232. self.processingProgress.emit(1.0)
  233. self._slicing = False
  234. if self._layer_view_active and (self._process_layers_job is None or not self._process_layers_job.isRunning()):
  235. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  236. self._process_layers_job.start()
  237. self._stored_optimized_layer_data = []
  238. ## Called when a g-code message is received from the engine.
  239. #
  240. # \param message The protobuf message containing g-code, encoded as UTF-8.
  241. def _onGCodeLayerMessage(self, message):
  242. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  243. ## Called when a g-code prefix message is received from the engine.
  244. #
  245. # \param message The protobuf message containing the g-code prefix,
  246. # encoded as UTF-8.
  247. def _onGCodePrefixMessage(self, message):
  248. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  249. ## Called when a print time message is received from the engine.
  250. #
  251. # \param message The protobuf message containing the print time and
  252. # material amount per extruder
  253. def _onPrintTimeMaterialEstimates(self, message):
  254. material_amounts = []
  255. for index in range(message.repeatedMessageCount("materialEstimates")):
  256. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  257. self.printDurationMessage.emit(message.time, material_amounts)
  258. ## Creates a new socket connection.
  259. def _createSocket(self):
  260. super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
  261. ## Manually triggers a reslice
  262. def forceSlice(self):
  263. self._change_timer.start()
  264. ## Called when anything has changed to the stuff that needs to be sliced.
  265. #
  266. # This indicates that we should probably re-slice soon.
  267. def _onChanged(self, *args, **kwargs):
  268. self._change_timer.start()
  269. ## Called when the back-end connects to the front-end.
  270. def _onBackendConnected(self):
  271. if self._restart:
  272. self._onChanged()
  273. self._restart = False
  274. ## Called when the user starts using some tool.
  275. #
  276. # When the user starts using a tool, we should pause slicing to prevent
  277. # continuously slicing while the user is dragging some tool handle.
  278. #
  279. # \param tool The tool that the user is using.
  280. def _onToolOperationStarted(self, tool):
  281. self._terminate() # Do not continue slicing once a tool has started
  282. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  283. ## Called when the user stops using some tool.
  284. #
  285. # This indicates that we can safely start slicing again.
  286. #
  287. # \param tool The tool that the user was using.
  288. def _onToolOperationStopped(self, tool):
  289. self._enabled = True # Tool stop, start listening for changes again.
  290. ## Called when the user changes the active view mode.
  291. def _onActiveViewChanged(self):
  292. if Application.getInstance().getController().getActiveView():
  293. view = Application.getInstance().getController().getActiveView()
  294. if view.getPluginId() == "LayerView": #If switching to layer view, we should process the layers if that hasn't been done yet.
  295. self._layer_view_active = True
  296. # There is data and we're not slicing at the moment
  297. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  298. if self._stored_optimized_layer_data and not self._slicing:
  299. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  300. self._process_layers_job.start()
  301. self._stored_optimized_layer_data = []
  302. else:
  303. self._layer_view_active = False
  304. ## Called when the back-end self-terminates.
  305. #
  306. # We should reset our state and start listening for new connections.
  307. def _onBackendQuit(self):
  308. if not self._restart and self._process:
  309. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
  310. self._process = None
  311. self._createSocket()
  312. ## Called when the global container stack changes
  313. def _onGlobalStackChanged(self):
  314. if self._global_container_stack:
  315. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  316. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  317. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  318. if self._global_container_stack:
  319. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) #Note: Only starts slicing when the value changed.
  320. self._global_container_stack.containersChanged.connect(self._onChanged)
  321. self._onActiveExtruderChanged()
  322. self._onChanged()
  323. def _onActiveExtruderChanged(self):
  324. if self._active_extruder_stack:
  325. self._active_extruder_stack.propertyChanged.disconnect(self._onSettingChanged)
  326. self._active_extruder_stack.containersChanged.disconnect(self._onChanged)
  327. self._active_extruder_stack = cura.Settings.ExtruderManager.getInstance().getActiveExtruderStack()
  328. if self._active_extruder_stack:
  329. self._active_extruder_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  330. self._active_extruder_stack.containersChanged.connect(self._onChanged)