CuraEngineBackend.py 37 KB

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