CuraEngineBackend.py 48 KB

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