value_tracker.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from __future__ import annotations
  2. import numpy as np
  3. from manimlib.mobject.mobject import Mobject
  4. from manimlib.utils.iterables import listify
  5. from typing import TYPE_CHECKING
  6. if TYPE_CHECKING:
  7. from manimlib.typing import Self
  8. class ValueTracker(Mobject):
  9. """
  10. Not meant to be displayed. Instead the position encodes some
  11. number, often one which another animation or continual_animation
  12. uses for its update function, and by treating it as a mobject it can
  13. still be animated and manipulated just like anything else.
  14. """
  15. value_type: type = np.float64
  16. def __init__(
  17. self,
  18. value: float | complex | np.ndarray = 0,
  19. **kwargs
  20. ):
  21. self.value = value
  22. super().__init__(**kwargs)
  23. def init_uniforms(self) -> None:
  24. super().init_uniforms()
  25. self.uniforms["value"] = np.array(
  26. listify(self.value),
  27. dtype=self.value_type,
  28. )
  29. def get_value(self) -> float | complex | np.ndarray:
  30. result = self.uniforms["value"]
  31. if len(result) == 1:
  32. return result[0]
  33. return result
  34. def set_value(self, value: float | complex | np.ndarray) -> Self:
  35. self.uniforms["value"][:] = value
  36. return self
  37. def increment_value(self, d_value: float | complex) -> None:
  38. self.set_value(self.get_value() + d_value)
  39. class ExponentialValueTracker(ValueTracker):
  40. """
  41. Operates just like ValueTracker, except it encodes the value as the
  42. exponential of a position coordinate, which changes how interpolation
  43. behaves
  44. """
  45. def get_value(self) -> float | complex:
  46. return np.exp(ValueTracker.get_value(self))
  47. def set_value(self, value: float | complex):
  48. return ValueTracker.set_value(self, np.log(value))
  49. class ComplexValueTracker(ValueTracker):
  50. value_type: type = np.complex128