CuraEngineBackend.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 . import Cura_pb2
  13. from . import ProcessSlicedObjectListJob
  14. from . import ProcessGCodeJob
  15. import os
  16. import sys
  17. import numpy
  18. from PyQt5.QtCore import QTimer
  19. class CuraEngineBackend(Backend):
  20. def __init__(self):
  21. super().__init__()
  22. # 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.
  23. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  24. if hasattr(sys, "frozen"):
  25. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  26. if sys.platform == "win32":
  27. default_engine_location += ".exe"
  28. default_engine_location = os.path.abspath(default_engine_location)
  29. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  30. self._scene = Application.getInstance().getController().getScene()
  31. self._scene.sceneChanged.connect(self._onSceneChanged)
  32. # Workaround to disable layer view processing if layer view is not active.
  33. self._layer_view_active = False
  34. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  35. self._onActiveViewChanged()
  36. self._stored_layer_data = None
  37. self._settings = None
  38. Application.getInstance().activeMachineChanged.connect(self._onActiveMachineChanged)
  39. self._onActiveMachineChanged()
  40. self._change_timer = QTimer()
  41. self._change_timer.setInterval(500)
  42. self._change_timer.setSingleShot(True)
  43. self._change_timer.timeout.connect(self.slice)
  44. self._message_handlers[Cura_pb2.SlicedObjectList] = self._onSlicedObjectListMessage
  45. self._message_handlers[Cura_pb2.Progress] = self._onProgressMessage
  46. self._message_handlers[Cura_pb2.GCodeLayer] = self._onGCodeLayerMessage
  47. self._message_handlers[Cura_pb2.GCodePrefix] = self._onGCodePrefixMessage
  48. self._message_handlers[Cura_pb2.ObjectPrintTime] = self._onObjectPrintTimeMessage
  49. self._slicing = False
  50. self._restart = False
  51. self._save_gcode = True
  52. self._save_polygons = True
  53. self._report_progress = True
  54. self._enabled = True
  55. self.backendConnected.connect(self._onBackendConnected)
  56. def getEngineCommand(self):
  57. return [Preferences.getInstance().getValue("backend/location"), "-j", Resources.getPath(Resources.SettingsLocation, "fdmprinter.json"), "-vv", "--connect", "127.0.0.1:{0}".format(self._port)]
  58. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  59. # \param time The amount of time the print will take.
  60. # \param material_amount The amount of material the print will use.
  61. printDurationMessage = Signal()
  62. ## Emitted when the slicing process starts.
  63. slicingStarted = Signal()
  64. ## Emitted whne the slicing process is aborted forcefully.
  65. slicingCancelled = Signal()
  66. ## Perform a slice of the scene with the given set of settings.
  67. #
  68. # \param kwargs Keyword arguments.
  69. # Valid values are:
  70. # - settings: The settings to use for the slice. The default is the active machine.
  71. # - save_gcode: True if the generated gcode should be saved, False if not. True by default.
  72. # - save_polygons: True if the generated polygon data should be saved, False if not. True by default.
  73. # - force_restart: True if the slicing process should be forcefully restarted if it is already slicing.
  74. # If False, this method will do nothing when already slicing. True by default.
  75. # - report_progress: True if the slicing progress should be reported, False if not. Default is True.
  76. def slice(self, **kwargs):
  77. if not self._enabled:
  78. return
  79. if self._slicing:
  80. if not kwargs.get("force_restart", True):
  81. return
  82. self._slicing = False
  83. self._restart = True
  84. if self._process is not None:
  85. Logger.log("d", "Killing engine process")
  86. try:
  87. self._process.terminate()
  88. except: # terminating a process that is already terminating causes an exception, silently ignore this.
  89. pass
  90. self.slicingCancelled.emit()
  91. return
  92. objects = []
  93. for node in DepthFirstIterator(self._scene.getRoot()):
  94. if type(node) is SceneNode and node.getMeshData() and node.getMeshData().getVertices() is not None:
  95. if not getattr(node, "_outside_buildarea", False):
  96. objects.append(node)
  97. if not objects:
  98. return #No point in slicing an empty build plate
  99. if kwargs.get("settings", self._settings).hasErrorValue():
  100. return #No slicing if we have error values since those are by definition illegal values.
  101. self._slicing = True
  102. self.slicingStarted.emit()
  103. self._report_progress = kwargs.get("report_progress", True)
  104. if self._report_progress:
  105. self.processingProgress.emit(0.0)
  106. self._sendSettings(kwargs.get("settings", self._settings))
  107. self._scene.acquireLock()
  108. # Set the gcode as an empty list. This will be filled with strings by GCodeLayer messages.
  109. # This is done so the gcode can be fragmented in memory and does not need a continues memory space.
  110. # (AKA. This prevents MemoryErrors)
  111. self._save_gcode = kwargs.get("save_gcode", True)
  112. if self._save_gcode:
  113. setattr(self._scene, "gcode_list", [])
  114. self._save_polygons = kwargs.get("save_polygons", True)
  115. msg = Cura_pb2.ObjectList()
  116. #TODO: All at once/one at a time mode
  117. center = Vector()
  118. for object in objects:
  119. center += object.getPosition()
  120. mesh_data = object.getMeshData().getTransformed(object.getWorldTransformation())
  121. obj = msg.objects.add()
  122. obj.id = id(object)
  123. verts = numpy.array(mesh_data.getVertices())
  124. verts[:,[1,2]] = verts[:,[2,1]]
  125. verts[:,1] *= -1
  126. obj.vertices = verts.tostring()
  127. #if meshData.hasNormals():
  128. #obj.normals = meshData.getNormalsAsByteArray()
  129. #if meshData.hasIndices():
  130. #obj.indices = meshData.getIndicesAsByteArray()
  131. self._scene.releaseLock()
  132. self._socket.sendMessage(msg)
  133. def _onSceneChanged(self, source):
  134. if (type(source) is not SceneNode) or (source is self._scene.getRoot()) or (source.getMeshData() is None):
  135. return
  136. if(source.getMeshData().getVertices() is None):
  137. return
  138. self._onChanged()
  139. def _onActiveMachineChanged(self):
  140. if self._settings:
  141. self._settings.settingChanged.disconnect(self._onSettingChanged)
  142. self._settings = Application.getInstance().getActiveMachine()
  143. if self._settings:
  144. self._settings.settingChanged.connect(self._onSettingChanged)
  145. self._onChanged()
  146. def _onSettingChanged(self, setting):
  147. self._onChanged()
  148. def _onSlicedObjectListMessage(self, message):
  149. if self._save_polygons:
  150. if self._layer_view_active:
  151. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(message)
  152. job.start()
  153. else :
  154. self._stored_layer_data = message
  155. def _onProgressMessage(self, message):
  156. if message.amount >= 0.99:
  157. self._slicing = False
  158. if self._report_progress:
  159. self.processingProgress.emit(message.amount)
  160. def _onGCodeLayerMessage(self, message):
  161. if self._save_gcode:
  162. job = ProcessGCodeJob.ProcessGCodeLayerJob(message)
  163. job.start()
  164. def _onGCodePrefixMessage(self, message):
  165. if self._save_gcode:
  166. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  167. def _onObjectPrintTimeMessage(self, message):
  168. self.printDurationMessage.emit(message.time, message.material_amount)
  169. self.processingProgress.emit(1.0)
  170. def _createSocket(self):
  171. super()._createSocket()
  172. self._socket.registerMessageType(1, Cura_pb2.ObjectList)
  173. self._socket.registerMessageType(2, Cura_pb2.SlicedObjectList)
  174. self._socket.registerMessageType(3, Cura_pb2.Progress)
  175. self._socket.registerMessageType(4, Cura_pb2.GCodeLayer)
  176. self._socket.registerMessageType(5, Cura_pb2.ObjectPrintTime)
  177. self._socket.registerMessageType(6, Cura_pb2.SettingList)
  178. self._socket.registerMessageType(7, Cura_pb2.GCodePrefix)
  179. def _onChanged(self):
  180. if not self._settings:
  181. return
  182. self._change_timer.start()
  183. def _sendSettings(self, settings):
  184. msg = Cura_pb2.SettingList()
  185. for setting in settings.getAllSettings(include_machine=True):
  186. s = msg.settings.add()
  187. s.name = setting.getKey()
  188. s.value = str(setting.getValue()).encode("utf-8")
  189. self._socket.sendMessage(msg)
  190. def _onBackendConnected(self):
  191. if self._restart:
  192. self._onChanged()
  193. self._restart = False
  194. def _onToolOperationStarted(self, tool):
  195. self._enabled = False
  196. def _onToolOperationStopped(self, tool):
  197. self._enabled = True
  198. self._onChanged()
  199. def _onActiveViewChanged(self):
  200. if Application.getInstance().getController().getActiveView():
  201. view = Application.getInstance().getController().getActiveView()
  202. if view.getPluginId() == "LayerView":
  203. self._layer_view_active = True
  204. if self._stored_layer_data:
  205. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(self._stored_layer_data)
  206. job.start()
  207. else:
  208. self._layer_view_active = False