CuraEngineBackend.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  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. 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. Logger.warning(f"Unable to slice with the current settings. The following settings have errors: {', '.join(error_labels)}")
  346. self._error_message.show()
  347. self.setState(BackendState.Error)
  348. self.backendError.emit(job)
  349. else:
  350. self.setState(BackendState.NotStarted)
  351. return
  352. elif job.getResult() == StartJobResult.ObjectSettingError:
  353. errors = {}
  354. for node in DepthFirstIterator(application.getController().getScene().getRoot()):
  355. stack = node.callDecoration("getStack")
  356. if not stack:
  357. continue
  358. for key in stack.getErrorKeys():
  359. if not self._global_container_stack:
  360. Logger.log("e", "CuraEngineBackend does not have global_container_stack assigned.")
  361. continue
  362. definition = cast(DefinitionContainerInterface, self._global_container_stack.getBottom()).findDefinitions(key = key)
  363. if not definition:
  364. Logger.log("e", "When checking settings for errors, unable to find definition for key {key} in per-object stack.".format(key = key))
  365. continue
  366. errors[key] = definition[0].label
  367. self._error_message = Message(catalog.i18nc("@info:status",
  368. "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())),
  369. title = catalog.i18nc("@info:title", "Unable to slice"),
  370. message_type = Message.MessageType.WARNING)
  371. Logger.warning(f"Unable to slice due to per-object settings. The following settings have errors on one or more models: {', '.join(errors.values())}")
  372. self._error_message.show()
  373. self.setState(BackendState.Error)
  374. self.backendError.emit(job)
  375. return
  376. if job.getResult() == StartJobResult.BuildPlateError:
  377. if application.platformActivity:
  378. self._error_message = Message(catalog.i18nc("@info:status",
  379. "Unable to slice because the prime tower or prime position(s) are invalid."),
  380. title = catalog.i18nc("@info:title", "Unable to slice"),
  381. message_type = Message.MessageType.WARNING)
  382. self._error_message.show()
  383. self.setState(BackendState.Error)
  384. self.backendError.emit(job)
  385. return
  386. else:
  387. self.setState(BackendState.NotStarted)
  388. if job.getResult() == StartJobResult.ObjectsWithDisabledExtruder:
  389. self._error_message = Message(catalog.i18nc("@info:status",
  390. "Unable to slice because there are objects associated with disabled Extruder %s.") % job.getMessage(),
  391. title = catalog.i18nc("@info:title", "Unable to slice"),
  392. message_type = Message.MessageType.WARNING)
  393. self._error_message.show()
  394. self.setState(BackendState.Error)
  395. self.backendError.emit(job)
  396. return
  397. if job.getResult() == StartJobResult.NothingToSlice:
  398. if application.platformActivity:
  399. self._error_message = Message(catalog.i18nc("@info:status", "Please review settings and check if your models:"
  400. "\n- Fit within the build volume"
  401. "\n- Are assigned to an enabled extruder"
  402. "\n- Are not all set as modifier meshes"),
  403. title = catalog.i18nc("@info:title", "Unable to slice"),
  404. message_type = Message.MessageType.WARNING)
  405. self._error_message.show()
  406. self.setState(BackendState.Error)
  407. self.backendError.emit(job)
  408. else:
  409. self.setState(BackendState.NotStarted)
  410. self._invokeSlice()
  411. return
  412. # Preparation completed, send it to the backend.
  413. self._socket.sendMessage(job.getSliceMessage())
  414. # Notify the user that it's now up to the backend to do it's job
  415. self.setState(BackendState.Processing)
  416. if self._slice_start_time:
  417. Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
  418. def determineAutoSlicing(self) -> bool:
  419. """Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  420. It disables when:
  421. - preference auto slice is off
  422. - decorator isBlockSlicing is found (used in g-code reader)
  423. """
  424. enable_timer = True
  425. self._is_disabled = False
  426. if not CuraApplication.getInstance().getPreferences().getValue("general/auto_slice"):
  427. enable_timer = False
  428. for node in DepthFirstIterator(self._scene.getRoot()):
  429. if node.callDecoration("isBlockSlicing"):
  430. enable_timer = False
  431. self.setState(BackendState.Disabled)
  432. self._is_disabled = True
  433. gcode_list = node.callDecoration("getGCodeList")
  434. if gcode_list is not None:
  435. self._scene.gcode_dict[node.callDecoration("getBuildPlateNumber")] = gcode_list #type: ignore #Because we generate this attribute dynamically.
  436. if self._use_timer == enable_timer:
  437. return self._use_timer
  438. if enable_timer:
  439. self.setState(BackendState.NotStarted)
  440. self.enableTimer()
  441. return True
  442. else:
  443. self.disableTimer()
  444. return False
  445. def _numObjectsPerBuildPlate(self) -> Dict[int, int]:
  446. """Return a dict with number of objects per build plate"""
  447. num_objects = defaultdict(int) #type: Dict[int, int]
  448. for node in DepthFirstIterator(self._scene.getRoot()):
  449. # Only count sliceable objects
  450. if node.callDecoration("isSliceable"):
  451. build_plate_number = node.callDecoration("getBuildPlateNumber")
  452. if build_plate_number is not None:
  453. num_objects[build_plate_number] += 1
  454. return num_objects
  455. def _onSceneChanged(self, source: SceneNode) -> None:
  456. """Listener for when the scene has changed.
  457. This should start a slice if the scene is now ready to slice.
  458. :param source: The scene node that was changed.
  459. """
  460. if not source.callDecoration("isSliceable") and source != self._scene.getRoot():
  461. return
  462. # This case checks if the source node is a node that contains GCode. In this case the
  463. # current layer data is removed so the previous data is not rendered - CURA-4821
  464. if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"):
  465. self._stored_optimized_layer_data = {}
  466. build_plate_changed = set()
  467. source_build_plate_number = source.callDecoration("getBuildPlateNumber")
  468. if source == self._scene.getRoot():
  469. # we got the root node
  470. num_objects = self._numObjectsPerBuildPlate()
  471. for build_plate_number in list(self._last_num_objects.keys()) + list(num_objects.keys()):
  472. if build_plate_number not in self._last_num_objects or num_objects[build_plate_number] != self._last_num_objects[build_plate_number]:
  473. self._last_num_objects[build_plate_number] = num_objects[build_plate_number]
  474. build_plate_changed.add(build_plate_number)
  475. else:
  476. # we got a single scenenode
  477. if not source.callDecoration("isGroup"):
  478. mesh_data = source.getMeshData()
  479. if mesh_data is None or mesh_data.getVertices() is None:
  480. return
  481. # There are some SceneNodes that do not have any build plate associated, then do not add to the list.
  482. if source_build_plate_number is not None:
  483. build_plate_changed.add(source_build_plate_number)
  484. if not build_plate_changed:
  485. return
  486. if self._tool_active:
  487. # do it later, each source only has to be done once
  488. if source not in self._postponed_scene_change_sources:
  489. self._postponed_scene_change_sources.append(source)
  490. return
  491. self.stopSlicing()
  492. for build_plate_number in build_plate_changed:
  493. if build_plate_number not in self._build_plates_to_be_sliced:
  494. self._build_plates_to_be_sliced.append(build_plate_number)
  495. self.printDurationMessage.emit(source_build_plate_number, {}, [])
  496. self.processingProgress.emit(0.0)
  497. self._clearLayerData(build_plate_changed)
  498. self._invokeSlice()
  499. def _onSocketError(self, error: Arcus.Error) -> None:
  500. """Called when an error occurs in the socket connection towards the engine.
  501. :param error: The exception that occurred.
  502. """
  503. if CuraApplication.getInstance().isShuttingDown():
  504. return
  505. super()._onSocketError(error)
  506. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  507. return
  508. self._terminate()
  509. self._createSocket()
  510. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  511. Logger.log("w", "A socket error caused the connection to be reset")
  512. # _terminate()' function sets the job status to 'cancel', after reconnecting to another Port the job status
  513. # needs to be updated. Otherwise backendState is "Unable To Slice"
  514. if error.getErrorCode() == Arcus.ErrorCode.BindFailedError and self._start_slice_job is not None:
  515. self._start_slice_job.setIsCancelled(False)
  516. # Check if there's any slicable object in the scene.
  517. def hasSlicableObject(self) -> bool:
  518. has_slicable = False
  519. for node in DepthFirstIterator(self._scene.getRoot()):
  520. if node.callDecoration("isSliceable"):
  521. has_slicable = True
  522. break
  523. return has_slicable
  524. def _clearLayerData(self, build_plate_numbers: Set = None) -> None:
  525. """Remove old layer data (if any)"""
  526. # Clear out any old gcode
  527. self._scene.gcode_dict = {} # type: ignore
  528. for node in DepthFirstIterator(self._scene.getRoot()):
  529. if node.callDecoration("getLayerData"):
  530. if not build_plate_numbers or node.callDecoration("getBuildPlateNumber") in build_plate_numbers:
  531. # We can assume that all nodes have a parent as we're looping through the scene (and filter out root)
  532. cast(SceneNode, node.getParent()).removeChild(node)
  533. def markSliceAll(self) -> None:
  534. for build_plate_number in range(CuraApplication.getInstance().getMultiBuildPlateModel().maxBuildPlate + 1):
  535. if build_plate_number not in self._build_plates_to_be_sliced:
  536. self._build_plates_to_be_sliced.append(build_plate_number)
  537. def needsSlicing(self) -> None:
  538. """Convenient function: mark everything to slice, emit state and clear layer data"""
  539. # CURA-6604: If there's no slicable object, do not (try to) trigger slice, which will clear all the current
  540. # gcode. This can break Gcode file loading if it tries to remove it afterwards.
  541. if not self.hasSlicableObject():
  542. return
  543. self.determineAutoSlicing()
  544. self.stopSlicing()
  545. self.markSliceAll()
  546. self.processingProgress.emit(0.0)
  547. if not self._use_timer:
  548. # With manually having to slice, we want to clear the old invalid layer data.
  549. self._clearLayerData()
  550. def _onSettingChanged(self, instance: SettingInstance, property: str) -> None:
  551. """A setting has changed, so check if we must reslice.
  552. :param instance: The setting instance that has changed.
  553. :param property: The property of the setting instance that has changed.
  554. """
  555. if property == "value": # Only reslice if the value has changed.
  556. self.needsSlicing()
  557. self._onChanged()
  558. elif property == "validationState":
  559. if self._use_timer:
  560. self._change_timer.stop()
  561. def _onStackErrorCheckFinished(self) -> None:
  562. self.determineAutoSlicing()
  563. if self._is_disabled:
  564. return
  565. if not self._slicing and self._build_plates_to_be_sliced:
  566. self.needsSlicing()
  567. self._onChanged()
  568. def _onLayerMessage(self, message: Arcus.PythonMessage) -> None:
  569. """Called when a sliced layer data message is received from the engine.
  570. :param message: The protobuf message containing sliced layer data.
  571. """
  572. self._stored_layer_data.append(message)
  573. def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None:
  574. """Called when an optimized sliced layer data message is received from the engine.
  575. :param message: The protobuf message containing sliced layer data.
  576. """
  577. if self._start_slice_job_build_plate is not None:
  578. if self._start_slice_job_build_plate not in self._stored_optimized_layer_data:
  579. self._stored_optimized_layer_data[self._start_slice_job_build_plate] = []
  580. self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message)
  581. def _onProgressMessage(self, message: Arcus.PythonMessage) -> None:
  582. """Called when a progress message is received from the engine.
  583. :param message: The protobuf message containing the slicing progress.
  584. """
  585. self.processingProgress.emit(message.amount)
  586. self.setState(BackendState.Processing)
  587. def _invokeSlice(self) -> None:
  588. if self._use_timer:
  589. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  590. # otherwise business as usual
  591. if self._machine_error_checker is None:
  592. self._change_timer.stop()
  593. return
  594. if self._machine_error_checker.needToWaitForResult:
  595. self._change_timer.stop()
  596. else:
  597. self._change_timer.start()
  598. def _onSlicingFinishedMessage(self, message: Arcus.PythonMessage) -> None:
  599. """Called when the engine sends a message that slicing is finished.
  600. :param message: The protobuf message signalling that slicing is finished.
  601. """
  602. self.setState(BackendState.Done)
  603. self.processingProgress.emit(1.0)
  604. try:
  605. gcode_list = self._scene.gcode_dict[self._start_slice_job_build_plate] #type: ignore #Because we generate this attribute dynamically.
  606. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  607. gcode_list = []
  608. application = CuraApplication.getInstance()
  609. for index, line in enumerate(gcode_list):
  610. replaced = line.replace("{print_time}", str(application.getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)))
  611. replaced = replaced.replace("{filament_amount}", str(application.getPrintInformation().materialLengths))
  612. replaced = replaced.replace("{filament_weight}", str(application.getPrintInformation().materialWeights))
  613. replaced = replaced.replace("{filament_cost}", str(application.getPrintInformation().materialCosts))
  614. replaced = replaced.replace("{jobname}", str(application.getPrintInformation().jobName))
  615. gcode_list[index] = replaced
  616. self._slicing = False
  617. if self._slice_start_time:
  618. Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
  619. Logger.log("d", "Number of models per buildplate: %s", dict(self._numObjectsPerBuildPlate()))
  620. # See if we need to process the sliced layers job.
  621. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  622. if (
  623. self._layer_view_active and
  624. (self._process_layers_job is None or not self._process_layers_job.isRunning()) and
  625. active_build_plate == self._start_slice_job_build_plate and
  626. active_build_plate not in self._build_plates_to_be_sliced):
  627. self._startProcessSlicedLayersJob(active_build_plate)
  628. # self._onActiveViewChanged()
  629. self._start_slice_job_build_plate = None
  630. Logger.log("d", "See if there is more to slice...")
  631. # Somehow this results in an Arcus Error
  632. # self.slice()
  633. # Call slice again using the timer, allowing the backend to restart
  634. if self._build_plates_to_be_sliced:
  635. self.enableTimer() # manually enable timer to be able to invoke slice, also when in manual slice mode
  636. self._invokeSlice()
  637. def _onGCodeLayerMessage(self, message: Arcus.PythonMessage) -> None:
  638. """Called when a g-code message is received from the engine.
  639. :param message: The protobuf message containing g-code, encoded as UTF-8.
  640. """
  641. try:
  642. 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.
  643. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  644. pass # Throw the message away.
  645. def _onGCodePrefixMessage(self, message: Arcus.PythonMessage) -> None:
  646. """Called when a g-code prefix message is received from the engine.
  647. :param message: The protobuf message containing the g-code prefix,
  648. encoded as UTF-8.
  649. """
  650. try:
  651. 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.
  652. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  653. pass # Throw the message away.
  654. def _createSocket(self, protocol_file: str = None) -> None:
  655. """Creates a new socket connection."""
  656. if not protocol_file:
  657. if not self.getPluginId():
  658. Logger.error("Can't create socket before CuraEngineBackend plug-in is registered.")
  659. return
  660. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  661. if not plugin_path:
  662. Logger.error("Could not get plugin path!", self.getPluginId())
  663. return
  664. protocol_file = os.path.abspath(os.path.join(plugin_path, "Cura.proto"))
  665. super()._createSocket(protocol_file)
  666. self._engine_is_fresh = True
  667. def _onChanged(self, *args: Any, **kwargs: Any) -> None:
  668. """Called when anything has changed to the stuff that needs to be sliced.
  669. This indicates that we should probably re-slice soon.
  670. """
  671. self.needsSlicing()
  672. if self._use_timer:
  673. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  674. # otherwise business as usual
  675. if self._machine_error_checker is None:
  676. self._change_timer.stop()
  677. return
  678. if self._machine_error_checker.needToWaitForResult:
  679. self._change_timer.stop()
  680. else:
  681. self._change_timer.start()
  682. def _onPrintTimeMaterialEstimates(self, message: Arcus.PythonMessage) -> None:
  683. """Called when a print time message is received from the engine.
  684. :param message: The protobuf message containing the print time per feature and
  685. material amount per extruder
  686. """
  687. material_amounts = []
  688. for index in range(message.repeatedMessageCount("materialEstimates")):
  689. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  690. times = self._parseMessagePrintTimes(message)
  691. self.printDurationMessage.emit(self._start_slice_job_build_plate, times, material_amounts)
  692. def _parseMessagePrintTimes(self, message: Arcus.PythonMessage) -> Dict[str, float]:
  693. """Called for parsing message to retrieve estimated time per feature
  694. :param message: The protobuf message containing the print time per feature
  695. """
  696. result = {
  697. "inset_0": message.time_inset_0,
  698. "inset_x": message.time_inset_x,
  699. "skin": message.time_skin,
  700. "infill": message.time_infill,
  701. "support_infill": message.time_support_infill,
  702. "support_interface": message.time_support_interface,
  703. "support": message.time_support,
  704. "skirt": message.time_skirt,
  705. "prime_tower": message.time_prime_tower,
  706. "travel": message.time_travel,
  707. "retract": message.time_retract,
  708. "none": message.time_none
  709. }
  710. return result
  711. def _onBackendConnected(self) -> None:
  712. """Called when the back-end connects to the front-end."""
  713. if self._restart:
  714. self._restart = False
  715. self._onChanged()
  716. def _onToolOperationStarted(self, tool: Tool) -> None:
  717. """Called when the user starts using some tool.
  718. When the user starts using a tool, we should pause slicing to prevent
  719. continuously slicing while the user is dragging some tool handle.
  720. :param tool: The tool that the user is using.
  721. """
  722. self._tool_active = True # Do not react on scene change
  723. self.disableTimer()
  724. # Restart engine as soon as possible, we know we want to slice afterwards
  725. if not self._engine_is_fresh:
  726. self._terminate()
  727. self._createSocket()
  728. def _onToolOperationStopped(self, tool: Tool) -> None:
  729. """Called when the user stops using some tool.
  730. This indicates that we can safely start slicing again.
  731. :param tool: The tool that the user was using.
  732. """
  733. self._tool_active = False # React on scene change again
  734. self.determineAutoSlicing() # Switch timer on if appropriate
  735. # Process all the postponed scene changes
  736. while self._postponed_scene_change_sources:
  737. source = self._postponed_scene_change_sources.pop(0)
  738. self._onSceneChanged(source)
  739. def _startProcessSlicedLayersJob(self, build_plate_number: int) -> None:
  740. self._process_layers_job = ProcessSlicedLayersJob(self._stored_optimized_layer_data[build_plate_number])
  741. self._process_layers_job.setBuildPlate(build_plate_number)
  742. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  743. self._process_layers_job.start()
  744. def _onActiveViewChanged(self) -> None:
  745. """Called when the user changes the active view mode."""
  746. view = CuraApplication.getInstance().getController().getActiveView()
  747. if view:
  748. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  749. if view.getPluginId() == "SimulationView": # If switching to layer view, we should process the layers if that hasn't been done yet.
  750. self._layer_view_active = True
  751. # There is data and we're not slicing at the moment
  752. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  753. # TODO: what build plate I am slicing
  754. if (active_build_plate in self._stored_optimized_layer_data and
  755. not self._slicing and
  756. not self._process_layers_job and
  757. active_build_plate not in self._build_plates_to_be_sliced):
  758. self._startProcessSlicedLayersJob(active_build_plate)
  759. else:
  760. self._layer_view_active = False
  761. def _onBackendQuit(self) -> None:
  762. """Called when the back-end self-terminates.
  763. We should reset our state and start listening for new connections.
  764. """
  765. if not self._restart:
  766. if self._process: # type: ignore
  767. return_code = self._process.wait()
  768. if return_code != 0:
  769. Logger.log("e", f"Backend exited abnormally with return code {return_code}!")
  770. self._slicing_error_message.show()
  771. self.setState(BackendState.Error)
  772. self.stopSlicing()
  773. else:
  774. Logger.log("d", "Backend finished slicing. Resetting process and socket.")
  775. self._process = None # type: ignore
  776. def _reportBackendError(self, _message_id: str, _action_id: str) -> None:
  777. """
  778. Triggered when the user wants to report an error in the back-end.
  779. """
  780. QDesktopServices.openUrl(QUrl("https://github.com/Ultimaker/Cura/issues/new/choose"))
  781. def _onGlobalStackChanged(self) -> None:
  782. """Called when the global container stack changes"""
  783. if self._global_container_stack:
  784. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  785. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  786. for extruder in self._global_container_stack.extruderList:
  787. extruder.propertyChanged.disconnect(self._onSettingChanged)
  788. extruder.containersChanged.disconnect(self._onChanged)
  789. self._global_container_stack = CuraApplication.getInstance().getMachineManager().activeMachine
  790. if self._global_container_stack:
  791. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  792. self._global_container_stack.containersChanged.connect(self._onChanged)
  793. for extruder in self._global_container_stack.extruderList:
  794. extruder.propertyChanged.connect(self._onSettingChanged)
  795. extruder.containersChanged.connect(self._onChanged)
  796. self._onChanged()
  797. def _onProcessLayersFinished(self, job: ProcessSlicedLayersJob) -> None:
  798. if job.getBuildPlate() in self._stored_optimized_layer_data:
  799. del self._stored_optimized_layer_data[job.getBuildPlate()]
  800. else:
  801. Logger.log("w", "The optimized layer data was already deleted for buildplate %s", job.getBuildPlate())
  802. self._process_layers_job = None
  803. Logger.log("d", "See if there is more to slice(2)...")
  804. self._invokeSlice()
  805. def enableTimer(self) -> None:
  806. """Connect slice function to timer."""
  807. if not self._use_timer:
  808. self._change_timer.timeout.connect(self.slice)
  809. self._use_timer = True
  810. def disableTimer(self) -> None:
  811. """Disconnect slice function from timer.
  812. This means that slicing will not be triggered automatically
  813. """
  814. if self._use_timer:
  815. self._use_timer = False
  816. self._change_timer.timeout.disconnect(self.slice)
  817. def _onPreferencesChanged(self, preference: str) -> None:
  818. if preference != "general/auto_slice":
  819. return
  820. auto_slice = self.determineAutoSlicing()
  821. if auto_slice:
  822. self._change_timer.start()
  823. def tickle(self) -> None:
  824. """Tickle the backend so in case of auto slicing, it starts the timer."""
  825. if self._use_timer:
  826. self._change_timer.start()
  827. def _extruderChanged(self) -> None:
  828. if not self._multi_build_plate_model:
  829. Logger.log("w", "CuraEngineBackend does not have multi_build_plate_model assigned!")
  830. return
  831. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  832. if build_plate_number not in self._build_plates_to_be_sliced:
  833. self._build_plates_to_be_sliced.append(build_plate_number)
  834. self._invokeSlice()