A community-maintained Python framework for creating mathematical animations.
Added :class:`.ChangeSpeed`, an animation wrapper that allows to smoothly change the speed at which an animation is played (#2749)
Sparsh Goenka6c58f4a77789
diff --git a/docs/source/reference.rst b/docs/source/reference.rstindex f84bde68b..5352f8322 100644--- a/docs/source/reference.rst+++ b/docs/source/reference.rst@@ -26,6 +26,7 @@ Animationsmanim.animation.numbersmanim.animation.rotationmanim.animation.specialized+ manim.animation.speedmodifiermanim.animation.transformmanim.animation.transform_matching_partsmanim.animation.updaters.mobject_update_utilsdiff --git a/docs/source/reference_index/animations.rst b/docs/source/reference_index/animations.rstindex 2afb09180..a25c61fdd 100644--- a/docs/source/reference_index/animations.rst+++ b/docs/source/reference_index/animations.rst@@ -17,6 +17,7 @@ Animations~animation.numbers~animation.rotation~animation.specialized+ ~animation.speedmodifier~animation.transform~animation.transform_matching_parts~animation.updatersdiff --git a/manim/__init__.py b/manim/__init__.pyindex a3fafb731..7734f32a2 100644--- a/manim/__init__.py+++ b/manim/__init__.py@@ -42,6 +42,7 @@ from .animation.movement import *from .animation.numbers import *from .animation.rotation import *from .animation.specialized import *+from .animation.speedmodifier import *from .animation.transform import *from .animation.transform_matching_parts import *from .animation.updaters.mobject_update_utils import *diff --git a/manim/animation/animation.py b/manim/animation/animation.pyindex 385917e16..65b45c300 100644--- a/manim/animation/animation.py+++ b/manim/animation/animation.py@@ -9,7 +9,7 @@ from .. import config, loggerfrom ..mobject import mobjectfrom ..mobject.mobject import Mobjectfrom ..mobject.opengl import opengl_mobject-from ..utils.rate_functions import smooth+from ..utils.rate_functions import linear, smooth__all__ = ["Animation", "Wait", "override_animation"]@@ -545,6 +545,7 @@ class Wait(Animation):run_time: float = 1,stop_condition: Callable[[], bool] | None = None,frozen_frame: bool | None = None,+ rate_func: Callable[[float], float] = linear,**kwargs,):if stop_condition and frozen_frame:@@ -553,7 +554,7 @@ class Wait(Animation):self.duration: float = run_timeself.stop_condition = stop_conditionself.is_static_wait: bool = frozen_frame- super().__init__(None, run_time=run_time, **kwargs)+ super().__init__(None, run_time=run_time, rate_func=rate_func, **kwargs)# quick fix to work in opengl setting:self.mobject.shader_wrapper_list = []diff --git a/manim/animation/composition.py b/manim/animation/composition.pyindex 6a541c97c..4c4f1db52 100644--- a/manim/animation/composition.py+++ b/manim/animation/composition.py@@ -38,6 +38,7 @@ class AnimationGroup(Animation):**kwargs,) -> None:self.animations = [prepare_animation(anim) for anim in animations]+ self.rate_func = rate_funcself.group = groupif self.group is None:mobjects = remove_list_redundancies(@@ -47,7 +48,9 @@ class AnimationGroup(Animation):self.group = OpenGLGroup(*mobjects)else:self.group = Group(*mobjects)- super().__init__(self.group, rate_func=rate_func, lag_ratio=lag_ratio, **kwargs)+ super().__init__(+ self.group, rate_func=self.rate_func, lag_ratio=lag_ratio, **kwargs+ )self.run_time: float = self.init_run_time(run_time)def get_all_mobjects(self) -> Sequence[Mobject]:@@ -108,7 +111,7 @@ class AnimationGroup(Animation):# times might not correspond to actual times,# e.g. of the surrounding scene. Instead they'd# be a rescaled version. But that's okay!- time = alpha * self.max_end_time+ time = self.rate_func(alpha) * self.max_end_timefor anim, start_time, end_time in self.anims_with_timings:anim_time = end_time - start_timeif anim_time == 0:@@ -163,7 +166,7 @@ class Succession(AnimationGroup):self.update_active_animation(self.active_index + 1)def interpolate(self, alpha: float) -> None:- current_time = alpha * self.run_time+ current_time = self.rate_func(alpha) * self.run_timewhile self.active_end_time is not None and current_time >= self.active_end_time:self.next_animation()if self.active_animation is not None and self.active_start_time is not None:diff --git a/manim/animation/speedmodifier.py b/manim/animation/speedmodifier.pynew file mode 100644index 000000000..311bd6285--- /dev/null+++ b/manim/animation/speedmodifier.py@@ -0,0 +1,293 @@+"""Utilities for modifying the speed at which animations are played."""++from __future__ import annotations++import types+from typing import Callable++from numpy import piecewise++from manim.utils.simple_functions import get_parameters++from ..animation.animation import Animation, Wait, prepare_animation+from ..animation.composition import AnimationGroup+from ..mobject.mobject import Mobject, Updater, _AnimationBuilder+from ..scene.scene import Scene+++class ChangeSpeed(Animation):+ """Modifies the speed of passed animation.+ :class:`AnimationGroup` with different ``lag_ratio`` can also be used+ which combines multiple animations into one.+ The ``run_time`` of the passed animation is changed to modify the speed.++ Parameters+ ----------+ anim+ Animation of which the speed is to be modified.+ speedinfo+ Contains nodes (percentage of ``run_time``) and its corresponding speed factor.+ rate_func+ Overrides ``rate_func`` of passed animation, applied before changing speed.++ Examples+ --------++ .. manim:: SpeedModifierExample++ class SpeedModifierExample(Scene):+ def construct(self):+ a = Dot().shift(LEFT * 4)+ b = Dot().shift(RIGHT * 4)+ self.add(a, b)+ self.play(+ ChangeSpeed(+ AnimationGroup(+ a.animate(run_time=1).shift(RIGHT * 8),+ b.animate(run_time=1).shift(LEFT * 8),+ ),+ speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1},+ rate_func=linear,+ )+ )++ .. manim:: SpeedModifierUpdaterExample++ class SpeedModifierUpdaterExample(Scene):+ def construct(self):+ a = Dot().shift(LEFT * 4)+ self.add(a)++ ChangeSpeed.add_updater(a, lambda x, dt: x.shift(RIGHT * 4 * dt))+ self.play(+ ChangeSpeed(+ Wait(2),+ speedinfo={0.4: 1, 0.5: 0.2, 0.8: 0.2, 1: 1},+ affects_speed_updaters=True,+ )+ )++ .. manim:: SpeedModifierUpdaterExample2++ class SpeedModifierUpdaterExample2(Scene):+ def construct(self):+ a = Dot().shift(LEFT * 4)+ self.add(a)++ ChangeSpeed.add_updater(a, lambda x, dt: x.shift(RIGHT * 4 * dt))+ self.wait()+ self.play(+ ChangeSpeed(+ Wait(),+ speedinfo={1: 0},+ affects_speed_updaters=True,+ )+ )++ """++ dt = 0+ is_changing_dt = False++ def __init__(+ self,+ anim: Animation | _AnimationBuilder,+ speedinfo: dict[float, float],+ rate_func: Callable[[float], float] | None = None,+ affects_speed_updaters: bool = True,+ **kwargs,+ ) -> None:++ if issubclass(type(anim), AnimationGroup):+ self.anim = type(anim)(+ *map(self.setup, anim.animations),+ group=anim.group,+ run_time=anim.run_time,+ rate_func=anim.rate_func,+ lag_ratio=anim.lag_ratio,+ )+ else:+ self.anim = self.setup(anim)++ if affects_speed_updaters:+ assert (+ ChangeSpeed.is_changing_dt is False+ ), "Only one animation at a time can play that changes speed (dt) for ChangeSpeed updaters"+ ChangeSpeed.is_changing_dt = True+ self.t = 0+ self.affects_speed_updaters = affects_speed_updaters++ self.rate_func = self.anim.rate_func if rate_func is None else rate_func++ # A function where, f(0) = 0, f'(0) = initial speed, f'( f-1(1) ) = final speed+ # Following function obtained when conditions applied to vertical parabola+ self.speed_modifier = lambda x, init_speed, final_speed: (+ (final_speed**2 - init_speed**2) * x**2 / 4 + init_speed * x+ )++ # f-1(1), returns x for which f(x) = 1 in `speed_modifier` function+ self.f_inv_1 = lambda init_speed, final_speed: 2 / (init_speed + final_speed)++ # if speed factors for the starting node (0) and the final node (1) are+ # not set, set them to 1 and the penultimate factor, respectively+ if 0 not in speedinfo:+ speedinfo[0] = 1+ if 1 not in speedinfo:+ speedinfo[1] = sorted(speedinfo.items())[-1][1]++ self.speedinfo = dict(sorted(speedinfo.items()))+ self.functions = []+ self.conditions = []++ # Get the time taken by amimation if `run_time` is assumed to be 1+ scaled_total_time = self.get_scaled_total_time()++ prevnode = 0+ init_speed = self.speedinfo[0]+ curr_time = 0+ for node, final_speed in list(self.speedinfo.items())[1:]:+ dur = node - prevnode++ def condition(+ t,+ curr_time=curr_time,+ init_speed=init_speed,+ final_speed=final_speed,+ dur=dur,+ ):+ lower_bound = curr_time / scaled_total_time+ upper_bound = (+ curr_time + self.f_inv_1(init_speed, final_speed) * dur+ ) / scaled_total_time+ return lower_bound <= t <= upper_bound++ self.conditions.append(condition)++ def function(+ t,+ curr_time=curr_time,+ init_speed=init_speed,+ final_speed=final_speed,+ dur=dur,+ prevnode=prevnode,+ ):+ return (+ self.speed_modifier(+ (scaled_total_time * t - curr_time) / dur,+ init_speed,+ final_speed,+ )+ * dur+ + prevnode+ )++ self.functions.append(function)++ curr_time += self.f_inv_1(init_speed, final_speed) * dur+ prevnode = node+ init_speed = final_speed++ def func(t):+ if t == 1:+ ChangeSpeed.is_changing_dt = False+ new_t = piecewise(+ self.rate_func(t),+ [condition(self.rate_func(t)) for condition in self.conditions],+ self.functions,+ )+ if self.affects_speed_updaters:+ ChangeSpeed.dt = (new_t - self.t) * self.anim.run_time+ self.t = new_t+ return new_t++ self.anim.set_rate_func(func)++ super().__init__(+ self.anim.mobject,+ rate_func=self.rate_func,+ run_time=scaled_total_time * self.anim.run_time,+ **kwargs,+ )++ def setup(self, anim):+ if type(anim) is Wait:+ anim.interpolate = types.MethodType(+ lambda self, alpha: self.rate_func(alpha), anim+ )+ return prepare_animation(anim)++ def get_scaled_total_time(self) -> float:+ """The time taken by the animation under the assumption that the ``run_time`` is 1."""+ prevnode = 0+ init_speed = self.speedinfo[0]+ total_time = 0+ for node, final_speed in list(self.speedinfo.items())[1:]:+ dur = node - prevnode+ total_time += dur * self.f_inv_1(init_speed, final_speed)+ prevnode = node+ init_speed = final_speed+ return total_time++ @classmethod+ def add_updater(+ self,+ mobject: Mobject,+ update_function: Updater,+ index: int | None = None,+ call_updater: bool = False,+ ):+ """This static method can be used to apply speed change to updaters.++ This updater will follow speed and rate function of any :class:`.ChangeSpeed`+ animation that is playing with ``affects_speed_updaters=True``. By default,+ updater functions added via the usual :meth:`.Mobject.add_updater` method+ do not respect the change of animation speed.++ Parameters+ ----------+ mobject+ The mobject to which the updater should be attached.+ update_function+ The function that is called whenever a new frame is rendered.+ index+ The position in the list of the mobject's updaters at which the+ function should be inserted.+ call_updater+ If ``True``, calls the update function when attaching it to the+ mobject.++ See also+ --------+ :class:`.ChangeSpeed`+ :meth:`.Mobject.add_updater`+ """+ parameters = get_parameters(update_function)+ if "dt" in parameters:+ mobject.add_updater(+ lambda mob, dt: update_function(+ mob, ChangeSpeed.dt if ChangeSpeed.is_changing_dt else dt+ ),+ index=index,+ call_updater=call_updater,+ )+ else:+ mobject.add_updater(update_function, index=index, call_updater=call_updater)++ def interpolate(self, alpha: float) -> None:+ self.anim.interpolate(alpha)++ def update_mobjects(self, dt: float) -> None:+ self.anim.update_mobjects(dt)++ def finish(self) -> None:+ ChangeSpeed.is_changing_dt = False+ self.anim.finish()++ def begin(self) -> None:+ self.anim.begin()++ def clean_up_from_scene(self, scene: Scene) -> None:+ self.anim.clean_up_from_scene(scene)++ def _setup_scene(self, scene) -> None:+ self.anim._setup_scene(scene)diff --git a/tests/test_graphical_units/control_data/speed/SpeedModifier.npz b/tests/test_graphical_units/control_data/speed/SpeedModifier.npznew file mode 100644index 000000000..f02482e5aBinary files /dev/null and b/tests/test_graphical_units/control_data/speed/SpeedModifier.npz differdiff --git a/tests/test_graphical_units/test_speed.py b/tests/test_graphical_units/test_speed.pynew file mode 100644index 000000000..c95064cca--- /dev/null+++ b/tests/test_graphical_units/test_speed.py@@ -0,0 +1,36 @@+from __future__ import annotations++from manim import *+from manim.utils.testing.frames_comparison import frames_comparison++__module_test__ = "speed"+++@frames_comparison(last_frame=False)+def test_SpeedModifier(scene):+ a = Dot().shift(LEFT * 2 + 0.5 * UP)+ b = Dot().shift(LEFT * 2 + 0.5 * DOWN)+ c = Dot().shift(2 * RIGHT)+ ChangeSpeed.add_updater(c, lambda x, dt: x.rotate_about_origin(PI / 3.7 * dt))+ scene.add(a, b, c)+ scene.play(ChangeSpeed(Wait(0.5), speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1}))+ scene.play(+ ChangeSpeed(+ AnimationGroup(+ a.animate(run_time=0.5, rate_func=linear).shift(RIGHT * 4),+ b.animate(run_time=0.5, rate_func=rush_from).shift(RIGHT * 4),+ ),+ speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1},+ affects_speed_updaters=False,+ ),+ )+ scene.play(+ ChangeSpeed(+ AnimationGroup(+ a.animate(run_time=0.5, rate_func=linear).shift(LEFT * 4),+ b.animate(run_time=0.5, rate_func=rush_into).shift(LEFT * 4),+ ),+ speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1},+ rate_func=there_and_back,+ ),+ )