CuraEngineBackend.py 45 KB

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