CuraEngineBackend.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import argparse #To run the engine in debug mode if the front-end is in debug mode.
  4. from collections import defaultdict
  5. import os
  6. from PyQt5.QtCore import QObject, QTimer, QUrl, pyqtSlot
  7. import sys
  8. from time import time
  9. from typing import Any, cast, Dict, List, Optional, Set, TYPE_CHECKING
  10. from PyQt5.QtGui import QDesktopServices, QImage
  11. from UM.Backend.Backend import Backend, BackendState
  12. from UM.Scene.SceneNode import SceneNode
  13. from UM.Signal import Signal
  14. from UM.Logger import Logger
  15. from UM.Mesh.MeshData import MeshData # For the structure visualization node.
  16. from UM.Message import Message
  17. from UM.PluginRegistry import PluginRegistry
  18. from UM.Platform import Platform
  19. from UM.Qt.Duration import DurationFormat
  20. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  21. from UM.Settings.Interfaces import DefinitionContainerInterface
  22. from UM.Settings.SettingInstance import SettingInstance #For typing.
  23. from UM.Tool import Tool #For typing.
  24. from cura.CuraApplication import CuraApplication
  25. from cura.Settings.ExtruderManager import ExtruderManager
  26. from cura.Snapshot import Snapshot
  27. from cura.Utils.Threading import call_on_qt_thread
  28. from .ProcessSlicedLayersJob import ProcessSlicedLayersJob
  29. from .StartSliceJob import StartSliceJob, StartJobResult
  30. import Arcus
  31. if TYPE_CHECKING:
  32. from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
  33. from cura.Machines.MachineErrorChecker import MachineErrorChecker
  34. from UM.Scene.Scene import Scene
  35. from UM.Settings.ContainerStack import ContainerStack
  36. from UM.i18n import i18nCatalog
  37. catalog = i18nCatalog("cura")
  38. class CuraEngineBackend(QObject, Backend):
  39. backendError = Signal()
  40. def __init__(self) -> None:
  41. """Starts the back-end plug-in.
  42. This registers all the signal listeners and prepares for communication
  43. with the back-end in general.
  44. CuraEngineBackend is exposed to qml as well.
  45. """
  46. super().__init__()
  47. # Find out where the engine is located, and how it is called.
  48. # This depends on how Cura is packaged and which OS we are running on.
  49. executable_name = "CuraEngine"
  50. if Platform.isWindows():
  51. executable_name += ".exe"
  52. default_engine_location = executable_name
  53. search_path = [
  54. os.path.abspath(os.path.dirname(sys.executable)),
  55. os.path.abspath(os.path.join(os.path.dirname(sys.executable), "bin")),
  56. os.path.abspath(os.path.join(os.path.dirname(sys.executable), "..")),
  57. os.path.join(CuraApplication.getInstallPrefix(), "bin"),
  58. os.path.dirname(os.path.abspath(sys.executable)),
  59. ]
  60. for path in search_path:
  61. engine_path = os.path.join(path, executable_name)
  62. if os.path.isfile(engine_path):
  63. default_engine_location = engine_path
  64. break
  65. if Platform.isLinux() and not default_engine_location:
  66. if not os.getenv("PATH"):
  67. raise OSError("There is something wrong with your Linux installation.")
  68. for pathdir in cast(str, os.getenv("PATH")).split(os.pathsep):
  69. execpath = os.path.join(pathdir, executable_name)
  70. if os.path.exists(execpath):
  71. default_engine_location = execpath
  72. break
  73. application = CuraApplication.getInstance() #type: CuraApplication
  74. self._multi_build_plate_model = None #type: Optional[MultiBuildPlateModel]
  75. self._machine_error_checker = None #type: Optional[MachineErrorChecker]
  76. if not default_engine_location:
  77. raise EnvironmentError("Could not find CuraEngine")
  78. Logger.log("i", "Found CuraEngine at: %s", default_engine_location)
  79. default_engine_location = os.path.abspath(default_engine_location)
  80. application.getPreferences().addPreference("backend/location", default_engine_location)
  81. # Workaround to disable layer view processing if layer view is not active.
  82. self._layer_view_active = False #type: bool
  83. self._onActiveViewChanged()
  84. self._stored_layer_data = [] # type: List[Arcus.PythonMessage]
  85. self._stored_optimized_layer_data = {} # type: Dict[int, List[Arcus.PythonMessage]] # key is build plate number, then arrays are stored until they go to the ProcessSlicesLayersJob
  86. self._scene = application.getController().getScene() #type: Scene
  87. self._scene.sceneChanged.connect(self._onSceneChanged)
  88. # Triggers for auto-slicing. Auto-slicing is triggered as follows:
  89. # - auto-slicing is started with a timer
  90. # - whenever there is a value change, we start the timer
  91. # - sometimes an error check can get scheduled for a value change, in that case, we ONLY want to start the
  92. # auto-slicing timer when that error check is finished
  93. # If there is an error check, stop the auto-slicing timer, and only wait for the error check to be finished
  94. # to start the auto-slicing timer again.
  95. #
  96. self._global_container_stack = None #type: Optional[ContainerStack]
  97. # Listeners for receiving messages from the back-end.
  98. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  99. self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
  100. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  101. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  102. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  103. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  104. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  105. self._message_handlers["cura.proto.StructurePolygon"] = self._onStructurePolygonMessage
  106. self._start_slice_job = None #type: Optional[StartSliceJob]
  107. self._start_slice_job_build_plate = None #type: Optional[int]
  108. self._slicing = False #type: bool # Are we currently slicing?
  109. self._restart = False #type: bool # Back-end is currently restarting?
  110. self._tool_active = False #type: bool # If a tool is active, some tasks do not have to do anything
  111. self._always_restart = True #type: bool # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  112. self._process_layers_job = None #type: Optional[ProcessSlicedLayersJob] # The currently active job to process layers, or None if it is not processing layers.
  113. self._build_plates_to_be_sliced = [] #type: List[int] # what needs slicing?
  114. self._engine_is_fresh = True #type: bool # Is the newly started engine used before or not?
  115. self._backend_log_max_lines = 20000 #type: int # Maximum number of lines to buffer
  116. self._error_message = None #type: Optional[Message] # Pop-up message that shows errors.
  117. self._last_num_objects = defaultdict(int) #type: Dict[int, int] # Count number of objects to see if there is something changed
  118. self._postponed_scene_change_sources = [] #type: List[SceneNode] # scene change is postponed (by a tool)
  119. self._structure_vis_node = None # type: Optional[SceneNode] # Node to store structure visualizations in.
  120. self._slice_start_time = None #type: Optional[float]
  121. self._is_disabled = False #type: bool
  122. application.getPreferences().addPreference("general/auto_slice", False)
  123. self._use_timer = False #type: bool
  124. # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  125. # This timer will group them up, and only slice for the last setting changed signal.
  126. # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  127. self._change_timer = QTimer() #type: QTimer
  128. self._change_timer.setSingleShot(True)
  129. self._change_timer.setInterval(500)
  130. self.determineAutoSlicing()
  131. application.getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  132. self._slicing_error_message = Message(
  133. text = catalog.i18nc("@message", "Slicing failed with an unexpected error. Please consider reporting a bug on our issue tracker."),
  134. title = catalog.i18nc("@message:title", "Slicing failed"),
  135. message_type = Message.MessageType.ERROR
  136. )
  137. self._slicing_error_message.addAction(
  138. action_id = "report_bug",
  139. name = catalog.i18nc("@message:button", "Report a bug"),
  140. description = catalog.i18nc("@message:description", "Report a bug on Ultimaker Cura's issue tracker."),
  141. icon = "[no_icon]"
  142. )
  143. self._slicing_error_message.actionTriggered.connect(self._reportBackendError)
  144. self._snapshot = None #type: Optional[QImage]
  145. application.initializationFinished.connect(self.initialize)
  146. def initialize(self) -> None:
  147. application = CuraApplication.getInstance()
  148. self._multi_build_plate_model = application.getMultiBuildPlateModel()
  149. application.getController().activeViewChanged.connect(self._onActiveViewChanged)
  150. if self._multi_build_plate_model:
  151. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveViewChanged)
  152. application.getMachineManager().globalContainerChanged.connect(self._onGlobalStackChanged)
  153. self._onGlobalStackChanged()
  154. # extruder enable / disable. Actually wanted to use machine manager here, but the initialization order causes it to crash
  155. ExtruderManager.getInstance().extrudersChanged.connect(self._extruderChanged)
  156. self.backendQuit.connect(self._onBackendQuit)
  157. self.backendConnected.connect(self._onBackendConnected)
  158. # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  159. application.getController().toolOperationStarted.connect(self._onToolOperationStarted)
  160. application.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  161. self._machine_error_checker = application.getMachineErrorChecker()
  162. self._machine_error_checker.errorCheckFinished.connect(self._onStackErrorCheckFinished)
  163. def close(self) -> None:
  164. """Terminate the engine process.
  165. This function should terminate the engine process.
  166. Called when closing the application.
  167. """
  168. # Terminate CuraEngine if it is still running at this point
  169. self._terminate()
  170. def getEngineCommand(self) -> List[str]:
  171. """Get the command that is used to call the engine.
  172. This is useful for debugging and used to actually start the engine.
  173. :return: list of commands and args / parameters.
  174. """
  175. command = [CuraApplication.getInstance().getPreferences().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), ""]
  176. parser = argparse.ArgumentParser(prog = "cura", add_help = False)
  177. parser.add_argument("--debug", action = "store_true", default = False, help = "Turn on the debug mode by setting this option.")
  178. known_args = vars(parser.parse_known_args()[0])
  179. if known_args["debug"]:
  180. command.append("-vvv")
  181. return command
  182. printDurationMessage = Signal()
  183. """Emitted when we get a message containing print duration and material amount.
  184. This also implies the slicing has finished.
  185. :param time: The amount of time the print will take.
  186. :param material_amount: The amount of material the print will use.
  187. """
  188. slicingStarted = Signal()
  189. """Emitted when the slicing process starts."""
  190. slicingCancelled = Signal()
  191. """Emitted when the slicing process is aborted forcefully."""
  192. @pyqtSlot()
  193. def stopSlicing(self) -> None:
  194. self.setState(BackendState.NotStarted)
  195. if self._slicing: # We were already slicing. Stop the old job.
  196. self._terminate()
  197. self._createSocket()
  198. if self._process_layers_job is not None: # We were processing layers. Stop that, the layers are going to change soon.
  199. Logger.log("i", "Aborting process layers job...")
  200. self._process_layers_job.abort()
  201. self._process_layers_job = None
  202. if self._error_message:
  203. self._error_message.hide()
  204. @pyqtSlot()
  205. def forceSlice(self) -> None:
  206. """Manually triggers a reslice"""
  207. self.markSliceAll()
  208. self.slice()
  209. @call_on_qt_thread # must be called from the main thread because of OpenGL
  210. def _createSnapshot(self) -> None:
  211. self._snapshot = None
  212. if not CuraApplication.getInstance().isVisible:
  213. Logger.log("w", "Can't create snapshot when renderer not initialized.")
  214. return
  215. Logger.log("i", "Creating thumbnail image (just before slice)...")
  216. try:
  217. self._snapshot = Snapshot.snapshot(width = 300, height = 300)
  218. except:
  219. Logger.logException("w", "Failed to create snapshot image")
  220. self._snapshot = None # Failing to create thumbnail should not fail creation of UFP
  221. def getLatestSnapshot(self) -> Optional[QImage]:
  222. return self._snapshot
  223. def slice(self) -> None:
  224. """Perform a slice of the scene."""
  225. self._createSnapshot()
  226. Logger.log("i", "Starting to slice...")
  227. self._slice_start_time = time()
  228. if not self._build_plates_to_be_sliced:
  229. self.processingProgress.emit(1.0)
  230. Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
  231. self.setState(BackendState.Done)
  232. return
  233. if self._process_layers_job:
  234. Logger.log("d", "Process layers job still busy, trying later.")
  235. return
  236. if not hasattr(self._scene, "gcode_dict"):
  237. self._scene.gcode_dict = {} #type: ignore #Because we are creating the missing attribute here.
  238. # Recreate structure visualization node.
  239. if self._structure_vis_node:
  240. self._scene.getRoot().removeChild(self._structure_vis_node)
  241. self._structure_vis_node = SceneNode()
  242. self._structure_vis_node.setId("structure_visualization")
  243. self._structure_vis_node.setMeshData(MeshData())
  244. self._scene.getRoot().addChild(self._structure_vis_node)
  245. # see if we really have to slice
  246. application = CuraApplication.getInstance()
  247. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  248. build_plate_to_be_sliced = self._build_plates_to_be_sliced.pop(0)
  249. Logger.log("d", "Going to slice build plate [%s]!" % build_plate_to_be_sliced)
  250. num_objects = self._numObjectsPerBuildPlate()
  251. self._stored_layer_data = []
  252. if build_plate_to_be_sliced not in num_objects or num_objects[build_plate_to_be_sliced] == 0:
  253. self._scene.gcode_dict[build_plate_to_be_sliced] = [] #type: ignore #Because we created this attribute above.
  254. Logger.log("d", "Build plate %s has no objects to be sliced, skipping", build_plate_to_be_sliced)
  255. if self._build_plates_to_be_sliced:
  256. self.slice()
  257. return
  258. self._stored_optimized_layer_data[build_plate_to_be_sliced] = []
  259. if application.getPrintInformation() and build_plate_to_be_sliced == active_build_plate:
  260. application.getPrintInformation().setToZeroPrintInformation(build_plate_to_be_sliced)
  261. if self._process is None: # type: ignore
  262. self._createSocket()
  263. self.stopSlicing()
  264. self._engine_is_fresh = False # Yes we're going to use the engine
  265. self.processingProgress.emit(0.0)
  266. self.backendStateChange.emit(BackendState.NotStarted)
  267. self._scene.gcode_dict[build_plate_to_be_sliced] = [] #type: ignore #[] indexed by build plate number
  268. self._slicing = True
  269. self.slicingStarted.emit()
  270. self.determineAutoSlicing() # Switch timer on or off if appropriate
  271. slice_message = self._socket.createMessage("cura.proto.Slice")
  272. self._start_slice_job = StartSliceJob(slice_message)
  273. self._start_slice_job_build_plate = build_plate_to_be_sliced
  274. self._start_slice_job.setBuildPlate(self._start_slice_job_build_plate)
  275. self._start_slice_job.start()
  276. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  277. def _terminate(self) -> None:
  278. """Terminate the engine process.
  279. Start the engine process by calling _createSocket()
  280. """
  281. self._slicing = False
  282. self._stored_layer_data = []
  283. if self._start_slice_job_build_plate in self._stored_optimized_layer_data:
  284. del self._stored_optimized_layer_data[self._start_slice_job_build_plate]
  285. if self._start_slice_job is not None:
  286. self._start_slice_job.cancel()
  287. self.slicingCancelled.emit()
  288. self.processingProgress.emit(0)
  289. Logger.log("d", "Attempting to kill the engine process")
  290. if CuraApplication.getInstance().getUseExternalBackend():
  291. return
  292. if self._process is not None: # type: ignore
  293. Logger.log("d", "Killing engine process")
  294. try:
  295. self._process.terminate() # type: ignore
  296. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait()) # type: ignore
  297. self._process = None # type: ignore
  298. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  299. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  300. def _onStartSliceCompleted(self, job: StartSliceJob) -> None:
  301. """Event handler to call when the job to initiate the slicing process is
  302. completed.
  303. When the start slice job is successfully completed, it will be happily
  304. slicing. This function handles any errors that may occur during the
  305. bootstrapping of a slice job.
  306. :param job: The start slice job that was just finished.
  307. """
  308. if self._error_message:
  309. self._error_message.hide()
  310. # Note that cancelled slice jobs can still call this method.
  311. if self._start_slice_job is job:
  312. self._start_slice_job = None
  313. if job.isCancelled() or job.getError() or job.getResult() == StartJobResult.Error:
  314. self.setState(BackendState.Error)
  315. self.backendError.emit(job)
  316. return
  317. application = CuraApplication.getInstance()
  318. if job.getResult() == StartJobResult.MaterialIncompatible:
  319. if application.platformActivity:
  320. self._error_message = Message(catalog.i18nc("@info:status",
  321. "Unable to slice with the current material as it is incompatible with the selected machine or configuration."),
  322. title = catalog.i18nc("@info:title", "Unable to slice"),
  323. message_type = Message.MessageType.WARNING)
  324. self._error_message.show()
  325. self.setState(BackendState.Error)
  326. self.backendError.emit(job)
  327. else:
  328. self.setState(BackendState.NotStarted)
  329. return
  330. if job.getResult() == StartJobResult.SettingError:
  331. if application.platformActivity:
  332. if not self._global_container_stack:
  333. Logger.log("w", "Global container stack not assigned to CuraEngineBackend!")
  334. return
  335. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  336. error_keys = [] #type: List[str]
  337. for extruder in extruders:
  338. error_keys.extend(extruder.getErrorKeys())
  339. if not extruders:
  340. error_keys = self._global_container_stack.getErrorKeys()
  341. error_labels = set()
  342. for key in error_keys:
  343. for stack in [self._global_container_stack] + extruders: #Search all container stacks for the definition of this setting. Some are only in an extruder stack.
  344. definitions = cast(DefinitionContainerInterface, stack.getBottom()).findDefinitions(key = key)
  345. if definitions:
  346. break #Found it! No need to continue search.
  347. else: #No stack has a definition for this setting.
  348. Logger.log("w", "When checking settings for errors, unable to find definition for key: {key}".format(key = key))
  349. continue
  350. error_labels.add(definitions[0].label)
  351. self._error_message = Message(catalog.i18nc("@info:status",
  352. "Unable to slice with the current settings. The following settings have errors: {0}").format(", ".join(error_labels)),
  353. title = catalog.i18nc("@info:title", "Unable to slice"),
  354. message_type = Message.MessageType.WARNING)
  355. Logger.warning(f"Unable to slice with the current settings. The following settings have errors: {', '.join(error_labels)}")
  356. self._error_message.show()
  357. self.setState(BackendState.Error)
  358. self.backendError.emit(job)
  359. else:
  360. self.setState(BackendState.NotStarted)
  361. return
  362. elif job.getResult() == StartJobResult.ObjectSettingError:
  363. errors = {}
  364. for node in DepthFirstIterator(application.getController().getScene().getRoot()):
  365. stack = node.callDecoration("getStack")
  366. if not stack:
  367. continue
  368. for key in stack.getErrorKeys():
  369. if not self._global_container_stack:
  370. Logger.log("e", "CuraEngineBackend does not have global_container_stack assigned.")
  371. continue
  372. definition = cast(DefinitionContainerInterface, self._global_container_stack.getBottom()).findDefinitions(key = key)
  373. if not definition:
  374. Logger.log("e", "When checking settings for errors, unable to find definition for key {key} in per-object stack.".format(key = key))
  375. continue
  376. errors[key] = definition[0].label
  377. self._error_message = Message(catalog.i18nc("@info:status",
  378. "Unable to slice due to some per-model settings. The following settings have errors on one or more models: {error_labels}").format(error_labels = ", ".join(errors.values())),
  379. title = catalog.i18nc("@info:title", "Unable to slice"),
  380. message_type = Message.MessageType.WARNING)
  381. Logger.warning(f"Unable to slice due to per-object settings. The following settings have errors on one or more models: {', '.join(errors.values())}")
  382. self._error_message.show()
  383. self.setState(BackendState.Error)
  384. self.backendError.emit(job)
  385. return
  386. if job.getResult() == StartJobResult.BuildPlateError:
  387. if application.platformActivity:
  388. self._error_message = Message(catalog.i18nc("@info:status",
  389. "Unable to slice because the prime tower or prime position(s) are invalid."),
  390. title = catalog.i18nc("@info:title", "Unable to slice"),
  391. message_type = Message.MessageType.WARNING)
  392. self._error_message.show()
  393. self.setState(BackendState.Error)
  394. self.backendError.emit(job)
  395. return
  396. else:
  397. self.setState(BackendState.NotStarted)
  398. if job.getResult() == StartJobResult.ObjectsWithDisabledExtruder:
  399. self._error_message = Message(catalog.i18nc("@info:status",
  400. "Unable to slice because there are objects associated with disabled Extruder %s.") % job.getMessage(),
  401. title = catalog.i18nc("@info:title", "Unable to slice"),
  402. message_type = Message.MessageType.WARNING)
  403. self._error_message.show()
  404. self.setState(BackendState.Error)
  405. self.backendError.emit(job)
  406. return
  407. if job.getResult() == StartJobResult.NothingToSlice:
  408. if application.platformActivity:
  409. self._error_message = Message(catalog.i18nc("@info:status", "Please review settings and check if your models:"
  410. "\n- Fit within the build volume"
  411. "\n- Are assigned to an enabled extruder"
  412. "\n- Are not all set as modifier meshes"),
  413. title = catalog.i18nc("@info:title", "Unable to slice"),
  414. message_type = Message.MessageType.WARNING)
  415. self._error_message.show()
  416. self.setState(BackendState.Error)
  417. self.backendError.emit(job)
  418. else:
  419. self.setState(BackendState.NotStarted)
  420. self._invokeSlice()
  421. return
  422. # Preparation completed, send it to the backend.
  423. self._socket.sendMessage(job.getSliceMessage())
  424. # Notify the user that it's now up to the backend to do it's job
  425. self.setState(BackendState.Processing)
  426. if self._slice_start_time:
  427. Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
  428. def determineAutoSlicing(self) -> bool:
  429. """Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  430. It disables when:
  431. - preference auto slice is off
  432. - decorator isBlockSlicing is found (used in g-code reader)
  433. """
  434. enable_timer = True
  435. self._is_disabled = False
  436. if not CuraApplication.getInstance().getPreferences().getValue("general/auto_slice"):
  437. enable_timer = False
  438. for node in DepthFirstIterator(self._scene.getRoot()):
  439. if node.callDecoration("isBlockSlicing"):
  440. enable_timer = False
  441. self.setState(BackendState.Disabled)
  442. self._is_disabled = True
  443. gcode_list = node.callDecoration("getGCodeList")
  444. if gcode_list is not None:
  445. self._scene.gcode_dict[node.callDecoration("getBuildPlateNumber")] = gcode_list #type: ignore #Because we generate this attribute dynamically.
  446. if self._use_timer == enable_timer:
  447. return self._use_timer
  448. if enable_timer:
  449. self.setState(BackendState.NotStarted)
  450. self.enableTimer()
  451. return True
  452. else:
  453. self.disableTimer()
  454. return False
  455. def _numObjectsPerBuildPlate(self) -> Dict[int, int]:
  456. """Return a dict with number of objects per build plate"""
  457. num_objects = defaultdict(int) #type: Dict[int, int]
  458. for node in DepthFirstIterator(self._scene.getRoot()):
  459. # Only count sliceable objects
  460. if node.callDecoration("isSliceable"):
  461. build_plate_number = node.callDecoration("getBuildPlateNumber")
  462. if build_plate_number is not None:
  463. num_objects[build_plate_number] += 1
  464. return num_objects
  465. def _onSceneChanged(self, source: SceneNode) -> None:
  466. """Listener for when the scene has changed.
  467. This should start a slice if the scene is now ready to slice.
  468. :param source: The scene node that was changed.
  469. """
  470. if not source.callDecoration("isSliceable") and source != self._scene.getRoot():
  471. return
  472. # This case checks if the source node is a node that contains GCode. In this case the
  473. # current layer data is removed so the previous data is not rendered - CURA-4821
  474. if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"):
  475. self._stored_optimized_layer_data = {}
  476. build_plate_changed = set()
  477. source_build_plate_number = source.callDecoration("getBuildPlateNumber")
  478. if source == self._scene.getRoot():
  479. # we got the root node
  480. num_objects = self._numObjectsPerBuildPlate()
  481. for build_plate_number in list(self._last_num_objects.keys()) + list(num_objects.keys()):
  482. if build_plate_number not in self._last_num_objects or num_objects[build_plate_number] != self._last_num_objects[build_plate_number]:
  483. self._last_num_objects[build_plate_number] = num_objects[build_plate_number]
  484. build_plate_changed.add(build_plate_number)
  485. else:
  486. # we got a single scenenode
  487. if not source.callDecoration("isGroup"):
  488. mesh_data = source.getMeshData()
  489. if mesh_data is None or mesh_data.getVertices() is None:
  490. return
  491. # There are some SceneNodes that do not have any build plate associated, then do not add to the list.
  492. if source_build_plate_number is not None:
  493. build_plate_changed.add(source_build_plate_number)
  494. if not build_plate_changed:
  495. return
  496. if self._tool_active:
  497. # do it later, each source only has to be done once
  498. if source not in self._postponed_scene_change_sources:
  499. self._postponed_scene_change_sources.append(source)
  500. return
  501. self.stopSlicing()
  502. for build_plate_number in build_plate_changed:
  503. if build_plate_number not in self._build_plates_to_be_sliced:
  504. self._build_plates_to_be_sliced.append(build_plate_number)
  505. self.printDurationMessage.emit(source_build_plate_number, {}, [])
  506. self.processingProgress.emit(0.0)
  507. self._clearLayerData(build_plate_changed)
  508. self._invokeSlice()
  509. def _onSocketError(self, error: Arcus.Error) -> None:
  510. """Called when an error occurs in the socket connection towards the engine.
  511. :param error: The exception that occurred.
  512. """
  513. if CuraApplication.getInstance().isShuttingDown():
  514. return
  515. super()._onSocketError(error)
  516. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  517. return
  518. self._terminate()
  519. self._createSocket()
  520. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  521. Logger.log("w", "A socket error caused the connection to be reset")
  522. # _terminate()' function sets the job status to 'cancel', after reconnecting to another Port the job status
  523. # needs to be updated. Otherwise backendState is "Unable To Slice"
  524. if error.getErrorCode() == Arcus.ErrorCode.BindFailedError and self._start_slice_job is not None:
  525. self._start_slice_job.setIsCancelled(False)
  526. # Check if there's any slicable object in the scene.
  527. def hasSlicableObject(self) -> bool:
  528. has_slicable = False
  529. for node in DepthFirstIterator(self._scene.getRoot()):
  530. if node.callDecoration("isSliceable"):
  531. has_slicable = True
  532. break
  533. return has_slicable
  534. def _clearLayerData(self, build_plate_numbers: Set = None) -> None:
  535. """Remove old layer data (if any)"""
  536. # Clear out any old gcode
  537. self._scene.gcode_dict = {} # type: ignore
  538. for node in DepthFirstIterator(self._scene.getRoot()):
  539. if node.callDecoration("getLayerData"):
  540. if not build_plate_numbers or node.callDecoration("getBuildPlateNumber") in build_plate_numbers:
  541. # We can assume that all nodes have a parent as we're looping through the scene (and filter out root)
  542. cast(SceneNode, node.getParent()).removeChild(node)
  543. def markSliceAll(self) -> None:
  544. for build_plate_number in range(CuraApplication.getInstance().getMultiBuildPlateModel().maxBuildPlate + 1):
  545. if build_plate_number not in self._build_plates_to_be_sliced:
  546. self._build_plates_to_be_sliced.append(build_plate_number)
  547. def needsSlicing(self) -> None:
  548. """Convenient function: mark everything to slice, emit state and clear layer data"""
  549. # CURA-6604: If there's no slicable object, do not (try to) trigger slice, which will clear all the current
  550. # gcode. This can break Gcode file loading if it tries to remove it afterwards.
  551. if not self.hasSlicableObject():
  552. return
  553. self.determineAutoSlicing()
  554. self.stopSlicing()
  555. self.markSliceAll()
  556. self.processingProgress.emit(0.0)
  557. if not self._use_timer:
  558. # With manually having to slice, we want to clear the old invalid layer data.
  559. self._clearLayerData()
  560. def _onSettingChanged(self, instance: SettingInstance, property: str) -> None:
  561. """A setting has changed, so check if we must reslice.
  562. :param instance: The setting instance that has changed.
  563. :param property: The property of the setting instance that has changed.
  564. """
  565. if property == "value": # Only reslice if the value has changed.
  566. self.needsSlicing()
  567. self._onChanged()
  568. elif property == "validationState":
  569. if self._use_timer:
  570. self._change_timer.stop()
  571. def _onStackErrorCheckFinished(self) -> None:
  572. self.determineAutoSlicing()
  573. if self._is_disabled:
  574. return
  575. if not self._slicing and self._build_plates_to_be_sliced:
  576. self.needsSlicing()
  577. self._onChanged()
  578. def _onLayerMessage(self, message: Arcus.PythonMessage) -> None:
  579. """Called when a sliced layer data message is received from the engine.
  580. :param message: The protobuf message containing sliced layer data.
  581. """
  582. self._stored_layer_data.append(message)
  583. def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None:
  584. """Called when an optimized sliced layer data message is received from the engine.
  585. :param message: The protobuf message containing sliced layer data.
  586. """
  587. if self._start_slice_job_build_plate is not None:
  588. if self._start_slice_job_build_plate not in self._stored_optimized_layer_data:
  589. self._stored_optimized_layer_data[self._start_slice_job_build_plate] = []
  590. self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message)
  591. structurePolygonReceived = Signal()
  592. def _onStructurePolygonMessage(self, message: Arcus.PythonMessage) -> None:
  593. """
  594. Called when a structure polygon visualization is received from the
  595. engine. This sends it on to a signal for others to listen to.
  596. :param message: The protobuf message containing a structure polygon.
  597. """
  598. self.structurePolygonReceived.emit(message)
  599. def _onProgressMessage(self, message: Arcus.PythonMessage) -> None:
  600. """Called when a progress message is received from the engine.
  601. :param message: The protobuf message containing the slicing progress.
  602. """
  603. self.processingProgress.emit(message.amount)
  604. self.setState(BackendState.Processing)
  605. def _invokeSlice(self) -> None:
  606. if self._use_timer:
  607. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  608. # otherwise business as usual
  609. if self._machine_error_checker is None:
  610. self._change_timer.stop()
  611. return
  612. if self._machine_error_checker.needToWaitForResult:
  613. self._change_timer.stop()
  614. else:
  615. self._change_timer.start()
  616. def _onSlicingFinishedMessage(self, message: Arcus.PythonMessage) -> None:
  617. """Called when the engine sends a message that slicing is finished.
  618. :param message: The protobuf message signalling that slicing is finished.
  619. """
  620. self.setState(BackendState.Done)
  621. self.processingProgress.emit(1.0)
  622. try:
  623. gcode_list = self._scene.gcode_dict[self._start_slice_job_build_plate] #type: ignore #Because we generate this attribute dynamically.
  624. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  625. gcode_list = []
  626. application = CuraApplication.getInstance()
  627. for index, line in enumerate(gcode_list):
  628. replaced = line.replace("{print_time}", str(application.getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)))
  629. replaced = replaced.replace("{filament_amount}", str(application.getPrintInformation().materialLengths))
  630. replaced = replaced.replace("{filament_weight}", str(application.getPrintInformation().materialWeights))
  631. replaced = replaced.replace("{filament_cost}", str(application.getPrintInformation().materialCosts))
  632. replaced = replaced.replace("{jobname}", str(application.getPrintInformation().jobName))
  633. gcode_list[index] = replaced
  634. self._slicing = False
  635. if self._slice_start_time:
  636. Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
  637. Logger.log("d", "Number of models per buildplate: %s", dict(self._numObjectsPerBuildPlate()))
  638. # See if we need to process the sliced layers job.
  639. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  640. if (
  641. self._layer_view_active and
  642. (self._process_layers_job is None or not self._process_layers_job.isRunning()) and
  643. active_build_plate == self._start_slice_job_build_plate and
  644. active_build_plate not in self._build_plates_to_be_sliced):
  645. self._startProcessSlicedLayersJob(active_build_plate)
  646. # self._onActiveViewChanged()
  647. self._start_slice_job_build_plate = None
  648. Logger.log("d", "See if there is more to slice...")
  649. # Somehow this results in an Arcus Error
  650. # self.slice()
  651. # Call slice again using the timer, allowing the backend to restart
  652. if self._build_plates_to_be_sliced:
  653. self.enableTimer() # manually enable timer to be able to invoke slice, also when in manual slice mode
  654. self._invokeSlice()
  655. def _onGCodeLayerMessage(self, message: Arcus.PythonMessage) -> None:
  656. """Called when a g-code message is received from the engine.
  657. :param message: The protobuf message containing g-code, encoded as UTF-8.
  658. """
  659. try:
  660. self._scene.gcode_dict[self._start_slice_job_build_plate].append(message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  661. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  662. pass # Throw the message away.
  663. def _onGCodePrefixMessage(self, message: Arcus.PythonMessage) -> None:
  664. """Called when a g-code prefix message is received from the engine.
  665. :param message: The protobuf message containing the g-code prefix,
  666. encoded as UTF-8.
  667. """
  668. try:
  669. self._scene.gcode_dict[self._start_slice_job_build_plate].insert(0, message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  670. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  671. pass # Throw the message away.
  672. def _createSocket(self, protocol_file: str = None) -> None:
  673. """Creates a new socket connection."""
  674. if not protocol_file:
  675. if not self.getPluginId():
  676. Logger.error("Can't create socket before CuraEngineBackend plug-in is registered.")
  677. return
  678. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  679. if not plugin_path:
  680. Logger.error("Could not get plugin path!", self.getPluginId())
  681. return
  682. protocol_file = os.path.abspath(os.path.join(plugin_path, "Cura.proto"))
  683. super()._createSocket(protocol_file)
  684. self._engine_is_fresh = True
  685. def _onChanged(self, *args: Any, **kwargs: Any) -> None:
  686. """Called when anything has changed to the stuff that needs to be sliced.
  687. This indicates that we should probably re-slice soon.
  688. """
  689. self.needsSlicing()
  690. if self._use_timer:
  691. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  692. # otherwise business as usual
  693. if self._machine_error_checker is None:
  694. self._change_timer.stop()
  695. return
  696. if self._machine_error_checker.needToWaitForResult:
  697. self._change_timer.stop()
  698. else:
  699. self._change_timer.start()
  700. def _onPrintTimeMaterialEstimates(self, message: Arcus.PythonMessage) -> None:
  701. """Called when a print time message is received from the engine.
  702. :param message: The protobuf message containing the print time per feature and
  703. material amount per extruder
  704. """
  705. material_amounts = []
  706. for index in range(message.repeatedMessageCount("materialEstimates")):
  707. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  708. times = self._parseMessagePrintTimes(message)
  709. self.printDurationMessage.emit(self._start_slice_job_build_plate, times, material_amounts)
  710. def _parseMessagePrintTimes(self, message: Arcus.PythonMessage) -> Dict[str, float]:
  711. """Called for parsing message to retrieve estimated time per feature
  712. :param message: The protobuf message containing the print time per feature
  713. """
  714. result = {
  715. "inset_0": message.time_inset_0,
  716. "inset_x": message.time_inset_x,
  717. "skin": message.time_skin,
  718. "infill": message.time_infill,
  719. "support_infill": message.time_support_infill,
  720. "support_interface": message.time_support_interface,
  721. "support": message.time_support,
  722. "skirt": message.time_skirt,
  723. "prime_tower": message.time_prime_tower,
  724. "travel": message.time_travel,
  725. "retract": message.time_retract,
  726. "none": message.time_none
  727. }
  728. return result
  729. def _onBackendConnected(self) -> None:
  730. """Called when the back-end connects to the front-end."""
  731. if self._restart:
  732. self._restart = False
  733. self._onChanged()
  734. def _onToolOperationStarted(self, tool: Tool) -> None:
  735. """Called when the user starts using some tool.
  736. When the user starts using a tool, we should pause slicing to prevent
  737. continuously slicing while the user is dragging some tool handle.
  738. :param tool: The tool that the user is using.
  739. """
  740. self._tool_active = True # Do not react on scene change
  741. self.disableTimer()
  742. # Restart engine as soon as possible, we know we want to slice afterwards
  743. if not self._engine_is_fresh:
  744. self._terminate()
  745. self._createSocket()
  746. def _onToolOperationStopped(self, tool: Tool) -> None:
  747. """Called when the user stops using some tool.
  748. This indicates that we can safely start slicing again.
  749. :param tool: The tool that the user was using.
  750. """
  751. self._tool_active = False # React on scene change again
  752. self.determineAutoSlicing() # Switch timer on if appropriate
  753. # Process all the postponed scene changes
  754. while self._postponed_scene_change_sources:
  755. source = self._postponed_scene_change_sources.pop(0)
  756. self._onSceneChanged(source)
  757. def _startProcessSlicedLayersJob(self, build_plate_number: int) -> None:
  758. self._process_layers_job = ProcessSlicedLayersJob(self._stored_optimized_layer_data[build_plate_number])
  759. self._process_layers_job.setBuildPlate(build_plate_number)
  760. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  761. self._process_layers_job.start()
  762. def _onActiveViewChanged(self) -> None:
  763. """Called when the user changes the active view mode."""
  764. view = CuraApplication.getInstance().getController().getActiveView()
  765. if view:
  766. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  767. if view.getPluginId() == "SimulationView": # If switching to layer view, we should process the layers if that hasn't been done yet.
  768. self._layer_view_active = True
  769. # There is data and we're not slicing at the moment
  770. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  771. # TODO: what build plate I am slicing
  772. if (active_build_plate in self._stored_optimized_layer_data and
  773. not self._slicing and
  774. not self._process_layers_job and
  775. active_build_plate not in self._build_plates_to_be_sliced):
  776. self._startProcessSlicedLayersJob(active_build_plate)
  777. else:
  778. self._layer_view_active = False
  779. def _onBackendQuit(self) -> None:
  780. """Called when the back-end self-terminates.
  781. We should reset our state and start listening for new connections.
  782. """
  783. if not self._restart:
  784. if self._process: # type: ignore
  785. return_code = self._process.wait()
  786. if return_code != 0:
  787. Logger.log("e", f"Backend exited abnormally with return code {return_code}!")
  788. self._slicing_error_message.show()
  789. self.setState(BackendState.Error)
  790. self.stopSlicing()
  791. else:
  792. Logger.log("d", "Backend finished slicing. Resetting process and socket.")
  793. self._process = None # type: ignore
  794. def _reportBackendError(self, _message_id: str, _action_id: str) -> None:
  795. """
  796. Triggered when the user wants to report an error in the back-end.
  797. """
  798. QDesktopServices.openUrl(QUrl("https://github.com/Ultimaker/Cura/issues/new/choose"))
  799. def _onGlobalStackChanged(self) -> None:
  800. """Called when the global container stack changes"""
  801. if self._global_container_stack:
  802. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  803. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  804. for extruder in self._global_container_stack.extruderList:
  805. extruder.propertyChanged.disconnect(self._onSettingChanged)
  806. extruder.containersChanged.disconnect(self._onChanged)
  807. self._global_container_stack = CuraApplication.getInstance().getMachineManager().activeMachine
  808. if self._global_container_stack:
  809. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  810. self._global_container_stack.containersChanged.connect(self._onChanged)
  811. for extruder in self._global_container_stack.extruderList:
  812. extruder.propertyChanged.connect(self._onSettingChanged)
  813. extruder.containersChanged.connect(self._onChanged)
  814. self._onChanged()
  815. def _onProcessLayersFinished(self, job: ProcessSlicedLayersJob) -> None:
  816. if job.getBuildPlate() in self._stored_optimized_layer_data:
  817. del self._stored_optimized_layer_data[job.getBuildPlate()]
  818. else:
  819. Logger.log("w", "The optimized layer data was already deleted for buildplate %s", job.getBuildPlate())
  820. self._process_layers_job = None
  821. Logger.log("d", "See if there is more to slice(2)...")
  822. self._invokeSlice()
  823. def enableTimer(self) -> None:
  824. """Connect slice function to timer."""
  825. if not self._use_timer:
  826. self._change_timer.timeout.connect(self.slice)
  827. self._use_timer = True
  828. def disableTimer(self) -> None:
  829. """Disconnect slice function from timer.
  830. This means that slicing will not be triggered automatically
  831. """
  832. if self._use_timer:
  833. self._use_timer = False
  834. self._change_timer.timeout.disconnect(self.slice)
  835. def _onPreferencesChanged(self, preference: str) -> None:
  836. if preference != "general/auto_slice":
  837. return
  838. auto_slice = self.determineAutoSlicing()
  839. if auto_slice:
  840. self._change_timer.start()
  841. def tickle(self) -> None:
  842. """Tickle the backend so in case of auto slicing, it starts the timer."""
  843. if self._use_timer:
  844. self._change_timer.start()
  845. def _extruderChanged(self) -> None:
  846. if not self._multi_build_plate_model:
  847. Logger.log("w", "CuraEngineBackend does not have multi_build_plate_model assigned!")
  848. return
  849. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  850. if build_plate_number not in self._build_plates_to_be_sliced:
  851. self._build_plates_to_be_sliced.append(build_plate_number)
  852. self._invokeSlice()