SetParentOperation.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Uranium is released under the terms of the AGPLv3 or higher.
  3. from UM.Scene.SceneNode import SceneNode
  4. from UM.Operations import Operation
  5. from UM.Math.Vector import Vector
  6. ## An operation that parents a scene node to another scene node.
  7. class SetParentOperation(Operation.Operation):
  8. ## Initialises this SetParentOperation.
  9. #
  10. # \param node The node which will be reparented.
  11. # \param parent_node The node which will be the parent.
  12. def __init__(self, node, parent_node):
  13. super().__init__()
  14. self._node = node
  15. self._parent = parent_node
  16. self._old_parent = node.getParent() # To restore the previous parent in case of an undo.
  17. ## Undoes the set-parent operation, restoring the old parent.
  18. def undo(self):
  19. self._set_parent(self._old_parent)
  20. ## Re-applies the set-parent operation.
  21. def redo(self):
  22. self._set_parent(self._parent)
  23. ## Sets the parent of the node while applying transformations to the world-transform of the node stays the same.
  24. #
  25. # \param new_parent The new parent. Note: this argument can be None, which would hide the node from the scene.
  26. def _set_parent(self, new_parent):
  27. if new_parent:
  28. self._node.setPosition(self._node.getWorldPosition() - new_parent.getWorldPosition())
  29. current_parent = self._node.getParent()
  30. if current_parent:
  31. self._node.scale(current_parent.getScale() / new_parent.getScale())
  32. self._node.rotate(current_parent.getOrientation())
  33. else:
  34. self._node.scale(Vector(1, 1, 1) / new_parent.getScale())
  35. self._node.rotate(new_parent.getOrientation().getInverse())
  36. self._node.setParent(new_parent)
  37. ## Returns a programmer-readable representation of this operation.
  38. #
  39. # \return A programmer-readable representation of this operation.
  40. def __repr__(self):
  41. return "SetParentOperation(node = {0}, parent_node={1})".format(self._node, self._parent)