StartSliceJob.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. import numpy
  4. from string import Formatter
  5. from enum import IntEnum
  6. import time
  7. from UM.Job import Job
  8. from UM.Application import Application
  9. from UM.Logger import Logger
  10. from UM.Scene.SceneNode import SceneNode
  11. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  12. from UM.Settings.Validator import ValidatorState
  13. from UM.Settings.SettingRelation import RelationType
  14. from cura.OneAtATimeIterator import OneAtATimeIterator
  15. from cura.Settings.ExtruderManager import ExtruderManager
  16. class StartJobResult(IntEnum):
  17. Finished = 1
  18. Error = 2
  19. SettingError = 3
  20. NothingToSlice = 4
  21. MaterialIncompatible = 5
  22. BuildPlateError = 6
  23. ## Formatter class that handles token expansion in start/end gcod
  24. class GcodeStartEndFormatter(Formatter):
  25. def get_value(self, key, args, kwargs): # [CodeStyle: get_value is an overridden function from the Formatter class]
  26. if isinstance(key, str):
  27. try:
  28. return kwargs[key]
  29. except KeyError:
  30. Logger.log("w", "Unable to replace '%s' placeholder in start/end gcode", key)
  31. return "{" + key + "}"
  32. else:
  33. Logger.log("w", "Incorrectly formatted placeholder '%s' in start/end gcode", key)
  34. return "{" + str(key) + "}"
  35. ## Job class that builds up the message of scene data to send to CuraEngine.
  36. class StartSliceJob(Job):
  37. def __init__(self, slice_message):
  38. super().__init__()
  39. self._scene = Application.getInstance().getController().getScene()
  40. self._slice_message = slice_message
  41. self._is_cancelled = False
  42. def getSliceMessage(self):
  43. return self._slice_message
  44. ## Check if a stack has any errors.
  45. ## returns true if it has errors, false otherwise.
  46. def _checkStackForErrors(self, stack):
  47. if stack is None:
  48. return False
  49. for key in stack.getAllKeys():
  50. validation_state = stack.getProperty(key, "validationState")
  51. if validation_state in (ValidatorState.Exception, ValidatorState.MaximumError, ValidatorState.MinimumError):
  52. Logger.log("w", "Setting %s is not valid, but %s. Aborting slicing.", key, validation_state)
  53. return True
  54. Job.yieldThread()
  55. return False
  56. ## Runs the job that initiates the slicing.
  57. def run(self):
  58. stack = Application.getInstance().getGlobalContainerStack()
  59. if not stack:
  60. self.setResult(StartJobResult.Error)
  61. return
  62. # Don't slice if there is a setting with an error value.
  63. if Application.getInstance().getMachineManager().stacksHaveErrors:
  64. self.setResult(StartJobResult.SettingError)
  65. return
  66. if Application.getInstance().getBuildVolume().hasErrors():
  67. self.setResult(StartJobResult.BuildPlateError)
  68. return
  69. for extruder_stack in ExtruderManager.getInstance().getMachineExtruders(stack.getId()):
  70. material = extruder_stack.findContainer({"type": "material"})
  71. if material:
  72. if material.getMetaDataEntry("compatible") == False:
  73. self.setResult(StartJobResult.MaterialIncompatible)
  74. return
  75. # Don't slice if there is a per object setting with an error value.
  76. for node in DepthFirstIterator(self._scene.getRoot()):
  77. if type(node) is not SceneNode or not node.isSelectable():
  78. continue
  79. if self._checkStackForErrors(node.callDecoration("getStack")):
  80. self.setResult(StartJobResult.SettingError)
  81. return
  82. with self._scene.getSceneLock():
  83. # Remove old layer data.
  84. for node in DepthFirstIterator(self._scene.getRoot()):
  85. if node.callDecoration("getLayerData"):
  86. node.getParent().removeChild(node)
  87. break
  88. # Get the objects in their groups to print.
  89. object_groups = []
  90. if stack.getProperty("print_sequence", "value") == "one_at_a_time":
  91. for node in OneAtATimeIterator(self._scene.getRoot()):
  92. temp_list = []
  93. # Node can't be printed, so don't bother sending it.
  94. if getattr(node, "_outside_buildarea", False):
  95. continue
  96. children = node.getAllChildren()
  97. children.append(node)
  98. for child_node in children:
  99. if type(child_node) is SceneNode and child_node.getMeshData() and child_node.getMeshData().getVertices() is not None:
  100. temp_list.append(child_node)
  101. if temp_list:
  102. object_groups.append(temp_list)
  103. Job.yieldThread()
  104. if len(object_groups) == 0:
  105. Logger.log("w", "No objects suitable for one at a time found, or no correct order found")
  106. else:
  107. temp_list = []
  108. for node in DepthFirstIterator(self._scene.getRoot()):
  109. if type(node) is SceneNode and node.getMeshData() and node.getMeshData().getVertices() is not None:
  110. if not getattr(node, "_outside_buildarea", False):
  111. temp_list.append(node)
  112. Job.yieldThread()
  113. if temp_list:
  114. object_groups.append(temp_list)
  115. # There are cases when there is nothing to slice. This can happen due to one at a time slicing not being
  116. # able to find a possible sequence or because there are no objects on the build plate (or they are outside
  117. # the build volume)
  118. if not object_groups:
  119. self.setResult(StartJobResult.NothingToSlice)
  120. return
  121. self._buildGlobalSettingsMessage(stack)
  122. self._buildGlobalInheritsStackMessage(stack)
  123. # Only add extruder stacks if there are multiple extruders
  124. # Single extruder machines only use the global stack to store setting values
  125. if stack.getProperty("machine_extruder_count", "value") > 1:
  126. for extruder_stack in ExtruderManager.getInstance().getMachineExtruders(stack.getId()):
  127. self._buildExtruderMessage(extruder_stack)
  128. else:
  129. self._buildExtruderMessageFromGlobalStack(stack)
  130. for group in object_groups:
  131. group_message = self._slice_message.addRepeatedMessage("object_lists")
  132. if group[0].getParent().callDecoration("isGroup"):
  133. self._handlePerObjectSettings(group[0].getParent(), group_message)
  134. for object in group:
  135. mesh_data = object.getMeshData()
  136. rot_scale = object.getWorldTransformation().getTransposed().getData()[0:3, 0:3]
  137. translate = object.getWorldTransformation().getData()[:3, 3]
  138. # This effectively performs a limited form of MeshData.getTransformed that ignores normals.
  139. verts = mesh_data.getVertices()
  140. verts = verts.dot(rot_scale)
  141. verts += translate
  142. # Convert from Y up axes to Z up axes. Equals a 90 degree rotation.
  143. verts[:, [1, 2]] = verts[:, [2, 1]]
  144. verts[:, 1] *= -1
  145. obj = group_message.addRepeatedMessage("objects")
  146. obj.id = id(object)
  147. indices = mesh_data.getIndices()
  148. if indices is not None:
  149. flat_verts = numpy.take(verts, indices.flatten(), axis=0)
  150. else:
  151. flat_verts = numpy.array(verts)
  152. obj.vertices = flat_verts
  153. self._handlePerObjectSettings(object, obj)
  154. Job.yieldThread()
  155. self.setResult(StartJobResult.Finished)
  156. def cancel(self):
  157. super().cancel()
  158. self._is_cancelled = True
  159. def isCancelled(self):
  160. return self._is_cancelled
  161. def _expandGcodeTokens(self, key, value, settings):
  162. try:
  163. # any setting can be used as a token
  164. fmt = GcodeStartEndFormatter()
  165. return str(fmt.format(value, **settings)).encode("utf-8")
  166. except:
  167. Logger.logException("w", "Unable to do token replacement on start/end gcode")
  168. return str(value).encode("utf-8")
  169. ## Create extruder message from stack
  170. def _buildExtruderMessage(self, stack):
  171. message = self._slice_message.addRepeatedMessage("extruders")
  172. message.id = int(stack.getMetaDataEntry("position"))
  173. material_instance_container = stack.findContainer({"type": "material"})
  174. for key in stack.getAllKeys():
  175. # Do not send settings that are not settable_per_extruder.
  176. if stack.getProperty(key, "settable_per_extruder") == False:
  177. continue
  178. setting = message.getMessage("settings").addRepeatedMessage("settings")
  179. setting.name = key
  180. if key == "material_guid" and material_instance_container:
  181. # Also send the material GUID. This is a setting in fdmprinter, but we have no interface for it.
  182. setting.value = str(material_instance_container.getMetaDataEntry("GUID", "")).encode("utf-8")
  183. else:
  184. setting.value = str(stack.getProperty(key, "value")).encode("utf-8")
  185. Job.yieldThread()
  186. ## Create extruder message from global stack
  187. def _buildExtruderMessageFromGlobalStack(self, stack):
  188. message = self._slice_message.addRepeatedMessage("extruders")
  189. for key in stack.getAllKeys():
  190. # Do not send settings that are not settable_per_extruder.
  191. if not stack.getProperty(key, "settable_per_extruder"):
  192. continue
  193. setting = message.getMessage("settings").addRepeatedMessage("settings")
  194. setting.name = key
  195. setting.value = str(stack.getProperty(key, "value")).encode("utf-8")
  196. Job.yieldThread()
  197. ## Sends all global settings to the engine.
  198. #
  199. # The settings are taken from the global stack. This does not include any
  200. # per-extruder settings or per-object settings.
  201. def _buildGlobalSettingsMessage(self, stack):
  202. keys = stack.getAllKeys()
  203. settings = {}
  204. for key in keys:
  205. settings[key] = stack.getProperty(key, "value")
  206. Job.yieldThread()
  207. start_gcode = settings["machine_start_gcode"]
  208. #Pre-compute material material_bed_temp_prepend and material_print_temp_prepend
  209. bed_temperature_settings = {"material_bed_temperature", "material_bed_temperature_layer_0"}
  210. settings["material_bed_temp_prepend"] = all(("{" + setting + "}" not in start_gcode for setting in bed_temperature_settings))
  211. print_temperature_settings = {"material_print_temperature", "material_print_temperature_layer_0", "default_material_print_temperature", "material_initial_print_temperature", "material_final_print_temperature", "material_standby_temperature"}
  212. settings["material_print_temp_prepend"] = all(("{" + setting + "}" not in start_gcode for setting in print_temperature_settings))
  213. settings["print_bed_temperature"] = settings["material_bed_temperature"]
  214. settings["print_temperature"] = settings["material_print_temperature"]
  215. settings["time"] = time.strftime('%H:%M:%S')
  216. settings["date"] = time.strftime('%d-%m-%Y')
  217. settings["day"] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))]
  218. for key, value in settings.items(): #Add all submessages for each individual setting.
  219. setting_message = self._slice_message.getMessage("global_settings").addRepeatedMessage("settings")
  220. setting_message.name = key
  221. if key == "machine_start_gcode" or key == "machine_end_gcode" or key == "machine_extruder_start_code" or key == "machine_extruder_end_code": #If it's a g-code message, use special formatting.
  222. setting_message.value = self._expandGcodeTokens(key, value, settings)
  223. else:
  224. setting_message.value = str(value).encode("utf-8")
  225. Job.yieldThread()
  226. ## Sends for some settings which extruder they should fallback to if not
  227. # set.
  228. #
  229. # This is only set for settings that have the limit_to_extruder
  230. # property.
  231. #
  232. # \param stack The global stack with all settings, from which to read the
  233. # limit_to_extruder property.
  234. def _buildGlobalInheritsStackMessage(self, stack):
  235. for key in stack.getAllKeys():
  236. extruder = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
  237. if extruder >= 0: #Set to a specific extruder.
  238. setting_extruder = self._slice_message.addRepeatedMessage("limit_to_extruder")
  239. setting_extruder.name = key
  240. setting_extruder.extruder = extruder
  241. Job.yieldThread()
  242. ## Check if a node has per object settings and ensure that they are set correctly in the message
  243. # \param node \type{SceneNode} Node to check.
  244. # \param message object_lists message to put the per object settings in
  245. def _handlePerObjectSettings(self, node, message):
  246. stack = node.callDecoration("getStack")
  247. # Check if the node has a stack attached to it and the stack has any settings in the top container.
  248. if stack:
  249. # Check all settings for relations, so we can also calculate the correct values for dependant settings.
  250. changed_setting_keys = set(stack.getTop().getAllKeys())
  251. for key in stack.getTop().getAllKeys():
  252. instance = stack.getTop().getInstance(key)
  253. self._addRelations(changed_setting_keys, instance.definition.relations)
  254. Job.yieldThread()
  255. # Ensure that the engine is aware what the build extruder is
  256. if stack.getProperty("machine_extruder_count", "value") > 1:
  257. changed_setting_keys.add("extruder_nr")
  258. # Get values for all changed settings
  259. for key in changed_setting_keys:
  260. setting = message.addRepeatedMessage("settings")
  261. setting.name = key
  262. setting.value = str(stack.getProperty(key, "value")).encode("utf-8")
  263. Job.yieldThread()
  264. ## Recursive function to put all settings that require eachother for value changes in a list
  265. # \param relations_set \type{set} Set of keys (strings) of settings that are influenced
  266. # \param relations list of relation objects that need to be checked.
  267. def _addRelations(self, relations_set, relations):
  268. for relation in filter(lambda r: r.role == "value", relations):
  269. if relation.type == RelationType.RequiresTarget:
  270. continue
  271. relations_set.add(relation.target.key)
  272. self._addRelations(relations_set, relation.target.relations)