CuraSceneNode.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from copy import deepcopy
  4. from typing import cast, Dict, List, Optional
  5. from UM.Application import Application
  6. from UM.Math.AxisAlignedBox import AxisAlignedBox
  7. from UM.Math.Polygon import Polygon # For typing.
  8. from UM.Scene.SceneNode import SceneNode
  9. from UM.Scene.SceneNodeDecorator import SceneNodeDecorator # To cast the deepcopy of every decorator back to SceneNodeDecorator.
  10. import cura.CuraApplication # To get the build plate.
  11. from cura.Settings.ExtruderStack import ExtruderStack # For typing.
  12. from cura.Settings.SettingOverrideDecorator import SettingOverrideDecorator # For per-object settings.
  13. class CuraSceneNode(SceneNode):
  14. """Scene nodes that are models are only seen when selecting the corresponding build plate
  15. Note that many other nodes can just be UM SceneNode objects.
  16. """
  17. def __init__(self, parent: Optional["SceneNode"] = None, visible: bool = True, name: str = "", no_setting_override: bool = False) -> None:
  18. super().__init__(parent = parent, visible = visible, name = name)
  19. if not no_setting_override:
  20. self.addDecorator(SettingOverrideDecorator()) # Now we always have a getActiveExtruderPosition, unless explicitly disabled
  21. self._outside_buildarea = False
  22. self._print_order = 0
  23. def setOutsideBuildArea(self, new_value: bool) -> None:
  24. self._outside_buildarea = new_value
  25. @property
  26. def printOrder(self):
  27. return self._print_order
  28. @printOrder.setter
  29. def printOrder(self, new_value):
  30. self._print_order = new_value
  31. def isOutsideBuildArea(self) -> bool:
  32. return self._outside_buildarea or self.callDecoration("getBuildPlateNumber") < 0
  33. def isVisible(self) -> bool:
  34. return super().isVisible() and self.callDecoration("getBuildPlateNumber") == cura.CuraApplication.CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  35. def isSelectable(self) -> bool:
  36. return super().isSelectable() and self.callDecoration("getBuildPlateNumber") == cura.CuraApplication.CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  37. def isSupportMesh(self) -> bool:
  38. per_mesh_stack = self.callDecoration("getStack")
  39. if not per_mesh_stack:
  40. return False
  41. return per_mesh_stack.getProperty("support_mesh", "value")
  42. def getPrintingExtruder(self) -> Optional[ExtruderStack]:
  43. """Get the extruder used to print this node. If there is no active node, then the extruder in position zero is returned
  44. TODO The best way to do it is by adding the setActiveExtruder decorator to every node when is loaded
  45. """
  46. global_container_stack = Application.getInstance().getGlobalContainerStack()
  47. if global_container_stack is None:
  48. return None
  49. per_mesh_stack = self.callDecoration("getStack")
  50. extruders = global_container_stack.extruderList
  51. # Use the support extruder instead of the active extruder if this is a support_mesh
  52. if per_mesh_stack:
  53. if per_mesh_stack.getProperty("support_mesh", "value"):
  54. return extruders[int(global_container_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))]
  55. # It's only set if you explicitly choose an extruder
  56. extruder_id = self.callDecoration("getActiveExtruder")
  57. for extruder in extruders:
  58. # Find out the extruder if we know the id.
  59. if extruder_id is not None:
  60. if extruder_id == extruder.getId():
  61. return extruder
  62. else: # If the id is unknown, then return the extruder in the position 0
  63. try:
  64. if extruder.getMetaDataEntry("position", default = "0") == "0": # Check if the position is zero
  65. return extruder
  66. except ValueError:
  67. continue
  68. # This point should never be reached
  69. return None
  70. def getDiffuseColor(self) -> List[float]:
  71. """Return the color of the material used to print this model"""
  72. printing_extruder = self.getPrintingExtruder()
  73. material_color = "#808080" # Fallback color
  74. if printing_extruder is not None and printing_extruder.material:
  75. material_color = printing_extruder.material.getMetaDataEntry("color_code", default = material_color)
  76. # Colors are passed as rgb hex strings (eg "#ffffff"), and the shader needs
  77. # an rgba list of floats (eg [1.0, 1.0, 1.0, 1.0])
  78. return [
  79. int(material_color[1:3], 16) / 255,
  80. int(material_color[3:5], 16) / 255,
  81. int(material_color[5:7], 16) / 255,
  82. 1.0
  83. ]
  84. def collidesWithAreas(self, areas: List[Polygon]) -> bool:
  85. """Return if any area collides with the convex hull of this scene node"""
  86. convex_hull = self.callDecoration("getPrintingArea")
  87. if convex_hull:
  88. if not convex_hull.isValid():
  89. return False
  90. # Check for collisions between provided areas and the object
  91. for area in areas:
  92. overlap = convex_hull.intersectsPolygon(area)
  93. if overlap is None:
  94. continue
  95. return True
  96. return False
  97. def _calculateAABB(self) -> None:
  98. """Override of SceneNode._calculateAABB to exclude non-printing-meshes from bounding box"""
  99. self._aabb = None
  100. if self._mesh_data:
  101. self._aabb = self._mesh_data.getExtents(self.getWorldTransformation(copy = False))
  102. for child in self.getAllChildren():
  103. if child.callDecoration("isNonPrintingMesh"):
  104. # Non-printing-meshes inside a group should not affect push apart or drop to build plate
  105. continue
  106. child_bb = child.getBoundingBox()
  107. if child_bb is None or child_bb.minimum == child_bb.maximum:
  108. # Child had a degenerate bounding box, such as an empty group. Don't count it along.
  109. continue
  110. if self._aabb is None:
  111. self._aabb = child_bb
  112. else:
  113. self._aabb = self._aabb + child_bb
  114. if self._aabb is None: # No children that should be included? Just use your own position then, but it's an invalid AABB.
  115. position = self.getWorldPosition()
  116. self._aabb = AxisAlignedBox(minimum = position, maximum = position)
  117. def __deepcopy__(self, memo: Dict[int, object]) -> "CuraSceneNode":
  118. """Taken from SceneNode, but replaced SceneNode with CuraSceneNode"""
  119. copy = CuraSceneNode(no_setting_override = True) # Setting override will be added later
  120. copy.setTransformation(self.getLocalTransformation(copy= False))
  121. copy.setMeshData(self._mesh_data)
  122. copy.setVisible(cast(bool, deepcopy(self._visible, memo)))
  123. copy.source_mime_type = cast(str, deepcopy(self.source_mime_type, memo))
  124. copy._selectable = cast(bool, deepcopy(self._selectable, memo))
  125. copy._name = cast(str, deepcopy(self._name, memo))
  126. for decorator in self._decorators:
  127. copy.addDecorator(cast(SceneNodeDecorator, deepcopy(decorator, memo)))
  128. for child in self._children:
  129. copy.addChild(cast(SceneNode, deepcopy(child, memo)))
  130. self.calculateBoundingBoxMesh()
  131. return copy
  132. def transformChanged(self) -> None:
  133. self._transformChanged()
  134. def __repr__(self) -> str:
  135. return "{print_order}. {name}".format(print_order = self._print_order, name = self.getName())