CuraEngineBackend.py 43 KB

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