Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Port over docs and typings from `mobject.py`/`vectorized_mobject` to their OpenGL counterparts. (#2354)

Laith Bahodia4c1c4f15a75
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 81c6b83ce..23df0a1a0 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -1632,7 +1632,7 @@ class Mobject:
# Background rectangle
def add_background_rectangle(
- self, color: Colors = BLACK, opacity: float = 0.75, **kwargs
+ self, color: Optional[Colors] = None, opacity: float = 0.75, **kwargs
):
"""Add a BackgroundRectangle as submobject.
diff --git a/manim/mobject/opengl_mobject.py b/manim/mobject/opengl_mobject.py
index 8fc03517a..175554612 100644
--- a/manim/mobject/opengl_mobject.py
+++ b/manim/mobject/opengl_mobject.py
@@ -4,7 +4,7 @@ import random
import sys
from functools import partialmethod, wraps
from math import ceil
-from typing import Iterable, Optional, Tuple, Union
+from typing import Iterable, Optional, Sequence, Tuple, Union
import moderngl
import numpy as np
@@ -14,6 +14,7 @@ from .. import config
from ..constants import *
from ..utils.bezier import integer_interpolate, interpolate
from ..utils.color import *
+from ..utils.color import Colors
from ..utils.config_ops import _Data, _Uniforms
from ..utils.deprecation import deprecated
@@ -38,8 +39,19 @@ from ..utils.space_ops import (
class OpenGLMobject:
- """
- Mathematical Object
+ """Mathematical Object: base class for objects that can be displayed on screen.
+
+ Attributes
+ ----------
+ submobjects : List[:class:`OpenGLMobject`]
+ The contained objects.
+ points : :class:`numpy.ndarray`
+ The points of the objects.
+
+ .. seealso::
+
+ :class:`~.OpenGLVMobject`
+
"""
shader_dtype = [
@@ -130,16 +142,72 @@ class OpenGLMobject:
super().__init_subclass__(**kwargs)
cls._original__init__ = cls.__init__
+ def __str__(self):
+ return self.__class__.__name__
+
+ def __repr__(self):
+ return self.__class__.__name__
+
+ def __sub__(self, other):
+ raise NotImplementedError
+
+ def __isub__(self, other):
+ raise NotImplementedError
+
+ def __add__(self, mobject):
+ raise NotImplementedError
+
+ def __iadd__(self, mobject):
+ raise NotImplementedError
+
@classmethod
def set_default(cls, **kwargs):
+ """Sets the default values of keyword arguments.
+
+ If this method is called without any additional keyword
+ arguments, the original default values of the initialization
+ method of this class are restored.
+
+ Parameters
+ ----------
+
+ kwargs
+ Passing any keyword argument will update the default
+ values of the keyword arguments of the initialization
+ function of this class.
+
+ Examples
+ --------
+
+ ::
+
+ >>> from manim import Square, GREEN
+ >>> Square.set_default(color=GREEN, fill_opacity=0.25)
+ >>> s = Square(); s.color, s.fill_opacity
+ (<Color #83c167>, 0.25)
+ >>> Square.set_default()
+ >>> s = Square(); s.color, s.fill_opacity
+ (<Color white>, 0.0)
+
+ .. manim:: ChangedDefaultTextcolor
+ :save_last_frame:
+
+ config.background_color = WHITE
+
+ class ChangedDefaultTextcolor(Scene):
+ def construct(self):
+ Text.set_default(color=BLACK)
+ self.add(Text("Changing default values is easy!"))
+
+ # we revert the colour back to the default to prevent a bug in the docs.
+ Text.set_default(color=WHITE)
+
+ """
if kwargs:
cls.__init__ = partialmethod(cls.__init__, **kwargs)
else:
cls.__init__ = cls._original__init__
- def __str__(self):
- return self.__class__.__name__
-
def init_data(self):
"""Initializes the ``points``, ``bounding_box`` and ``rgbas`` attributes and groups them into self.data.
Subclasses can inherit and overwrite this method to extend `self.data`."""
@@ -148,12 +216,53 @@ class OpenGLMobject:
self.rgbas = np.zeros((1, 4))
def init_colors(self):
+ """Initializes the colors.
+
+ Gets called upon creation"""
self.set_color(self.color, self.opacity)
def init_points(self):
+ """Initializes :attr:`points` and therefore the shape.
+
+ Gets called upon creation. This is an empty method that can be implemented by
+ subclasses."""
# Typically implemented in subclass, unless purposefully left blank
pass
+ def set(self, **kwargs) -> "OpenGLMobject":
+ """Sets attributes.
+
+ Mainly to be used along with :attr:`animate` to
+ animate setting attributes.
+
+ Examples
+ --------
+ ::
+
+ >>> mob = OpenGLMobject()
+ >>> mob.set(foo=0)
+ OpenGLMobject
+ >>> mob.foo
+ 0
+
+ Parameters
+ ----------
+ **kwargs
+ The attributes and corresponding values to set.
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ ``self``
+
+
+ """
+
+ for attr, value in kwargs.items():
+ setattr(self, attr, value)
+
+ return self
+
def set_data(self, data):
for key in data:
self.data[key] = data[key].copy()
@@ -166,7 +275,90 @@ class OpenGLMobject:
@property
def animate(self):
- # Borrowed from https://github.com/ManimCommunity/manim/
+ """Used to animate the application of a method.
+
+ .. warning::
+
+ Passing multiple animations for the same :class:`OpenGLMobject` in one
+ call to :meth:`~.Scene.play` is discouraged and will most likely
+ not work properly. Instead of writing an animation like
+
+ ::
+
+ self.play(my_mobject.animate.shift(RIGHT), my_mobject.animate.rotate(PI))
+
+ make use of method chaining for ``animate``, meaning::
+
+ self.play(my_mobject.animate.shift(RIGHT).rotate(PI))
+
+ Keyword arguments that can be passed to :meth:`.Scene.play` can be passed
+ directly after accessing ``.animate``, like so::
+
+ self.play(my_mobject.animate(rate_func=linear).shift(RIGHT))
+
+ This is especially useful when animating simultaneous ``.animate`` calls that
+ you want to behave differently::
+
+ self.play(
+ mobject1.animate(run_time=2).rotate(PI),
+ mobject2.animate(rate_func=there_and_back).shift(RIGHT),
+ )
+
+ .. seealso::
+
+ :func:`override_animate`
+
+
+ Examples
+ --------
+
+ .. manim:: AnimateExample
+
+ class AnimateExample(Scene):
+ def construct(self):
+ s = Square()
+ self.play(Create(s))
+ self.play(s.animate.shift(RIGHT))
+ self.play(s.animate.scale(2))
+ self.play(s.animate.rotate(PI / 2))
+ self.play(Uncreate(s))
+
+
+ .. manim:: AnimateChainExample
+
+ class AnimateChainExample(Scene):
+ def construct(self):
+ s = Square()
+ self.play(Create(s))
+ self.play(s.animate.shift(RIGHT).scale(2).rotate(PI / 2))
+ self.play(Uncreate(s))
+
+ .. manim:: AnimateWithArgsExample
+
+ class AnimateWithArgsExample(Scene):
+ def construct(self):
+ s = Square()
+ c = Circle()
+
+ VGroup(s, c).arrange(RIGHT, buff=2)
+ self.add(s, c)
+
+ self.play(
+ s.animate(run_time=2).rotate(PI / 2),
+ c.animate(rate_func=there_and_back).shift(RIGHT),
+ )
+
+ .. warning::
+
+ ``.animate``
+ will interpolate the :class:`~.OpenGLMobject` between its points prior to
+ ``.animate`` and its points after applying ``.animate`` to it. This may
+ result in unexpected behavior when attempting to interpolate along paths,
+ or rotations.
+ If you want animations to consider the points between, consider using
+ :class:`~.ValueTracker` with updaters instead.
+
+ """
return _AnimationBuilder(self)
@property
@@ -297,7 +489,27 @@ class OpenGLMobject:
mob.data[key] = mob.data[key][::-1]
return self
- def get_midpoint(self):
+ def get_midpoint(self) -> np.ndarray:
+ """Get coordinates of the middle of the path that forms the :class:`~.OpenGLMobject`.
+
+ Examples
+ --------
+
+ .. manim:: AngleMidPoint
+ :save_last_frame:
+
+ class AngleMidPoint(Scene):
+ def construct(self):
+ line1 = Line(ORIGIN, 2*RIGHT)
+ line2 = Line(ORIGIN, 2*RIGHT).rotate_about_origin(80*DEGREES)
+
+ a = Angle(line1, line2, radius=1.5, other_angle=False)
+ d = Dot(a.get_midpoint()).set_color(RED)
+
+ self.add(line1, line2, a, d)
+ self.wait()
+
+ """
return self.point_from_proportion(0.5)
def apply_points_function(
@@ -333,6 +545,22 @@ class OpenGLMobject:
# Others related to points
def match_points(self, mobject):
+ """Edit points, positions, and submobjects to be identical
+ to another :class:`~.OpenGLMobject`, while keeping the style unchanged.
+
+ Examples
+ --------
+ .. manim:: MatchPointsScene
+
+ class MatchPointsScene(Scene):
+ def construct(self):
+ circ = Circle(fill_color=RED, fill_opacity=0.8)
+ square = Square(fill_color=BLUE, fill_opacity=0.2)
+ self.add(circ)
+ self.wait(0.5)
+ self.play(circ.animate.match_points(square))
+ self.wait(0.5)
+ """
self.set_points(mobject.points)
def clear_points(self):
@@ -425,7 +653,67 @@ class OpenGLMobject:
def family_members_with_points(self):
return [m for m in self.get_family() if m.has_points()]
- def add(self, *mobjects, update_parent=False):
+ def add(
+ self, *mobjects: "OpenGLMobject", update_parent: bool = False
+ ) -> "OpenGLMobject":
+ """Add mobjects as submobjects.
+
+ The mobjects are added to :attr:`submobjects`.
+
+ Subclasses of mobject may implement ``+`` and ``+=`` dunder methods.
+
+ Parameters
+ ----------
+ mobjects
+ The mobjects to add.
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ ``self``
+
+ Raises
+ ------
+ :class:`ValueError`
+ When a mobject tries to add itself.
+ :class:`TypeError`
+ When trying to add an object that is not an instance of :class:`OpenGLMobject`.
+
+
+ Notes
+ -----
+ A mobject cannot contain itself, and it cannot contain a submobject
+ more than once. If the parent mobject is displayed, the newly-added
+ submobjects will also be displayed (i.e. they are automatically added
+ to the parent Scene).
+
+ See Also
+ --------
+ :meth:`remove`
+ :meth:`add_to_back`
+
+ Examples
+ --------
+ ::
+
+ >>> outer = OpenGLMobject()
+ >>> inner = OpenGLMobject()
+ >>> outer = outer.add(inner)
+
+ Duplicates are not added again::
+
+ >>> outer = outer.add(inner)
+ >>> len(outer.submobjects)
+ 1
+
+ Adding an object to itself raises an error::
+
+ >>> outer.add(outer)
+ Traceback (most recent call last):
+ ...
+ ValueError: OpenGLMobject cannot contain self
+
+ """
if update_parent:
assert len(mobjects) == 1, "Can't set multiple parents."
mobjects[0].parent = self
@@ -442,7 +730,30 @@ class OpenGLMobject:
self.assemble_family()
return self
- def remove(self, *mobjects, update_parent=False):
+ def remove(
+ self, *mobjects: "OpenGLMobject", update_parent: bool = False
+ ) -> "OpenGLMobject":
+ """Remove :attr:`submobjects`.
+
+ The mobjects are removed from :attr:`submobjects`, if they exist.
+
+ Subclasses of mobject may implement ``-`` and ``-=`` dunder methods.
+
+ Parameters
+ ----------
+ mobjects
+ The mobjects to remove.
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ ``self``
+
+ See Also
+ --------
+ :meth:`add`
+
+ """
if update_parent:
assert len(mobjects) == 1, "Can't remove multiple parents."
mobjects[0].parent = None
@@ -455,7 +766,51 @@ class OpenGLMobject:
self.assemble_family()
return self
- def add_to_back(self, *mobjects):
+ def add_to_back(self, *mobjects: "OpenGLMobject") -> "OpenGLMobject":
+ # NOTE: is the note true OpenGLMobjects?
+ """Add all passed mobjects to the back of the submobjects.
+
+ If :attr:`submobjects` already contains the given mobjects, they just get moved
+ to the back instead.
+
+ Parameters
+ ----------
+ mobjects
+ The mobjects to add.
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ ``self``
+
+
+ .. note::
+
+ Technically, this is done by adding (or moving) the mobjects to
+ the head of :attr:`submobjects`. The head of this list is rendered
+ first, which places the corresponding mobjects behind the
+ subsequent list members.
+
+ Raises
+ ------
+ :class:`ValueError`
+ When a mobject tries to add itself.
+ :class:`TypeError`
+ When trying to add an object that is not an instance of :class:`OpenGLMobject`.
+
+ Notes
+ -----
+ A mobject cannot contain itself, and it cannot contain a submobject
+ more than once. If the parent mobject is displayed, the newly-added
+ submobjects will also be displayed (i.e. they are automatically added
+ to the parent Scene).
+
+ See Also
+ --------
+ :meth:`remove`
+ :meth:`add`
+
+ """
self.submobjects = list_update(mobjects, self.submobjects)
return self
@@ -505,20 +860,26 @@ class OpenGLMobject:
list.reverse(self.submobjects)
self.assemble_family()
- def digest_mobject_attrs(self):
- """
- Ensures all attributes which are mobjects are included
- in the submobjects list.
- """
- mobject_attrs = [
- x for x in list(self.__dict__.values()) if isinstance(x, OpenGLMobject)
- ]
- self.submobjects = list_update(self.submobjects, mobject_attrs)
- return self
-
# Submobject organization
def arrange(self, direction=RIGHT, center=True, **kwargs):
+ """Sorts :class:`~.OpenGLMobject` next to each other on screen.
+
+ Examples
+ --------
+
+ .. manim:: Example
+ :save_last_frame:
+
+ class Example(Scene):
+ def construct(self):
+ s1 = Square()
+ s2 = Square()
+ s3 = Square()
+ s4 = Square()
+ x = OpenGLVGroup(s1, s2, s3, s4).set_x(0).arrange(buff=1.0)
+ self.add(x)
+ """
for m1, m2 in zip(self.submobjects, self.submobjects[1:]):
m2.next_to(m1, direction, **kwargs)
if center:
@@ -570,7 +931,7 @@ class OpenGLMobject:
Returns
-------
- Mobject
+ OpenGLMobject
The mobject.
NOTES
@@ -774,13 +1135,18 @@ class OpenGLMobject:
Returns a new mobject containing multiple copies of this one
arranged in a grid
"""
- grid = self.get_group_class()(*(self.copy() for n in range(n_rows * n_cols)))
+ grid = self.duplicate(n_rows * n_cols)
grid.arrange_in_grid(n_rows, n_cols, **kwargs)
if height is not None:
grid.set_height(height)
return grid
+ def duplicate(self, n: int):
+ """Returns an :class:`~.OpenGLVGroup` containing ``n`` copies of the mobject."""
+ return self.get_group_class()(*[self.copy() for _ in range(n)])
+
def sort(self, point_to_num_func=lambda p: p[0], submob_func=None):
+ """Sorts the list of :attr:`submobjects` by a function defined by ``submob_func``."""
if submob_func is not None:
self.submobjects.sort(key=submob_func)
else:
@@ -788,6 +1154,21 @@ class OpenGLMobject:
return self
def shuffle(self, recurse=False):
+ """Shuffles the order of :attr:`submobjects`
+
+ Examples
+ --------
+
+ .. manim:: ShuffleSubmobjectsExample
+
+ class ShuffleSubmobjectsExample(Scene):
+ def construct(self):
+ s= OpenGLVGroup(*[Dot().shift(i*0.1*RIGHT) for i in range(-20,20)])
+ s2= s.copy()
+ s2.shuffle()
+ s2.shift(DOWN)
+ self.play(Write(s), Write(s2))
+ """
if recurse:
for submob in self.submobjects:
submob.shuffle(recurse=True)
@@ -795,15 +1176,51 @@ class OpenGLMobject:
self.assemble_family()
return self
+ def invert(self, recursive=False):
+ """Inverts the list of :attr:`submobjects`.
+
+ Parameters
+ ----------
+ recursive
+ If ``True``, all submobject lists of this mobject's family are inverted.
+
+ Examples
+ --------
+
+ .. manim:: InvertSumobjectsExample
+
+ class InvertSumobjectsExample(Scene):
+ def construct(self):
+ s = VGroup(*[Dot().shift(i*0.1*RIGHT) for i in range(-20,20)])
+ s2 = s.copy()
+ s2.invert()
+ s2.shift(DOWN)
+ self.play(Write(s), Write(s2))
+ """
+ if recursive:
+ for submob in self.submobjects:
+ submob.invert(recursive=True)
+ list.reverse(self.submobjects)
+
# Copying
def copy(self, shallow: bool = False):
- """Copies the mobject.
+ """Create and return an identical copy of the :class:`OpenGLMobject` including all
+ :attr:`submobjects`.
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ The copy.
Parameters
----------
shallow
Controls whether a shallow copy is returned.
+
+ Note
+ ----
+ The clone is initially not visible in the Scene, even if the original was.
"""
if not shallow:
return self.deepcopy()
@@ -852,7 +1269,7 @@ class OpenGLMobject:
self.parents = parents
return result
- def generate_target(self, use_deepcopy=False):
+ def generate_target(self, use_deepcopy: bool = False):
self.target = None # Prevent exponential explosion
if use_deepcopy:
self.target = self.deepcopy()
@@ -860,7 +1277,8 @@ class OpenGLMobject:
self.target = self.copy()
return self.target
- def save_state(self, use_deepcopy=False):
+ def save_state(self, use_deepcopy: bool = False):
+ """Save the current state (position, color & size). Can be restored with :meth:`~.OpenGLMobject.restore`."""
if hasattr(self, "saved_state"):
# Prevent exponential growth of data
self.saved_state = None
@@ -871,6 +1289,7 @@ class OpenGLMobject:
return self
def restore(self):
+ """Restores the state that was previously saved with :meth:`~.OpenGLMobject.save_state`."""
if not hasattr(self, "saved_state") or self.save_state is None:
raise Exception("Trying to restore without having saved")
self.become(self.saved_state)
@@ -978,8 +1397,15 @@ class OpenGLMobject:
)
return self
- def scale(self, scale_factor, **kwargs):
- """
+ def scale(
+ self,
+ scale_factor: float,
+ about_point: Optional[Sequence[float]] = None,
+ about_edge: Sequence[float] = ORIGIN,
+ **kwargs,
+ ) -> "OpenGLMobject":
+ r"""Scale the size by a factor.
+
Default behavior is to scale about the center of the mobject.
The argument about_edge can be a vector, indicating which side of
the mobject to scale about, e.g., mob.scale(about_edge = RIGHT)
@@ -987,9 +1413,49 @@ class OpenGLMobject:
Otherwise, if about_point is given a value, scaling is done with
respect to that point.
+
+ Parameters
+ ----------
+ scale_factor
+ The scaling factor :math:`\alpha`. If :math:`0 < |\alpha| < 1`, the mobject
+ will shrink, and for :math:`|\alpha| > 1` it will grow. Furthermore,
+ if :math:`\alpha < 0`, the mobject is also flipped.
+ kwargs
+ Additional keyword arguments passed to
+ :meth:`apply_points_function_about_point`.
+
+ Returns
+ -------
+ OpenGLMobject
+ The scaled mobject.
+
+ Examples
+ --------
+
+ .. manim:: MobjectScaleExample
+ :save_last_frame:
+
+ class MobjectScaleExample(Scene):
+ def construct(self):
+ f1 = Text("F")
+ f2 = Text("F").scale(2)
+ f3 = Text("F").scale(0.5)
+ f4 = Text("F").scale(-1)
+
+ vgroup = VGroup(f1, f2, f3, f4).arrange(6 * RIGHT)
+ self.add(vgroup)
+
+ See also
+ --------
+ :meth:`move_to`
+
"""
self.apply_points_function(
- lambda points: scale_factor * points, works_on_bounding_box=True, **kwargs
+ lambda points: scale_factor * points,
+ about_point=about_point,
+ about_edge=about_edge,
+ works_on_bounding_box=True,
+ **kwargs,
)
return self
@@ -1008,15 +1474,35 @@ class OpenGLMobject:
self,
angle,
axis=OUT,
+ about_point: Optional[Sequence[float]] = None,
**kwargs,
):
+ """Rotates the :class:`~.OpenGLMobject` about a certain point."""
rot_matrix_T = rotation_matrix_transpose(angle, axis)
self.apply_points_function(
- lambda points: np.dot(points, rot_matrix_T), **kwargs
+ lambda points: np.dot(points, rot_matrix_T),
+ about_point=about_point,
+ **kwargs,
)
return self
def flip(self, axis=UP, **kwargs):
+ """Flips/Mirrors an mobject about its center.
+
+ Examples
+ --------
+
+ .. manim:: FlipExample
+ :save_last_frame:
+
+ class FlipExample(Scene):
+ def construct(self):
+ s= Line(LEFT, RIGHT+UP).shift(4*LEFT)
+ self.add(s)
+ s2= s.copy().flip()
+ self.add(s2)
+
+ """
return self.rotate(TAU / 2, axis, **kwargs)
def apply_function(self, function, **kwargs):
@@ -1050,6 +1536,32 @@ class OpenGLMobject:
return self
def apply_complex_function(self, function, **kwargs):
+ """Applies a complex function to a :class:`OpenGLMobject`.
+ The x and y coordinates correspond to the real and imaginary parts respectively.
+
+ Example
+ -------
+
+ .. manim:: ApplyFuncExample
+
+ class ApplyFuncExample(Scene):
+ def construct(self):
+ circ = Circle().scale(1.5)
+ circ_ref = circ.copy()
+ circ.apply_complex_function(
+ lambda x: np.exp(x*1j)
+ )
+ t = ValueTracker(0)
+ circ.add_updater(
+ lambda x: x.become(circ_ref.copy().apply_complex_function(
+ lambda x: np.exp(x+t.get_value()*1j)
+ )).set_color(BLUE)
+ )
+ self.add(circ_ref)
+ self.play(TransformFromCopy(circ_ref, circ))
+ self.play(t.animate.set_value(TAU), run_time=3)
+ """
+
def R3_func(point):
x, y, z = point
xy_complex = function(complex(x, y))
@@ -1086,6 +1598,7 @@ class OpenGLMobject:
# Positioning methods
def center(self):
+ """Moves the mobject to the center of the Scene."""
self.shift(-self.get_center())
return self
@@ -1121,6 +1634,26 @@ class OpenGLMobject:
index_of_submobject_to_align=None,
coor_mask=np.array([1, 1, 1]),
):
+ """Move this :class:`~.OpenGLMobject` next to another's :class:`~.OpenGLMobject` or coordinate.
+
+ Examples
+ --------
+
+ .. manim:: GeometricShapes
+ :save_last_frame:
+
+ class GeometricShapes(Scene):
+ def construct(self):
+ d = Dot()
+ c = Circle()
+ s = Square()
+ t = Triangle()
+ d.next_to(c, RIGHT)
+ s.next_to(c, LEFT)
+ t.next_to(c, DOWN)
+ self.add(d, c, s, t)
+
+ """
if isinstance(mobject_or_point, OpenGLMobject):
mob = mobject_or_point
if index_of_submobject_to_align is not None:
@@ -1154,23 +1687,19 @@ class OpenGLMobject:
return self
def is_off_screen(self):
- if self.get_left()[0] > config["frame_x_radius"]:
+ if self.get_left()[0] > config.frame_x_radius:
return True
- if self.get_right()[0] < -config["frame_x_radius"]:
+ if self.get_right()[0] < config.frame_x_radius:
return True
- if self.get_bottom()[1] > config["frame_y_radius"]:
+ if self.get_bottom()[1] > config.frame_y_radius:
return True
- if self.get_top()[1] < -config["frame_y_radius"]:
+ if self.get_top()[1] < -config.frame_y_radius:
return True
return False
def stretch_about_point(self, factor, dim, point):
return self.stretch(factor, dim, about_point=point)
- def stretch_in_place(self, factor, dim):
- # Now redundant with stretch
- return self.stretch(factor, dim)
-
def rescale_to_fit(self, length, dim, stretch=False, **kwargs):
old_length = self.length_over_dim(dim)
if old_length == 0:
@@ -1182,27 +1711,77 @@ class OpenGLMobject:
return self
def stretch_to_fit_width(self, width, **kwargs):
+ """Stretches the :class:`~.OpenGLMobject` to fit a width, not keeping height/depth proportional.
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ ``self``
+
+ Examples
+ --------
+ ::
+
+ >>> from manim import *
+ >>> sq = Square()
+ >>> sq.height
+ 2.0
+ >>> sq.stretch_to_fit_width(5)
+ Square
+ >>> sq.width
+ 5.0
+ >>> sq.height
+ 2.0
+ """
return self.rescale_to_fit(width, 0, stretch=True, **kwargs)
def stretch_to_fit_height(self, height, **kwargs):
+ """Stretches the :class:`~.OpenGLMobject` to fit a height, not keeping width/height proportional."""
return self.rescale_to_fit(height, 1, stretch=True, **kwargs)
def stretch_to_fit_depth(self, depth, **kwargs):
+ """Stretches the :class:`~.OpenGLMobject` to fit a depth, not keeping width/height proportional."""
return self.rescale_to_fit(depth, 1, stretch=True, **kwargs)
def set_width(self, width, stretch=False, **kwargs):
+ """Scales the :class:`~.OpenGLMobject` to fit a width while keeping height/depth proportional.
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ ``self``
+
+ Examples
+ --------
+ ::
+
+ >>> from manim import *
+ >>> sq = Square()
+ >>> sq.height
+ 2.0
+ >>> sq.scale_to_fit_width(5)
+ Square
+ >>> sq.width
+ 5.0
+ >>> sq.height
+ 5.0
+ """
return self.rescale_to_fit(width, 0, stretch=stretch, **kwargs)
scale_to_fit_width = set_width
def set_height(self, height, stretch=False, **kwargs):
+ """Scales the :class:`~.OpenGLMobject` to fit a height while keeping width/depth proportional."""
return self.rescale_to_fit(height, 1, stretch=stretch, **kwargs)
scale_to_fit_height = set_height
def set_depth(self, depth, stretch=False, **kwargs):
+ """Scales the :class:`~.OpenGLMobject` to fit a depth while keeping width/height proportional."""
return self.rescale_to_fit(depth, 2, stretch=stretch, **kwargs)
+ scale_to_fit_depth = set_depth
+
def set_coord(self, value, dim, direction=ORIGIN):
curr = self.get_coord(dim, direction)
shift_vect = np.zeros(self.dim)
@@ -1211,12 +1790,15 @@ class OpenGLMobject:
return self
def set_x(self, x, direction=ORIGIN):
+ """Set x value of the center of the :class:`~.OpenGLMobject` (``int`` or ``float``)"""
return self.set_coord(x, 0, direction)
def set_y(self, y, direction=ORIGIN):
+ """Set y value of the center of the :class:`~.OpenGLMobject` (``int`` or ``float``)"""
return self.set_coord(y, 1, direction)
def set_z(self, z, direction=ORIGIN):
+ """Set z value of the center of the :class:`~.OpenGLMobject` (``int`` or ``float``)"""
return self.set_coord(z, 2, direction)
def space_out_submobjects(self, factor=1.5, **kwargs):
@@ -1231,6 +1813,7 @@ class OpenGLMobject:
aligned_edge=ORIGIN,
coor_mask=np.array([1, 1, 1]),
):
+ """Move center of the :class:`~.OpenGLMobject` to certain coordinate."""
if isinstance(point_or_mobject, OpenGLMobject):
target = point_or_mobject.get_bounding_box_point(aligned_edge)
else:
@@ -1255,7 +1838,13 @@ class OpenGLMobject:
self.shift(mobject.get_center() - self.get_center())
return self
- def surround(self, mobject, dim_to_match=0, stretch=False, buff=MED_SMALL_BUFF):
+ def surround(
+ self,
+ mobject: "OpenGLMobject",
+ dim_to_match: int = 0,
+ stretch: bool = False,
+ buff: float = MED_SMALL_BUFF,
+ ):
self.replace(mobject, dim_to_match, stretch)
length = mobject.length_over_dim(dim_to_match)
self.scale((length + buff) / length)
@@ -1393,9 +1982,38 @@ class OpenGLMobject:
# Background rectangle
- def add_background_rectangle(self, color=None, opacity=0.75, **kwargs):
+ def add_background_rectangle(
+ self, color: Optional[Colors] = None, opacity: float = 0.75, **kwargs
+ ):
# TODO, this does not behave well when the mobject has points,
# since it gets displayed on top
+ """Add a BackgroundRectangle as submobject.
+
+ The BackgroundRectangle is added behind other submobjects.
+
+ This can be used to increase the mobjects visibility in front of a noisy background.
+
+ Parameters
+ ----------
+ color
+ The color of the BackgroundRectangle
+ opacity
+ The opacity of the BackgroundRectangle
+ kwargs
+ Additional keyword arguments passed to the BackgroundRectangle constructor
+
+
+ Returns
+ -------
+ :class:`OpenGLMobject`
+ ``self``
+
+ See Also
+ --------
+ :meth:`add_to_back`
+ :class:`~.BackgroundRectangle`
+
+ """
from ..mobject.shape_matchers import BackgroundRectangle
self.background_rectangle = BackgroundRectangle(
@@ -1421,13 +2039,16 @@ class OpenGLMobject:
indices = (np.sign(direction) + 1).astype(int)
return np.array([bb[indices[i]][i] for i in range(3)])
- def get_edge_center(self, direction):
+ def get_edge_center(self, direction) -> np.ndarray:
+ """Get edge coordinates for certain direction."""
return self.get_bounding_box_point(direction)
- def get_corner(self, direction):
+ def get_corner(self, direction) -> np.ndarray:
+ """Get corner coordinates for certain direction."""
return self.get_bounding_box_point(direction)
- def get_center(self):
+ def get_center(self) -> np.ndarray:
+ """Get center coordinates."""
return self.get_bounding_box()[1]
def get_center_of_mass(self):
@@ -1455,22 +2076,28 @@ class OpenGLMobject:
),
)
- def get_top(self):
+ def get_top(self) -> np.ndarray:
+ """Get top coordinates of a box bounding the :class:`~.OpenGLMobject`"""
return self.get_edge_center(UP)
- def get_bottom(self):
+ def get_bottom(self) -> np.ndarray:
+ """Get bottom coordinates of a box bounding the :class:`~.OpenGLMobject`"""
return self.get_edge_center(DOWN)
- def get_right(self):
+ def get_right(self) -> np.ndarray:
+ """Get right coordinates of a box bounding the :class:`~.OpenGLMobject`"""
return self.get_edge_center(RIGHT)
- def get_left(self):
+ def get_left(self) -> np.ndarray:
+ """Get left coordinates of a box bounding the :class:`~.OpenGLMobject`"""
return self.get_edge_center(LEFT)
- def get_zenith(self):
+ def get_zenith(self) -> np.ndarray:
+ """Get zenith coordinates of a box bounding a 3D :class:`~.OpenGLMobject`."""
return self.get_edge_center(OUT)
- def get_nadir(self):
+ def get_nadir(self) -> np.ndarray:
+ """Get nadir (opposite the zenith) coordinates of a box bounding a 3D :class:`~.OpenGLMobject`."""
return self.get_edge_center(IN)
def length_over_dim(self, dim):
@@ -1478,38 +2105,45 @@ class OpenGLMobject:
return abs((bb[2] - bb[0])[dim])
def get_width(self):
+ """Returns the width of the mobject."""
return self.length_over_dim(0)
def get_height(self):
+ """Returns the height of the mobject."""
return self.length_over_dim(1)
def get_depth(self):
+ """Returns the depth of the mobject."""
return self.length_over_dim(2)
- def get_coord(self, dim, direction=ORIGIN):
- """
- Meant to generalize get_x, get_y, get_z
- """
+ def get_coord(self, dim: int, direction=ORIGIN):
+ """Meant to generalize ``get_x``, ``get_y`` and ``get_z``"""
return self.get_bounding_box_point(direction)[dim]
- def get_x(self, direction=ORIGIN):
+ def get_x(self, direction=ORIGIN) -> np.float64:
+ """Returns x coordinate of the center of the :class:`~.OpenGLMobject` as ``float``"""
return self.get_coord(0, direction)
- def get_y(self, direction=ORIGIN):
+ def get_y(self, direction=ORIGIN) -> np.float64:
+ """Returns y coordinate of the center of the :class:`~.OpenGLMobject` as ``float``"""
return self.get_coord(1, direction)
- def get_z(self, direction=ORIGIN):
+ def get_z(self, direction=ORIGIN) -> np.float64:
+ """Returns z coordinate of the center of the :class:`~.OpenGLMobject` as ``float``"""
return self.get_coord(2, direction)
def get_start(self):
+ """Returns the point, where the stroke that surrounds the :class:`~.OpenGLMobject` starts."""
self.throw_error_if_no_points()
return np.array(self.points[0])
def get_end(self):
+ """Returns the point, where the stroke that surrounds the :class:`~.OpenGLMobject` ends."""
self.throw_error_if_no_points()
return np.array(self.points[-1])
def get_start_and_end(self):
+ """Returns starting and ending point of a stroke as a ``tuple``."""
return self.get_start(), self.get_end()
def point_from_proportion(self, alpha):
@@ -1539,22 +2173,28 @@ class OpenGLMobject:
# Match other mobject properties
- def match_color(self, mobject):
+ def match_color(self, mobject: "OpenGLMobject"):
+ """Match the color with the color of another :class:`~.OpenGLMobject`."""
return self.set_color(mobject.get_color())
- def match_dim_size(self, mobject, dim, **kwargs):
+ def match_dim_size(self, mobject: "OpenGLMobject", dim, **kwargs):
+ """Match the specified dimension with the dimension of another :class:`~.OpenGLMobject`."""
return self.rescale_to_fit(mobject.length_over_dim(dim), dim, **kwargs)
- def match_width(self, mobject, **kwargs):
+ def match_width(self, mobject: "OpenGLMobject", **kwargs):
+ """Match the width with the width of another :class:`~.OpenGLMobject`."""
return self.match_dim_size(mobject, 0, **kwargs)
- def match_height(self, mobject, **kwargs):
+ def match_height(self, mobject: "OpenGLMobject", **kwargs):
+ """Match the height with the height of another :class:`~.OpenGLMobject`."""
return self.match_dim_size(mobject, 1, **kwargs)
- def match_depth(self, mobject, **kwargs):
+ def match_depth(self, mobject: "OpenGLMobject", **kwargs):
+ """Match the depth with the depth of another :class:`~.OpenGLMobject`."""
return self.match_dim_size(mobject, 2, **kwargs)
- def match_coord(self, mobject, dim, direction=ORIGIN):
+ def match_coord(self, mobject: "OpenGLMobject", dim, direction=ORIGIN):
+ """Match the coordinates with the coordinates of another :class:`~.OpenGLMobject`."""
return self.set_coord(
mobject.get_coord(dim, direction),
dim=dim,
@@ -1562,15 +2202,22 @@ class OpenGLMobject:
)
def match_x(self, mobject, direction=ORIGIN):
+ """Match x coord. to the x coord. of another :class:`~.OpenGLMobject`."""
return self.match_coord(mobject, 0, direction)
def match_y(self, mobject, direction=ORIGIN):
+ """Match y coord. to the x coord. of another :class:`~.OpenGLMobject`."""
return self.match_coord(mobject, 1, direction)
def match_z(self, mobject, direction=ORIGIN):
+ """Match z coord. to the x coord. of another :class:`~.OpenGLMobject`."""
return self.match_coord(mobject, 2, direction)
- def align_to(self, mobject_or_point, direction=ORIGIN):
+ def align_to(
+ self,
+ mobject_or_point: Union["OpenGLMobject", Sequence[float]],
+ direction=ORIGIN,
+ ):
"""
Examples:
mob1.align_to(mob2, UP) moves mob1 vertically so that its
@@ -1672,6 +2319,26 @@ class OpenGLMobject:
# Interpolate
def interpolate(self, mobject1, mobject2, alpha, path_func=straight_path):
+ """Turns this :class:`~.OpenGLMobject` into an interpolation between ``mobject1``
+ and ``mobject2``.
+
+ Examples
+ --------
+
+ .. manim:: DotInterpolation
+ :save_last_frame:
+
+ class DotInterpolation(Scene):
+ def construct(self):
+ dotR = Dot(color=DARK_GREY)
+ dotR.shift(2 * RIGHT)
+ dotL = Dot(color=WHITE)
+ dotL.shift(2 * LEFT)
+
+ dotMiddle = OpenGLVMobject().interpolate(dotL, dotR, alpha=0.3)
+
+ self.add(dotL, dotR, dotMiddle)
+ """
for key in self.data:
if key in self.locked_data_keys:
continue
@@ -1703,11 +2370,65 @@ class OpenGLMobject:
"""
pass # To implement in subclass
- def become(self, mobject):
- """
- Edit all data and submobjects to be identical
- to another mobject
+ def become(
+ self,
+ mobject: "OpenGLMobject",
+ match_height: bool = False,
+ match_width: bool = False,
+ match_depth: bool = False,
+ match_center: bool = False,
+ stretch: bool = False,
+ ):
+ """Edit all data and submobjects to be identical
+ to another :class:`~.OpenGLMobject`
+
+ .. note::
+
+ If both match_height and match_width are ``True`` then the transformed :class:`~.OpenGLMobject`
+ will match the height first and then the width
+
+ Parameters
+ ----------
+ match_height
+ If ``True``, then the transformed :class:`~.OpenGLMobject` will match the height of the original
+ match_width
+ If ``True``, then the transformed :class:`~.OpenGLMobject` will match the width of the original
+ match_depth
+ If ``True``, then the transformed :class:`~.OpenGLMobject` will match the depth of the original
+ match_center
+ If ``True``, then the transformed :class:`~.OpenGLMobject` will match the center of the original
+ stretch
+ If ``True``, then the transformed :class:`~.OpenGLMobject` will stretch to fit the proportions of the original
+
+ Examples
+ --------
+ .. manim:: BecomeScene
+
+ class BecomeScene(Scene):
+ def construct(self):
+ circ = Circle(fill_color=RED, fill_opacity=0.8)
+ square = Square(fill_color=BLUE, fill_opacity=0.2)
+ self.add(circ)
+ self.wait(0.5)
+ circ.become(square)
+ self.wait(0.5)
"""
+
+ if stretch:
+ mobject.stretch_to_fit_height(self.height)
+ mobject.stretch_to_fit_width(self.width)
+ mobject.stretch_to_fit_depth(self.depth)
+ else:
+ if match_height:
+ mobject.match_height(self)
+ if match_width:
+ mobject.match_width(self)
+ if match_depth:
+ mobject.match_depth(self)
+
+ if match_center:
+ mobject.move_to(self.get_center())
+
self.align_family(mobject)
for sm1, sm2 in zip(self.get_family(), mobject.get_family()):
sm1.set_data(sm2.data)
@@ -1915,96 +2636,13 @@ class OpenGLMobject:
self.remove(*self.submobjects)
self.add(*submobject_list)
- # Event Handlers
- """
- Event handling follows the Event Bubbling model of DOM in javascript.
- Return false to stop the event bubbling.
- To learn more visit https://www.quirksmode.org/js/events_order.html
-
- Event Callback Argument is a callable function taking two arguments:
- 1. Mobject
- 2. EventData
- """
-
- def init_event_listners(self):
- self.event_listners = []
-
- def add_event_listner(self, event_type, event_callback):
- event_listner = EventListner(self, event_type, event_callback)
- self.event_listners.append(event_listner)
- EVENT_DISPATCHER.add_listner(event_listner)
- return self
-
- def remove_event_listner(self, event_type, event_callback):
- event_listner = EventListner(self, event_type, event_callback)
- while event_listner in self.event_listners:
- self.event_listners.remove(event_listner)
- EVENT_DISPATCHER.remove_listner(event_listner)
- return self
-
- def clear_event_listners(self, recurse=True):
- self.event_listners = []
- if recurse:
- for submob in self.submobjects:
- submob.clear_event_listners(recurse=recurse)
- return self
-
- def get_event_listners(self):
- return self.event_listners
-
- def get_family_event_listners(self):
- return list(it.chain(*(sm.get_event_listners() for sm in self.get_family())))
-
- def get_has_event_listner(self):
- return any(mob.get_event_listners() for mob in self.get_family())
-
- def add_mouse_motion_listner(self, callback):
- self.add_event_listner(EventType.MouseMotionEvent, callback)
-
- def remove_mouse_motion_listner(self, callback):
- self.remove_event_listner(EventType.MouseMotionEvent, callback)
-
- def add_mouse_press_listner(self, callback):
- self.add_event_listner(EventType.MousePressEvent, callback)
-
- def remove_mouse_press_listner(self, callback):
- self.remove_event_listner(EventType.MousePressEvent, callback)
-
- def add_mouse_release_listner(self, callback):
- self.add_event_listner(EventType.MouseReleaseEvent, callback)
-
- def remove_mouse_release_listner(self, callback):
- self.remove_event_listner(EventType.MouseReleaseEvent, callback)
-
- def add_mouse_drag_listner(self, callback):
- self.add_event_listner(EventType.MouseDragEvent, callback)
-
- def remove_mouse_drag_listner(self, callback):
- self.remove_event_listner(EventType.MouseDragEvent, callback)
-
- def add_mouse_scroll_listner(self, callback):
- self.add_event_listner(EventType.MouseScrollEvent, callback)
-
- def remove_mouse_scroll_listner(self, callback):
- self.remove_event_listner(EventType.MouseScrollEvent, callback)
-
- def add_key_press_listner(self, callback):
- self.add_event_listner(EventType.KeyPressEvent, callback)
-
- def remove_key_press_listner(self, callback):
- self.remove_event_listner(EventType.KeyPressEvent, callback)
-
- def add_key_release_listner(self, callback):
- self.add_event_listner(EventType.KeyReleaseEvent, callback)
-
- def remove_key_release_listner(self, callback):
- self.remove_event_listner(EventType.KeyReleaseEvent, callback)
-
# Errors
def throw_error_if_no_points(self):
if not self.has_points():
- message = "Cannot call Mobject.{} " + "for a Mobject with no points"
+ message = (
+ "Cannot call OpenGLMobject.{} " + "for a OpenGLMobject with no points"
+ )
caller_name = sys._getframe(1).f_code.co_name
raise Exception(message.format(caller_name))
@@ -2012,7 +2650,7 @@ class OpenGLMobject:
class OpenGLGroup(OpenGLMobject):
def __init__(self, *mobjects, **kwargs):
if not all([isinstance(m, OpenGLMobject) for m in mobjects]):
- raise Exception("All submobjects must be of type Mobject")
+ raise Exception("All submobjects must be of type OpenGLMobject")
super().__init__(**kwargs)
self.add(*mobjects)
@@ -2109,6 +2747,57 @@ class _AnimationBuilder:
def override_animate(method):
+ r"""Decorator for overriding method animations.
+
+ This allows to specify a method (returning an :class:`~.Animation`)
+ which is called when the decorated method is used with the ``.animate`` syntax
+ for animating the application of a method.
+
+ .. seealso::
+
+ :attr:`OpenGLMobject.animate`
+
+ .. note::
+
+ Overridden methods cannot be combined with normal or other overridden
+ methods using method chaining with the ``.animate`` syntax.
+
+
+ Examples
+ --------
+
+ .. manim:: AnimationOverrideExample
+
+ class CircleWithContent(VGroup):
+ def __init__(self, content):
+ super().__init__()
+ self.circle = Circle()
+ self.content = content
+ self.add(self.circle, content)
+ content.move_to(self.circle.get_center())
+
+ def clear_content(self):
+ self.remove(self.content)
+ self.content = None
+
+ @override_animate(clear_content)
+ def _clear_content_animation(self, anim_args=None):
+ if anim_args is None:
+ anim_args = {}
+ anim = Uncreate(self.content, **anim_args)
+ self.clear_content()
+ return anim
+
+ class AnimationOverrideExample(Scene):
+ def construct(self):
+ t = Text("hello!")
+ my_mobject = CircleWithContent(t)
+ self.play(Create(my_mobject))
+ self.play(my_mobject.animate.clear_content())
+ self.wait()
+
+ """
+
def decorator(animation_method):
method._override_animate = animation_method
return animation_method
diff --git a/manim/mobject/shape_matchers.py b/manim/mobject/shape_matchers.py
index e08fac8a1..a32050243 100644
--- a/manim/mobject/shape_matchers.py
+++ b/manim/mobject/shape_matchers.py
@@ -4,11 +4,14 @@ __all__ = ["SurroundingRectangle", "BackgroundRectangle", "Cross", "Underline"]
from typing import Optional
+from manim.utils.color import Color
+
+from .. import config
from ..constants import *
from ..mobject.geometry import Line, RoundedRectangle
from ..mobject.mobject import Mobject
from ..mobject.types.vectorized_mobject import VGroup
-from ..utils.color import BLACK, RED, YELLOW, Color
+from ..utils.color import BLACK, RED, YELLOW, Colors
class SurroundingRectangle(RoundedRectangle):
@@ -52,7 +55,8 @@ class SurroundingRectangle(RoundedRectangle):
class BackgroundRectangle(SurroundingRectangle):
- """A background rectangle
+ """A background rectangle. Its default color is the background color
+ of the scene.
Examples
--------
@@ -79,13 +83,16 @@ class BackgroundRectangle(SurroundingRectangle):
def __init__(
self,
mobject,
- color=BLACK,
- stroke_width=0,
- stroke_opacity=0,
- fill_opacity=0.75,
- buff=0,
+ color: Optional[Colors] = None,
+ stroke_width: float = 0,
+ stroke_opacity: float = 0,
+ fill_opacity: float = 0.75,
+ buff: float = 0,
**kwargs
):
+ if color is None:
+ color = config.background_color
+
super().__init__(
mobject,
color=color,
diff --git a/manim/mobject/types/opengl_vectorized_mobject.py b/manim/mobject/types/opengl_vectorized_mobject.py
index f3e6006e8..c8c618727 100644
--- a/manim/mobject/types/opengl_vectorized_mobject.py
+++ b/manim/mobject/types/opengl_vectorized_mobject.py
@@ -1,7 +1,7 @@
import itertools as it
import operator as op
from functools import reduce, wraps
-from typing import Callable, Iterable, Optional, Tuple
+from typing import Callable, Iterable, Optional, Sequence, Tuple, Union
import moderngl
import numpy as np
@@ -17,6 +17,7 @@ from ...utils.bezier import (
integer_interpolate,
interpolate,
partial_quadratic_bezier_points,
+ proportions_along_bezier_curve_for_point,
)
from ...utils.color import *
from ...utils.config_ops import _Data
@@ -39,6 +40,8 @@ JOINT_TYPE_MAP = {
class OpenGLVMobject(OpenGLMobject):
+ """A vectorized mobject."""
+
fill_dtype = [
("point", np.float32, (3,)),
("unit_normal", np.float32, (3,)),
@@ -63,30 +66,30 @@ class OpenGLVMobject(OpenGLMobject):
def __init__(
self,
- fill_color=None,
- fill_opacity=0.0,
- stroke_color=None,
- stroke_opacity=1.0,
- stroke_width=DEFAULT_STROKE_WIDTH,
- draw_stroke_behind_fill=False,
+ fill_color: Optional[Color] = None,
+ fill_opacity: float = 0.0,
+ stroke_color: Optional[Color] = None,
+ stroke_opacity: float = 1.0,
+ stroke_width: float = DEFAULT_STROKE_WIDTH,
+ draw_stroke_behind_fill: bool = False,
# Indicates that it will not be displayed, but
# that it should count in parent mobject's path
- pre_function_handle_to_anchor_scale_factor=0.01,
- make_smooth_after_applying_functions=False,
- background_image_file=None,
+ pre_function_handle_to_anchor_scale_factor: float = 0.01,
+ make_smooth_after_applying_functions: float = False,
+ background_image_file: Optional[str] = None,
# This is within a pixel
# TODO, do we care about accounting for
# varying zoom levels?
- tolerance_for_point_equality=1e-8,
- n_points_per_curve=3,
- long_lines=False,
- should_subdivide_sharp_curves=False,
- should_remove_null_curves=False,
+ tolerance_for_point_equality: float = 1e-8,
+ n_points_per_curve: int = 3,
+ long_lines: bool = False,
+ should_subdivide_sharp_curves: bool = False,
+ should_remove_null_curves: bool = False,
# Could also be "bevel", "miter", "round"
- joint_type="auto",
- flat_stroke=True,
+ joint_type: str = "auto",
+ flat_stroke: bool = True,
render_primitive=moderngl.TRIANGLES,
- triangulation_locked=False,
+ triangulation_locked: bool = False,
**kwargs,
):
self.data = {}
@@ -151,7 +154,47 @@ class OpenGLVMobject(OpenGLMobject):
self.set_flat_stroke(self.flat_stroke)
return self
- def set_fill(self, color=None, opacity=None, recurse=True):
+ def set_fill(
+ self,
+ color: Optional[Color] = None,
+ opacity: Optional[float] = None,
+ recurse: bool = True,
+ ) -> "OpenGLVMobject":
+ """Set the fill color and fill opacity of a :class:`OpenGLVMobject`.
+
+ Parameters
+ ----------
+ color
+ Fill color of the :class:`OpenGLVMobject`.
+ opacity
+ Fill opacity of the :class:`OpenGLVMobject`.
+ family
+ If ``True``, the fill color of all submobjects is also set.
+
+ Returns
+ -------
+ OpenGLVMobject
+ self. For chaining purposes.
+
+ Examples
+ --------
+ .. manim:: SetFill
+ :save_last_frame:
+
+ class SetFill(Scene):
+ def construct(self):
+ square = Square().scale(2).set_fill(WHITE,1)
+ circle1 = Circle().set_fill(GREEN,0.8)
+ circle2 = Circle().set_fill(YELLOW) # No fill_opacity
+ circle3 = Circle().set_fill(color = '#FF2135', opacity = 0.2)
+ group = Group(circle1,circle2,circle3).arrange()
+ self.add(square)
+ self.add(group)
+
+ See Also
+ --------
+ :meth:`~.OpenGLVMobject.set_style`
+ """
if color is not None:
if isinstance(color, str):
self.fill_color = Color(color)
@@ -405,7 +448,15 @@ class OpenGLVMobject(OpenGLMobject):
else:
self.append_points([self.get_last_point(), handle, anchor])
- def add_line_to(self, point):
+ def add_line_to(self, point: Sequence[float]) -> "OpenGLVMobject":
+ """Add a straight line from the last point of OpenGLVMobject to the given point.
+
+ Parameters
+ ----------
+
+ point : Sequence[float]
+ end of the straight line.
+ """
end = self.points[-1]
alphas = np.linspace(0, 1, self.n_points_per_curve)
if self.long_lines:
@@ -476,7 +527,22 @@ class OpenGLVMobject(OpenGLMobject):
self.add_line_to(point)
return points
- def set_points_as_corners(self, points):
+ def set_points_as_corners(self, points: Iterable[float]) -> "OpenGLVMobject":
+ """Given an array of points, set them as corner of the vmobject.
+
+ To achieve that, this algorithm sets handles aligned with the anchors such that the resultant bezier curve will be the segment
+ between the two anchors.
+
+ Parameters
+ ----------
+ points : Iterable[float]
+ Array of points that will be set as corners.
+
+ Returns
+ -------
+ OpenGLVMobject
+ self. For chaining purposes.
+ """
nppc = self.n_points_per_curve
points = np.array(points)
self.set_anchors_and_handles(
@@ -490,6 +556,15 @@ class OpenGLVMobject(OpenGLMobject):
return self
def change_anchor_mode(self, mode):
+ """Changes the anchor mode of the bezier curves. This will modify the handles.
+
+ There can be only three modes, "jagged", "approx_smooth" and "true_smooth".
+
+ Returns
+ -------
+ OpenGLVMobject
+ For chaining purposes.
+ """
assert mode in ("jagged", "approx_smooth", "true_smooth")
nppc = self.n_points_per_curve
for submob in self.family_members_with_points():
@@ -499,6 +574,7 @@ class OpenGLVMobject(OpenGLMobject):
anchors = np.vstack([subpath[::nppc], subpath[-1:]])
new_subpath = np.array(subpath)
if mode == "approx_smooth":
+ # TODO: get_smooth_quadratic_bezier_handle_points is not defined
new_subpath[1::nppc] = get_smooth_quadratic_bezier_handle_points(
anchors,
)
@@ -562,6 +638,14 @@ class OpenGLVMobject(OpenGLMobject):
# Information about the curve
def force_direction(self, target_direction):
+ """Makes sure that points are either directed clockwise or
+ counterclockwise.
+
+ Parameters
+ ----------
+ target_direction : :class:`str`
+ Either ``"CW"`` or ``"CCW"``.
+ """
if target_direction not in ("CW", "CCW"):
raise ValueError('Invalid input for force_direction. Use "CW" or "CCW"')
@@ -571,6 +655,27 @@ class OpenGLVMobject(OpenGLMobject):
return self
def reverse_direction(self):
+ """Reverts the point direction by inverting the point order.
+
+ Returns
+ -------
+ :class:`OpenGLVMobject`
+ Returns self.
+
+ Examples
+ --------
+ .. manim:: ChangeOfDirection
+
+ class ChangeOfDirection(Scene):
+ def construct(self):
+ ccw = RegularPolygon(5)
+ ccw.shift(LEFT).rotate
+ cw = RegularPolygon(5)
+ cw.shift(RIGHT).reverse_direction()
+
+ self.play(Create(ccw), Create(cw),
+ run_time=4)
+ """
self.set_points(self.points[::-1])
return self
@@ -601,14 +706,47 @@ class OpenGLVMobject(OpenGLMobject):
]
def get_subpaths(self):
+ """Returns subpaths formed by the curves of the OpenGLVMobject.
+
+ We define a subpath between two curve if one of their extreminities are coincidents.
+
+ Returns
+ -------
+ Tuple
+ subpaths.
+ """
return self.get_subpaths_from_points(self.points)
- def get_nth_curve_points(self, n):
+ def get_nth_curve_points(self, n: int) -> np.ndarray:
+ """Returns the points defining the nth curve of the vmobject.
+
+ Parameters
+ ----------
+ n : int
+ index of the desired bezier curve.
+
+ Returns
+ -------
+ np.ndarray
+ points defininf the nth bezier curve (anchors, handles)
+ """
assert n < self.get_num_curves()
nppc = self.n_points_per_curve
return self.points[nppc * n : nppc * (n + 1)]
- def get_nth_curve_function(self, n):
+ def get_nth_curve_function(self, n: int) -> Callable[[float], np.ndarray]:
+ """Returns the expression of the nth curve.
+
+ Parameters
+ ----------
+ n : int
+ index of the desired curve.
+
+ Returns
+ -------
+ typing.Callable[float]
+ expression of the nth bezier curve.
+ """
return bezier(self.get_nth_curve_points(n))
def get_nth_curve_function_with_length(
@@ -646,9 +784,75 @@ class OpenGLVMobject(OpenGLMobject):
return curve, length
- def get_num_curves(self):
+ def get_num_curves(self) -> int:
+ """Returns the number of curves of the vmobject.
+
+ Returns
+ -------
+ int
+ number of curves. of the vmobject.
+ """
return self.get_num_points() // self.n_points_per_curve
+ def get_nth_curve_length(
+ self,
+ n: int,
+ sample_points: Optional[int] = None,
+ ) -> float:
+ """Returns the (approximate) length of the nth curve.
+
+ Parameters
+ ----------
+ n
+ The index of the desired curve.
+ sample_points
+ The number of points to sample to find the length.
+
+ Returns
+ -------
+ length : :class:`float`
+ The length of the nth curve.
+ """
+
+ _, length = self.get_nth_curve_function_with_length(n, sample_points)
+
+ return length
+
+ def get_nth_curve_function_with_length(
+ self,
+ n: int,
+ sample_points: Optional[int] = None,
+ ) -> Tuple[Callable[[float], np.ndarray], float]:
+ """Returns the expression of the nth curve along with its (approximate) length.
+
+ Parameters
+ ----------
+ n
+ The index of the desired curve.
+ sample_points
+ The number of points to sample to find the length.
+
+ Returns
+ -------
+ curve : typing.Callable[[float], np.ndarray]
+ The function for the nth curve.
+ length : :class:`float`
+ The length of the nth curve.
+ """
+
+ if sample_points is None:
+ sample_points = 10
+
+ curve = self.get_nth_curve_function(n)
+
+ points = np.array([curve(a) for a in np.linspace(0, 1, sample_points)])
+ diffs = points[1:] - points[:-1]
+ norms = np.apply_along_axis(np.linalg.norm, 1, diffs)
+
+ length = np.sum(norms)
+
+ return curve, length
+
def get_curve_functions(
self,
) -> Iterable[Callable[[float], np.ndarray]]:
@@ -730,6 +934,62 @@ class OpenGLVMobject(OpenGLMobject):
current_length += length
+ def proportion_from_point(
+ self,
+ point: Iterable[Union[float, int]],
+ ) -> float:
+ """Returns the proportion along the path of the :class:`OpenGLVMobject`
+ a particular given point is at.
+
+ Parameters
+ ----------
+ point
+ The Cartesian coordinates of the point which may or may not lie on the :class:`OpenGLVMobject`
+
+ Returns
+ -------
+ float
+ The proportion along the path of the :class:`OpenGLVMobject`.
+
+ Raises
+ ------
+ :exc:`ValueError`
+ If ``point`` does not lie on the curve.
+ :exc:`Exception`
+ If the :class:`OpenGLVMobject` has no points.
+ """
+ self.throw_error_if_no_points()
+
+ # Iterate over each bezier curve that the ``VMobject`` is composed of, checking
+ # if the point lies on that curve. If it does not lie on that curve, add
+ # the whole length of the curve to ``target_length`` and move onto the next
+ # curve. If the point does lie on the curve, add how far along the curve
+ # the point is to ``target_length``.
+ # Then, divide ``target_length`` by the total arc length of the shape to get
+ # the proportion along the ``VMobject`` the point is at.
+
+ num_curves = self.get_num_curves()
+ total_length = self.get_arc_length()
+ target_length = 0
+ for n in range(num_curves):
+ control_points = self.get_nth_curve_points(n)
+ length = self.get_nth_curve_length(n)
+ proportions_along_bezier = proportions_along_bezier_curve_for_point(
+ point,
+ control_points,
+ )
+ if len(proportions_along_bezier) > 0:
+ proportion_along_nth_curve = max(proportions_along_bezier)
+ target_length += length * proportion_along_nth_curve
+ break
+ target_length += length
+ else:
+ raise ValueError(f"Point {point} does not lie on this curve.")
+
+ alpha = target_length / total_length
+
+ return alpha
+
def get_anchors_and_handles(self):
"""
Returns anchors1, handles, anchors2,
@@ -741,14 +1001,35 @@ class OpenGLVMobject(OpenGLMobject):
points = self.points
return [points[i::nppc] for i in range(nppc)]
- def get_start_anchors(self):
+ def get_start_anchors(self) -> np.ndarray:
+ """Returns the start anchors of the bezier curves.
+
+ Returns
+ -------
+ np.ndarray
+ Starting anchors
+ """
return self.points[0 :: self.n_points_per_curve]
- def get_end_anchors(self):
+ def get_end_anchors(self) -> np.ndarray:
+ """Return the starting anchors of the bezier curves.
+
+ Returns
+ -------
+ np.ndarray
+ Starting anchors
+ """
nppc = self.n_points_per_curve
return self.points[nppc - 1 :: nppc]
- def get_anchors(self):
+ def get_anchors(self) -> np.ndarray:
+ """Returns the anchors of the curves forming the OpenGLVMobject.
+
+ Returns
+ -------
+ np.ndarray
+ The anchors.
+ """
points = self.points
if len(points) == 1:
return points
@@ -825,6 +1106,23 @@ class OpenGLVMobject(OpenGLMobject):
)
def get_direction(self):
+ """Uses :func:`~.space_ops.shoelace_direction` to calculate the direction.
+ The direction of points determines in which direction the
+ object is drawn, clockwise or counterclockwise.
+
+ Examples
+ --------
+ The default direction of a :class:`~.Circle` is counterclockwise::
+
+ >>> from manim import Circle
+ >>> Circle().get_direction()
+ 'CCW'
+
+ Returns
+ -------
+ :class:`str`
+ Either ``"CW"`` or ``"CCW"``.
+ """
return shoelace_direction(self.get_start_anchors())
def get_unit_normal(self, recompute=False):
@@ -894,7 +1192,19 @@ class OpenGLVMobject(OpenGLMobject):
vmobject.set_points(np.vstack(new_subpaths2))
return self
- def insert_n_curves(self, n, recurse=True):
+ def insert_n_curves(self, n: int, recurse=True) -> "OpenGLVMobject":
+ """Inserts n curves to the bezier curves of the vmobject.
+
+ Parameters
+ ----------
+ n
+ Number of curves to insert.
+
+ Returns
+ -------
+ OpenGLVMobject
+ for chaining.
+ """
for mob in self.get_family(recurse):
if mob.get_num_curves() > 0:
new_points = mob.insert_n_curves_to_point_list(n, mob.points)
@@ -904,7 +1214,23 @@ class OpenGLVMobject(OpenGLMobject):
mob.set_points(new_points)
return self
- def insert_n_curves_to_point_list(self, n, points):
+ def insert_n_curves_to_point_list(self, n: int, points: np.ndarray) -> np.ndarray:
+ """Given an array of k points defining a bezier curves
+ (anchors and handles), returns points defining exactly
+ k + n bezier curves.
+
+ Parameters
+ ----------
+ n : int
+ Number of desired curves.
+ points : np.ndarray
+ Starting points.
+
+ Returns
+ -------
+ np.ndarray
+ Points generated.
+ """
nppc = self.n_points_per_curve
if len(points) == 1:
return np.repeat(points, nppc * n, 0)
@@ -946,7 +1272,24 @@ class OpenGLVMobject(OpenGLMobject):
self.refresh_triangulation()
return self
- def pointwise_become_partial(self, vmobject, a, b):
+ def pointwise_become_partial(
+ self,
+ vmobject: "OpenGLVMobject",
+ a: float,
+ b: float,
+ ) -> "OpenGLVMobject":
+ """Given two bounds a and b, transforms the points of the self vmobject into the points of the vmobject
+ passed as parameter with respect to the bounds. Points here stand for control points of the bezier curves (anchors and handles)
+
+ Parameters
+ ----------
+ vmobject : OpenGLVMobject
+ The vmobject that will serve as a model.
+ a : float
+ upper-bound.
+ b : float
+ lower-bound
+ """
assert isinstance(vmobject, OpenGLVMobject)
if a <= 0 and b >= 1:
self.become(vmobject)
@@ -1000,7 +1343,23 @@ class OpenGLVMobject(OpenGLMobject):
self.set_points(new_points)
return self
- def get_subcurve(self, a, b):
+ def get_subcurve(self, a: float, b: float) -> "OpenGLVMobject":
+ """Returns the subcurve of the OpenGLVMobject between the interval [a, b].
+ The curve is a OpenGLVMobject itself.
+
+ Parameters
+ ----------
+
+ a
+ The lower bound.
+ b
+ The upper bound.
+
+ Returns
+ -------
+ OpenGLVMobject
+ The subcurve between of [a, b]
+ """
vmob = self.copy()
vmob.pointwise_become_partial(self, a, b)
return vmob
@@ -1244,12 +1603,169 @@ class OpenGLVMobject(OpenGLMobject):
class OpenGLVGroup(OpenGLVMobject):
+ """A group of vectorized mobjects.
+
+ This can be used to group multiple :class:`~.OpenGLVMobject` instances together
+ in order to scale, move, ... them together.
+
+ Examples
+ --------
+
+ To add :class:`~.OpenGLVMobject`s to a :class:`~.OpenGLVGroup`, you can either use the
+ :meth:`~.OpenGLVGroup.add` method, or use the `+` and `+=` operators. Similarly, you
+ can subtract elements of a OpenGLVGroup via :meth:`~.OpenGLVGroup.remove` method, or
+ `-` and `-=` operators:
+
+ >>> from manim import Triangle, Square, OpenGLVGroup
+ >>> vg = OpenGLVGroup()
+ >>> triangle, square = Triangle(), Square()
+ >>> vg.add(triangle)
+ OpenGLVGroup(Triangle)
+ >>> vg + square # a new OpenGLVGroup is constructed
+ OpenGLVGroup(Triangle, Square)
+ >>> vg # not modified
+ OpenGLVGroup(Triangle)
+ >>> vg += square; vg # modifies vg
+ OpenGLVGroup(Triangle, Square)
+ >>> vg.remove(triangle)
+ OpenGLVGroup(Square)
+ >>> vg - square; # a new OpenGLVGroup is constructed
+ OpenGLVGroup()
+ >>> vg # not modified
+ OpenGLVGroup(Square)
+ >>> vg -= square; vg # modifies vg
+ OpenGLVGroup()
+
+ .. manim:: ArcShapeIris
+ :save_last_frame:
+
+ class ArcShapeIris(Scene):
+ def construct(self):
+ colors = [DARK_BROWN, BLUE_E, BLUE_D, BLUE_A, TEAL_B, GREEN_B, YELLOW_E]
+ radius = [1 + rad * 0.1 for rad in range(len(colors))]
+
+ circles_group = OpenGLVGroup()
+
+ # zip(radius, color) makes the iterator [(radius[i], color[i]) for i in range(radius)]
+ circles_group.add(*[Circle(radius=rad, stroke_width=10, color=col)
+ for rad, col in zip(radius, colors)])
+ self.add(circles_group)
+ """
+
def __init__(self, *vmobjects, **kwargs):
if not all([isinstance(m, OpenGLVMobject) for m in vmobjects]):
- raise Exception("All submobjects must be of type VMobject")
+ raise Exception("All submobjects must be of type OpenGLVMobject")
super().__init__(**kwargs)
self.add(*vmobjects)
+ def __repr__(self):
+ return (
+ self.__class__.__name__
+ + "("
+ + ", ".join(str(mob) for mob in self.submobjects)
+ + ")"
+ )
+
+ def __str__(self):
+ return (
+ f"{self.__class__.__name__} of {len(self.submobjects)} "
+ f"submobject{'s' if len(self.submobjects) > 0 else ''}"
+ )
+
+ def add(self, *vmobjects):
+ """Checks if all passed elements are an instance of OpenGLVMobject and then add them to submobjects
+
+ Parameters
+ ----------
+ vmobjects : :class:`~.OpenGLVMobject`
+ List of OpenGLVMobject to add
+
+ Returns
+ -------
+ :class:`OpenGLVGroup`
+
+ Raises
+ ------
+ TypeError
+ If one element of the list is not an instance of OpenGLVMobject
+
+ Examples
+ --------
+ .. manim:: AddToOpenGLVGroup
+
+ class AddToOpenGLVGroup(Scene):
+ def construct(self):
+ circle_red = Circle(color=RED)
+ circle_green = Circle(color=GREEN)
+ circle_blue = Circle(color=BLUE)
+ circle_red.shift(LEFT)
+ circle_blue.shift(RIGHT)
+ gr = OpenGLVGroup(circle_red, circle_green)
+ gr2 = OpenGLVGroup(circle_blue) # Constructor uses add directly
+ self.add(gr,gr2)
+ self.wait()
+ gr += gr2 # Add group to another
+ self.play(
+ gr.animate.shift(DOWN),
+ )
+ gr -= gr2 # Remove group
+ self.play( # Animate groups separately
+ gr.animate.shift(LEFT),
+ gr2.animate.shift(UP),
+ )
+ self.play( #Animate groups without modification
+ (gr+gr2).animate.shift(RIGHT)
+ )
+ self.play( # Animate group without component
+ (gr-circle_red).animate.shift(RIGHT)
+ )
+ """
+ if not all(isinstance(m, OpenGLVMobject) for m in vmobjects):
+ raise TypeError("All submobjects must be of type OpenGLVMobject")
+ return super().add(*vmobjects)
+
+ def __add__(self, vmobject):
+ return OpenGLVGroup(*self.submobjects, vmobject)
+
+ def __iadd__(self, vmobject):
+ return self.add(vmobject)
+
+ def __sub__(self, vmobject):
+ copy = OpenGLVGroup(*self.submobjects)
+ copy.remove(vmobject)
+ return copy
+
+ def __isub__(self, vmobject):
+ return self.remove(vmobject)
+
+ def __setitem__(
+ self, key: int, value: Union[OpenGLVMobject, Sequence[OpenGLVMobject]]
+ ):
+ """Override the [] operator for item assignment.
+
+ Parameters
+ ----------
+ key
+ The index of the submobject to be assigned
+ value
+ The vmobject value to assign to the key
+
+ Returns
+ -------
+ None
+
+ Examples
+ --------
+ Normal usage::
+
+ >>> vgroup = OpenGLVGroup(OpenGLVMobject())
+ >>> new_obj = OpenGLVMobject()
+ >>> vgroup[0] = new_obj
+ """
+ if not all(isinstance(m, OpenGLVMobject) for m in value):
+ raise TypeError("All submobjects must be of type OpenGLVMobject")
+ self.submobjects[key] = value
+
class OpenGLVectorizedPoint(OpenGLPoint, OpenGLVMobject):
def __init__(
@@ -1272,6 +1788,22 @@ class OpenGLVectorizedPoint(OpenGLPoint, OpenGLVMobject):
class OpenGLCurvesAsSubmobjects(OpenGLVGroup):
+ """Convert a curve's elements to submobjects.
+
+ Examples
+ --------
+ .. manim:: LineGradientExample
+ :save_last_frame:
+
+ class LineGradientExample(Scene):
+ def construct(self):
+ curve = ParametricFunction(lambda t: [t, np.sin(t), 0], t_range=[-PI, PI, 0.01], stroke_width=10)
+ new_curve = CurvesAsSubmobjects(curve)
+ new_curve.set_color_by_gradient(BLUE, RED)
+ self.add(new_curve.shift(UP), curve)
+
+ """
+
def __init__(self, vmobject, **kwargs):
super().__init__(**kwargs)
for tup in vmobject.get_bezier_tuples():
@@ -1282,8 +1814,47 @@ class OpenGLCurvesAsSubmobjects(OpenGLVGroup):
class OpenGLDashedVMobject(OpenGLVMobject):
+ """A :class:`OpenGLVMobject` composed of dashes instead of lines.
+
+ Examples
+ --------
+ .. manim:: DashedVMobjectExample
+ :save_last_frame:
+
+ class DashedVMobjectExample(Scene):
+ def construct(self):
+ r = 0.5
+
+ top_row = OpenGLVGroup() # Increasing num_dashes
+ for dashes in range(2, 12):
+ circ = DashedVMobject(Circle(radius=r, color=WHITE), num_dashes=dashes)
+ top_row.add(circ)
+
+ middle_row = OpenGLVGroup() # Increasing dashed_ratio
+ for ratio in np.arange(1 / 11, 1, 1 / 11):
+ circ = DashedVMobject(
+ Circle(radius=r, color=WHITE), dashed_ratio=ratio
+ )
+ middle_row.add(circ)
+
+ sq = DashedVMobject(Square(1.5, color=RED))
+ penta = DashedVMobject(RegularPolygon(5, color=BLUE))
+ bottom_row = OpenGLVGroup(sq, penta)
+
+ top_row.arrange(buff=0.4)
+ middle_row.arrange()
+ bottom_row.arrange(buff=1)
+ everything = OpenGLVGroup(top_row, middle_row, bottom_row).arrange(DOWN, buff=1)
+ self.add(everything)
+ """
+
def __init__(
- self, vmobject, num_dashes=15, dashed_ratio=0.5, color=WHITE, **kwargs
+ self,
+ vmobject: "OpenGLVMobject",
+ num_dashes: int = 15,
+ dashed_ratio: float = 0.5,
+ color: Color = WHITE,
+ **kwargs,
):
self.dashed_ratio = dashed_ratio
self.num_dashes = num_dashes