PlatformPhysics.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import QTimer
  4. from UM.Application import Application
  5. from UM.Scene.SceneNode import SceneNode
  6. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  7. from UM.Math.Vector import Vector
  8. from UM.Scene.Selection import Selection
  9. from UM.Preferences import Preferences
  10. from cura.ConvexHullDecorator import ConvexHullDecorator
  11. from . import PlatformPhysicsOperation
  12. from . import ZOffsetDecorator
  13. import random # used for list shuffling
  14. class PlatformPhysics:
  15. def __init__(self, controller, volume):
  16. super().__init__()
  17. self._controller = controller
  18. self._controller.getScene().sceneChanged.connect(self._onSceneChanged)
  19. self._controller.toolOperationStarted.connect(self._onToolOperationStarted)
  20. self._controller.toolOperationStopped.connect(self._onToolOperationStopped)
  21. self._build_volume = volume
  22. self._enabled = True
  23. self._change_timer = QTimer()
  24. self._change_timer.setInterval(100)
  25. self._change_timer.setSingleShot(True)
  26. self._change_timer.timeout.connect(self._onChangeTimerFinished)
  27. self._move_factor = 1.1 # By how much should we multiply overlap to calculate a new spot?
  28. self._max_overlap_checks = 10 # How many times should we try to find a new spot per tick?
  29. Preferences.getInstance().addPreference("physics/automatic_push_free", True)
  30. Preferences.getInstance().addPreference("physics/automatic_drop_down", True)
  31. def _onSceneChanged(self, source):
  32. self._change_timer.start()
  33. def _onChangeTimerFinished(self, was_triggered_by_tool=False):
  34. if not self._enabled:
  35. return
  36. root = self._controller.getScene().getRoot()
  37. # Keep a list of nodes that are moving. We use this so that we don't move two intersecting objects in the
  38. # same direction.
  39. transformed_nodes = []
  40. # We try to shuffle all the nodes to prevent "locked" situations, where iteration B inverts iteration A.
  41. # By shuffling the order of the nodes, this might happen a few times, but at some point it will resolve.
  42. nodes = list(BreadthFirstIterator(root))
  43. # Only check nodes inside build area.
  44. nodes = [node for node in nodes if (hasattr(node, "_outside_buildarea") and not node._outside_buildarea)]
  45. random.shuffle(nodes)
  46. for node in nodes:
  47. if node is root or type(node) is not SceneNode or node.getBoundingBox() is None:
  48. continue
  49. bbox = node.getBoundingBox()
  50. # Move it downwards if bottom is above platform
  51. move_vector = Vector()
  52. if Preferences.getInstance().getValue("physics/automatic_drop_down") and not (node.getParent() and node.getParent().callDecoration("isGroup")) and node.isEnabled(): #If an object is grouped, don't move it down
  53. z_offset = node.callDecoration("getZOffset") if node.getDecorator(ZOffsetDecorator.ZOffsetDecorator) else 0
  54. move_vector = move_vector.set(y=-bbox.bottom + z_offset)
  55. # If there is no convex hull for the node, start calculating it and continue.
  56. if not node.getDecorator(ConvexHullDecorator):
  57. node.addDecorator(ConvexHullDecorator())
  58. if Preferences.getInstance().getValue("physics/automatic_push_free"):
  59. # Check for collisions between convex hulls
  60. for other_node in BreadthFirstIterator(root):
  61. # Ignore root, ourselves and anything that is not a normal SceneNode.
  62. if other_node is root or type(other_node) is not SceneNode or other_node is node:
  63. continue
  64. # Ignore collisions of a group with it's own children
  65. if other_node in node.getAllChildren() or node in other_node.getAllChildren():
  66. continue
  67. # Ignore collisions within a group
  68. if other_node.getParent() and node.getParent() and (other_node.getParent().callDecoration("isGroup") is not None or node.getParent().callDecoration("isGroup") is not None):
  69. continue
  70. # Ignore nodes that do not have the right properties set.
  71. if not other_node.callDecoration("getConvexHull") or not other_node.getBoundingBox():
  72. continue
  73. if other_node in transformed_nodes:
  74. continue # Other node is already moving, wait for next pass.
  75. overlap = (0, 0) # Start loop with no overlap
  76. current_overlap_checks = 0
  77. # Continue to check the overlap until we no longer find one.
  78. while overlap and current_overlap_checks < self._max_overlap_checks:
  79. current_overlap_checks += 1
  80. head_hull = node.callDecoration("getConvexHullHead")
  81. if head_hull: # One at a time intersection.
  82. overlap = head_hull.translate(move_vector.x, move_vector.z).intersectsPolygon(other_node.callDecoration("getConvexHull"))
  83. if not overlap:
  84. other_head_hull = other_node.callDecoration("getConvexHullHead")
  85. if other_head_hull:
  86. overlap = node.callDecoration("getConvexHull").translate(move_vector.x, move_vector.z).intersectsPolygon(other_head_hull)
  87. if overlap:
  88. # Moving ensured that overlap was still there. Try anew!
  89. move_vector = move_vector.set(x=move_vector.x + overlap[0] * self._move_factor,
  90. z=move_vector.z + overlap[1] * self._move_factor)
  91. else:
  92. # Moving ensured that overlap was still there. Try anew!
  93. move_vector = move_vector.set(x=move_vector.x + overlap[0] * self._move_factor,
  94. z=move_vector.z + overlap[1] * self._move_factor)
  95. else:
  96. own_convex_hull = node.callDecoration("getConvexHull")
  97. other_convex_hull = other_node.callDecoration("getConvexHull")
  98. if own_convex_hull and other_convex_hull:
  99. overlap = own_convex_hull.translate(move_vector.x, move_vector.z).intersectsPolygon(other_convex_hull)
  100. if overlap: # Moving ensured that overlap was still there. Try anew!
  101. move_vector = move_vector.set(x=move_vector.x + overlap[0] * self._move_factor,
  102. z=move_vector.z + overlap[1] * self._move_factor)
  103. else:
  104. # This can happen in some cases if the object is not yet done with being loaded.
  105. # Simply waiting for the next tick seems to resolve this correctly.
  106. overlap = None
  107. if not Vector.Null.equals(move_vector, epsilon=1e-5):
  108. transformed_nodes.append(node)
  109. op = PlatformPhysicsOperation.PlatformPhysicsOperation(node, move_vector)
  110. op.push()
  111. # After moving, we have to evaluate the boundary checks for nodes
  112. build_volume = Application.getInstance().getBuildVolume()
  113. build_volume.updateNodeBoundaryCheck()
  114. def _onToolOperationStarted(self, tool):
  115. self._enabled = False
  116. def _onToolOperationStopped(self, tool):
  117. # Selection tool should not trigger an update.
  118. if tool.getPluginId() == "SelectionTool":
  119. return
  120. if tool.getPluginId() == "TranslateTool":
  121. for node in Selection.getAllSelectedObjects():
  122. if node.getBoundingBox().bottom < 0:
  123. if not node.getDecorator(ZOffsetDecorator.ZOffsetDecorator):
  124. node.addDecorator(ZOffsetDecorator.ZOffsetDecorator())
  125. node.callDecoration("setZOffset", node.getBoundingBox().bottom)
  126. else:
  127. if node.getDecorator(ZOffsetDecorator.ZOffsetDecorator):
  128. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  129. self._enabled = True
  130. self._onChangeTimerFinished(True)