CuraEngineBackend.py 49 KB

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