CuraEngineBackend.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Backend.Backend import Backend
  4. from UM.Application import Application
  5. from UM.Scene.SceneNode import SceneNode
  6. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  7. from UM.Preferences import Preferences
  8. from UM.Math.Vector import Vector
  9. from UM.Signal import Signal
  10. from UM.Logger import Logger
  11. from UM.Resources import Resources
  12. from UM.Settings.SettingOverrideDecorator import SettingOverrideDecorator
  13. from UM.Message import Message
  14. from cura.OneAtATimeIterator import OneAtATimeIterator
  15. from . import Cura_pb2
  16. from . import ProcessSlicedObjectListJob
  17. from . import ProcessGCodeJob
  18. import os
  19. import sys
  20. import numpy
  21. from PyQt5.QtCore import QTimer
  22. from UM.i18n import i18nCatalog
  23. catalog = i18nCatalog("cura")
  24. class CuraEngineBackend(Backend):
  25. def __init__(self):
  26. super().__init__()
  27. # Find out where the engine is located, and how it is called. This depends on how Cura is packaged and which OS we are running on.
  28. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  29. if hasattr(sys, "frozen"):
  30. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  31. if sys.platform == "win32":
  32. default_engine_location += ".exe"
  33. default_engine_location = os.path.abspath(default_engine_location)
  34. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  35. self._scene = Application.getInstance().getController().getScene()
  36. self._scene.sceneChanged.connect(self._onSceneChanged)
  37. # Workaround to disable layer view processing if layer view is not active.
  38. self._layer_view_active = False
  39. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  40. self._onActiveViewChanged()
  41. self._stored_layer_data = None
  42. self._profile = None
  43. Application.getInstance().getMachineManager().activeProfileChanged.connect(self._onActiveProfileChanged)
  44. self._onActiveProfileChanged()
  45. self._change_timer = QTimer()
  46. self._change_timer.setInterval(500)
  47. self._change_timer.setSingleShot(True)
  48. self._change_timer.timeout.connect(self.slice)
  49. self._message_handlers[Cura_pb2.SlicedObjectList] = self._onSlicedObjectListMessage
  50. self._message_handlers[Cura_pb2.Progress] = self._onProgressMessage
  51. self._message_handlers[Cura_pb2.GCodeLayer] = self._onGCodeLayerMessage
  52. self._message_handlers[Cura_pb2.GCodePrefix] = self._onGCodePrefixMessage
  53. self._message_handlers[Cura_pb2.ObjectPrintTime] = self._onObjectPrintTimeMessage
  54. self._slicing = False
  55. self._restart = False
  56. self._save_gcode = True
  57. self._save_polygons = True
  58. self._report_progress = True
  59. self._enabled = True
  60. self._message = None
  61. self.backendConnected.connect(self._onBackendConnected)
  62. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  63. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  64. ## Get the command that is used to call the engine.
  65. # This is usefull for debugging and used to actually start the engine
  66. # \return list of commands and args / parameters.
  67. def getEngineCommand(self):
  68. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", Resources.getPath(Resources.MachineDefinitions, "fdmprinter.json"), "-vv"]
  69. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  70. # \param time The amount of time the print will take.
  71. # \param material_amount The amount of material the print will use.
  72. printDurationMessage = Signal()
  73. ## Emitted when the slicing process starts.
  74. slicingStarted = Signal()
  75. ## Emitted whne the slicing process is aborted forcefully.
  76. slicingCancelled = Signal()
  77. ## Perform a slice of the scene with the given set of settings.
  78. #
  79. # \param kwargs Keyword arguments.
  80. # Valid values are:
  81. # - settings: The settings to use for the slice. The default is the active machine.
  82. # - save_gcode: True if the generated gcode should be saved, False if not. True by default.
  83. # - save_polygons: True if the generated polygon data should be saved, False if not. True by default.
  84. # - force_restart: True if the slicing process should be forcefully restarted if it is already slicing.
  85. # If False, this method will do nothing when already slicing. True by default.
  86. # - report_progress: True if the slicing progress should be reported, False if not. Default is True.
  87. def slice(self, **kwargs):
  88. if not self._enabled:
  89. return
  90. if self._slicing:
  91. if not kwargs.get("force_restart", True):
  92. return
  93. self._slicing = False
  94. self._restart = True
  95. if self._process is not None:
  96. Logger.log("d", "Killing engine process")
  97. try:
  98. self._process.terminate()
  99. except: # terminating a process that is already terminating causes an exception, silently ignore this.
  100. pass
  101. self.slicingCancelled.emit()
  102. return
  103. Logger.log("d", "Preparing to send slice data to engine.")
  104. object_groups = []
  105. if self._profile.getSettingValue("print_sequence") == "one_at_a_time":
  106. for node in OneAtATimeIterator(self._scene.getRoot()):
  107. temp_list = []
  108. children = node.getAllChildren()
  109. children.append(node)
  110. for child_node in children:
  111. if type(child_node) is SceneNode and child_node.getMeshData() and child_node.getMeshData().getVertices() is not None:
  112. temp_list.append(child_node)
  113. object_groups.append(temp_list)
  114. else:
  115. temp_list = []
  116. for node in DepthFirstIterator(self._scene.getRoot()):
  117. if type(node) is SceneNode and node.getMeshData() and node.getMeshData().getVertices() is not None:
  118. if not getattr(node, "_outside_buildarea", False):
  119. temp_list.append(node)
  120. if len(temp_list) == 0:
  121. self.processingProgress.emit(0.0)
  122. return
  123. object_groups.append(temp_list)
  124. #for node in DepthFirstIterator(self._scene.getRoot()):
  125. # if type(node) is SceneNode and node.getMeshData() and node.getMeshData().getVertices() is not None:
  126. # if not getattr(node, "_outside_buildarea", False):
  127. # objects.append(node)
  128. if len(object_groups) == 0:
  129. if self._message:
  130. self._message.hide()
  131. self._message = None
  132. return #No point in slicing an empty build plate
  133. if kwargs.get("profile", self._profile).hasErrorValue():
  134. Logger.log('w', "Profile has error values. Aborting slicing")
  135. if self._message:
  136. self._message.hide()
  137. self._message = None
  138. self._message = Message(catalog.i18nc("@info:status", "Unable to slice. Please check your setting values for errors."))
  139. self._message.show()
  140. return #No slicing if we have error values since those are by definition illegal values.
  141. # Remove existing layer data (if any)
  142. for node in DepthFirstIterator(self._scene.getRoot()):
  143. if type(node) is SceneNode and node.getMeshData():
  144. if node.callDecoration("getLayerData"):
  145. Application.getInstance().getController().getScene().getRoot().removeChild(node)
  146. break
  147. Application.getInstance().getController().getScene().gcode_list = None
  148. self._slicing = True
  149. self.slicingStarted.emit()
  150. self._report_progress = kwargs.get("report_progress", True)
  151. if self._report_progress:
  152. self.processingProgress.emit(0.0)
  153. if not self._message:
  154. self._message = Message(catalog.i18nc("@info:status", "Slicing..."), 0, False, -1)
  155. self._message.show()
  156. else:
  157. self._message.setProgress(-1)
  158. self._sendSettings(kwargs.get("profile", self._profile))
  159. self._scene.acquireLock()
  160. # Set the gcode as an empty list. This will be filled with strings by GCodeLayer messages.
  161. # This is done so the gcode can be fragmented in memory and does not need a continues memory space.
  162. # (AKA. This prevents MemoryErrors)
  163. self._save_gcode = kwargs.get("save_gcode", True)
  164. if self._save_gcode:
  165. setattr(self._scene, "gcode_list", [])
  166. self._save_polygons = kwargs.get("save_polygons", True)
  167. slice_message = Cura_pb2.Slice()
  168. for group in object_groups:
  169. group_message = slice_message.object_lists.add()
  170. for object in group:
  171. mesh_data = object.getMeshData().getTransformed(object.getWorldTransformation())
  172. obj = group_message.objects.add()
  173. obj.id = id(object)
  174. verts = numpy.array(mesh_data.getVertices())
  175. verts[:,[1,2]] = verts[:,[2,1]]
  176. verts[:,1] *= -1
  177. obj.vertices = verts.tostring()
  178. self._handlePerObjectSettings(object, obj)
  179. # Hack to add per-object settings also to the "MeshGroup" in CuraEngine
  180. # We really should come up with a better solution for this.
  181. self._handlePerObjectSettings(group[0], group_message)
  182. self._scene.releaseLock()
  183. Logger.log("d", "Sending data to engine for slicing.")
  184. self._socket.sendMessage(slice_message)
  185. def _onSceneChanged(self, source):
  186. if type(source) is not SceneNode:
  187. return
  188. if source is self._scene.getRoot():
  189. return
  190. if source.getMeshData() is None:
  191. return
  192. if source.getMeshData().getVertices() is None:
  193. return
  194. self._onChanged()
  195. def _onActiveProfileChanged(self):
  196. if self._profile:
  197. self._profile.settingValueChanged.disconnect(self._onSettingChanged)
  198. self._profile = Application.getInstance().getMachineManager().getActiveProfile()
  199. if self._profile:
  200. self._profile.settingValueChanged.connect(self._onSettingChanged)
  201. self._onChanged()
  202. def _onSettingChanged(self, setting):
  203. self._onChanged()
  204. def _onSlicedObjectListMessage(self, message):
  205. if self._save_polygons:
  206. if self._layer_view_active:
  207. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(message)
  208. job.start()
  209. else :
  210. self._stored_layer_data = message
  211. def _onProgressMessage(self, message):
  212. if message.amount >= 0.99:
  213. self._slicing = False
  214. if self._message:
  215. self._message.setProgress(100)
  216. self._message.hide()
  217. self._message = None
  218. if self._message:
  219. self._message.setProgress(round(message.amount * 100))
  220. if self._report_progress:
  221. self.processingProgress.emit(message.amount)
  222. def _onGCodeLayerMessage(self, message):
  223. if self._save_gcode:
  224. job = ProcessGCodeJob.ProcessGCodeLayerJob(message)
  225. job.start()
  226. def _onGCodePrefixMessage(self, message):
  227. if self._save_gcode:
  228. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  229. def _onObjectPrintTimeMessage(self, message):
  230. self.printDurationMessage.emit(message.time, message.material_amount)
  231. self.processingProgress.emit(1.0)
  232. def _createSocket(self):
  233. super()._createSocket()
  234. self._socket.registerMessageType(1, Cura_pb2.Slice)
  235. self._socket.registerMessageType(2, Cura_pb2.SlicedObjectList)
  236. self._socket.registerMessageType(3, Cura_pb2.Progress)
  237. self._socket.registerMessageType(4, Cura_pb2.GCodeLayer)
  238. self._socket.registerMessageType(5, Cura_pb2.ObjectPrintTime)
  239. self._socket.registerMessageType(6, Cura_pb2.SettingList)
  240. self._socket.registerMessageType(7, Cura_pb2.GCodePrefix)
  241. ## Manually triggers a reslice
  242. def forceSlice(self):
  243. self._change_timer.start()
  244. def _onChanged(self):
  245. if not self._profile:
  246. return
  247. self._change_timer.start()
  248. def _sendSettings(self, profile):
  249. msg = Cura_pb2.SettingList()
  250. for key, value in profile.getAllSettingValues(include_machine = True).items():
  251. s = msg.settings.add()
  252. s.name = key
  253. s.value = str(value).encode("utf-8")
  254. self._socket.sendMessage(msg)
  255. def _onBackendConnected(self):
  256. if self._restart:
  257. self._onChanged()
  258. self._restart = False
  259. def _onToolOperationStarted(self, tool):
  260. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  261. def _onToolOperationStopped(self, tool):
  262. self._enabled = True # Tool stop, start listening for changes again.
  263. self._onChanged()
  264. def _onActiveViewChanged(self):
  265. if Application.getInstance().getController().getActiveView():
  266. view = Application.getInstance().getController().getActiveView()
  267. if view.getPluginId() == "LayerView":
  268. self._layer_view_active = True
  269. if self._stored_layer_data:
  270. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(self._stored_layer_data)
  271. job.start()
  272. else:
  273. self._layer_view_active = False
  274. def _handlePerObjectSettings(self, node, message):
  275. profile = node.callDecoration("getProfile")
  276. if profile:
  277. for key, value in profile.getChangedSettingValues().items():
  278. setting = message.settings.add()
  279. setting.name = key
  280. setting.value = str(value).encode()
  281. object_settings = node.callDecoration("getAllSettingValues")
  282. if not object_settings:
  283. return
  284. for key, value in object_settings.items():
  285. setting = message.settings.add()
  286. setting.name = key
  287. setting.value = str(value).encode()