CuraEngineBackend.py 44 KB

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