CuraEngineBackend.py 42 KB

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