CuraEngineBackend.py 23 KB

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