ExtruderManager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import pyqtSignal, pyqtProperty, QObject, QVariant # For communicating data and events to Qt.
  4. from UM.FlameProfiler import pyqtSlot
  5. import cura.CuraApplication # To get the global container stack to find the current machine.
  6. from cura.Settings.GlobalStack import GlobalStack
  7. from UM.Logger import Logger
  8. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  9. from UM.Scene.SceneNode import SceneNode
  10. from UM.Scene.Selection import Selection
  11. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  12. from UM.Settings.ContainerRegistry import ContainerRegistry # Finding containers by ID.
  13. from UM.Decorators import deprecated
  14. from typing import Any, cast, Dict, List, Optional, TYPE_CHECKING, Union
  15. if TYPE_CHECKING:
  16. from cura.Settings.ExtruderStack import ExtruderStack
  17. ## Manages all existing extruder stacks.
  18. #
  19. # This keeps a list of extruder stacks for each machine.
  20. class ExtruderManager(QObject):
  21. ## Registers listeners and such to listen to changes to the extruders.
  22. def __init__(self, parent = None):
  23. if ExtruderManager.__instance is not None:
  24. raise RuntimeError("Try to create singleton '%s' more than once" % self.__class__.__name__)
  25. ExtruderManager.__instance = self
  26. super().__init__(parent)
  27. self._application = cura.CuraApplication.CuraApplication.getInstance()
  28. # Per machine, a dictionary of extruder container stack IDs. Only for separately defined extruders.
  29. self._extruder_trains = {} # type: Dict[str, Dict[str, "ExtruderStack"]]
  30. self._active_extruder_index = -1 # Indicates the index of the active extruder stack. -1 means no active extruder stack
  31. # TODO; I have no idea why this is a union of ID's and extruder stacks. This needs to be fixed at some point.
  32. self._selected_object_extruders = [] # type: List[Union[str, "ExtruderStack"]]
  33. self._addCurrentMachineExtruders()
  34. Selection.selectionChanged.connect(self.resetSelectedObjectExtruders)
  35. ## Signal to notify other components when the list of extruders for a machine definition changes.
  36. extrudersChanged = pyqtSignal(QVariant)
  37. ## Notify when the user switches the currently active extruder.
  38. activeExtruderChanged = pyqtSignal()
  39. ## Gets the unique identifier of the currently active extruder stack.
  40. #
  41. # The currently active extruder stack is the stack that is currently being
  42. # edited.
  43. #
  44. # \return The unique ID of the currently active extruder stack.
  45. @pyqtProperty(str, notify = activeExtruderChanged)
  46. def activeExtruderStackId(self) -> Optional[str]:
  47. if not self._application.getGlobalContainerStack():
  48. return None # No active machine, so no active extruder.
  49. try:
  50. return self._extruder_trains[self._application.getGlobalContainerStack().getId()][str(self.activeExtruderIndex)].getId()
  51. except KeyError: # Extruder index could be -1 if the global tab is selected, or the entry doesn't exist if the machine definition is wrong.
  52. return None
  53. ## Gets a dict with the extruder stack ids with the extruder number as the key.
  54. @pyqtProperty("QVariantMap", notify = extrudersChanged)
  55. def extruderIds(self) -> Dict[str, str]:
  56. extruder_stack_ids = {} # type: Dict[str, str]
  57. global_container_stack = self._application.getGlobalContainerStack()
  58. if global_container_stack:
  59. extruder_stack_ids = {position: extruder.id for position, extruder in global_container_stack.extruders.items()}
  60. return extruder_stack_ids
  61. ## Changes the active extruder by index.
  62. #
  63. # \param index The index of the new active extruder.
  64. @pyqtSlot(int)
  65. def setActiveExtruderIndex(self, index: int) -> None:
  66. if self._active_extruder_index != index:
  67. self._active_extruder_index = index
  68. self.activeExtruderChanged.emit()
  69. @pyqtProperty(int, notify = activeExtruderChanged)
  70. def activeExtruderIndex(self) -> int:
  71. return self._active_extruder_index
  72. ## Gets the extruder name of an extruder of the currently active machine.
  73. #
  74. # \param index The index of the extruder whose name to get.
  75. @pyqtSlot(int, result = str)
  76. @deprecated("Use Cura.MachineManager.activeMachine.extruders[index].name instead", "4.3")
  77. def getExtruderName(self, index: int) -> str:
  78. try:
  79. return self.getActiveExtruderStacks()[index].getName()
  80. except IndexError:
  81. return ""
  82. ## Emitted whenever the selectedObjectExtruders property changes.
  83. selectedObjectExtrudersChanged = pyqtSignal()
  84. ## Provides a list of extruder IDs used by the current selected objects.
  85. @pyqtProperty("QVariantList", notify = selectedObjectExtrudersChanged)
  86. def selectedObjectExtruders(self) -> List[Union[str, "ExtruderStack"]]:
  87. if not self._selected_object_extruders:
  88. object_extruders = set()
  89. # First, build a list of the actual selected objects (including children of groups, excluding group nodes)
  90. selected_nodes = [] # type: List["SceneNode"]
  91. for node in Selection.getAllSelectedObjects():
  92. if node.callDecoration("isGroup"):
  93. for grouped_node in BreadthFirstIterator(node):
  94. if grouped_node.callDecoration("isGroup"):
  95. continue
  96. selected_nodes.append(grouped_node)
  97. else:
  98. selected_nodes.append(node)
  99. # Then, figure out which nodes are used by those selected nodes.
  100. current_extruder_trains = self.getActiveExtruderStacks()
  101. for node in selected_nodes:
  102. extruder = node.callDecoration("getActiveExtruder")
  103. if extruder:
  104. object_extruders.add(extruder)
  105. elif current_extruder_trains:
  106. object_extruders.add(current_extruder_trains[0].getId())
  107. self._selected_object_extruders = list(object_extruders)
  108. return self._selected_object_extruders
  109. ## Reset the internal list used for the selectedObjectExtruders property
  110. #
  111. # This will trigger a recalculation of the extruders used for the
  112. # selection.
  113. def resetSelectedObjectExtruders(self) -> None:
  114. self._selected_object_extruders = []
  115. self.selectedObjectExtrudersChanged.emit()
  116. @pyqtSlot(result = QObject)
  117. def getActiveExtruderStack(self) -> Optional["ExtruderStack"]:
  118. return self.getExtruderStack(self.activeExtruderIndex)
  119. ## Get an extruder stack by index
  120. def getExtruderStack(self, index) -> Optional["ExtruderStack"]:
  121. global_container_stack = self._application.getGlobalContainerStack()
  122. if global_container_stack:
  123. if global_container_stack.getId() in self._extruder_trains:
  124. if str(index) in self._extruder_trains[global_container_stack.getId()]:
  125. return self._extruder_trains[global_container_stack.getId()][str(index)]
  126. return None
  127. def registerExtruder(self, extruder_train: "ExtruderStack", machine_id: str) -> None:
  128. changed = False
  129. if machine_id not in self._extruder_trains:
  130. self._extruder_trains[machine_id] = {}
  131. changed = True
  132. # do not register if an extruder has already been registered at the position on this machine
  133. if any(item.getId() == extruder_train.getId() for item in self._extruder_trains[machine_id].values()):
  134. Logger.log("w", "Extruder [%s] has already been registered on machine [%s], not doing anything",
  135. extruder_train.getId(), machine_id)
  136. return
  137. if extruder_train:
  138. self._extruder_trains[machine_id][extruder_train.getMetaDataEntry("position")] = extruder_train
  139. changed = True
  140. if changed:
  141. self.extrudersChanged.emit(machine_id)
  142. ## Gets a property of a setting for all extruders.
  143. #
  144. # \param setting_key \type{str} The setting to get the property of.
  145. # \param property \type{str} The property to get.
  146. # \return \type{List} the list of results
  147. def getAllExtruderSettings(self, setting_key: str, prop: str) -> List[Any]:
  148. result = []
  149. for extruder_stack in self.getActiveExtruderStacks():
  150. result.append(extruder_stack.getProperty(setting_key, prop))
  151. return result
  152. def extruderValueWithDefault(self, value: str) -> str:
  153. machine_manager = self._application.getMachineManager()
  154. if value == "-1":
  155. return machine_manager.defaultExtruderPosition
  156. else:
  157. return value
  158. ## Gets the extruder stacks that are actually being used at the moment.
  159. #
  160. # An extruder stack is being used if it is the extruder to print any mesh
  161. # with, or if it is the support infill extruder, the support interface
  162. # extruder, or the bed adhesion extruder.
  163. #
  164. # If there are no extruders, this returns the global stack as a singleton
  165. # list.
  166. #
  167. # \return A list of extruder stacks.
  168. def getUsedExtruderStacks(self) -> List["ExtruderStack"]:
  169. global_stack = self._application.getGlobalContainerStack()
  170. container_registry = ContainerRegistry.getInstance()
  171. used_extruder_stack_ids = set()
  172. # Get the extruders of all meshes in the scene
  173. support_enabled = False
  174. support_bottom_enabled = False
  175. support_roof_enabled = False
  176. scene_root = self._application.getController().getScene().getRoot()
  177. # If no extruders are registered in the extruder manager yet, return an empty array
  178. if len(self.extruderIds) == 0:
  179. return []
  180. # Get the extruders of all printable meshes in the scene
  181. meshes = [node for node in DepthFirstIterator(scene_root) if isinstance(node, SceneNode) and node.isSelectable()] #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  182. # Exclude anti-overhang meshes
  183. mesh_list = []
  184. for mesh in meshes:
  185. stack = mesh.callDecoration("getStack")
  186. if stack is not None and (stack.getProperty("anti_overhang_mesh", "value") or stack.getProperty("support_mesh", "value")):
  187. continue
  188. mesh_list.append(mesh)
  189. for mesh in mesh_list:
  190. extruder_stack_id = mesh.callDecoration("getActiveExtruder")
  191. if not extruder_stack_id:
  192. # No per-object settings for this node
  193. extruder_stack_id = self.extruderIds["0"]
  194. used_extruder_stack_ids.add(extruder_stack_id)
  195. # Get whether any of them use support.
  196. stack_to_use = mesh.callDecoration("getStack") # if there is a per-mesh stack, we use it
  197. if not stack_to_use:
  198. # if there is no per-mesh stack, we use the build extruder for this mesh
  199. stack_to_use = container_registry.findContainerStacks(id = extruder_stack_id)[0]
  200. support_enabled |= stack_to_use.getProperty("support_enable", "value")
  201. support_bottom_enabled |= stack_to_use.getProperty("support_bottom_enable", "value")
  202. support_roof_enabled |= stack_to_use.getProperty("support_roof_enable", "value")
  203. # Check limit to extruders
  204. limit_to_extruder_feature_list = ["wall_0_extruder_nr",
  205. "wall_x_extruder_nr",
  206. "roofing_extruder_nr",
  207. "top_bottom_extruder_nr",
  208. "infill_extruder_nr",
  209. ]
  210. for extruder_nr_feature_name in limit_to_extruder_feature_list:
  211. extruder_nr = int(global_stack.getProperty(extruder_nr_feature_name, "value"))
  212. if extruder_nr == -1:
  213. continue
  214. used_extruder_stack_ids.add(self.extruderIds[str(extruder_nr)])
  215. # Check support extruders
  216. if support_enabled:
  217. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_infill_extruder_nr", "value")))])
  218. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_extruder_nr_layer_0", "value")))])
  219. if support_bottom_enabled:
  220. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_bottom_extruder_nr", "value")))])
  221. if support_roof_enabled:
  222. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_roof_extruder_nr", "value")))])
  223. # The platform adhesion extruder. Not used if using none.
  224. if global_stack.getProperty("adhesion_type", "value") != "none" or (
  225. global_stack.getProperty("prime_tower_brim_enable", "value") and
  226. global_stack.getProperty("adhesion_type", "value") != 'raft'):
  227. extruder_str_nr = str(global_stack.getProperty("adhesion_extruder_nr", "value"))
  228. if extruder_str_nr == "-1":
  229. extruder_str_nr = self._application.getMachineManager().defaultExtruderPosition
  230. if extruder_str_nr in self.extruderIds:
  231. used_extruder_stack_ids.add(self.extruderIds[extruder_str_nr])
  232. try:
  233. return [container_registry.findContainerStacks(id = stack_id)[0] for stack_id in used_extruder_stack_ids]
  234. except IndexError: # One or more of the extruders was not found.
  235. Logger.log("e", "Unable to find one or more of the extruders in %s", used_extruder_stack_ids)
  236. return []
  237. ## Removes the container stack and user profile for the extruders for a specific machine.
  238. #
  239. # \param machine_id The machine to remove the extruders for.
  240. def removeMachineExtruders(self, machine_id: str) -> None:
  241. for extruder in self.getMachineExtruders(machine_id):
  242. ContainerRegistry.getInstance().removeContainer(extruder.userChanges.getId())
  243. ContainerRegistry.getInstance().removeContainer(extruder.getId())
  244. if machine_id in self._extruder_trains:
  245. del self._extruder_trains[machine_id]
  246. ## Returns extruders for a specific machine.
  247. #
  248. # \param machine_id The machine to get the extruders of.
  249. def getMachineExtruders(self, machine_id: str) -> List["ExtruderStack"]:
  250. if machine_id not in self._extruder_trains:
  251. return []
  252. return [self._extruder_trains[machine_id][name] for name in self._extruder_trains[machine_id]]
  253. ## Returns the list of active extruder stacks, taking into account the machine extruder count.
  254. #
  255. # \return \type{List[ContainerStack]} a list of
  256. def getActiveExtruderStacks(self) -> List["ExtruderStack"]:
  257. global_stack = self._application.getGlobalContainerStack()
  258. if not global_stack:
  259. return []
  260. return global_stack.extruderList
  261. def _globalContainerStackChanged(self) -> None:
  262. # If the global container changed, the machine changed and might have extruders that were not registered yet
  263. self._addCurrentMachineExtruders()
  264. self.resetSelectedObjectExtruders()
  265. ## Adds the extruders of the currently active machine.
  266. def _addCurrentMachineExtruders(self) -> None:
  267. global_stack = self._application.getGlobalContainerStack()
  268. extruders_changed = False
  269. if global_stack:
  270. container_registry = ContainerRegistry.getInstance()
  271. global_stack_id = global_stack.getId()
  272. # Gets the extruder trains that we just created as well as any that still existed.
  273. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = global_stack_id)
  274. # Make sure the extruder trains for the new machine can be placed in the set of sets
  275. if global_stack_id not in self._extruder_trains:
  276. self._extruder_trains[global_stack_id] = {}
  277. extruders_changed = True
  278. # Register the extruder trains by position
  279. for extruder_train in extruder_trains:
  280. extruder_position = extruder_train.getMetaDataEntry("position")
  281. self._extruder_trains[global_stack_id][extruder_position] = extruder_train
  282. # regardless of what the next stack is, we have to set it again, because of signal routing. ???
  283. extruder_train.setParent(global_stack)
  284. extruder_train.setNextStack(global_stack)
  285. extruders_changed = True
  286. self.fixSingleExtrusionMachineExtruderDefinition(global_stack)
  287. if extruders_changed:
  288. self.extrudersChanged.emit(global_stack_id)
  289. self.setActiveExtruderIndex(0)
  290. self.activeExtruderChanged.emit()
  291. # After 3.4, all single-extrusion machines have their own extruder definition files instead of reusing
  292. # "fdmextruder". We need to check a machine here so its extruder definition is correct according to this.
  293. def fixSingleExtrusionMachineExtruderDefinition(self, global_stack: "GlobalStack") -> None:
  294. container_registry = ContainerRegistry.getInstance()
  295. expected_extruder_definition_0_id = global_stack.getMetaDataEntry("machine_extruder_trains")["0"]
  296. extruder_stack_0 = global_stack.extruders.get("0")
  297. # At this point, extruder stacks for this machine may not have been loaded yet. In this case, need to look in
  298. # the container registry as well.
  299. if not global_stack.extruders:
  300. extruder_trains = container_registry.findContainerStacks(type = "extruder_train",
  301. machine = global_stack.getId())
  302. if extruder_trains:
  303. for extruder in extruder_trains:
  304. if extruder.getMetaDataEntry("position") == "0":
  305. extruder_stack_0 = extruder
  306. break
  307. if extruder_stack_0 is None:
  308. Logger.log("i", "No extruder stack for global stack [%s], create one", global_stack.getId())
  309. # Single extrusion machine without an ExtruderStack, create it
  310. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  311. CuraStackBuilder.createExtruderStackWithDefaultSetup(global_stack, 0)
  312. elif extruder_stack_0.definition.getId() != expected_extruder_definition_0_id:
  313. Logger.log("e", "Single extruder printer [{printer}] expected extruder [{expected}], but got [{got}]. I'm making it [{expected}].".format(
  314. printer = global_stack.getId(), expected = expected_extruder_definition_0_id, got = extruder_stack_0.definition.getId()))
  315. try:
  316. extruder_definition = container_registry.findDefinitionContainers(id = expected_extruder_definition_0_id)[0]
  317. except IndexError as e:
  318. # It still needs to break, but we want to know what extruder ID made it break.
  319. msg = "Unable to find extruder definition with the id [%s]" % expected_extruder_definition_0_id
  320. Logger.logException("e", msg)
  321. raise IndexError(msg)
  322. extruder_stack_0.definition = extruder_definition
  323. ## Get all extruder values for a certain setting.
  324. #
  325. # This is exposed to qml for display purposes
  326. #
  327. # \param key The key of the setting to retrieve values for.
  328. #
  329. # \return String representing the extruder values
  330. @pyqtSlot(str, result="QVariant")
  331. def getInstanceExtruderValues(self, key: str) -> List:
  332. return self._application.getCuraFormulaFunctions().getValuesInAllExtruders(key)
  333. ## Get the resolve value or value for a given key
  334. #
  335. # This is the effective value for a given key, it is used for values in the global stack.
  336. # This is exposed to SettingFunction to use in value functions.
  337. # \param key The key of the setting to get the value of.
  338. #
  339. # \return The effective value
  340. @staticmethod
  341. def getResolveOrValue(key: str) -> Any:
  342. global_stack = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack())
  343. resolved_value = global_stack.getProperty(key, "value")
  344. return resolved_value
  345. __instance = None # type: ExtruderManager
  346. @classmethod
  347. def getInstance(cls, *args, **kwargs) -> "ExtruderManager":
  348. return cls.__instance