SupportEraser.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import Qt, QTimer
  4. from PyQt5.QtWidgets import QApplication
  5. from UM.Application import Application
  6. from UM.Math.Vector import Vector
  7. from UM.Operations.TranslateOperation import TranslateOperation
  8. from UM.Tool import Tool
  9. from UM.Event import Event, MouseEvent
  10. from UM.Mesh.MeshBuilder import MeshBuilder
  11. from UM.Scene.Selection import Selection
  12. from cura.CuraApplication import CuraApplication
  13. from cura.Scene.CuraSceneNode import CuraSceneNode
  14. from cura.PickingPass import PickingPass
  15. from UM.Operations.GroupedOperation import GroupedOperation
  16. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  17. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  18. from cura.Operations.SetParentOperation import SetParentOperation
  19. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  20. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  21. from UM.Settings.SettingInstance import SettingInstance
  22. import numpy
  23. class SupportEraser(Tool):
  24. def __init__(self):
  25. super().__init__()
  26. self._shortcut_key = Qt.Key_E
  27. self._controller = self.getController()
  28. self._selection_pass = None
  29. CuraApplication.getInstance().globalContainerStackChanged.connect(self._updateEnabled)
  30. # Note: if the selection is cleared with this tool active, there is no way to switch to
  31. # another tool than to reselect an object (by clicking it) because the tool buttons in the
  32. # toolbar will have been disabled. That is why we need to ignore the first press event
  33. # after the selection has been cleared.
  34. Selection.selectionChanged.connect(self._onSelectionChanged)
  35. self._had_selection = False
  36. self._skip_press = False
  37. self._had_selection_timer = QTimer()
  38. self._had_selection_timer.setInterval(0)
  39. self._had_selection_timer.setSingleShot(True)
  40. self._had_selection_timer.timeout.connect(self._selectionChangeDelay)
  41. def event(self, event):
  42. super().event(event)
  43. modifiers = QApplication.keyboardModifiers()
  44. ctrl_is_active = modifiers & Qt.ControlModifier
  45. if event.type == Event.MousePressEvent and MouseEvent.LeftButton in event.buttons and self._controller.getToolsEnabled():
  46. if ctrl_is_active:
  47. self._controller.setActiveTool("TranslateTool")
  48. return
  49. if self._skip_press:
  50. # The selection was previously cleared, do not add/remove an anti-support mesh but
  51. # use this click for selection and reactivating this tool only.
  52. self._skip_press = False
  53. return
  54. if self._selection_pass is None:
  55. # The selection renderpass is used to identify objects in the current view
  56. self._selection_pass = Application.getInstance().getRenderer().getRenderPass("selection")
  57. picked_node = self._controller.getScene().findObject(self._selection_pass.getIdAtPosition(event.x, event.y))
  58. if not picked_node:
  59. # There is no slicable object at the picked location
  60. return
  61. node_stack = picked_node.callDecoration("getStack")
  62. if node_stack:
  63. if node_stack.getProperty("anti_overhang_mesh", "value"):
  64. self._removeEraserMesh(picked_node)
  65. return
  66. elif node_stack.getProperty("support_mesh", "value") or node_stack.getProperty("infill_mesh", "value") or node_stack.getProperty("cutting_mesh", "value"):
  67. # Only "normal" meshes can have anti_overhang_meshes added to them
  68. return
  69. # Create a pass for picking a world-space location from the mouse location
  70. active_camera = self._controller.getScene().getActiveCamera()
  71. picking_pass = PickingPass(active_camera.getViewportWidth(), active_camera.getViewportHeight())
  72. picking_pass.render()
  73. picked_position = picking_pass.getPickedPosition(event.x, event.y)
  74. # Add the anti_overhang_mesh cube at the picked location
  75. self._createEraserMesh(picked_node, picked_position)
  76. def _createEraserMesh(self, parent: CuraSceneNode, position: Vector):
  77. node = CuraSceneNode()
  78. node.setName("Eraser")
  79. node.setSelectable(True)
  80. node.setCalculateBoundingBox(True)
  81. mesh = self._createCube(10)
  82. node.setMeshData(mesh.build())
  83. node.calculateBoundingBoxMesh()
  84. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  85. node.addDecorator(BuildPlateDecorator(active_build_plate))
  86. node.addDecorator(SliceableObjectDecorator())
  87. stack = node.callDecoration("getStack") # created by SettingOverrideDecorator that is automatically added to CuraSceneNode
  88. settings = stack.getTop()
  89. definition = stack.getSettingDefinition("anti_overhang_mesh")
  90. new_instance = SettingInstance(definition, settings)
  91. new_instance.setProperty("value", True)
  92. new_instance.resetState() # Ensure that the state is not seen as a user state.
  93. settings.addInstance(new_instance)
  94. op = GroupedOperation()
  95. # First add node to the scene at the correct position/scale, before parenting, so the eraser mesh does not get scaled with the parent
  96. op.addOperation(AddSceneNodeOperation(node, self._controller.getScene().getRoot()))
  97. op.addOperation(SetParentOperation(node, parent))
  98. op.addOperation(TranslateOperation(node, position, set_position = True))
  99. op.push()
  100. CuraApplication.getInstance().getController().getScene().sceneChanged.emit(node)
  101. def _removeEraserMesh(self, node: CuraSceneNode):
  102. parent = node.getParent()
  103. if parent == self._controller.getScene().getRoot():
  104. parent = None
  105. op = RemoveSceneNodeOperation(node)
  106. op.push()
  107. if parent and not Selection.isSelected(parent):
  108. Selection.add(parent)
  109. CuraApplication.getInstance().getController().getScene().sceneChanged.emit(node)
  110. def _updateEnabled(self):
  111. plugin_enabled = False
  112. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  113. if global_container_stack:
  114. plugin_enabled = global_container_stack.getProperty("anti_overhang_mesh", "enabled")
  115. CuraApplication.getInstance().getController().toolEnabledChanged.emit(self._plugin_id, plugin_enabled)
  116. def _onSelectionChanged(self):
  117. # When selection is passed from one object to another object, first the selection is cleared
  118. # and then it is set to the new object. We are only interested in the change from no selection
  119. # to a selection or vice-versa, not in a change from one object to another. A timer is used to
  120. # "merge" a possible clear/select action in a single frame
  121. if Selection.hasSelection() != self._had_selection:
  122. self._had_selection_timer.start()
  123. def _selectionChangeDelay(self):
  124. has_selection = Selection.hasSelection()
  125. if not has_selection and self._had_selection:
  126. self._skip_press = True
  127. else:
  128. self._skip_press = False
  129. self._had_selection = has_selection
  130. def _createCube(self, size):
  131. mesh = MeshBuilder()
  132. # Can't use MeshBuilder.addCube() because that does not get per-vertex normals
  133. # Per-vertex normals require duplication of vertices
  134. s = size / 2
  135. verts = [ # 6 faces with 4 corners each
  136. [-s, -s, s], [-s, s, s], [ s, s, s], [ s, -s, s],
  137. [-s, s, -s], [-s, -s, -s], [ s, -s, -s], [ s, s, -s],
  138. [ s, -s, -s], [-s, -s, -s], [-s, -s, s], [ s, -s, s],
  139. [-s, s, -s], [ s, s, -s], [ s, s, s], [-s, s, s],
  140. [-s, -s, s], [-s, -s, -s], [-s, s, -s], [-s, s, s],
  141. [ s, -s, -s], [ s, -s, s], [ s, s, s], [ s, s, -s]
  142. ]
  143. mesh.setVertices(numpy.asarray(verts, dtype=numpy.float32))
  144. indices = []
  145. for i in range(0, 24, 4): # All 6 quads (12 triangles)
  146. indices.append([i, i+2, i+1])
  147. indices.append([i, i+3, i+2])
  148. mesh.setIndices(numpy.asarray(indices, dtype=numpy.int32))
  149. mesh.calculateNormals()
  150. return mesh