ExtruderManager.py 21 KB

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