CuraEngineBackend.py 51 KB

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