CuraEngineBackend.py 37 KB

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