CuraEngineBackend.py 43 KB

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