ObjectsModel.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Logger import Logger
  4. import re
  5. from typing import Dict, List, Optional, Union
  6. from PyQt5.QtCore import QTimer, Qt
  7. from UM.Application import Application
  8. from UM.Qt.ListModel import ListModel
  9. from UM.Scene.Camera import Camera
  10. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  11. from UM.Scene.SceneNode import SceneNode
  12. from UM.Scene.Selection import Selection
  13. from UM.i18n import i18nCatalog
  14. catalog = i18nCatalog("cura")
  15. # Simple convenience class to keep stuff together. Since we're still stuck on python 3.5, we can't use the full
  16. # typed named tuple, so we have to do it like this.
  17. # Once we are at python 3.6, feel free to change this to a named tuple.
  18. class _NodeInfo:
  19. def __init__(self, index_to_node: Optional[Dict[int, SceneNode]] = None, nodes_to_rename: Optional[List[SceneNode]] = None, is_group: bool = False) -> None:
  20. if index_to_node is None:
  21. index_to_node = {}
  22. if nodes_to_rename is None:
  23. nodes_to_rename = []
  24. self.index_to_node = index_to_node # type: Dict[int, SceneNode]
  25. self.nodes_to_rename = nodes_to_rename # type: List[SceneNode]
  26. self.is_group = is_group # type: bool
  27. class ObjectsModel(ListModel):
  28. """Keep track of all objects in the project"""
  29. NameRole = Qt.UserRole + 1
  30. SelectedRole = Qt.UserRole + 2
  31. OutsideAreaRole = Qt.UserRole + 3
  32. BuilplateNumberRole = Qt.UserRole + 4
  33. NodeRole = Qt.UserRole + 5
  34. PerObjectSettingsCountRole = Qt.UserRole + 6
  35. MeshTypeRole = Qt.UserRole + 7
  36. ExtruderNumberRole = Qt.UserRole + 8
  37. def __init__(self, parent = None) -> None:
  38. super().__init__(parent)
  39. self.addRoleName(self.NameRole, "name")
  40. self.addRoleName(self.SelectedRole, "selected")
  41. self.addRoleName(self.OutsideAreaRole, "outside_build_area")
  42. self.addRoleName(self.BuilplateNumberRole, "buildplate_number")
  43. self.addRoleName(self.ExtruderNumberRole, "extruder_number")
  44. self.addRoleName(self.PerObjectSettingsCountRole, "per_object_settings_count")
  45. self.addRoleName(self.MeshTypeRole, "mesh_type")
  46. self.addRoleName(self.NodeRole, "node")
  47. Application.getInstance().getController().getScene().sceneChanged.connect(self._updateSceneDelayed)
  48. Application.getInstance().getPreferences().preferenceChanged.connect(self._updateDelayed)
  49. Selection.selectionChanged.connect(self._updateDelayed)
  50. self._update_timer = QTimer()
  51. self._update_timer.setInterval(200)
  52. self._update_timer.setSingleShot(True)
  53. self._update_timer.timeout.connect(self._update)
  54. self._build_plate_number = -1
  55. self._group_name_template = catalog.i18nc("@label", "Group #{group_nr}")
  56. self._group_name_prefix = self._group_name_template.split("#")[0]
  57. self._naming_regex = re.compile("^(.+)\(([0-9]+)\)$")
  58. def setActiveBuildPlate(self, nr: int) -> None:
  59. if self._build_plate_number != nr:
  60. self._build_plate_number = nr
  61. self._update()
  62. def _updateSceneDelayed(self, source) -> None:
  63. if not isinstance(source, Camera):
  64. self._update_timer.start()
  65. def _updateDelayed(self, *args) -> None:
  66. self._update_timer.start()
  67. def _shouldNodeBeHandled(self, node: SceneNode) -> bool:
  68. is_group = bool(node.callDecoration("isGroup"))
  69. if not node.callDecoration("isSliceable") and not is_group:
  70. return False
  71. parent = node.getParent()
  72. if parent and parent.callDecoration("isGroup"):
  73. return False # Grouped nodes don't need resetting as their parent (the group) is resetted)
  74. node_build_plate_number = node.callDecoration("getBuildPlateNumber")
  75. if Application.getInstance().getPreferences().getValue("view/filter_current_build_plate") and node_build_plate_number != self._build_plate_number:
  76. return False
  77. return True
  78. @staticmethod
  79. def _renameNodes(node_info_dict: Dict[str, _NodeInfo]) -> List[SceneNode]:
  80. # Go through all names and find out the names for all nodes that need to be renamed.
  81. all_nodes = [] # type: List[SceneNode]
  82. for name, node_info in node_info_dict.items():
  83. # First add the ones that do not need to be renamed.
  84. for node in node_info.index_to_node.values():
  85. all_nodes.append(node)
  86. # Generate new names for the nodes that need to be renamed
  87. current_index = 0
  88. for node in node_info.nodes_to_rename:
  89. current_index += 1
  90. while current_index in node_info.index_to_node:
  91. current_index += 1
  92. if not node_info.is_group:
  93. new_group_name = "{0}({1})".format(name, current_index)
  94. else:
  95. new_group_name = "{0}#{1}".format(name, current_index)
  96. node.setName(new_group_name)
  97. all_nodes.append(node)
  98. return all_nodes
  99. def _update(self, *args) -> None:
  100. nodes = [] # type: List[Dict[str, Union[str, int, bool, SceneNode]]]
  101. name_to_node_info_dict = {} # type: Dict[str, _NodeInfo]
  102. for node in DepthFirstIterator(Application.getInstance().getController().getScene().getRoot()): # type: ignore
  103. if not self._shouldNodeBeHandled(node):
  104. continue
  105. is_group = bool(node.callDecoration("isGroup"))
  106. force_rename = False
  107. if not is_group:
  108. # Handle names for individual nodes
  109. name = node.getName()
  110. name_match = self._naming_regex.fullmatch(name)
  111. if name_match is None:
  112. original_name = name
  113. name_index = 0
  114. else:
  115. original_name = name_match.groups()[0]
  116. name_index = int(name_match.groups()[1])
  117. else:
  118. # Handle names for grouped nodes
  119. original_name = self._group_name_prefix
  120. current_name = node.getName()
  121. if current_name.startswith(self._group_name_prefix):
  122. name_index = int(current_name.split("#")[-1])
  123. else:
  124. # Force rename this group because this node has not been named as a group yet, probably because
  125. # it's a newly created group.
  126. name_index = 0
  127. force_rename = True
  128. if original_name not in name_to_node_info_dict:
  129. # Keep track of 2 things:
  130. # - known indices for nodes which doesn't need to be renamed
  131. # - a list of nodes that need to be renamed. When renaming then, we should avoid using the known indices.
  132. name_to_node_info_dict[original_name] = _NodeInfo(is_group = is_group)
  133. node_info = name_to_node_info_dict[original_name]
  134. if not force_rename and name_index not in node_info.index_to_node:
  135. node_info.index_to_node[name_index] = node
  136. else:
  137. node_info.nodes_to_rename.append(node)
  138. all_nodes = self._renameNodes(name_to_node_info_dict)
  139. for node in all_nodes:
  140. if hasattr(node, "isOutsideBuildArea"):
  141. is_outside_build_area = node.isOutsideBuildArea() # type: ignore
  142. else:
  143. is_outside_build_area = False
  144. node_build_plate_number = node.callDecoration("getBuildPlateNumber")
  145. node_mesh_type = ""
  146. per_object_settings_count = 0
  147. per_object_stack = node.callDecoration("getStack")
  148. if per_object_stack:
  149. per_object_settings_count = per_object_stack.getTop().getNumInstances()
  150. if node.callDecoration("isAntiOverhangMesh"):
  151. node_mesh_type = "anti_overhang_mesh"
  152. per_object_settings_count -= 1 # do not count this mesh type setting
  153. elif node.callDecoration("isSupportMesh"):
  154. node_mesh_type = "support_mesh"
  155. per_object_settings_count -= 1 # do not count this mesh type setting
  156. elif node.callDecoration("isCuttingMesh"):
  157. node_mesh_type = "cutting_mesh"
  158. per_object_settings_count -= 1 # do not count this mesh type setting
  159. elif node.callDecoration("isInfillMesh"):
  160. node_mesh_type = "infill_mesh"
  161. per_object_settings_count -= 1 # do not count this mesh type setting
  162. if per_object_settings_count > 0:
  163. if node_mesh_type == "support_mesh":
  164. # support meshes only allow support settings
  165. per_object_settings_count = 0
  166. for key in per_object_stack.getTop().getAllKeys():
  167. if per_object_stack.getTop().getInstance(key).definition.isAncestor("support"):
  168. per_object_settings_count += 1
  169. elif node_mesh_type == "anti_overhang_mesh":
  170. # anti overhang meshes ignore per model settings
  171. per_object_settings_count = 0
  172. extruder_position = node.callDecoration("getActiveExtruderPosition")
  173. if extruder_position is None:
  174. extruder_number = -1
  175. else:
  176. extruder_number = int(extruder_position)
  177. if node_mesh_type == "anti_overhang_mesh" or node.callDecoration("isGroup"):
  178. # for anti overhang meshes and groups the extruder nr is irrelevant
  179. extruder_number = -1
  180. nodes.append({
  181. "name": node.getName(),
  182. "selected": Selection.isSelected(node),
  183. "outside_build_area": is_outside_build_area,
  184. "buildplate_number": node_build_plate_number,
  185. "extruder_number": extruder_number,
  186. "per_object_settings_count": per_object_settings_count,
  187. "mesh_type": node_mesh_type,
  188. "node": node
  189. })
  190. nodes = sorted(nodes, key=lambda n: n["name"])
  191. self.setItems(nodes)