Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Added new fade and transform animations (:class:`~.TransformMatchingShapes`, :class:`~.TransformMatchingTex`, :class:`~.FadeTransform`) from 3b1b/manim (#1037)

Benjamin Hacklb09919febe8e
diff --git a/docs/source/reference.rst b/docs/source/reference.rst
index 19bd00196..c7fe10b24 100644
--- a/docs/source/reference.rst
+++ b/docs/source/reference.rst
@@ -82,6 +82,7 @@ Animations
~animation.numbers
~animation.rotation
~animation.transform
+ ~animation.transform_matching_parts
~animation.update
diff --git a/manim/__init__.py b/manim/__init__.py
index a458fa368..64983268c 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -26,6 +26,7 @@ from .animation.movement import *
from .animation.numbers import *
from .animation.rotation import *
from .animation.transform import *
+from .animation.transform_matching_parts import *
from .animation.update import *
from .renderer.cairo_renderer import *
diff --git a/manim/animation/fading.py b/manim/animation/fading.py
index 40ab5a7b7..b13dbc72f 100644
--- a/manim/animation/fading.py
+++ b/manim/animation/fading.py
@@ -58,6 +58,7 @@ __all__ = [
"FadeIn",
"FadeInFrom",
"FadeOutAndShift",
+ "FadeOutToPoint",
"FadeInFromPoint",
"FadeInFromLarge",
"VFadeIn",
@@ -72,7 +73,8 @@ import numpy as np
from .. import logger
from ..animation.animation import Animation
from ..animation.transform import Transform
-from ..constants import DOWN
+from ..constants import DOWN, ORIGIN
+from ..mobject.mobject import Group
from ..mobject.types.vectorized_mobject import VMobject
from ..mobject.types.opengl_vectorized_mobject import OpenGLVMobject
from ..utils.bezier import interpolate
@@ -155,6 +157,37 @@ class FadeOutAndShift(FadeOut):
return target
+class FadeOutToPoint(FadeOut):
+ """Fades out a mobject while moving it to a specified point.
+
+ Parameters
+ ----------
+ mobject
+ The :class:`~.Mobject` to be animated.
+ point
+ Either a point or another :class:`~.Mobject` to whose center the
+ Mobject is moved in the animation. Defaults to ``ORIGIN``.
+ kwargs
+ Further keyword arguments are passed to the parent class.
+
+ """
+
+ def __init__(
+ self,
+ mobject: "Mobject",
+ point: typing.Union["Mobject", np.ndarray] = ORIGIN,
+ **kwargs
+ ) -> None:
+ self.point = point
+ super().__init__(mobject, **kwargs)
+
+ def create_target(self) -> "Mobject":
+ """Creates the target of the animation."""
+ target = super().create_target()
+ target.move_to(self.point)
+ return target
+
+
class FadeInFromPoint(FadeIn):
def __init__(
self, mobject: "Mobject", point: typing.Union["Mobject", np.ndarray], **kwargs
diff --git a/manim/animation/transform.py b/manim/animation/transform.py
index 064e71193..4f6e11e52 100644
--- a/manim/animation/transform.py
+++ b/manim/animation/transform.py
@@ -11,6 +11,8 @@ __all__ = [
"ApplyPointwiseFunction",
"ApplyPointwiseFunctionToCenter",
"FadeToColor",
+ "FadeTransform",
+ "FadeTransformPieces",
"ScaleInPlace",
"ShrinkToCenter",
"Restore",
@@ -401,3 +403,135 @@ class TransformAnimations(Transform):
self.start_anim.interpolate(alpha)
self.end_anim.interpolate(alpha)
Transform.interpolate(self, alpha)
+
+
+class FadeTransform(Transform):
+ """Fades one mobject into another.
+
+ Parameters
+ ----------
+ mobject
+ The starting :class:`~.Mobject`.
+ target_mobject
+ The target :class:`~.Mobject`.
+ stretch
+ Controls whether the target :class:`~.Mobject` is stretched during
+ the animation. Default: ``True``.
+ dim_to_match
+ If the target mobject is not stretched automatically, this allows
+ to adjust the initial scale of the target :class:`~.Mobject` while
+ it is shifted in. Setting this to 0, 1, and 2, respectively,
+ matches the length of the target with the length of the starting
+ :class:`~.Mobject` in x, y, and z direction, respectively.
+ kwargs
+ Further keyword arguments are passed to the parent class.
+
+ Examples
+ --------
+
+ .. manim:: DifferentFadeTransforms
+
+ class DifferentFadeTransforms(Scene):
+ def construct(self):
+ starts = [Rectangle(width=4, height=1) for _ in range(3)]
+ VGroup(*starts).arrange(DOWN, buff=1).shift(3*LEFT)
+ targets = [Circle(fill_opacity=1).scale(0.25) for _ in range(3)]
+ VGroup(*targets).arrange(DOWN, buff=1).shift(3*RIGHT)
+
+ self.play(*[FadeIn(s) for s in starts])
+ self.play(
+ FadeTransform(starts[0], targets[0], stretch=True),
+ FadeTransform(starts[1], targets[1], stretch=False, dim_to_match=0),
+ FadeTransform(starts[2], targets[2], stretch=False, dim_to_match=1)
+ )
+
+ self.play(*[FadeOut(mobj) for mobj in self.mobjects])
+
+ """
+
+ def __init__(self, mobject, target_mobject, stretch=True, dim_to_match=1, **kwargs):
+ self.to_add_on_completion = target_mobject
+ self.stretch = stretch
+ self.dim_to_match = dim_to_match
+ mobject.save_state()
+ super().__init__(Group(mobject, target_mobject.copy()), **kwargs)
+
+ def begin(self):
+ """Initial setup for the animation.
+
+ The mobject to which this animation is bound is a group consisting of
+ both the starting and the ending mobject. At the start, the ending
+ mobject replaces the starting mobject (and is completely faded). In the
+ end, it is set to be the other way around.
+ """
+ self.ending_mobject = self.mobject.copy()
+ Animation.begin(self)
+ # Both 'start' and 'end' consists of the source and target mobjects.
+ # At the start, the target should be faded replacing the source,
+ # and at the end it should be the other way around.
+ start, end = self.starting_mobject, self.ending_mobject
+ for m0, m1 in ((start[1], start[0]), (end[0], end[1])):
+ self.ghost_to(m0, m1)
+
+ def ghost_to(self, source, target):
+ """Replaces the source by the target and sets the opacity to 0."""
+ source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match)
+ source.set_opacity(0)
+
+ def get_all_mobjects(self):
+ return [
+ self.mobject,
+ self.starting_mobject,
+ self.ending_mobject,
+ ]
+
+ def get_all_families_zipped(self):
+ return Animation.get_all_families_zipped(self)
+
+ def clean_up_from_scene(self, scene):
+ Animation.clean_up_from_scene(self, scene)
+ scene.remove(self.mobject)
+ self.mobject[0].restore()
+ scene.add(self.to_add_on_completion)
+
+
+class FadeTransformPieces(FadeTransform):
+ """Fades submobjects of one mobject into submobjects of another one.
+
+ See also
+ --------
+ :class:`~.FadeTransform`
+
+ Examples
+ --------
+ .. manim:: FadeTransformSubmobjects
+
+ class FadeTransformSubmobjects(Scene):
+ def construct(self):
+ src = VGroup(Square(), Circle().shift(LEFT + UP))
+ src.shift(3*LEFT + 2*UP)
+ src_copy = src.copy().shift(4*DOWN)
+
+ target = VGroup(Circle(), Triangle().shift(RIGHT + DOWN))
+ target.shift(3*RIGHT + 2*UP)
+ target_copy = target.copy().shift(4*DOWN)
+
+ self.play(FadeIn(src), FadeIn(src_copy))
+ self.play(
+ FadeTransform(src, target),
+ FadeTransformPieces(src_copy, target_copy)
+ )
+ self.play(*[FadeOut(mobj) for mobj in self.mobjects])
+
+ """
+
+ def begin(self):
+ self.mobject[0].align_submobjects(self.mobject[1])
+ super().begin()
+
+ def ghost_to(self, source, target):
+ """Replaces the source submobjects by the target submobjects and sets
+ the opacity to 0.
+ """
+ for sm0, sm1 in zip(source.get_family(), target.get_family()):
+ super().ghost_to(sm0, sm1)
diff --git a/manim/animation/transform_matching_parts.py b/manim/animation/transform_matching_parts.py
new file mode 100644
index 000000000..d7a95e831
--- /dev/null
+++ b/manim/animation/transform_matching_parts.py
@@ -0,0 +1,270 @@
+"""Animations that try to transform Mobjects while keeping track of identical parts."""
+
+__all__ = ["TransformMatchingShapes", "TransformMatchingTex"]
+
+
+import numpy as np
+from typing import List, Optional
+
+from .composition import AnimationGroup
+from .fading import FadeInFromPoint, FadeOutToPoint
+from .transform import Transform, ReplacementTransform, FadeTransformPieces
+
+from ..mobject.mobject import Mobject, Group
+from ..mobject.types.vectorized_mobject import VGroup, VMobject
+from ..mobject.svg.tex_mobject import MathTex
+
+
+class TransformMatchingAbstractBase(AnimationGroup):
+ """Abstract base class for transformations that keep track of matching parts.
+
+ Subclasses have to implement the two static methods
+ :meth:`~.TransformMatchingAbstractBase.get_mobject_parts` and
+ :meth:`~.TransformMatchingAbstractBase.get_mobject_key`.
+
+ Basically, this transformation first maps all submobjects returned
+ by the ``get_mobject_parts`` method to certain keys by applying the
+ ``get_mobject_key`` method. Then, submobjects with matching keys
+ are transformed into each other.
+
+ Parameters
+ ----------
+ mobject
+ The starting :class:`~.Mobject`.
+ target_mobject
+ The target :class:`~.Mobject`.
+ transform_mismatches
+ Controls whether submobjects without a matching key are transformed
+ into each other by using :class:`~.Transform`. Default: ``False``.
+ fade_transform_mismatches
+ Controls whether submobjects without a matching key are transformed
+ into each other by using :class:`~.FadeTransform`. Default: ``False``.
+ key_map
+ Optional. A dictionary mapping keys belonging to some of the starting mobject's
+ submobjects (i.e., the return values of the ``get_mobject_key`` method)
+ to some keys belonging to the target mobject's submobjects that should
+ be transformed although the keys don't match.
+ kwargs
+ All further keyword arguments are passed to the submobject transformations.
+
+
+ Note
+ ----
+ If neither ``transform_mismatches`` nor ``fade_transform_mismatches``
+ are set to ``True``, submobjects without matching keys in the starting
+ mobject are faded out in the direction of the unmatched submobjects in
+ the target mobject, and unmatched submobjects in the target mobject
+ are faded in from the direction of the unmatched submobjects in the
+ start mobject.
+
+ """
+
+ def __init__(
+ self,
+ mobject: "Mobject",
+ target_mobject: "Mobject",
+ transform_mismatches: bool = False,
+ fade_transform_mismatches: bool = False,
+ key_map: Optional[dict] = None,
+ **kwargs
+ ):
+ assert type(mobject) is type(target_mobject)
+
+ if isinstance(mobject, VMobject):
+ group_type = VGroup
+ else:
+ group_type = Group
+
+ source_map = self.get_shape_map(mobject)
+ target_map = self.get_shape_map(target_mobject)
+
+ if key_map is None:
+ key_map = {}
+
+ # Create two mobjects whose submobjects all match each other
+ # according to whatever keys are used for source_map and
+ # target_map
+ transform_source = group_type()
+ transform_target = group_type()
+ kwargs["final_alpha_value"] = 0
+ for key in set(source_map).intersection(target_map):
+ transform_source.add(source_map[key])
+ transform_target.add(target_map[key])
+ anims = [Transform(transform_source, transform_target, **kwargs)]
+ # User can manually specify when one part should transform
+ # into another despite not matching by using key_map
+ key_mapped_source = group_type()
+ key_mapped_target = group_type()
+ for key1, key2 in key_map.items():
+ if key1 in source_map and key2 in target_map:
+ key_mapped_source.add(source_map[key1])
+ key_mapped_target.add(target_map[key2])
+ source_map.pop(key1, None)
+ target_map.pop(key2, None)
+ if len(key_mapped_source) > 0:
+ anims.append(
+ FadeTransformPieces(key_mapped_source, key_mapped_target, **kwargs)
+ )
+
+ fade_source = group_type()
+ fade_target = group_type()
+ for key in set(source_map).difference(target_map):
+ fade_source.add(source_map[key])
+ for key in set(target_map).difference(source_map):
+ fade_target.add(target_map[key])
+
+ if transform_mismatches:
+ anims.append(Transform(fade_source.copy(), fade_target, **kwargs))
+ if fade_transform_mismatches:
+ anims.append(FadeTransformPieces(fade_source, fade_target, **kwargs))
+ else:
+ anims.append(
+ FadeOutToPoint(fade_source, fade_target.get_center(), **kwargs)
+ )
+ anims.append(
+ FadeInFromPoint(fade_target.copy(), fade_source.get_center(), **kwargs)
+ )
+
+ super().__init__(*anims)
+
+ self.to_remove = mobject
+ self.to_add = target_mobject
+
+ def get_shape_map(self, mobject: "Mobject") -> dict:
+ shape_map = {}
+ for sm in self.get_mobject_parts(mobject):
+ key = self.get_mobject_key(sm)
+ if key not in shape_map:
+ shape_map[key] = VGroup()
+ shape_map[key].add(sm)
+ return shape_map
+
+ def clean_up_from_scene(self, scene: "Scene") -> None:
+ for anim in self.animations:
+ anim.interpolate(0)
+ scene.remove(self.mobject)
+ scene.remove(self.to_remove)
+ scene.add(self.to_add)
+
+ @staticmethod
+ def get_mobject_parts(mobject: "Mobject"):
+ raise NotImplementedError("To be implemented in subclass.")
+
+ @staticmethod
+ def get_mobject_key(mobject: "Mobject"):
+ raise NotImplementedError("To be implemented in subclass.")
+
+
+class TransformMatchingShapes(TransformMatchingAbstractBase):
+ """An animation trying to transform groups by matching the shape
+ of their submobjects.
+
+ Two submobjects match if the hash of their point coordinates after
+ normalization (i.e., after translation to the origin, fixing the submobject
+ height at 1 unit, and rounding the coordinates to three decimal places)
+ matches.
+
+ See also
+ --------
+ :class:`~.TransformMatchingAbstractBase`
+
+ Examples
+ --------
+
+ .. manim:: Anagram
+
+ class Anagram(Scene):
+ def construct(self):
+ src = Text("the morse code")
+ tar = Text("here come dots")
+ self.play(Write(src))
+ self.wait(0.5)
+ self.play(TransformMatchingShapes(src, tar, path_arc=PI/2))
+ self.wait(0.5)
+
+ """
+
+ def __init__(
+ self,
+ mobject: "Mobject",
+ target_mobject: "Mobject",
+ transform_mismatches: bool = False,
+ fade_transform_mismatches: bool = False,
+ key_map: Optional[dict] = None,
+ **kwargs
+ ):
+ super().__init__(
+ mobject,
+ target_mobject,
+ transform_mismatches=transform_mismatches,
+ fade_transform_mismatches=fade_transform_mismatches,
+ key_map=key_map,
+ **kwargs
+ )
+
+ @staticmethod
+ def get_mobject_parts(mobject: "Mobject") -> List["Mobject"]:
+ return mobject.family_members_with_points()
+
+ @staticmethod
+ def get_mobject_key(mobject: "Mobject") -> int:
+ mobject.save_state()
+ mobject.center()
+ mobject.set_height(1)
+ result = hash(np.round(mobject.get_points(), 3).tobytes())
+ mobject.restore()
+ return result
+
+
+class TransformMatchingTex(TransformMatchingAbstractBase):
+ """A transformation trying to transform rendered LaTeX strings.
+
+ Two submobjects match if their ``tex_string`` matches.
+
+ See also
+ --------
+ :class:`~.TransformMatchingAbstractBase`
+
+ Examples
+ --------
+
+ .. manim:: MatchingEquationParts
+
+ class MatchingEquationParts(Scene):
+ def construct(self):
+ eq1 = MathTex("{{a^2}} + {{b^2}} = {{c^2}}")
+ eq2 = MathTex("{{a^2}} = {{c^2}} - {{b^2}}")
+ self.add(eq1)
+ self.wait(0.5)
+ self.play(TransformMatchingTex(eq1, eq2))
+ self.wait(0.5)
+
+ """
+
+ def __init__(
+ self,
+ mobject: "Mobject",
+ target_mobject: "Mobject",
+ transform_mismatches: bool = False,
+ fade_transform_mismatches: bool = False,
+ key_map: Optional[dict] = None,
+ **kwargs
+ ):
+ assert hasattr(mobject, "tex_string")
+ assert hasattr(target_mobject, "tex_string")
+ super().__init__(
+ mobject,
+ target_mobject,
+ transform_mismatches=transform_mismatches,
+ fade_transform_mismatches=fade_transform_mismatches,
+ key_map=key_map,
+ **kwargs
+ )
+
+ @staticmethod
+ def get_mobject_parts(mobject: "Mobject") -> List["Mobject"]:
+ return mobject.submobjects
+
+ @staticmethod
+ def get_mobject_key(mobject: "Mobject") -> str:
+ return mobject.tex_string
diff --git a/manim/mobject/svg/tex_mobject.py b/manim/mobject/svg/tex_mobject.py
index 624fbb59b..e17a2a4cc 100644
--- a/manim/mobject/svg/tex_mobject.py
+++ b/manim/mobject/svg/tex_mobject.py
@@ -170,6 +170,8 @@ __all__ = [
from functools import reduce
import operator as op
+import itertools as it
+import re
from .style_utils import parse_style
from ... import config, logger
@@ -396,17 +398,24 @@ class MathTex(SingleStringMathTex):
self.organize_submobjects_left_to_right()
def break_up_tex_strings(self, tex_strings):
- substrings_to_isolate = op.add(
- self.substrings_to_isolate, list(self.tex_to_color_map.keys())
- )
- split_list = split_string_list_to_isolate_substrings(
- tex_strings, *substrings_to_isolate
+ tex_strings = [str(t) for t in tex_strings]
+ # Separate out anything surrounded in double braces
+ patterns = ["{{", "}}"]
+ # Separate out any strings specified in the isolate
+ # or tex_to_color_map lists.
+ patterns.extend(
+ [
+ "({})".format(re.escape(ss))
+ for ss in it.chain(
+ self.substrings_to_isolate, self.tex_to_color_map.keys()
+ )
+ ]
)
- if self.arg_separator == " ":
- split_list = [str(x).strip() for x in split_list]
- # split_list = list(map(str.strip, split_list))
- split_list = [s for s in split_list if s != ""]
- return split_list
+ pattern = "|".join(patterns)
+ pieces = []
+ for s in tex_strings:
+ pieces.extend(re.split(pattern, s))
+ return list(filter(lambda s: s, pieces))
def break_up_by_substrings(self):
"""