file_path
stringlengths 29
93
| content
stringlengths 0
117k
|
---|---|
manim_ManimCommunity/manim/mobject/geometry/shape_matchers.py
|
"""Mobjects used to mark and annotate other mobjects."""
from __future__ import annotations
__all__ = ["SurroundingRectangle", "BackgroundRectangle", "Cross", "Underline"]
from typing import Any
from typing_extensions import Self
from manim import config, logger
from manim.constants import *
from manim.mobject.geometry.line import Line
from manim.mobject.geometry.polygram import RoundedRectangle
from manim.mobject.mobject import Mobject
from manim.mobject.types.vectorized_mobject import VGroup
from manim.utils.color import BLACK, RED, YELLOW, ManimColor, ParsableManimColor
class SurroundingRectangle(RoundedRectangle):
r"""A rectangle surrounding a :class:`~.Mobject`
Examples
--------
.. manim:: SurroundingRectExample
:save_last_frame:
class SurroundingRectExample(Scene):
def construct(self):
title = Title("A Quote from Newton")
quote = Text(
"If I have seen further than others, \n"
"it is by standing upon the shoulders of giants.",
color=BLUE,
).scale(0.75)
box = SurroundingRectangle(quote, color=YELLOW, buff=MED_LARGE_BUFF)
t2 = Tex(r"Hello World").scale(1.5)
box2 = SurroundingRectangle(t2, corner_radius=0.2)
mobjects = VGroup(VGroup(box, quote), VGroup(t2, box2)).arrange(DOWN)
self.add(title, mobjects)
"""
def __init__(
self,
mobject: Mobject,
color: ParsableManimColor = YELLOW,
buff: float = SMALL_BUFF,
corner_radius: float = 0.0,
**kwargs,
) -> None:
super().__init__(
color=color,
width=mobject.width + 2 * buff,
height=mobject.height + 2 * buff,
corner_radius=corner_radius,
**kwargs,
)
self.buff = buff
self.move_to(mobject)
class BackgroundRectangle(SurroundingRectangle):
"""A background rectangle. Its default color is the background color
of the scene.
Examples
--------
.. manim:: ExampleBackgroundRectangle
:save_last_frame:
class ExampleBackgroundRectangle(Scene):
def construct(self):
circle = Circle().shift(LEFT)
circle.set_stroke(color=GREEN, width=20)
triangle = Triangle().shift(2 * RIGHT)
triangle.set_fill(PINK, opacity=0.5)
backgroundRectangle1 = BackgroundRectangle(circle, color=WHITE, fill_opacity=0.15)
backgroundRectangle2 = BackgroundRectangle(triangle, color=WHITE, fill_opacity=0.15)
self.add(backgroundRectangle1)
self.add(backgroundRectangle2)
self.add(circle)
self.add(triangle)
self.play(Rotate(backgroundRectangle1, PI / 4))
self.play(Rotate(backgroundRectangle2, PI / 2))
"""
def __init__(
self,
mobject: Mobject,
color: ParsableManimColor | None = 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,
stroke_width=stroke_width,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
buff=buff,
**kwargs,
)
self.original_fill_opacity: float = self.fill_opacity
def pointwise_become_partial(self, mobject: Mobject, a: Any, b: float) -> Self:
self.set_fill(opacity=b * self.original_fill_opacity)
return self
def set_style(self, fill_opacity: float, **kwargs) -> Self:
# Unchangeable style, except for fill_opacity
# All other style arguments are ignored
super().set_style(
stroke_color=BLACK,
stroke_width=0,
fill_color=BLACK,
fill_opacity=fill_opacity,
)
if len(kwargs) > 0:
logger.info(
"Argument %s is ignored in BackgroundRectangle.set_style.",
kwargs,
)
return self
def get_fill_color(self) -> ManimColor:
return self.color
class Cross(VGroup):
"""Creates a cross.
Parameters
----------
mobject
The mobject linked to this instance. It fits the mobject when specified. Defaults to None.
stroke_color
Specifies the color of the cross lines. Defaults to RED.
stroke_width
Specifies the width of the cross lines. Defaults to 6.
scale_factor
Scales the cross to the provided units. Defaults to 1.
Examples
--------
.. manim:: ExampleCross
:save_last_frame:
class ExampleCross(Scene):
def construct(self):
cross = Cross()
self.add(cross)
"""
def __init__(
self,
mobject: Mobject | None = None,
stroke_color: ParsableManimColor = RED,
stroke_width: float = 6.0,
scale_factor: float = 1.0,
**kwargs,
) -> None:
super().__init__(
Line(UP + LEFT, DOWN + RIGHT), Line(UP + RIGHT, DOWN + LEFT), **kwargs
)
if mobject is not None:
self.replace(mobject, stretch=True)
self.scale(scale_factor)
self.set_stroke(color=stroke_color, width=stroke_width)
class Underline(Line):
"""Creates an underline.
Examples
--------
.. manim:: UnderLine
:save_last_frame:
class UnderLine(Scene):
def construct(self):
man = Tex("Manim") # Full Word
ul = Underline(man) # Underlining the word
self.add(man, ul)
"""
def __init__(self, mobject: Mobject, buff: float = SMALL_BUFF, **kwargs) -> None:
super().__init__(LEFT, RIGHT, buff=buff, **kwargs)
self.match_width(mobject)
self.next_to(mobject, DOWN, buff=self.buff)
|
manim_ManimCommunity/manim/mobject/geometry/labeled.py
|
r"""Mobjects that inherit from lines and contain a label along the length."""
from __future__ import annotations
__all__ = ["LabeledLine", "LabeledArrow"]
from manim.constants import *
from manim.mobject.geometry.line import Arrow, Line
from manim.mobject.geometry.shape_matchers import (
BackgroundRectangle,
SurroundingRectangle,
)
from manim.mobject.text.tex_mobject import MathTex, Tex
from manim.mobject.text.text_mobject import Text
from manim.utils.color import WHITE, ManimColor, ParsableManimColor
class LabeledLine(Line):
"""Constructs a line containing a label box somewhere along its length.
Parameters
----------
label : str | Tex | MathTex | Text
Label that will be displayed on the line.
label_position : float | optional
A ratio in the range [0-1] to indicate the position of the label with respect to the length of the line. Default value is 0.5.
font_size : float | optional
Control font size for the label. This parameter is only used when `label` is of type `str`.
label_color: ParsableManimColor | optional
The color of the label's text. This parameter is only used when `label` is of type `str`.
label_frame : Bool | optional
Add a `SurroundingRectangle` frame to the label box.
frame_fill_color : ParsableManimColor | optional
Background color to fill the label box. If no value is provided, the background color of the canvas will be used.
frame_fill_opacity : float | optional
Determine the opacity of the label box by passing a value in the range [0-1], where 0 indicates complete transparency and 1 means full opacity.
.. seealso::
:class:`LabeledArrow`
Examples
--------
.. manim:: LabeledLineExample
:save_last_frame:
class LabeledLineExample(Scene):
def construct(self):
line = LabeledLine(
label = '0.5',
label_position = 0.8,
font_size = 20,
label_color = WHITE,
label_frame = True,
start=LEFT+DOWN,
end=RIGHT+UP)
line.set_length(line.get_length() * 2)
self.add(line)
"""
def __init__(
self,
label: str | Tex | MathTex | Text,
label_position: float = 0.5,
font_size: float = DEFAULT_FONT_SIZE,
label_color: ParsableManimColor = WHITE,
label_frame: bool = True,
frame_fill_color: ParsableManimColor = None,
frame_fill_opacity: float = 1,
*args,
**kwargs,
) -> None:
label_color = ManimColor(label_color)
frame_fill_color = ManimColor(frame_fill_color)
if isinstance(label, str):
from manim import MathTex
rendered_label = MathTex(label, color=label_color, font_size=font_size)
else:
rendered_label = label
super().__init__(*args, **kwargs)
# calculating the vector for the label position
line_start, line_end = self.get_start_and_end()
new_vec = (line_end - line_start) * label_position
label_coords = line_start + new_vec
# rendered_label.move_to(self.get_vector() * label_position)
rendered_label.move_to(label_coords)
box = BackgroundRectangle(
rendered_label,
buff=0.05,
color=frame_fill_color,
fill_opacity=frame_fill_opacity,
stroke_width=0.5,
)
self.add(box)
if label_frame:
box_frame = SurroundingRectangle(
rendered_label, buff=0.05, color=label_color, stroke_width=0.5
)
self.add(box_frame)
self.add(rendered_label)
class LabeledArrow(LabeledLine, Arrow):
"""Constructs an arrow containing a label box somewhere along its length.
This class inherits its label properties from `LabeledLine`, so the main parameters controlling it are the same.
Parameters
----------
label : str | Tex | MathTex | Text
Label that will be displayed on the line.
label_position : float | optional
A ratio in the range [0-1] to indicate the position of the label with respect to the length of the line. Default value is 0.5.
font_size : float | optional
Control font size for the label. This parameter is only used when `label` is of type `str`.
label_color: ParsableManimColor | optional
The color of the label's text. This parameter is only used when `label` is of type `str`.
label_frame : Bool | optional
Add a `SurroundingRectangle` frame to the label box.
frame_fill_color : ParsableManimColor | optional
Background color to fill the label box. If no value is provided, the background color of the canvas will be used.
frame_fill_opacity : float | optional
Determine the opacity of the label box by passing a value in the range [0-1], where 0 indicates complete transparency and 1 means full opacity.
.. seealso::
:class:`LabeledLine`
Examples
--------
.. manim:: LabeledArrowExample
:save_last_frame:
class LabeledArrowExample(Scene):
def construct(self):
l_arrow = LabeledArrow("0.5", start=LEFT*3, end=RIGHT*3 + UP*2, label_position=0.5)
self.add(l_arrow)
"""
def __init__(
self,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
|
manim_ManimCommunity/manim/mobject/types/__init__.py
|
"""Specialized mobject base classes.
Modules
=======
.. autosummary::
:toctree: ../reference
~image_mobject
~point_cloud_mobject
~vectorized_mobject
"""
|
manim_ManimCommunity/manim/mobject/types/image_mobject.py
|
"""Mobjects representing raster images."""
from __future__ import annotations
__all__ = ["AbstractImageMobject", "ImageMobject", "ImageMobjectFromCamera"]
import pathlib
import numpy as np
from PIL import Image
from PIL.Image import Resampling
from manim.mobject.geometry.shape_matchers import SurroundingRectangle
from ... import config
from ...constants import *
from ...mobject.mobject import Mobject
from ...utils.bezier import interpolate
from ...utils.color import WHITE, ManimColor, color_to_int_rgb
from ...utils.images import change_to_rgba_array, get_full_raster_image_path
__all__ = ["ImageMobject", "ImageMobjectFromCamera"]
class AbstractImageMobject(Mobject):
"""
Automatically filters out black pixels
Parameters
----------
scale_to_resolution
At this resolution the image is placed pixel by pixel onto the screen, so it
will look the sharpest and best.
This is a custom parameter of ImageMobject so that rendering a scene with
e.g. the ``--quality low`` or ``--quality medium`` flag for faster rendering
won't effect the position of the image on the screen.
"""
def __init__(
self,
scale_to_resolution: int,
pixel_array_dtype="uint8",
resampling_algorithm=Resampling.BICUBIC,
**kwargs,
):
self.pixel_array_dtype = pixel_array_dtype
self.scale_to_resolution = scale_to_resolution
self.set_resampling_algorithm(resampling_algorithm)
super().__init__(**kwargs)
def get_pixel_array(self):
raise NotImplementedError()
def set_color(self, color, alpha=None, family=True):
# Likely to be implemented in subclasses, but no obligation
pass
def set_resampling_algorithm(self, resampling_algorithm: int):
"""
Sets the interpolation method for upscaling the image. By default the image is
interpolated using bicubic algorithm. This method lets you change it.
Interpolation is done internally using Pillow, and the function besides the
string constants describing the algorithm accepts the Pillow integer constants.
Parameters
----------
resampling_algorithm
An integer constant described in the Pillow library,
or one from the RESAMPLING_ALGORITHMS global dictionary,
under the following keys:
* 'bicubic' or 'cubic'
* 'nearest' or 'none'
* 'box'
* 'bilinear' or 'linear'
* 'hamming'
* 'lanczos' or 'antialias'
"""
if isinstance(resampling_algorithm, int):
self.resampling_algorithm = resampling_algorithm
else:
raise ValueError(
"resampling_algorithm has to be an int, one of the values defined in "
"RESAMPLING_ALGORITHMS or a Pillow resampling filter constant. "
"Available algorithms: 'bicubic', 'nearest', 'box', 'bilinear', "
"'hamming', 'lanczos'.",
)
return self
def reset_points(self):
"""Sets :attr:`points` to be the four image corners."""
self.points = np.array(
[
UP + LEFT,
UP + RIGHT,
DOWN + LEFT,
DOWN + RIGHT,
],
)
self.center()
h, w = self.get_pixel_array().shape[:2]
if self.scale_to_resolution:
height = h / self.scale_to_resolution * config["frame_height"]
else:
height = 3 # this is the case for ImageMobjectFromCamera
self.stretch_to_fit_height(height)
self.stretch_to_fit_width(height * w / h)
class ImageMobject(AbstractImageMobject):
"""Displays an Image from a numpy array or a file.
Parameters
----------
scale_to_resolution
At this resolution the image is placed pixel by pixel onto the screen, so it
will look the sharpest and best.
This is a custom parameter of ImageMobject so that rendering a scene with
e.g. the ``--quality low`` or ``--quality medium`` flag for faster rendering
won't effect the position of the image on the screen.
Example
-------
.. manim:: ImageFromArray
:save_last_frame:
class ImageFromArray(Scene):
def construct(self):
image = ImageMobject(np.uint8([[0, 100, 30, 200],
[255, 0, 5, 33]]))
image.height = 7
self.add(image)
Changing interpolation style:
.. manim:: ImageInterpolationEx
:save_last_frame:
class ImageInterpolationEx(Scene):
def construct(self):
img = ImageMobject(np.uint8([[63, 0, 0, 0],
[0, 127, 0, 0],
[0, 0, 191, 0],
[0, 0, 0, 255]
]))
img.height = 2
img1 = img.copy()
img2 = img.copy()
img3 = img.copy()
img4 = img.copy()
img5 = img.copy()
img1.set_resampling_algorithm(RESAMPLING_ALGORITHMS["nearest"])
img2.set_resampling_algorithm(RESAMPLING_ALGORITHMS["lanczos"])
img3.set_resampling_algorithm(RESAMPLING_ALGORITHMS["linear"])
img4.set_resampling_algorithm(RESAMPLING_ALGORITHMS["cubic"])
img5.set_resampling_algorithm(RESAMPLING_ALGORITHMS["box"])
img1.add(Text("nearest").scale(0.5).next_to(img1,UP))
img2.add(Text("lanczos").scale(0.5).next_to(img2,UP))
img3.add(Text("linear").scale(0.5).next_to(img3,UP))
img4.add(Text("cubic").scale(0.5).next_to(img4,UP))
img5.add(Text("box").scale(0.5).next_to(img5,UP))
x= Group(img1,img2,img3,img4,img5)
x.arrange()
self.add(x)
"""
def __init__(
self,
filename_or_array,
scale_to_resolution: int = QUALITIES[DEFAULT_QUALITY]["pixel_height"],
invert=False,
image_mode="RGBA",
**kwargs,
):
self.fill_opacity = 1
self.stroke_opacity = 1
self.invert = invert
self.image_mode = image_mode
if isinstance(filename_or_array, (str, pathlib.PurePath)):
path = get_full_raster_image_path(filename_or_array)
image = Image.open(path).convert(self.image_mode)
self.pixel_array = np.array(image)
self.path = path
else:
self.pixel_array = np.array(filename_or_array)
self.pixel_array_dtype = kwargs.get("pixel_array_dtype", "uint8")
self.pixel_array = change_to_rgba_array(
self.pixel_array, self.pixel_array_dtype
)
if self.invert:
self.pixel_array[:, :, :3] = (
np.iinfo(self.pixel_array_dtype).max - self.pixel_array[:, :, :3]
)
super().__init__(scale_to_resolution, **kwargs)
def get_pixel_array(self):
"""A simple getter method."""
return self.pixel_array
def set_color(self, color, alpha=None, family=True):
rgb = color_to_int_rgb(color)
self.pixel_array[:, :, :3] = rgb
if alpha is not None:
self.pixel_array[:, :, 3] = int(255 * alpha)
for submob in self.submobjects:
submob.set_color(color, alpha, family)
self.color = color
return self
def set_opacity(self, alpha: float):
"""Sets the image's opacity.
Parameters
----------
alpha
The alpha value of the object, 1 being opaque and 0 being
transparent.
"""
self.pixel_array[:, :, 3] = int(255 * alpha)
self.fill_opacity = alpha
self.stroke_opacity = alpha
return self
def fade(self, darkness: float = 0.5, family: bool = True):
"""Sets the image's opacity using a 1 - alpha relationship.
Parameters
----------
darkness
The alpha value of the object, 1 being transparent and 0 being
opaque.
family
Whether the submobjects of the ImageMobject should be affected.
"""
self.set_opacity(1 - darkness)
super().fade(darkness, family)
return self
def interpolate_color(
self, mobject1: ImageMobject, mobject2: ImageMobject, alpha: float
):
"""Interpolates the array of pixel color values from one ImageMobject
into an array of equal size in the target ImageMobject.
Parameters
----------
mobject1
The ImageMobject to transform from.
mobject2
The ImageMobject to transform into.
alpha
Used to track the lerp relationship. Not opacity related.
"""
assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, (
f"Mobject pixel array shapes incompatible for interpolation.\n"
f"Mobject 1 ({mobject1}) : {mobject1.pixel_array.shape}\n"
f"Mobject 2 ({mobject2}) : {mobject2.pixel_array.shape}"
)
self.fill_opacity = interpolate(
mobject1.fill_opacity,
mobject2.fill_opacity,
alpha,
)
self.stroke_opacity = interpolate(
mobject1.stroke_opacity,
mobject2.stroke_opacity,
alpha,
)
self.pixel_array = interpolate(
mobject1.pixel_array,
mobject2.pixel_array,
alpha,
).astype(self.pixel_array_dtype)
def get_style(self):
return {
"fill_color": ManimColor(self.color.get_rgb()).to_hex(),
"fill_opacity": self.fill_opacity,
}
# TODO, add the ability to have the dimensions/orientation of this
# mobject more strongly tied to the frame of the camera it contains,
# in the case where that's a MovingCamera
class ImageMobjectFromCamera(AbstractImageMobject):
def __init__(self, camera, default_display_frame_config=None, **kwargs):
self.camera = camera
if default_display_frame_config is None:
default_display_frame_config = {
"stroke_width": 3,
"stroke_color": WHITE,
"buff": 0,
}
self.default_display_frame_config = default_display_frame_config
self.pixel_array = self.camera.pixel_array
super().__init__(scale_to_resolution=False, **kwargs)
# TODO: Get rid of this.
def get_pixel_array(self):
self.pixel_array = self.camera.pixel_array
return self.pixel_array
def add_display_frame(self, **kwargs):
config = dict(self.default_display_frame_config)
config.update(kwargs)
self.display_frame = SurroundingRectangle(self, **config)
self.add(self.display_frame)
return self
def interpolate_color(self, mobject1, mobject2, alpha):
assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, (
f"Mobject pixel array shapes incompatible for interpolation.\n"
f"Mobject 1 ({mobject1}) : {mobject1.pixel_array.shape}\n"
f"Mobject 2 ({mobject2}) : {mobject2.pixel_array.shape}"
)
self.pixel_array = interpolate(
mobject1.pixel_array,
mobject2.pixel_array,
alpha,
).astype(self.pixel_array_dtype)
|
manim_ManimCommunity/manim/mobject/types/vectorized_mobject.py
|
"""Mobjects that use vector graphics."""
from __future__ import annotations
__all__ = [
"VMobject",
"VGroup",
"VDict",
"VectorizedPoint",
"CurvesAsSubmobjects",
"DashedVMobject",
]
import itertools as it
import sys
from typing import (
TYPE_CHECKING,
Callable,
Generator,
Hashable,
Iterable,
Literal,
Mapping,
Sequence,
)
import numpy as np
import numpy.typing as npt
from PIL.Image import Image
from typing_extensions import Self
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject
from manim.mobject.three_d.three_d_utils import (
get_3d_vmob_gradient_start_and_end_points,
)
from ... import config
from ...constants import *
from ...mobject.mobject import Mobject
from ...utils.bezier import (
bezier,
get_smooth_handle_points,
integer_interpolate,
interpolate,
partial_bezier_points,
proportions_along_bezier_curve_for_point,
)
from ...utils.color import BLACK, WHITE, ManimColor, ParsableManimColor
from ...utils.iterables import make_even, resize_array, stretch_array_to_length, tuplify
from ...utils.space_ops import rotate_vector, shoelace_direction
if TYPE_CHECKING:
from manim.typing import (
BezierPoints,
CubicBezierPoints,
ManimFloat,
MappingFunction,
Point2D,
Point3D,
Point3D_Array,
QuadraticBezierPoints,
RGBA_Array_Float,
Vector3D,
Zeros,
)
# TODO
# - Change cubic curve groups to have 4 points instead of 3
# - Change sub_path idea accordingly
# - No more mark_paths_closed, instead have the camera test
# if last point in close to first point
# - Think about length of self.points. Always 0 or 1 mod 4?
# That's kind of weird.
__all__ = [
"VMobject",
"VGroup",
"VDict",
"VectorizedPoint",
"CurvesAsSubmobjects",
"VectorizedPoint",
"DashedVMobject",
]
class VMobject(Mobject):
"""A vectorized mobject.
Parameters
----------
background_stroke_color
The purpose of background stroke is to have something
that won't overlap fill, e.g. For text against some
textured background.
sheen_factor
When a color c is set, there will be a second color
computed based on interpolating c to WHITE by with
sheen_factor, and the display will gradient to this
secondary color in the direction of sheen_direction.
close_new_points
Indicates that it will not be displayed, but
that it should count in parent mobject's path
tolerance_for_point_equality
This is within a pixel
joint_type
The line joint type used to connect the curve segments
of this vectorized mobject. See :class:`.LineJointType`
for options.
"""
sheen_factor = 0.0
def __init__(
self,
fill_color: ParsableManimColor | None = None,
fill_opacity: float = 0.0,
stroke_color: ParsableManimColor | None = None,
stroke_opacity: float = 1.0,
stroke_width: float = DEFAULT_STROKE_WIDTH,
background_stroke_color: ParsableManimColor | None = BLACK,
background_stroke_opacity: float = 1.0,
background_stroke_width: float = 0,
sheen_factor: float = 0.0,
joint_type: LineJointType | None = None,
sheen_direction: Vector3D = UL,
close_new_points: bool = False,
pre_function_handle_to_anchor_scale_factor: float = 0.01,
make_smooth_after_applying_functions: bool = False,
background_image: Image | str | None = None,
shade_in_3d: bool = False,
# TODO, do we care about accounting for varying zoom levels?
tolerance_for_point_equality: float = 1e-6,
n_points_per_cubic_curve: int = 4,
cap_style: CapStyleType = CapStyleType.AUTO,
**kwargs,
):
self.fill_opacity = fill_opacity
self.stroke_opacity = stroke_opacity
self.stroke_width = stroke_width
if background_stroke_color is not None:
self.background_stroke_color: ManimColor = ManimColor(
background_stroke_color
)
self.background_stroke_opacity: float = background_stroke_opacity
self.background_stroke_width: float = background_stroke_width
self.sheen_factor: float = sheen_factor
self.joint_type: LineJointType = (
LineJointType.AUTO if joint_type is None else joint_type
)
self.sheen_direction: Vector3D = sheen_direction
self.close_new_points: bool = close_new_points
self.pre_function_handle_to_anchor_scale_factor: float = (
pre_function_handle_to_anchor_scale_factor
)
self.make_smooth_after_applying_functions: bool = (
make_smooth_after_applying_functions
)
self.background_image: Image | str | None = background_image
self.shade_in_3d: bool = shade_in_3d
self.tolerance_for_point_equality: float = tolerance_for_point_equality
self.n_points_per_cubic_curve: int = n_points_per_cubic_curve
self.cap_style: CapStyleType = cap_style
super().__init__(**kwargs)
self.submobjects: list[VMobject]
# TODO: Find where color overwrites are happening and remove the color doubling
# if "color" in kwargs:
# fill_color = kwargs["color"]
# stroke_color = kwargs["color"]
if fill_color is not None:
self.fill_color = ManimColor.parse(fill_color)
if stroke_color is not None:
self.stroke_color = ManimColor.parse(stroke_color)
# OpenGL compatibility
@property
def n_points_per_curve(self) -> int:
return self.n_points_per_cubic_curve
def get_group_class(self) -> type[VGroup]:
return VGroup
@staticmethod
def get_mobject_type_class() -> type[VMobject]:
return VMobject
# Colors
def init_colors(self, propagate_colors: bool = True) -> Self:
self.set_fill(
color=self.fill_color,
opacity=self.fill_opacity,
family=propagate_colors,
)
self.set_stroke(
color=self.stroke_color,
width=self.stroke_width,
opacity=self.stroke_opacity,
family=propagate_colors,
)
self.set_background_stroke(
color=self.background_stroke_color,
width=self.background_stroke_width,
opacity=self.background_stroke_opacity,
family=propagate_colors,
)
self.set_sheen(
factor=self.sheen_factor,
direction=self.sheen_direction,
family=propagate_colors,
)
if not propagate_colors:
for submobject in self.submobjects:
submobject.init_colors(propagate_colors=False)
return self
def generate_rgbas_array(
self, color: ManimColor | list[ManimColor], opacity: float | Iterable[float]
) -> RGBA_Array_Float:
"""
First arg can be either a color, or a tuple/list of colors.
Likewise, opacity can either be a float, or a tuple of floats.
If self.sheen_factor is not zero, and only
one color was passed in, a second slightly light color
will automatically be added for the gradient
"""
colors: list[ManimColor] = [
ManimColor(c) if (c is not None) else BLACK for c in tuplify(color)
]
opacities: list[float] = [
o if (o is not None) else 0.0 for o in tuplify(opacity)
]
rgbas: npt.NDArray[RGBA_Array_Float] = np.array(
[c.to_rgba_with_alpha(o) for c, o in zip(*make_even(colors, opacities))],
)
sheen_factor = self.get_sheen_factor()
if sheen_factor != 0 and len(rgbas) == 1:
light_rgbas = np.array(rgbas)
light_rgbas[:, :3] += sheen_factor
np.clip(light_rgbas, 0, 1, out=light_rgbas)
rgbas = np.append(rgbas, light_rgbas, axis=0)
return rgbas
def update_rgbas_array(
self,
array_name: str,
color: ManimColor | None = None,
opacity: float | None = None,
) -> Self:
rgbas = self.generate_rgbas_array(color, opacity)
if not hasattr(self, array_name):
setattr(self, array_name, rgbas)
return self
# Match up current rgbas array with the newly calculated
# one. 99% of the time they'll be the same.
curr_rgbas = getattr(self, array_name)
if len(curr_rgbas) < len(rgbas):
curr_rgbas = stretch_array_to_length(curr_rgbas, len(rgbas))
setattr(self, array_name, curr_rgbas)
elif len(rgbas) < len(curr_rgbas):
rgbas = stretch_array_to_length(rgbas, len(curr_rgbas))
# Only update rgb if color was not None, and only
# update alpha channel if opacity was passed in
if color is not None:
curr_rgbas[:, :3] = rgbas[:, :3]
if opacity is not None:
curr_rgbas[:, 3] = rgbas[:, 3]
return self
def set_fill(
self,
color: ParsableManimColor | None = None,
opacity: float | None = None,
family: bool = True,
) -> Self:
"""Set the fill color and fill opacity of a :class:`VMobject`.
Parameters
----------
color
Fill color of the :class:`VMobject`.
opacity
Fill opacity of the :class:`VMobject`.
family
If ``True``, the fill color of all submobjects is also set.
Returns
-------
:class:`VMobject`
``self``
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:`~.VMobject.set_style`
"""
if family:
for submobject in self.submobjects:
submobject.set_fill(color, opacity, family)
self.update_rgbas_array("fill_rgbas", color, opacity)
self.fill_rgbas: RGBA_Array_Float
if opacity is not None:
self.fill_opacity = opacity
return self
def set_stroke(
self,
color: ParsableManimColor = None,
width: float | None = None,
opacity: float | None = None,
background=False,
family: bool = True,
) -> Self:
if family:
for submobject in self.submobjects:
submobject.set_stroke(color, width, opacity, background, family)
if background:
array_name = "background_stroke_rgbas"
width_name = "background_stroke_width"
opacity_name = "background_stroke_opacity"
else:
array_name = "stroke_rgbas"
width_name = "stroke_width"
opacity_name = "stroke_opacity"
self.update_rgbas_array(array_name, color, opacity)
if width is not None:
setattr(self, width_name, width)
if opacity is not None:
setattr(self, opacity_name, opacity)
if color is not None and background:
if isinstance(color, (list, tuple)):
self.background_stroke_color = color
else:
self.background_stroke_color = ManimColor(color)
return self
def set_cap_style(self, cap_style: CapStyleType) -> Self:
"""
Sets the cap style of the :class:`VMobject`.
Parameters
----------
cap_style
The cap style to be set. See :class:`.CapStyleType` for options.
Returns
-------
:class:`VMobject`
``self``
Examples
--------
.. manim:: CapStyleExample
:save_last_frame:
class CapStyleExample(Scene):
def construct(self):
line = Line(LEFT, RIGHT, color=YELLOW, stroke_width=20)
line.set_cap_style(CapStyleType.ROUND)
self.add(line)
"""
self.cap_style = cap_style
return self
def set_background_stroke(self, **kwargs) -> Self:
kwargs["background"] = True
self.set_stroke(**kwargs)
return self
def set_style(
self,
fill_color: ParsableManimColor | None = None,
fill_opacity: float | None = None,
stroke_color: ParsableManimColor | None = None,
stroke_width: float | None = None,
stroke_opacity: float | None = None,
background_stroke_color: ParsableManimColor | None = None,
background_stroke_width: float | None = None,
background_stroke_opacity: float | None = None,
sheen_factor: float | None = None,
sheen_direction: Vector3D | None = None,
background_image: Image | str | None = None,
family: bool = True,
) -> Self:
self.set_fill(color=fill_color, opacity=fill_opacity, family=family)
self.set_stroke(
color=stroke_color,
width=stroke_width,
opacity=stroke_opacity,
family=family,
)
self.set_background_stroke(
color=background_stroke_color,
width=background_stroke_width,
opacity=background_stroke_opacity,
family=family,
)
if sheen_factor:
self.set_sheen(
factor=sheen_factor,
direction=sheen_direction,
family=family,
)
if background_image:
self.color_using_background_image(background_image)
return self
def get_style(self, simple: bool = False) -> dict:
ret = {
"stroke_opacity": self.get_stroke_opacity(),
"stroke_width": self.get_stroke_width(),
}
# TODO: FIX COLORS HERE
if simple:
ret["fill_color"] = self.get_fill_color()
ret["fill_opacity"] = self.get_fill_opacity()
ret["stroke_color"] = self.get_stroke_color()
else:
ret["fill_color"] = self.get_fill_colors()
ret["fill_opacity"] = self.get_fill_opacities()
ret["stroke_color"] = self.get_stroke_colors()
ret["background_stroke_color"] = self.get_stroke_colors(background=True)
ret["background_stroke_width"] = self.get_stroke_width(background=True)
ret["background_stroke_opacity"] = self.get_stroke_opacity(background=True)
ret["sheen_factor"] = self.get_sheen_factor()
ret["sheen_direction"] = self.get_sheen_direction()
ret["background_image"] = self.get_background_image()
return ret
def match_style(self, vmobject: VMobject, family: bool = True) -> Self:
self.set_style(**vmobject.get_style(), family=False)
if family:
# Does its best to match up submobject lists, and
# match styles accordingly
submobs1, submobs2 = self.submobjects, vmobject.submobjects
if len(submobs1) == 0:
return self
elif len(submobs2) == 0:
submobs2 = [vmobject]
for sm1, sm2 in zip(*make_even(submobs1, submobs2)):
sm1.match_style(sm2)
return self
def set_color(self, color: ParsableManimColor, family: bool = True) -> Self:
self.set_fill(color, family=family)
self.set_stroke(color, family=family)
return self
def set_opacity(self, opacity: float, family: bool = True) -> Self:
self.set_fill(opacity=opacity, family=family)
self.set_stroke(opacity=opacity, family=family)
self.set_stroke(opacity=opacity, family=family, background=True)
return self
def fade(self, darkness: float = 0.5, family: bool = True) -> Self:
factor = 1.0 - darkness
self.set_fill(opacity=factor * self.get_fill_opacity(), family=False)
self.set_stroke(opacity=factor * self.get_stroke_opacity(), family=False)
self.set_background_stroke(
opacity=factor * self.get_stroke_opacity(background=True),
family=False,
)
super().fade(darkness, family)
return self
def get_fill_rgbas(self) -> RGBA_Array_Float | Zeros:
try:
return self.fill_rgbas
except AttributeError:
return np.zeros((1, 4))
def get_fill_color(self) -> ManimColor:
"""
If there are multiple colors (for gradient)
this returns the first one
"""
return self.get_fill_colors()[0]
fill_color = property(get_fill_color, set_fill)
def get_fill_opacity(self) -> ManimFloat:
"""
If there are multiple opacities, this returns the
first
"""
return self.get_fill_opacities()[0]
# TODO: Does this just do a copy?
# TODO: I have the feeling that this function should not return None, does that have any usage ?
def get_fill_colors(self) -> list[ManimColor | None]:
return [
ManimColor(rgba[:3]) if rgba.any() else None
for rgba in self.get_fill_rgbas()
]
def get_fill_opacities(self) -> npt.NDArray[ManimFloat]:
return self.get_fill_rgbas()[:, 3]
def get_stroke_rgbas(self, background: bool = False) -> RGBA_Array_float | Zeros:
try:
if background:
self.background_stroke_rgbas: RGBA_Array_Float
rgbas = self.background_stroke_rgbas
else:
self.stroke_rgbas: RGBA_Array_Float
rgbas = self.stroke_rgbas
return rgbas
except AttributeError:
return np.zeros((1, 4))
def get_stroke_color(self, background: bool = False) -> ManimColor | None:
return self.get_stroke_colors(background)[0]
stroke_color = property(get_stroke_color, set_stroke)
def get_stroke_width(self, background: bool = False) -> float:
if background:
self.background_stroke_width: float
width = self.background_stroke_width
else:
width = self.stroke_width
if isinstance(width, str):
width = int(width)
return max(0.0, width)
def get_stroke_opacity(self, background: bool = False) -> ManimFloat:
return self.get_stroke_opacities(background)[0]
def get_stroke_colors(self, background: bool = False) -> list[ManimColor | None]:
return [
ManimColor(rgba[:3]) if rgba.any() else None
for rgba in self.get_stroke_rgbas(background)
]
def get_stroke_opacities(self, background: bool = False) -> npt.NDArray[ManimFloat]:
return self.get_stroke_rgbas(background)[:, 3]
def get_color(self) -> ManimColor:
if np.all(self.get_fill_opacities() == 0):
return self.get_stroke_color()
return self.get_fill_color()
color = property(get_color, set_color)
def set_sheen_direction(self, direction: Vector3D, family: bool = True) -> Self:
"""Sets the direction of the applied sheen.
Parameters
----------
direction
Direction from where the gradient is applied.
Examples
--------
Normal usage::
Circle().set_sheen_direction(UP)
See Also
--------
:meth:`~.VMobject.set_sheen`
:meth:`~.VMobject.rotate_sheen_direction`
"""
direction = np.array(direction)
if family:
for submob in self.get_family():
submob.sheen_direction = direction
else:
self.sheen_direction: Vector3D = direction
return self
def rotate_sheen_direction(
self, angle: float, axis: Vector3D = OUT, family: bool = True
) -> Self:
"""Rotates the direction of the applied sheen.
Parameters
----------
angle
Angle by which the direction of sheen is rotated.
axis
Axis of rotation.
Examples
--------
Normal usage::
Circle().set_sheen_direction(UP).rotate_sheen_direction(PI)
See Also
--------
:meth:`~.VMobject.set_sheen_direction`
"""
if family:
for submob in self.get_family():
submob.sheen_direction = rotate_vector(
submob.sheen_direction,
angle,
axis,
)
else:
self.sheen_direction = rotate_vector(self.sheen_direction, angle, axis)
return self
def set_sheen(
self, factor: float, direction: Vector3D | None = None, family: bool = True
) -> Self:
"""Applies a color gradient from a direction.
Parameters
----------
factor
The extent of lustre/gradient to apply. If negative, the gradient
starts from black, if positive the gradient starts from white and
changes to the current color.
direction
Direction from where the gradient is applied.
Examples
--------
.. manim:: SetSheen
:save_last_frame:
class SetSheen(Scene):
def construct(self):
circle = Circle(fill_opacity=1).set_sheen(-0.3, DR)
self.add(circle)
"""
if family:
for submob in self.submobjects:
submob.set_sheen(factor, direction, family)
self.sheen_factor: float = factor
if direction is not None:
# family set to false because recursion will
# already be handled above
self.set_sheen_direction(direction, family=False)
# Reset color to put sheen_factor into effect
if factor != 0:
self.set_stroke(self.get_stroke_color(), family=family)
self.set_fill(self.get_fill_color(), family=family)
return self
def get_sheen_direction(self) -> Vector3D:
return np.array(self.sheen_direction)
def get_sheen_factor(self) -> float:
return self.sheen_factor
def get_gradient_start_and_end_points(self) -> tuple[Point3D, Point3D]:
if self.shade_in_3d:
return get_3d_vmob_gradient_start_and_end_points(self)
else:
direction = self.get_sheen_direction()
c = self.get_center()
bases = np.array(
[self.get_edge_center(vect) - c for vect in [RIGHT, UP, OUT]],
).transpose()
offset = np.dot(bases, direction)
return (c - offset, c + offset)
def color_using_background_image(self, background_image: Image | str) -> Self:
self.background_image: Image | str = background_image
self.set_color(WHITE)
for submob in self.submobjects:
submob.color_using_background_image(background_image)
return self
def get_background_image(self) -> Image | str:
return self.background_image
def match_background_image(self, vmobject: VMobject) -> Self:
self.color_using_background_image(vmobject.get_background_image())
return self
def set_shade_in_3d(
self, value: bool = True, z_index_as_group: bool = False
) -> Self:
for submob in self.get_family():
submob.shade_in_3d = value
if z_index_as_group:
submob.z_index_group = self
return self
def set_points(self, points: Point3D_Array) -> Self:
self.points: Point3D_Array = np.array(points)
return self
def resize_points(
self,
new_length: int,
resize_func: Callable[[Point3D, int], Point3D] = resize_array,
) -> Self:
"""Resize the array of anchor points and handles to have
the specified size.
Parameters
----------
new_length
The new (total) number of points.
resize_func
A function mapping a Numpy array (the points) and an integer
(the target size) to a Numpy array. The default implementation
is based on Numpy's ``resize`` function.
"""
if new_length != len(self.points):
self.points = resize_func(self.points, new_length)
return self
def set_anchors_and_handles(
self,
anchors1: CubicBezierPoints,
handles1: CubicBezierPoints,
handles2: CubicBezierPoints,
anchors2: CubicBezierPoints,
) -> Self:
"""Given two sets of anchors and handles, process them to set them as anchors
and handles of the VMobject.
anchors1[i], handles1[i], handles2[i] and anchors2[i] define the i-th bezier
curve of the vmobject. There are four hardcoded parameters and this is a
problem as it makes the number of points per cubic curve unchangeable from 4
(two anchors and two handles).
Returns
-------
:class:`VMobject`
``self``
"""
assert len(anchors1) == len(handles1) == len(handles2) == len(anchors2)
nppcc = self.n_points_per_cubic_curve # 4
total_len = nppcc * len(anchors1)
self.points = np.zeros((total_len, self.dim))
# the following will, from the four sets, dispatch them in points such that
# self.points = [
# anchors1[0], handles1[0], handles2[0], anchors1[0], anchors1[1],
# handles1[1], ...
# ]
arrays = [anchors1, handles1, handles2, anchors2]
for index, array in enumerate(arrays):
self.points[index::nppcc] = array
return self
def clear_points(self) -> None:
self.points = np.zeros((0, self.dim))
def append_points(self, new_points: Point3D_Array) -> Self:
# TODO, check that number new points is a multiple of 4?
# or else that if len(self.points) % 4 == 1, then
# len(new_points) % 4 == 3?
self.points = np.append(self.points, new_points, axis=0)
return self
def start_new_path(self, point: Point3D) -> Self:
if len(self.points) % 4 != 0:
# close the open path by appending the last
# start anchor sufficiently often
last_anchor = self.get_start_anchors()[-1]
for _ in range(4 - (len(self.points) % 4)):
self.append_points([last_anchor])
self.append_points([point])
return self
def add_cubic_bezier_curve(
self,
anchor1: CubicBezierPoints,
handle1: CubicBezierPoints,
handle2: CubicBezierPoints,
anchor2: CubicBezierPoints,
) -> None:
# TODO, check the len(self.points) % 4 == 0?
self.append_points([anchor1, handle1, handle2, anchor2])
# what type is curves?
def add_cubic_bezier_curves(self, curves) -> None:
self.append_points(curves.flatten())
def add_cubic_bezier_curve_to(
self,
handle1: CubicBezierPoints,
handle2: CubicBezierPoints,
anchor: CubicBezierPoints,
) -> Self:
"""Add cubic bezier curve to the path.
NOTE : the first anchor is not a parameter as by default the end of the last sub-path!
Parameters
----------
handle1
first handle
handle2
second handle
anchor
anchor
Returns
-------
:class:`VMobject`
``self``
"""
self.throw_error_if_no_points()
new_points = [handle1, handle2, anchor]
if self.has_new_path_started():
self.append_points(new_points)
else:
self.append_points([self.get_last_point()] + new_points)
return self
def add_quadratic_bezier_curve_to(
self,
handle: QuadraticBezierPoints,
anchor: QuadraticBezierPoints,
) -> Self:
"""Add Quadratic bezier curve to the path.
Returns
-------
:class:`VMobject`
``self``
"""
# How does one approximate a quadratic with a cubic?
# refer to the Wikipedia page on Bezier curves
# https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Degree_elevation, accessed Jan 20, 2021
# 1. Copy the end points, and then
# 2. Place the 2 middle control points 2/3 along the line segments
# from the end points to the quadratic curve's middle control point.
# I think that's beautiful.
self.add_cubic_bezier_curve_to(
2 / 3 * handle + 1 / 3 * self.get_last_point(),
2 / 3 * handle + 1 / 3 * anchor,
anchor,
)
return self
def add_line_to(self, point: Point3D) -> Self:
"""Add a straight line from the last point of VMobject to the given point.
Parameters
----------
point
end of the straight line.
Returns
-------
:class:`VMobject`
``self``
"""
nppcc = self.n_points_per_cubic_curve
self.add_cubic_bezier_curve_to(
*(
interpolate(self.get_last_point(), point, a)
for a in np.linspace(0, 1, nppcc)[1:]
)
)
return self
def add_smooth_curve_to(self, *points: Point3D) -> Self:
"""Creates a smooth curve from given points and add it to the VMobject. If two points are passed in, the first is interpreted
as a handle, the second as an anchor.
Parameters
----------
points
Points (anchor and handle, or just anchor) to add a smooth curve from
Returns
-------
:class:`VMobject`
``self``
Raises
------
ValueError
If 0 or more than 2 points are given.
"""
# TODO remove the value error and just add two parameters with one optional
if len(points) == 1:
handle2 = None
new_anchor = points[0]
elif len(points) == 2:
handle2, new_anchor = points
else:
name = sys._getframe(0).f_code.co_name
raise ValueError(f"Only call {name} with 1 or 2 points")
if self.has_new_path_started():
self.add_line_to(new_anchor)
else:
self.throw_error_if_no_points()
last_h2, last_a2 = self.points[-2:]
last_tangent = last_a2 - last_h2
handle1 = last_a2 + last_tangent
if handle2 is None:
to_anchor_vect = new_anchor - last_a2
new_tangent = rotate_vector(last_tangent, PI, axis=to_anchor_vect)
handle2 = new_anchor - new_tangent
self.append_points([last_a2, handle1, handle2, new_anchor])
return self
def has_new_path_started(self) -> bool:
nppcc = self.n_points_per_cubic_curve # 4
# A new path starting is defined by a control point which is not part of a bezier subcurve.
return len(self.points) % nppcc == 1
def get_last_point(self) -> Point3D:
return self.points[-1]
def is_closed(self) -> bool:
# TODO use consider_points_equals_2d ?
return self.consider_points_equals(self.points[0], self.points[-1])
def close_path(self) -> None:
if not self.is_closed():
self.add_line_to(self.get_subpaths()[-1][0])
def add_points_as_corners(self, points: Iterable[Point3D]) -> Iterable[Point3D]:
for point in points:
self.add_line_to(point)
return points
def set_points_as_corners(self, points: Point3D_Array) -> Self:
"""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
Array of points that will be set as corners.
Returns
-------
:class:`VMobject`
``self``
"""
nppcc = self.n_points_per_cubic_curve
points = np.array(points)
# This will set the handles aligned with the anchors.
# Id est, a bezier curve will be the segment from the two anchors such that the handles belongs to this segment.
self.set_anchors_and_handles(
*(interpolate(points[:-1], points[1:], a) for a in np.linspace(0, 1, nppcc))
)
return self
def set_points_smoothly(self, points: Point3D_Array) -> Self:
self.set_points_as_corners(points)
self.make_smooth()
return self
def change_anchor_mode(self, mode: Literal["jagged", "smooth"]) -> Self:
"""Changes the anchor mode of the bezier curves. This will modify the handles.
There can be only two modes, "jagged", and "smooth".
Returns
-------
:class:`VMobject`
``self``
"""
assert mode in ["jagged", "smooth"], 'mode must be either "jagged" or "smooth"'
nppcc = self.n_points_per_cubic_curve
for submob in self.family_members_with_points():
subpaths = submob.get_subpaths()
submob.clear_points()
# A subpath can be composed of several bezier curves.
for subpath in subpaths:
# This will retrieve the anchors of the subpath, by selecting every n element in the array subpath
# The append is needed as the last element is not reached when slicing with numpy.
anchors = np.append(subpath[::nppcc], subpath[-1:], 0)
if mode == "smooth":
h1, h2 = get_smooth_handle_points(anchors)
else: # mode == "jagged"
# The following will make the handles aligned with the anchors, thus making the bezier curve a segment
a1 = anchors[:-1]
a2 = anchors[1:]
h1 = interpolate(a1, a2, 1.0 / 3)
h2 = interpolate(a1, a2, 2.0 / 3)
new_subpath = np.array(subpath)
new_subpath[1::nppcc] = h1
new_subpath[2::nppcc] = h2
submob.append_points(new_subpath)
return self
def make_smooth(self) -> Self:
return self.change_anchor_mode("smooth")
def make_jagged(self) -> Self:
return self.change_anchor_mode("jagged")
def add_subpath(self, points: Point3D_Array) -> Self:
assert len(points) % 4 == 0
self.points: Point3D_Array = np.append(self.points, points, axis=0)
return self
def append_vectorized_mobject(self, vectorized_mobject: VMobject) -> None:
new_points = list(vectorized_mobject.points)
if self.has_new_path_started():
# Remove last point, which is starting
# a new path
self.points = self.points[:-1]
self.append_points(new_points)
def apply_function(self, function: MappingFunction) -> Self:
factor = self.pre_function_handle_to_anchor_scale_factor
self.scale_handle_to_anchor_distances(factor)
super().apply_function(function)
self.scale_handle_to_anchor_distances(1.0 / factor)
if self.make_smooth_after_applying_functions:
self.make_smooth()
return self
def rotate(
self,
angle: float,
axis: Vector3D = OUT,
about_point: Point3D | None = None,
**kwargs,
) -> Self:
self.rotate_sheen_direction(angle, axis)
super().rotate(angle, axis, about_point, **kwargs)
return self
def scale_handle_to_anchor_distances(self, factor: float) -> Self:
"""If the distance between a given handle point H and its associated
anchor point A is d, then it changes H to be a distances factor*d
away from A, but so that the line from A to H doesn't change.
This is mostly useful in the context of applying a (differentiable)
function, to preserve tangency properties. One would pull all the
handles closer to their anchors, apply the function then push them out
again.
Parameters
----------
factor
The factor used for scaling.
Returns
-------
:class:`VMobject`
``self``
"""
for submob in self.family_members_with_points():
if len(submob.points) < self.n_points_per_cubic_curve:
# The case that a bezier quad is not complete (there is no bezier curve as there is not enough control points.)
continue
a1, h1, h2, a2 = submob.get_anchors_and_handles()
a1_to_h1 = h1 - a1
a2_to_h2 = h2 - a2
new_h1 = a1 + factor * a1_to_h1
new_h2 = a2 + factor * a2_to_h2
submob.set_anchors_and_handles(a1, new_h1, new_h2, a2)
return self
#
def consider_points_equals(self, p0: Point3D, p1: Point3D) -> bool:
return np.allclose(p0, p1, atol=self.tolerance_for_point_equality)
def consider_points_equals_2d(self, p0: Point2D, p1: Point2D) -> bool:
"""Determine if two points are close enough to be considered equal.
This uses the algorithm from np.isclose(), but expanded here for the
2D point case. NumPy is overkill for such a small question.
Parameters
----------
p0
first point
p1
second point
Returns
-------
bool
whether two points considered close.
"""
rtol = 1.0e-5 # default from np.isclose()
atol = self.tolerance_for_point_equality
if abs(p0[0] - p1[0]) > atol + rtol * abs(p1[0]):
return False
if abs(p0[1] - p1[1]) > atol + rtol * abs(p1[1]):
return False
return True
# Information about line
def get_cubic_bezier_tuples_from_points(
self, points: Point3D_Array
) -> npt.NDArray[Point3D_Array]:
return np.array(self.gen_cubic_bezier_tuples_from_points(points))
def gen_cubic_bezier_tuples_from_points(
self, points: Point3D_Array
) -> tuple[Point3D_Array]:
"""Returns the bezier tuples from an array of points.
self.points is a list of the anchors and handles of the bezier curves of the mobject (ie [anchor1, handle1, handle2, anchor2, anchor3 ..])
This algorithm basically retrieve them by taking an element every n, where n is the number of control points
of the bezier curve.
Parameters
----------
points
Points from which control points will be extracted.
Returns
-------
tuple
Bezier control points.
"""
nppcc = self.n_points_per_cubic_curve
remainder = len(points) % nppcc
points = points[: len(points) - remainder]
# Basically take every nppcc element.
return tuple(points[i : i + nppcc] for i in range(0, len(points), nppcc))
def get_cubic_bezier_tuples(self) -> npt.NDArray[Point3D_Array]:
return self.get_cubic_bezier_tuples_from_points(self.points)
def _gen_subpaths_from_points(
self,
points: Point3D_Array,
filter_func: Callable[[int], bool],
) -> Generator[Point3D_Array]:
"""Given an array of points defining the bezier curves of the vmobject, return subpaths formed by these points.
Here, Two bezier curves form a path if at least two of their anchors are evaluated True by the relation defined by filter_func.
The algorithm every bezier tuple (anchors and handles) in ``self.points`` (by regrouping each n elements, where
n is the number of points per cubic curve)), and evaluate the relation between two anchors with filter_func.
NOTE : The filter_func takes an int n as parameter, and will evaluate the relation between points[n] and points[n - 1]. This should probably be changed so
the function takes two points as parameters.
Parameters
----------
points
points defining the bezier curve.
filter_func
Filter-func defining the relation.
Returns
-------
Generator[Point3D_Array]
subpaths formed by the points.
"""
nppcc = self.n_points_per_cubic_curve
filtered = filter(filter_func, range(nppcc, len(points), nppcc))
split_indices = [0] + list(filtered) + [len(points)]
return (
points[i1:i2]
for i1, i2 in zip(split_indices, split_indices[1:])
if (i2 - i1) >= nppcc
)
def get_subpaths_from_points(self, points: Point3D_Array) -> list[Point3D_Array]:
return list(
self._gen_subpaths_from_points(
points,
lambda n: not self.consider_points_equals(points[n - 1], points[n]),
),
)
def gen_subpaths_from_points_2d(
self, points: Point3D_Array
) -> Generator[Point3D_Array]:
return self._gen_subpaths_from_points(
points,
lambda n: not self.consider_points_equals_2d(points[n - 1], points[n]),
)
def get_subpaths(self) -> list[Point3D_Array]:
"""Returns subpaths formed by the curves of the VMobject.
Subpaths are ranges of curves with each pair of consecutive curves having their end/start points coincident.
Returns
-------
list[Point3D_Array]
subpaths.
"""
return self.get_subpaths_from_points(self.points)
def get_nth_curve_points(self, n: int) -> Point3D_Array:
"""Returns the points defining the nth curve of the vmobject.
Parameters
----------
n
index of the desired bezier curve.
Returns
-------
Point3D_Array
points defining the nth bezier curve (anchors, handles)
"""
assert n < self.get_num_curves()
nppcc = self.n_points_per_cubic_curve
return self.points[nppcc * n : nppcc * (n + 1)]
def get_nth_curve_function(self, n: int) -> Callable[[float], Point3D]:
"""Returns the expression of the nth curve.
Parameters
----------
n
index of the desired curve.
Returns
-------
Callable[float, Point3D]
expression of the nth bezier curve.
"""
return bezier(self.get_nth_curve_points(n))
def get_nth_curve_length_pieces(
self,
n: int,
sample_points: int | None = None,
) -> npt.NDArray[ManimFloat]:
"""Returns the array of short line lengths used for length approximation.
Parameters
----------
n
The index of the desired curve.
sample_points
The number of points to sample to find the length.
Returns
-------
The short length-pieces 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.linalg.norm(diffs, axis=1)
return norms
def get_nth_curve_length(
self,
n: int,
sample_points: int | None = 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: int | None = None,
) -> tuple[Callable[[float], Point3D], 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 : Callable[[float], Point3D]
The function for the nth curve.
length : :class:`float`
The length of the nth curve.
"""
curve = self.get_nth_curve_function(n)
norms = self.get_nth_curve_length_pieces(n, sample_points=sample_points)
length = np.sum(norms)
return curve, length
def get_num_curves(self) -> int:
"""Returns the number of curves of the vmobject.
Returns
-------
int
number of curves of the vmobject.
"""
nppcc = self.n_points_per_cubic_curve
return len(self.points) // nppcc
def get_curve_functions(
self,
) -> Generator[Callable[[float], Point3D]]:
"""Gets the functions for the curves of the mobject.
Returns
-------
Generator[Callable[[float], Point3D]]
The functions for the curves.
"""
num_curves = self.get_num_curves()
for n in range(num_curves):
yield self.get_nth_curve_function(n)
def get_curve_functions_with_lengths(
self, **kwargs
) -> Generator[tuple[Callable[[float], Point3D], float]]:
"""Gets the functions and lengths of the curves for the mobject.
Parameters
----------
**kwargs
The keyword arguments passed to :meth:`get_nth_curve_function_with_length`
Returns
-------
Generator[tuple[Callable[[float], Point3D], float]]
The functions and lengths of the curves.
"""
num_curves = self.get_num_curves()
for n in range(num_curves):
yield self.get_nth_curve_function_with_length(n, **kwargs)
def point_from_proportion(self, alpha: float) -> Point3D:
"""Gets the point at a proportion along the path of the :class:`VMobject`.
Parameters
----------
alpha
The proportion along the the path of the :class:`VMobject`.
Returns
-------
:class:`numpy.ndarray`
The point on the :class:`VMobject`.
Raises
------
:exc:`ValueError`
If ``alpha`` is not between 0 and 1.
:exc:`Exception`
If the :class:`VMobject` has no points.
"""
if alpha < 0 or alpha > 1:
raise ValueError(f"Alpha {alpha} not between 0 and 1.")
self.throw_error_if_no_points()
if alpha == 1:
return self.points[-1]
curves_and_lengths = tuple(self.get_curve_functions_with_lengths())
target_length = alpha * sum(length for _, length in curves_and_lengths)
current_length = 0
for curve, length in curves_and_lengths:
if current_length + length >= target_length:
if length != 0:
residue = (target_length - current_length) / length
else:
residue = 0
return curve(residue)
current_length += length
def proportion_from_point(
self,
point: Iterable[float | int],
) -> float:
"""Returns the proportion along the path of the :class:`VMobject`
a particular given point is at.
Parameters
----------
point
The Cartesian coordinates of the point which may or may not lie on the :class:`VMobject`
Returns
-------
float
The proportion along the path of the :class:`VMobject`.
Raises
------
:exc:`ValueError`
If ``point`` does not lie on the curve.
:exc:`Exception`
If the :class:`VMobject` 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) -> list[Point3D_Array]:
"""Returns anchors1, handles1, handles2, anchors2,
where (anchors1[i], handles1[i], handles2[i], anchors2[i])
will be four points defining a cubic bezier curve
for any i in range(0, len(anchors1))
Returns
-------
`list[Point3D_Array]`
Iterable of the anchors and handles.
"""
nppcc = self.n_points_per_cubic_curve
return [self.points[i::nppcc] for i in range(nppcc)]
def get_start_anchors(self) -> Point3D_Array:
"""Returns the start anchors of the bezier curves.
Returns
-------
Point3D_Array
Starting anchors
"""
return self.points[:: self.n_points_per_cubic_curve]
def get_end_anchors(self) -> Point3D_Array:
"""Return the end anchors of the bezier curves.
Returns
-------
Point3D_Array
Starting anchors
"""
nppcc = self.n_points_per_cubic_curve
return self.points[nppcc - 1 :: nppcc]
def get_anchors(self) -> Point3D_Array:
"""Returns the anchors of the curves forming the VMobject.
Returns
-------
Point3D_Array
The anchors.
"""
if self.points.shape[0] == 1:
return self.points
return np.array(
tuple(it.chain(*zip(self.get_start_anchors(), self.get_end_anchors()))),
)
def get_points_defining_boundary(self) -> Point3D_Array:
# Probably returns all anchors, but this is weird regarding the name of the method.
return np.array(
tuple(it.chain(*(sm.get_anchors() for sm in self.get_family())))
)
def get_arc_length(self, sample_points_per_curve: int | None = None) -> float:
"""Return the approximated length of the whole curve.
Parameters
----------
sample_points_per_curve
Number of sample points per curve used to approximate the length. More points result in a better approximation.
Returns
-------
float
The length of the :class:`VMobject`.
"""
return sum(
length
for _, length in self.get_curve_functions_with_lengths(
sample_points=sample_points_per_curve,
)
)
# Alignment
def align_points(self, vmobject: VMobject) -> Self:
"""Adds points to self and vmobject so that they both have the same number of subpaths, with
corresponding subpaths each containing the same number of points.
Points are added either by subdividing curves evenly along the subpath, or by creating new subpaths consisting
of a single point repeated.
Parameters
----------
vmobject
The object to align points with.
Returns
-------
:class:`VMobject`
``self``
"""
self.align_rgbas(vmobject)
# TODO: This shortcut can be a bit over eager. What if they have the same length, but different subpath lengths?
if self.get_num_points() == vmobject.get_num_points():
return
for mob in self, vmobject:
# If there are no points, add one to
# wherever the "center" is
if mob.has_no_points():
mob.start_new_path(mob.get_center())
# If there's only one point, turn it into
# a null curve
if mob.has_new_path_started():
mob.add_line_to(mob.get_last_point())
# Figure out what the subpaths are
subpaths1 = self.get_subpaths()
subpaths2 = vmobject.get_subpaths()
n_subpaths = max(len(subpaths1), len(subpaths2))
# Start building new ones
new_path1 = np.zeros((0, self.dim))
new_path2 = np.zeros((0, self.dim))
nppcc = self.n_points_per_cubic_curve
def get_nth_subpath(path_list, n):
if n >= len(path_list):
# Create a null path at the very end
return [path_list[-1][-1]] * nppcc
path = path_list[n]
# Check for useless points at the end of the path and remove them
# https://github.com/ManimCommunity/manim/issues/1959
while len(path) > nppcc:
# If the last nppc points are all equal to the preceding point
if self.consider_points_equals(path[-nppcc:], path[-nppcc - 1]):
path = path[:-nppcc]
else:
break
return path
for n in range(n_subpaths):
# For each pair of subpaths, add points until they are the same length
sp1 = get_nth_subpath(subpaths1, n)
sp2 = get_nth_subpath(subpaths2, n)
diff1 = max(0, (len(sp2) - len(sp1)) // nppcc)
diff2 = max(0, (len(sp1) - len(sp2)) // nppcc)
sp1 = self.insert_n_curves_to_point_list(diff1, sp1)
sp2 = self.insert_n_curves_to_point_list(diff2, sp2)
new_path1 = np.append(new_path1, sp1, axis=0)
new_path2 = np.append(new_path2, sp2, axis=0)
self.set_points(new_path1)
vmobject.set_points(new_path2)
return self
def insert_n_curves(self, n: int) -> Self:
"""Inserts n curves to the bezier curves of the vmobject.
Parameters
----------
n
Number of curves to insert.
Returns
-------
:class:`VMobject`
``self``
"""
new_path_point = None
if self.has_new_path_started():
new_path_point = self.get_last_point()
new_points = self.insert_n_curves_to_point_list(n, self.points)
self.set_points(new_points)
if new_path_point is not None:
self.append_points([new_path_point])
return self
def insert_n_curves_to_point_list(
self, n: int, points: Point3D_Array
) -> npt.NDArray[BezierPoints]:
"""Given an array of k points defining a bezier curves (anchors and handles), returns points defining exactly k + n bezier curves.
Parameters
----------
n
Number of desired curves.
points
Starting points.
Returns
-------
Points generated.
"""
if len(points) == 1:
nppcc = self.n_points_per_cubic_curve
return np.repeat(points, nppcc * n, 0)
bezier_quads = self.get_cubic_bezier_tuples_from_points(points)
curr_num = len(bezier_quads)
target_num = curr_num + n
# This is an array with values ranging from 0
# up to curr_num, with repeats such that
# it's total length is target_num. For example,
# with curr_num = 10, target_num = 15, this would
# be [0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
repeat_indices = (np.arange(target_num, dtype="i") * curr_num) // target_num
# If the nth term of this list is k, it means
# that the nth curve of our path should be split
# into k pieces.
# In the above example our array had the following elements
# [0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
# We have two 0s, one 1, two 2s and so on.
# The split factors array would hence be:
# [2, 1, 2, 1, 2, 1, 2, 1, 2, 1]
split_factors = np.zeros(curr_num, dtype="i")
for val in repeat_indices:
split_factors[val] += 1
new_points = np.zeros((0, self.dim))
for quad, sf in zip(bezier_quads, split_factors):
# What was once a single cubic curve defined
# by "quad" will now be broken into sf
# smaller cubic curves
alphas = np.linspace(0, 1, sf + 1)
for a1, a2 in zip(alphas, alphas[1:]):
new_points = np.append(
new_points,
partial_bezier_points(quad, a1, a2),
axis=0,
)
return new_points
def align_rgbas(self, vmobject: VMobject) -> Self:
attrs = ["fill_rgbas", "stroke_rgbas", "background_stroke_rgbas"]
for attr in attrs:
a1 = getattr(self, attr)
a2 = getattr(vmobject, attr)
if len(a1) > len(a2):
new_a2 = stretch_array_to_length(a2, len(a1))
setattr(vmobject, attr, new_a2)
elif len(a2) > len(a1):
new_a1 = stretch_array_to_length(a1, len(a2))
setattr(self, attr, new_a1)
return self
def get_point_mobject(self, center: Point3D | None = None) -> VectorizedPoint:
if center is None:
center = self.get_center()
point = VectorizedPoint(center)
point.match_style(self)
return point
def interpolate_color(
self, mobject1: VMobject, mobject2: VMobject, alpha: float
) -> None:
attrs = [
"fill_rgbas",
"stroke_rgbas",
"background_stroke_rgbas",
"stroke_width",
"background_stroke_width",
"sheen_direction",
"sheen_factor",
]
for attr in attrs:
setattr(
self,
attr,
interpolate(getattr(mobject1, attr), getattr(mobject2, attr), alpha),
)
if alpha == 1.0:
setattr(self, attr, getattr(mobject2, attr))
def pointwise_become_partial(
self,
vmobject: VMobject,
a: float,
b: float,
) -> Self:
"""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
The vmobject that will serve as a model.
a
upper-bound.
b
lower-bound
Returns
-------
:class:`VMobject`
``self``
"""
assert isinstance(vmobject, VMobject)
# Partial curve includes three portions:
# - A middle section, which matches the curve exactly
# - A start, which is some ending portion of an inner cubic
# - An end, which is the starting portion of a later inner cubic
if a <= 0 and b >= 1:
self.set_points(vmobject.points)
return self
bezier_quads = vmobject.get_cubic_bezier_tuples()
num_cubics = len(bezier_quads)
# The following two lines will compute which bezier curves of the given mobject need to be processed.
# The residue basically indicates de proportion of the selected bezier curve that have to be selected.
# Ex : if lower_index is 3, and lower_residue is 0.4, then the algorithm will append to the points 0.4 of the third bezier curve
lower_index, lower_residue = integer_interpolate(0, num_cubics, a)
upper_index, upper_residue = integer_interpolate(0, num_cubics, b)
self.clear_points()
if num_cubics == 0:
return self
if lower_index == upper_index:
self.append_points(
partial_bezier_points(
bezier_quads[lower_index],
lower_residue,
upper_residue,
),
)
else:
self.append_points(
partial_bezier_points(bezier_quads[lower_index], lower_residue, 1),
)
for quad in bezier_quads[lower_index + 1 : upper_index]:
self.append_points(quad)
self.append_points(
partial_bezier_points(bezier_quads[upper_index], 0, upper_residue),
)
return self
def get_subcurve(self, a: float, b: float) -> Self:
"""Returns the subcurve of the VMobject between the interval [a, b].
The curve is a VMobject itself.
Parameters
----------
a
The lower bound.
b
The upper bound.
Returns
-------
VMobject
The subcurve between of [a, b]
"""
if self.is_closed() and a > b:
vmob = self.copy()
vmob.pointwise_become_partial(self, a, 1)
vmob2 = self.copy()
vmob2.pointwise_become_partial(self, 0, b)
vmob.append_vectorized_mobject(vmob2)
else:
vmob = self.copy()
vmob.pointwise_become_partial(self, a, b)
return vmob
def get_direction(self) -> Literal["CW", "CCW"]:
"""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 reverse_direction(self) -> Self:
"""Reverts the point direction by inverting the point order.
Returns
-------
:class:`VMobject`
Returns self.
Examples
--------
.. manim:: ChangeOfDirection
class ChangeOfDirection(Scene):
def construct(self):
ccw = RegularPolygon(5)
ccw.shift(LEFT)
cw = RegularPolygon(5)
cw.shift(RIGHT).reverse_direction()
self.play(Create(ccw), Create(cw),
run_time=4)
"""
self.points = self.points[::-1]
return self
def force_direction(self, target_direction: Literal["CW", "CCW"]) -> Self:
"""Makes sure that points are either directed clockwise or
counterclockwise.
Parameters
----------
target_direction
Either ``"CW"`` or ``"CCW"``.
"""
if target_direction not in ("CW", "CCW"):
raise ValueError('Invalid input for force_direction. Use "CW" or "CCW"')
if self.get_direction() != target_direction:
# Since we already assured the input is CW or CCW,
# and the directions don't match, we just reverse
self.reverse_direction()
return self
class VGroup(VMobject, metaclass=ConvertToOpenGL):
"""A group of vectorized mobjects.
This can be used to group multiple :class:`~.VMobject` instances together
in order to scale, move, ... them together.
Notes
-----
When adding the same mobject more than once, repetitions are ignored.
Use :meth:`.Mobject.copy` to create a separate copy which can then
be added to the group.
Examples
--------
To add :class:`~.VMobject`s to a :class:`~.VGroup`, you can either use the
:meth:`~.VGroup.add` method, or use the `+` and `+=` operators. Similarly, you
can subtract elements of a VGroup via :meth:`~.VGroup.remove` method, or
`-` and `-=` operators:
>>> from manim import Triangle, Square, VGroup
>>> vg = VGroup()
>>> triangle, square = Triangle(), Square()
>>> vg.add(triangle)
VGroup(Triangle)
>>> vg + square # a new VGroup is constructed
VGroup(Triangle, Square)
>>> vg # not modified
VGroup(Triangle)
>>> vg += square; vg # modifies vg
VGroup(Triangle, Square)
>>> vg.remove(triangle)
VGroup(Square)
>>> vg - square; # a new VGroup is constructed
VGroup()
>>> vg # not modified
VGroup(Square)
>>> vg -= square; vg # modifies vg
VGroup()
.. 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 = VGroup()
# 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):
super().__init__(**kwargs)
self.add(*vmobjects)
def __repr__(self) -> str:
return f'{self.__class__.__name__}({", ".join(str(mob) for mob in self.submobjects)})'
def __str__(self) -> str:
return (
f"{self.__class__.__name__} of {len(self.submobjects)} "
f"submobject{'s' if len(self.submobjects) > 0 else ''}"
)
def add(self, *vmobjects: VMobject) -> Self:
"""Checks if all passed elements are an instance of VMobject and then add them to submobjects
Parameters
----------
vmobjects
List of VMobject to add
Returns
-------
:class:`VGroup`
Raises
------
TypeError
If one element of the list is not an instance of VMobject
Examples
--------
.. manim:: AddToVGroup
class AddToVGroup(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 = VGroup(circle_red, circle_green)
gr2 = VGroup(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)
)
"""
for m in vmobjects:
if not isinstance(m, (VMobject, OpenGLVMobject)):
raise TypeError(
f"All submobjects of {self.__class__.__name__} must be of type VMobject. "
f"Got {repr(m)} ({type(m).__name__}) instead. "
"You can try using `Group` instead."
)
return super().add(*vmobjects)
def __add__(self, vmobject: VMobject) -> Self:
return VGroup(*self.submobjects, vmobject)
def __iadd__(self, vmobject: VMobject) -> Self:
return self.add(vmobject)
def __sub__(self, vmobject: VMobject) -> Self:
copy = VGroup(*self.submobjects)
copy.remove(vmobject)
return copy
def __isub__(self, vmobject: VMobject) -> Self:
return self.remove(vmobject)
def __setitem__(self, key: int, value: VMobject | Sequence[VMobject]) -> None:
"""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
Tests
-----
Check that item assignment does not raise error::
>>> vgroup = VGroup(VMobject())
>>> new_obj = VMobject()
>>> vgroup[0] = new_obj
"""
if not all(isinstance(m, (VMobject, OpenGLVMobject)) for m in value):
raise TypeError("All submobjects must be of type VMobject")
self.submobjects[key] = value
class VDict(VMobject, metaclass=ConvertToOpenGL):
"""A VGroup-like class, also offering submobject access by
key, like a python dict
Parameters
----------
mapping_or_iterable
The parameter specifying the key-value mapping of keys and mobjects.
show_keys
Whether to also display the key associated with
the mobject. This might be useful when debugging,
especially when there are a lot of mobjects in the
:class:`VDict`. Defaults to False.
kwargs
Other arguments to be passed to `Mobject`.
Attributes
----------
show_keys : :class:`bool`
Whether to also display the key associated with
the mobject. This might be useful when debugging,
especially when there are a lot of mobjects in the
:class:`VDict`. When displayed, the key is towards
the left of the mobject.
Defaults to False.
submob_dict : :class:`dict`
Is the actual python dictionary that is used to bind
the keys to the mobjects.
Examples
--------
.. manim:: ShapesWithVDict
class ShapesWithVDict(Scene):
def construct(self):
square = Square().set_color(RED)
circle = Circle().set_color(YELLOW).next_to(square, UP)
# create dict from list of tuples each having key-mobject pair
pairs = [("s", square), ("c", circle)]
my_dict = VDict(pairs, show_keys=True)
# display it just like a VGroup
self.play(Create(my_dict))
self.wait()
text = Tex("Some text").set_color(GREEN).next_to(square, DOWN)
# add a key-value pair by wrapping it in a single-element list of tuple
# after attrs branch is merged, it will be easier like `.add(t=text)`
my_dict.add([("t", text)])
self.wait()
rect = Rectangle().next_to(text, DOWN)
# can also do key assignment like a python dict
my_dict["r"] = rect
# access submobjects like a python dict
my_dict["t"].set_color(PURPLE)
self.play(my_dict["t"].animate.scale(3))
self.wait()
# also supports python dict styled reassignment
my_dict["t"] = Tex("Some other text").set_color(BLUE)
self.wait()
# remove submobject by key
my_dict.remove("t")
self.wait()
self.play(Uncreate(my_dict["s"]))
self.wait()
self.play(FadeOut(my_dict["c"]))
self.wait()
self.play(FadeOut(my_dict["r"], shift=DOWN))
self.wait()
# you can also make a VDict from an existing dict of mobjects
plain_dict = {
1: Integer(1).shift(DOWN),
2: Integer(2).shift(2 * DOWN),
3: Integer(3).shift(3 * DOWN),
}
vdict_from_plain_dict = VDict(plain_dict)
vdict_from_plain_dict.shift(1.5 * (UP + LEFT))
self.play(Create(vdict_from_plain_dict))
# you can even use zip
vdict_using_zip = VDict(zip(["s", "c", "r"], [Square(), Circle(), Rectangle()]))
vdict_using_zip.shift(1.5 * RIGHT)
self.play(Create(vdict_using_zip))
self.wait()
"""
def __init__(
self,
mapping_or_iterable: (
Mapping[Hashable, VMobject] | Iterable[tuple[Hashable, VMobject]]
) = {},
show_keys: bool = False,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.show_keys = show_keys
self.submob_dict = {}
self.add(mapping_or_iterable)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({repr(self.submob_dict)})"
def add(
self,
mapping_or_iterable: (
Mapping[Hashable, VMobject] | Iterable[tuple[Hashable, VMobject]]
),
) -> Self:
"""Adds the key-value pairs to the :class:`VDict` object.
Also, it internally adds the value to the `submobjects` :class:`list`
of :class:`~.Mobject`, which is responsible for actual on-screen display.
Parameters
---------
mapping_or_iterable
The parameter specifying the key-value mapping of keys and mobjects.
Returns
-------
:class:`VDict`
Returns the :class:`VDict` object on which this method was called.
Examples
--------
Normal usage::
square_obj = Square()
my_dict.add([('s', square_obj)])
"""
for key, value in dict(mapping_or_iterable).items():
self.add_key_value_pair(key, value)
return self
def remove(self, key: Hashable) -> Self:
"""Removes the mobject from the :class:`VDict` object having the key `key`
Also, it internally removes the mobject from the `submobjects` :class:`list`
of :class:`~.Mobject`, (which is responsible for removing it from the screen)
Parameters
----------
key
The key of the submoject to be removed.
Returns
-------
:class:`VDict`
Returns the :class:`VDict` object on which this method was called.
Examples
--------
Normal usage::
my_dict.remove('square')
"""
if key not in self.submob_dict:
raise KeyError("The given key '%s' is not present in the VDict" % str(key))
super().remove(self.submob_dict[key])
del self.submob_dict[key]
return self
def __getitem__(self, key: Hashable):
"""Override the [] operator for item retrieval.
Parameters
----------
key
The key of the submoject to be accessed
Returns
-------
:class:`VMobject`
The submobject corresponding to the key `key`
Examples
--------
Normal usage::
self.play(Create(my_dict['s']))
"""
submob = self.submob_dict[key]
return submob
def __setitem__(self, key: Hashable, value: VMobject) -> None:
"""Override the [] operator for item assignment.
Parameters
----------
key
The key of the submoject to be assigned
value
The submobject to bind the key to
Returns
-------
None
Examples
--------
Normal usage::
square_obj = Square()
my_dict['sq'] = square_obj
"""
if key in self.submob_dict:
self.remove(key)
self.add([(key, value)])
def __delitem__(self, key: Hashable):
"""Override the del operator for deleting an item.
Parameters
----------
key
The key of the submoject to be deleted
Returns
-------
None
Examples
--------
::
>>> from manim import *
>>> my_dict = VDict({'sq': Square()})
>>> 'sq' in my_dict
True
>>> del my_dict['sq']
>>> 'sq' in my_dict
False
Notes
-----
Removing an item from a VDict does not remove that item from any Scene
that the VDict is part of.
"""
del self.submob_dict[key]
def __contains__(self, key: Hashable):
"""Override the in operator.
Parameters
----------
key
The key to check membership of.
Returns
-------
:class:`bool`
Examples
--------
::
>>> from manim import *
>>> my_dict = VDict({'sq': Square()})
>>> 'sq' in my_dict
True
"""
return key in self.submob_dict
def get_all_submobjects(self) -> list[list]:
"""To get all the submobjects associated with a particular :class:`VDict` object
Returns
-------
:class:`dict_values`
All the submobjects associated with the :class:`VDict` object
Examples
--------
Normal usage::
for submob in my_dict.get_all_submobjects():
self.play(Create(submob))
"""
submobjects = self.submob_dict.values()
return submobjects
def add_key_value_pair(self, key: Hashable, value: VMobject) -> None:
"""A utility function used by :meth:`add` to add the key-value pair
to :attr:`submob_dict`. Not really meant to be used externally.
Parameters
----------
key
The key of the submobject to be added.
value
The mobject associated with the key
Returns
-------
None
Raises
------
TypeError
If the value is not an instance of VMobject
Examples
--------
Normal usage::
square_obj = Square()
self.add_key_value_pair('s', square_obj)
"""
if not isinstance(value, (VMobject, OpenGLVMobject)):
raise TypeError("All submobjects must be of type VMobject")
mob = value
if self.show_keys:
# This import is here and not at the top to avoid circular import
from manim.mobject.text.tex_mobject import Tex
key_text = Tex(str(key)).next_to(value, LEFT)
mob.add(key_text)
self.submob_dict[key] = mob
super().add(value)
class VectorizedPoint(VMobject, metaclass=ConvertToOpenGL):
def __init__(
self,
location: Point3D = ORIGIN,
color: ManimColor = BLACK,
fill_opacity: float = 0,
stroke_width: float = 0,
artificial_width: float = 0.01,
artificial_height: float = 0.01,
**kwargs,
) -> None:
self.artificial_width = artificial_width
self.artificial_height = artificial_height
super().__init__(
color=color,
fill_opacity=fill_opacity,
stroke_width=stroke_width,
**kwargs,
)
self.set_points(np.array([location]))
basecls = OpenGLVMobject if config.renderer == RendererType.OPENGL else VMobject
@basecls.width.getter
def width(self) -> float:
return self.artificial_width
@basecls.height.getter
def height(self) -> float:
return self.artificial_height
def get_location(self) -> Point3D:
return np.array(self.points[0])
def set_location(self, new_loc: Point3D):
self.set_points(np.array([new_loc]))
class CurvesAsSubmobjects(VGroup):
"""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: VMobject, **kwargs) -> None:
super().__init__(**kwargs)
tuples = vmobject.get_cubic_bezier_tuples()
for tup in tuples:
part = VMobject()
part.set_points(tup)
part.match_style(vmobject)
self.add(part)
def point_from_proportion(self, alpha: float) -> Point3D:
"""Gets the point at a proportion along the path of the :class:`CurvesAsSubmobjects`.
Parameters
----------
alpha
The proportion along the the path of the :class:`CurvesAsSubmobjects`.
Returns
-------
:class:`numpy.ndarray`
The point on the :class:`CurvesAsSubmobjects`.
Raises
------
:exc:`ValueError`
If ``alpha`` is not between 0 and 1.
:exc:`Exception`
If the :class:`CurvesAsSubmobjects` has no submobjects, or no submobject has points.
"""
if alpha < 0 or alpha > 1:
raise ValueError(f"Alpha {alpha} not between 0 and 1.")
self._throw_error_if_no_submobjects()
submobjs_with_pts = self._get_submobjects_with_points()
if alpha == 1:
return submobjs_with_pts[-1].points[-1]
submobjs_arc_lengths = tuple(
part.get_arc_length() for part in submobjs_with_pts
)
total_length = sum(submobjs_arc_lengths)
target_length = alpha * total_length
current_length = 0
for i, part in enumerate(submobjs_with_pts):
part_length = submobjs_arc_lengths[i]
if current_length + part_length >= target_length:
residue = (target_length - current_length) / part_length
return part.point_from_proportion(residue)
current_length += part_length
def _throw_error_if_no_submobjects(self):
if len(self.submobjects) == 0:
caller_name = sys._getframe(1).f_code.co_name
raise Exception(
f"Cannot call CurvesAsSubmobjects. {caller_name} for a CurvesAsSubmobject with no submobjects"
)
def _get_submobjects_with_points(self):
submobjs_with_pts = tuple(
part for part in self.submobjects if len(part.points) > 0
)
if len(submobjs_with_pts) == 0:
caller_name = sys._getframe(1).f_code.co_name
raise Exception(
f"Cannot call CurvesAsSubmobjects. {caller_name} for a CurvesAsSubmobject whose submobjects have no points"
)
return submobjs_with_pts
class DashedVMobject(VMobject, metaclass=ConvertToOpenGL):
"""A :class:`VMobject` composed of dashes instead of lines.
Parameters
----------
vmobject
The object that will get dashed
num_dashes
Number of dashes to add.
dashed_ratio
Ratio of dash to empty space.
dash_offset
Shifts the starting point of dashes along the
path. Value 1 shifts by one full dash length.
equal_lengths
If ``True``, dashes will be (approximately) equally long.
If ``False``, dashes will be split evenly in the curve's
input t variable (legacy behavior).
Examples
--------
.. manim:: DashedVMobjectExample
:save_last_frame:
class DashedVMobjectExample(Scene):
def construct(self):
r = 0.5
top_row = VGroup() # Increasing num_dashes
for dashes in range(1, 12):
circ = DashedVMobject(Circle(radius=r, color=WHITE), num_dashes=dashes)
top_row.add(circ)
middle_row = VGroup() # 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)
func1 = FunctionGraph(lambda t: t**5,[-1,1],color=WHITE)
func_even = DashedVMobject(func1,num_dashes=6,equal_lengths=True)
func_stretched = DashedVMobject(func1, num_dashes=6, equal_lengths=False)
bottom_row = VGroup(func_even,func_stretched)
top_row.arrange(buff=0.3)
middle_row.arrange()
bottom_row.arrange(buff=1)
everything = VGroup(top_row, middle_row, bottom_row).arrange(DOWN, buff=1)
self.add(everything)
"""
def __init__(
self,
vmobject: VMobject,
num_dashes: int = 15,
dashed_ratio: float = 0.5,
dash_offset: float = 0,
color: ManimColor = WHITE,
equal_lengths: bool = True,
**kwargs,
) -> None:
self.dashed_ratio = dashed_ratio
self.num_dashes = num_dashes
super().__init__(color=color, **kwargs)
r = self.dashed_ratio
n = self.num_dashes
if n > 0:
# Assuming total length is 1
dash_len = r / n
if vmobject.is_closed():
void_len = (1 - r) / n
else:
if n == 1:
void_len = 1 - r
else:
void_len = (1 - r) / (n - 1)
period = dash_len + void_len
phase_shift = (dash_offset % 1) * period
if vmobject.is_closed():
# closed curves have equal amount of dashes and voids
pattern_len = 1
else:
# open curves start and end with a dash, so the whole dash pattern with the last void is longer
pattern_len = 1 + void_len
dash_starts = [((i * period + phase_shift) % pattern_len) for i in range(n)]
dash_ends = [
((i * period + dash_len + phase_shift) % pattern_len) for i in range(n)
]
# closed shapes can handle overflow at the 0-point
# open shapes need special treatment for it
if not vmobject.is_closed():
# due to phase shift being [0...1] range, always the last dash element needs attention for overflow
# if an entire dash moves out of the shape end:
if dash_ends[-1] > 1 and dash_starts[-1] > 1:
# remove the last element since it is out-of-bounds
dash_ends.pop()
dash_starts.pop()
elif dash_ends[-1] < dash_len: # if it overflowed
if (
dash_starts[-1] < 1
): # if the beginning of the piece is still in range
dash_starts.append(0)
dash_ends.append(dash_ends[-1])
dash_ends[-2] = 1
else:
dash_starts[-1] = 0
elif dash_starts[-1] > (1 - dash_len):
dash_ends[-1] = 1
if equal_lengths:
# calculate the entire length by adding up short line-pieces
norms = np.array(0)
for k in range(vmobject.get_num_curves()):
norms = np.append(norms, vmobject.get_nth_curve_length_pieces(k))
# add up length-pieces in array form
length_vals = np.cumsum(norms)
ref_points = np.linspace(0, 1, length_vals.size)
curve_length = length_vals[-1]
self.add(
*(
vmobject.get_subcurve(
np.interp(
dash_starts[i] * curve_length,
length_vals,
ref_points,
),
np.interp(
dash_ends[i] * curve_length,
length_vals,
ref_points,
),
)
for i in range(len(dash_starts))
)
)
else:
self.add(
*(
vmobject.get_subcurve(
dash_starts[i],
dash_ends[i],
)
for i in range(len(dash_starts))
)
)
# Family is already taken care of by get_subcurve
# implementation
if config.renderer == RendererType.OPENGL:
self.match_style(vmobject, recurse=False)
else:
self.match_style(vmobject, family=False)
|
manim_ManimCommunity/manim/mobject/types/point_cloud_mobject.py
|
"""Mobjects representing point clouds."""
from __future__ import annotations
__all__ = ["PMobject", "Mobject1D", "Mobject2D", "PGroup", "PointCloudDot", "Point"]
import numpy as np
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.opengl.opengl_point_cloud_mobject import OpenGLPMobject
from ...constants import *
from ...mobject.mobject import Mobject
from ...utils.bezier import interpolate
from ...utils.color import (
BLACK,
WHITE,
YELLOW,
ManimColor,
color_gradient,
color_to_rgba,
rgba_to_color,
)
from ...utils.iterables import stretch_array_to_length
__all__ = ["PMobject", "Mobject1D", "Mobject2D", "PGroup", "PointCloudDot", "Point"]
class PMobject(Mobject, metaclass=ConvertToOpenGL):
"""A disc made of a cloud of Dots
Examples
--------
.. manim:: PMobjectExample
:save_last_frame:
class PMobjectExample(Scene):
def construct(self):
pG = PGroup() # This is just a collection of PMobject's
# As the scale factor increases, the number of points
# removed increases.
for sf in range(1, 9 + 1):
p = PointCloudDot(density=20, radius=1).thin_out(sf)
# PointCloudDot is a type of PMobject
# and can therefore be added to a PGroup
pG.add(p)
# This organizes all the shapes in a grid.
pG.arrange_in_grid()
self.add(pG)
"""
def __init__(self, stroke_width=DEFAULT_STROKE_WIDTH, **kwargs):
self.stroke_width = stroke_width
super().__init__(**kwargs)
def reset_points(self):
self.rgbas = np.zeros((0, 4))
self.points = np.zeros((0, 3))
return self
def get_array_attrs(self):
return super().get_array_attrs() + ["rgbas"]
def add_points(self, points, rgbas=None, color=None, alpha=1):
"""Add points.
Points must be a Nx3 numpy array.
Rgbas must be a Nx4 numpy array if it is not None.
"""
if not isinstance(points, np.ndarray):
points = np.array(points)
num_new_points = len(points)
self.points = np.append(self.points, points, axis=0)
if rgbas is None:
color = ManimColor(color) if color else self.color
rgbas = np.repeat([color_to_rgba(color, alpha)], num_new_points, axis=0)
elif len(rgbas) != len(points):
raise ValueError("points and rgbas must have same length")
self.rgbas = np.append(self.rgbas, rgbas, axis=0)
return self
def set_color(self, color=YELLOW, family=True):
rgba = color_to_rgba(color)
mobs = self.family_members_with_points() if family else [self]
for mob in mobs:
mob.rgbas[:, :] = rgba
self.color = color
return self
def get_stroke_width(self):
return self.stroke_width
def set_stroke_width(self, width, family=True):
mobs = self.family_members_with_points() if family else [self]
for mob in mobs:
mob.stroke_width = width
return self
def set_color_by_gradient(self, *colors):
self.rgbas = np.array(
list(map(color_to_rgba, color_gradient(*colors, len(self.points)))),
)
return self
def set_colors_by_radial_gradient(
self,
center=None,
radius=1,
inner_color=WHITE,
outer_color=BLACK,
):
start_rgba, end_rgba = list(map(color_to_rgba, [inner_color, outer_color]))
if center is None:
center = self.get_center()
for mob in self.family_members_with_points():
distances = np.abs(self.points - center)
alphas = np.linalg.norm(distances, axis=1) / radius
mob.rgbas = np.array(
np.array(
[interpolate(start_rgba, end_rgba, alpha) for alpha in alphas],
),
)
return self
def match_colors(self, mobject):
Mobject.align_data(self, mobject)
self.rgbas = np.array(mobject.rgbas)
return self
def filter_out(self, condition):
for mob in self.family_members_with_points():
to_eliminate = ~np.apply_along_axis(condition, 1, mob.points)
mob.points = mob.points[to_eliminate]
mob.rgbas = mob.rgbas[to_eliminate]
return self
def thin_out(self, factor=5):
"""
Removes all but every nth point for n = factor
"""
for mob in self.family_members_with_points():
num_points = self.get_num_points()
mob.apply_over_attr_arrays(
lambda arr: arr[np.arange(0, num_points, factor)],
)
return self
def sort_points(self, function=lambda p: p[0]):
"""
Function is any map from R^3 to R
"""
for mob in self.family_members_with_points():
indices = np.argsort(np.apply_along_axis(function, 1, mob.points))
mob.apply_over_attr_arrays(lambda arr: arr[indices])
return self
def fade_to(self, color, alpha, family=True):
self.rgbas = interpolate(self.rgbas, color_to_rgba(color), alpha)
for mob in self.submobjects:
mob.fade_to(color, alpha, family)
return self
def get_all_rgbas(self):
return self.get_merged_array("rgbas")
def ingest_submobjects(self):
attrs = self.get_array_attrs()
arrays = list(map(self.get_merged_array, attrs))
for attr, array in zip(attrs, arrays):
setattr(self, attr, array)
self.submobjects = []
return self
def get_color(self):
return rgba_to_color(self.rgbas[0, :])
def point_from_proportion(self, alpha):
index = alpha * (self.get_num_points() - 1)
return self.points[index]
@staticmethod
def get_mobject_type_class():
return PMobject
# Alignment
def align_points_with_larger(self, larger_mobject):
assert isinstance(larger_mobject, PMobject)
self.apply_over_attr_arrays(
lambda a: stretch_array_to_length(a, larger_mobject.get_num_points()),
)
def get_point_mobject(self, center=None):
if center is None:
center = self.get_center()
return Point(center)
def interpolate_color(self, mobject1, mobject2, alpha):
self.rgbas = interpolate(mobject1.rgbas, mobject2.rgbas, alpha)
self.set_stroke_width(
interpolate(
mobject1.get_stroke_width(),
mobject2.get_stroke_width(),
alpha,
),
)
return self
def pointwise_become_partial(self, mobject, a, b):
lower_index, upper_index = (int(x * mobject.get_num_points()) for x in (a, b))
for attr in self.get_array_attrs():
full_array = getattr(mobject, attr)
partial_array = full_array[lower_index:upper_index]
setattr(self, attr, partial_array)
# TODO, Make the two implementations below non-redundant
class Mobject1D(PMobject, metaclass=ConvertToOpenGL):
def __init__(self, density=DEFAULT_POINT_DENSITY_1D, **kwargs):
self.density = density
self.epsilon = 1.0 / self.density
super().__init__(**kwargs)
def add_line(self, start, end, color=None):
start, end = list(map(np.array, [start, end]))
length = np.linalg.norm(end - start)
if length == 0:
points = [start]
else:
epsilon = self.epsilon / length
points = [interpolate(start, end, t) for t in np.arange(0, 1, epsilon)]
self.add_points(points, color=color)
class Mobject2D(PMobject, metaclass=ConvertToOpenGL):
def __init__(self, density=DEFAULT_POINT_DENSITY_2D, **kwargs):
self.density = density
self.epsilon = 1.0 / self.density
super().__init__(**kwargs)
class PGroup(PMobject):
"""A group for several point mobjects.
Examples
--------
.. manim:: PgroupExample
:save_last_frame:
class PgroupExample(Scene):
def construct(self):
p1 = PointCloudDot(radius=1, density=20, color=BLUE)
p1.move_to(4.5 * LEFT)
p2 = PointCloudDot()
p3 = PointCloudDot(radius=1.5, stroke_width=2.5, color=PINK)
p3.move_to(4.5 * RIGHT)
pList = PGroup(p1, p2, p3)
self.add(pList)
"""
def __init__(self, *pmobs, **kwargs):
if not all(isinstance(m, (PMobject, OpenGLPMobject)) for m in pmobs):
raise ValueError(
"All submobjects must be of type PMobject or OpenGLPMObject"
" if using the opengl renderer",
)
super().__init__(**kwargs)
self.add(*pmobs)
def fade_to(self, color, alpha, family=True):
if family:
for mob in self.submobjects:
mob.fade_to(color, alpha, family)
class PointCloudDot(Mobject1D):
"""A disc made of a cloud of dots.
Examples
--------
.. manim:: PointCloudDotExample
:save_last_frame:
class PointCloudDotExample(Scene):
def construct(self):
cloud_1 = PointCloudDot(color=RED)
cloud_2 = PointCloudDot(stroke_width=4, radius=1)
cloud_3 = PointCloudDot(density=15)
group = Group(cloud_1, cloud_2, cloud_3).arrange()
self.add(group)
.. manim:: PointCloudDotExample2
class PointCloudDotExample2(Scene):
def construct(self):
plane = ComplexPlane()
cloud = PointCloudDot(color=RED)
self.add(
plane, cloud
)
self.wait()
self.play(
cloud.animate.apply_complex_function(lambda z: np.exp(z))
)
"""
def __init__(
self,
center=ORIGIN,
radius=2.0,
stroke_width=2,
density=DEFAULT_POINT_DENSITY_1D,
color=YELLOW,
**kwargs,
):
self.radius = radius
self.epsilon = 1.0 / density
super().__init__(
stroke_width=stroke_width, density=density, color=color, **kwargs
)
self.shift(center)
def init_points(self):
self.reset_points()
self.generate_points()
def generate_points(self):
self.add_points(
[
r * (np.cos(theta) * RIGHT + np.sin(theta) * UP)
for r in np.arange(self.epsilon, self.radius, self.epsilon)
# Num is equal to int(stop - start)/ (step + 1) reformulated.
for theta in np.linspace(
0,
2 * np.pi,
num=int(2 * np.pi * (r + self.epsilon) / self.epsilon),
)
],
)
class Point(PMobject):
"""A mobject representing a point.
Examples
--------
.. manim:: ExamplePoint
:save_last_frame:
class ExamplePoint(Scene):
def construct(self):
colorList = [RED, GREEN, BLUE, YELLOW]
for i in range(200):
point = Point(location=[0.63 * np.random.randint(-4, 4), 0.37 * np.random.randint(-4, 4), 0], color=np.random.choice(colorList))
self.add(point)
for i in range(200):
point = Point(location=[0.37 * np.random.randint(-4, 4), 0.63 * np.random.randint(-4, 4), 0], color=np.random.choice(colorList))
self.add(point)
self.add(point)
"""
def __init__(self, location=ORIGIN, color=BLACK, **kwargs):
self.location = location
super().__init__(color=color, **kwargs)
def init_points(self):
self.reset_points()
self.generate_points()
self.set_points([self.location])
def generate_points(self):
self.add_points([self.location])
|
manim_ManimCommunity/manim/utils/debug.py
|
"""Debugging utilities."""
from __future__ import annotations
__all__ = ["print_family", "index_labels"]
from manim.mobject.mobject import Mobject
from manim.mobject.text.numbers import Integer
from ..mobject.types.vectorized_mobject import VGroup
from .color import BLACK
def print_family(mobject, n_tabs=0):
"""For debugging purposes"""
print("\t" * n_tabs, mobject, id(mobject))
for submob in mobject.submobjects:
print_family(submob, n_tabs + 1)
def index_labels(
mobject: Mobject,
label_height: float = 0.15,
background_stroke_width=5,
background_stroke_color=BLACK,
**kwargs,
):
r"""Returns a :class:`~.VGroup` of :class:`~.Integer` mobjects
that shows the index of each submobject.
Useful for working with parts of complicated mobjects.
Parameters
----------
mobject
The mobject that will have its submobjects labelled.
label_height
The height of the labels, by default 0.15.
background_stroke_width
The stroke width of the outline of the labels, by default 5.
background_stroke_color
The stroke color of the outline of labels.
kwargs
Additional parameters to be passed into the :class`~.Integer`
mobjects used to construct the labels.
Examples
--------
.. manim:: IndexLabelsExample
:save_last_frame:
class IndexLabelsExample(Scene):
def construct(self):
text = MathTex(
"\\frac{d}{dx}f(x)g(x)=",
"f(x)\\frac{d}{dx}g(x)",
"+",
"g(x)\\frac{d}{dx}f(x)",
)
#index the fist term in the MathTex mob
indices = index_labels(text[0])
text[0][1].set_color(PURPLE_B)
text[0][8:12].set_color(DARK_BLUE)
self.add(text, indices)
"""
labels = VGroup()
for n, submob in enumerate(mobject):
label = Integer(n, **kwargs)
label.set_stroke(
background_stroke_color, background_stroke_width, background=True
)
label.height = label_height
label.move_to(submob)
labels.add(label)
return labels
|
manim_ManimCommunity/manim/utils/family.py
|
from __future__ import annotations
import itertools as it
from typing import Iterable
from ..mobject.mobject import Mobject
from ..utils.iterables import remove_list_redundancies
__all__ = ["extract_mobject_family_members"]
def extract_mobject_family_members(
mobjects: Iterable[Mobject],
use_z_index=False,
only_those_with_points: bool = False,
):
"""Returns a list of the types of mobjects and their family members present.
A "family" in this context refers to a mobject, its submobjects, and their
submobjects, recursively.
Parameters
----------
mobjects
The Mobjects currently in the Scene
only_those_with_points
Whether or not to only do this for
those mobjects that have points. By default False
Returns
-------
list
list of the mobjects and family members.
"""
if only_those_with_points:
method = Mobject.family_members_with_points
else:
method = Mobject.get_family
extracted_mobjects = remove_list_redundancies(
list(it.chain(*(method(m) for m in mobjects))),
)
if use_z_index:
return sorted(extracted_mobjects, key=lambda m: m.z_index)
return extracted_mobjects
|
manim_ManimCommunity/manim/utils/tex.py
|
"""Utilities for processing LaTeX templates."""
from __future__ import annotations
__all__ = [
"TexTemplate",
]
import copy
import re
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from typing_extensions import Self
from manim.typing import StrPath
_DEFAULT_PREAMBLE = r"""\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}"""
_BEGIN_DOCUMENT = r"\begin{document}"
_END_DOCUMENT = r"\end{document}"
@dataclass(eq=True)
class TexTemplate:
"""TeX templates are used to create ``Tex`` and ``MathTex`` objects."""
_body: str = field(default="", init=False)
"""A custom body, can be set from a file."""
tex_compiler: str = "latex"
"""The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``."""
output_format: str = ".dvi"
"""The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``."""
documentclass: str = r"\documentclass[preview]{standalone}"
r"""The command defining the documentclass, e.g. ``\documentclass[preview]{standalone}``."""
preamble: str = _DEFAULT_PREAMBLE
r"""The document's preamble, i.e. the part between ``\documentclass`` and ``\begin{document}``."""
placeholder_text: str = "YourTextHere"
"""Text in the document that will be replaced by the expression to be rendered."""
post_doc_commands: str = ""
r"""Text (definitions, commands) to be inserted at right after ``\begin{document}``, e.g. ``\boldmath``."""
@property
def body(self) -> str:
"""The entire TeX template."""
return self._body or "\n".join(
filter(
None,
[
self.documentclass,
self.preamble,
_BEGIN_DOCUMENT,
self.post_doc_commands,
self.placeholder_text,
_END_DOCUMENT,
],
)
)
@body.setter
def body(self, value: str) -> None:
self._body = value
@classmethod
def from_file(cls, file: StrPath = "tex_template.tex", **kwargs: Any) -> Self:
"""Create an instance by reading the content of a file.
Using the ``add_to_preamble`` and ``add_to_document`` methods on this instance
will have no effect, as the body is read from the file.
"""
instance = cls(**kwargs)
instance.body = Path(file).read_text(encoding="utf-8")
return instance
def add_to_preamble(self, txt: str, prepend: bool = False) -> Self:
r"""Adds text to the TeX template's preamble (e.g. definitions, packages). Text can be inserted at the beginning or at the end of the preamble.
Parameters
----------
txt
String containing the text to be added, e.g. ``\usepackage{hyperref}``.
prepend
Whether the text should be added at the beginning of the preamble, i.e. right after ``\documentclass``.
Default is to add it at the end of the preamble, i.e. right before ``\begin{document}``.
"""
if self._body:
warnings.warn(
"This TeX template was created with a fixed body, trying to add text the preamble will have no effect.",
UserWarning,
stacklevel=2,
)
if prepend:
self.preamble = txt + "\n" + self.preamble
else:
self.preamble += "\n" + txt
return self
def add_to_document(self, txt: str) -> Self:
r"""Adds text to the TeX template just after \begin{document}, e.g. ``\boldmath``.
Parameters
----------
txt
String containing the text to be added.
"""
if self._body:
warnings.warn(
"This TeX template was created with a fixed body, trying to add text the document will have no effect.",
UserWarning,
stacklevel=2,
)
self.post_doc_commands += txt
return self
def get_texcode_for_expression(self, expression: str) -> str:
r"""Inserts expression verbatim into TeX template.
Parameters
----------
expression
The string containing the expression to be typeset, e.g. ``$\sqrt{2}$``
Returns
-------
:class:`str`
LaTeX code based on current template, containing the given ``expression`` and ready for typesetting
"""
return self.body.replace(self.placeholder_text, expression)
def get_texcode_for_expression_in_env(
self, expression: str, environment: str
) -> str:
r"""Inserts expression into TeX template wrapped in ``\begin{environment}`` and ``\end{environment}``.
Parameters
----------
expression
The string containing the expression to be typeset, e.g. ``$\sqrt{2}$``.
environment
The string containing the environment in which the expression should be typeset, e.g. ``align*``.
Returns
-------
:class:`str`
LaTeX code based on template, containing the given expression inside its environment, ready for typesetting
"""
begin, end = _texcode_for_environment(environment)
return self.body.replace(
self.placeholder_text, "\n".join([begin, expression, end])
)
def copy(self) -> Self:
"""Create a deep copy of the TeX template instance."""
return copy.deepcopy(self)
def _texcode_for_environment(environment: str) -> tuple[str, str]:
r"""Processes the tex_environment string to return the correct ``\begin{environment}[extra]{extra}`` and
``\end{environment}`` strings.
Parameters
----------
environment
The tex_environment as a string. Acceptable formats include:
``{align*}``, ``align*``, ``{tabular}[t]{cccl}``, ``tabular}{cccl``, ``\begin{tabular}[t]{cccl}``.
Returns
-------
Tuple[:class:`str`, :class:`str`]
A pair of strings representing the opening and closing of the tex environment, e.g.
``\begin{tabular}{cccl}`` and ``\end{tabular}``
"""
environment.removeprefix(r"\begin").removeprefix("{")
# The \begin command takes everything and closes with a brace
begin = r"\begin{" + environment
# If it doesn't end on } or ], assume missing }
if not begin.endswith(("}", "]")):
begin += "}"
# While the \end command terminates at the first closing brace
split_at_brace = re.split("}", environment, 1)
end = r"\end{" + split_at_brace[0] + "}"
return begin, end
|
manim_ManimCommunity/manim/utils/tex_file_writing.py
|
"""Interface for writing, compiling, and converting ``.tex`` files.
.. SEEALSO::
:mod:`.mobject.svg.tex_mobject`
"""
from __future__ import annotations
import hashlib
import os
import re
import unicodedata
from pathlib import Path
from typing import Iterable
from manim.utils.tex import TexTemplate
from .. import config, logger
__all__ = ["tex_to_svg_file"]
def tex_hash(expression):
id_str = str(expression)
hasher = hashlib.sha256()
hasher.update(id_str.encode())
# Truncating at 16 bytes for cleanliness
return hasher.hexdigest()[:16]
def tex_to_svg_file(
expression: str,
environment: str | None = None,
tex_template: TexTemplate | None = None,
):
"""Takes a tex expression and returns the svg version of the compiled tex
Parameters
----------
expression
String containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo``
environment
The string containing the environment in which the expression should be typeset, e.g. ``align*``
tex_template
Template class used to typesetting. If not set, use default template set via `config["tex_template"]`
Returns
-------
:class:`Path`
Path to generated SVG file.
"""
if tex_template is None:
tex_template = config["tex_template"]
tex_file = generate_tex_file(expression, environment, tex_template)
# check if svg already exists
svg_file = tex_file.with_suffix(".svg")
if svg_file.exists():
return svg_file
dvi_file = compile_tex(
tex_file,
tex_template.tex_compiler,
tex_template.output_format,
)
svg_file = convert_to_svg(dvi_file, tex_template.output_format)
if not config["no_latex_cleanup"]:
delete_nonsvg_files()
return svg_file
def generate_tex_file(
expression: str,
environment: str | None = None,
tex_template: TexTemplate | None = None,
) -> Path:
"""Takes a tex expression (and an optional tex environment),
and returns a fully formed tex file ready for compilation.
Parameters
----------
expression
String containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo``
environment
The string containing the environment in which the expression should be typeset, e.g. ``align*``
tex_template
Template class used to typesetting. If not set, use default template set via `config["tex_template"]`
Returns
-------
:class:`Path`
Path to generated TeX file
"""
if tex_template is None:
tex_template = config["tex_template"]
if environment is not None:
output = tex_template.get_texcode_for_expression_in_env(expression, environment)
else:
output = tex_template.get_texcode_for_expression(expression)
tex_dir = config.get_dir("tex_dir")
if not tex_dir.exists():
tex_dir.mkdir()
result = tex_dir / (tex_hash(output) + ".tex")
if not result.exists():
logger.info(
"Writing %(expression)s to %(path)s",
{"expression": expression, "path": f"{result}"},
)
result.write_text(output, encoding="utf-8")
return result
def tex_compilation_command(
tex_compiler: str, output_format: str, tex_file: Path, tex_dir: Path
) -> str:
"""Prepares the tex compilation command with all necessary cli flags
Parameters
----------
tex_compiler
String containing the compiler to be used, e.g. ``pdflatex`` or ``lualatex``
output_format
String containing the output format generated by the compiler, e.g. ``.dvi`` or ``.pdf``
tex_file
File name of TeX file to be typeset.
tex_dir
Path to the directory where compiler output will be stored.
Returns
-------
:class:`str`
Compilation command according to given parameters
"""
if tex_compiler in {"latex", "pdflatex", "luatex", "lualatex"}:
commands = [
tex_compiler,
"-interaction=batchmode",
f'-output-format="{output_format[1:]}"',
"-halt-on-error",
f'-output-directory="{tex_dir.as_posix()}"',
f'"{tex_file.as_posix()}"',
">",
os.devnull,
]
elif tex_compiler == "xelatex":
if output_format == ".xdv":
outflag = "-no-pdf"
elif output_format == ".pdf":
outflag = ""
else:
raise ValueError("xelatex output is either pdf or xdv")
commands = [
"xelatex",
outflag,
"-interaction=batchmode",
"-halt-on-error",
f'-output-directory="{tex_dir.as_posix()}"',
f'"{tex_file.as_posix()}"',
">",
os.devnull,
]
else:
raise ValueError(f"Tex compiler {tex_compiler} unknown.")
return " ".join(commands)
def insight_inputenc_error(matching):
code_point = chr(int(matching[1], 16))
name = unicodedata.name(code_point)
yield f"TexTemplate does not support character '{name}' (U+{matching[1]})."
yield "See the documentation for manim.mobject.svg.tex_mobject for details on using a custom TexTemplate."
def insight_package_not_found_error(matching):
yield f"You do not have package {matching[1]} installed."
yield f"Install {matching[1]} it using your LaTeX package manager, or check for typos."
def compile_tex(tex_file: Path, tex_compiler: str, output_format: str) -> Path:
"""Compiles a tex_file into a .dvi or a .xdv or a .pdf
Parameters
----------
tex_file
File name of TeX file to be typeset.
tex_compiler
String containing the compiler to be used, e.g. ``pdflatex`` or ``lualatex``
output_format
String containing the output format generated by the compiler, e.g. ``.dvi`` or ``.pdf``
Returns
-------
:class:`Path`
Path to generated output file in desired format (DVI, XDV or PDF).
"""
result = tex_file.with_suffix(output_format)
tex_dir = config.get_dir("tex_dir")
if not result.exists():
command = tex_compilation_command(
tex_compiler,
output_format,
tex_file,
tex_dir,
)
exit_code = os.system(command)
if exit_code != 0:
log_file = tex_file.with_suffix(".log")
print_all_tex_errors(log_file, tex_compiler, tex_file)
raise ValueError(
f"{tex_compiler} error converting to"
f" {output_format[1:]}. See log output above or"
f" the log file: {log_file}",
)
return result
def convert_to_svg(dvi_file: Path, extension: str, page: int = 1):
"""Converts a .dvi, .xdv, or .pdf file into an svg using dvisvgm.
Parameters
----------
dvi_file
File name of the input file to be converted.
extension
String containing the file extension and thus indicating the file type, e.g. ``.dvi`` or ``.pdf``
page
Page to be converted if input file is multi-page.
Returns
-------
:class:`Path`
Path to generated SVG file.
"""
result = dvi_file.with_suffix(".svg")
if not result.exists():
commands = [
"dvisvgm",
"--pdf" if extension == ".pdf" else "",
"-p " + str(page),
f'"{dvi_file.as_posix()}"',
"-n",
"-v 0",
"-o " + f'"{result.as_posix()}"',
">",
os.devnull,
]
os.system(" ".join(commands))
# if the file does not exist now, this means conversion failed
if not result.exists():
raise ValueError(
f"Your installation does not support converting {dvi_file.suffix} files to SVG."
f" Consider updating dvisvgm to at least version 2.4."
f" If this does not solve the problem, please refer to our troubleshooting guide at:"
f" https://docs.manim.community/en/stable/faq/general.html#my-installation-"
f"does-not-support-converting-pdf-to-svg-help",
)
return result
def delete_nonsvg_files(additional_endings: Iterable[str] = ()) -> None:
"""Deletes every file that does not have a suffix in ``(".svg", ".tex", *additional_endings)``
Parameters
----------
additional_endings
Additional endings to whitelist
"""
tex_dir = config.get_dir("tex_dir")
file_suffix_whitelist = {".svg", ".tex", *additional_endings}
for f in tex_dir.iterdir():
if f.suffix not in file_suffix_whitelist:
f.unlink()
def print_all_tex_errors(log_file: Path, tex_compiler: str, tex_file: Path) -> None:
if not log_file.exists():
raise RuntimeError(
f"{tex_compiler} failed but did not produce a log file. "
"Check your LaTeX installation.",
)
with log_file.open(encoding="utf-8") as f:
tex_compilation_log = f.readlines()
error_indices = [
index for index, line in enumerate(tex_compilation_log) if line.startswith("!")
]
if error_indices:
with tex_file.open() as f:
tex = f.readlines()
for error_index in error_indices:
print_tex_error(tex_compilation_log, error_index, tex)
LATEX_ERROR_INSIGHTS = [
(
r"inputenc Error: Unicode character (?:.*) \(U\+([0-9a-fA-F]+)\)",
insight_inputenc_error,
),
(
r"LaTeX Error: File `(.*?[clsty])' not found",
insight_package_not_found_error,
),
]
def print_tex_error(tex_compilation_log, error_start_index, tex_source):
logger.error(
f"LaTeX compilation error: {tex_compilation_log[error_start_index][2:]}",
)
# TeX errors eventually contain a line beginning 'l.xxx` where xxx is the line number that caused the compilation
# failure. This code finds the next such line after the error current error message
line_of_tex_error = (
int(
[
log_line
for log_line in tex_compilation_log[error_start_index:]
if log_line.startswith("l.")
][0]
.split(" ")[0]
.split(".")[1],
)
- 1
)
# our tex error may be on a line outside our user input because of post-processing
if line_of_tex_error >= len(tex_source):
return None
context = ["Context of error: \n"]
if line_of_tex_error < 3:
context += tex_source[: line_of_tex_error + 3]
context[-4] = "-> " + context[-4]
elif line_of_tex_error > len(tex_source) - 3:
context += tex_source[line_of_tex_error - 1 :]
context[1] = "-> " + context[1]
else:
context += tex_source[line_of_tex_error - 3 : line_of_tex_error + 3]
context[-4] = "-> " + context[-4]
context = "".join(context)
logger.error(context)
for insights in LATEX_ERROR_INSIGHTS:
prob, get_insight = insights
matching = re.search(
prob,
"".join(tex_compilation_log[error_start_index])[2:],
)
if matching is not None:
for insight in get_insight(matching):
logger.info(insight)
|
manim_ManimCommunity/manim/utils/__init__.py
| |
manim_ManimCommunity/manim/utils/deprecation.py
|
"""Decorators for deprecating classes, functions and function parameters."""
from __future__ import annotations
__all__ = ["deprecated", "deprecated_params"]
import inspect
import re
from typing import Any, Callable, Iterable
from decorator import decorate, decorator
from .. import logger
def _get_callable_info(callable: Callable) -> tuple[str, str]:
"""Returns type and name of a callable.
Parameters
----------
callable
The callable
Returns
-------
Tuple[str, str]
The type and name of the callable. Type can can be one of "class", "method" (for
functions defined in classes) or "function"). For methods, name is Class.method.
"""
what = type(callable).__name__
name = callable.__qualname__
if what == "function" and "." in name:
what = "method"
elif what != "function":
what = "class"
return (what, name)
def _deprecation_text_component(
since: str | None,
until: str | None,
message: str,
) -> str:
"""Generates a text component used in deprecation messages.
Parameters
----------
since
The version or date since deprecation
until
The version or date until removal of the deprecated callable
message
The reason for why the callable has been deprecated
Returns
-------
str
The deprecation message text component.
"""
since = f"since {since} " if since else ""
until = (
f"is expected to be removed after {until}"
if until
else "may be removed in a later version"
)
msg = " " + message if message else ""
return f"deprecated {since}and {until}.{msg}"
def deprecated(
func: Callable = None,
since: str | None = None,
until: str | None = None,
replacement: str | None = None,
message: str | None = "",
) -> Callable:
"""Decorator to mark a callable as deprecated.
The decorated callable will cause a warning when used. The docstring of the
deprecated callable is adjusted to indicate that this callable is deprecated.
Parameters
----------
func
The function to be decorated. Should not be set by the user.
since
The version or date since deprecation.
until
The version or date until removal of the deprecated callable.
replacement
The identifier of the callable replacing the deprecated one.
message
The reason for why the callable has been deprecated.
Returns
-------
Callable
The decorated callable.
Examples
--------
Basic usage::
from manim.utils.deprecation import deprecated
@deprecated
def foo(**kwargs):
pass
@deprecated
class Bar:
def __init__(self):
pass
@deprecated
def baz(self):
pass
foo()
# WARNING The function foo has been deprecated and may be removed in a later version.
a = Bar()
# WARNING The class Bar has been deprecated and may be removed in a later version.
a.baz()
# WARNING The method Bar.baz has been deprecated and may be removed in a later version.
You can specify additional information for a more precise warning::
from manim.utils.deprecation import deprecated
@deprecated(
since="v0.2",
until="v0.4",
replacement="bar",
message="It is cooler."
)
def foo():
pass
foo()
# WARNING The function foo has been deprecated since v0.2 and is expected to be removed after v0.4. Use bar instead. It is cooler.
You may also use dates instead of versions::
from manim.utils.deprecation import deprecated
@deprecated(since="05/01/2021", until="06/01/2021")
def foo():
pass
foo()
# WARNING The function foo has been deprecated since 05/01/2021 and is expected to be removed after 06/01/2021.
"""
# If used as factory:
if func is None:
return lambda func: deprecated(func, since, until, replacement, message)
what, name = _get_callable_info(func)
def warning_msg(for_docs: bool = False) -> str:
"""Generate the deprecation warning message.
Parameters
----------
for_docs
Whether or not to format the message for use in documentation.
Returns
-------
str
The deprecation message.
"""
msg = message
if replacement is not None:
repl = replacement
if for_docs:
mapper = {"class": "class", "method": "meth", "function": "func"}
repl = f":{mapper[what]}:`~.{replacement}`"
msg = f"Use {repl} instead.{' ' + message if message else ''}"
deprecated = _deprecation_text_component(since, until, msg)
return f"The {what} {name} has been {deprecated}"
def deprecate_docs(func: Callable):
"""Adjust docstring to indicate the deprecation.
Parameters
----------
func
The callable whose docstring to adjust.
"""
warning = warning_msg(True)
doc_string = func.__doc__ or ""
func.__doc__ = f"{doc_string}\n\n.. attention:: Deprecated\n {warning}"
def deprecate(func: Callable, *args, **kwargs):
"""The actual decorator used to extend the callables behavior.
Logs a warning message.
Parameters
----------
func
The callable to decorate.
args
The arguments passed to the given callable.
kwargs
The keyword arguments passed to the given callable.
Returns
-------
Any
The return value of the given callable when being passed the given
arguments.
"""
logger.warning(warning_msg())
return func(*args, **kwargs)
if type(func).__name__ != "function":
deprecate_docs(func)
func.__init__ = decorate(func.__init__, deprecate)
return func
func = decorate(func, deprecate)
deprecate_docs(func)
return func
def deprecated_params(
params: str | Iterable[str] | None = None,
since: str | None = None,
until: str | None = None,
message: str | None = "",
redirections: None
| (Iterable[tuple[str, str] | Callable[..., dict[str, Any]]]) = None,
) -> Callable:
"""Decorator to mark parameters of a callable as deprecated.
It can also be used to automatically redirect deprecated parameter values to their
replacements.
Parameters
----------
params
The parameters to be deprecated. Can consist of:
* An iterable of strings, with each element representing a parameter to deprecate
* A single string, with parameter names separated by commas or spaces.
since
The version or date since deprecation.
until
The version or date until removal of the deprecated callable.
message
The reason for why the callable has been deprecated.
redirections
A list of parameter redirections. Each redirection can be one of the following:
* A tuple of two strings. The first string defines the name of the deprecated
parameter; the second string defines the name of the parameter to redirect to,
when attempting to use the first string.
* A function performing the mapping operation. The parameter names of the
function determine which parameters are used as input. The function must
return a dictionary which contains the redirected arguments.
Redirected parameters are also implicitly deprecated.
Returns
-------
Callable
The decorated callable.
Raises
------
ValueError
If no parameters are defined (neither explicitly nor implicitly).
ValueError
If defined parameters are invalid python identifiers.
Examples
--------
Basic usage::
from manim.utils.deprecation import deprecated_params
@deprecated_params(params="a, b, c")
def foo(**kwargs):
pass
foo(x=2, y=3, z=4)
# No warning
foo(a=2, b=3, z=4)
# WARNING The parameters a and b of method foo have been deprecated and may be removed in a later version.
You can also specify additional information for a more precise warning::
from manim.utils.deprecation import deprecated_params
@deprecated_params(
params="a, b, c",
since="v0.2",
until="v0.4",
message="The letters x, y, z are cooler."
)
def foo(**kwargs):
pass
foo(a=2)
# WARNING The parameter a of method foo has been deprecated since v0.2 and is expected to be removed after v0.4. The letters x, y, z are cooler.
Basic parameter redirection::
from manim.utils.deprecation import deprecated_params
@deprecated_params(redirections=[
# Two ways to redirect one parameter to another:
("old_param", "new_param"),
lambda old_param2: {"new_param22": old_param2}
])
def foo(**kwargs):
return kwargs
foo(x=1, old_param=2)
# WARNING The parameter old_param of method foo has been deprecated and may be removed in a later version.
# returns {"x": 1, "new_param": 2}
Redirecting using a calculated value::
from manim.utils.deprecation import deprecated_params
@deprecated_params(redirections=[
lambda runtime_in_ms: {"run_time": runtime_in_ms / 1000}
])
def foo(**kwargs):
return kwargs
foo(runtime_in_ms=500)
# WARNING The parameter runtime_in_ms of method foo has been deprecated and may be removed in a later version.
# returns {"run_time": 0.5}
Redirecting multiple parameter values to one::
from manim.utils.deprecation import deprecated_params
@deprecated_params(redirections=[
lambda buff_x=1, buff_y=1: {"buff": (buff_x, buff_y)}
])
def foo(**kwargs):
return kwargs
foo(buff_x=2)
# WARNING The parameter buff_x of method foo has been deprecated and may be removed in a later version.
# returns {"buff": (2, 1)}
Redirect one parameter to multiple::
from manim.utils.deprecation import deprecated_params
@deprecated_params(redirections=[
lambda buff=1: {"buff_x": buff[0], "buff_y": buff[1]} if isinstance(buff, tuple)
else {"buff_x": buff, "buff_y": buff}
])
def foo(**kwargs):
return kwargs
foo(buff=0)
# WARNING The parameter buff of method foo has been deprecated and may be removed in a later version.
# returns {"buff_x": 0, buff_y: 0}
foo(buff=(1,2))
# WARNING The parameter buff of method foo has been deprecated and may be removed in a later version.
# returns {"buff_x": 1, buff_y: 2}
"""
# Check if decorator is used without parenthesis
if callable(params):
raise ValueError("deprecate_parameters requires arguments to be specified.")
if params is None:
params = []
# Construct params list
params = re.split(r"[,\s]+", params) if isinstance(params, str) else list(params)
# Add params which are only implicitly given via redirections
if redirections is None:
redirections = []
for redirector in redirections:
if isinstance(redirector, tuple):
params.append(redirector[0])
else:
params.extend(list(inspect.signature(redirector).parameters))
# Keep ordering of params so that warning message is consistently the same
# This will also help pass unit testing
params = list(dict.fromkeys(params))
# Make sure params only contains valid identifiers
identifier = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE)
if not all(re.match(identifier, param) for param in params):
raise ValueError("Given parameter values are invalid.")
redirections = list(redirections)
def warning_msg(func: Callable, used: list[str]):
"""Generate the deprecation warning message.
Parameters
----------
func
The callable with deprecated parameters.
used
The list of deprecated parameters used in a call.
Returns
-------
str
The deprecation message.
"""
what, name = _get_callable_info(func)
plural = len(used) > 1
parameter_s = "s" if plural else ""
used_ = ", ".join(used[:-1]) + " and " + used[-1] if plural else used[0]
has_have_been = "have been" if plural else "has been"
deprecated = _deprecation_text_component(since, until, message)
return f"The parameter{parameter_s} {used_} of {what} {name} {has_have_been} {deprecated}"
def redirect_params(kwargs: dict, used: list[str]):
"""Adjust the keyword arguments as defined by the redirections.
Parameters
----------
kwargs
The keyword argument dictionary to be updated.
used
The list of deprecated parameters used in a call.
"""
for redirector in redirections:
if isinstance(redirector, tuple):
old_param, new_param = redirector
if old_param in used:
kwargs[new_param] = kwargs.pop(old_param)
else:
redirector_params = list(inspect.signature(redirector).parameters)
redirector_args = {}
for redirector_param in redirector_params:
if redirector_param in used:
redirector_args[redirector_param] = kwargs.pop(redirector_param)
if len(redirector_args) > 0:
kwargs.update(redirector(**redirector_args))
def deprecate_params(func, *args, **kwargs):
"""The actual decorator function used to extend the callables behavior.
Logs a warning message when a deprecated parameter is used and redirects it if
specified.
Parameters
----------
func
The callable to decorate.
args
The arguments passed to the given callable.
kwargs
The keyword arguments passed to the given callable.
Returns
-------
Any
The return value of the given callable when being passed the given
arguments.
"""
used = []
for param in params:
if param in kwargs:
used.append(param)
if len(used) > 0:
logger.warning(warning_msg(func, used))
redirect_params(kwargs, used)
return func(*args, **kwargs)
return decorator(deprecate_params)
|
manim_ManimCommunity/manim/utils/ipython_magic.py
|
"""Utilities for using Manim with IPython (in particular: Jupyter notebooks)"""
from __future__ import annotations
import mimetypes
import os
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
from manim import Group, config, logger, tempconfig
from manim.__main__ import main
from manim.renderer.shader import shader_program_cache
from ..constants import RendererType
__all__ = ["ManimMagic"]
try:
from IPython import get_ipython
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.magic import (
Magics,
line_cell_magic,
magics_class,
needs_local_scope,
)
from IPython.display import Image, Video, display
except ImportError:
pass
else:
@magics_class
class ManimMagic(Magics):
def __init__(self, shell: InteractiveShell) -> None:
super().__init__(shell)
self.rendered_files = {}
@needs_local_scope
@line_cell_magic
def manim(
self,
line: str,
cell: str = None,
local_ns: dict[str, Any] = None,
) -> None:
r"""Render Manim scenes contained in IPython cells.
Works as a line or cell magic.
.. hint::
This line and cell magic works best when used in a JupyterLab
environment: while all of the functionality is available for
classic Jupyter notebooks as well, it is possible that videos
sometimes don't update on repeated execution of the same cell
if the scene name stays the same.
This problem does not occur when using JupyterLab.
Please refer to `<https://jupyter.org/>`_ for more information about JupyterLab
and Jupyter notebooks.
Usage in line mode::
%manim [CLI options] MyAwesomeScene
Usage in cell mode::
%%manim [CLI options] MyAwesomeScene
class MyAweseomeScene(Scene):
def construct(self):
...
Run ``%manim --help`` and ``%manim render --help`` for possible command line interface options.
.. note::
The maximal width of the rendered videos that are displayed in the notebook can be
configured via the ``media_width`` configuration option. The default is set to ``25vw``,
which is 25% of your current viewport width. To allow the output to become as large
as possible, set ``config.media_width = "100%"``.
The ``media_embed`` option will embed the image/video output in the notebook. This is
generally undesirable as it makes the notebooks very large, but is required on some
platforms (notably Google's CoLab, where it is automatically enabled unless suppressed
by ``config.embed = False``) and needed in cases when the notebook (or converted HTML
file) will be moved relative to the video locations. Use-cases include building
documentation with Sphinx and JupyterBook. See also the :mod:`manim directive for Sphinx
<manim.utils.docbuild.manim_directive>`.
Examples
--------
First make sure to put ``import manim``, or even ``from manim import *``
in a cell and evaluate it. Then, a typical Jupyter notebook cell for Manim
could look as follows::
%%manim -v WARNING --disable_caching -qm BannerExample
config.media_width = "75%"
config.media_embed = True
class BannerExample(Scene):
def construct(self):
self.camera.background_color = "#ece6e2"
banner_large = ManimBanner(dark_theme=False).scale(0.7)
self.play(banner_large.create())
self.play(banner_large.expand())
Evaluating this cell will render and display the ``BannerExample`` scene defined in the body of the cell.
.. note::
In case you want to hide the red box containing the output progress bar, the ``progress_bar`` config
option should be set to ``None``. This can also be done by passing ``--progress_bar None`` as a
CLI flag.
"""
if cell:
exec(cell, local_ns)
args = line.split()
if not len(args) or "-h" in args or "--help" in args or "--version" in args:
main(args, standalone_mode=False, prog_name="manim")
return
modified_args = self.add_additional_args(args)
args = main(modified_args, standalone_mode=False, prog_name="manim")
with tempconfig(local_ns.get("config", {})):
config.digest_args(args)
renderer = None
if config.renderer == RendererType.OPENGL:
from manim.renderer.opengl_renderer import OpenGLRenderer
renderer = OpenGLRenderer()
try:
SceneClass = local_ns[config["scene_names"][0]]
scene = SceneClass(renderer=renderer)
scene.render()
finally:
# Shader cache becomes invalid as the context is destroyed
shader_program_cache.clear()
# Close OpenGL window here instead of waiting for the main thread to
# finish causing the window to stay open and freeze
if renderer is not None and renderer.window is not None:
renderer.window.close()
if config["output_file"] is None:
logger.info("No output file produced")
return
local_path = Path(config["output_file"]).relative_to(Path.cwd())
tmpfile = (
Path(config["media_dir"])
/ "jupyter"
/ f"{_generate_file_name()}{local_path.suffix}"
)
if local_path in self.rendered_files:
self.rendered_files[local_path].unlink()
self.rendered_files[local_path] = tmpfile
tmpfile.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(local_path, tmpfile)
file_type = mimetypes.guess_type(config["output_file"])[0]
embed = config["media_embed"]
if embed is None:
# videos need to be embedded when running in google colab.
# do this automatically in case config.media_embed has not been
# set explicitly.
embed = "google.colab" in str(get_ipython())
if file_type.startswith("image"):
result = Image(filename=config["output_file"])
else:
result = Video(
tmpfile,
html_attributes=f'controls autoplay loop style="max-width: {config["media_width"]};"',
embed=embed,
)
display(result)
def add_additional_args(self, args: list[str]) -> list[str]:
additional_args = ["--jupyter"]
# Use webm to support transparency
if "-t" in args and "--format" not in args:
additional_args += ["--format", "webm"]
return additional_args + args[:-1] + [""] + [args[-1]]
def _generate_file_name() -> str:
return config["scene_names"][0] + "@" + datetime.now().strftime("%Y-%m-%d@%H-%M-%S")
|
manim_ManimCommunity/manim/utils/iterables.py
|
"""Operations on iterables."""
from __future__ import annotations
__all__ = [
"adjacent_n_tuples",
"adjacent_pairs",
"all_elements_are_instances",
"concatenate_lists",
"list_difference_update",
"list_update",
"listify",
"make_even",
"make_even_by_cycling",
"remove_list_redundancies",
"remove_nones",
"stretch_array_to_length",
"tuplify",
]
import itertools as it
from typing import Any, Callable, Collection, Generator, Iterable, Reversible, Sequence
import numpy as np
def adjacent_n_tuples(objects: Sequence, n: int) -> zip:
"""Returns the Sequence objects cyclically split into n length tuples.
See Also
--------
adjacent_pairs : alias with n=2
Examples
--------
Normal usage::
list(adjacent_n_tuples([1, 2, 3, 4], 2))
# returns [(1, 2), (2, 3), (3, 4), (4, 1)]
list(adjacent_n_tuples([1, 2, 3, 4], 3))
# returns [(1, 2, 3), (2, 3, 4), (3, 4, 1), (4, 1, 2)]
"""
return zip(*([*objects[k:], *objects[:k]] for k in range(n)))
def adjacent_pairs(objects: Sequence) -> zip:
"""Alias for ``adjacent_n_tuples(objects, 2)``.
See Also
--------
adjacent_n_tuples
Examples
--------
Normal usage::
list(adjacent_pairs([1, 2, 3, 4]))
# returns [(1, 2), (2, 3), (3, 4), (4, 1)]
"""
return adjacent_n_tuples(objects, 2)
def all_elements_are_instances(iterable: Iterable, Class) -> bool:
"""Returns ``True`` if all elements of iterable are instances of Class.
False otherwise.
"""
return all(isinstance(e, Class) for e in iterable)
def batch_by_property(
items: Sequence, property_func: Callable
) -> list[tuple[list, Any]]:
"""Takes in a Sequence, and returns a list of tuples, (batch, prop)
such that all items in a batch have the same output when
put into the Callable property_func, and such that chaining all these
batches together would give the original Sequence (i.e. order is
preserved).
Examples
--------
Normal usage::
batch_by_property([(1, 2), (3, 4), (5, 6, 7), (8, 9)], len)
# returns [([(1, 2), (3, 4)], 2), ([(5, 6, 7)], 3), ([(8, 9)], 2)]
"""
batch_prop_pairs = []
curr_batch = []
curr_prop = None
for item in items:
prop = property_func(item)
if prop != curr_prop:
# Add current batch
if len(curr_batch) > 0:
batch_prop_pairs.append((curr_batch, curr_prop))
# Redefine curr
curr_prop = prop
curr_batch = [item]
else:
curr_batch.append(item)
if len(curr_batch) > 0:
batch_prop_pairs.append((curr_batch, curr_prop))
return batch_prop_pairs
def concatenate_lists(*list_of_lists: Iterable) -> list:
"""Combines the Iterables provided as arguments into one list.
Examples
--------
Normal usage::
concatenate_lists([1, 2], [3, 4], [5])
# returns [1, 2, 3, 4, 5]
"""
return [item for lst in list_of_lists for item in lst]
def list_difference_update(l1: Iterable, l2: Iterable) -> list:
"""Returns a list containing all the elements of l1 not in l2.
Examples
--------
Normal usage::
list_difference_update([1, 2, 3, 4], [2, 4])
# returns [1, 3]
"""
return [e for e in l1 if e not in l2]
def list_update(l1: Iterable, l2: Iterable) -> list:
"""Used instead of ``set.update()`` to maintain order,
making sure duplicates are removed from l1, not l2.
Removes overlap of l1 and l2 and then concatenates l2 unchanged.
Examples
--------
Normal usage::
list_update([1, 2, 3], [2, 4, 4])
# returns [1, 3, 2, 4, 4]
"""
return [e for e in l1 if e not in l2] + list(l2)
def listify(obj) -> list:
"""Converts obj to a list intelligently.
Examples
--------
Normal usage::
listify('str') # ['str']
listify((1, 2)) # [1, 2]
listify(len) # [<built-in function len>]
"""
if isinstance(obj, str):
return [obj]
try:
return list(obj)
except TypeError:
return [obj]
def make_even(iterable_1: Iterable, iterable_2: Iterable) -> tuple[list, list]:
"""Extends the shorter of the two iterables with duplicate values until its
length is equal to the longer iterable (favours earlier elements).
See Also
--------
make_even_by_cycling : cycles elements instead of favouring earlier ones
Examples
--------
Normal usage::
make_even([1, 2], [3, 4, 5, 6])
([1, 1, 2, 2], [3, 4, 5, 6])
make_even([1, 2], [3, 4, 5, 6, 7])
# ([1, 1, 1, 2, 2], [3, 4, 5, 6, 7])
"""
list_1, list_2 = list(iterable_1), list(iterable_2)
len_list_1 = len(list_1)
len_list_2 = len(list_2)
length = max(len_list_1, len_list_2)
return (
[list_1[(n * len_list_1) // length] for n in range(length)],
[list_2[(n * len_list_2) // length] for n in range(length)],
)
def make_even_by_cycling(
iterable_1: Collection, iterable_2: Collection
) -> tuple[list, list]:
"""Extends the shorter of the two iterables with duplicate values until its
length is equal to the longer iterable (cycles over shorter iterable).
See Also
--------
make_even : favours earlier elements instead of cycling them
Examples
--------
Normal usage::
make_even_by_cycling([1, 2], [3, 4, 5, 6])
([1, 2, 1, 2], [3, 4, 5, 6])
make_even_by_cycling([1, 2], [3, 4, 5, 6, 7])
# ([1, 2, 1, 2, 1], [3, 4, 5, 6, 7])
"""
length = max(len(iterable_1), len(iterable_2))
cycle1 = it.cycle(iterable_1)
cycle2 = it.cycle(iterable_2)
return (
[next(cycle1) for _ in range(length)],
[next(cycle2) for _ in range(length)],
)
def remove_list_redundancies(lst: Reversible) -> list:
"""Used instead of ``list(set(l))`` to maintain order.
Keeps the last occurrence of each element.
"""
reversed_result = []
used = set()
for x in reversed(lst):
if x not in used:
reversed_result.append(x)
used.add(x)
reversed_result.reverse()
return reversed_result
def remove_nones(sequence: Iterable) -> list:
"""Removes elements where bool(x) evaluates to False.
Examples
--------
Normal usage::
remove_nones(['m', '', 'l', 0, 42, False, True])
# ['m', 'l', 42, True]
"""
# Note this is redundant with it.chain
return [x for x in sequence if x]
def resize_array(nparray: np.ndarray, length: int) -> np.ndarray:
"""Extends/truncates nparray so that ``len(result) == length``.
The elements of nparray are cycled to achieve the desired length.
See Also
--------
resize_preserving_order : favours earlier elements instead of cycling them
make_even_by_cycling : similar cycling behaviour for balancing 2 iterables
Examples
--------
Normal usage::
>>> points = np.array([[1, 2], [3, 4]])
>>> resize_array(points, 1)
array([[1, 2]])
>>> resize_array(points, 3)
array([[1, 2],
[3, 4],
[1, 2]])
>>> resize_array(points, 2)
array([[1, 2],
[3, 4]])
"""
if len(nparray) == length:
return nparray
return np.resize(nparray, (length, *nparray.shape[1:]))
def resize_preserving_order(nparray: np.ndarray, length: int) -> np.ndarray:
"""Extends/truncates nparray so that ``len(result) == length``.
The elements of nparray are duplicated to achieve the desired length
(favours earlier elements).
Constructs a zeroes array of length if nparray is empty.
See Also
--------
resize_array : cycles elements instead of favouring earlier ones
make_even : similar earlier-favouring behaviour for balancing 2 iterables
Examples
--------
Normal usage::
resize_preserving_order(np.array([]), 5)
# np.array([0., 0., 0., 0., 0.])
nparray = np.array([[1, 2],
[3, 4]])
resize_preserving_order(nparray, 1)
# np.array([[1, 2]])
resize_preserving_order(nparray, 3)
# np.array([[1, 2],
# [1, 2],
# [3, 4]])
"""
if len(nparray) == 0:
return np.zeros((length, *nparray.shape[1:]))
if len(nparray) == length:
return nparray
indices = np.arange(length) * len(nparray) // length
return nparray[indices]
def resize_with_interpolation(nparray: np.ndarray, length: int) -> np.ndarray:
"""Extends/truncates nparray so that ``len(result) == length``.
New elements are interpolated to achieve the desired length.
Note that if nparray's length changes, its dtype may too
(e.g. int -> float: see Examples)
See Also
--------
resize_array : cycles elements instead of interpolating
resize_preserving_order : favours earlier elements instead of interpolating
Examples
--------
Normal usage::
nparray = np.array([[1, 2],
[3, 4]])
resize_with_interpolation(nparray, 1)
# np.array([[1., 2.]])
resize_with_interpolation(nparray, 4)
# np.array([[1. , 2. ],
# [1.66666667, 2.66666667],
# [2.33333333, 3.33333333],
# [3. , 4. ]])
nparray = np.array([[[1, 2],[3, 4]]])
resize_with_interpolation(nparray, 3)
# np.array([[[1., 2.], [3., 4.]],
# [[1., 2.], [3., 4.]],
# [[1., 2.], [3., 4.]]])
nparray = np.array([[1, 2], [3, 4], [5, 6]])
resize_with_interpolation(nparray, 4)
# np.array([[1. , 2. ],
# [2.33333333, 3.33333333],
# [3.66666667, 4.66666667],
# [5. , 6. ]])
nparray = np.array([[1, 2], [3, 4], [1, 2]])
resize_with_interpolation(nparray, 4)
# np.array([[1. , 2. ],
# [2.33333333, 3.33333333],
# [2.33333333, 3.33333333],
# [1. , 2. ]])
"""
if len(nparray) == length:
return nparray
cont_indices = np.linspace(0, len(nparray) - 1, length)
return np.array(
[
(1 - a) * nparray[lh] + a * nparray[rh]
for ci in cont_indices
for lh, rh, a in [(int(ci), int(np.ceil(ci)), ci % 1)]
],
)
def stretch_array_to_length(nparray: np.ndarray, length: int) -> np.ndarray:
# todo: is this the same as resize_preserving_order()?
curr_len = len(nparray)
if curr_len > length:
raise Warning("Trying to stretch array to a length shorter than its own")
indices = np.arange(length) / float(length)
indices *= curr_len
return nparray[indices.astype(int)]
def tuplify(obj) -> tuple:
"""Converts obj to a tuple intelligently.
Examples
--------
Normal usage::
tuplify('str') # ('str',)
tuplify([1, 2]) # (1, 2)
tuplify(len) # (<built-in function len>,)
"""
if isinstance(obj, str):
return (obj,)
try:
return tuple(obj)
except TypeError:
return (obj,)
def uniq_chain(*args: Iterable) -> Generator:
"""Returns a generator that yields all unique elements of the Iterables
provided via args in the order provided.
Examples
--------
Normal usage::
uniq_chain([1, 2], [2, 3], [1, 4, 4])
# yields 1, 2, 3, 4
"""
unique_items = set()
for x in it.chain(*args):
if x in unique_items:
continue
unique_items.add(x)
yield x
def hash_obj(obj: object) -> int:
"""Determines a hash, even of potentially mutable objects."""
if isinstance(obj, dict):
return hash(tuple(sorted((hash_obj(k), hash_obj(v)) for k, v in obj.items())))
if isinstance(obj, set):
return hash(tuple(sorted(hash_obj(e) for e in obj)))
if isinstance(obj, (tuple, list)):
return hash(tuple(hash_obj(e) for e in obj))
return hash(obj)
|
manim_ManimCommunity/manim/utils/caching.py
|
from __future__ import annotations
from typing import Callable
from .. import config, logger
from ..utils.hashing import get_hash_from_play_call
__all__ = ["handle_caching_play"]
def handle_caching_play(func: Callable[..., None]):
"""Decorator that returns a wrapped version of func that will compute
the hash of the play invocation.
The returned function will act according to the computed hash: either skip
the animation because it's already cached, or let the invoked function
play normally.
Parameters
----------
func
The play like function that has to be written to the video file stream.
Take the same parameters as `scene.play`.
"""
# NOTE : This is only kept for OpenGL renderer.
# The play logic of the cairo renderer as been refactored and does not need this function anymore.
# When OpenGL renderer will have a proper testing system,
# the play logic of the latter has to be refactored in the same way the cairo renderer has been, and thus this
# method has to be deleted.
def wrapper(self, scene, *args, **kwargs):
self.skip_animations = self._original_skipping_status
self.update_skipping_status()
animations = scene.compile_animations(*args, **kwargs)
scene.add_mobjects_from_animations(animations)
if self.skip_animations:
logger.debug(f"Skipping animation {self.num_plays}")
func(self, scene, *args, **kwargs)
# If the animation is skipped, we mark its hash as None.
# When sceneFileWriter will start combining partial movie files, it won't take into account None hashes.
self.animations_hashes.append(None)
self.file_writer.add_partial_movie_file(None)
return
if not config["disable_caching"]:
mobjects_on_scene = scene.mobjects
hash_play = get_hash_from_play_call(
self,
self.camera,
animations,
mobjects_on_scene,
)
if self.file_writer.is_already_cached(hash_play):
logger.info(
f"Animation {self.num_plays} : Using cached data (hash : %(hash_play)s)",
{"hash_play": hash_play},
)
self.skip_animations = True
else:
hash_play = f"uncached_{self.num_plays:05}"
self.animations_hashes.append(hash_play)
self.file_writer.add_partial_movie_file(hash_play)
logger.debug(
"List of the first few animation hashes of the scene: %(h)s",
{"h": str(self.animations_hashes[:5])},
)
func(self, scene, *args, **kwargs)
return wrapper
|
manim_ManimCommunity/manim/utils/opengl.py
|
from __future__ import annotations
import numpy as np
import numpy.linalg as linalg
from .. import config
depth = 20
__all__ = [
"matrix_to_shader_input",
"orthographic_projection_matrix",
"perspective_projection_matrix",
"translation_matrix",
"x_rotation_matrix",
"y_rotation_matrix",
"z_rotation_matrix",
"rotate_in_place_matrix",
"rotation_matrix",
"scale_matrix",
"view_matrix",
]
def matrix_to_shader_input(matrix):
return tuple(matrix.T.ravel())
def orthographic_projection_matrix(
width=None,
height=None,
near=1,
far=depth + 1,
format=True,
):
if width is None:
width = config["frame_width"]
if height is None:
height = config["frame_height"]
projection_matrix = np.array(
[
[2 / width, 0, 0, 0],
[0, 2 / height, 0, 0],
[0, 0, -2 / (far - near), -(far + near) / (far - near)],
[0, 0, 0, 1],
],
)
if format:
return matrix_to_shader_input(projection_matrix)
else:
return projection_matrix
def perspective_projection_matrix(width=None, height=None, near=2, far=50, format=True):
if width is None:
width = config["frame_width"] / 6
if height is None:
height = config["frame_height"] / 6
projection_matrix = np.array(
[
[2 * near / width, 0, 0, 0],
[0, 2 * near / height, 0, 0],
[0, 0, (far + near) / (near - far), (2 * far * near) / (near - far)],
[0, 0, -1, 0],
],
)
if format:
return matrix_to_shader_input(projection_matrix)
else:
return projection_matrix
def translation_matrix(x=0, y=0, z=0):
return np.array(
[
[1, 0, 0, x],
[0, 1, 0, y],
[0, 0, 1, z],
[0, 0, 0, 1],
],
)
def x_rotation_matrix(x=0):
return np.array(
[
[1, 0, 0, 0],
[0, np.cos(x), -np.sin(x), 0],
[0, np.sin(x), np.cos(x), 0],
[0, 0, 0, 1],
],
)
def y_rotation_matrix(y=0):
return np.array(
[
[np.cos(y), 0, np.sin(y), 0],
[0, 1, 0, 0],
[-np.sin(y), 0, np.cos(y), 0],
[0, 0, 0, 1],
],
)
def z_rotation_matrix(z=0):
return np.array(
[
[np.cos(z), -np.sin(z), 0, 0],
[np.sin(z), np.cos(z), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
],
)
# TODO: When rotating around the x axis, rotation eventually stops.
def rotate_in_place_matrix(initial_position, x=0, y=0, z=0):
return np.matmul(
translation_matrix(*-initial_position),
np.matmul(
rotation_matrix(x, y, z),
translation_matrix(*initial_position),
),
)
def rotation_matrix(x=0, y=0, z=0):
return np.matmul(
np.matmul(x_rotation_matrix(x), y_rotation_matrix(y)),
z_rotation_matrix(z),
)
def scale_matrix(scale_factor=1):
return np.array(
[
[scale_factor, 0, 0, 0],
[0, scale_factor, 0, 0],
[0, 0, scale_factor, 0],
[0, 0, 0, 1],
],
)
def view_matrix(
translation=None,
x_rotation=0,
y_rotation=0,
z_rotation=0,
):
if translation is None:
translation = np.array([0, 0, depth / 2 + 1])
model_matrix = np.matmul(
np.matmul(
translation_matrix(*translation),
rotation_matrix(x=x_rotation, y=y_rotation, z=z_rotation),
),
scale_matrix(),
)
return tuple(linalg.inv(model_matrix).T.ravel())
|
manim_ManimCommunity/manim/utils/simple_functions.py
|
"""A collection of simple functions."""
from __future__ import annotations
__all__ = [
"binary_search",
"choose",
"clip",
"sigmoid",
]
import inspect
from functools import lru_cache
from types import MappingProxyType
from typing import Callable
import numpy as np
from scipy import special
def binary_search(
function: Callable[[int | float], int | float],
target: int | float,
lower_bound: int | float,
upper_bound: int | float,
tolerance: int | float = 1e-4,
) -> int | float | None:
"""Searches for a value in a range by repeatedly dividing the range in half.
To be more precise, performs numerical binary search to determine the
input to ``function``, between the bounds given, that outputs ``target``
to within ``tolerance`` (default of 0.0001).
Returns ``None`` if no input can be found within the bounds.
Examples
--------
Consider the polynomial :math:`x^2 + 3x + 1` where we search for
a target value of :math:`11`. An exact solution is :math:`x = 2`.
::
>>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5)
>>> abs(solution - 2) < 1e-4
True
>>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5, tolerance=0.01)
>>> abs(solution - 2) < 0.01
True
Searching in the interval :math:`[0, 5]` for a target value of :math:`71`
does not yield a solution::
>>> binary_search(lambda x: x**2 + 3*x + 1, 71, 0, 5) is None
True
"""
lh = lower_bound
rh = upper_bound
mh = np.mean(np.array([lh, rh]))
while abs(rh - lh) > tolerance:
mh = np.mean(np.array([lh, rh]))
lx, mx, rx = (function(h) for h in (lh, mh, rh))
if lx == target:
return lh
if rx == target:
return rh
if lx <= target <= rx:
if mx > target:
rh = mh
else:
lh = mh
elif lx > target > rx:
lh, rh = rh, lh
else:
return None
return mh
@lru_cache(maxsize=10)
def choose(n: int, k: int) -> int:
r"""The binomial coefficient n choose k.
:math:`\binom{n}{k}` describes the number of possible choices of
:math:`k` elements from a set of :math:`n` elements.
References
----------
- https://en.wikipedia.org/wiki/Combination
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.comb.html
"""
return special.comb(n, k, exact=True)
def clip(a, min_a, max_a):
"""Clips ``a`` to the interval [``min_a``, ``max_a``].
Accepts any comparable objects (i.e. those that support <, >).
Returns ``a`` if it is between ``min_a`` and ``max_a``.
Otherwise, whichever of ``min_a`` and ``max_a`` is closest.
Examples
--------
::
>>> clip(15, 11, 20)
15
>>> clip('a', 'h', 'k')
'h'
"""
if a < min_a:
return min_a
elif a > max_a:
return max_a
return a
def sigmoid(x: float) -> float:
r"""Returns the output of the logistic function.
The logistic function, a common example of a sigmoid function, is defined
as :math:`\frac{1}{1 + e^{-x}}`.
References
----------
- https://en.wikipedia.org/wiki/Sigmoid_function
- https://en.wikipedia.org/wiki/Logistic_function
"""
return 1.0 / (1 + np.exp(-x))
|
manim_ManimCommunity/manim/utils/config_ops.py
|
"""Utilities that might be useful for configuration dictionaries."""
from __future__ import annotations
__all__ = [
"merge_dicts_recursively",
"update_dict_recursively",
"DictAsObject",
]
import itertools as it
import numpy as np
def merge_dicts_recursively(*dicts):
"""
Creates a dict whose keyset is the union of all the
input dictionaries. The value for each key is based
on the first dict in the list with that key.
dicts later in the list have higher priority
When values are dictionaries, it is applied recursively
"""
result = {}
all_items = it.chain(*(d.items() for d in dicts))
for key, value in all_items:
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = merge_dicts_recursively(result[key], value)
else:
result[key] = value
return result
def update_dict_recursively(current_dict, *others):
updated_dict = merge_dicts_recursively(current_dict, *others)
current_dict.update(updated_dict)
# Occasionally convenient in order to write dict.x instead of more laborious
# (and less in keeping with all other attr accesses) dict["x"]
class DictAsObject:
def __init__(self, dictin):
self.__dict__ = dictin
class _Data:
"""Descriptor that allows _Data variables to be grouped and accessed from self.data["attr"] via self.attr.
self.data attributes must be arrays.
"""
def __set_name__(self, obj, name):
self.name = name
def __get__(self, obj, owner):
return obj.data[self.name]
def __set__(self, obj, array: np.ndarray):
obj.data[self.name] = array
class _Uniforms:
"""Descriptor that allows _Uniforms variables to be grouped from self.uniforms["attr"] via self.attr.
self.uniforms attributes must be floats.
"""
def __set_name__(self, obj, name):
self.name = name
def __get__(self, obj, owner):
return obj.__dict__["uniforms"][self.name]
def __set__(self, obj, num: float):
obj.__dict__["uniforms"][self.name] = num
|
manim_ManimCommunity/manim/utils/module_ops.py
|
from __future__ import annotations
import importlib.util
import inspect
import os
import re
import sys
import types
import warnings
from pathlib import Path
from .. import config, console, constants, logger
from ..scene.scene_file_writer import SceneFileWriter
__all__ = ["scene_classes_from_file"]
def get_module(file_name: Path):
if str(file_name) == "-":
module = types.ModuleType("input_scenes")
logger.info(
"Enter the animation's code & end with an EOF (CTRL+D on Linux/Unix, CTRL+Z on Windows):",
)
code = sys.stdin.read()
if not code.startswith("from manim import"):
logger.warning(
"Didn't find an import statement for Manim. Importing automatically...",
)
code = "from manim import *\n" + code
logger.info("Rendering animation from typed code...")
try:
exec(code, module.__dict__)
return module
except Exception as e:
logger.error(f"Failed to render scene: {str(e)}")
sys.exit(2)
else:
if file_name.exists():
ext = file_name.suffix
if ext != ".py":
raise ValueError(f"{file_name} is not a valid Manim python script.")
module_name = ".".join(file_name.with_suffix("").parts)
warnings.filterwarnings(
"default",
category=DeprecationWarning,
module=module_name,
)
spec = importlib.util.spec_from_file_location(module_name, file_name)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
sys.path.insert(0, str(file_name.parent.absolute()))
spec.loader.exec_module(module)
return module
else:
raise FileNotFoundError(f"{file_name} not found")
def get_scene_classes_from_module(module):
from ..scene.scene import Scene
def is_child_scene(obj, module):
return (
inspect.isclass(obj)
and issubclass(obj, Scene)
and obj != Scene
and obj.__module__.startswith(module.__name__)
)
return [
member[1]
for member in inspect.getmembers(module, lambda x: is_child_scene(x, module))
]
def get_scenes_to_render(scene_classes):
if not scene_classes:
logger.error(constants.NO_SCENE_MESSAGE)
return []
if config["write_all"]:
return scene_classes
result = []
for scene_name in config["scene_names"]:
found = False
for scene_class in scene_classes:
if scene_class.__name__ == scene_name:
result.append(scene_class)
found = True
break
if not found and (scene_name != ""):
logger.error(constants.SCENE_NOT_FOUND_MESSAGE.format(scene_name))
if result:
return result
if len(scene_classes) == 1:
config["scene_names"] = [scene_classes[0].__name__]
return [scene_classes[0]]
return prompt_user_for_choice(scene_classes)
def prompt_user_for_choice(scene_classes):
num_to_class = {}
SceneFileWriter.force_output_as_scene_name = True
for count, scene_class in enumerate(scene_classes, 1):
name = scene_class.__name__
console.print(f"{count}: {name}", style="logging.level.info")
num_to_class[count] = scene_class
try:
user_input = console.input(
f"[log.message] {constants.CHOOSE_NUMBER_MESSAGE} [/log.message]",
)
scene_classes = [
num_to_class[int(num_str)]
for num_str in re.split(r"\s*,\s*", user_input.strip())
]
config["scene_names"] = [scene_class.__name__ for scene_class in scene_classes]
return scene_classes
except KeyError:
logger.error(constants.INVALID_NUMBER_MESSAGE)
sys.exit(2)
except EOFError:
sys.exit(1)
except ValueError:
logger.error("No scenes were selected. Exiting.")
sys.exit(1)
def scene_classes_from_file(
file_path: Path, require_single_scene=False, full_list=False
):
module = get_module(file_path)
all_scene_classes = get_scene_classes_from_module(module)
if full_list:
return all_scene_classes
scene_classes_to_render = get_scenes_to_render(all_scene_classes)
if require_single_scene:
assert len(scene_classes_to_render) == 1
return scene_classes_to_render[0]
return scene_classes_to_render
|
manim_ManimCommunity/manim/utils/tex_templates.py
|
"""A library of LaTeX templates."""
from __future__ import annotations
__all__ = [
"TexTemplateLibrary",
"TexFontTemplates",
]
from .tex import *
# This file makes TexTemplateLibrary and TexFontTemplates available for use in manim Tex and MathTex objects.
def _new_ams_template():
"""Returns a simple Tex Template with only basic AMS packages"""
preamble = r"""
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
"""
return TexTemplate(preamble=preamble)
""" Tex Template preamble used by original upstream 3b1b """
_3b1b_preamble = r"""
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{dsfont}
\usepackage{setspace}
\usepackage{tipa}
\usepackage{relsize}
\usepackage{textcomp}
\usepackage{mathrsfs}
\usepackage{calligra}
\usepackage{wasysym}
\usepackage{ragged2e}
\usepackage{physics}
\usepackage{xcolor}
\usepackage{microtype}
\DisableLigatures{encoding = *, family = * }
\linespread{1}
"""
# TexTemplateLibrary
#
class TexTemplateLibrary:
"""
A collection of basic TeX template objects
Examples
--------
Normal usage as a value for the keyword argument tex_template of Tex() and MathTex() mobjects::
``Tex("My TeX code", tex_template=TexTemplateLibrary.ctex)``
"""
default = TexTemplate(preamble=_3b1b_preamble)
"""An instance of the default TeX template in manim"""
threeb1b = TexTemplate(preamble=_3b1b_preamble)
""" An instance of the default TeX template used by 3b1b """
ctex = TexTemplate(
tex_compiler="xelatex",
output_format=".xdv",
preamble=_3b1b_preamble.replace(
r"\DisableLigatures{encoding = *, family = * }",
r"\usepackage[UTF8]{ctex}",
),
)
"""An instance of the TeX template used by 3b1b when using the use_ctex flag"""
simple = _new_ams_template()
"""An instance of a simple TeX template with only basic AMS packages loaded"""
# TexFontTemplates
#
# TexFontTemplates takes a font_id and returns the appropriate TexTemplate()
# Usage:
# my_tex_template = TexFontTemplates.font_id
#
# Note: not all of these will work out-of-the-box.
# They may require specific fonts to be installed on the local system.
# For example TexFontTemplates.comic_sans will only work if the Microsoft font 'Comic Sans'
# is installed on the local system.
#
# More information on these templates, along with example output can be found at
# http://jf.burnol.free.fr/showcase.html"
#
#
# Choices for font_id are:
#
# american_typewriter : "American Typewriter"
# antykwa : "Antykwa Półtawskiego (TX Fonts for Greek and math symbols)"
# apple_chancery : "Apple Chancery"
# auriocus_kalligraphicus : "Auriocus Kalligraphicus (Symbol Greek)"
# baskervald_adf_fourier : "Baskervald ADF with Fourier"
# baskerville_it : "Baskerville (Italic)"
# biolinum : "Biolinum"
# brushscriptx : "BrushScriptX-Italic (PX math and Greek)"
# chalkboard_se : "Chalkboard SE"
# chalkduster : "Chalkduster"
# comfortaa : "Comfortaa"
# comic_sans : "Comic Sans MS"
# droid_sans : "Droid Sans"
# droid_sans_it : "Droid Sans (Italic)"
# droid_serif : "Droid Serif"
# droid_serif_px_it : "Droid Serif (PX math symbols) (Italic)"
# ecf_augie : "ECF Augie (Euler Greek)"
# ecf_jd : "ECF JD (with TX fonts)"
# ecf_skeetch : "ECF Skeetch (CM Greek)"
# ecf_tall_paul : "ECF Tall Paul (with Symbol font)"
# ecf_webster : "ECF Webster (with TX fonts)"
# electrum_adf : "Electrum ADF (CM Greek)"
# epigrafica : Epigrafica
# fourier_utopia : "Fourier Utopia (Fourier upright Greek)"
# french_cursive : "French Cursive (Euler Greek)"
# gfs_bodoni : "GFS Bodoni"
# gfs_didot : "GFS Didot (Italic)"
# gfs_neoHellenic : "GFS NeoHellenic"
# gnu_freesans_tx : "GNU FreeSerif (and TX fonts symbols)"
# gnu_freeserif_freesans : "GNU FreeSerif and FreeSans"
# helvetica_fourier_it : "Helvetica with Fourier (Italic)"
# latin_modern_tw_it : "Latin Modern Typewriter Proportional (CM Greek) (Italic)"
# latin_modern_tw : "Latin Modern Typewriter Proportional"
# libertine : "Libertine"
# libris_adf_fourier : "Libris ADF with Fourier"
# minion_pro_myriad_pro : "Minion Pro and Myriad Pro (and TX fonts symbols)"
# minion_pro_tx : "Minion Pro (and TX fonts symbols)"
# new_century_schoolbook : "New Century Schoolbook (Symbol Greek)"
# new_century_schoolbook_px : "New Century Schoolbook (Symbol Greek, PX math symbols)"
# noteworthy_light : "Noteworthy Light"
# palatino : "Palatino (Symbol Greek)"
# papyrus : "Papyrus"
# romande_adf_fourier_it : "Romande ADF with Fourier (Italic)"
# slitex : "SliTeX (Euler Greek)"
# times_fourier_it : "Times with Fourier (Italic)"
# urw_avant_garde : "URW Avant Garde (Symbol Greek)"
# urw_zapf_chancery : "URW Zapf Chancery (CM Greek)"
# venturis_adf_fourier_it : "Venturis ADF with Fourier (Italic)"
# verdana_it : "Verdana (Italic)"
# vollkorn_fourier_it : "Vollkorn with Fourier (Italic)"
# vollkorn : "Vollkorn (TX fonts for Greek and math symbols)"
# zapf_chancery : "Zapf Chancery"
# -----------------------------------------------------------------------------------------
#
#
#
#
#
#
#
#
#
#
# Latin Modern Typewriter Proportional
lmtp = _new_ams_template()
lmtp.description = "Latin Modern Typewriter Proportional"
lmtp.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[variablett]{lmodern}
\renewcommand{\rmdefault}{\ttdefault}
\usepackage[LGRgreek]{mathastext}
\MTgreekfont{lmtt} % no lgr lmvtt, so use lgr lmtt
\Mathastext
\let\varepsilon\epsilon % only \varsigma in LGR
""",
)
# Fourier Utopia (Fourier upright Greek)
fufug = _new_ams_template()
fufug.description = "Fourier Utopia (Fourier upright Greek)"
fufug.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[upright]{fourier}
\usepackage{mathastext}
""",
)
# Droid Serif
droidserif = _new_ams_template()
droidserif.description = "Droid Serif"
droidserif.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[default]{droidserif}
\usepackage[LGRgreek]{mathastext}
\let\varepsilon\epsilon
""",
)
# Droid Sans
droidsans = _new_ams_template()
droidsans.description = "Droid Sans"
droidsans.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[default]{droidsans}
\usepackage[LGRgreek]{mathastext}
\let\varepsilon\epsilon
""",
)
# New Century Schoolbook (Symbol Greek)
ncssg = _new_ams_template()
ncssg.description = "New Century Schoolbook (Symbol Greek)"
ncssg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{newcent}
\usepackage[symbolgreek]{mathastext}
\linespread{1.1}
""",
)
# French Cursive (Euler Greek)
fceg = _new_ams_template()
fceg.description = "French Cursive (Euler Greek)"
fceg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[default]{frcursive}
\usepackage[eulergreek,noplusnominus,noequal,nohbar,%
nolessnomore,noasterisk]{mathastext}
""",
)
# Auriocus Kalligraphicus (Symbol Greek)
aksg = _new_ams_template()
aksg.description = "Auriocus Kalligraphicus (Symbol Greek)"
aksg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{aurical}
\renewcommand{\rmdefault}{AuriocusKalligraphicus}
\usepackage[symbolgreek]{mathastext}
""",
)
# Palatino (Symbol Greek)
palatinosg = _new_ams_template()
palatinosg.description = "Palatino (Symbol Greek)"
palatinosg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{palatino}
\usepackage[symbolmax,defaultmathsizes]{mathastext}
""",
)
# Comfortaa
comfortaa = _new_ams_template()
comfortaa.description = "Comfortaa"
comfortaa.add_to_preamble(
r"""
\usepackage[default]{comfortaa}
\usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext}
\let\varphi\phi
\linespread{1.06}
""",
)
# ECF Augie (Euler Greek)
ecfaugieeg = _new_ams_template()
ecfaugieeg.description = "ECF Augie (Euler Greek)"
ecfaugieeg.add_to_preamble(
r"""
\renewcommand\familydefault{fau} % emerald package
\usepackage[defaultmathsizes,eulergreek]{mathastext}
""",
)
# Electrum ADF (CM Greek)
electrumadfcm = _new_ams_template()
electrumadfcm.description = "Electrum ADF (CM Greek)"
electrumadfcm.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[LGRgreek,basic,defaultmathsizes]{mathastext}
\usepackage[lf]{electrum}
\Mathastext
\let\varphi\phi
""",
)
# American Typewriter
americantypewriter = _new_ams_template()
americantypewriter.description = "American Typewriter"
americantypewriter.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{American Typewriter}
\usepackage[defaultmathsizes]{mathastext}
""",
)
americantypewriter.tex_compiler = "xelatex"
americantypewriter.output_format = ".xdv"
# Minion Pro and Myriad Pro (and TX fonts symbols)
mpmptx = _new_ams_template()
mpmptx.description = "Minion Pro and Myriad Pro (and TX fonts symbols)"
mpmptx.add_to_preamble(
r"""
\usepackage{txfonts}
\usepackage[upright]{txgreeks}
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Minion Pro}
\setsansfont[Mapping=tex-text,Scale=MatchUppercase]{Myriad Pro}
\renewcommand\familydefault\sfdefault
\usepackage[defaultmathsizes]{mathastext}
\renewcommand\familydefault\rmdefault
""",
)
mpmptx.tex_compiler = "xelatex"
mpmptx.output_format = ".xdv"
# New Century Schoolbook (Symbol Greek, PX math symbols)
ncssgpxm = _new_ams_template()
ncssgpxm.description = "New Century Schoolbook (Symbol Greek, PX math symbols)"
ncssgpxm.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{pxfonts}
\usepackage{newcent}
\usepackage[symbolgreek,defaultmathsizes]{mathastext}
\linespread{1.06}
""",
)
# Vollkorn (TX fonts for Greek and math symbols)
vollkorntx = _new_ams_template()
vollkorntx.description = "Vollkorn (TX fonts for Greek and math symbols)"
vollkorntx.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{txfonts}
\usepackage[upright]{txgreeks}
\usepackage{vollkorn}
\usepackage[defaultmathsizes]{mathastext}
""",
)
# Libertine
libertine = _new_ams_template()
libertine.description = "Libertine"
libertine.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{libertine}
\usepackage[greek=n]{libgreek}
\usepackage[noasterisk,defaultmathsizes]{mathastext}
""",
)
# SliTeX (Euler Greek)
slitexeg = _new_ams_template()
slitexeg.description = "SliTeX (Euler Greek)"
slitexeg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{tpslifonts}
\usepackage[eulergreek,defaultmathsizes]{mathastext}
\MTEulerScale{1.06}
\linespread{1.2}
""",
)
# ECF Webster (with TX fonts)
ecfwebstertx = _new_ams_template()
ecfwebstertx.description = "ECF Webster (with TX fonts)"
ecfwebstertx.add_to_preamble(
r"""
\usepackage{txfonts}
\usepackage[upright]{txgreeks}
\renewcommand\familydefault{fwb} % emerald package
\usepackage{mathastext}
\renewcommand{\int}{\intop\limits}
\linespread{1.5}
""",
)
ecfwebstertx.add_to_document(
r"""
\mathversion{bold}
""",
)
# Romande ADF with Fourier (Italic)
italicromandeadff = _new_ams_template()
italicromandeadff.description = "Romande ADF with Fourier (Italic)"
italicromandeadff.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{fourier}
\usepackage{romande}
\usepackage[italic,defaultmathsizes,noasterisk]{mathastext}
\renewcommand{\itshape}{\swashstyle}
""",
)
# Apple Chancery
applechancery = _new_ams_template()
applechancery.description = "Apple Chancery"
applechancery.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Apple Chancery}
\usepackage[defaultmathsizes]{mathastext}
""",
)
applechancery.tex_compiler = "xelatex"
applechancery.output_format = ".xdv"
# Zapf Chancery
zapfchancery = _new_ams_template()
zapfchancery.description = "Zapf Chancery"
zapfchancery.add_to_preamble(
r"""
\DeclareFontFamily{T1}{pzc}{}
\DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{}
\DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{}
\usepackage{chancery} % = \renewcommand{\rmdefault}{pzc}
\renewcommand\shapedefault\itdefault
\renewcommand\bfdefault\mddefault
\usepackage[defaultmathsizes]{mathastext}
\linespread{1.05}
""",
)
# Verdana (Italic)
italicverdana = _new_ams_template()
italicverdana.description = "Verdana (Italic)"
italicverdana.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Verdana}
\usepackage[defaultmathsizes,italic]{mathastext}
""",
)
italicverdana.tex_compiler = "xelatex"
italicverdana.output_format = ".xdv"
# URW Zapf Chancery (CM Greek)
urwzccmg = _new_ams_template()
urwzccmg.description = "URW Zapf Chancery (CM Greek)"
urwzccmg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\DeclareFontFamily{T1}{pzc}{}
\DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{}
\DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{}
\DeclareFontShape{T1}{pzc}{mb}{sl}{<->ssub * pzc/mb/it}{}
\DeclareFontShape{T1}{pzc}{m}{sl}{<->ssub * pzc/mb/sl}{}
\DeclareFontShape{T1}{pzc}{m}{n}{<->ssub * pzc/mb/it}{}
\usepackage{chancery}
\usepackage{mathastext}
\linespread{1.05}""",
)
urwzccmg.add_to_document(
r"""
\boldmath
""",
)
# Comic Sans MS
comicsansms = _new_ams_template()
comicsansms.description = "Comic Sans MS"
comicsansms.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Comic Sans MS}
\usepackage[defaultmathsizes]{mathastext}
""",
)
comicsansms.tex_compiler = "xelatex"
comicsansms.output_format = ".xdv"
# GFS Didot (Italic)
italicgfsdidot = _new_ams_template()
italicgfsdidot.description = "GFS Didot (Italic)"
italicgfsdidot.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\renewcommand\rmdefault{udidot}
\usepackage[LGRgreek,defaultmathsizes,italic]{mathastext}
\let\varphi\phi
""",
)
# Chalkduster
chalkduster = _new_ams_template()
chalkduster.description = "Chalkduster"
chalkduster.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Chalkduster}
\usepackage[defaultmathsizes]{mathastext}
""",
)
chalkduster.tex_compiler = "lualatex"
chalkduster.output_format = ".pdf"
# Minion Pro (and TX fonts symbols)
mptx = _new_ams_template()
mptx.description = "Minion Pro (and TX fonts symbols)"
mptx.add_to_preamble(
r"""
\usepackage{txfonts}
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Minion Pro}
\usepackage[defaultmathsizes]{mathastext}
""",
)
mptx.tex_compiler = "xelatex"
mptx.output_format = ".xdv"
# GNU FreeSerif and FreeSans
gnufsfs = _new_ams_template()
gnufsfs.description = "GNU FreeSerif and FreeSans"
gnufsfs.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[ExternalLocation,
Mapping=tex-text,
BoldFont=FreeSerifBold,
ItalicFont=FreeSerifItalic,
BoldItalicFont=FreeSerifBoldItalic]{FreeSerif}
\setsansfont[ExternalLocation,
Mapping=tex-text,
BoldFont=FreeSansBold,
ItalicFont=FreeSansOblique,
BoldItalicFont=FreeSansBoldOblique,
Scale=MatchLowercase]{FreeSans}
\renewcommand{\familydefault}{lmss}
\usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext}
\renewcommand{\familydefault}{\sfdefault}
\Mathastext
\let\varphi\phi % no `var' phi in LGR encoding
\renewcommand{\familydefault}{\rmdefault}
""",
)
gnufsfs.tex_compiler = "xelatex"
gnufsfs.output_format = ".xdv"
# GFS NeoHellenic
gfsneohellenic = _new_ams_template()
gfsneohellenic.description = "GFS NeoHellenic"
gfsneohellenic.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\renewcommand{\rmdefault}{neohellenic}
\usepackage[LGRgreek]{mathastext}
\let\varphi\phi
\linespread{1.06}
""",
)
# ECF Tall Paul (with Symbol font)
ecftallpaul = _new_ams_template()
ecftallpaul.description = "ECF Tall Paul (with Symbol font)"
ecftallpaul.add_to_preamble(
r"""
\DeclareFontFamily{T1}{ftp}{}
\DeclareFontShape{T1}{ftp}{m}{n}{
<->s*[1.4] ftpmw8t
}{} % increase size by factor 1.4
\renewcommand\familydefault{ftp} % emerald package
\usepackage[symbol]{mathastext}
\let\infty\inftypsy
""",
)
# Droid Sans (Italic)
italicdroidsans = _new_ams_template()
italicdroidsans.description = "Droid Sans (Italic)"
italicdroidsans.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[default]{droidsans}
\usepackage[LGRgreek,defaultmathsizes,italic]{mathastext}
\let\varphi\phi
""",
)
# Baskerville (Italic)
italicbaskerville = _new_ams_template()
italicbaskerville.description = "Baskerville (Italic)"
italicbaskerville.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Baskerville}
\usepackage[defaultmathsizes,italic]{mathastext}
""",
)
italicbaskerville.tex_compiler = "xelatex"
italicbaskerville.output_format = ".xdv"
# ECF JD (with TX fonts)
ecfjdtx = _new_ams_template()
ecfjdtx.description = "ECF JD (with TX fonts)"
ecfjdtx.add_to_preamble(
r"""
\usepackage{txfonts}
\usepackage[upright]{txgreeks}
\renewcommand\familydefault{fjd} % emerald package
\usepackage{mathastext}
""",
)
ecfjdtx.add_to_document(
r"""\mathversion{bold}
""",
)
# Antykwa Półtawskiego (TX Fonts for Greek and math symbols)
aptxgm = _new_ams_template()
aptxgm.description = "Antykwa Półtawskiego (TX Fonts for Greek and math symbols)"
aptxgm.add_to_preamble(
r"""
\usepackage[OT4,OT1]{fontenc}
\usepackage{txfonts}
\usepackage[upright]{txgreeks}
\usepackage{antpolt}
\usepackage[defaultmathsizes,nolessnomore]{mathastext}
""",
)
# Papyrus
papyrus = _new_ams_template()
papyrus.description = "Papyrus"
papyrus.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Papyrus}
\usepackage[defaultmathsizes]{mathastext}
""",
)
papyrus.tex_compiler = "xelatex"
papyrus.output_format = ".xdv"
# GNU FreeSerif (and TX fonts symbols)
gnufstx = _new_ams_template()
gnufstx.description = "GNU FreeSerif (and TX fonts symbols)"
gnufstx.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\usepackage{txfonts} %\let\mathbb=\varmathbb
\setmainfont[ExternalLocation,
Mapping=tex-text,
BoldFont=FreeSerifBold,
ItalicFont=FreeSerifItalic,
BoldItalicFont=FreeSerifBoldItalic]{FreeSerif}
\usepackage[defaultmathsizes]{mathastext}
""",
)
gnufstx.tex_compiler = "xelatex"
gnufstx.output_format = ".pdf"
# ECF Skeetch (CM Greek)
ecfscmg = _new_ams_template()
ecfscmg.description = "ECF Skeetch (CM Greek)"
ecfscmg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[T1]{fontenc}
\DeclareFontFamily{T1}{fsk}{}
\DeclareFontShape{T1}{fsk}{m}{n}{<->s*[1.315] fskmw8t}{}
\renewcommand\rmdefault{fsk}
\usepackage[noendash,defaultmathsizes,nohbar,defaultimath]{mathastext}
""",
)
# Latin Modern Typewriter Proportional (CM Greek) (Italic)
italiclmtpcm = _new_ams_template()
italiclmtpcm.description = "Latin Modern Typewriter Proportional (CM Greek) (Italic)"
italiclmtpcm.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[variablett,nomath]{lmodern}
\renewcommand{\familydefault}{\ttdefault}
\usepackage[frenchmath]{mathastext}
\linespread{1.08}
""",
)
# Baskervald ADF with Fourier
baskervaldadff = _new_ams_template()
baskervaldadff.description = "Baskervald ADF with Fourier"
baskervaldadff.add_to_preamble(
r"""
\usepackage[upright]{fourier}
\usepackage{baskervald}
\usepackage[defaultmathsizes,noasterisk]{mathastext}
""",
)
# Droid Serif (PX math symbols) (Italic)
italicdroidserifpx = _new_ams_template()
italicdroidserifpx.description = "Droid Serif (PX math symbols) (Italic)"
italicdroidserifpx.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{pxfonts}
\usepackage[default]{droidserif}
\usepackage[LGRgreek,defaultmathsizes,italic,basic]{mathastext}
\let\varphi\phi
""",
)
# Biolinum
biolinum = _new_ams_template()
biolinum.description = "Biolinum"
biolinum.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{libertine}
\renewcommand{\familydefault}{\sfdefault}
\usepackage[greek=n,biolinum]{libgreek}
\usepackage[noasterisk,defaultmathsizes]{mathastext}
""",
)
# Vollkorn with Fourier (Italic)
italicvollkornf = _new_ams_template()
italicvollkornf.description = "Vollkorn with Fourier (Italic)"
italicvollkornf.add_to_preamble(
r"""
\usepackage{fourier}
\usepackage{vollkorn}
\usepackage[italic,nohbar]{mathastext}
""",
)
# Chalkboard SE
chalkboardse = _new_ams_template()
chalkboardse.description = "Chalkboard SE"
chalkboardse.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Chalkboard SE}
\usepackage[defaultmathsizes]{mathastext}
""",
)
chalkboardse.tex_compiler = "xelatex"
chalkboardse.output_format = ".xdv"
# Noteworthy Light
noteworthylight = _new_ams_template()
noteworthylight.description = "Noteworthy Light"
noteworthylight.add_to_preamble(
r"""
\usepackage[no-math]{fontspec}
\setmainfont[Mapping=tex-text]{Noteworthy Light}
\usepackage[defaultmathsizes]{mathastext}
""",
)
# Epigrafica
epigrafica = _new_ams_template()
epigrafica.description = "Epigrafica"
epigrafica.add_to_preamble(
r"""
\usepackage[LGR,OT1]{fontenc}
\usepackage{epigrafica}
\usepackage[basic,LGRgreek,defaultmathsizes]{mathastext}
\let\varphi\phi
\linespread{1.2}
""",
)
# Libris ADF with Fourier
librisadff = _new_ams_template()
librisadff.description = "Libris ADF with Fourier"
librisadff.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[upright]{fourier}
\usepackage{libris}
\renewcommand{\familydefault}{\sfdefault}
\usepackage[noasterisk]{mathastext}
""",
)
# Venturis ADF with Fourier (Italic)
italicvanturisadff = _new_ams_template()
italicvanturisadff.description = "Venturis ADF with Fourier (Italic)"
italicvanturisadff.add_to_preamble(
r"""
\usepackage{fourier}
\usepackage[lf]{venturis}
\usepackage[italic,defaultmathsizes,noasterisk]{mathastext}
""",
)
# GFS Bodoni
gfsbodoni = _new_ams_template()
gfsbodoni.description = "GFS Bodoni"
gfsbodoni.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\renewcommand{\rmdefault}{bodoni}
\usepackage[LGRgreek]{mathastext}
\let\varphi\phi
\linespread{1.06}
""",
)
# BrushScriptX-Italic (PX math and Greek)
brushscriptxpx = _new_ams_template()
brushscriptxpx.description = "BrushScriptX-Italic (PX math and Greek)"
brushscriptxpx.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{pxfonts}
%\usepackage{pbsi}
\renewcommand{\rmdefault}{pbsi}
\renewcommand{\mddefault}{xl}
\renewcommand{\bfdefault}{xl}
\usepackage[defaultmathsizes,noasterisk]{mathastext}
""",
)
brushscriptxpx.add_to_document(
r"""\boldmath
""",
)
brushscriptxpx.tex_compiler = "xelatex"
brushscriptxpx.output_format = ".xdv"
# URW Avant Garde (Symbol Greek)
urwagsg = _new_ams_template()
urwagsg.description = "URW Avant Garde (Symbol Greek)"
urwagsg.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage{avant}
\renewcommand{\familydefault}{\sfdefault}
\usepackage[symbolgreek,defaultmathsizes]{mathastext}
""",
)
# Times with Fourier (Italic)
italictimesf = _new_ams_template()
italictimesf.description = "Times with Fourier (Italic)"
italictimesf.add_to_preamble(
r"""
\usepackage{fourier}
\renewcommand{\rmdefault}{ptm}
\usepackage[italic,defaultmathsizes,noasterisk]{mathastext}
""",
)
# Helvetica with Fourier (Italic)
italichelveticaf = _new_ams_template()
italichelveticaf.description = "Helvetica with Fourier (Italic)"
italichelveticaf.add_to_preamble(
r"""
\usepackage[T1]{fontenc}
\usepackage[scaled]{helvet}
\usepackage{fourier}
\renewcommand{\rmdefault}{phv}
\usepackage[italic,defaultmathsizes,noasterisk]{mathastext}
""",
)
class TexFontTemplates:
"""
A collection of TeX templates for the fonts described at http://jf.burnol.free.fr/showcase.html
These templates are specifically designed to allow you to typeset formulae and mathematics using
different fonts. They are based on the mathastext LaTeX package.
Examples
---------
Normal usage as a value for the keyword argument tex_template of Tex() and MathTex() mobjects::
``Tex("My TeX code", tex_template=TexFontTemplates.comic_sans)``
Notes
------
Many of these templates require that specific fonts
are installed on your local machine.
For example, choosing the template TexFontTemplates.comic_sans will
not compile if the Comic Sans Microsoft font is not installed.
To experiment, try to render the TexFontTemplateLibrary example scene:
``manim path/to/manim/example_scenes/advanced_tex_fonts.py TexFontTemplateLibrary -p -ql``
"""
american_typewriter = americantypewriter
"""American Typewriter"""
antykwa = aptxgm
"""Antykwa Półtawskiego (TX Fonts for Greek and math symbols)"""
apple_chancery = applechancery
"""Apple Chancery"""
auriocus_kalligraphicus = aksg
"""Auriocus Kalligraphicus (Symbol Greek)"""
baskervald_adf_fourier = baskervaldadff
"""Baskervald ADF with Fourier"""
baskerville_it = italicbaskerville
"""Baskerville (Italic)"""
biolinum = biolinum
"""Biolinum"""
brushscriptx = brushscriptxpx
"""BrushScriptX-Italic (PX math and Greek)"""
chalkboard_se = chalkboardse
"""Chalkboard SE"""
chalkduster = chalkduster
"""Chalkduster"""
comfortaa = comfortaa
"""Comfortaa"""
comic_sans = comicsansms
"""Comic Sans MS"""
droid_sans = droidsans
"""Droid Sans"""
droid_sans_it = italicdroidsans
"""Droid Sans (Italic)"""
droid_serif = droidserif
"""Droid Serif"""
droid_serif_px_it = italicdroidserifpx
"""Droid Serif (PX math symbols) (Italic)"""
ecf_augie = ecfaugieeg
"""ECF Augie (Euler Greek)"""
ecf_jd = ecfjdtx
"""ECF JD (with TX fonts)"""
ecf_skeetch = ecfscmg
"""ECF Skeetch (CM Greek)"""
ecf_tall_paul = ecftallpaul
"""ECF Tall Paul (with Symbol font)"""
ecf_webster = ecfwebstertx
"""ECF Webster (with TX fonts)"""
electrum_adf = electrumadfcm
"""Electrum ADF (CM Greek)"""
epigrafica = epigrafica
""" Epigrafica """
fourier_utopia = fufug
"""Fourier Utopia (Fourier upright Greek)"""
french_cursive = fceg
"""French Cursive (Euler Greek)"""
gfs_bodoni = gfsbodoni
"""GFS Bodoni"""
gfs_didot = italicgfsdidot
"""GFS Didot (Italic)"""
gfs_neoHellenic = gfsneohellenic
"""GFS NeoHellenic"""
gnu_freesans_tx = gnufstx
"""GNU FreeSerif (and TX fonts symbols)"""
gnu_freeserif_freesans = gnufsfs
"""GNU FreeSerif and FreeSans"""
helvetica_fourier_it = italichelveticaf
"""Helvetica with Fourier (Italic)"""
latin_modern_tw_it = italiclmtpcm
"""Latin Modern Typewriter Proportional (CM Greek) (Italic)"""
latin_modern_tw = lmtp
"""Latin Modern Typewriter Proportional"""
libertine = libertine
"""Libertine"""
libris_adf_fourier = librisadff
"""Libris ADF with Fourier"""
minion_pro_myriad_pro = mpmptx
"""Minion Pro and Myriad Pro (and TX fonts symbols)"""
minion_pro_tx = mptx
"""Minion Pro (and TX fonts symbols)"""
new_century_schoolbook = ncssg
"""New Century Schoolbook (Symbol Greek)"""
new_century_schoolbook_px = ncssgpxm
"""New Century Schoolbook (Symbol Greek, PX math symbols)"""
noteworthy_light = noteworthylight
"""Noteworthy Light"""
palatino = palatinosg
"""Palatino (Symbol Greek)"""
papyrus = papyrus
"""Papyrus"""
romande_adf_fourier_it = italicromandeadff
"""Romande ADF with Fourier (Italic)"""
slitex = slitexeg
"""SliTeX (Euler Greek)"""
times_fourier_it = italictimesf
"""Times with Fourier (Italic)"""
urw_avant_garde = urwagsg
"""URW Avant Garde (Symbol Greek)"""
urw_zapf_chancery = urwzccmg
"""URW Zapf Chancery (CM Greek)"""
venturis_adf_fourier_it = italicvanturisadff
"""Venturis ADF with Fourier (Italic)"""
verdana_it = italicverdana
"""Verdana (Italic)"""
vollkorn_fourier_it = italicvollkornf
"""Vollkorn with Fourier (Italic)"""
vollkorn = vollkorntx
"""Vollkorn (TX fonts for Greek and math symbols)"""
zapf_chancery = zapfchancery
"""Zapf Chancery"""
|
manim_ManimCommunity/manim/utils/space_ops.py
|
"""Utility functions for two- and three-dimensional vectors."""
from __future__ import annotations
import itertools as it
from typing import TYPE_CHECKING, Sequence
import numpy as np
from mapbox_earcut import triangulate_float32 as earcut
from scipy.spatial.transform import Rotation
from manim.constants import DOWN, OUT, PI, RIGHT, TAU, UP, RendererType
from manim.utils.iterables import adjacent_pairs
if TYPE_CHECKING:
import numpy.typing as npt
from manim.typing import (
ManimFloat,
Point3D_Array,
Vector2D,
Vector2D_Array,
Vector3D,
)
__all__ = [
"quaternion_mult",
"quaternion_from_angle_axis",
"angle_axis_from_quaternion",
"quaternion_conjugate",
"rotate_vector",
"thick_diagonal",
"rotation_matrix",
"rotation_about_z",
"z_to_vector",
"angle_of_vector",
"angle_between_vectors",
"normalize",
"get_unit_normal",
"compass_directions",
"regular_vertices",
"complex_to_R3",
"R3_to_complex",
"complex_func_to_R3_func",
"center_of_mass",
"midpoint",
"find_intersection",
"line_intersection",
"get_winding_number",
"shoelace",
"shoelace_direction",
"cross2d",
"earclip_triangulation",
"cartesian_to_spherical",
"spherical_to_cartesian",
"perpendicular_bisector",
]
def norm_squared(v: float) -> float:
return np.dot(v, v)
def cross(v1: Vector3D, v2: Vector3D) -> Vector3D:
return np.array(
[
v1[1] * v2[2] - v1[2] * v2[1],
v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0],
]
)
# Quaternions
# TODO, implement quaternion type
def quaternion_mult(
*quats: Sequence[float],
) -> np.ndarray | list[float | np.ndarray]:
"""Gets the Hamilton product of the quaternions provided.
For more information, check `this Wikipedia page
<https://en.wikipedia.org/wiki/Quaternion>`__.
Returns
-------
Union[np.ndarray, List[Union[float, np.ndarray]]]
Returns a list of product of two quaternions.
"""
if len(quats) == 0:
return [1, 0, 0, 0]
result = quats[0]
for next_quat in quats[1:]:
w1, x1, y1, z1 = result
w2, x2, y2, z2 = next_quat
result = [
w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2,
w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2,
]
return result
def quaternion_from_angle_axis(
angle: float,
axis: np.ndarray,
axis_normalized: bool = False,
) -> list[float]:
"""Gets a quaternion from an angle and an axis.
For more information, check `this Wikipedia page
<https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles>`__.
Parameters
----------
angle
The angle for the quaternion.
axis
The axis for the quaternion
axis_normalized
Checks whether the axis is normalized, by default False
Returns
-------
list[float]
Gives back a quaternion from the angle and axis
"""
if not axis_normalized:
axis = normalize(axis)
return [np.cos(angle / 2), *(np.sin(angle / 2) * axis)]
def angle_axis_from_quaternion(quaternion: Sequence[float]) -> Sequence[float]:
"""Gets angle and axis from a quaternion.
Parameters
----------
quaternion
The quaternion from which we get the angle and axis.
Returns
-------
Sequence[float]
Gives the angle and axis
"""
axis = normalize(quaternion[1:], fall_back=np.array([1, 0, 0]))
angle = 2 * np.arccos(quaternion[0])
if angle > TAU / 2:
angle = TAU - angle
return angle, axis
def quaternion_conjugate(quaternion: Sequence[float]) -> np.ndarray:
"""Used for finding the conjugate of the quaternion
Parameters
----------
quaternion
The quaternion for which you want to find the conjugate for.
Returns
-------
np.ndarray
The conjugate of the quaternion.
"""
result = np.array(quaternion)
result[1:] *= -1
return result
def rotate_vector(
vector: np.ndarray, angle: float, axis: np.ndarray = OUT
) -> np.ndarray:
"""Function for rotating a vector.
Parameters
----------
vector
The vector to be rotated.
angle
The angle to be rotated by.
axis
The axis to be rotated, by default OUT
Returns
-------
np.ndarray
The rotated vector with provided angle and axis.
Raises
------
ValueError
If vector is not of dimension 2 or 3.
"""
if len(vector) > 3:
raise ValueError("Vector must have the correct dimensions.")
if len(vector) == 2:
vector = np.append(vector, 0)
return rotation_matrix(angle, axis) @ vector
def thick_diagonal(dim: int, thickness=2) -> np.ndarray:
row_indices = np.arange(dim).repeat(dim).reshape((dim, dim))
col_indices = np.transpose(row_indices)
return (np.abs(row_indices - col_indices) < thickness).astype("uint8")
def rotation_matrix_transpose_from_quaternion(quat: np.ndarray) -> list[np.ndarray]:
"""Converts the quaternion, quat, to an equivalent rotation matrix representation.
For more information, check `this page
<https://in.mathworks.com/help/driving/ref/quaternion.rotmat.html>`_.
Parameters
----------
quat
The quaternion which is to be converted.
Returns
-------
List[np.ndarray]
Gives back the Rotation matrix representation, returned as a 3-by-3
matrix or 3-by-3-by-N multidimensional array.
"""
quat_inv = quaternion_conjugate(quat)
return [
quaternion_mult(quat, [0, *basis], quat_inv)[1:]
for basis in [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
]
]
def rotation_matrix_from_quaternion(quat: np.ndarray) -> np.ndarray:
return np.transpose(rotation_matrix_transpose_from_quaternion(quat))
def rotation_matrix_transpose(angle: float, axis: np.ndarray) -> np.ndarray:
if all(np.array(axis)[:2] == np.zeros(2)):
return rotation_about_z(angle * np.sign(axis[2])).T
return rotation_matrix(angle, axis).T
def rotation_matrix(
angle: float,
axis: np.ndarray,
homogeneous: bool = False,
) -> np.ndarray:
"""
Rotation in R^3 about a specified axis of rotation.
"""
inhomogeneous_rotation_matrix = Rotation.from_rotvec(
angle * normalize(np.array(axis))
).as_matrix()
if not homogeneous:
return inhomogeneous_rotation_matrix
else:
rotation_matrix = np.eye(4)
rotation_matrix[:3, :3] = inhomogeneous_rotation_matrix
return rotation_matrix
def rotation_about_z(angle: float) -> np.ndarray:
"""Returns a rotation matrix for a given angle.
Parameters
----------
angle
Angle for the rotation matrix.
Returns
-------
np.ndarray
Gives back the rotated matrix.
"""
c, s = np.cos(angle), np.sin(angle)
return np.array(
[
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
]
)
def z_to_vector(vector: np.ndarray) -> np.ndarray:
"""
Returns some matrix in SO(3) which takes the z-axis to the
(normalized) vector provided as an argument
"""
axis_z = normalize(vector)
axis_y = normalize(cross(axis_z, RIGHT))
axis_x = cross(axis_y, axis_z)
if np.linalg.norm(axis_y) == 0:
# the vector passed just so happened to be in the x direction.
axis_x = normalize(cross(UP, axis_z))
axis_y = -cross(axis_x, axis_z)
return np.array([axis_x, axis_y, axis_z]).T
def angle_of_vector(vector: Sequence[float] | np.ndarray) -> float:
"""Returns polar coordinate theta when vector is projected on xy plane.
Parameters
----------
vector
The vector to find the angle for.
Returns
-------
float
The angle of the vector projected.
"""
if isinstance(vector, np.ndarray) and len(vector.shape) > 1:
if vector.shape[0] < 2:
raise ValueError("Vector must have the correct dimensions. (2, n)")
c_vec = np.empty(vector.shape[1], dtype=np.complex128)
c_vec.real = vector[0]
c_vec.imag = vector[1]
return np.angle(c_vec)
return np.angle(complex(*vector[:2]))
def angle_between_vectors(v1: np.ndarray, v2: np.ndarray) -> float:
"""Returns the angle between two vectors.
This angle will always be between 0 and pi
Parameters
----------
v1
The first vector.
v2
The second vector.
Returns
-------
float
The angle between the vectors.
"""
return 2 * np.arctan2(
np.linalg.norm(normalize(v1) - normalize(v2)),
np.linalg.norm(normalize(v1) + normalize(v2)),
)
def normalize(vect: np.ndarray | tuple[float], fall_back=None) -> np.ndarray:
norm = np.linalg.norm(vect)
if norm > 0:
return np.array(vect) / norm
else:
return fall_back or np.zeros(len(vect))
def normalize_along_axis(array: np.ndarray, axis: np.ndarray) -> np.ndarray:
"""Normalizes an array with the provided axis.
Parameters
----------
array
The array which has to be normalized.
axis
The axis to be normalized to.
Returns
-------
np.ndarray
Array which has been normalized according to the axis.
"""
norms = np.sqrt((array * array).sum(axis))
norms[norms == 0] = 1
buffed_norms = np.repeat(norms, array.shape[axis]).reshape(array.shape)
array /= buffed_norms
return array
def get_unit_normal(v1: Vector3D, v2: Vector3D, tol: float = 1e-6) -> Vector3D:
"""Gets the unit normal of the vectors.
Parameters
----------
v1
The first vector.
v2
The second vector
tol
[description], by default 1e-6
Returns
-------
np.ndarray
The normal of the two vectors.
"""
# Instead of normalizing v1 and v2, just divide by the greatest
# of all their absolute components, which is just enough
div1, div2 = max(np.abs(v1)), max(np.abs(v2))
if div1 == 0.0:
if div2 == 0.0:
return DOWN
u = v2 / div2
elif div2 == 0.0:
u = v1 / div1
else:
# Normal scenario: v1 and v2 are both non-null
u1, u2 = v1 / div1, v2 / div2
cp = cross(u1, u2)
cp_norm = np.sqrt(norm_squared(cp))
if cp_norm > tol:
return cp / cp_norm
# Otherwise, v1 and v2 were aligned
u = u1
# If you are here, you have an "unique", non-zero, unit-ish vector u
# If it's also too aligned to the Z axis, just return DOWN
if abs(u[0]) < tol and abs(u[1]) < tol:
return DOWN
# Otherwise rotate u in the plane it shares with the Z axis,
# 90° TOWARDS the Z axis. This is done via (u x [0, 0, 1]) x u,
# which gives [-xz, -yz, x²+y²] (slightly scaled as well)
cp = np.array([-u[0] * u[2], -u[1] * u[2], u[0] * u[0] + u[1] * u[1]])
cp_norm = np.sqrt(norm_squared(cp))
# Because the norm(u) == 0 case was filtered in the beginning,
# there is no need to check if the norm of cp is 0
return cp / cp_norm
###
def compass_directions(n: int = 4, start_vect: np.ndarray = RIGHT) -> np.ndarray:
"""Finds the cardinal directions using tau.
Parameters
----------
n
The amount to be rotated, by default 4
start_vect
The direction for the angle to start with, by default RIGHT
Returns
-------
np.ndarray
The angle which has been rotated.
"""
angle = TAU / n
return np.array([rotate_vector(start_vect, k * angle) for k in range(n)])
def regular_vertices(
n: int, *, radius: float = 1, start_angle: float | None = None
) -> tuple[np.ndarray, float]:
"""Generates regularly spaced vertices around a circle centered at the origin.
Parameters
----------
n
The number of vertices
radius
The radius of the circle that the vertices are placed on.
start_angle
The angle the vertices start at.
If unspecified, for even ``n`` values, ``0`` will be used.
For odd ``n`` values, 90 degrees is used.
Returns
-------
vertices : :class:`numpy.ndarray`
The regularly spaced vertices.
start_angle : :class:`float`
The angle the vertices start at.
"""
if start_angle is None:
if n % 2 == 0:
start_angle = 0
else:
start_angle = TAU / 4
start_vector = rotate_vector(RIGHT * radius, start_angle)
vertices = compass_directions(n, start_vector)
return vertices, start_angle
def complex_to_R3(complex_num: complex) -> np.ndarray:
return np.array((complex_num.real, complex_num.imag, 0))
def R3_to_complex(point: Sequence[float]) -> np.ndarray:
return complex(*point[:2])
def complex_func_to_R3_func(complex_func):
return lambda p: complex_to_R3(complex_func(R3_to_complex(p)))
def center_of_mass(points: Sequence[float]) -> np.ndarray:
"""Gets the center of mass of the points in space.
Parameters
----------
points
The points to find the center of mass from.
Returns
-------
np.ndarray
The center of mass of the points.
"""
return np.average(points, 0, np.ones(len(points)))
def midpoint(
point1: Sequence[float],
point2: Sequence[float],
) -> float | np.ndarray:
"""Gets the midpoint of two points.
Parameters
----------
point1
The first point.
point2
The second point.
Returns
-------
Union[float, np.ndarray]
The midpoint of the points
"""
return center_of_mass([point1, point2])
def line_intersection(
line1: Sequence[np.ndarray], line2: Sequence[np.ndarray]
) -> np.ndarray:
"""Returns the intersection point of two lines, each defined by
a pair of distinct points lying on the line.
Parameters
----------
line1
A list of two points that determine the first line.
line2
A list of two points that determine the second line.
Returns
-------
np.ndarray
The intersection points of the two lines which are intersecting.
Raises
------
ValueError
Error is produced if the two lines don't intersect with each other
or if the coordinates don't lie on the xy-plane.
"""
if any(np.array([line1, line2])[:, :, 2].reshape(-1)):
# checks for z coordinates != 0
raise ValueError("Coords must be in the xy-plane.")
# algorithm from https://stackoverflow.com/a/42727584
padded = (
np.pad(np.array(i)[:, :2], ((0, 0), (0, 1)), constant_values=1)
for i in (line1, line2)
)
line1, line2 = (cross(*i) for i in padded)
x, y, z = cross(line1, line2)
if z == 0:
raise ValueError(
"The lines are parallel, there is no unique intersection point."
)
return np.array([x / z, y / z, 0])
def find_intersection(
p0s: Sequence[np.ndarray] | Point3D_Array,
v0s: Sequence[np.ndarray] | Point3D_Array,
p1s: Sequence[np.ndarray] | Point3D_Array,
v1s: Sequence[np.ndarray] | Point3D_Array,
threshold: float = 1e-5,
) -> Sequence[np.ndarray]:
"""
Return the intersection of a line passing through p0 in direction v0
with one passing through p1 in direction v1 (or array of intersections
from arrays of such points/directions).
For 3d values, it returns the point on the ray p0 + v0 * t closest to the
ray p1 + v1 * t
"""
# algorithm from https://en.wikipedia.org/wiki/Skew_lines#Nearest_points
result = []
for p0, v0, p1, v1 in zip(*[p0s, v0s, p1s, v1s]):
normal = cross(v1, cross(v0, v1))
denom = max(np.dot(v0, normal), threshold)
result += [p0 + np.dot(p1 - p0, normal) / denom * v0]
return result
def get_winding_number(points: Sequence[np.ndarray]) -> float:
"""Determine the number of times a polygon winds around the origin.
The orientation is measured mathematically positively, i.e.,
counterclockwise.
Parameters
----------
points
The vertices of the polygon being queried.
Examples
--------
>>> from manim import Square, get_winding_number
>>> polygon = Square()
>>> get_winding_number(polygon.get_vertices())
1.0
>>> polygon.shift(2*UP)
Square
>>> get_winding_number(polygon.get_vertices())
0.0
"""
total_angle = 0
for p1, p2 in adjacent_pairs(points):
d_angle = angle_of_vector(p2) - angle_of_vector(p1)
d_angle = ((d_angle + PI) % TAU) - PI
total_angle += d_angle
return total_angle / TAU
def shoelace(x_y: np.ndarray) -> float:
"""2D implementation of the shoelace formula.
Returns
-------
:class:`float`
Returns signed area.
"""
x = x_y[:, 0]
y = x_y[:, 1]
return np.trapz(y, x)
def shoelace_direction(x_y: np.ndarray) -> str:
"""
Uses the area determined by the shoelace method to determine whether
the input set of points is directed clockwise or counterclockwise.
Returns
-------
:class:`str`
Either ``"CW"`` or ``"CCW"``.
"""
area = shoelace(x_y)
return "CW" if area > 0 else "CCW"
def cross2d(
a: Vector2D | Vector2D_Array,
b: Vector2D | Vector2D_Array,
) -> ManimFloat | npt.NDArray[ManimFloat]:
"""Compute the determinant(s) of the passed
vector (sequences).
Parameters
----------
a
A vector or a sequence of vectors.
b
A vector or a sequence of vectors.
Returns
-------
Sequence[float] | float
The determinant or sequence of determinants
of the first two components of the specified
vectors.
Examples
--------
.. code-block:: pycon
>>> cross2d(np.array([1, 2]), np.array([3, 4]))
-2
>>> cross2d(
... np.array([[1, 2, 0], [1, 0, 0]]),
... np.array([[3, 4, 0], [0, 1, 0]]),
... )
array([-2, 1])
"""
if len(a.shape) == 2:
return a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0]
else:
return a[0] * b[1] - b[0] * a[1]
def earclip_triangulation(verts: np.ndarray, ring_ends: list) -> list:
"""Returns a list of indices giving a triangulation
of a polygon, potentially with holes.
Parameters
----------
verts
verts is a numpy array of points.
ring_ends
ring_ends is a list of indices indicating where
the ends of new paths are.
Returns
-------
list
A list of indices giving a triangulation of a polygon.
"""
# First, connect all the rings so that the polygon
# with holes is instead treated as a (very convex)
# polygon with one edge. Do this by drawing connections
# between rings close to each other
rings = [list(range(e0, e1)) for e0, e1 in zip([0, *ring_ends], ring_ends)]
attached_rings = rings[:1]
detached_rings = rings[1:]
loop_connections = {}
while detached_rings:
i_range, j_range = (
list(
filter(
# Ignore indices that are already being
# used to draw some connection
lambda i: i not in loop_connections,
it.chain(*ring_group),
),
)
for ring_group in (attached_rings, detached_rings)
)
# Closest point on the attached rings to an estimated midpoint
# of the detached rings
tmp_j_vert = midpoint(verts[j_range[0]], verts[j_range[len(j_range) // 2]])
i = min(i_range, key=lambda i: norm_squared(verts[i] - tmp_j_vert))
# Closest point of the detached rings to the aforementioned
# point of the attached rings
j = min(j_range, key=lambda j: norm_squared(verts[i] - verts[j]))
# Recalculate i based on new j
i = min(i_range, key=lambda i: norm_squared(verts[i] - verts[j]))
# Remember to connect the polygon at these points
loop_connections[i] = j
loop_connections[j] = i
# Move the ring which j belongs to from the
# attached list to the detached list
new_ring = next(
(ring for ring in detached_rings if ring[0] <= j < ring[-1]), None
)
if new_ring is not None:
detached_rings.remove(new_ring)
attached_rings.append(new_ring)
else:
raise Exception("Could not find a ring to attach")
# Setup linked list
after = []
end0 = 0
for end1 in ring_ends:
after.extend(range(end0 + 1, end1))
after.append(end0)
end0 = end1
# Find an ordering of indices walking around the polygon
indices = []
i = 0
for _ in range(len(verts) + len(ring_ends) - 1):
# starting = False
if i in loop_connections:
j = loop_connections[i]
indices.extend([i, j])
i = after[j]
else:
indices.append(i)
i = after[i]
if i == 0:
break
meta_indices = earcut(verts[indices, :2], [len(indices)])
return [indices[mi] for mi in meta_indices]
def cartesian_to_spherical(vec: Sequence[float]) -> np.ndarray:
"""Returns an array of numbers corresponding to each
polar coordinate value (distance, phi, theta).
Parameters
----------
vec
A numpy array ``[x, y, z]``.
"""
norm = np.linalg.norm(vec)
if norm == 0:
return 0, 0, 0
r = norm
phi = np.arccos(vec[2] / r)
theta = np.arctan2(vec[1], vec[0])
return np.array([r, theta, phi])
def spherical_to_cartesian(spherical: Sequence[float]) -> np.ndarray:
"""Returns a numpy array ``[x, y, z]`` based on the spherical
coordinates given.
Parameters
----------
spherical
A list of three floats that correspond to the following:
r - The distance between the point and the origin.
theta - The azimuthal angle of the point to the positive x-axis.
phi - The vertical angle of the point to the positive z-axis.
"""
r, theta, phi = spherical
return np.array(
[
r * np.cos(theta) * np.sin(phi),
r * np.sin(theta) * np.sin(phi),
r * np.cos(phi),
],
)
def perpendicular_bisector(
line: Sequence[np.ndarray],
norm_vector=OUT,
) -> Sequence[np.ndarray]:
"""Returns a list of two points that correspond
to the ends of the perpendicular bisector of the
two points given.
Parameters
----------
line
a list of two numpy array points (corresponding
to the ends of a line).
norm_vector
the vector perpendicular to both the line given
and the perpendicular bisector.
Returns
-------
list
A list of two numpy array points that correspond
to the ends of the perpendicular bisector
"""
p1 = line[0]
p2 = line[1]
direction = cross(p1 - p2, norm_vector)
m = midpoint(p1, p2)
return [m + direction, m - direction]
|
manim_ManimCommunity/manim/utils/paths.py
|
"""Functions determining transformation paths between sets of points."""
from __future__ import annotations
__all__ = [
"straight_path",
"path_along_arc",
"clockwise_path",
"counterclockwise_path",
]
from typing import Callable
import numpy as np
from ..constants import OUT
from ..utils.bezier import interpolate
from ..utils.deprecation import deprecated_params
from ..utils.space_ops import rotation_matrix
STRAIGHT_PATH_THRESHOLD = 0.01
PATH_FUNC_TYPE = Callable[[np.ndarray, np.ndarray, float], np.ndarray]
# Remove `*args` and the `if` inside the functions when removing deprecation
@deprecated_params(
params="start_points, end_points, alpha",
since="v0.14",
until="v0.15",
message="Straight path is now returning interpolating function to make it consistent with other path functions. Use straight_path()(a,b,c) instead of straight_path(a,b,c).",
)
def straight_path(*args) -> PATH_FUNC_TYPE:
"""Simplest path function. Each point in a set goes in a straight path toward its destination.
Examples
--------
.. manim :: StraightPathExample
class StraightPathExample(Scene):
def construct(self):
colors = [RED, GREEN, BLUE]
starting_points = VGroup(
*[
Dot(LEFT + pos, color=color)
for pos, color in zip([UP, DOWN, LEFT], colors)
]
)
finish_points = VGroup(
*[
Dot(RIGHT + pos, color=color)
for pos, color in zip([ORIGIN, UP, DOWN], colors)
]
)
self.add(starting_points)
self.add(finish_points)
for dot in starting_points:
self.add(TracedPath(dot.get_center, stroke_color=dot.get_color()))
self.wait()
self.play(
Transform(
starting_points,
finish_points,
path_func=utils.paths.straight_path(),
run_time=2,
)
)
self.wait()
"""
if len(args) > 0:
return interpolate(*args)
return interpolate
def path_along_circles(
arc_angle: float, circles_centers: np.ndarray, axis: np.ndarray = OUT
) -> PATH_FUNC_TYPE:
"""This function transforms each point by moving it roughly along a circle, each with its own specified center.
The path may be seen as each point smoothly changing its orbit from its starting position to its destination.
Parameters
----------
arc_angle
The angle each point traverses around the quasicircle.
circles_centers
The centers of each point's quasicircle to rotate around.
axis
The axis of rotation.
Examples
--------
.. manim :: PathAlongCirclesExample
class PathAlongCirclesExample(Scene):
def construct(self):
colors = [RED, GREEN, BLUE]
starting_points = VGroup(
*[
Dot(LEFT + pos, color=color)
for pos, color in zip([UP, DOWN, LEFT], colors)
]
)
finish_points = VGroup(
*[
Dot(RIGHT + pos, color=color)
for pos, color in zip([ORIGIN, UP, DOWN], colors)
]
)
self.add(starting_points)
self.add(finish_points)
for dot in starting_points:
self.add(TracedPath(dot.get_center, stroke_color=dot.get_color()))
circle_center = Dot(3 * LEFT)
self.add(circle_center)
self.wait()
self.play(
Transform(
starting_points,
finish_points,
path_func=utils.paths.path_along_circles(
2 * PI, circle_center.get_center()
),
run_time=3,
)
)
self.wait()
"""
if np.linalg.norm(axis) == 0:
axis = OUT
unit_axis = axis / np.linalg.norm(axis)
def path(start_points: np.ndarray, end_points: np.ndarray, alpha: float):
detransformed_end_points = circles_centers + np.dot(
end_points - circles_centers, rotation_matrix(-arc_angle, unit_axis).T
)
rot_matrix = rotation_matrix(alpha * arc_angle, unit_axis)
return circles_centers + np.dot(
interpolate(start_points, detransformed_end_points, alpha)
- circles_centers,
rot_matrix.T,
)
return path
def path_along_arc(arc_angle: float, axis: np.ndarray = OUT) -> PATH_FUNC_TYPE:
"""This function transforms each point by moving it along a circular arc.
Parameters
----------
arc_angle
The angle each point traverses around a circular arc.
axis
The axis of rotation.
Examples
--------
.. manim :: PathAlongArcExample
class PathAlongArcExample(Scene):
def construct(self):
colors = [RED, GREEN, BLUE]
starting_points = VGroup(
*[
Dot(LEFT + pos, color=color)
for pos, color in zip([UP, DOWN, LEFT], colors)
]
)
finish_points = VGroup(
*[
Dot(RIGHT + pos, color=color)
for pos, color in zip([ORIGIN, UP, DOWN], colors)
]
)
self.add(starting_points)
self.add(finish_points)
for dot in starting_points:
self.add(TracedPath(dot.get_center, stroke_color=dot.get_color()))
self.wait()
self.play(
Transform(
starting_points,
finish_points,
path_func=utils.paths.path_along_arc(TAU * 2 / 3),
run_time=3,
)
)
self.wait()
"""
if abs(arc_angle) < STRAIGHT_PATH_THRESHOLD:
return straight_path()
if np.linalg.norm(axis) == 0:
axis = OUT
unit_axis = axis / np.linalg.norm(axis)
def path(start_points: np.ndarray, end_points: np.ndarray, alpha: float):
vects = end_points - start_points
centers = start_points + 0.5 * vects
if arc_angle != np.pi:
centers += np.cross(unit_axis, vects / 2.0) / np.tan(arc_angle / 2)
rot_matrix = rotation_matrix(alpha * arc_angle, unit_axis)
return centers + np.dot(start_points - centers, rot_matrix.T)
return path
def clockwise_path() -> PATH_FUNC_TYPE:
"""This function transforms each point by moving clockwise around a half circle.
Examples
--------
.. manim :: ClockwisePathExample
class ClockwisePathExample(Scene):
def construct(self):
colors = [RED, GREEN, BLUE]
starting_points = VGroup(
*[
Dot(LEFT + pos, color=color)
for pos, color in zip([UP, DOWN, LEFT], colors)
]
)
finish_points = VGroup(
*[
Dot(RIGHT + pos, color=color)
for pos, color in zip([ORIGIN, UP, DOWN], colors)
]
)
self.add(starting_points)
self.add(finish_points)
for dot in starting_points:
self.add(TracedPath(dot.get_center, stroke_color=dot.get_color()))
self.wait()
self.play(
Transform(
starting_points,
finish_points,
path_func=utils.paths.clockwise_path(),
run_time=2,
)
)
self.wait()
"""
return path_along_arc(-np.pi)
def counterclockwise_path() -> PATH_FUNC_TYPE:
"""This function transforms each point by moving counterclockwise around a half circle.
Examples
--------
.. manim :: CounterclockwisePathExample
class CounterclockwisePathExample(Scene):
def construct(self):
colors = [RED, GREEN, BLUE]
starting_points = VGroup(
*[
Dot(LEFT + pos, color=color)
for pos, color in zip([UP, DOWN, LEFT], colors)
]
)
finish_points = VGroup(
*[
Dot(RIGHT + pos, color=color)
for pos, color in zip([ORIGIN, UP, DOWN], colors)
]
)
self.add(starting_points)
self.add(finish_points)
for dot in starting_points:
self.add(TracedPath(dot.get_center, stroke_color=dot.get_color()))
self.wait()
self.play(
Transform(
starting_points,
finish_points,
path_func=utils.paths.counterclockwise_path(),
run_time=2,
)
)
self.wait()
"""
return path_along_arc(np.pi)
def spiral_path(angle: float, axis: np.ndarray = OUT) -> PATH_FUNC_TYPE:
"""This function transforms each point by moving along a spiral to its destination.
Parameters
----------
angle
The angle each point traverses around a spiral.
axis
The axis of rotation.
Examples
--------
.. manim :: SpiralPathExample
class SpiralPathExample(Scene):
def construct(self):
colors = [RED, GREEN, BLUE]
starting_points = VGroup(
*[
Dot(LEFT + pos, color=color)
for pos, color in zip([UP, DOWN, LEFT], colors)
]
)
finish_points = VGroup(
*[
Dot(RIGHT + pos, color=color)
for pos, color in zip([ORIGIN, UP, DOWN], colors)
]
)
self.add(starting_points)
self.add(finish_points)
for dot in starting_points:
self.add(TracedPath(dot.get_center, stroke_color=dot.get_color()))
self.wait()
self.play(
Transform(
starting_points,
finish_points,
path_func=utils.paths.spiral_path(2 * TAU),
run_time=5,
)
)
self.wait()
"""
if abs(angle) < STRAIGHT_PATH_THRESHOLD:
return straight_path()
if np.linalg.norm(axis) == 0:
axis = OUT
unit_axis = axis / np.linalg.norm(axis)
def path(start_points: np.ndarray, end_points: np.ndarray, alpha: float):
rot_matrix = rotation_matrix((alpha - 1) * angle, unit_axis)
return start_points + alpha * np.dot(end_points - start_points, rot_matrix.T)
return path
|
manim_ManimCommunity/manim/utils/commands.py
|
from __future__ import annotations
import json
import os
from pathlib import Path
from subprocess import run
from typing import Generator
__all__ = [
"capture",
"get_video_metadata",
"get_dir_layout",
]
def capture(command, cwd=None, command_input=None):
p = run(command, cwd=cwd, input=command_input, capture_output=True, text=True)
out, err = p.stdout, p.stderr
return out, err, p.returncode
def get_video_metadata(path_to_video: str | os.PathLike) -> dict[str]:
command = [
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height,nb_frames,duration,avg_frame_rate,codec_name",
"-print_format",
"json",
str(path_to_video),
]
config, err, exitcode = capture(command)
assert exitcode == 0, f"FFprobe error: {err}"
return json.loads(config)["streams"][0]
def get_dir_layout(dirpath: Path) -> Generator[str, None, None]:
"""Get list of paths relative to dirpath of all files in dir and subdirs recursively."""
for p in dirpath.iterdir():
if p.is_dir():
yield from get_dir_layout(p)
continue
yield str(p.relative_to(dirpath))
|
manim_ManimCommunity/manim/utils/exceptions.py
|
from __future__ import annotations
__all__ = [
"EndSceneEarlyException",
"RerunSceneException",
"MultiAnimationOverrideException",
]
class EndSceneEarlyException(Exception):
pass
class RerunSceneException(Exception):
pass
class MultiAnimationOverrideException(Exception):
pass
|
manim_ManimCommunity/manim/utils/rate_functions.py
|
"""A selection of rate functions, i.e., *speed curves* for animations.
Please find a standard list at https://easings.net/. Here is a picture
for the non-standard ones
.. manim:: RateFuncExample
:save_last_frame:
class RateFuncExample(Scene):
def construct(self):
x = VGroup()
for k, v in rate_functions.__dict__.items():
if "function" in str(v):
if (
not k.startswith("__")
and not k.startswith("sqrt")
and not k.startswith("bezier")
):
try:
rate_func = v
plot = (
ParametricFunction(
lambda x: [x, rate_func(x), 0],
t_range=[0, 1, .01],
use_smoothing=False,
color=YELLOW,
)
.stretch_to_fit_width(1.5)
.stretch_to_fit_height(1)
)
plot_bg = SurroundingRectangle(plot).set_color(WHITE)
plot_title = (
Text(rate_func.__name__, weight=BOLD)
.scale(0.5)
.next_to(plot_bg, UP, buff=0.1)
)
x.add(VGroup(plot_bg, plot, plot_title))
except: # because functions `not_quite_there`, `function squish_rate_func` are not working.
pass
x.arrange_in_grid(cols=8)
x.height = config.frame_height
x.width = config.frame_width
x.move_to(ORIGIN).scale(0.95)
self.add(x)
There are primarily 3 kinds of standard easing functions:
#. Ease In - The animation has a smooth start.
#. Ease Out - The animation has a smooth end.
#. Ease In Out - The animation has a smooth start as well as smooth end.
.. note:: The standard functions are not exported, so to use them you do something like this:
rate_func=rate_functions.ease_in_sine
On the other hand, the non-standard functions, which are used more commonly, are exported and can be used directly.
.. manim:: RateFunctions1Example
class RateFunctions1Example(Scene):
def construct(self):
line1 = Line(3*LEFT, 3*RIGHT).shift(UP).set_color(RED)
line2 = Line(3*LEFT, 3*RIGHT).set_color(GREEN)
line3 = Line(3*LEFT, 3*RIGHT).shift(DOWN).set_color(BLUE)
dot1 = Dot().move_to(line1.get_left())
dot2 = Dot().move_to(line2.get_left())
dot3 = Dot().move_to(line3.get_left())
label1 = Tex("Ease In").next_to(line1, RIGHT)
label2 = Tex("Ease out").next_to(line2, RIGHT)
label3 = Tex("Ease In Out").next_to(line3, RIGHT)
self.play(
FadeIn(VGroup(line1, line2, line3)),
FadeIn(VGroup(dot1, dot2, dot3)),
Write(VGroup(label1, label2, label3)),
)
self.play(
MoveAlongPath(dot1, line1, rate_func=rate_functions.ease_in_sine),
MoveAlongPath(dot2, line2, rate_func=rate_functions.ease_out_sine),
MoveAlongPath(dot3, line3, rate_func=rate_functions.ease_in_out_sine),
run_time=7
)
self.wait()
"""
from __future__ import annotations
__all__ = [
"linear",
"smooth",
"smoothstep",
"smootherstep",
"smoothererstep",
"rush_into",
"rush_from",
"slow_into",
"double_smooth",
"there_and_back",
"there_and_back_with_pause",
"running_start",
"not_quite_there",
"wiggle",
"squish_rate_func",
"lingering",
"exponential_decay",
]
import typing
from functools import wraps
from math import sqrt
import numpy as np
from ..utils.bezier import bezier
from ..utils.simple_functions import sigmoid
# This is a decorator that makes sure any function it's used on will
# return 0 if t<0 and 1 if t>1.
def unit_interval(function):
@wraps(function)
def wrapper(t, *args, **kwargs):
if 0 <= t <= 1:
return function(t, *args, **kwargs)
elif t < 0:
return 0
else:
return 1
return wrapper
# This is a decorator that makes sure any function it's used on will
# return 0 if t<0 or t>1.
def zero(function):
@wraps(function)
def wrapper(t, *args, **kwargs):
if 0 <= t <= 1:
return function(t, *args, **kwargs)
else:
return 0
return wrapper
@unit_interval
def linear(t: float) -> float:
return t
@unit_interval
def smooth(t: float, inflection: float = 10.0) -> float:
error = sigmoid(-inflection / 2)
return min(
max((sigmoid(inflection * (t - 0.5)) - error) / (1 - 2 * error), 0),
1,
)
def smoothstep(t: float) -> float:
"""Implementation of the 1st order SmoothStep sigmoid function.
The 1st derivative (speed) is zero at the endpoints.
https://en.wikipedia.org/wiki/Smoothstep
"""
return 0 if t <= 0 else 3 * t**2 - 2 * t**3 if t < 1 else 1
def smootherstep(t: float) -> float:
"""Implementation of the 2nd order SmoothStep sigmoid function.
The 1st and 2nd derivatives (speed and acceleration) are zero at the endpoints.
https://en.wikipedia.org/wiki/Smoothstep
"""
return 0 if t <= 0 else 6 * t**5 - 15 * t**4 + 10 * t**3 if t < 1 else 1
def smoothererstep(t: float) -> float:
"""Implementation of the 3rd order SmoothStep sigmoid function.
The 1st, 2nd and 3rd derivatives (speed, acceleration and jerk) are zero at the endpoints.
https://en.wikipedia.org/wiki/Smoothstep
"""
return (
0
if t <= 0
else 35 * t**4 - 84 * t**5 + 70 * t**6 - 20 * t**7
if t < 1
else 1
)
@unit_interval
def rush_into(t: float, inflection: float = 10.0) -> float:
return 2 * smooth(t / 2.0, inflection)
@unit_interval
def rush_from(t: float, inflection: float = 10.0) -> float:
return 2 * smooth(t / 2.0 + 0.5, inflection) - 1
@unit_interval
def slow_into(t: float) -> float:
return np.sqrt(1 - (1 - t) * (1 - t))
@unit_interval
def double_smooth(t: float) -> float:
if t < 0.5:
return 0.5 * smooth(2 * t)
else:
return 0.5 * (1 + smooth(2 * t - 1))
@zero
def there_and_back(t: float, inflection: float = 10.0) -> float:
new_t = 2 * t if t < 0.5 else 2 * (1 - t)
return smooth(new_t, inflection)
@zero
def there_and_back_with_pause(t: float, pause_ratio: float = 1.0 / 3) -> float:
a = 1.0 / pause_ratio
if t < 0.5 - pause_ratio / 2:
return smooth(a * t)
elif t < 0.5 + pause_ratio / 2:
return 1
else:
return smooth(a - a * t)
@unit_interval
def running_start(
t: float,
pull_factor: float = -0.5,
) -> typing.Iterable: # what is func return type?
return bezier([0, 0, pull_factor, pull_factor, 1, 1, 1])(t)
def not_quite_there(
func: typing.Callable[[float], float] = smooth,
proportion: float = 0.7,
) -> typing.Callable[[float], float]:
def result(t):
return proportion * func(t)
return result
@zero
def wiggle(t: float, wiggles: float = 2) -> float:
return there_and_back(t) * np.sin(wiggles * np.pi * t)
def squish_rate_func(
func: typing.Callable[[float], float],
a: float = 0.4,
b: float = 0.6,
) -> typing.Callable[[float], float]:
def result(t):
if a == b:
return a
if t < a:
return func(0)
elif t > b:
return func(1)
else:
return func((t - a) / (b - a))
return result
# Stylistically, should this take parameters (with default values)?
# Ultimately, the functionality is entirely subsumed by squish_rate_func,
# but it may be useful to have a nice name for with nice default params for
# "lingering", different from squish_rate_func's default params
@unit_interval
def lingering(t: float) -> float:
return squish_rate_func(lambda t: t, 0, 0.8)(t)
@unit_interval
def exponential_decay(t: float, half_life: float = 0.1) -> float:
# The half-life should be rather small to minimize
# the cut-off error at the end
return 1 - np.exp(-t / half_life)
@unit_interval
def ease_in_sine(t: float) -> float:
return 1 - np.cos((t * np.pi) / 2)
@unit_interval
def ease_out_sine(t: float) -> float:
return np.sin((t * np.pi) / 2)
@unit_interval
def ease_in_out_sine(t: float) -> float:
return -(np.cos(np.pi * t) - 1) / 2
@unit_interval
def ease_in_quad(t: float) -> float:
return t * t
@unit_interval
def ease_out_quad(t: float) -> float:
return 1 - (1 - t) * (1 - t)
@unit_interval
def ease_in_out_quad(t: float) -> float:
return 2 * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 2) / 2
@unit_interval
def ease_in_cubic(t: float) -> float:
return t * t * t
@unit_interval
def ease_out_cubic(t: float) -> float:
return 1 - pow(1 - t, 3)
@unit_interval
def ease_in_out_cubic(t: float) -> float:
return 4 * t * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 3) / 2
@unit_interval
def ease_in_quart(t: float) -> float:
return t * t * t * t
@unit_interval
def ease_out_quart(t: float) -> float:
return 1 - pow(1 - t, 4)
@unit_interval
def ease_in_out_quart(t: float) -> float:
return 8 * t * t * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 4) / 2
@unit_interval
def ease_in_quint(t: float) -> float:
return t * t * t * t * t
@unit_interval
def ease_out_quint(t: float) -> float:
return 1 - pow(1 - t, 5)
@unit_interval
def ease_in_out_quint(t: float) -> float:
return 16 * t * t * t * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 5) / 2
@unit_interval
def ease_in_expo(t: float) -> float:
return 0 if t == 0 else pow(2, 10 * t - 10)
@unit_interval
def ease_out_expo(t: float) -> float:
return 1 if t == 1 else 1 - pow(2, -10 * t)
@unit_interval
def ease_in_out_expo(t: float) -> float:
if t == 0:
return 0
elif t == 1:
return 1
elif t < 0.5:
return pow(2, 20 * t - 10) / 2
else:
return (2 - pow(2, -20 * t + 10)) / 2
@unit_interval
def ease_in_circ(t: float) -> float:
return 1 - sqrt(1 - pow(t, 2))
@unit_interval
def ease_out_circ(t: float) -> float:
return sqrt(1 - pow(t - 1, 2))
@unit_interval
def ease_in_out_circ(t: float) -> float:
return (
(1 - sqrt(1 - pow(2 * t, 2))) / 2
if t < 0.5
else (sqrt(1 - pow(-2 * t + 2, 2)) + 1) / 2
)
@unit_interval
def ease_in_back(t: float) -> float:
c1 = 1.70158
c3 = c1 + 1
return c3 * t * t * t - c1 * t * t
@unit_interval
def ease_out_back(t: float) -> float:
c1 = 1.70158
c3 = c1 + 1
return 1 + c3 * pow(t - 1, 3) + c1 * pow(t - 1, 2)
@unit_interval
def ease_in_out_back(t: float) -> float:
c1 = 1.70158
c2 = c1 * 1.525
return (
(pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2
if t < 0.5
else (pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2
)
@unit_interval
def ease_in_elastic(t: float) -> float:
c4 = (2 * np.pi) / 3
if t == 0:
return 0
elif t == 1:
return 1
else:
return -pow(2, 10 * t - 10) * np.sin((t * 10 - 10.75) * c4)
@unit_interval
def ease_out_elastic(t: float) -> float:
c4 = (2 * np.pi) / 3
if t == 0:
return 0
elif t == 1:
return 1
else:
return pow(2, -10 * t) * np.sin((t * 10 - 0.75) * c4) + 1
@unit_interval
def ease_in_out_elastic(t: float) -> float:
c5 = (2 * np.pi) / 4.5
if t == 0:
return 0
elif t == 1:
return 1
elif t < 0.5:
return -(pow(2, 20 * t - 10) * np.sin((20 * t - 11.125) * c5)) / 2
else:
return (pow(2, -20 * t + 10) * np.sin((20 * t - 11.125) * c5)) / 2 + 1
@unit_interval
def ease_in_bounce(t: float) -> float:
return 1 - ease_out_bounce(1 - t)
@unit_interval
def ease_out_bounce(t: float) -> float:
n1 = 7.5625
d1 = 2.75
if t < 1 / d1:
return n1 * t * t
elif t < 2 / d1:
return n1 * (t - 1.5 / d1) * (t - 1.5 / d1) + 0.75
elif t < 2.5 / d1:
return n1 * (t - 2.25 / d1) * (t - 2.25 / d1) + 0.9375
else:
return n1 * (t - 2.625 / d1) * (t - 2.625 / d1) + 0.984375
@unit_interval
def ease_in_out_bounce(t: float) -> float:
if t < 0.5:
return (1 - ease_out_bounce(1 - 2 * t)) / 2
else:
return (1 + ease_out_bounce(2 * t - 1)) / 2
|
manim_ManimCommunity/manim/utils/family_ops.py
|
from __future__ import annotations
import itertools as it
__all__ = [
"extract_mobject_family_members",
"restructure_list_to_exclude_certain_family_members",
]
def extract_mobject_family_members(mobject_list, only_those_with_points=False):
result = list(it.chain(*(mob.get_family() for mob in mobject_list)))
if only_those_with_points:
result = [mob for mob in result if mob.has_points()]
return result
def restructure_list_to_exclude_certain_family_members(mobject_list, to_remove):
"""
Removes anything in to_remove from mobject_list, but in the event that one of
the items to be removed is a member of the family of an item in mobject_list,
the other family members are added back into the list.
This is useful in cases where a scene contains a group, e.g. Group(m1, m2, m3),
but one of its submobjects is removed, e.g. scene.remove(m1), it's useful
for the list of mobject_list to be edited to contain other submobjects, but not m1.
"""
new_list = []
to_remove = extract_mobject_family_members(to_remove)
def add_safe_mobjects_from_list(list_to_examine, set_to_remove):
for mob in list_to_examine:
if mob in set_to_remove:
continue
intersect = set_to_remove.intersection(mob.get_family())
if intersect:
add_safe_mobjects_from_list(mob.submobjects, intersect)
else:
new_list.append(mob)
add_safe_mobjects_from_list(mobject_list, set(to_remove))
return new_list
|
manim_ManimCommunity/manim/utils/unit.py
|
"""Implement the Unit class."""
from __future__ import annotations
import numpy as np
from .. import config, constants
__all__ = ["Pixels", "Degrees", "Munits", "Percent"]
class _PixelUnits:
def __mul__(self, val):
return val * config.frame_width / config.pixel_width
def __rmul__(self, val):
return val * config.frame_width / config.pixel_width
class Percent:
def __init__(self, axis):
if np.array_equal(axis, constants.X_AXIS):
self.length = config.frame_width
if np.array_equal(axis, constants.Y_AXIS):
self.length = config.frame_height
if np.array_equal(axis, constants.Z_AXIS):
raise NotImplementedError("length of Z axis is undefined")
def __mul__(self, val):
return val / 100 * self.length
def __rmul__(self, val):
return val / 100 * self.length
Pixels = _PixelUnits()
Degrees = constants.PI / 180
Munits = 1
|
manim_ManimCommunity/manim/utils/hashing.py
|
"""Utilities for scene caching."""
from __future__ import annotations
import collections
import copy
import inspect
import json
import typing
import zlib
from time import perf_counter
from types import FunctionType, MappingProxyType, MethodType, ModuleType
from typing import Any
import numpy as np
from manim.animation.animation import Animation
from manim.camera.camera import Camera
from manim.mobject.mobject import Mobject
from .. import config, logger
if typing.TYPE_CHECKING:
from manim.scene.scene import Scene
__all__ = ["KEYS_TO_FILTER_OUT", "get_hash_from_play_call", "get_json"]
# Sometimes there are elements that are not suitable for hashing (too long or
# run-dependent). This is used to filter them out.
KEYS_TO_FILTER_OUT = {
"original_id",
"background",
"pixel_array",
"pixel_array_to_cairo_context",
}
class _Memoizer:
"""Implements the memoization logic to optimize the hashing procedure and prevent
the circular references within iterable processed.
Keeps a record of all the processed objects, and handle the logic to return a place
holder instead of the original object if the object has already been processed
by the hashing logic (i.e, recursively checked, converted to JSON, etc..).
This class uses two signatures functions to keep a track of processed objects :
hash or id. Whenever possible, hash is used to ensure a broader object
content-equality detection.
"""
_already_processed = set()
# Can be changed to whatever string to help debugging the JSon generation.
ALREADY_PROCESSED_PLACEHOLDER = "AP"
THRESHOLD_WARNING = 170_000
@classmethod
def reset_already_processed(cls):
cls._already_processed.clear()
@classmethod
def check_already_processed_decorator(cls: _Memoizer, is_method: bool = False):
"""Decorator to handle the arguments that goes through the decorated function.
Returns _ALREADY_PROCESSED_PLACEHOLDER if the obj has been processed, or lets
the decorated function call go ahead.
Parameters
----------
is_method
Whether the function passed is a method, by default False.
"""
def layer(func):
# NOTE : There is probably a better way to separate both case when func is
# a method or a function.
if is_method:
return lambda self, obj: cls._handle_already_processed(
obj,
default_function=lambda obj: func(self, obj),
)
return lambda obj: cls._handle_already_processed(obj, default_function=func)
return layer
@classmethod
def check_already_processed(cls, obj: Any) -> Any:
"""Checks if obj has been already processed. Returns itself if it has not been,
or the value of _ALREADY_PROCESSED_PLACEHOLDER if it has.
Marks the object as processed in the second case.
Parameters
----------
obj
The object to check.
Returns
-------
Any
Either the object itself or the placeholder.
"""
# When the object is not memoized, we return the object itself.
return cls._handle_already_processed(obj, lambda x: x)
@classmethod
def mark_as_processed(cls, obj: Any) -> None:
"""Marks an object as processed.
Parameters
----------
obj
The object to mark as processed.
"""
cls._handle_already_processed(obj, lambda x: x)
return cls._return(obj, id, lambda x: x, memoizing=False)
@classmethod
def _handle_already_processed(
cls,
obj,
default_function: typing.Callable[[Any], Any],
):
if isinstance(
obj,
(
int,
float,
str,
complex,
),
) and obj not in [None, cls.ALREADY_PROCESSED_PLACEHOLDER]:
# It makes no sense (and it'd slower) to memoize objects of these primitive
# types. Hence, we simply return the object.
return obj
if isinstance(obj, collections.abc.Hashable):
try:
return cls._return(obj, hash, default_function)
except TypeError:
# In case of an error with the hash (eg an object is marked as hashable
# but contains a non hashable within it)
# Fallback to use the built-in function id instead.
pass
return cls._return(obj, id, default_function)
@classmethod
def _return(
cls,
obj: typing.Any,
obj_to_membership_sign: typing.Callable[[Any], int],
default_func,
memoizing=True,
) -> str | Any:
obj_membership_sign = obj_to_membership_sign(obj)
if obj_membership_sign in cls._already_processed:
return cls.ALREADY_PROCESSED_PLACEHOLDER
if memoizing:
if (
not config.disable_caching_warning
and len(cls._already_processed) == cls.THRESHOLD_WARNING
):
logger.warning(
"It looks like the scene contains a lot of sub-mobjects. Caching "
"is sometimes not suited to handle such large scenes, you might "
"consider disabling caching with --disable_caching to potentially "
"speed up the rendering process.",
)
logger.warning(
"You can disable this warning by setting disable_caching_warning "
"to True in your config file.",
)
cls._already_processed.add(obj_membership_sign)
return default_func(obj)
class _CustomEncoder(json.JSONEncoder):
def default(self, obj: Any):
"""
This method is used to serialize objects to JSON format.
If obj is a function, then it will return a dict with two keys : 'code', for
the code source, and 'nonlocals' for all nonlocalsvalues. (including nonlocals
functions, that will be serialized as this is recursive.)
if obj is a np.darray, it converts it into a list.
if obj is an object with __dict__ attribute, it returns its __dict__.
Else, will let the JSONEncoder do the stuff, and throw an error if the type is
not suitable for JSONEncoder.
Parameters
----------
obj
Arbitrary object to convert
Returns
-------
Any
Python object that JSON encoder will recognize
"""
if not (isinstance(obj, ModuleType)) and isinstance(
obj,
(MethodType, FunctionType),
):
cvars = inspect.getclosurevars(obj)
cvardict = {**copy.copy(cvars.globals), **copy.copy(cvars.nonlocals)}
for i in list(cvardict):
# NOTE : All module types objects are removed, because otherwise it
# throws ValueError: Circular reference detected if not. TODO
if isinstance(cvardict[i], ModuleType):
del cvardict[i]
try:
code = inspect.getsource(obj)
except (OSError, TypeError):
# This happens when rendering videos included in the documentation
# within doctests and should be replaced by a solution avoiding
# hash collision (due to the same, empty, code strings) at some point.
# See https://github.com/ManimCommunity/manim/pull/402.
code = ""
return self._cleaned_iterable({"code": code, "nonlocals": cvardict})
elif isinstance(obj, np.ndarray):
if obj.size > 1000:
obj = np.resize(obj, (100, 100))
return f"TRUNCATED ARRAY: {repr(obj)}"
# We return the repr and not a list to avoid the JsonEncoder to iterate over it.
return repr(obj)
elif hasattr(obj, "__dict__"):
temp = getattr(obj, "__dict__")
# MappingProxy is scene-caching nightmare. It contains all of the object methods and attributes. We skip it as the mechanism will at some point process the object, but instantiated.
# Indeed, there is certainly no case where scene-caching will receive only a non instancied object, as this is never used in the library or encouraged to be used user-side.
if isinstance(temp, MappingProxyType):
return "MappingProxy"
return self._cleaned_iterable(temp)
elif isinstance(obj, np.uint8):
return int(obj)
# Serialize it with only the type of the object. You can change this to whatever string when debugging the serialization process.
return str(type(obj))
def _cleaned_iterable(self, iterable: typing.Iterable[Any]):
"""Check for circular reference at each iterable that will go through the JSONEncoder, as well as key of the wrong format.
If a key with a bad format is found (i.e not a int, string, or float), it gets replaced byt its hash using the same process implemented here.
If a circular reference is found within the iterable, it will be replaced by the string "already processed".
Parameters
----------
iterable
The iterable to check.
"""
def _key_to_hash(key):
return zlib.crc32(json.dumps(key, cls=_CustomEncoder).encode())
def _iter_check_list(lst):
processed_list = [None] * len(lst)
for i, el in enumerate(lst):
el = _Memoizer.check_already_processed(el)
if isinstance(el, (list, tuple)):
new_value = _iter_check_list(el)
elif isinstance(el, dict):
new_value = _iter_check_dict(el)
else:
new_value = el
processed_list[i] = new_value
return processed_list
def _iter_check_dict(dct):
processed_dict = {}
for k, v in dct.items():
v = _Memoizer.check_already_processed(v)
if k in KEYS_TO_FILTER_OUT:
continue
# We check if the k is of the right format (supporter by Json)
if not isinstance(k, (str, int, float, bool)) and k is not None:
k_new = _key_to_hash(k)
else:
k_new = k
if isinstance(v, dict):
new_value = _iter_check_dict(v)
elif isinstance(v, (list, tuple)):
new_value = _iter_check_list(v)
else:
new_value = v
processed_dict[k_new] = new_value
return processed_dict
if isinstance(iterable, (list, tuple)):
return _iter_check_list(iterable)
elif isinstance(iterable, dict):
return _iter_check_dict(iterable)
def encode(self, obj: Any):
"""Overriding of :meth:`JSONEncoder.encode`, to make our own process.
Parameters
----------
obj
The object to encode in JSON.
Returns
-------
:class:`str`
The object encoder with the standard json process.
"""
_Memoizer.mark_as_processed(obj)
if isinstance(obj, (dict, list, tuple)):
return super().encode(self._cleaned_iterable(obj))
return super().encode(obj)
def get_json(obj: dict):
"""Recursively serialize `object` to JSON using the :class:`CustomEncoder` class.
Parameters
----------
obj
The dict to flatten
Returns
-------
:class:`str`
The flattened object
"""
return json.dumps(obj, cls=_CustomEncoder)
def get_hash_from_play_call(
scene_object: Scene,
camera_object: Camera,
animations_list: typing.Iterable[Animation],
current_mobjects_list: typing.Iterable[Mobject],
) -> str:
"""Take the list of animations and a list of mobjects and output their hashes. This is meant to be used for `scene.play` function.
Parameters
-----------
scene_object
The scene object.
camera_object
The camera object used in the scene.
animations_list
The list of animations.
current_mobjects_list
The list of mobjects.
Returns
-------
:class:`str`
A string concatenation of the respective hashes of `camera_object`, `animations_list` and `current_mobjects_list`, separated by `_`.
"""
logger.debug("Hashing ...")
t_start = perf_counter()
_Memoizer.mark_as_processed(scene_object)
camera_json = get_json(camera_object)
animations_list_json = [get_json(x) for x in sorted(animations_list, key=str)]
current_mobjects_list_json = [get_json(x) for x in current_mobjects_list]
hash_camera, hash_animations, hash_current_mobjects = (
zlib.crc32(repr(json_val).encode())
for json_val in [camera_json, animations_list_json, current_mobjects_list_json]
)
hash_complete = f"{hash_camera}_{hash_animations}_{hash_current_mobjects}"
t_end = perf_counter()
logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]})
# End of the hashing for the animation, reset all the memoize.
_Memoizer.reset_already_processed()
logger.debug("Hash generated : %(h)s", {"h": hash_complete})
return hash_complete
|
manim_ManimCommunity/manim/utils/images.py
|
"""Image manipulation utilities."""
from __future__ import annotations
__all__ = [
"get_full_raster_image_path",
"drag_pixels",
"invert_image",
"change_to_rgba_array",
]
from pathlib import Path
import numpy as np
from PIL import Image
from .. import config
from ..utils.file_ops import seek_full_path_from_defaults
def get_full_raster_image_path(image_file_name: str) -> Path:
return seek_full_path_from_defaults(
image_file_name,
default_dir=config.get_dir("assets_dir"),
extensions=[".jpg", ".jpeg", ".png", ".gif", ".ico"],
)
def get_full_vector_image_path(image_file_name: str) -> Path:
return seek_full_path_from_defaults(
image_file_name,
default_dir=config.get_dir("assets_dir"),
extensions=[".svg"],
)
def drag_pixels(frames: list[np.array]) -> list[np.array]:
curr = frames[0]
new_frames = []
for frame in frames:
curr += (curr == 0) * np.array(frame)
new_frames.append(np.array(curr))
return new_frames
def invert_image(image: np.array) -> Image:
arr = np.array(image)
arr = (255 * np.ones(arr.shape)).astype(arr.dtype) - arr
return Image.fromarray(arr)
def change_to_rgba_array(image, dtype="uint8"):
"""Converts an RGB array into RGBA with the alpha value opacity maxed."""
pa = image
if len(pa.shape) == 2:
pa = pa.reshape(list(pa.shape) + [1])
if pa.shape[2] == 1:
pa = pa.repeat(3, axis=2)
if pa.shape[2] == 3:
alphas = 255 * np.ones(
list(pa.shape[:2]) + [1],
dtype=dtype,
)
pa = np.append(pa, alphas, axis=2)
return pa
|
manim_ManimCommunity/manim/utils/bezier.py
|
"""Utility functions related to Bézier curves."""
from __future__ import annotations
from manim.typing import (
BezierPoints,
ColVector,
MatrixMN,
Point3D,
Point3D_Array,
PointDType,
QuadraticBezierPoints,
QuadraticBezierPoints_Array,
)
__all__ = [
"bezier",
"partial_bezier_points",
"partial_quadratic_bezier_points",
"interpolate",
"integer_interpolate",
"mid",
"inverse_interpolate",
"match_interpolate",
"get_smooth_handle_points",
"get_smooth_cubic_bezier_handle_points",
"diag_to_matrix",
"is_closed",
"proportions_along_bezier_curve_for_point",
"point_lies_on_bezier",
]
from functools import reduce
from typing import Any, Callable, Sequence, overload
import numpy as np
import numpy.typing as npt
from scipy import linalg
from ..utils.simple_functions import choose
from ..utils.space_ops import cross2d, find_intersection
def bezier(
points: Sequence[Point3D] | Point3D_Array,
) -> Callable[[float], Point3D]:
"""Classic implementation of a bezier curve.
Parameters
----------
points
points defining the desired bezier curve.
Returns
-------
function describing the bezier curve.
You can pass a t value between 0 and 1 to get the corresponding point on the curve.
"""
n = len(points) - 1
# Cubic Bezier curve
if n == 3:
return lambda t: np.asarray(
(1 - t) ** 3 * points[0]
+ 3 * t * (1 - t) ** 2 * points[1]
+ 3 * (1 - t) * t**2 * points[2]
+ t**3 * points[3],
dtype=PointDType,
)
# Quadratic Bezier curve
if n == 2:
return lambda t: np.asarray(
(1 - t) ** 2 * points[0] + 2 * t * (1 - t) * points[1] + t**2 * points[2],
dtype=PointDType,
)
return lambda t: np.asarray(
np.asarray(
[
(((1 - t) ** (n - k)) * (t**k) * choose(n, k) * point)
for k, point in enumerate(points)
],
dtype=PointDType,
).sum(axis=0)
)
# !TODO: This function has still a weird implementation with the overlapping points
def partial_bezier_points(points: BezierPoints, a: float, b: float) -> BezierPoints:
"""Given an array of points which define bezier curve, and two numbers 0<=a<b<=1, return an array of the same size,
which describes the portion of the original bezier curve on the interval [a, b].
This algorithm is pretty nifty, and pretty dense.
Parameters
----------
points
set of points defining the bezier curve.
a
lower bound of the desired partial bezier curve.
b
upper bound of the desired partial bezier curve.
Returns
-------
np.ndarray
Set of points defining the partial bezier curve.
"""
_len = len(points)
if a == 1:
return np.asarray([points[-1]] * _len, dtype=PointDType)
a_to_1 = np.asarray(
[bezier(points[i:])(a) for i in range(_len)],
dtype=PointDType,
)
end_prop = (b - a) / (1.0 - a)
return np.asarray(
[bezier(a_to_1[: i + 1])(end_prop) for i in range(_len)],
dtype=PointDType,
)
# Shortened version of partial_bezier_points just for quadratics,
# since this is called a fair amount
def partial_quadratic_bezier_points(
points: QuadraticBezierPoints, a: float, b: float
) -> QuadraticBezierPoints:
if a == 1:
return np.asarray(3 * [points[-1]])
def curve(t: float) -> Point3D:
return np.asarray(
points[0] * (1 - t) * (1 - t)
+ 2 * points[1] * t * (1 - t)
+ points[2] * t * t
)
# bezier(points)
h0 = curve(a) if a > 0 else points[0]
h2 = curve(b) if b < 1 else points[2]
h1_prime = (1 - a) * points[1] + a * points[2]
end_prop = (b - a) / (1.0 - a)
h1 = (1 - end_prop) * h0 + end_prop * h1_prime
return np.asarray((h0, h1, h2))
def split_quadratic_bezier(points: QuadraticBezierPoints, t: float) -> BezierPoints:
"""Split a quadratic Bézier curve at argument ``t`` into two quadratic curves.
Parameters
----------
points
The control points of the bezier curve
has shape ``[a1, h1, b1]``
t
The ``t``-value at which to split the Bézier curve
Returns
-------
The two Bézier curves as a list of tuples,
has the shape ``[a1, h1, b1], [a2, h2, b2]``
"""
a1, h1, a2 = points
s1 = interpolate(a1, h1, t)
s2 = interpolate(h1, a2, t)
p = interpolate(s1, s2, t)
return np.array((a1, s1, p, p, s2, a2))
def subdivide_quadratic_bezier(points: QuadraticBezierPoints, n: int) -> BezierPoints:
"""Subdivide a quadratic Bézier curve into ``n`` subcurves which have the same shape.
The points at which the curve is split are located at the
arguments :math:`t = i/n` for :math:`i = 1, ..., n-1`.
Parameters
----------
points
The control points of the Bézier curve in form ``[a1, h1, b1]``
n
The number of curves to subdivide the Bézier curve into
Returns
-------
The new points for the Bézier curve in the form ``[a1, h1, b1, a2, h2, b2, ...]``
.. image:: /_static/bezier_subdivision_example.png
"""
beziers = np.empty((n, 3, 3))
current = points
for j in range(0, n):
i = n - j
tmp = split_quadratic_bezier(current, 1 / i)
beziers[j] = tmp[:3]
current = tmp[3:]
return beziers.reshape(-1, 3)
def quadratic_bezier_remap(
triplets: QuadraticBezierPoints_Array, new_number_of_curves: int
) -> QuadraticBezierPoints_Array:
"""Remaps the number of curves to a higher amount by splitting bezier curves
Parameters
----------
triplets
The triplets of the quadratic bezier curves to be remapped shape(n, 3, 3)
new_number_of_curves
The number of curves that the output will contain. This needs to be higher than the current number.
Returns
-------
The new triplets for the quadratic bezier curves.
"""
difference = new_number_of_curves - len(triplets)
if difference <= 0:
return triplets
new_triplets = np.zeros((new_number_of_curves, 3, 3))
idx = 0
for triplet in triplets:
if difference > 0:
tmp_noc = int(np.ceil(difference / len(triplets))) + 1
tmp = subdivide_quadratic_bezier(triplet, tmp_noc).reshape(-1, 3, 3)
for i in range(tmp_noc):
new_triplets[idx + i] = tmp[i]
difference -= tmp_noc - 1
idx += tmp_noc
else:
new_triplets[idx] = triplet
idx += 1
return new_triplets
"""
This is an alternate version of the function just for documentation purposes
--------
difference = new_number_of_curves - len(triplets)
if difference <= 0:
return triplets
new_triplets = []
for triplet in triplets:
if difference > 0:
tmp_noc = int(np.ceil(difference / len(triplets))) + 1
tmp = subdivide_quadratic_bezier(triplet, tmp_noc).reshape(-1, 3, 3)
for i in range(tmp_noc):
new_triplets.append(tmp[i])
difference -= tmp_noc - 1
else:
new_triplets.append(triplet)
return new_triplets
"""
# Linear interpolation variants
@overload
def interpolate(start: float, end: float, alpha: float) -> float:
...
@overload
def interpolate(start: Point3D, end: Point3D, alpha: float) -> Point3D:
...
def interpolate(
start: int | float | Point3D, end: int | float | Point3D, alpha: float | Point3D
) -> float | Point3D:
return (1 - alpha) * start + alpha * end
def integer_interpolate(
start: float,
end: float,
alpha: float,
) -> tuple[int, float]:
"""
This is a variant of interpolate that returns an integer and the residual
Parameters
----------
start
The start of the range
end
The end of the range
alpha
a float between 0 and 1.
Returns
-------
tuple[int, float]
This returns an integer between start and end (inclusive) representing
appropriate interpolation between them, along with a
"residue" representing a new proportion between the
returned integer and the next one of the
list.
Example
-------
.. code-block:: pycon
>>> integer, residue = integer_interpolate(start=0, end=10, alpha=0.46)
>>> np.allclose((integer, residue), (4, 0.6))
True
"""
if alpha >= 1:
return (int(end - 1), 1.0)
if alpha <= 0:
return (int(start), 0)
value = int(interpolate(start, end, alpha))
residue = ((end - start) * alpha) % 1
return (value, residue)
@overload
def mid(start: float, end: float) -> float:
...
@overload
def mid(start: Point3D, end: Point3D) -> Point3D:
...
def mid(start: float | Point3D, end: float | Point3D) -> float | Point3D:
"""Returns the midpoint between two values.
Parameters
----------
start
The first value
end
The second value
Returns
-------
The midpoint between the two values
"""
return (start + end) / 2.0
@overload
def inverse_interpolate(start: float, end: float, value: float) -> float:
...
@overload
def inverse_interpolate(start: float, end: float, value: Point3D) -> Point3D:
...
@overload
def inverse_interpolate(start: Point3D, end: Point3D, value: Point3D) -> Point3D:
...
def inverse_interpolate(
start: float | Point3D, end: float | Point3D, value: float | Point3D
) -> float | Point3D:
"""Perform inverse interpolation to determine the alpha
values that would produce the specified ``value``
given the ``start`` and ``end`` values or points.
Parameters
----------
start
The start value or point of the interpolation.
end
The end value or point of the interpolation.
value
The value or point for which the alpha value
should be determined.
Returns
-------
The alpha values producing the given input
when interpolating between ``start`` and ``end``.
Example
-------
.. code-block:: pycon
>>> inverse_interpolate(start=2, end=6, value=4)
0.5
>>> start = np.array([1, 2, 1])
>>> end = np.array([7, 8, 11])
>>> value = np.array([4, 5, 5])
>>> inverse_interpolate(start, end, value)
array([0.5, 0.5, 0.4])
"""
return np.true_divide(value - start, end - start)
@overload
def match_interpolate(
new_start: float,
new_end: float,
old_start: float,
old_end: float,
old_value: float,
) -> float:
...
@overload
def match_interpolate(
new_start: float,
new_end: float,
old_start: float,
old_end: float,
old_value: Point3D,
) -> Point3D:
...
def match_interpolate(
new_start: float,
new_end: float,
old_start: float,
old_end: float,
old_value: float | Point3D,
) -> float | Point3D:
"""Interpolate a value from an old range to a new range.
Parameters
----------
new_start
The start of the new range.
new_end
The end of the new range.
old_start
The start of the old range.
old_end
The end of the old range.
old_value
The value within the old range whose corresponding
value in the new range (with the same alpha value)
is desired.
Returns
-------
The interpolated value within the new range.
Examples
--------
>>> match_interpolate(0, 100, 10, 20, 15)
50.0
"""
old_alpha = inverse_interpolate(old_start, old_end, old_value)
return interpolate(
new_start,
new_end,
old_alpha, # type: ignore
)
def get_smooth_cubic_bezier_handle_points(
points: Point3D_Array,
) -> tuple[BezierPoints, BezierPoints]:
points = np.asarray(points)
num_handles = len(points) - 1
dim = points.shape[1]
if num_handles < 1:
return np.zeros((0, dim)), np.zeros((0, dim))
# Must solve 2*num_handles equations to get the handles.
# l and u are the number of lower an upper diagonal rows
# in the matrix to solve.
l, u = 2, 1
# diag is a representation of the matrix in diagonal form
# See https://www.particleincell.com/2012/bezier-splines/
# for how to arrive at these equations
diag: MatrixMN = np.zeros((l + u + 1, 2 * num_handles))
diag[0, 1::2] = -1
diag[0, 2::2] = 1
diag[1, 0::2] = 2
diag[1, 1::2] = 1
diag[2, 1:-2:2] = -2
diag[3, 0:-3:2] = 1
# last
diag[2, -2] = -1
diag[1, -1] = 2
# This is the b as in Ax = b, where we are solving for x,
# and A is represented using diag. However, think of entries
# to x and b as being points in space, not numbers
b: Point3D_Array = np.zeros((2 * num_handles, dim))
b[1::2] = 2 * points[1:]
b[0] = points[0]
b[-1] = points[-1]
def solve_func(b: ColVector) -> ColVector | MatrixMN:
return linalg.solve_banded((l, u), diag, b) # type: ignore
use_closed_solve_function = is_closed(points)
if use_closed_solve_function:
# Get equations to relate first and last points
matrix = diag_to_matrix((l, u), diag)
# last row handles second derivative
matrix[-1, [0, 1, -2, -1]] = [2, -1, 1, -2]
# first row handles first derivative
matrix[0, :] = np.zeros(matrix.shape[1])
matrix[0, [0, -1]] = [1, 1]
b[0] = 2 * points[0]
b[-1] = np.zeros(dim)
def closed_curve_solve_func(b: ColVector) -> ColVector | MatrixMN:
return linalg.solve(matrix, b) # type: ignore
handle_pairs = np.zeros((2 * num_handles, dim))
for i in range(dim):
if use_closed_solve_function:
handle_pairs[:, i] = closed_curve_solve_func(b[:, i])
else:
handle_pairs[:, i] = solve_func(b[:, i])
return handle_pairs[0::2], handle_pairs[1::2]
def get_smooth_handle_points(
points: BezierPoints,
) -> tuple[BezierPoints, BezierPoints]:
"""Given some anchors (points), compute handles so the resulting bezier curve is smooth.
Parameters
----------
points
Anchors.
Returns
-------
typing.Tuple[np.ndarray, np.ndarray]
Computed handles.
"""
# NOTE points here are anchors.
points = np.asarray(points)
num_handles = len(points) - 1
dim = points.shape[1]
if num_handles < 1:
return np.zeros((0, dim)), np.zeros((0, dim))
# Must solve 2*num_handles equations to get the handles.
# l and u are the number of lower an upper diagonal rows
# in the matrix to solve.
l, u = 2, 1
# diag is a representation of the matrix in diagonal form
# See https://www.particleincell.com/2012/bezier-splines/
# for how to arrive at these equations
diag: MatrixMN = np.zeros((l + u + 1, 2 * num_handles))
diag[0, 1::2] = -1
diag[0, 2::2] = 1
diag[1, 0::2] = 2
diag[1, 1::2] = 1
diag[2, 1:-2:2] = -2
diag[3, 0:-3:2] = 1
# last
diag[2, -2] = -1
diag[1, -1] = 2
# This is the b as in Ax = b, where we are solving for x,
# and A is represented using diag. However, think of entries
# to x and b as being points in space, not numbers
b = np.zeros((2 * num_handles, dim))
b[1::2] = 2 * points[1:]
b[0] = points[0]
b[-1] = points[-1]
def solve_func(b: ColVector) -> ColVector | MatrixMN:
return linalg.solve_banded((l, u), diag, b) # type: ignore
use_closed_solve_function = is_closed(points)
if use_closed_solve_function:
# Get equations to relate first and last points
matrix = diag_to_matrix((l, u), diag)
# last row handles second derivative
matrix[-1, [0, 1, -2, -1]] = [2, -1, 1, -2]
# first row handles first derivative
matrix[0, :] = np.zeros(matrix.shape[1])
matrix[0, [0, -1]] = [1, 1]
b[0] = 2 * points[0]
b[-1] = np.zeros(dim)
def closed_curve_solve_func(b: ColVector) -> ColVector | MatrixMN:
return linalg.solve(matrix, b) # type: ignore
handle_pairs = np.zeros((2 * num_handles, dim))
for i in range(dim):
if use_closed_solve_function:
handle_pairs[:, i] = closed_curve_solve_func(b[:, i])
else:
handle_pairs[:, i] = solve_func(b[:, i])
return handle_pairs[0::2], handle_pairs[1::2]
def diag_to_matrix(
l_and_u: tuple[int, int], diag: npt.NDArray[Any]
) -> npt.NDArray[Any]:
"""
Converts array whose rows represent diagonal
entries of a matrix into the matrix itself.
See scipy.linalg.solve_banded
"""
l, u = l_and_u
dim = diag.shape[1]
matrix = np.zeros((dim, dim))
for i in range(l + u + 1):
np.fill_diagonal(
matrix[max(0, i - u) :, max(0, u - i) :],
diag[i, max(0, u - i) :],
)
return matrix
# Given 4 control points for a cubic bezier curve (or arrays of such)
# return control points for 2 quadratics (or 2n quadratics) approximating them.
def get_quadratic_approximation_of_cubic(
a0: Point3D, h0: Point3D, h1: Point3D, a1: Point3D
) -> BezierPoints:
a0 = np.array(a0, ndmin=2)
h0 = np.array(h0, ndmin=2)
h1 = np.array(h1, ndmin=2)
a1 = np.array(a1, ndmin=2)
# Tangent vectors at the start and end.
T0 = h0 - a0
T1 = a1 - h1
# Search for inflection points. If none are found, use the
# midpoint as a cut point.
# Based on http://www.caffeineowl.com/graphics/2d/vectorial/cubic-inflexion.html
has_infl = np.ones(len(a0), dtype=bool)
p = h0 - a0
q = h1 - 2 * h0 + a0
r = a1 - 3 * h1 + 3 * h0 - a0
a = cross2d(q, r)
b = cross2d(p, r)
c = cross2d(p, q)
disc = b * b - 4 * a * c
has_infl &= disc > 0
sqrt_disc = np.sqrt(np.abs(disc))
settings = np.seterr(all="ignore")
ti_bounds = []
for sgn in [-1, +1]:
ti = (-b + sgn * sqrt_disc) / (2 * a)
ti[a == 0] = (-c / b)[a == 0]
ti[(a == 0) & (b == 0)] = 0
ti_bounds.append(ti)
ti_min, ti_max = ti_bounds
np.seterr(**settings)
ti_min_in_range = has_infl & (0 < ti_min) & (ti_min < 1)
ti_max_in_range = has_infl & (0 < ti_max) & (ti_max < 1)
# Choose a value of t which starts at 0.5,
# but is updated to one of the inflection points
# if they lie between 0 and 1
t_mid = 0.5 * np.ones(len(a0))
t_mid[ti_min_in_range] = ti_min[ti_min_in_range]
t_mid[ti_max_in_range] = ti_max[ti_max_in_range]
m, n = a0.shape
t_mid = t_mid.repeat(n).reshape((m, n))
# Compute bezier point and tangent at the chosen value of t (these are vectorized)
mid = bezier([a0, h0, h1, a1])(t_mid) # type: ignore
Tm = bezier([h0 - a0, h1 - h0, a1 - h1])(t_mid) # type: ignore
# Intersection between tangent lines at end points
# and tangent in the middle
i0 = find_intersection(a0, T0, mid, Tm)
i1 = find_intersection(a1, T1, mid, Tm)
m, n = np.shape(a0)
result = np.zeros((6 * m, n))
result[0::6] = a0
result[1::6] = i0
result[2::6] = mid
result[3::6] = mid
result[4::6] = i1
result[5::6] = a1
return result
def is_closed(points: Point3D_Array) -> bool:
return np.allclose(points[0], points[-1]) # type: ignore
def proportions_along_bezier_curve_for_point(
point: Point3D,
control_points: BezierPoints,
round_to: float = 1e-6,
) -> npt.NDArray[Any]:
"""Obtains the proportion along the bezier curve corresponding to a given point
given the bezier curve's control points.
The bezier polynomial is constructed using the coordinates of the given point
as well as the bezier curve's control points. On solving the polynomial for each dimension,
if there are roots common to every dimension, those roots give the proportion along the
curve the point is at. If there are no real roots, the point does not lie on the curve.
Parameters
----------
point
The Cartesian Coordinates of the point whose parameter
should be obtained.
control_points
The Cartesian Coordinates of the ordered control
points of the bezier curve on which the point may
or may not lie.
round_to
A float whose number of decimal places all values
such as coordinates of points will be rounded.
Returns
-------
np.ndarray[float]
List containing possible parameters (the proportions along the bezier curve)
for the given point on the given bezier curve.
This usually only contains one or zero elements, but if the
point is, say, at the beginning/end of a closed loop, may return
a list with more than 1 value, corresponding to the beginning and
end etc. of the loop.
Raises
------
:class:`ValueError`
When ``point`` and the control points have different shapes.
"""
# Method taken from
# http://polymathprogrammer.com/2012/04/03/does-point-lie-on-bezier-curve/
if not all(np.shape(point) == np.shape(c_p) for c_p in control_points):
raise ValueError(
f"Point {point} and Control Points {control_points} have different shapes.",
)
control_points = np.array(control_points)
n = len(control_points) - 1
roots = []
for dim, coord in enumerate(point):
control_coords = control_points[:, dim]
terms = []
for term_power in range(n, -1, -1):
outercoeff = choose(n, term_power)
term = []
sign = 1
for subterm_num in range(term_power, -1, -1):
innercoeff = choose(term_power, subterm_num) * sign
subterm = innercoeff * control_coords[subterm_num]
if term_power == 0:
subterm -= coord
term.append(subterm)
sign *= -1
terms.append(outercoeff * sum(np.array(term)))
if all(term == 0 for term in terms):
# Then both Bezier curve and Point lie on the same plane.
# Roots will be none, but in this specific instance, we don't need to consider that.
continue
bezier_polynom = np.polynomial.Polynomial(terms[::-1])
polynom_roots = bezier_polynom.roots() # type: ignore
if len(polynom_roots) > 0:
polynom_roots = np.around(polynom_roots, int(np.log10(1 / round_to)))
roots.append(polynom_roots)
roots = [[root for root in rootlist if root.imag == 0] for rootlist in roots]
# Get common roots
# arg-type: ignore
roots = reduce(np.intersect1d, roots) # type: ignore
result = np.asarray([r.real for r in roots if 0 <= r.real <= 1])
return result
def point_lies_on_bezier(
point: Point3D,
control_points: BezierPoints,
round_to: float = 1e-6,
) -> bool:
"""Checks if a given point lies on the bezier curves with the given control points.
This is done by solving the bezier polynomial with the point as the constant term; if
any real roots exist, the point lies on the bezier curve.
Parameters
----------
point
The Cartesian Coordinates of the point to check.
control_points
The Cartesian Coordinates of the ordered control
points of the bezier curve on which the point may
or may not lie.
round_to
A float whose number of decimal places all values
such as coordinates of points will be rounded.
Returns
-------
bool
Whether the point lies on the curve.
"""
roots = proportions_along_bezier_curve_for_point(point, control_points, round_to)
return len(roots) > 0
|
manim_ManimCommunity/manim/utils/file_ops.py
|
"""Utility functions for interacting with the file system."""
from __future__ import annotations
__all__ = [
"add_extension_if_not_present",
"guarantee_existence",
"guarantee_empty_existence",
"seek_full_path_from_defaults",
"modify_atime",
"open_file",
"is_mp4_format",
"is_gif_format",
"is_png_format",
"is_webm_format",
"is_mov_format",
"write_to_movie",
"ensure_executable",
]
import os
import platform
import shutil
import subprocess as sp
import time
from pathlib import Path
from shutil import copyfile
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..scene.scene_file_writer import SceneFileWriter
from manim import __version__, config, logger
from .. import console
def is_mp4_format() -> bool:
"""
Determines if output format is .mp4
Returns
-------
class:`bool`
``True`` if format is set as mp4
"""
return config["format"] == "mp4"
def is_gif_format() -> bool:
"""
Determines if output format is .gif
Returns
-------
class:`bool`
``True`` if format is set as gif
"""
return config["format"] == "gif"
def is_webm_format() -> bool:
"""
Determines if output format is .webm
Returns
-------
class:`bool`
``True`` if format is set as webm
"""
return config["format"] == "webm"
def is_mov_format() -> bool:
"""
Determines if output format is .mov
Returns
-------
class:`bool`
``True`` if format is set as mov
"""
return config["format"] == "mov"
def is_png_format() -> bool:
"""
Determines if output format is .png
Returns
-------
class:`bool`
``True`` if format is set as png
"""
return config["format"] == "png"
def write_to_movie() -> bool:
"""
Determines from config if the output is a video format such as mp4 or gif, if the --format is set as 'png'
then it will take precedence event if the write_to_movie flag is set
Returns
-------
class:`bool`
``True`` if the output should be written in a movie format
"""
if is_png_format():
return False
return (
config["write_to_movie"]
or is_mp4_format()
or is_gif_format()
or is_webm_format()
or is_mov_format()
)
def ensure_executable(path_to_exe: Path) -> bool:
if path_to_exe.parent == Path("."):
executable = shutil.which(path_to_exe.stem)
if executable is None:
return False
else:
executable = path_to_exe
return os.access(executable, os.X_OK)
def add_extension_if_not_present(file_name: Path, extension: str) -> Path:
if file_name.suffix != extension:
return file_name.with_suffix(file_name.suffix + extension)
else:
return file_name
def add_version_before_extension(file_name: Path) -> Path:
return file_name.with_name(
f"{file_name.stem}_ManimCE_v{__version__}{file_name.suffix}"
)
def guarantee_existence(path: Path) -> Path:
if not path.exists():
path.mkdir(parents=True)
return path.resolve(strict=True)
def guarantee_empty_existence(path: Path) -> Path:
if path.exists():
shutil.rmtree(str(path))
path.mkdir(parents=True)
return path.resolve(strict=True)
def seek_full_path_from_defaults(
file_name: str, default_dir: Path, extensions: list[str]
) -> Path:
possible_paths = [Path(file_name).expanduser()]
possible_paths += [
Path(default_dir) / f"{file_name}{extension}" for extension in ["", *extensions]
]
for path in possible_paths:
if path.exists():
return path
error = (
f"From: {Path.cwd()}, could not find {file_name} at either "
f"of these locations: {list(map(str, possible_paths))}"
)
raise OSError(error)
def modify_atime(file_path: str) -> None:
"""Will manually change the accessed time (called `atime`) of the file, as on a lot of OS the accessed time refresh is disabled by default.
Parameters
----------
file_path
The path of the file.
"""
os.utime(file_path, times=(time.time(), Path(file_path).stat().st_mtime))
def open_file(file_path, in_browser=False):
current_os = platform.system()
if current_os == "Windows":
os.startfile(file_path if not in_browser else file_path.parent)
else:
if current_os == "Linux":
commands = ["xdg-open"]
file_path = file_path if not in_browser else file_path.parent
elif current_os.startswith("CYGWIN"):
commands = ["cygstart"]
file_path = file_path if not in_browser else file_path.parent
elif current_os == "Darwin":
if is_gif_format():
commands = ["ffplay", "-loglevel", config["ffmpeg_loglevel"].lower()]
else:
commands = ["open"] if not in_browser else ["open", "-R"]
else:
raise OSError("Unable to identify your operating system...")
commands.append(file_path)
sp.Popen(commands)
def open_media_file(file_writer: SceneFileWriter) -> None:
file_paths = []
if config["save_last_frame"]:
file_paths.append(file_writer.image_file_path)
if write_to_movie() and not is_gif_format():
file_paths.append(file_writer.movie_file_path)
if write_to_movie() and is_gif_format():
file_paths.append(file_writer.gif_file_path)
for file_path in file_paths:
if config["show_in_file_browser"]:
open_file(file_path, True)
if config["preview"]:
open_file(file_path, False)
logger.info(f"Previewed File at: '{file_path}'")
def get_template_names() -> list[str]:
"""Returns template names from the templates directory.
Returns
-------
:class:`list`
"""
template_path = Path.resolve(Path(__file__).parent.parent / "templates")
return [template_name.stem for template_name in template_path.glob("*.mtp")]
def get_template_path() -> Path:
"""Returns the Path of templates directory.
Returns
-------
:class:`Path`
"""
return Path.resolve(Path(__file__).parent.parent / "templates")
def add_import_statement(file: Path):
"""Prepends an import statement in a file
Parameters
----------
file
"""
with file.open("r+") as f:
import_line = "from manim import *"
content = f.read()
f.seek(0)
f.write(import_line + "\n" + content)
def copy_template_files(
project_dir: Path = Path("."), template_name: str = "Default"
) -> None:
"""Copies template files from templates dir to project_dir.
Parameters
----------
project_dir
Path to project directory.
template_name
Name of template.
"""
template_cfg_path = Path.resolve(
Path(__file__).parent.parent / "templates/template.cfg",
)
template_scene_path = Path.resolve(
Path(__file__).parent.parent / f"templates/{template_name}.mtp",
)
if not template_cfg_path.exists():
raise FileNotFoundError(f"{template_cfg_path} : file does not exist")
if not template_scene_path.exists():
raise FileNotFoundError(f"{template_scene_path} : file does not exist")
copyfile(template_cfg_path, Path.resolve(project_dir / "manim.cfg"))
console.print("\n\t[green]copied[/green] [blue]manim.cfg[/blue]\n")
copyfile(template_scene_path, Path.resolve(project_dir / "main.py"))
console.print("\n\t[green]copied[/green] [blue]main.py[/blue]\n")
add_import_statement(Path.resolve(project_dir / "main.py"))
|
manim_ManimCommunity/manim/utils/parameter_parsing.py
|
from __future__ import annotations
from types import GeneratorType
from typing import Iterable, TypeVar
T = TypeVar("T")
def flatten_iterable_parameters(
args: Iterable[T | Iterable[T] | GeneratorType],
) -> list[T]:
"""Flattens an iterable of parameters into a list of parameters.
Parameters
----------
args
The iterable of parameters to flatten.
[(generator), [], (), ...]
Returns
-------
:class:`list`
The flattened list of parameters.
"""
flattened_parameters = []
for arg in args:
if isinstance(arg, (Iterable, GeneratorType)):
flattened_parameters.extend(arg)
else:
flattened_parameters.append(arg)
return flattened_parameters
|
manim_ManimCommunity/manim/utils/sounds.py
|
"""Sound-related utility functions."""
from __future__ import annotations
__all__ = [
"get_full_sound_file_path",
]
from .. import config
from ..utils.file_ops import seek_full_path_from_defaults
# Still in use by add_sound() function in scene_file_writer.py
def get_full_sound_file_path(sound_file_name):
return seek_full_path_from_defaults(
sound_file_name,
default_dir=config.get_dir("assets_dir"),
extensions=[".wav", ".mp3"],
)
|
manim_ManimCommunity/manim/utils/docbuild/__init__.py
|
"""Utilities for building the Manim documentation.
For more information about the Manim documentation building, see:
- :doc:`/contributing/development`, specifically the ``Documentation``
bullet point under :ref:`polishing-changes-and-submitting-a-pull-request`
- :doc:`/contributing/docs`
.. autosummary::
:toctree: ../reference
autoaliasattr_directive
autocolor_directive
manim_directive
module_parsing
"""
|
manim_ManimCommunity/manim/utils/docbuild/module_parsing.py
|
"""Read and parse all the Manim modules and extract documentation from them."""
from __future__ import annotations
import ast
from pathlib import Path
from typing_extensions import TypeAlias
__all__ = ["parse_module_attributes"]
AliasInfo: TypeAlias = dict[str, str]
"""Dictionary with a `definition` key containing the definition of
a :class:`TypeAlias` as a string, and optionally a `doc` key containing
the documentation for that alias, if it exists.
"""
AliasCategoryDict: TypeAlias = dict[str, AliasInfo]
"""Dictionary which holds an `AliasInfo` for every alias name in a same
category.
"""
ModuleLevelAliasDict: TypeAlias = dict[str, AliasCategoryDict]
"""Dictionary containing every :class:`TypeAlias` defined in a module,
classified by category in different `AliasCategoryDict` objects.
"""
AliasDocsDict: TypeAlias = dict[str, ModuleLevelAliasDict]
"""Dictionary which, for every module in Manim, contains documentation
about their module-level attributes which are explicitly defined as
:class:`TypeAlias`, separating them from the rest of attributes.
"""
DataDict: TypeAlias = dict[str, list[str]]
"""Type for a dictionary which, for every module, contains a list with
the names of all their DOCUMENTED module-level attributes (identified
by Sphinx via the ``data`` role, hence the name) which are NOT
explicitly defined as :class:`TypeAlias`.
"""
ALIAS_DOCS_DICT: AliasDocsDict = {}
DATA_DICT: DataDict = {}
MANIM_ROOT = Path(__file__).resolve().parent.parent.parent
def parse_module_attributes() -> tuple[AliasDocsDict, DataDict]:
"""Read all files, generate Abstract Syntax Trees from them, and
extract useful information about the type aliases defined in the
files: the category they belong to, their definition and their
description, separating them from the "regular" module attributes.
Returns
-------
ALIAS_DOCS_DICT : `AliasDocsDict`
A dictionary containing the information from all the type
aliases in Manim. See `AliasDocsDict` for more information.
DATA_DICT : `DataDict`
A dictionary containing the names of all DOCUMENTED
module-level attributes which are not a :class:`TypeAlias`.
"""
global ALIAS_DOCS_DICT
global DATA_DICT
if ALIAS_DOCS_DICT or DATA_DICT:
return ALIAS_DOCS_DICT, DATA_DICT
for module_path in MANIM_ROOT.rglob("*.py"):
module_name = module_path.resolve().relative_to(MANIM_ROOT)
module_name = list(module_name.parts)
module_name[-1] = module_name[-1][:-3] # remove .py
module_name = ".".join(module_name)
module_content = module_path.read_text(encoding="utf-8")
# For storing TypeAliases
module_dict: ModuleLevelAliasDict = {}
category_dict: AliasCategoryDict | None = None
alias_info: AliasInfo | None = None
# For storing regular module attributes
data_list: list[str] = []
data_name: str | None = None
for node in ast.iter_child_nodes(ast.parse(module_content)):
# If we encounter a string:
if (
type(node) is ast.Expr
and type(node.value) is ast.Constant
and type(node.value.value) is str
):
string = node.value.value.strip()
# It can be the start of a category
section_str = "[CATEGORY]"
if string.startswith(section_str):
category_name = string[len(section_str) :].strip()
module_dict[category_name] = {}
category_dict = module_dict[category_name]
alias_info = None
# or a docstring of the alias defined before
elif alias_info:
alias_info["doc"] = string
# or a docstring of the module attribute defined before
elif data_name:
data_list.append(data_name)
continue
# If we encounter an assignment annotated as "TypeAlias":
if (
type(node) is ast.AnnAssign
and type(node.annotation) is ast.Name
and node.annotation.id == "TypeAlias"
and type(node.target) is ast.Name
and node.value is not None
):
alias_name = node.target.id
def_node = node.value
# If it's an Union, replace it with vertical bar notation
if (
type(def_node) is ast.Subscript
and type(def_node.value) is ast.Name
and def_node.value.id == "Union"
):
definition = " | ".join(
ast.unparse(elem) for elem in def_node.slice.elts
)
else:
definition = ast.unparse(def_node)
definition = definition.replace("npt.", "")
if category_dict is None:
module_dict[""] = {}
category_dict = module_dict[""]
category_dict[alias_name] = {"definition": definition}
alias_info = category_dict[alias_name]
continue
# If here, the node is not a TypeAlias definition
alias_info = None
# It could still be a module attribute definition.
# Does the assignment have a target of type Name? Then
# it could be considered a definition of a module attribute.
if type(node) is ast.AnnAssign:
target = node.target
elif type(node) is ast.Assign and len(node.targets) == 1:
target = node.targets[0]
else:
target = None
if type(target) is ast.Name:
data_name = target.id
else:
data_name = None
if len(module_dict) > 0:
ALIAS_DOCS_DICT[module_name] = module_dict
if len(data_list) > 0:
DATA_DICT[module_name] = data_list
return ALIAS_DOCS_DICT, DATA_DICT
|
manim_ManimCommunity/manim/utils/docbuild/autocolor_directive.py
|
"""A directive for documenting colors in Manim."""
from __future__ import annotations
import inspect
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive
from manim import ManimColor
if TYPE_CHECKING:
from sphinx.application import Sphinx
__all__ = ["ManimColorModuleDocumenter"]
def setup(app: Sphinx) -> None:
app.add_directive("automanimcolormodule", ManimColorModuleDocumenter)
class ManimColorModuleDocumenter(Directive):
objtype = "automanimcolormodule"
required_arguments = 1
has_content = True
def add_directive_header(self, sig: str) -> None:
super().add_directive_header(sig)
def run(self) -> list[nodes.Element]:
module_name = self.arguments[0]
try:
import importlib
module = importlib.import_module(module_name)
except ImportError:
return [
nodes.error(
None,
nodes.paragraph(text="Failed to import module '%s'" % module_name),
)
]
# Number of Colors displayed in one row
num_color_cols = 2
table = nodes.table(align="center")
tgroup = nodes.tgroup(cols=num_color_cols * 2)
table += tgroup
for _ in range(num_color_cols * 2):
tgroup += nodes.colspec(colwidth=1)
# Create header rows for the table
thead = nodes.thead()
row = nodes.row()
for _ in range(num_color_cols):
col1 = nodes.paragraph(text="Color Name")
col2 = nodes.paragraph(text="RGB Hex Code")
row += nodes.entry("", col1)
row += nodes.entry("", col2)
thead += row
tgroup += thead
color_elements = []
for member_name, member_obj in inspect.getmembers(module):
if isinstance(member_obj, ManimColor):
r, g, b = member_obj.to_rgb()
luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
# Choose the font color based on the background luminance
if luminance > 0.5:
font_color = "black"
else:
font_color = "white"
color_elements.append((member_name, member_obj.to_hex(), font_color))
tbody = nodes.tbody()
for base_i in range(0, len(color_elements), num_color_cols):
row = nodes.row()
for member_name, hex_code, font_color in color_elements[
base_i : base_i + num_color_cols
]:
col1 = nodes.literal(text=member_name)
col2 = nodes.raw(
"",
f'<div style="background-color:{hex_code};padding: 0.25rem 0;border-radius:8px;margin: 0.5rem 0.2rem"><code style="color:{font_color};">{hex_code}</code></div>',
format="html",
)
row += nodes.entry("", col1)
row += nodes.entry("", col2)
tbody += row
tgroup += tbody
return [table]
|
manim_ManimCommunity/manim/utils/docbuild/manim_directive.py
|
r"""
A directive for including Manim videos in a Sphinx document
===========================================================
When rendering the HTML documentation, the ``.. manim::`` directive
implemented here allows to include rendered videos.
Its basic usage that allows processing **inline content**
looks as follows::
.. manim:: MyScene
class MyScene(Scene):
def construct(self):
...
It is required to pass the name of the class representing the
scene to be rendered to the directive.
As a second application, the directive can also be used to
render scenes that are defined within doctests, for example::
.. manim:: DirectiveDoctestExample
:ref_classes: Dot
>>> from manim import Create, Dot, RED, Scene
>>> dot = Dot(color=RED)
>>> dot.color
ManimColor('#FC6255')
>>> class DirectiveDoctestExample(Scene):
... def construct(self):
... self.play(Create(dot))
Options
-------
Options can be passed as follows::
.. manim:: <Class name>
:<option name>: <value>
The following configuration options are supported by the
directive:
hide_source
If this flag is present without argument,
the source code is not displayed above the rendered video.
no_autoplay
If this flag is present without argument,
the video will not autoplay.
quality : {'low', 'medium', 'high', 'fourk'}
Controls render quality of the video, in analogy to
the corresponding command line flags.
save_as_gif
If this flag is present without argument,
the scene is rendered as a gif.
save_last_frame
If this flag is present without argument,
an image representing the last frame of the scene will
be rendered and displayed, instead of a video.
ref_classes
A list of classes, separated by spaces, that is
rendered in a reference block after the source code.
ref_functions
A list of functions, separated by spaces,
that is rendered in a reference block after the source code.
ref_methods
A list of methods, separated by spaces,
that is rendered in a reference block after the source code.
"""
from __future__ import annotations
import csv
import itertools as it
import os
import re
import shutil
import sys
import textwrap
from pathlib import Path
from timeit import timeit
from typing import TYPE_CHECKING, Any
import jinja2
from docutils import nodes
from docutils.parsers.rst import Directive, directives # type: ignore
from docutils.statemachine import StringList
from manim import QUALITIES
from manim import __version__ as manim_version
if TYPE_CHECKING:
from sphinx.application import Sphinx
__all__ = ["ManimDirective"]
classnamedict: dict[str, int] = {}
class SkipManimNode(nodes.Admonition, nodes.Element):
"""Auxiliary node class that is used when the ``skip-manim`` tag is present
or ``.pot`` files are being built.
Skips rendering the manim directive and outputs a placeholder instead.
"""
pass
def visit(self: SkipManimNode, node: nodes.Element, name: str = "") -> None:
self.visit_admonition(node, name)
if not isinstance(node[0], nodes.title):
node.insert(0, nodes.title("skip-manim", "Example Placeholder"))
def depart(self: SkipManimNode, node: nodes.Element) -> None:
self.depart_admonition(node)
def process_name_list(option_input: str, reference_type: str) -> list[str]:
r"""Reformats a string of space separated class names
as a list of strings containing valid Sphinx references.
Tests
-----
::
>>> process_name_list("Tex TexTemplate", "class")
[':class:`~.Tex`', ':class:`~.TexTemplate`']
>>> process_name_list("Scene.play Mobject.rotate", "func")
[':func:`~.Scene.play`', ':func:`~.Mobject.rotate`']
"""
return [f":{reference_type}:`~.{name}`" for name in option_input.split()]
class ManimDirective(Directive):
r"""The manim directive, rendering videos while building
the documentation.
See the module docstring for documentation.
"""
has_content = True
required_arguments = 1
optional_arguments = 0
option_spec = {
"hide_source": bool,
"no_autoplay": bool,
"quality": lambda arg: directives.choice(
arg,
("low", "medium", "high", "fourk"),
),
"save_as_gif": bool,
"save_last_frame": bool,
"ref_modules": lambda arg: process_name_list(arg, "mod"),
"ref_classes": lambda arg: process_name_list(arg, "class"),
"ref_functions": lambda arg: process_name_list(arg, "func"),
"ref_methods": lambda arg: process_name_list(arg, "meth"),
}
final_argument_whitespace = True
def run(self) -> list[nodes.Element]:
# Rendering is skipped if the tag skip-manim is present,
# or if we are making the pot-files
should_skip = (
"skip-manim" in self.state.document.settings.env.app.builder.tags.tags
or self.state.document.settings.env.app.builder.name == "gettext"
)
if should_skip:
clsname = self.arguments[0]
node = SkipManimNode()
self.state.nested_parse(
StringList(
[
f"Placeholder block for ``{clsname}``.",
"",
".. code-block:: python",
"",
]
+ [" " + line for line in self.content]
+ [
"",
".. raw:: html",
"",
f' <pre data-manim-binder data-manim-classname="{clsname}">',
]
+ [" " + line for line in self.content]
+ [" </pre>"],
),
self.content_offset,
node,
)
return [node]
from manim import config, tempconfig
global classnamedict
clsname = self.arguments[0]
if clsname not in classnamedict:
classnamedict[clsname] = 1
else:
classnamedict[clsname] += 1
hide_source = "hide_source" in self.options
no_autoplay = "no_autoplay" in self.options
save_as_gif = "save_as_gif" in self.options
save_last_frame = "save_last_frame" in self.options
assert not (save_as_gif and save_last_frame)
ref_content = (
self.options.get("ref_modules", [])
+ self.options.get("ref_classes", [])
+ self.options.get("ref_functions", [])
+ self.options.get("ref_methods", [])
)
if ref_content:
ref_block = "References: " + " ".join(ref_content)
else:
ref_block = ""
if "quality" in self.options:
quality = f'{self.options["quality"]}_quality'
else:
quality = "example_quality"
frame_rate = QUALITIES[quality]["frame_rate"]
pixel_height = QUALITIES[quality]["pixel_height"]
pixel_width = QUALITIES[quality]["pixel_width"]
state_machine = self.state_machine
document = state_machine.document
source_file_name = Path(document.attributes["source"])
source_rel_name = source_file_name.relative_to(setup.confdir)
source_rel_dir = source_rel_name.parents[0]
dest_dir = Path(setup.app.builder.outdir, source_rel_dir).absolute()
if not dest_dir.exists():
dest_dir.mkdir(parents=True, exist_ok=True)
source_block = [
".. code-block:: python",
"",
" from manim import *\n",
*(" " + line for line in self.content),
"",
".. raw:: html",
"",
f' <pre data-manim-binder data-manim-classname="{clsname}">',
*(" " + line for line in self.content),
"",
" </pre>",
]
source_block = "\n".join(source_block)
config.media_dir = (Path(setup.confdir) / "media").absolute()
config.images_dir = "{media_dir}/images"
config.video_dir = "{media_dir}/videos/{quality}"
output_file = f"{clsname}-{classnamedict[clsname]}"
config.assets_dir = Path("_static")
config.progress_bar = "none"
config.verbosity = "WARNING"
example_config = {
"frame_rate": frame_rate,
"no_autoplay": no_autoplay,
"pixel_height": pixel_height,
"pixel_width": pixel_width,
"save_last_frame": save_last_frame,
"write_to_movie": not save_last_frame,
"output_file": output_file,
}
if save_last_frame:
example_config["format"] = None
if save_as_gif:
example_config["format"] = "gif"
user_code = self.content
if user_code[0].startswith(">>> "): # check whether block comes from doctest
user_code = [
line[4:] for line in user_code if line.startswith((">>> ", "... "))
]
code = [
"from manim import *",
*user_code,
f"{clsname}().render()",
]
try:
with tempconfig(example_config):
run_time = timeit(lambda: exec("\n".join(code), globals()), number=1)
video_dir = config.get_dir("video_dir")
images_dir = config.get_dir("images_dir")
except Exception as e:
raise RuntimeError(f"Error while rendering example {clsname}") from e
_write_rendering_stats(
clsname,
run_time,
self.state.document.settings.env.docname,
)
# copy video file to output directory
if not (save_as_gif or save_last_frame):
filename = f"{output_file}.mp4"
filesrc = video_dir / filename
destfile = Path(dest_dir, filename)
shutil.copyfile(filesrc, destfile)
elif save_as_gif:
filename = f"{output_file}.gif"
filesrc = video_dir / filename
elif save_last_frame:
filename = f"{output_file}.png"
filesrc = images_dir / filename
else:
raise ValueError("Invalid combination of render flags received.")
rendered_template = jinja2.Template(TEMPLATE).render(
clsname=clsname,
clsname_lowercase=clsname.lower(),
hide_source=hide_source,
filesrc_rel=Path(filesrc).relative_to(setup.confdir).as_posix(),
no_autoplay=no_autoplay,
output_file=output_file,
save_last_frame=save_last_frame,
save_as_gif=save_as_gif,
source_block=source_block,
ref_block=ref_block,
)
state_machine.insert_input(
rendered_template.split("\n"),
source=document.attributes["source"],
)
return []
rendering_times_file_path = Path("../rendering_times.csv")
def _write_rendering_stats(scene_name: str, run_time: str, file_name: str) -> None:
with rendering_times_file_path.open("a") as file:
csv.writer(file).writerow(
[
re.sub(r"^(reference\/)|(manim\.)", "", file_name),
scene_name,
"%.3f" % run_time,
],
)
def _log_rendering_times(*args: tuple[Any]) -> None:
if rendering_times_file_path.exists():
with rendering_times_file_path.open() as file:
data = list(csv.reader(file))
if len(data) == 0:
sys.exit()
print("\nRendering Summary\n-----------------\n")
# filter out empty lists caused by csv reader
data = [row for row in data if row]
max_file_length = max(len(row[0]) for row in data)
for key, group in it.groupby(data, key=lambda row: row[0]):
key = key.ljust(max_file_length + 1, ".")
group = list(group)
if len(group) == 1:
row = group[0]
print(f"{key}{row[2].rjust(7, '.')}s {row[1]}")
continue
time_sum = sum(float(row[2]) for row in group)
print(
f"{key}{f'{time_sum:.3f}'.rjust(7, '.')}s => {len(group)} EXAMPLES",
)
for row in group:
print(f"{' '*(max_file_length)} {row[2].rjust(7)}s {row[1]}")
print("")
def _delete_rendering_times(*args: tuple[Any]) -> None:
if rendering_times_file_path.exists():
rendering_times_file_path.unlink()
def setup(app: Sphinx) -> dict[str, Any]:
app.add_node(SkipManimNode, html=(visit, depart))
setup.app = app
setup.config = app.config
setup.confdir = app.confdir
app.add_directive("manim", ManimDirective)
app.connect("builder-inited", _delete_rendering_times)
app.connect("build-finished", _log_rendering_times)
app.add_js_file("manim-binder.min.js")
app.add_js_file(
None,
body=textwrap.dedent(
f"""\
window.initManimBinder({{branch: "v{manim_version}"}})
"""
).strip(),
)
metadata = {"parallel_read_safe": False, "parallel_write_safe": True}
return metadata
TEMPLATE = r"""
{% if not hide_source %}
.. raw:: html
<div id="{{ clsname_lowercase }}" class="admonition admonition-manim-example">
<p class="admonition-title">Example: {{ clsname }} <a class="headerlink" href="#{{ clsname_lowercase }}">¶</a></p>
{% endif %}
{% if not (save_as_gif or save_last_frame) %}
.. raw:: html
<video
class="manim-video"
controls
loop
{{ '' if no_autoplay else 'autoplay' }}
src="./{{ output_file }}.mp4">
</video>
{% elif save_as_gif %}
.. image:: /{{ filesrc_rel }}
:align: center
{% elif save_last_frame %}
.. image:: /{{ filesrc_rel }}
:align: center
{% endif %}
{% if not hide_source %}
{{ source_block }}
{{ ref_block }}
.. raw:: html
</div>
{% endif %}
"""
|
manim_ManimCommunity/manim/utils/docbuild/autoaliasattr_directive.py
|
"""A directive for documenting type aliases and other module-level attributes."""
from __future__ import annotations
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.statemachine import ViewList
from manim.utils.docbuild.module_parsing import parse_module_attributes
if TYPE_CHECKING:
from sphinx.application import Sphinx
from typing_extensions import TypeAlias
__all__ = ["AliasAttrDocumenter"]
ALIAS_DOCS_DICT, DATA_DICT = parse_module_attributes()
ALIAS_LIST = [
alias_name
for module_dict in ALIAS_DOCS_DICT.values()
for category_dict in module_dict.values()
for alias_name in category_dict.keys()
]
def smart_replace(base: str, alias: str, substitution: str) -> str:
"""Auxiliary function for substituting type aliases into a base
string, when there are overlaps between the aliases themselves.
Parameters
----------
base
The string in which the type aliases will be located and
replaced.
alias
The substring to be substituted.
substitution
The string which will replace every occurrence of ``alias``.
Returns
-------
str
The new string after the alias substitution.
"""
occurrences = []
len_alias = len(alias)
len_base = len(base)
condition = lambda char: (not char.isalnum()) and char != "_"
start = 0
i = 0
while True:
i = base.find(alias, start)
if i == -1:
break
if (i == 0 or condition(base[i - 1])) and (
i + len_alias == len_base or condition(base[i + len_alias])
):
occurrences.append(i)
start = i + len_alias
for o in occurrences[::-1]:
base = base[:o] + substitution + base[o + len_alias :]
return base
def setup(app: Sphinx) -> None:
app.add_directive("autoaliasattr", AliasAttrDocumenter)
class AliasAttrDocumenter(Directive):
"""Directive which replaces Sphinx's Autosummary for module-level
attributes: instead, it manually crafts a new "Type Aliases"
section, where all the module-level attributes which are explicitly
annotated as :class:`TypeAlias` are considered as such, for their
use all around the Manim docs.
These type aliases are separated from the "regular" module-level
attributes, which get their traditional "Module Attributes"
section autogenerated with Sphinx's Autosummary under "Type
Aliases".
See ``docs/source/_templates/autosummary/module.rst`` to watch
this directive in action.
See :func:`~.parse_module_attributes` for more information on how
the modules are parsed to obtain the :class:`TypeAlias` information
and separate it from the other attributes.
"""
objtype = "autoaliasattr"
required_arguments = 1
has_content = True
def run(self) -> list[nodes.Element]:
module_name = self.arguments[0]
# Slice module_name[6:] to remove the "manim." prefix which is
# not present in the keys of the DICTs
module_alias_dict = ALIAS_DOCS_DICT.get(module_name[6:], None)
module_attrs_list = DATA_DICT.get(module_name[6:], None)
content = nodes.container()
# Add "Type Aliases" section
if module_alias_dict is not None:
module_alias_section = nodes.section(ids=[f"{module_name}.alias"])
content += module_alias_section
# Use a rubric (title-like), just like in `module.rst`
module_alias_section += nodes.rubric(text="Type Aliases")
# category_name: str
# category_dict: AliasCategoryDict = dict[str, AliasInfo]
for category_name, category_dict in module_alias_dict.items():
category_section = nodes.section(
ids=[category_name.lower().replace(" ", "_")]
)
module_alias_section += category_section
# category_name can be possibly "" for uncategorized aliases
if category_name:
category_section += nodes.title(text=category_name)
category_alias_container = nodes.container()
category_section += category_alias_container
# alias_name: str
# alias_info: AliasInfo = dict[str, str]
# Contains "definition": str
# Can possibly contain "doc": str
for alias_name, alias_info in category_dict.items():
# Replace all occurrences of type aliases in the
# definition for automatic cross-referencing!
alias_def = alias_info["definition"]
for A in ALIAS_LIST:
alias_def = smart_replace(alias_def, A, f":class:`~.{A}`")
# Using the `.. class::` directive is CRUCIAL, since
# function/method parameters are always annotated via
# classes - therefore Sphinx expects a class
unparsed = ViewList(
[
f".. class:: {alias_name}",
"",
" .. parsed-literal::",
"",
f" {alias_def}",
"",
]
)
if "doc" in alias_info:
# Replace all occurrences of type aliases in
# the docs for automatic cross-referencing!
alias_doc = alias_info["doc"]
for A in ALIAS_LIST:
alias_doc = alias_doc.replace(f"`{A}`", f":class:`~.{A}`")
# Add all the lines with 4 spaces behind, to consider all the
# documentation as a paragraph INSIDE the `.. class::` block
doc_lines = alias_doc.split("\n")
unparsed.extend(ViewList([f" {line}" for line in doc_lines]))
# Parse the reST text into a fresh container
# https://www.sphinx-doc.org/en/master/extdev/markupapi.html#parsing-directive-content-as-rest
alias_container = nodes.container()
self.state.nested_parse(unparsed, 0, alias_container)
category_alias_container += alias_container
# Then, add the traditional "Module Attributes" section
if module_attrs_list is not None:
module_attrs_section = nodes.section(ids=[f"{module_name}.data"])
content += module_attrs_section
# Use the same rubric (title-like) as in `module.rst`
module_attrs_section += nodes.rubric(text="Module Attributes")
# Let Sphinx Autosummary do its thing as always
# Add all the attribute names with 4 spaces behind, so that
# they're considered as INSIDE the `.. autosummary::` block
unparsed = ViewList(
[
".. autosummary::",
*(f" {attr}" for attr in module_attrs_list),
]
)
# Parse the reST text into a fresh container
# https://www.sphinx-doc.org/en/master/extdev/markupapi.html#parsing-directive-content-as-rest
data_container = nodes.container()
self.state.nested_parse(unparsed, 0, data_container)
module_attrs_section += data_container
return [content]
|
manim_ManimCommunity/manim/utils/color/XKCD.py
|
"""Colors from the XKCD Color Name Survey
XKCD is a popular `web comic <https://xkcd.com/353/>`__ created by Randall Munroe.
His "`Color Name Survey <http://blog.xkcd.com/2010/05/03/color-survey-results/>`__" (with
200000 participants) resulted in a list of nearly 1000 color names.
While the ``XKCD`` module is exposed to Manim's global name space, the colors included
in it are not. This means that in order to use the colors, access them via the module name:
.. code:: pycon
>>> from manim import XKCD
>>> XKCD.MANGO
ManimColor('#FFA62B')
List of Color Constants
-----------------------
These hex values are non official approximate values intended to simulate the colors in HTML,
taken from https://www.w3schools.com/colors/colors_xkcd.asp.
.. automanimcolormodule:: manim.utils.color.XKCD
"""
from .core import ManimColor
ACIDGREEN = ManimColor("#8FFE09")
ADOBE = ManimColor("#BD6C48")
ALGAE = ManimColor("#54AC68")
ALGAEGREEN = ManimColor("#21C36F")
ALMOSTBLACK = ManimColor("#070D0D")
AMBER = ManimColor("#FEB308")
AMETHYST = ManimColor("#9B5FC0")
APPLE = ManimColor("#6ECB3C")
APPLEGREEN = ManimColor("#76CD26")
APRICOT = ManimColor("#FFB16D")
AQUA = ManimColor("#13EAC9")
AQUABLUE = ManimColor("#02D8E9")
AQUAGREEN = ManimColor("#12E193")
AQUAMARINE = ManimColor("#2EE8BB")
ARMYGREEN = ManimColor("#4B5D16")
ASPARAGUS = ManimColor("#77AB56")
AUBERGINE = ManimColor("#3D0734")
AUBURN = ManimColor("#9A3001")
AVOCADO = ManimColor("#90B134")
AVOCADOGREEN = ManimColor("#87A922")
AZUL = ManimColor("#1D5DEC")
AZURE = ManimColor("#069AF3")
BABYBLUE = ManimColor("#A2CFFE")
BABYGREEN = ManimColor("#8CFF9E")
BABYPINK = ManimColor("#FFB7CE")
BABYPOO = ManimColor("#AB9004")
BABYPOOP = ManimColor("#937C00")
BABYPOOPGREEN = ManimColor("#8F9805")
BABYPUKEGREEN = ManimColor("#B6C406")
BABYPURPLE = ManimColor("#CA9BF7")
BABYSHITBROWN = ManimColor("#AD900D")
BABYSHITGREEN = ManimColor("#889717")
BANANA = ManimColor("#FFFF7E")
BANANAYELLOW = ManimColor("#FAFE4B")
BARBIEPINK = ManimColor("#FE46A5")
BARFGREEN = ManimColor("#94AC02")
BARNEY = ManimColor("#AC1DB8")
BARNEYPURPLE = ManimColor("#A00498")
BATTLESHIPGREY = ManimColor("#6B7C85")
BEIGE = ManimColor("#E6DAA6")
BERRY = ManimColor("#990F4B")
BILE = ManimColor("#B5C306")
BLACK = ManimColor("#000000")
BLAND = ManimColor("#AFA88B")
BLOOD = ManimColor("#770001")
BLOODORANGE = ManimColor("#FE4B03")
BLOODRED = ManimColor("#980002")
BLUE = ManimColor("#0343DF")
BLUEBERRY = ManimColor("#464196")
BLUEBLUE = ManimColor("#2242C7")
BLUEGREEN = ManimColor("#0F9B8E")
BLUEGREY = ManimColor("#85A3B2")
BLUEPURPLE = ManimColor("#5A06EF")
BLUEVIOLET = ManimColor("#5D06E9")
BLUEWITHAHINTOFPURPLE = ManimColor("#533CC6")
BLUEYGREEN = ManimColor("#2BB179")
BLUEYGREY = ManimColor("#89A0B0")
BLUEYPURPLE = ManimColor("#6241C7")
BLUISH = ManimColor("#2976BB")
BLUISHGREEN = ManimColor("#10A674")
BLUISHGREY = ManimColor("#748B97")
BLUISHPURPLE = ManimColor("#703BE7")
BLURPLE = ManimColor("#5539CC")
BLUSH = ManimColor("#F29E8E")
BLUSHPINK = ManimColor("#FE828C")
BOOGER = ManimColor("#9BB53C")
BOOGERGREEN = ManimColor("#96B403")
BORDEAUX = ManimColor("#7B002C")
BORINGGREEN = ManimColor("#63B365")
BOTTLEGREEN = ManimColor("#044A05")
BRICK = ManimColor("#A03623")
BRICKORANGE = ManimColor("#C14A09")
BRICKRED = ManimColor("#8F1402")
BRIGHTAQUA = ManimColor("#0BF9EA")
BRIGHTBLUE = ManimColor("#0165FC")
BRIGHTCYAN = ManimColor("#41FDFE")
BRIGHTGREEN = ManimColor("#01FF07")
BRIGHTLAVENDER = ManimColor("#C760FF")
BRIGHTLIGHTBLUE = ManimColor("#26F7FD")
BRIGHTLIGHTGREEN = ManimColor("#2DFE54")
BRIGHTLILAC = ManimColor("#C95EFB")
BRIGHTLIME = ManimColor("#87FD05")
BRIGHTLIMEGREEN = ManimColor("#65FE08")
BRIGHTMAGENTA = ManimColor("#FF08E8")
BRIGHTOLIVE = ManimColor("#9CBB04")
BRIGHTORANGE = ManimColor("#FF5B00")
BRIGHTPINK = ManimColor("#FE01B1")
BRIGHTPURPLE = ManimColor("#BE03FD")
BRIGHTRED = ManimColor("#FF000D")
BRIGHTSEAGREEN = ManimColor("#05FFA6")
BRIGHTSKYBLUE = ManimColor("#02CCFE")
BRIGHTTEAL = ManimColor("#01F9C6")
BRIGHTTURQUOISE = ManimColor("#0FFEF9")
BRIGHTVIOLET = ManimColor("#AD0AFD")
BRIGHTYELLOW = ManimColor("#FFFD01")
BRIGHTYELLOWGREEN = ManimColor("#9DFF00")
BRITISHRACINGGREEN = ManimColor("#05480D")
BRONZE = ManimColor("#A87900")
BROWN = ManimColor("#653700")
BROWNGREEN = ManimColor("#706C11")
BROWNGREY = ManimColor("#8D8468")
BROWNISH = ManimColor("#9C6D57")
BROWNISHGREEN = ManimColor("#6A6E09")
BROWNISHGREY = ManimColor("#86775F")
BROWNISHORANGE = ManimColor("#CB7723")
BROWNISHPINK = ManimColor("#C27E79")
BROWNISHPURPLE = ManimColor("#76424E")
BROWNISHRED = ManimColor("#9E3623")
BROWNISHYELLOW = ManimColor("#C9B003")
BROWNORANGE = ManimColor("#B96902")
BROWNRED = ManimColor("#922B05")
BROWNYELLOW = ManimColor("#B29705")
BROWNYGREEN = ManimColor("#6F6C0A")
BROWNYORANGE = ManimColor("#CA6B02")
BRUISE = ManimColor("#7E4071")
BUBBLEGUM = ManimColor("#FF6CB5")
BUBBLEGUMPINK = ManimColor("#FF69AF")
BUFF = ManimColor("#FEF69E")
BURGUNDY = ManimColor("#610023")
BURNTORANGE = ManimColor("#C04E01")
BURNTRED = ManimColor("#9F2305")
BURNTSIENA = ManimColor("#B75203")
BURNTSIENNA = ManimColor("#B04E0F")
BURNTUMBER = ManimColor("#A0450E")
BURNTYELLOW = ManimColor("#D5AB09")
BURPLE = ManimColor("#6832E3")
BUTTER = ManimColor("#FFFF81")
BUTTERSCOTCH = ManimColor("#FDB147")
BUTTERYELLOW = ManimColor("#FFFD74")
CADETBLUE = ManimColor("#4E7496")
CAMEL = ManimColor("#C69F59")
CAMO = ManimColor("#7F8F4E")
CAMOGREEN = ManimColor("#526525")
CAMOUFLAGEGREEN = ManimColor("#4B6113")
CANARY = ManimColor("#FDFF63")
CANARYYELLOW = ManimColor("#FFFE40")
CANDYPINK = ManimColor("#FF63E9")
CARAMEL = ManimColor("#AF6F09")
CARMINE = ManimColor("#9D0216")
CARNATION = ManimColor("#FD798F")
CARNATIONPINK = ManimColor("#FF7FA7")
CAROLINABLUE = ManimColor("#8AB8FE")
CELADON = ManimColor("#BEFDB7")
CELERY = ManimColor("#C1FD95")
CEMENT = ManimColor("#A5A391")
CERISE = ManimColor("#DE0C62")
CERULEAN = ManimColor("#0485D1")
CERULEANBLUE = ManimColor("#056EEE")
CHARCOAL = ManimColor("#343837")
CHARCOALGREY = ManimColor("#3C4142")
CHARTREUSE = ManimColor("#C1F80A")
CHERRY = ManimColor("#CF0234")
CHERRYRED = ManimColor("#F7022A")
CHESTNUT = ManimColor("#742802")
CHOCOLATE = ManimColor("#3D1C02")
CHOCOLATEBROWN = ManimColor("#411900")
CINNAMON = ManimColor("#AC4F06")
CLARET = ManimColor("#680018")
CLAY = ManimColor("#B66A50")
CLAYBROWN = ManimColor("#B2713D")
CLEARBLUE = ManimColor("#247AFD")
COBALT = ManimColor("#1E488F")
COBALTBLUE = ManimColor("#030AA7")
COCOA = ManimColor("#875F42")
COFFEE = ManimColor("#A6814C")
COOLBLUE = ManimColor("#4984B8")
COOLGREEN = ManimColor("#33B864")
COOLGREY = ManimColor("#95A3A6")
COPPER = ManimColor("#B66325")
CORAL = ManimColor("#FC5A50")
CORALPINK = ManimColor("#FF6163")
CORNFLOWER = ManimColor("#6A79F7")
CORNFLOWERBLUE = ManimColor("#5170D7")
CRANBERRY = ManimColor("#9E003A")
CREAM = ManimColor("#FFFFC2")
CREME = ManimColor("#FFFFB6")
CRIMSON = ManimColor("#8C000F")
CUSTARD = ManimColor("#FFFD78")
CYAN = ManimColor("#00FFFF")
DANDELION = ManimColor("#FEDF08")
DARK = ManimColor("#1B2431")
DARKAQUA = ManimColor("#05696B")
DARKAQUAMARINE = ManimColor("#017371")
DARKBEIGE = ManimColor("#AC9362")
DARKBLUE = ManimColor("#030764")
DARKBLUEGREEN = ManimColor("#005249")
DARKBLUEGREY = ManimColor("#1F3B4D")
DARKBROWN = ManimColor("#341C02")
DARKCORAL = ManimColor("#CF524E")
DARKCREAM = ManimColor("#FFF39A")
DARKCYAN = ManimColor("#0A888A")
DARKFORESTGREEN = ManimColor("#002D04")
DARKFUCHSIA = ManimColor("#9D0759")
DARKGOLD = ManimColor("#B59410")
DARKGRASSGREEN = ManimColor("#388004")
DARKGREEN = ManimColor("#054907")
DARKGREENBLUE = ManimColor("#1F6357")
DARKGREY = ManimColor("#363737")
DARKGREYBLUE = ManimColor("#29465B")
DARKHOTPINK = ManimColor("#D90166")
DARKINDIGO = ManimColor("#1F0954")
DARKISHBLUE = ManimColor("#014182")
DARKISHGREEN = ManimColor("#287C37")
DARKISHPINK = ManimColor("#DA467D")
DARKISHPURPLE = ManimColor("#751973")
DARKISHRED = ManimColor("#A90308")
DARKKHAKI = ManimColor("#9B8F55")
DARKLAVENDER = ManimColor("#856798")
DARKLILAC = ManimColor("#9C6DA5")
DARKLIME = ManimColor("#84B701")
DARKLIMEGREEN = ManimColor("#7EBD01")
DARKMAGENTA = ManimColor("#960056")
DARKMAROON = ManimColor("#3C0008")
DARKMAUVE = ManimColor("#874C62")
DARKMINT = ManimColor("#48C072")
DARKMINTGREEN = ManimColor("#20C073")
DARKMUSTARD = ManimColor("#A88905")
DARKNAVY = ManimColor("#000435")
DARKNAVYBLUE = ManimColor("#00022E")
DARKOLIVE = ManimColor("#373E02")
DARKOLIVEGREEN = ManimColor("#3C4D03")
DARKORANGE = ManimColor("#C65102")
DARKPASTELGREEN = ManimColor("#56AE57")
DARKPEACH = ManimColor("#DE7E5D")
DARKPERIWINKLE = ManimColor("#665FD1")
DARKPINK = ManimColor("#CB416B")
DARKPLUM = ManimColor("#3F012C")
DARKPURPLE = ManimColor("#35063E")
DARKRED = ManimColor("#840000")
DARKROSE = ManimColor("#B5485D")
DARKROYALBLUE = ManimColor("#02066F")
DARKSAGE = ManimColor("#598556")
DARKSALMON = ManimColor("#C85A53")
DARKSAND = ManimColor("#A88F59")
DARKSEAFOAM = ManimColor("#1FB57A")
DARKSEAFOAMGREEN = ManimColor("#3EAF76")
DARKSEAGREEN = ManimColor("#11875D")
DARKSKYBLUE = ManimColor("#448EE4")
DARKSLATEBLUE = ManimColor("#214761")
DARKTAN = ManimColor("#AF884A")
DARKTAUPE = ManimColor("#7F684E")
DARKTEAL = ManimColor("#014D4E")
DARKTURQUOISE = ManimColor("#045C5A")
DARKVIOLET = ManimColor("#34013F")
DARKYELLOW = ManimColor("#D5B60A")
DARKYELLOWGREEN = ManimColor("#728F02")
DEEPAQUA = ManimColor("#08787F")
DEEPBLUE = ManimColor("#040273")
DEEPBROWN = ManimColor("#410200")
DEEPGREEN = ManimColor("#02590F")
DEEPLAVENDER = ManimColor("#8D5EB7")
DEEPLILAC = ManimColor("#966EBD")
DEEPMAGENTA = ManimColor("#A0025C")
DEEPORANGE = ManimColor("#DC4D01")
DEEPPINK = ManimColor("#CB0162")
DEEPPURPLE = ManimColor("#36013F")
DEEPRED = ManimColor("#9A0200")
DEEPROSE = ManimColor("#C74767")
DEEPSEABLUE = ManimColor("#015482")
DEEPSKYBLUE = ManimColor("#0D75F8")
DEEPTEAL = ManimColor("#00555A")
DEEPTURQUOISE = ManimColor("#017374")
DEEPVIOLET = ManimColor("#490648")
DENIM = ManimColor("#3B638C")
DENIMBLUE = ManimColor("#3B5B92")
DESERT = ManimColor("#CCAD60")
DIARRHEA = ManimColor("#9F8303")
DIRT = ManimColor("#8A6E45")
DIRTBROWN = ManimColor("#836539")
DIRTYBLUE = ManimColor("#3F829D")
DIRTYGREEN = ManimColor("#667E2C")
DIRTYORANGE = ManimColor("#C87606")
DIRTYPINK = ManimColor("#CA7B80")
DIRTYPURPLE = ManimColor("#734A65")
DIRTYYELLOW = ManimColor("#CDC50A")
DODGERBLUE = ManimColor("#3E82FC")
DRAB = ManimColor("#828344")
DRABGREEN = ManimColor("#749551")
DRIEDBLOOD = ManimColor("#4B0101")
DUCKEGGBLUE = ManimColor("#C3FBF4")
DULLBLUE = ManimColor("#49759C")
DULLBROWN = ManimColor("#876E4B")
DULLGREEN = ManimColor("#74A662")
DULLORANGE = ManimColor("#D8863B")
DULLPINK = ManimColor("#D5869D")
DULLPURPLE = ManimColor("#84597E")
DULLRED = ManimColor("#BB3F3F")
DULLTEAL = ManimColor("#5F9E8F")
DULLYELLOW = ManimColor("#EEDC5B")
DUSK = ManimColor("#4E5481")
DUSKBLUE = ManimColor("#26538D")
DUSKYBLUE = ManimColor("#475F94")
DUSKYPINK = ManimColor("#CC7A8B")
DUSKYPURPLE = ManimColor("#895B7B")
DUSKYROSE = ManimColor("#BA6873")
DUST = ManimColor("#B2996E")
DUSTYBLUE = ManimColor("#5A86AD")
DUSTYGREEN = ManimColor("#76A973")
DUSTYLAVENDER = ManimColor("#AC86A8")
DUSTYORANGE = ManimColor("#F0833A")
DUSTYPINK = ManimColor("#D58A94")
DUSTYPURPLE = ManimColor("#825F87")
DUSTYRED = ManimColor("#B9484E")
DUSTYROSE = ManimColor("#C0737A")
DUSTYTEAL = ManimColor("#4C9085")
EARTH = ManimColor("#A2653E")
EASTERGREEN = ManimColor("#8CFD7E")
EASTERPURPLE = ManimColor("#C071FE")
ECRU = ManimColor("#FEFFCA")
EGGPLANT = ManimColor("#380835")
EGGPLANTPURPLE = ManimColor("#430541")
EGGSHELL = ManimColor("#FFFCC4")
EGGSHELLBLUE = ManimColor("#C4FFF7")
ELECTRICBLUE = ManimColor("#0652FF")
ELECTRICGREEN = ManimColor("#21FC0D")
ELECTRICLIME = ManimColor("#A8FF04")
ELECTRICPINK = ManimColor("#FF0490")
ELECTRICPURPLE = ManimColor("#AA23FF")
EMERALD = ManimColor("#01A049")
EMERALDGREEN = ManimColor("#028F1E")
EVERGREEN = ManimColor("#05472A")
FADEDBLUE = ManimColor("#658CBB")
FADEDGREEN = ManimColor("#7BB274")
FADEDORANGE = ManimColor("#F0944D")
FADEDPINK = ManimColor("#DE9DAC")
FADEDPURPLE = ManimColor("#916E99")
FADEDRED = ManimColor("#D3494E")
FADEDYELLOW = ManimColor("#FEFF7F")
FAWN = ManimColor("#CFAF7B")
FERN = ManimColor("#63A950")
FERNGREEN = ManimColor("#548D44")
FIREENGINERED = ManimColor("#FE0002")
FLATBLUE = ManimColor("#3C73A8")
FLATGREEN = ManimColor("#699D4C")
FLUORESCENTGREEN = ManimColor("#08FF08")
FLUROGREEN = ManimColor("#0AFF02")
FOAMGREEN = ManimColor("#90FDA9")
FOREST = ManimColor("#0B5509")
FORESTGREEN = ManimColor("#06470C")
FORRESTGREEN = ManimColor("#154406")
FRENCHBLUE = ManimColor("#436BAD")
FRESHGREEN = ManimColor("#69D84F")
FROGGREEN = ManimColor("#58BC08")
FUCHSIA = ManimColor("#ED0DD9")
GOLD = ManimColor("#DBB40C")
GOLDEN = ManimColor("#F5BF03")
GOLDENBROWN = ManimColor("#B27A01")
GOLDENROD = ManimColor("#F9BC08")
GOLDENYELLOW = ManimColor("#FEC615")
GRAPE = ManimColor("#6C3461")
GRAPEFRUIT = ManimColor("#FD5956")
GRAPEPURPLE = ManimColor("#5D1451")
GRASS = ManimColor("#5CAC2D")
GRASSGREEN = ManimColor("#3F9B0B")
GRASSYGREEN = ManimColor("#419C03")
GREEN = ManimColor("#15B01A")
GREENAPPLE = ManimColor("#5EDC1F")
GREENBLUE = ManimColor("#01C08D")
GREENBROWN = ManimColor("#544E03")
GREENGREY = ManimColor("#77926F")
GREENISH = ManimColor("#40A368")
GREENISHBEIGE = ManimColor("#C9D179")
GREENISHBLUE = ManimColor("#0B8B87")
GREENISHBROWN = ManimColor("#696112")
GREENISHCYAN = ManimColor("#2AFEB7")
GREENISHGREY = ManimColor("#96AE8D")
GREENISHTAN = ManimColor("#BCCB7A")
GREENISHTEAL = ManimColor("#32BF84")
GREENISHTURQUOISE = ManimColor("#00FBB0")
GREENISHYELLOW = ManimColor("#CDFD02")
GREENTEAL = ManimColor("#0CB577")
GREENYBLUE = ManimColor("#42B395")
GREENYBROWN = ManimColor("#696006")
GREENYELLOW = ManimColor("#B5CE08")
GREENYGREY = ManimColor("#7EA07A")
GREENYYELLOW = ManimColor("#C6F808")
GREY = ManimColor("#929591")
GREYBLUE = ManimColor("#647D8E")
GREYBROWN = ManimColor("#7F7053")
GREYGREEN = ManimColor("#86A17D")
GREYISH = ManimColor("#A8A495")
GREYISHBLUE = ManimColor("#5E819D")
GREYISHBROWN = ManimColor("#7A6A4F")
GREYISHGREEN = ManimColor("#82A67D")
GREYISHPINK = ManimColor("#C88D94")
GREYISHPURPLE = ManimColor("#887191")
GREYISHTEAL = ManimColor("#719F91")
GREYPINK = ManimColor("#C3909B")
GREYPURPLE = ManimColor("#826D8C")
GREYTEAL = ManimColor("#5E9B8A")
GROSSGREEN = ManimColor("#A0BF16")
GUNMETAL = ManimColor("#536267")
HAZEL = ManimColor("#8E7618")
HEATHER = ManimColor("#A484AC")
HELIOTROPE = ManimColor("#D94FF5")
HIGHLIGHTERGREEN = ManimColor("#1BFC06")
HOSPITALGREEN = ManimColor("#9BE5AA")
HOTGREEN = ManimColor("#25FF29")
HOTMAGENTA = ManimColor("#F504C9")
HOTPINK = ManimColor("#FF028D")
HOTPURPLE = ManimColor("#CB00F5")
HUNTERGREEN = ManimColor("#0B4008")
ICE = ManimColor("#D6FFFA")
ICEBLUE = ManimColor("#D7FFFE")
ICKYGREEN = ManimColor("#8FAE22")
INDIANRED = ManimColor("#850E04")
INDIGO = ManimColor("#380282")
INDIGOBLUE = ManimColor("#3A18B1")
IRIS = ManimColor("#6258C4")
IRISHGREEN = ManimColor("#019529")
IVORY = ManimColor("#FFFFCB")
JADE = ManimColor("#1FA774")
JADEGREEN = ManimColor("#2BAF6A")
JUNGLEGREEN = ManimColor("#048243")
KELLEYGREEN = ManimColor("#009337")
KELLYGREEN = ManimColor("#02AB2E")
KERMITGREEN = ManimColor("#5CB200")
KEYLIME = ManimColor("#AEFF6E")
KHAKI = ManimColor("#AAA662")
KHAKIGREEN = ManimColor("#728639")
KIWI = ManimColor("#9CEF43")
KIWIGREEN = ManimColor("#8EE53F")
LAVENDER = ManimColor("#C79FEF")
LAVENDERBLUE = ManimColor("#8B88F8")
LAVENDERPINK = ManimColor("#DD85D7")
LAWNGREEN = ManimColor("#4DA409")
LEAF = ManimColor("#71AA34")
LEAFGREEN = ManimColor("#5CA904")
LEAFYGREEN = ManimColor("#51B73B")
LEATHER = ManimColor("#AC7434")
LEMON = ManimColor("#FDFF52")
LEMONGREEN = ManimColor("#ADF802")
LEMONLIME = ManimColor("#BFFE28")
LEMONYELLOW = ManimColor("#FDFF38")
LICHEN = ManimColor("#8FB67B")
LIGHTAQUA = ManimColor("#8CFFDB")
LIGHTAQUAMARINE = ManimColor("#7BFDC7")
LIGHTBEIGE = ManimColor("#FFFEB6")
LIGHTBLUE = ManimColor("#7BC8F6")
LIGHTBLUEGREEN = ManimColor("#7EFBB3")
LIGHTBLUEGREY = ManimColor("#B7C9E2")
LIGHTBLUISHGREEN = ManimColor("#76FDA8")
LIGHTBRIGHTGREEN = ManimColor("#53FE5C")
LIGHTBROWN = ManimColor("#AD8150")
LIGHTBURGUNDY = ManimColor("#A8415B")
LIGHTCYAN = ManimColor("#ACFFFC")
LIGHTEGGPLANT = ManimColor("#894585")
LIGHTERGREEN = ManimColor("#75FD63")
LIGHTERPURPLE = ManimColor("#A55AF4")
LIGHTFORESTGREEN = ManimColor("#4F9153")
LIGHTGOLD = ManimColor("#FDDC5C")
LIGHTGRASSGREEN = ManimColor("#9AF764")
LIGHTGREEN = ManimColor("#76FF7B")
LIGHTGREENBLUE = ManimColor("#56FCA2")
LIGHTGREENISHBLUE = ManimColor("#63F7B4")
LIGHTGREY = ManimColor("#D8DCD6")
LIGHTGREYBLUE = ManimColor("#9DBCD4")
LIGHTGREYGREEN = ManimColor("#B7E1A1")
LIGHTINDIGO = ManimColor("#6D5ACF")
LIGHTISHBLUE = ManimColor("#3D7AFD")
LIGHTISHGREEN = ManimColor("#61E160")
LIGHTISHPURPLE = ManimColor("#A552E6")
LIGHTISHRED = ManimColor("#FE2F4A")
LIGHTKHAKI = ManimColor("#E6F2A2")
LIGHTLAVENDAR = ManimColor("#EFC0FE")
LIGHTLAVENDER = ManimColor("#DFC5FE")
LIGHTLIGHTBLUE = ManimColor("#CAFFFB")
LIGHTLIGHTGREEN = ManimColor("#C8FFB0")
LIGHTLILAC = ManimColor("#EDC8FF")
LIGHTLIME = ManimColor("#AEFD6C")
LIGHTLIMEGREEN = ManimColor("#B9FF66")
LIGHTMAGENTA = ManimColor("#FA5FF7")
LIGHTMAROON = ManimColor("#A24857")
LIGHTMAUVE = ManimColor("#C292A1")
LIGHTMINT = ManimColor("#B6FFBB")
LIGHTMINTGREEN = ManimColor("#A6FBB2")
LIGHTMOSSGREEN = ManimColor("#A6C875")
LIGHTMUSTARD = ManimColor("#F7D560")
LIGHTNAVY = ManimColor("#155084")
LIGHTNAVYBLUE = ManimColor("#2E5A88")
LIGHTNEONGREEN = ManimColor("#4EFD54")
LIGHTOLIVE = ManimColor("#ACBF69")
LIGHTOLIVEGREEN = ManimColor("#A4BE5C")
LIGHTORANGE = ManimColor("#FDAA48")
LIGHTPASTELGREEN = ManimColor("#B2FBA5")
LIGHTPEACH = ManimColor("#FFD8B1")
LIGHTPEAGREEN = ManimColor("#C4FE82")
LIGHTPERIWINKLE = ManimColor("#C1C6FC")
LIGHTPINK = ManimColor("#FFD1DF")
LIGHTPLUM = ManimColor("#9D5783")
LIGHTPURPLE = ManimColor("#BF77F6")
LIGHTRED = ManimColor("#FF474C")
LIGHTROSE = ManimColor("#FFC5CB")
LIGHTROYALBLUE = ManimColor("#3A2EFE")
LIGHTSAGE = ManimColor("#BCECAC")
LIGHTSALMON = ManimColor("#FEA993")
LIGHTSEAFOAM = ManimColor("#A0FEBF")
LIGHTSEAFOAMGREEN = ManimColor("#a7ffb5")
LIGHTSEAGREEN = ManimColor("#98F6B0")
LIGHTSKYBLUE = ManimColor("#C6FCFF")
LIGHTTAN = ManimColor("#FBEEAC")
LIGHTTEAL = ManimColor("#90E4C1")
LIGHTTURQUOISE = ManimColor("#7EF4CC")
LIGHTURPLE = ManimColor("#B36FF6")
LIGHTVIOLET = ManimColor("#D6B4FC")
LIGHTYELLOW = ManimColor("#FFFE7A")
LIGHTYELLOWGREEN = ManimColor("#CCFD7F")
LIGHTYELLOWISHGREEN = ManimColor("#C2FF89")
LILAC = ManimColor("#CEA2FD")
LILIAC = ManimColor("#C48EFD")
LIME = ManimColor("#AAFF32")
LIMEGREEN = ManimColor("#89FE05")
LIMEYELLOW = ManimColor("#D0FE1D")
LIPSTICK = ManimColor("#D5174E")
LIPSTICKRED = ManimColor("#C0022F")
MACARONIANDCHEESE = ManimColor("#EFB435")
MAGENTA = ManimColor("#C20078")
MAHOGANY = ManimColor("#4A0100")
MAIZE = ManimColor("#F4D054")
MANGO = ManimColor("#FFA62B")
MANILLA = ManimColor("#FFFA86")
MARIGOLD = ManimColor("#FCC006")
MARINE = ManimColor("#042E60")
MARINEBLUE = ManimColor("#01386A")
MAROON = ManimColor("#650021")
MAUVE = ManimColor("#AE7181")
MEDIUMBLUE = ManimColor("#2C6FBB")
MEDIUMBROWN = ManimColor("#7F5112")
MEDIUMGREEN = ManimColor("#39AD48")
MEDIUMGREY = ManimColor("#7D7F7C")
MEDIUMPINK = ManimColor("#F36196")
MEDIUMPURPLE = ManimColor("#9E43A2")
MELON = ManimColor("#FF7855")
MERLOT = ManimColor("#730039")
METALLICBLUE = ManimColor("#4F738E")
MIDBLUE = ManimColor("#276AB3")
MIDGREEN = ManimColor("#50A747")
MIDNIGHT = ManimColor("#03012D")
MIDNIGHTBLUE = ManimColor("#020035")
MIDNIGHTPURPLE = ManimColor("#280137")
MILITARYGREEN = ManimColor("#667C3E")
MILKCHOCOLATE = ManimColor("#7F4E1E")
MINT = ManimColor("#9FFEB0")
MINTGREEN = ManimColor("#8FFF9F")
MINTYGREEN = ManimColor("#0BF77D")
MOCHA = ManimColor("#9D7651")
MOSS = ManimColor("#769958")
MOSSGREEN = ManimColor("#658B38")
MOSSYGREEN = ManimColor("#638B27")
MUD = ManimColor("#735C12")
MUDBROWN = ManimColor("#60460F")
MUDDYBROWN = ManimColor("#886806")
MUDDYGREEN = ManimColor("#657432")
MUDDYYELLOW = ManimColor("#BFAC05")
MUDGREEN = ManimColor("#606602")
MULBERRY = ManimColor("#920A4E")
MURKYGREEN = ManimColor("#6C7A0E")
MUSHROOM = ManimColor("#BA9E88")
MUSTARD = ManimColor("#CEB301")
MUSTARDBROWN = ManimColor("#AC7E04")
MUSTARDGREEN = ManimColor("#A8B504")
MUSTARDYELLOW = ManimColor("#D2BD0A")
MUTEDBLUE = ManimColor("#3B719F")
MUTEDGREEN = ManimColor("#5FA052")
MUTEDPINK = ManimColor("#D1768F")
MUTEDPURPLE = ManimColor("#805B87")
NASTYGREEN = ManimColor("#70B23F")
NAVY = ManimColor("#01153E")
NAVYBLUE = ManimColor("#001146")
NAVYGREEN = ManimColor("#35530A")
NEONBLUE = ManimColor("#04D9FF")
NEONGREEN = ManimColor("#0CFF0C")
NEONPINK = ManimColor("#FE019A")
NEONPURPLE = ManimColor("#BC13FE")
NEONRED = ManimColor("#FF073A")
NEONYELLOW = ManimColor("#CFFF04")
NICEBLUE = ManimColor("#107AB0")
NIGHTBLUE = ManimColor("#040348")
OCEAN = ManimColor("#017B92")
OCEANBLUE = ManimColor("#03719C")
OCEANGREEN = ManimColor("#3D9973")
OCHER = ManimColor("#BF9B0C")
OCHRE = ManimColor("#BF9005")
OCRE = ManimColor("#C69C04")
OFFBLUE = ManimColor("#5684AE")
OFFGREEN = ManimColor("#6BA353")
OFFWHITE = ManimColor("#FFFFE4")
OFFYELLOW = ManimColor("#F1F33F")
OLDPINK = ManimColor("#C77986")
OLDROSE = ManimColor("#C87F89")
OLIVE = ManimColor("#6E750E")
OLIVEBROWN = ManimColor("#645403")
OLIVEDRAB = ManimColor("#6F7632")
OLIVEGREEN = ManimColor("#677A04")
OLIVEYELLOW = ManimColor("#C2B709")
ORANGE = ManimColor("#F97306")
ORANGEBROWN = ManimColor("#BE6400")
ORANGEISH = ManimColor("#FD8D49")
ORANGEPINK = ManimColor("#FF6F52")
ORANGERED = ManimColor("#FE420F")
ORANGEYBROWN = ManimColor("#B16002")
ORANGEYELLOW = ManimColor("#FFAD01")
ORANGEYRED = ManimColor("#FA4224")
ORANGEYYELLOW = ManimColor("#FDB915")
ORANGISH = ManimColor("#FC824A")
ORANGISHBROWN = ManimColor("#B25F03")
ORANGISHRED = ManimColor("#F43605")
ORCHID = ManimColor("#C875C4")
PALE = ManimColor("#FFF9D0")
PALEAQUA = ManimColor("#B8FFEB")
PALEBLUE = ManimColor("#D0FEFE")
PALEBROWN = ManimColor("#B1916E")
PALECYAN = ManimColor("#B7FFFA")
PALEGOLD = ManimColor("#FDDE6C")
PALEGREEN = ManimColor("#C7FDB5")
PALEGREY = ManimColor("#FDFDFE")
PALELAVENDER = ManimColor("#EECFFE")
PALELIGHTGREEN = ManimColor("#B1FC99")
PALELILAC = ManimColor("#E4CBFF")
PALELIME = ManimColor("#BEFD73")
PALELIMEGREEN = ManimColor("#B1FF65")
PALEMAGENTA = ManimColor("#D767AD")
PALEMAUVE = ManimColor("#FED0FC")
PALEOLIVE = ManimColor("#B9CC81")
PALEOLIVEGREEN = ManimColor("#B1D27B")
PALEORANGE = ManimColor("#FFA756")
PALEPEACH = ManimColor("#FFE5AD")
PALEPINK = ManimColor("#FFCFDC")
PALEPURPLE = ManimColor("#B790D4")
PALERED = ManimColor("#D9544D")
PALEROSE = ManimColor("#FDC1C5")
PALESALMON = ManimColor("#FFB19A")
PALESKYBLUE = ManimColor("#BDF6FE")
PALETEAL = ManimColor("#82CBB2")
PALETURQUOISE = ManimColor("#A5FBD5")
PALEVIOLET = ManimColor("#CEAEFA")
PALEYELLOW = ManimColor("#FFFF84")
PARCHMENT = ManimColor("#FEFCAF")
PASTELBLUE = ManimColor("#A2BFFE")
PASTELGREEN = ManimColor("#B0FF9D")
PASTELORANGE = ManimColor("#FF964F")
PASTELPINK = ManimColor("#FFBACD")
PASTELPURPLE = ManimColor("#CAA0FF")
PASTELRED = ManimColor("#DB5856")
PASTELYELLOW = ManimColor("#FFFE71")
PEA = ManimColor("#A4BF20")
PEACH = ManimColor("#FFB07C")
PEACHYPINK = ManimColor("#FF9A8A")
PEACOCKBLUE = ManimColor("#016795")
PEAGREEN = ManimColor("#8EAB12")
PEAR = ManimColor("#CBF85F")
PEASOUP = ManimColor("#929901")
PEASOUPGREEN = ManimColor("#94A617")
PERIWINKLE = ManimColor("#8E82FE")
PERIWINKLEBLUE = ManimColor("#8F99FB")
PERRYWINKLE = ManimColor("#8F8CE7")
PETROL = ManimColor("#005F6A")
PIGPINK = ManimColor("#E78EA5")
PINE = ManimColor("#2B5D34")
PINEGREEN = ManimColor("#0A481E")
PINK = ManimColor("#FF81C0")
PINKISH = ManimColor("#D46A7E")
PINKISHBROWN = ManimColor("#B17261")
PINKISHGREY = ManimColor("#C8ACA9")
PINKISHORANGE = ManimColor("#FF724C")
PINKISHPURPLE = ManimColor("#D648D7")
PINKISHRED = ManimColor("#F10C45")
PINKISHTAN = ManimColor("#D99B82")
PINKPURPLE = ManimColor("#EF1DE7")
PINKRED = ManimColor("#F5054F")
PINKY = ManimColor("#FC86AA")
PINKYPURPLE = ManimColor("#C94CBE")
PINKYRED = ManimColor("#FC2647")
PISSYELLOW = ManimColor("#DDD618")
PISTACHIO = ManimColor("#C0FA8B")
PLUM = ManimColor("#580F41")
PLUMPURPLE = ManimColor("#4E0550")
POISONGREEN = ManimColor("#40FD14")
POO = ManimColor("#8F7303")
POOBROWN = ManimColor("#885F01")
POOP = ManimColor("#7F5E00")
POOPBROWN = ManimColor("#7A5901")
POOPGREEN = ManimColor("#6F7C00")
POWDERBLUE = ManimColor("#B1D1FC")
POWDERPINK = ManimColor("#FFB2D0")
PRIMARYBLUE = ManimColor("#0804F9")
PRUSSIANBLUE = ManimColor("#004577")
PUCE = ManimColor("#A57E52")
PUKE = ManimColor("#A5A502")
PUKEBROWN = ManimColor("#947706")
PUKEGREEN = ManimColor("#9AAE07")
PUKEYELLOW = ManimColor("#C2BE0E")
PUMPKIN = ManimColor("#E17701")
PUMPKINORANGE = ManimColor("#FB7D07")
PUREBLUE = ManimColor("#0203E2")
PURPLE = ManimColor("#7E1E9C")
PURPLEBLUE = ManimColor("#5D21D0")
PURPLEBROWN = ManimColor("#673A3F")
PURPLEGREY = ManimColor("#866F85")
PURPLEISH = ManimColor("#98568D")
PURPLEISHBLUE = ManimColor("#6140EF")
PURPLEISHPINK = ManimColor("#DF4EC8")
PURPLEPINK = ManimColor("#D725DE")
PURPLERED = ManimColor("#990147")
PURPLEY = ManimColor("#8756E4")
PURPLEYBLUE = ManimColor("#5F34E7")
PURPLEYGREY = ManimColor("#947E94")
PURPLEYPINK = ManimColor("#C83CB9")
PURPLISH = ManimColor("#94568C")
PURPLISHBLUE = ManimColor("#601EF9")
PURPLISHBROWN = ManimColor("#6B4247")
PURPLISHGREY = ManimColor("#7A687F")
PURPLISHPINK = ManimColor("#CE5DAE")
PURPLISHRED = ManimColor("#B0054B")
PURPLY = ManimColor("#983FB2")
PURPLYBLUE = ManimColor("#661AEE")
PURPLYPINK = ManimColor("#F075E6")
PUTTY = ManimColor("#BEAE8A")
RACINGGREEN = ManimColor("#014600")
RADIOACTIVEGREEN = ManimColor("#2CFA1F")
RASPBERRY = ManimColor("#B00149")
RAWSIENNA = ManimColor("#9A6200")
RAWUMBER = ManimColor("#A75E09")
REALLYLIGHTBLUE = ManimColor("#D4FFFF")
RED = ManimColor("#E50000")
REDBROWN = ManimColor("#8B2E16")
REDDISH = ManimColor("#C44240")
REDDISHBROWN = ManimColor("#7F2B0A")
REDDISHGREY = ManimColor("#997570")
REDDISHORANGE = ManimColor("#F8481C")
REDDISHPINK = ManimColor("#FE2C54")
REDDISHPURPLE = ManimColor("#910951")
REDDYBROWN = ManimColor("#6E1005")
REDORANGE = ManimColor("#FD3C06")
REDPINK = ManimColor("#FA2A55")
REDPURPLE = ManimColor("#820747")
REDVIOLET = ManimColor("#9E0168")
REDWINE = ManimColor("#8C0034")
RICHBLUE = ManimColor("#021BF9")
RICHPURPLE = ManimColor("#720058")
ROBINEGGBLUE = ManimColor("#8AF1FE")
ROBINSEGG = ManimColor("#6DEDFD")
ROBINSEGGBLUE = ManimColor("#98EFF9")
ROSA = ManimColor("#FE86A4")
ROSE = ManimColor("#CF6275")
ROSEPINK = ManimColor("#F7879A")
ROSERED = ManimColor("#BE013C")
ROSYPINK = ManimColor("#F6688E")
ROGUE = ManimColor("#AB1239")
ROYAL = ManimColor("#0C1793")
ROYALBLUE = ManimColor("#0504AA")
ROYALPURPLE = ManimColor("#4B006E")
RUBY = ManimColor("#CA0147")
RUSSET = ManimColor("#A13905")
RUST = ManimColor("#A83C09")
RUSTBROWN = ManimColor("#8B3103")
RUSTORANGE = ManimColor("#C45508")
RUSTRED = ManimColor("#AA2704")
RUSTYORANGE = ManimColor("#CD5909")
RUSTYRED = ManimColor("#AF2F0D")
SAFFRON = ManimColor("#FEB209")
SAGE = ManimColor("#87AE73")
SAGEGREEN = ManimColor("#88B378")
SALMON = ManimColor("#FF796C")
SALMONPINK = ManimColor("#FE7B7C")
SAND = ManimColor("#E2CA76")
SANDBROWN = ManimColor("#CBA560")
SANDSTONE = ManimColor("#C9AE74")
SANDY = ManimColor("#F1DA7A")
SANDYBROWN = ManimColor("#C4A661")
SANDYELLOW = ManimColor("#FCE166")
SANDYYELLOW = ManimColor("#FDEE73")
SAPGREEN = ManimColor("#5C8B15")
SAPPHIRE = ManimColor("#2138AB")
SCARLET = ManimColor("#BE0119")
SEA = ManimColor("#3C9992")
SEABLUE = ManimColor("#047495")
SEAFOAM = ManimColor("#80F9AD")
SEAFOAMBLUE = ManimColor("#78D1B6")
SEAFOAMGREEN = ManimColor("#7AF9AB")
SEAGREEN = ManimColor("#53FCA1")
SEAWEED = ManimColor("#18D17B")
SEAWEEDGREEN = ManimColor("#35AD6B")
SEPIA = ManimColor("#985E2B")
SHAMROCK = ManimColor("#01B44C")
SHAMROCKGREEN = ManimColor("#02C14D")
SHIT = ManimColor("#7F5F00")
SHITBROWN = ManimColor("#7B5804")
SHITGREEN = ManimColor("#758000")
SHOCKINGPINK = ManimColor("#FE02A2")
SICKGREEN = ManimColor("#9DB92C")
SICKLYGREEN = ManimColor("#94B21C")
SICKLYYELLOW = ManimColor("#D0E429")
SIENNA = ManimColor("#A9561E")
SILVER = ManimColor("#C5C9C7")
SKY = ManimColor("#82CAFC")
SKYBLUE = ManimColor("#75BBFD")
SLATE = ManimColor("#516572")
SLATEBLUE = ManimColor("#5B7C99")
SLATEGREEN = ManimColor("#658D6D")
SLATEGREY = ManimColor("#59656D")
SLIMEGREEN = ManimColor("#99CC04")
SNOT = ManimColor("#ACBB0D")
SNOTGREEN = ManimColor("#9DC100")
SOFTBLUE = ManimColor("#6488EA")
SOFTGREEN = ManimColor("#6FC276")
SOFTPINK = ManimColor("#FDB0C0")
SOFTPURPLE = ManimColor("#A66FB5")
SPEARMINT = ManimColor("#1EF876")
SPRINGGREEN = ManimColor("#A9F971")
SPRUCE = ManimColor("#0A5F38")
SQUASH = ManimColor("#F2AB15")
STEEL = ManimColor("#738595")
STEELBLUE = ManimColor("#5A7D9A")
STEELGREY = ManimColor("#6F828A")
STONE = ManimColor("#ADA587")
STORMYBLUE = ManimColor("#507B9C")
STRAW = ManimColor("#FCF679")
STRAWBERRY = ManimColor("#FB2943")
STRONGBLUE = ManimColor("#0C06F7")
STRONGPINK = ManimColor("#FF0789")
SUNFLOWER = ManimColor("#FFC512")
SUNFLOWERYELLOW = ManimColor("#FFDA03")
SUNNYYELLOW = ManimColor("#FFF917")
SUNSHINEYELLOW = ManimColor("#FFFD37")
SUNYELLOW = ManimColor("#FFDF22")
SWAMP = ManimColor("#698339")
SWAMPGREEN = ManimColor("#748500")
TAN = ManimColor("#D1B26F")
TANBROWN = ManimColor("#AB7E4C")
TANGERINE = ManimColor("#FF9408")
TANGREEN = ManimColor("#A9BE70")
TAUPE = ManimColor("#B9A281")
TEA = ManimColor("#65AB7C")
TEAGREEN = ManimColor("#BDF8A3")
TEAL = ManimColor("#029386")
TEALBLUE = ManimColor("#01889F")
TEALGREEN = ManimColor("#25A36F")
TEALISH = ManimColor("#24BCA8")
TEALISHGREEN = ManimColor("#0CDC73")
TERRACOTA = ManimColor("#CB6843")
TERRACOTTA = ManimColor("#C9643B")
TIFFANYBLUE = ManimColor("#7BF2DA")
TOMATO = ManimColor("#EF4026")
TOMATORED = ManimColor("#EC2D01")
TOPAZ = ManimColor("#13BBAF")
TOUPE = ManimColor("#C7AC7D")
TOXICGREEN = ManimColor("#61DE2A")
TREEGREEN = ManimColor("#2A7E19")
TRUEBLUE = ManimColor("#010FCC")
TRUEGREEN = ManimColor("#089404")
TURQUOISE = ManimColor("#06C2AC")
TURQUOISEBLUE = ManimColor("#06B1C4")
TURQUOISEGREEN = ManimColor("#04F489")
TURTLEGREEN = ManimColor("#75B84F")
TWILIGHT = ManimColor("#4E518B")
TWILIGHTBLUE = ManimColor("#0A437A")
UGLYBLUE = ManimColor("#31668A")
UGLYBROWN = ManimColor("#7D7103")
UGLYGREEN = ManimColor("#7A9703")
UGLYPINK = ManimColor("#CD7584")
UGLYPURPLE = ManimColor("#A442A0")
UGLYYELLOW = ManimColor("#D0C101")
ULTRAMARINE = ManimColor("#2000B1")
ULTRAMARINEBLUE = ManimColor("#1805DB")
UMBER = ManimColor("#B26400")
VELVET = ManimColor("#750851")
VERMILION = ManimColor("#F4320C")
VERYDARKBLUE = ManimColor("#000133")
VERYDARKBROWN = ManimColor("#1D0200")
VERYDARKGREEN = ManimColor("#062E03")
VERYDARKPURPLE = ManimColor("#2A0134")
VERYLIGHTBLUE = ManimColor("#D5FFFF")
VERYLIGHTBROWN = ManimColor("#D3B683")
VERYLIGHTGREEN = ManimColor("#D1FFBD")
VERYLIGHTPINK = ManimColor("#FFF4F2")
VERYLIGHTPURPLE = ManimColor("#F6CEFC")
VERYPALEBLUE = ManimColor("#D6FFFE")
VERYPALEGREEN = ManimColor("#CFFDBC")
VIBRANTBLUE = ManimColor("#0339F8")
VIBRANTGREEN = ManimColor("#0ADD08")
VIBRANTPURPLE = ManimColor("#AD03DE")
VIOLET = ManimColor("#9A0EEA")
VIOLETBLUE = ManimColor("#510AC9")
VIOLETPINK = ManimColor("#FB5FFC")
VIOLETRED = ManimColor("#A50055")
VIRIDIAN = ManimColor("#1E9167")
VIVIDBLUE = ManimColor("#152EFF")
VIVIDGREEN = ManimColor("#2FEF10")
VIVIDPURPLE = ManimColor("#9900FA")
VOMIT = ManimColor("#A2A415")
VOMITGREEN = ManimColor("#89A203")
VOMITYELLOW = ManimColor("#C7C10C")
WARMBLUE = ManimColor("#4B57DB")
WARMBROWN = ManimColor("#964E02")
WARMGREY = ManimColor("#978A84")
WARMPINK = ManimColor("#FB5581")
WARMPURPLE = ManimColor("#952E8F")
WASHEDOUTGREEN = ManimColor("#BCF5A6")
WATERBLUE = ManimColor("#0E87CC")
WATERMELON = ManimColor("#FD4659")
WEIRDGREEN = ManimColor("#3AE57F")
WHEAT = ManimColor("#FBDD7E")
WHITE = ManimColor("#FFFFFF")
WINDOWSBLUE = ManimColor("#3778BF")
WINE = ManimColor("#80013F")
WINERED = ManimColor("#7B0323")
WINTERGREEN = ManimColor("#20F986")
WISTERIA = ManimColor("#A87DC2")
YELLOW = ManimColor("#FFFF14")
YELLOWBROWN = ManimColor("#B79400")
YELLOWGREEN = ManimColor("#BBF90F")
YELLOWISH = ManimColor("#FAEE66")
YELLOWISHBROWN = ManimColor("#9B7A01")
YELLOWISHGREEN = ManimColor("#B0DD16")
YELLOWISHORANGE = ManimColor("#FFAB0F")
YELLOWISHTAN = ManimColor("#FCFC81")
YELLOWOCHRE = ManimColor("#CB9D06")
YELLOWORANGE = ManimColor("#FCB001")
YELLOWTAN = ManimColor("#FFE36E")
YELLOWYBROWN = ManimColor("#AE8B0C")
YELLOWYGREEN = ManimColor("#BFF128")
|
manim_ManimCommunity/manim/utils/color/__init__.py
|
"""Utilities for working with colors and predefined color constants.
Color data structure
--------------------
.. autosummary::
:toctree: ../reference
core
Predefined colors
-----------------
There are several predefined colors available in Manim:
- The colors listed in :mod:`.color.manim_colors` are loaded into
Manim's global name space.
- The colors in :mod:`.color.AS2700`, :mod:`.color.BS381`, :mod:`.color.X11`,
and :mod:`.color.XKCD` need to be accessed via their module (which are available
in Manim's global name space), or imported separately. For example:
.. code:: pycon
>>> from manim import XKCD
>>> XKCD.AVOCADO
ManimColor('#90B134')
Or, alternatively:
.. code:: pycon
>>> from manim.utils.color.XKCD import AVOCADO
>>> AVOCADO
ManimColor('#90B134')
The following modules contain the predefined color constants:
.. autosummary::
:toctree: ../reference
manim_colors
AS2700
BS381
XKCD
X11
"""
from typing import Dict, List
from . import AS2700, BS381, X11, XKCD
from .core import *
from .manim_colors import *
_all_color_dict: Dict[str, ManimColor] = {
k: v for k, v in globals().items() if isinstance(v, ManimColor)
}
|
manim_ManimCommunity/manim/utils/color/AS2700.py
|
"""Australian Color Standard
In 1985 the Australian Independent Color Standard AS 2700 was created. In
this standard, all colors can be identified via a category code (one of
B -- Blue, G -- Green, N -- Neutrals (grey), P -- Purple, R -- Red, T -- Blue/Green,
X -- Yellow/Red, Y -- Yellow) and a number. The colors also have (natural) names.
To use the colors from this list, access them directly from the module (which
is exposed to Manim's global name space):
.. code:: pycon
>>> from manim import AS2700
>>> AS2700.B23_BRIGHT_BLUE
ManimColor('#174F90')
List of Color Constants
-----------------------
These hex values (taken from https://www.w3schools.com/colors/colors_australia.asp)
are non official approximate values intended to simulate AS 2700 colors:
.. automanimcolormodule:: manim.utils.color.AS2700
"""
from .core import ManimColor
B11_RICH_BLUE = ManimColor("#2B3770")
B12_ROYAL_BLUE = ManimColor("#2C3563")
B13_NAVY_BLUE = ManimColor("#28304D")
B14_SAPHHIRE = ManimColor("#28426B")
B15_MID_BLUE = ManimColor("#144B6F")
B21_ULTRAMARINE = ManimColor("#2C5098")
B22_HOMEBUSH_BLUE = ManimColor("#215097")
B23_BRIGHT_BLUE = ManimColor("#174F90")
B24_HARBOUR_BLUE = ManimColor("#1C6293")
B25_AQUA = ManimColor("#5097AC")
B32_POWDER_BLUE = ManimColor("#B7C8DB")
B33_MIST_BLUE = ManimColor("#E0E6E2")
B34_PARADISE_BLUE = ManimColor("#3499BA")
B35_PALE_BLUE = ManimColor("#CDE4E2")
B41_BLUEBELL = ManimColor("#5B94D1")
B42_PURPLE_BLUE = ManimColor("#5E7899")
B43_GREY_BLUE = ManimColor("#627C8D")
B44_LIGHT_GREY_BLUE = ManimColor("#C0C0C1")
B45_SKY_BLUE = ManimColor("#7DB7C7")
B51_PERIWINKLE = ManimColor("#3871AC")
B53_DARK_GREY_BLUE = ManimColor("#4F6572")
B55_STORM_BLUE = ManimColor("#3F7C94")
B61_CORAL_SEA = ManimColor("#2B3873")
B62_MIDNIGHT_BLUE = ManimColor("#292A34")
B64_CHARCOAL = ManimColor("#363E45")
G11_BOTTLE_GREEN = ManimColor("#253A32")
G12_HOLLY = ManimColor("#21432D")
G13_EMERALD = ManimColor("#195F35")
G14_MOSS_GREEN = ManimColor("#33572D")
G15_RAINFOREST_GREEN = ManimColor("#3D492D")
G16_TRAFFIC_GREEN = ManimColor("#305442")
G17_MINT_GREEN = ManimColor("#006B45")
G21_JADE = ManimColor("#127453")
G22_SERPENTINE = ManimColor("#78A681")
G23_SHAMROCK = ManimColor("#336634")
G24_FERN_TREE = ManimColor("#477036")
G25_OLIVE = ManimColor("#595B2A")
G26_APPLE_GREEN = ManimColor("#4E9843")
G27_HOMEBUSH_GREEN = ManimColor("#017F4D")
G31_VERTIGRIS = ManimColor("#468A65")
G32_OPALINE = ManimColor("#AFCBB8")
G33_LETTUCE = ManimColor("#7B9954")
G34_AVOCADO = ManimColor("#757C4C")
G35_LIME_GREEN = ManimColor("#89922E")
G36_KIKUYU = ManimColor("#95B43B")
G37_BEANSTALK = ManimColor("#45A56A")
G41_LAWN_GREEN = ManimColor("#0D875D")
G42_GLACIER = ManimColor("#D5E1D2")
G43_SURF_GREEN = ManimColor("#C8C8A7")
G44_PALM_GREEN = ManimColor("#99B179")
G45_CHARTREUSE = ManimColor("#C7C98D")
G46_CITRONELLA = ManimColor("#BFC83E")
G47_CRYSTAL_GREEN = ManimColor("#ADCCA8")
G51_SPRUCE = ManimColor("#05674F")
G52_EUCALYPTUS = ManimColor("#66755B")
G53_BANKSIA = ManimColor("#929479")
G54_MIST_GREEN = ManimColor("#7A836D")
G55_LICHEN = ManimColor("#A7A98C")
G56_SAGE_GREEN = ManimColor("#677249")
G61_DARK_GREEN = ManimColor("#283533")
G62_RIVERGUM = ManimColor("#617061")
G63_DEEP_BRONZE_GREEN = ManimColor("#333334")
G64_SLATE = ManimColor("#5E6153")
G65_TI_TREE = ManimColor("#5D5F4E")
G66_ENVIRONMENT_GREEN = ManimColor("#484C3F")
G67_ZUCCHINI = ManimColor("#2E443A")
N11_PEARL_GREY = ManimColor("#D8D3C7")
N12_PASTEL_GREY = ManimColor("#CCCCCC")
N14_WHITE = ManimColor("#FFFFFF")
N15_HOMEBUSH_GREY = ManimColor("#A29B93")
N22_CLOUD_GREY = ManimColor("#C4C1B9")
N23_NEUTRAL_GREY = ManimColor("#CCCCCC")
N24_SILVER_GREY = ManimColor("#BDC7C5")
N25_BIRCH_GREY = ManimColor("#ABA498")
N32_GREEN_GREY = ManimColor("#8E9282")
N33_LIGHTBOX_GREY = ManimColor("#ACADAD")
N35_LIGHT_GREY = ManimColor("#A6A7A1")
N41_OYSTER = ManimColor("#998F78")
N42_STORM_GREY = ManimColor("#858F88")
N43_PIPELINE_GREY = ManimColor("#999999")
N44_BRIDGE_GREY = ManimColor("#767779")
N45_KOALA_GREY = ManimColor("#928F88")
N52_MID_GREY = ManimColor("#727A77")
N53_BLUE_GREY = ManimColor("#7C8588")
N54_BASALT = ManimColor("#585C63")
N55_LEAD_GREY = ManimColor("#5E5C58")
N61_BLACK = ManimColor("#2A2A2C")
N63_PEWTER = ManimColor("#596064")
N64_DARK_GREY = ManimColor("#4B5259")
N65_GRAPHITE_GREY = ManimColor("#45474A")
P11_MAGENTA = ManimColor("#7B2B48")
P12_PURPLE = ManimColor("#85467B")
P13_VIOLET = ManimColor("#5D3A61")
P14_BLUEBERRY = ManimColor("#4C4176")
P21_SUNSET_PINK = ManimColor("#E3BBBD")
P22_CYCLAMEN = ManimColor("#83597D")
P23_LILAC = ManimColor("#A69FB1")
P24_JACKARANDA = ManimColor("#795F91")
P31_DUSTY_PINK = ManimColor("#DBBEBC")
P33_RIBBON_PINK = ManimColor("#D1BCC9")
P41_ERICA_PINK = ManimColor("#C55A83")
P42_MULBERRY = ManimColor("#A06574")
P43_WISTERIA = ManimColor("#756D91")
P52_PLUM = ManimColor("#6E3D4B")
R11_INTERNATIONAL_ORANGE = ManimColor("#CE482A")
R12_SCARLET = ManimColor("#CD392A")
R13_SIGNAL_RED = ManimColor("#BA312B")
R14_WARATAH = ManimColor("#AA2429")
R15_CRIMSON = ManimColor("#9E2429")
R21_TANGERINE = ManimColor("#E96957")
R22_HOMEBUSH_RED = ManimColor("#D83A2D")
R23_LOLLIPOP = ManimColor("#CC5058")
R24_STRAWBERRY = ManimColor("#B4292A")
R25_ROSE_PINK = ManimColor("#E8919C")
R32_APPLE_BLOSSOM = ManimColor("#F2E1D8")
R33_GHOST_GUM = ManimColor("#E8DAD4")
R34_MUSHROOM = ManimColor("#D7C0B6")
R35_DEEP_ROSE = ManimColor("#CD6D71")
R41_SHELL_PINK = ManimColor("#F9D9BB")
R42_SALMON_PINK = ManimColor("#D99679")
R43_RED_DUST = ManimColor("#D0674F")
R44_POSSUM = ManimColor("#A18881")
R45_RUBY = ManimColor("#8F3E5C")
R51_BURNT_PINK = ManimColor("#E19B8E")
R52_TERRACOTTA = ManimColor("#A04C36")
R53_RED_GUM = ManimColor("#8D4338")
R54_RASPBERRY = ManimColor("#852F31")
R55_CLARET = ManimColor("#67292D")
R62_VENETIAN_RED = ManimColor("#77372B")
R63_RED_OXIDE = ManimColor("#663334")
R64_DEEP_INDIAN_RED = ManimColor("#542E2B")
R65_MAROON = ManimColor("#3F2B3C")
T11_TROPICAL_BLUE = ManimColor("#006698")
T12_DIAMANTIA = ManimColor("#006C74")
T14_MALACHITE = ManimColor("#105154")
T15_TURQUOISE = ManimColor("#098587")
T22_ORIENTAL_BLUE = ManimColor("#358792")
T24_BLUE_JADE = ManimColor("#427F7E")
T32_HUON_GREEN = ManimColor("#72B3B1")
T33_SMOKE_BLUE = ManimColor("#9EB6B2")
T35_GREEN_ICE = ManimColor("#78AEA2")
T44_BLUE_GUM = ManimColor("#6A8A88")
T45_COOTAMUNDRA = ManimColor("#759E91")
T51_MOUNTAIN_BLUE = ManimColor("#295668")
T53_PEACOCK_BLUE = ManimColor("#245764")
T63_TEAL = ManimColor("#183F4E")
X11_BUTTERSCOTCH = ManimColor("#D38F43")
X12_PUMPKIN = ManimColor("#DD7E1A")
X13_MARIGOLD = ManimColor("#ED7F15")
X14_MANDARIN = ManimColor("#E45427")
X15_ORANGE = ManimColor("#E36C2B")
X21_PALE_OCHRE = ManimColor("#DAA45F")
X22_SAFFRON = ManimColor("#F6AA51")
X23_APRICOT = ManimColor("#FEB56D")
X24_ROCKMELON = ManimColor("#F6894B")
X31_RAFFIA = ManimColor("#EBC695")
X32_MAGNOLIA = ManimColor("#F1DEBE")
X33_WARM_WHITE = ManimColor("#F3E7D4")
X34_DRIFTWOOD = ManimColor("#D5C4AE")
X41_BUFF = ManimColor("#C28A44")
X42_BISCUIT = ManimColor("#DEBA92")
X43_BEIGE = ManimColor("#C9AA8C")
X45_CINNAMON = ManimColor("#AC826D")
X51_TAN = ManimColor("#8F5F32")
X52_COFFEE = ManimColor("#AD7948")
X53_GOLDEN_TAN = ManimColor("#925629")
X54_BROWN = ManimColor("#68452C")
X55_NUT_BROWN = ManimColor("#764832")
X61_WOMBAT = ManimColor("#6E5D52")
X62_DARK_EARTH = ManimColor("#6E5D52")
X63_IRONBARK = ManimColor("#443B36")
X64_CHOCOLATE = ManimColor("#4A3B31")
X65_DARK_BROWN = ManimColor("#4F372D")
Y11_CANARY = ManimColor("#E7BD11")
Y12_WATTLE = ManimColor("#E8AF01")
Y13_VIVID_YELLOW = ManimColor("#FCAE01")
Y14_GOLDEN_YELLOW = ManimColor("#F5A601")
Y15_SUNFLOWER = ManimColor("#FFA709")
Y16_INCA_GOLD = ManimColor("#DF8C19")
Y21_PRIMROSE = ManimColor("#F5CF5B")
Y22_CUSTARD = ManimColor("#EFD25C")
Y23_BUTTERCUP = ManimColor("#E0CD41")
Y24_STRAW = ManimColor("#E3C882")
Y25_DEEP_CREAM = ManimColor("#F3C968")
Y26_HOMEBUSH_GOLD = ManimColor("#FCC51A")
Y31_LILY_GREEN = ManimColor("#E3E3CD")
Y32_FLUMMERY = ManimColor("#E6DF9E")
Y33_PALE_PRIMROSE = ManimColor("#F5F3CE")
Y34_CREAM = ManimColor("#EFE3BE")
Y35_OFF_WHITE = ManimColor("#F1E9D5")
Y41_OLIVE_YELLOW = ManimColor("#8E7426")
Y42_MUSTARD = ManimColor("#C4A32E")
Y43_PARCHMENT = ManimColor("#D4C9A3")
Y44_SAND = ManimColor("#DCC18B")
Y45_MANILLA = ManimColor("#E5D0A7")
Y51_BRONZE_OLIVE = ManimColor("#695D3E")
Y52_CHAMOIS = ManimColor("#BEA873")
Y53_SANDSTONE = ManimColor("#D5BF8E")
Y54_OATMEAL = ManimColor("#CAAE82")
Y55_DEEP_STONE = ManimColor("#BC9969")
Y56_MERINO = ManimColor("#C9B79E")
Y61_BLACK_OLIVE = ManimColor("#47473B")
Y62_SUGAR_CANE = ManimColor("#BCA55C")
Y63_KHAKI = ManimColor("#826843")
Y65_MUSHROOM = ManimColor("#A39281")
Y66_MUDSTONE = ManimColor("#574E45")
|
manim_ManimCommunity/manim/utils/color/X11.py
|
# from https://www.w3schools.com/colors/colors_x11.asp
"""X11 Colors
These color and their names (taken from
https://www.w3schools.com/colors/colors_x11.asp) were developed at the
Massachusetts Intitute of Technology (MIT) during
the development of color based computer display system.
To use the colors from this list, access them directly from the module (which
is exposed to Manim's global name space):
.. code:: pycon
>>> from manim import X11
>>> X11.BEIGE
ManimColor('#F5F5DC')
List of Color Constants
-----------------------
.. automanimcolormodule:: manim.utils.color.X11
"""
from .core import ManimColor
ALICEBLUE = ManimColor("#F0F8FF")
ANTIQUEWHITE = ManimColor("#FAEBD7")
ANTIQUEWHITE1 = ManimColor("#FFEFDB")
ANTIQUEWHITE2 = ManimColor("#EEDFCC")
ANTIQUEWHITE3 = ManimColor("#CDC0B0")
ANTIQUEWHITE4 = ManimColor("#8B8378")
AQUAMARINE1 = ManimColor("#7FFFD4")
AQUAMARINE2 = ManimColor("#76EEC6")
AQUAMARINE4 = ManimColor("#458B74")
AZURE1 = ManimColor("#F0FFFF")
AZURE2 = ManimColor("#E0EEEE")
AZURE3 = ManimColor("#C1CDCD")
AZURE4 = ManimColor("#838B8B")
BEIGE = ManimColor("#F5F5DC")
BISQUE1 = ManimColor("#FFE4C4")
BISQUE2 = ManimColor("#EED5B7")
BISQUE3 = ManimColor("#CDB79E")
BISQUE4 = ManimColor("#8B7D6B")
BLACK = ManimColor("#000000")
BLANCHEDALMOND = ManimColor("#FFEBCD")
BLUE1 = ManimColor("#0000FF")
BLUE2 = ManimColor("#0000EE")
BLUE4 = ManimColor("#00008B")
BLUEVIOLET = ManimColor("#8A2BE2")
BROWN = ManimColor("#A52A2A")
BROWN1 = ManimColor("#FF4040")
BROWN2 = ManimColor("#EE3B3B")
BROWN3 = ManimColor("#CD3333")
BROWN4 = ManimColor("#8B2323")
BURLYWOOD = ManimColor("#DEB887")
BURLYWOOD1 = ManimColor("#FFD39B")
BURLYWOOD2 = ManimColor("#EEC591")
BURLYWOOD3 = ManimColor("#CDAA7D")
BURLYWOOD4 = ManimColor("#8B7355")
CADETBLUE = ManimColor("#5F9EA0")
CADETBLUE1 = ManimColor("#98F5FF")
CADETBLUE2 = ManimColor("#8EE5EE")
CADETBLUE3 = ManimColor("#7AC5CD")
CADETBLUE4 = ManimColor("#53868B")
CHARTREUSE1 = ManimColor("#7FFF00")
CHARTREUSE2 = ManimColor("#76EE00")
CHARTREUSE3 = ManimColor("#66CD00")
CHARTREUSE4 = ManimColor("#458B00")
CHOCOLATE = ManimColor("#D2691E")
CHOCOLATE1 = ManimColor("#FF7F24")
CHOCOLATE2 = ManimColor("#EE7621")
CHOCOLATE3 = ManimColor("#CD661D")
CORAL = ManimColor("#FF7F50")
CORAL1 = ManimColor("#FF7256")
CORAL2 = ManimColor("#EE6A50")
CORAL3 = ManimColor("#CD5B45")
CORAL4 = ManimColor("#8B3E2F")
CORNFLOWERBLUE = ManimColor("#6495ED")
CORNSILK1 = ManimColor("#FFF8DC")
CORNSILK2 = ManimColor("#EEE8CD")
CORNSILK3 = ManimColor("#CDC8B1")
CORNSILK4 = ManimColor("#8B8878")
CYAN1 = ManimColor("#00FFFF")
CYAN2 = ManimColor("#00EEEE")
CYAN3 = ManimColor("#00CDCD")
CYAN4 = ManimColor("#008B8B")
DARKGOLDENROD = ManimColor("#B8860B")
DARKGOLDENROD1 = ManimColor("#FFB90F")
DARKGOLDENROD2 = ManimColor("#EEAD0E")
DARKGOLDENROD3 = ManimColor("#CD950C")
DARKGOLDENROD4 = ManimColor("#8B6508")
DARKGREEN = ManimColor("#006400")
DARKKHAKI = ManimColor("#BDB76B")
DARKOLIVEGREEN = ManimColor("#556B2F")
DARKOLIVEGREEN1 = ManimColor("#CAFF70")
DARKOLIVEGREEN2 = ManimColor("#BCEE68")
DARKOLIVEGREEN3 = ManimColor("#A2CD5A")
DARKOLIVEGREEN4 = ManimColor("#6E8B3D")
DARKORANGE = ManimColor("#FF8C00")
DARKORANGE1 = ManimColor("#FF7F00")
DARKORANGE2 = ManimColor("#EE7600")
DARKORANGE3 = ManimColor("#CD6600")
DARKORANGE4 = ManimColor("#8B4500")
DARKORCHID = ManimColor("#9932CC")
DARKORCHID1 = ManimColor("#BF3EFF")
DARKORCHID2 = ManimColor("#B23AEE")
DARKORCHID3 = ManimColor("#9A32CD")
DARKORCHID4 = ManimColor("#68228B")
DARKSALMON = ManimColor("#E9967A")
DARKSEAGREEN = ManimColor("#8FBC8F")
DARKSEAGREEN1 = ManimColor("#C1FFC1")
DARKSEAGREEN2 = ManimColor("#B4EEB4")
DARKSEAGREEN3 = ManimColor("#9BCD9B")
DARKSEAGREEN4 = ManimColor("#698B69")
DARKSLATEBLUE = ManimColor("#483D8B")
DARKSLATEGRAY = ManimColor("#2F4F4F")
DARKSLATEGRAY1 = ManimColor("#97FFFF")
DARKSLATEGRAY2 = ManimColor("#8DEEEE")
DARKSLATEGRAY3 = ManimColor("#79CDCD")
DARKSLATEGRAY4 = ManimColor("#528B8B")
DARKTURQUOISE = ManimColor("#00CED1")
DARKVIOLET = ManimColor("#9400D3")
DEEPPINK1 = ManimColor("#FF1493")
DEEPPINK2 = ManimColor("#EE1289")
DEEPPINK3 = ManimColor("#CD1076")
DEEPPINK4 = ManimColor("#8B0A50")
DEEPSKYBLUE1 = ManimColor("#00BFFF")
DEEPSKYBLUE2 = ManimColor("#00B2EE")
DEEPSKYBLUE3 = ManimColor("#009ACD")
DEEPSKYBLUE4 = ManimColor("#00688B")
DIMGRAY = ManimColor("#696969")
DODGERBLUE1 = ManimColor("#1E90FF")
DODGERBLUE2 = ManimColor("#1C86EE")
DODGERBLUE3 = ManimColor("#1874CD")
DODGERBLUE4 = ManimColor("#104E8B")
FIREBRICK = ManimColor("#B22222")
FIREBRICK1 = ManimColor("#FF3030")
FIREBRICK2 = ManimColor("#EE2C2C")
FIREBRICK3 = ManimColor("#CD2626")
FIREBRICK4 = ManimColor("#8B1A1A")
FLORALWHITE = ManimColor("#FFFAF0")
FORESTGREEN = ManimColor("#228B22")
GAINSBORO = ManimColor("#DCDCDC")
GHOSTWHITE = ManimColor("#F8F8FF")
GOLD1 = ManimColor("#FFD700")
GOLD2 = ManimColor("#EEC900")
GOLD3 = ManimColor("#CDAD00")
GOLD4 = ManimColor("#8B7500")
GOLDENROD = ManimColor("#DAA520")
GOLDENROD1 = ManimColor("#FFC125")
GOLDENROD2 = ManimColor("#EEB422")
GOLDENROD3 = ManimColor("#CD9B1D")
GOLDENROD4 = ManimColor("#8B6914")
GRAY = ManimColor("#BEBEBE")
GRAY1 = ManimColor("#030303")
GRAY2 = ManimColor("#050505")
GRAY3 = ManimColor("#080808")
GRAY4 = ManimColor("#0A0A0A")
GRAY5 = ManimColor("#0D0D0D")
GRAY6 = ManimColor("#0F0F0F")
GRAY7 = ManimColor("#121212")
GRAY8 = ManimColor("#141414")
GRAY9 = ManimColor("#171717")
GRAY10 = ManimColor("#1A1A1A")
GRAY11 = ManimColor("#1C1C1C")
GRAY12 = ManimColor("#1F1F1F")
GRAY13 = ManimColor("#212121")
GRAY14 = ManimColor("#242424")
GRAY15 = ManimColor("#262626")
GRAY16 = ManimColor("#292929")
GRAY17 = ManimColor("#2B2B2B")
GRAY18 = ManimColor("#2E2E2E")
GRAY19 = ManimColor("#303030")
GRAY20 = ManimColor("#333333")
GRAY21 = ManimColor("#363636")
GRAY22 = ManimColor("#383838")
GRAY23 = ManimColor("#3B3B3B")
GRAY24 = ManimColor("#3D3D3D")
GRAY25 = ManimColor("#404040")
GRAY26 = ManimColor("#424242")
GRAY27 = ManimColor("#454545")
GRAY28 = ManimColor("#474747")
GRAY29 = ManimColor("#4A4A4A")
GRAY30 = ManimColor("#4D4D4D")
GRAY31 = ManimColor("#4F4F4F")
GRAY32 = ManimColor("#525252")
GRAY33 = ManimColor("#545454")
GRAY34 = ManimColor("#575757")
GRAY35 = ManimColor("#595959")
GRAY36 = ManimColor("#5C5C5C")
GRAY37 = ManimColor("#5E5E5E")
GRAY38 = ManimColor("#616161")
GRAY39 = ManimColor("#636363")
GRAY40 = ManimColor("#666666")
GRAY41 = ManimColor("#696969")
GRAY42 = ManimColor("#6B6B6B")
GRAY43 = ManimColor("#6E6E6E")
GRAY44 = ManimColor("#707070")
GRAY45 = ManimColor("#737373")
GRAY46 = ManimColor("#757575")
GRAY47 = ManimColor("#787878")
GRAY48 = ManimColor("#7A7A7A")
GRAY49 = ManimColor("#7D7D7D")
GRAY50 = ManimColor("#7F7F7F")
GRAY51 = ManimColor("#828282")
GRAY52 = ManimColor("#858585")
GRAY53 = ManimColor("#878787")
GRAY54 = ManimColor("#8A8A8A")
GRAY55 = ManimColor("#8C8C8C")
GRAY56 = ManimColor("#8F8F8F")
GRAY57 = ManimColor("#919191")
GRAY58 = ManimColor("#949494")
GRAY59 = ManimColor("#969696")
GRAY60 = ManimColor("#999999")
GRAY61 = ManimColor("#9C9C9C")
GRAY62 = ManimColor("#9E9E9E")
GRAY63 = ManimColor("#A1A1A1")
GRAY64 = ManimColor("#A3A3A3")
GRAY65 = ManimColor("#A6A6A6")
GRAY66 = ManimColor("#A8A8A8")
GRAY67 = ManimColor("#ABABAB")
GRAY68 = ManimColor("#ADADAD")
GRAY69 = ManimColor("#B0B0B0")
GRAY70 = ManimColor("#B3B3B3")
GRAY71 = ManimColor("#B5B5B5")
GRAY72 = ManimColor("#B8B8B8")
GRAY73 = ManimColor("#BABABA")
GRAY74 = ManimColor("#BDBDBD")
GRAY75 = ManimColor("#BFBFBF")
GRAY76 = ManimColor("#C2C2C2")
GRAY77 = ManimColor("#C4C4C4")
GRAY78 = ManimColor("#C7C7C7")
GRAY79 = ManimColor("#C9C9C9")
GRAY80 = ManimColor("#CCCCCC")
GRAY81 = ManimColor("#CFCFCF")
GRAY82 = ManimColor("#D1D1D1")
GRAY83 = ManimColor("#D4D4D4")
GRAY84 = ManimColor("#D6D6D6")
GRAY85 = ManimColor("#D9D9D9")
GRAY86 = ManimColor("#DBDBDB")
GRAY87 = ManimColor("#DEDEDE")
GRAY88 = ManimColor("#E0E0E0")
GRAY89 = ManimColor("#E3E3E3")
GRAY90 = ManimColor("#E5E5E5")
GRAY91 = ManimColor("#E8E8E8")
GRAY92 = ManimColor("#EBEBEB")
GRAY93 = ManimColor("#EDEDED")
GRAY94 = ManimColor("#F0F0F0")
GRAY95 = ManimColor("#F2F2F2")
GRAY97 = ManimColor("#F7F7F7")
GRAY98 = ManimColor("#FAFAFA")
GRAY99 = ManimColor("#FCFCFC")
GREEN1 = ManimColor("#00FF00")
GREEN2 = ManimColor("#00EE00")
GREEN3 = ManimColor("#00CD00")
GREEN4 = ManimColor("#008B00")
GREENYELLOW = ManimColor("#ADFF2F")
HONEYDEW1 = ManimColor("#F0FFF0")
HONEYDEW2 = ManimColor("#E0EEE0")
HONEYDEW3 = ManimColor("#C1CDC1")
HONEYDEW4 = ManimColor("#838B83")
HOTPINK = ManimColor("#FF69B4")
HOTPINK1 = ManimColor("#FF6EB4")
HOTPINK2 = ManimColor("#EE6AA7")
HOTPINK3 = ManimColor("#CD6090")
HOTPINK4 = ManimColor("#8B3A62")
INDIANRED = ManimColor("#CD5C5C")
INDIANRED1 = ManimColor("#FF6A6A")
INDIANRED2 = ManimColor("#EE6363")
INDIANRED3 = ManimColor("#CD5555")
INDIANRED4 = ManimColor("#8B3A3A")
IVORY1 = ManimColor("#FFFFF0")
IVORY2 = ManimColor("#EEEEE0")
IVORY3 = ManimColor("#CDCDC1")
IVORY4 = ManimColor("#8B8B83")
KHAKI = ManimColor("#F0E68C")
KHAKI1 = ManimColor("#FFF68F")
KHAKI2 = ManimColor("#EEE685")
KHAKI3 = ManimColor("#CDC673")
KHAKI4 = ManimColor("#8B864E")
LAVENDER = ManimColor("#E6E6FA")
LAVENDERBLUSH1 = ManimColor("#FFF0F5")
LAVENDERBLUSH2 = ManimColor("#EEE0E5")
LAVENDERBLUSH3 = ManimColor("#CDC1C5")
LAVENDERBLUSH4 = ManimColor("#8B8386")
LAWNGREEN = ManimColor("#7CFC00")
LEMONCHIFFON1 = ManimColor("#FFFACD")
LEMONCHIFFON2 = ManimColor("#EEE9BF")
LEMONCHIFFON3 = ManimColor("#CDC9A5")
LEMONCHIFFON4 = ManimColor("#8B8970")
LIGHT = ManimColor("#EEDD82")
LIGHTBLUE = ManimColor("#ADD8E6")
LIGHTBLUE1 = ManimColor("#BFEFFF")
LIGHTBLUE2 = ManimColor("#B2DFEE")
LIGHTBLUE3 = ManimColor("#9AC0CD")
LIGHTBLUE4 = ManimColor("#68838B")
LIGHTCORAL = ManimColor("#F08080")
LIGHTCYAN1 = ManimColor("#E0FFFF")
LIGHTCYAN2 = ManimColor("#D1EEEE")
LIGHTCYAN3 = ManimColor("#B4CDCD")
LIGHTCYAN4 = ManimColor("#7A8B8B")
LIGHTGOLDENROD1 = ManimColor("#FFEC8B")
LIGHTGOLDENROD2 = ManimColor("#EEDC82")
LIGHTGOLDENROD3 = ManimColor("#CDBE70")
LIGHTGOLDENROD4 = ManimColor("#8B814C")
LIGHTGOLDENRODYELLOW = ManimColor("#FAFAD2")
LIGHTGRAY = ManimColor("#D3D3D3")
LIGHTPINK = ManimColor("#FFB6C1")
LIGHTPINK1 = ManimColor("#FFAEB9")
LIGHTPINK2 = ManimColor("#EEA2AD")
LIGHTPINK3 = ManimColor("#CD8C95")
LIGHTPINK4 = ManimColor("#8B5F65")
LIGHTSALMON1 = ManimColor("#FFA07A")
LIGHTSALMON2 = ManimColor("#EE9572")
LIGHTSALMON3 = ManimColor("#CD8162")
LIGHTSALMON4 = ManimColor("#8B5742")
LIGHTSEAGREEN = ManimColor("#20B2AA")
LIGHTSKYBLUE = ManimColor("#87CEFA")
LIGHTSKYBLUE1 = ManimColor("#B0E2FF")
LIGHTSKYBLUE2 = ManimColor("#A4D3EE")
LIGHTSKYBLUE3 = ManimColor("#8DB6CD")
LIGHTSKYBLUE4 = ManimColor("#607B8B")
LIGHTSLATEBLUE = ManimColor("#8470FF")
LIGHTSLATEGRAY = ManimColor("#778899")
LIGHTSTEELBLUE = ManimColor("#B0C4DE")
LIGHTSTEELBLUE1 = ManimColor("#CAE1FF")
LIGHTSTEELBLUE2 = ManimColor("#BCD2EE")
LIGHTSTEELBLUE3 = ManimColor("#A2B5CD")
LIGHTSTEELBLUE4 = ManimColor("#6E7B8B")
LIGHTYELLOW1 = ManimColor("#FFFFE0")
LIGHTYELLOW2 = ManimColor("#EEEED1")
LIGHTYELLOW3 = ManimColor("#CDCDB4")
LIGHTYELLOW4 = ManimColor("#8B8B7A")
LIMEGREEN = ManimColor("#32CD32")
LINEN = ManimColor("#FAF0E6")
MAGENTA = ManimColor("#FF00FF")
MAGENTA2 = ManimColor("#EE00EE")
MAGENTA3 = ManimColor("#CD00CD")
MAGENTA4 = ManimColor("#8B008B")
MAROON = ManimColor("#B03060")
MAROON1 = ManimColor("#FF34B3")
MAROON2 = ManimColor("#EE30A7")
MAROON3 = ManimColor("#CD2990")
MAROON4 = ManimColor("#8B1C62")
MEDIUM = ManimColor("#66CDAA")
MEDIUMAQUAMARINE = ManimColor("#66CDAA")
MEDIUMBLUE = ManimColor("#0000CD")
MEDIUMORCHID = ManimColor("#BA55D3")
MEDIUMORCHID1 = ManimColor("#E066FF")
MEDIUMORCHID2 = ManimColor("#D15FEE")
MEDIUMORCHID3 = ManimColor("#B452CD")
MEDIUMORCHID4 = ManimColor("#7A378B")
MEDIUMPURPLE = ManimColor("#9370DB")
MEDIUMPURPLE1 = ManimColor("#AB82FF")
MEDIUMPURPLE2 = ManimColor("#9F79EE")
MEDIUMPURPLE3 = ManimColor("#8968CD")
MEDIUMPURPLE4 = ManimColor("#5D478B")
MEDIUMSEAGREEN = ManimColor("#3CB371")
MEDIUMSLATEBLUE = ManimColor("#7B68EE")
MEDIUMSPRINGGREEN = ManimColor("#00FA9A")
MEDIUMTURQUOISE = ManimColor("#48D1CC")
MEDIUMVIOLETRED = ManimColor("#C71585")
MIDNIGHTBLUE = ManimColor("#191970")
MINTCREAM = ManimColor("#F5FFFA")
MISTYROSE1 = ManimColor("#FFE4E1")
MISTYROSE2 = ManimColor("#EED5D2")
MISTYROSE3 = ManimColor("#CDB7B5")
MISTYROSE4 = ManimColor("#8B7D7B")
MOCCASIN = ManimColor("#FFE4B5")
NAVAJOWHITE1 = ManimColor("#FFDEAD")
NAVAJOWHITE2 = ManimColor("#EECFA1")
NAVAJOWHITE3 = ManimColor("#CDB38B")
NAVAJOWHITE4 = ManimColor("#8B795E")
NAVYBLUE = ManimColor("#000080")
OLDLACE = ManimColor("#FDF5E6")
OLIVEDRAB = ManimColor("#6B8E23")
OLIVEDRAB1 = ManimColor("#C0FF3E")
OLIVEDRAB2 = ManimColor("#B3EE3A")
OLIVEDRAB4 = ManimColor("#698B22")
ORANGE1 = ManimColor("#FFA500")
ORANGE2 = ManimColor("#EE9A00")
ORANGE3 = ManimColor("#CD8500")
ORANGE4 = ManimColor("#8B5A00")
ORANGERED1 = ManimColor("#FF4500")
ORANGERED2 = ManimColor("#EE4000")
ORANGERED3 = ManimColor("#CD3700")
ORANGERED4 = ManimColor("#8B2500")
ORCHID = ManimColor("#DA70D6")
ORCHID1 = ManimColor("#FF83FA")
ORCHID2 = ManimColor("#EE7AE9")
ORCHID3 = ManimColor("#CD69C9")
ORCHID4 = ManimColor("#8B4789")
PALE = ManimColor("#DB7093")
PALEGOLDENROD = ManimColor("#EEE8AA")
PALEGREEN = ManimColor("#98FB98")
PALEGREEN1 = ManimColor("#9AFF9A")
PALEGREEN2 = ManimColor("#90EE90")
PALEGREEN3 = ManimColor("#7CCD7C")
PALEGREEN4 = ManimColor("#548B54")
PALETURQUOISE = ManimColor("#AFEEEE")
PALETURQUOISE1 = ManimColor("#BBFFFF")
PALETURQUOISE2 = ManimColor("#AEEEEE")
PALETURQUOISE3 = ManimColor("#96CDCD")
PALETURQUOISE4 = ManimColor("#668B8B")
PALEVIOLETRED = ManimColor("#DB7093")
PALEVIOLETRED1 = ManimColor("#FF82AB")
PALEVIOLETRED2 = ManimColor("#EE799F")
PALEVIOLETRED3 = ManimColor("#CD6889")
PALEVIOLETRED4 = ManimColor("#8B475D")
PAPAYAWHIP = ManimColor("#FFEFD5")
PEACHPUFF1 = ManimColor("#FFDAB9")
PEACHPUFF2 = ManimColor("#EECBAD")
PEACHPUFF3 = ManimColor("#CDAF95")
PEACHPUFF4 = ManimColor("#8B7765")
PINK = ManimColor("#FFC0CB")
PINK1 = ManimColor("#FFB5C5")
PINK2 = ManimColor("#EEA9B8")
PINK3 = ManimColor("#CD919E")
PINK4 = ManimColor("#8B636C")
PLUM = ManimColor("#DDA0DD")
PLUM1 = ManimColor("#FFBBFF")
PLUM2 = ManimColor("#EEAEEE")
PLUM3 = ManimColor("#CD96CD")
PLUM4 = ManimColor("#8B668B")
POWDERBLUE = ManimColor("#B0E0E6")
PURPLE = ManimColor("#A020F0")
PURPLE1 = ManimColor("#9B30FF")
PURPLE2 = ManimColor("#912CEE")
PURPLE3 = ManimColor("#7D26CD")
PURPLE4 = ManimColor("#551A8B")
RED1 = ManimColor("#FF0000")
RED2 = ManimColor("#EE0000")
RED3 = ManimColor("#CD0000")
RED4 = ManimColor("#8B0000")
ROSYBROWN = ManimColor("#BC8F8F")
ROSYBROWN1 = ManimColor("#FFC1C1")
ROSYBROWN2 = ManimColor("#EEB4B4")
ROSYBROWN3 = ManimColor("#CD9B9B")
ROSYBROWN4 = ManimColor("#8B6969")
ROYALBLUE = ManimColor("#4169E1")
ROYALBLUE1 = ManimColor("#4876FF")
ROYALBLUE2 = ManimColor("#436EEE")
ROYALBLUE3 = ManimColor("#3A5FCD")
ROYALBLUE4 = ManimColor("#27408B")
SADDLEBROWN = ManimColor("#8B4513")
SALMON = ManimColor("#FA8072")
SALMON1 = ManimColor("#FF8C69")
SALMON2 = ManimColor("#EE8262")
SALMON3 = ManimColor("#CD7054")
SALMON4 = ManimColor("#8B4C39")
SANDYBROWN = ManimColor("#F4A460")
SEAGREEN1 = ManimColor("#54FF9F")
SEAGREEN2 = ManimColor("#4EEE94")
SEAGREEN3 = ManimColor("#43CD80")
SEAGREEN4 = ManimColor("#2E8B57")
SEASHELL1 = ManimColor("#FFF5EE")
SEASHELL2 = ManimColor("#EEE5DE")
SEASHELL3 = ManimColor("#CDC5BF")
SEASHELL4 = ManimColor("#8B8682")
SIENNA = ManimColor("#A0522D")
SIENNA1 = ManimColor("#FF8247")
SIENNA2 = ManimColor("#EE7942")
SIENNA3 = ManimColor("#CD6839")
SIENNA4 = ManimColor("#8B4726")
SKYBLUE = ManimColor("#87CEEB")
SKYBLUE1 = ManimColor("#87CEFF")
SKYBLUE2 = ManimColor("#7EC0EE")
SKYBLUE3 = ManimColor("#6CA6CD")
SKYBLUE4 = ManimColor("#4A708B")
SLATEBLUE = ManimColor("#6A5ACD")
SLATEBLUE1 = ManimColor("#836FFF")
SLATEBLUE2 = ManimColor("#7A67EE")
SLATEBLUE3 = ManimColor("#6959CD")
SLATEBLUE4 = ManimColor("#473C8B")
SLATEGRAY = ManimColor("#708090")
SLATEGRAY1 = ManimColor("#C6E2FF")
SLATEGRAY2 = ManimColor("#B9D3EE")
SLATEGRAY3 = ManimColor("#9FB6CD")
SLATEGRAY4 = ManimColor("#6C7B8B")
SNOW1 = ManimColor("#FFFAFA")
SNOW2 = ManimColor("#EEE9E9")
SNOW3 = ManimColor("#CDC9C9")
SNOW4 = ManimColor("#8B8989")
SPRINGGREEN1 = ManimColor("#00FF7F")
SPRINGGREEN2 = ManimColor("#00EE76")
SPRINGGREEN3 = ManimColor("#00CD66")
SPRINGGREEN4 = ManimColor("#008B45")
STEELBLUE = ManimColor("#4682B4")
STEELBLUE1 = ManimColor("#63B8FF")
STEELBLUE2 = ManimColor("#5CACEE")
STEELBLUE3 = ManimColor("#4F94CD")
STEELBLUE4 = ManimColor("#36648B")
TAN = ManimColor("#D2B48C")
TAN1 = ManimColor("#FFA54F")
TAN2 = ManimColor("#EE9A49")
TAN3 = ManimColor("#CD853F")
TAN4 = ManimColor("#8B5A2B")
THISTLE = ManimColor("#D8BFD8")
THISTLE1 = ManimColor("#FFE1FF")
THISTLE2 = ManimColor("#EED2EE")
THISTLE3 = ManimColor("#CDB5CD")
THISTLE4 = ManimColor("#8B7B8B")
TOMATO1 = ManimColor("#FF6347")
TOMATO2 = ManimColor("#EE5C42")
TOMATO3 = ManimColor("#CD4F39")
TOMATO4 = ManimColor("#8B3626")
TURQUOISE = ManimColor("#40E0D0")
TURQUOISE1 = ManimColor("#00F5FF")
TURQUOISE2 = ManimColor("#00E5EE")
TURQUOISE3 = ManimColor("#00C5CD")
TURQUOISE4 = ManimColor("#00868B")
VIOLET = ManimColor("#EE82EE")
VIOLETRED = ManimColor("#D02090")
VIOLETRED1 = ManimColor("#FF3E96")
VIOLETRED2 = ManimColor("#EE3A8C")
VIOLETRED3 = ManimColor("#CD3278")
VIOLETRED4 = ManimColor("#8B2252")
WHEAT = ManimColor("#F5DEB3")
WHEAT1 = ManimColor("#FFE7BA")
WHEAT2 = ManimColor("#EED8AE")
WHEAT3 = ManimColor("#CDBA96")
WHEAT4 = ManimColor("#8B7E66")
WHITE = ManimColor("#FFFFFF")
WHITESMOKE = ManimColor("#F5F5F5")
YELLOW1 = ManimColor("#FFFF00")
YELLOW2 = ManimColor("#EEEE00")
YELLOW3 = ManimColor("#CDCD00")
YELLOW4 = ManimColor("#8B8B00")
YELLOWGREEN = ManimColor("#9ACD32")
|
manim_ManimCommunity/manim/utils/color/core.py
|
"""Manim's (internal) color data structure and some utilities for
color conversion.
This module contains the implementation of :class:`.ManimColor`,
the data structure internally used to represent colors.
The preferred way of using these colors is by importing their constants from manim:
.. code-block:: pycon
>>> from manim import RED, GREEN, BLUE
>>> print(RED)
#FC6255
Note this way uses the name of the colors in UPPERCASE.
.. note::
The colors of type "C" have an alias equal to the colorname without a letter,
e.g. GREEN = GREEN_C
"""
from __future__ import annotations
import colorsys
# logger = _config.logger
import random
import re
from typing import Any, Sequence, TypeVar, Union, overload
import numpy as np
import numpy.typing as npt
from typing_extensions import Self, TypeAlias
from manim.typing import (
HSV_Array_Float,
HSV_Tuple_Float,
ManimColorDType,
ManimColorInternal,
RGB_Array_Float,
RGB_Array_Int,
RGB_Tuple_Float,
RGB_Tuple_Int,
RGBA_Array_Float,
RGBA_Array_Int,
RGBA_Tuple_Float,
RGBA_Tuple_Int,
)
from ...utils.space_ops import normalize
# import manim._config as _config
re_hex = re.compile("((?<=#)|(?<=0x))[A-F0-9]{6,8}", re.IGNORECASE)
class ManimColor:
"""Internal representation of a color.
The ManimColor class is the main class for the representation of a color.
It's internal representation is a 4 element array of floats corresponding
to a [r,g,b,a] value where r,g,b,a can be between 0 to 1.
This is done in order to reduce the amount of color inconsitencies by constantly
casting between integers and floats which introduces errors.
The class can accept any value of type :class:`ParsableManimColor` i.e.
ManimColor, int, str, RGB_Tuple_Int, RGB_Tuple_Float, RGBA_Tuple_Int, RGBA_Tuple_Float, RGB_Array_Int,
RGB_Array_Float, RGBA_Array_Int, RGBA_Array_Float
ManimColor itself only accepts singular values and will directly interpret them into a single color if possible
Be careful when passing strings to ManimColor it can create a big overhead for the color processing.
If you want to parse a list of colors use the function :meth:`parse` in :class:`ManimColor` which assumes that
you are going to pass a list of color so arrays will not be interpreted as a single color.
.. warning::
If you pass an array of numbers to :meth:`parse` it will interpret the r,g,b,a numbers in that array as colors
so instead of the expect singular color you get and array with 4 colors.
For conversion behaviors see the ``_internal`` functions for further documentation
You can create a ``ManimColor`` instance via its classmethods. See the respective methods for more info.
.. code-block:: python
mycolor = ManimColor.from_rgb((0, 1, 0.4, 0.5))
myothercolor = ManimColor.from_rgb((153, 255, 255))
You can also convert between different color spaces:
.. code-block:: python
mycolor_hex = mycolor.to_hex()
myoriginalcolor = ManimColor.from_hex(mycolor_hex).to_hsv()
Parameters
----------
value
Some representation of a color (e.g., a string or
a suitable tuple). The default ``None`` is ``BLACK``.
alpha
The opacity of the color. By default, colors are
fully opaque (value 1.0).
"""
def __init__(
self,
value: ParsableManimColor | None,
alpha: float = 1.0,
) -> None:
if value is None:
self._internal_value = np.array((0, 0, 0, alpha), dtype=ManimColorDType)
elif isinstance(value, ManimColor):
# logger.info(
# "ManimColor was passed another ManimColor. This is probably not what "
# "you want. Created a copy of the passed ManimColor instead."
# )
self._internal_value = value._internal_value
elif isinstance(value, int):
self._internal_value = ManimColor._internal_from_integer(value, alpha)
elif isinstance(value, str):
result = re_hex.search(value)
if result is not None:
self._internal_value = ManimColor._internal_from_hex_string(
result.group(), alpha
)
else:
# This is not expected to be called on module initialization time
# It can be horribly slow to convert a string to a color because
# it has to access the dictionary of colors and find the right color
self._internal_value = ManimColor._internal_from_string(value)
elif isinstance(value, (list, tuple, np.ndarray)):
length = len(value)
if all(isinstance(x, float) for x in value):
if length == 3:
self._internal_value = ManimColor._internal_from_rgb(value, alpha) # type: ignore
elif length == 4:
self._internal_value = ManimColor._internal_from_rgba(value) # type: ignore
else:
raise ValueError(
f"ManimColor only accepts lists/tuples/arrays of length 3 or 4, not {length}"
)
else:
if length == 3:
self._internal_value = ManimColor._internal_from_int_rgb(
value, alpha # type: ignore
)
elif length == 4:
self._internal_value = ManimColor._internal_from_int_rgba(value) # type: ignore
else:
raise ValueError(
f"ManimColor only accepts lists/tuples/arrays of length 3 or 4, not {length}"
)
elif hasattr(value, "get_hex") and callable(value.get_hex):
result = re_hex.search(value.get_hex())
if result is None:
raise ValueError(f"Failed to parse a color from {value}")
self._internal_value = ManimColor._internal_from_hex_string(
result.group(), alpha
)
else:
# logger.error(f"Invalid color value: {value}")
raise TypeError(
"ManimColor only accepts int, str, list[int, int, int], "
"list[int, int, int, int], list[float, float, float], "
f"list[float, float, float, float], not {type(value)}"
)
@property
def _internal_value(self) -> ManimColorInternal:
"""Returns the internal value of the current Manim color [r,g,b,a] float array
Returns
-------
ManimColorInternal
internal color representation
"""
return self.__value
@_internal_value.setter
def _internal_value(self, value: ManimColorInternal) -> None:
"""Overwrites the internal color value of the ManimColor object
Parameters
----------
value : ManimColorInternal
The value which will overwrite the current color
Raises
------
TypeError
Raises a TypeError if an invalid array is passed
"""
if not isinstance(value, np.ndarray):
raise TypeError("value must be a numpy array")
if value.shape[0] != 4:
raise TypeError("Array must have 4 values exactly")
self.__value: ManimColorInternal = value
@staticmethod
def _internal_from_integer(value: int, alpha: float) -> ManimColorInternal:
return np.asarray(
(
((value >> 16) & 0xFF) / 255,
((value >> 8) & 0xFF) / 255,
((value >> 0) & 0xFF) / 255,
alpha,
),
dtype=ManimColorDType,
)
# TODO: Maybe make 8 nibble hex also convertible ?
@staticmethod
def _internal_from_hex_string(hex: str, alpha: float) -> ManimColorInternal:
"""Internal function for converting a hex string into the internal representation of a ManimColor.
.. warning::
This does not accept any prefixes like # or similar in front of the hex string.
This is just intended for the raw hex part
*For internal use only*
Parameters
----------
hex : str
hex string to be parsed
alpha : float
alpha value used for the color
Returns
-------
ManimColorInternal
Internal color representation
"""
if len(hex) == 6:
hex += "00"
tmp = int(hex, 16)
return np.asarray(
(
((tmp >> 24) & 0xFF) / 255,
((tmp >> 16) & 0xFF) / 255,
((tmp >> 8) & 0xFF) / 255,
alpha,
),
dtype=ManimColorDType,
)
@staticmethod
def _internal_from_int_rgb(
rgb: RGB_Tuple_Int, alpha: float = 1.0
) -> ManimColorInternal:
"""Internal function for converting a rgb tuple of integers into the internal representation of a ManimColor.
*For internal use only*
Parameters
----------
rgb : RGB_Tuple_Int
integer rgb tuple to be parsed
alpha : float, optional
optional alpha value, by default 1.0
Returns
-------
ManimColorInternal
Internal color representation
"""
value: np.ndarray = np.asarray(rgb, dtype=ManimColorDType).copy() / 255
value.resize(4, refcheck=False)
value[3] = alpha
return value
@staticmethod
def _internal_from_rgb(
rgb: RGB_Tuple_Float, alpha: float = 1.0
) -> ManimColorInternal:
"""Internal function for converting a rgb tuple of floats into the internal representation of a ManimColor.
*For internal use only*
Parameters
----------
rgb : RGB_Tuple_Float
float rgb tuple to be parsed
alpha : float, optional
optional alpha value, by default 1.0
Returns
-------
ManimColorInternal
Internal color representation
"""
value: np.ndarray = np.asarray(rgb, dtype=ManimColorDType).copy()
value.resize(4, refcheck=False)
value[3] = alpha
return value
@staticmethod
def _internal_from_int_rgba(rgba: RGBA_Tuple_Int) -> ManimColorInternal:
"""Internal function for converting a rgba tuple of integers into the internal representation of a ManimColor.
*For internal use only*
Parameters
----------
rgba : RGBA_Tuple_Int
int rgba tuple to be parsed
Returns
-------
ManimColorInternal
Internal color representation
"""
return np.asarray(rgba, dtype=ManimColorDType) / 255
@staticmethod
def _internal_from_rgba(rgba: RGBA_Tuple_Float) -> ManimColorInternal:
"""Internal function for converting a rgba tuple of floats into the internal representation of a ManimColor.
*For internal use only*
Parameters
----------
rgba : RGBA_Tuple_Float
int rgba tuple to be parsed
Returns
-------
ManimColorInternal
Internal color representation
"""
return np.asarray(rgba, dtype=ManimColorDType)
@staticmethod
def _internal_from_string(name: str) -> ManimColorInternal:
"""Internal function for converting a string into the internal representation of a ManimColor.
This is not used for hex strings, please refer to :meth:`_internal_from_hex` for this functionality.
*For internal use only*
Parameters
----------
name : str
The color name to be parsed into a color. Refer to the different color Modules in the documentation Page to
find the corresponding Color names.
Returns
-------
ManimColorInternal
Internal color representation
Raises
------
ValueError
Raises a ValueError if the color name is not present with manim
"""
from . import _all_color_dict
upper_name = name.upper()
if upper_name in _all_color_dict:
return _all_color_dict[upper_name]._internal_value
else:
raise ValueError(f"Color {name} not found")
def to_integer(self) -> int:
"""Converts the current ManimColor into an integer
Returns
-------
int
integer representation of the color
.. warning::
This will return only the rgb part of the color
"""
return int.from_bytes(
(self._internal_value[:3] * 255).astype(int).tobytes(), "big"
)
def to_rgb(self) -> RGB_Array_Float:
"""Converts the current ManimColor into a rgb array of floats
Returns
-------
RGB_Array_Float
rgb array with 3 elements of type float
"""
return self._internal_value[:3]
def to_int_rgb(self) -> RGB_Array_Int:
"""Converts the current ManimColor into a rgb array of int
Returns
-------
RGB_Array_Int
rgb array with 3 elements of type int
"""
return (self._internal_value[:3] * 255).astype(int)
def to_rgba(self) -> RGBA_Array_Float:
"""Converts the current ManimColor into a rgba array of floats
Returns
-------
RGBA_Array_Float
rgba array with 4 elements of type float
"""
return self._internal_value
def to_int_rgba(self) -> RGBA_Array_Int:
"""Converts the current ManimColor into a rgba array of int
Returns
-------
RGBA_Array_Int
rgba array with 4 elements of type int
"""
return (self._internal_value * 255).astype(int)
def to_rgba_with_alpha(self, alpha: float) -> RGBA_Array_Float:
"""Converts the current ManimColor into a rgba array of float as :meth:`to_rgba` but you can change the alpha
value.
Parameters
----------
alpha : float
alpha value to be used in the return value
Returns
-------
RGBA_Array_Float
rgba array with 4 elements of type float
"""
return np.fromiter((*self._internal_value[:3], alpha), dtype=ManimColorDType)
def to_int_rgba_with_alpha(self, alpha: float) -> RGBA_Array_Int:
"""Converts the current ManimColor into a rgba array of integers as :meth:`to_int_rgba` but you can change the alpha
value.
Parameters
----------
alpha : float
alpha value to be used for the return value. (Will automatically be scaled from 0-1 to 0-255 so just pass 0-1)
Returns
-------
RGBA_Array_Int
rgba array with 4 elements of type int
"""
tmp = self._internal_value * 255
tmp[3] = alpha * 255
return tmp.astype(int)
def to_hex(self, with_alpha: bool = False) -> str:
"""Converts the manim color to a hexadecimal representation of the color
Parameters
----------
with_alpha : bool, optional
Changes the result from 6 to 8 values where the last 2 nibbles represent the alpha value of 0-255,
by default False
Returns
-------
str
A hex string starting with a # with either 6 or 8 nibbles depending on your input, by default 6 i.e #XXXXXX
"""
tmp = f"#{int(self._internal_value[0]*255):02X}{int(self._internal_value[1]*255):02X}{int(self._internal_value[2]*255):02X}"
if with_alpha:
tmp += f"{int(self._internal_value[3]*255):02X}"
return tmp
def to_hsv(self) -> HSV_Array_Float:
"""Converts the Manim Color to HSV array.
.. note::
Be careful this returns an array in the form `[h, s, v]` where the elements are floats.
This might be confusing because rgb can also be an array of floats so you might want to annotate the usage
of this function in your code by typing the variables with :class:`HSV_Array_Float` in order to differentiate
between rgb arrays and hsv arrays
Returns
-------
HSV_Array_Float
A hsv array containing 3 elements of type float ranging from 0 to 1
"""
return colorsys.rgb_to_hsv(*self.to_rgb())
def invert(self, with_alpha=False) -> ManimColor:
"""Returns an linearly inverted version of the color (no inplace changes)
Parameters
----------
with_alpha : bool, optional
if true the alpha value will be inverted too, by default False
.. note::
This can result in unintended behavior where objects are not displayed because their alpha
value is suddenly 0 or very low. Please keep that in mind when setting this to true
Returns
-------
ManimColor
The linearly inverted ManimColor
"""
return ManimColor(1.0 - self._internal_value, with_alpha)
def interpolate(self, other: ManimColor, alpha: float) -> ManimColor:
"""Interpolates between the current and the given ManimColor an returns the interpolated color
Parameters
----------
other : ManimColor
The other ManimColor to be used for interpolation
alpha : float
A point on the line in rgba colorspace connecting the two colors i.e. the interpolation point
0 corresponds to the current ManimColor and 1 corresponds to the other ManimColor
Returns
-------
ManimColor
The interpolated ManimColor
"""
return ManimColor(
self._internal_value * (1 - alpha) + other._internal_value * alpha
)
@classmethod
def from_rgb(
cls,
rgb: RGB_Array_Float | RGB_Tuple_Float | RGB_Array_Int | RGB_Tuple_Int,
alpha: float = 1.0,
) -> Self:
"""Creates a ManimColor from an RGB Array. Automagically decides which type it is int/float
.. warning::
Please make sure that your elements are not floats if you want integers. A 5.0 will result in the input
being interpreted as if it was a float rgb array with the value 5.0 and not the integer 5
Parameters
----------
rgb : RGB_Array_Float | RGB_Tuple_Float | RGB_Array_Int | RGB_Tuple_Int
Any 3 Element Iterable
alpha : float, optional
alpha value to be used in the color, by default 1.0
Returns
-------
ManimColor
Returns the ManimColor object
"""
return cls(rgb, alpha)
@classmethod
def from_rgba(
cls, rgba: RGBA_Array_Float | RGBA_Tuple_Float | RGBA_Array_Int | RGBA_Tuple_Int
) -> Self:
"""Creates a ManimColor from an RGBA Array. Automagically decides which type it is int/float
.. warning::
Please make sure that your elements are not floats if you want integers. A 5.0 will result in the input
being interpreted as if it was a float rgb array with the value 5.0 and not the integer 5
Parameters
----------
rgba : RGBA_Array_Float | RGBA_Tuple_Float | RGBA_Array_Int | RGBA_Tuple_Int
Any 4 Element Iterable
Returns
-------
ManimColor
Returns the ManimColor object
"""
return cls(rgba)
@classmethod
def from_hex(cls, hex: str, alpha: float = 1.0) -> Self:
"""Creates a Manim Color from a hex string, prefixes allowed # and 0x
Parameters
----------
hex : str
The hex string to be converted (currently only supports 6 nibbles)
alpha : float, optional
alpha value to be used for the hex string, by default 1.0
Returns
-------
ManimColor
The ManimColor represented by the hex string
"""
return cls(hex, alpha)
@classmethod
def from_hsv(
cls, hsv: HSV_Array_Float | HSV_Tuple_Float, alpha: float = 1.0
) -> Self:
"""Creates a ManimColor from an HSV Array
Parameters
----------
hsv : HSV_Array_Float | HSV_Tuple_Float
Any 3 Element Iterable containing floats from 0-1
alpha : float, optional
the alpha value to be used, by default 1.0
Returns
-------
ManimColor
The ManimColor with the corresponding RGB values to the HSV
"""
rgb = colorsys.hsv_to_rgb(*hsv)
return cls(rgb, alpha)
@overload
@classmethod
def parse(
cls,
color: ParsableManimColor | None,
alpha: float = ...,
) -> Self:
...
@overload
@classmethod
def parse(
cls,
color: Sequence[ParsableManimColor],
alpha: float = ...,
) -> list[Self]:
...
@classmethod
def parse(
cls,
color: ParsableManimColor | list[ParsableManimColor] | None,
alpha: float = 1.0,
) -> Self | list[Self]:
"""
Handles the parsing of a list of colors or a single color.
Parameters
----------
color
The color or list of colors to parse. Note that this function can not accept rgba tuples. It will assume that you mean list[ManimColor] and will return a list of ManimColors.
alpha
The alpha value to use if a single color is passed. or if a list of colors is passed to set the value of all colors.
Returns
-------
ManimColor
Either a list of colors or a singular color depending on the input
"""
if isinstance(color, (list, tuple)):
return [cls(c, alpha) for c in color] # type: ignore
return cls(color, alpha) # type: ignore
@staticmethod
def gradient(colors: list[ManimColor], length: int):
"""This is not implemented by now refer to :func:`color_gradient` for a working implementation for now"""
# TODO: implement proper gradient, research good implementation for this or look at 3b1b implementation
raise NotImplementedError
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.to_hex()}')"
def __str__(self) -> str:
return f"{self.to_hex()}"
def __eq__(self, other: object) -> bool:
if not isinstance(other, ManimColor):
raise TypeError(
f"Cannot compare {self.__class__.__name__} with {other.__class__.__name__}"
)
return np.allclose(self._internal_value, other._internal_value)
def __add__(self, other: ManimColor) -> ManimColor:
return ManimColor(self._internal_value + other._internal_value)
def __sub__(self, other: ManimColor) -> ManimColor:
return ManimColor(self._internal_value - other._internal_value)
def __mul__(self, other: ManimColor) -> ManimColor:
return ManimColor(self._internal_value * other._internal_value)
def __truediv__(self, other: ManimColor) -> ManimColor:
return ManimColor(self._internal_value / other._internal_value)
def __floordiv__(self, other: ManimColor) -> ManimColor:
return ManimColor(self._internal_value // other._internal_value)
def __mod__(self, other: ManimColor) -> ManimColor:
return ManimColor(self._internal_value % other._internal_value)
def __pow__(self, other: ManimColor) -> ManimColor:
return ManimColor(self._internal_value**other._internal_value)
def __and__(self, other: ManimColor) -> ManimColor:
return ManimColor(self.to_integer() & other.to_integer())
def __or__(self, other: ManimColor) -> ManimColor:
return ManimColor(self.to_integer() | other.to_integer())
def __xor__(self, other: ManimColor) -> ManimColor:
return ManimColor(self.to_integer() ^ other.to_integer())
ParsableManimColor: TypeAlias = Union[
ManimColor,
int,
str,
RGB_Tuple_Int,
RGB_Tuple_Float,
RGBA_Tuple_Int,
RGBA_Tuple_Float,
RGB_Array_Int,
RGB_Array_Float,
RGBA_Array_Int,
RGBA_Array_Float,
]
"""`ParsableManimColor` represents all the types which can be parsed
to a color in Manim.
"""
ManimColorT = TypeVar("ManimColorT", bound=ManimColor)
def color_to_rgb(color: ParsableManimColor) -> RGB_Array_Float:
"""Helper function for use in functional style programming.
Refer to :meth:`to_rgb` in :class:`ManimColor`.
Parameters
----------
color : ParsableManimColor
A color
Returns
-------
RGB_Array_Float
the corresponding rgb array
"""
return ManimColor(color).to_rgb()
def color_to_rgba(color: ParsableManimColor, alpha: float = 1) -> RGBA_Array_Float:
"""Helper function for use in functional style programming refer to :meth:`to_rgba_with_alpha` in :class:`ManimColor`
Parameters
----------
color : ParsableManimColor
A color
alpha : float, optional
alpha value to be used in the color, by default 1
Returns
-------
RGBA_Array_Float
the corresponding rgba array
"""
return ManimColor(color).to_rgba_with_alpha(alpha)
def color_to_int_rgb(color: ParsableManimColor) -> RGB_Array_Int:
"""Helper function for use in functional style programming refer to :meth:`to_int_rgb` in :class:`ManimColor`
Parameters
----------
color : ParsableManimColor
A color
Returns
-------
RGB_Array_Int
the corresponding int rgb array
"""
return ManimColor(color).to_int_rgb()
def color_to_int_rgba(color: ParsableManimColor, alpha: float = 1.0) -> RGBA_Array_Int:
"""Helper function for use in functional style programming refer to :meth:`to_int_rgba_with_alpha` in :class:`ManimColor`
Parameters
----------
color : ParsableManimColor
A color
alpha : float, optional
alpha value to be used in the color, by default 1.0
Returns
-------
RGBA_Array_Int
the corresponding int rgba array
"""
return ManimColor(color).to_int_rgba_with_alpha(alpha)
def rgb_to_color(
rgb: RGB_Array_Float | RGB_Tuple_Float | RGB_Array_Int | RGB_Tuple_Int,
) -> ManimColor:
"""Helper function for use in functional style programming refer to :meth:`from_rgb` in :class:`ManimColor`
Parameters
----------
rgb : RGB_Array_Float | RGB_Tuple_Float
A 3 element iterable
Returns
-------
ManimColor
A ManimColor with the corresponding value
"""
return ManimColor.from_rgb(rgb)
def rgba_to_color(
rgba: RGBA_Array_Float | RGBA_Tuple_Float | RGBA_Array_Int | RGBA_Tuple_Int,
) -> ManimColor:
"""Helper function for use in functional style programming refer to :meth:`from_rgba` in :class:`ManimColor`
Parameters
----------
rgba : RGBA_Array_Float | RGBA_Tuple_Float
A 4 element iterable
Returns
-------
ManimColor
A ManimColor with the corresponding value
"""
return ManimColor.from_rgba(rgba)
def rgb_to_hex(
rgb: RGB_Array_Float | RGB_Tuple_Float | RGB_Array_Int | RGB_Tuple_Int,
) -> str:
"""Helper function for use in functional style programming refer to :meth:`from_rgb` in :class:`ManimColor`
Parameters
----------
rgb : RGB_Array_Float | RGB_Tuple_Float
A 3 element iterable
Returns
-------
str
A hex representation of the color, refer to :meth:`to_hex` in :class:`ManimColor`
"""
return ManimColor.from_rgb(rgb).to_hex()
def hex_to_rgb(hex_code: str) -> RGB_Array_Float:
"""Helper function for use in functional style programming refer to :meth:`to_hex` in :class:`ManimColor`
Parameters
----------
hex_code : str
A hex string representing a color
Returns
-------
RGB_Array_Float
RGB array representing the color
"""
return ManimColor(hex_code).to_rgb()
def invert_color(color: ManimColorT) -> ManimColorT:
"""Helper function for use in functional style programming refer to :meth:`invert` in :class:`ManimColor`
Parameters
----------
color : ManimColor
A ManimColor
Returns
-------
ManimColor
The linearly inverted ManimColor
"""
return color.invert()
def interpolate_arrays(
arr1: npt.NDArray[Any], arr2: npt.NDArray[Any], alpha: float
) -> np.ndarray:
"""Helper function used in Manim to fade between two objects smoothly
Parameters
----------
arr1 : npt.NDArray[Any]
The first array of colors
arr2 : npt.NDArray[Any]
The second array of colors
alpha : float
The alpha value corresponding to the interpolation point between the two inputs
Returns
-------
np.ndarray
The interpolated value of the to arrays
"""
return (1 - alpha) * arr1 + alpha * arr2
def color_gradient(
reference_colors: Sequence[ParsableManimColor],
length_of_output: int,
) -> list[ManimColor] | ManimColor:
"""Creates a list of colors interpolated between the input array of colors with a specific number of colors
Parameters
----------
reference_colors : Sequence[ParsableManimColor]
The colors to be interpolated between or spread apart
length_of_output : int
The number of colors that the output should have, ideally more than the input
Returns
-------
list[ManimColor] | ManimColor
A list of ManimColor's which has the interpolated colors
"""
if length_of_output == 0:
return ManimColor(reference_colors[0])
if len(reference_colors) == 1:
return [ManimColor(reference_colors[0])] * length_of_output
rgbs = [color_to_rgb(color) for color in reference_colors]
alphas = np.linspace(0, (len(rgbs) - 1), length_of_output)
floors = alphas.astype("int")
alphas_mod1 = alphas % 1
# End edge case
alphas_mod1[-1] = 1
floors[-1] = len(rgbs) - 2
return [
rgb_to_color((rgbs[i] * (1 - alpha)) + (rgbs[i + 1] * alpha))
for i, alpha in zip(floors, alphas_mod1)
]
def interpolate_color(
color1: ManimColorT, color2: ManimColor, alpha: float
) -> ManimColorT:
"""Standalone function to interpolate two ManimColors and get the result refer to :meth:`interpolate` in :class:`ManimColor`
Parameters
----------
color1 : ManimColor
First ManimColor
color2 : ManimColor
Second ManimColor
alpha : float
The alpha value determining the point of interpolation between the colors
Returns
-------
ManimColor
The interpolated ManimColor
"""
return color1.interpolate(color2, alpha)
def average_color(*colors: ParsableManimColor) -> ManimColor:
"""Determines the Average color of the given parameters
Returns
-------
ManimColor
The average color of the input
"""
rgbs = np.array([color_to_rgb(color) for color in colors])
mean_rgb = np.apply_along_axis(np.mean, 0, rgbs)
return rgb_to_color(mean_rgb)
def random_bright_color() -> ManimColor:
"""Returns you a random bright color
.. warning::
This operation is very expensive please keep in mind the performance loss.
Returns
-------
ManimColor
A bright ManimColor
"""
curr_rgb = color_to_rgb(random_color())
new_rgb = interpolate_arrays(curr_rgb, np.ones(len(curr_rgb)), 0.5)
return ManimColor(new_rgb)
def random_color() -> ManimColor:
"""Return you a random ManimColor
.. warning::
This operation is very expensive please keep in mind the performance loss.
Returns
-------
ManimColor
_description_
"""
import manim.utils.color.manim_colors as manim_colors
return random.choice(manim_colors._all_manim_colors)
def get_shaded_rgb(
rgb: npt.NDArray[Any],
point: npt.NDArray[Any],
unit_normal_vect: npt.NDArray[Any],
light_source: npt.NDArray[Any],
) -> RGBA_Array_Float:
to_sun = normalize(light_source - point)
factor = 0.5 * np.dot(unit_normal_vect, to_sun) ** 3
if factor < 0:
factor *= 0.5
result = rgb + factor
return result
__all__ = [
"ManimColor",
"ManimColorDType",
"ParsableManimColor",
"color_to_rgb",
"color_to_rgba",
"color_to_int_rgb",
"color_to_int_rgba",
"rgb_to_color",
"rgba_to_color",
"rgb_to_hex",
"hex_to_rgb",
"invert_color",
"interpolate_arrays",
"color_gradient",
"interpolate_color",
"average_color",
"random_bright_color",
"random_color",
"get_shaded_rgb",
]
|
manim_ManimCommunity/manim/utils/color/BS381.py
|
"""British Color Standard
This module contains colors defined in one of the British Standards
for colors, BS381C. This standard specifies colors used in identification,
coding, and other special purposes. See https://www.britishstandardcolour.com/
for more information.
To use the colors from this list, access them directly from the module (which
is exposed to Manim's global name space):
.. code:: pycon
>>> from manim import BS381
>>> BS381.OXFORD_BLUE
ManimColor('#1F3057')
List of Color Constants
-----------------------
These hex values (taken from https://www.w3schools.com/colors/colors_british.asp)
are non official approximate values intended to simulate the ones defined
in the standard:
.. automanimcolormodule:: manim.utils.color.BS381
"""
from .core import ManimColor
BS381_101 = ManimColor("#94BFAC")
SKY_BLUE = ManimColor("#94BFAC")
BS381_102 = ManimColor("#5B9291")
TURQUOISE_BLUE = ManimColor("#5B9291")
BS381_103 = ManimColor("#3B6879")
PEACOCK_BLUE = ManimColor("#3B6879")
BS381_104 = ManimColor("#264D7E")
AZURE_BLUE = ManimColor("#264D7E")
BS381_105 = ManimColor("#1F3057")
OXFORD_BLUE = ManimColor("#1F3057")
BS381_106 = ManimColor("#2A283D")
ROYAL_BLUE = ManimColor("#2A283D")
BS381_107 = ManimColor("#3A73A9")
STRONG_BLUE = ManimColor("#3A73A9")
BS381_108 = ManimColor("#173679")
AIRCRAFT_BLUE = ManimColor("#173679")
BS381_109 = ManimColor("#1C5680")
MIDDLE_BLUE = ManimColor("#1C5680")
BS381_110 = ManimColor("#2C3E75")
ROUNDEL_BLUE = ManimColor("#2C3E75")
BS381_111 = ManimColor("#8CC5BB")
PALE_BLUE = ManimColor("#8CC5BB")
BS381_112 = ManimColor("#78ADC2")
ARCTIC_BLUE = ManimColor("#78ADC2")
FIESTA_BLUE = ManimColor("#78ADC2")
BS381_113 = ManimColor("#3F687D")
DEEP_SAXE_BLUE = ManimColor("#3F687D")
BS381_114 = ManimColor("#1F4B61")
RAIL_BLUE = ManimColor("#1F4B61")
BS381_115 = ManimColor("#5F88C1")
COBALT_BLUE = ManimColor("#5F88C1")
BS381_166 = ManimColor("#2458AF")
FRENCH_BLUE = ManimColor("#2458AF")
BS381_169 = ManimColor("#135B75")
TRAFFIC_BLUE = ManimColor("#135B75")
BS381_172 = ManimColor("#A7C6EB")
PALE_ROUNDEL_BLUE = ManimColor("#A7C6EB")
BS381_174 = ManimColor("#64A0AA")
ORIENT_BLUE = ManimColor("#64A0AA")
BS381_175 = ManimColor("#4F81C5")
LIGHT_FRENCH_BLUE = ManimColor("#4F81C5")
BS381_210 = ManimColor("#BBC9A5")
SKY = ManimColor("#BBC9A5")
BS381_216 = ManimColor("#BCD890")
EAU_DE_NIL = ManimColor("#BCD890")
BS381_217 = ManimColor("#96BF65")
SEA_GREEN = ManimColor("#96BF65")
BS381_218 = ManimColor("#698B47")
GRASS_GREEN = ManimColor("#698B47")
BS381_219 = ManimColor("#757639")
SAGE_GREEN = ManimColor("#757639")
BS381_220 = ManimColor("#4B5729")
OLIVE_GREEN = ManimColor("#4B5729")
BS381_221 = ManimColor("#507D3A")
BRILLIANT_GREEN = ManimColor("#507D3A")
BS381_222 = ManimColor("#6A7031")
LIGHT_BRONZE_GREEN = ManimColor("#6A7031")
BS381_223 = ManimColor("#49523A")
MIDDLE_BRONZE_GREEN = ManimColor("#49523A")
BS381_224 = ManimColor("#3E4630")
DEEP_BRONZE_GREEN = ManimColor("#3E4630")
BS381_225 = ManimColor("#406A28")
LIGHT_BRUNSWICK_GREEN = ManimColor("#406A28")
BS381_226 = ManimColor("#33533B")
MID_BRUNSWICK_GREEN = ManimColor("#33533B")
BS381_227 = ManimColor("#254432")
DEEP_BRUNSWICK_GREEN = ManimColor("#254432")
BS381_228 = ManimColor("#428B64")
EMERALD_GREEN = ManimColor("#428B64")
BS381_241 = ManimColor("#4F5241")
DARK_GREEN = ManimColor("#4F5241")
BS381_262 = ManimColor("#44945E")
BOLD_GREEN = ManimColor("#44945E")
BS381_267 = ManimColor("#476A4C")
DEEP_CHROME_GREEN = ManimColor("#476A4C")
TRAFFIC_GREEN = ManimColor("#476A4C")
BS381_275 = ManimColor("#8FC693")
OPALINE_GREEN = ManimColor("#8FC693")
BS381_276 = ManimColor("#2E4C1E")
LINCON_GREEN = ManimColor("#2E4C1E")
BS381_277 = ManimColor("#364A20")
CYPRESS_GREEN = ManimColor("#364A20")
BS381_278 = ManimColor("#87965A")
LIGHT_OLIVE_GREEN = ManimColor("#87965A")
BS381_279 = ManimColor("#3B3629")
STEEL_FURNITURE_GREEN = ManimColor("#3B3629")
BS381_280 = ManimColor("#68AB77")
VERDIGRIS_GREEN = ManimColor("#68AB77")
BS381_282 = ManimColor("#506B52")
FOREST_GREEN = ManimColor("#506B52")
BS381_283 = ManimColor("#7E8F6E")
AIRCRAFT_GREY_GREEN = ManimColor("#7E8F6E")
BS381_284 = ManimColor("#6B6F5A")
SPRUCE_GREEN = ManimColor("#6B6F5A")
BS381_285 = ManimColor("#5F5C4B")
NATO_GREEN = ManimColor("#5F5C4B")
BS381_298 = ManimColor("#4F5138")
OLIVE_DRAB = ManimColor("#4F5138")
BS381_309 = ManimColor("#FEEC04")
CANARY_YELLOW = ManimColor("#FEEC04")
BS381_310 = ManimColor("#FEF963")
PRIMROSE = ManimColor("#FEF963")
BS381_315 = ManimColor("#FEF96A")
GRAPEFRUIT = ManimColor("#FEF96A")
BS381_320 = ManimColor("#9E7339")
LIGHT_BROWN = ManimColor("#9E7339")
BS381_337 = ManimColor("#4C4A3C")
VERY_DARK_DRAB = ManimColor("#4C4A3C")
BS381_350 = ManimColor("#7B6B4F")
DARK_EARTH = ManimColor("#7B6B4F")
BS381_352 = ManimColor("#FCED96")
PALE_CREAM = ManimColor("#FCED96")
BS381_353 = ManimColor("#FDF07A")
DEEP_CREAM = ManimColor("#FDF07A")
BS381_354 = ManimColor("#E9BB43")
PRIMROSE_2 = ManimColor("#E9BB43")
BS381_355 = ManimColor("#FDD906")
LEMON = ManimColor("#FDD906")
BS381_356 = ManimColor("#FCC808")
GOLDEN_YELLOW = ManimColor("#FCC808")
BS381_358 = ManimColor("#F6C870")
LIGHT_BUFF = ManimColor("#F6C870")
BS381_359 = ManimColor("#DBAC50")
MIDDLE_BUFF = ManimColor("#DBAC50")
BS381_361 = ManimColor("#D4B97D")
LIGHT_STONE = ManimColor("#D4B97D")
BS381_362 = ManimColor("#AC7C42")
MIDDLE_STONE = ManimColor("#AC7C42")
BS381_363 = ManimColor("#FDE706")
BOLD_YELLOW = ManimColor("#FDE706")
BS381_364 = ManimColor("#CEC093")
PORTLAND_STONE = ManimColor("#CEC093")
BS381_365 = ManimColor("#F4F0BD")
VELLUM = ManimColor("#F4F0BD")
BS381_366 = ManimColor("#F5E7A1")
LIGHT_BEIGE = ManimColor("#F5E7A1")
BS381_367 = ManimColor("#FEF6BF")
MANILLA = ManimColor("#fef6bf")
BS381_368 = ManimColor("#DD7B00")
TRAFFIC_YELLOW = ManimColor("#DD7B00")
BS381_369 = ManimColor("#FEEBA8")
BISCUIT = ManimColor("#feeba8")
BS381_380 = ManimColor("#BBA38A")
CAMOUFLAGE_DESERT_SAND = ManimColor("#BBA38A")
BS381_384 = ManimColor("#EEDFA5")
LIGHT_STRAW = ManimColor("#EEDFA5")
BS381_385 = ManimColor("#E8C88F")
LIGHT_BISCUIT = ManimColor("#E8C88F")
BS381_386 = ManimColor("#E6C18D")
CHAMPAGNE = ManimColor("#e6c18d")
BS381_387 = ManimColor("#CFB48A")
SUNRISE = ManimColor("#cfb48a")
SUNSHINE = ManimColor("#cfb48a")
BS381_388 = ManimColor("#E4CF93")
BEIGE = ManimColor("#e4cf93")
BS381_389 = ManimColor("#B2A788")
CAMOUFLAGE_BEIGE = ManimColor("#B2A788")
BS381_397 = ManimColor("#F3D163")
JASMINE_YELLOW = ManimColor("#F3D163")
BS381_411 = ManimColor("#74542F")
MIDDLE_BROWN = ManimColor("#74542F")
BS381_412 = ManimColor("#5C422E")
DARK_BROWN = ManimColor("#5C422E")
BS381_413 = ManimColor("#402D21")
NUT_BROWN = ManimColor("#402D21")
BS381_414 = ManimColor("#A86C29")
GOLDEN_BROWN = ManimColor("#A86C29")
BS381_415 = ManimColor("#61361E")
IMPERIAL_BROWN = ManimColor("#61361E")
BS381_420 = ManimColor("#A89177")
DARK_CAMOUFLAGE_DESERT_SAND = ManimColor("#A89177")
BS381_435 = ManimColor("#845B4D")
CAMOUFLAGE_RED = ManimColor("#845B4D")
BS381_436 = ManimColor("#564B47")
DARK_CAMOUFLAGE_BROWN = ManimColor("#564B47")
BS381_439 = ManimColor("#753B1E")
ORANGE_BROWN = ManimColor("#753B1E")
BS381_443 = ManimColor("#C98A71")
SALMON = ManimColor("#c98a71")
BS381_444 = ManimColor("#A65341")
TERRACOTTA = ManimColor("#a65341")
BS381_445 = ManimColor("#83422B")
VENETIAN_RED = ManimColor("#83422B")
BS381_446 = ManimColor("#774430")
RED_OXIDE = ManimColor("#774430")
BS381_447 = ManimColor("#F3B28B")
SALMON_PINK = ManimColor("#F3B28B")
BS381_448 = ManimColor("#67403A")
DEEP_INDIAN_RED = ManimColor("#67403A")
BS381_449 = ManimColor("#693B3F")
LIGHT_PURPLE_BROWN = ManimColor("#693B3F")
BS381_452 = ManimColor("#613339")
DARK_CRIMSON = ManimColor("#613339")
BS381_453 = ManimColor("#FBDED6")
SHELL_PINK = ManimColor("#FBDED6")
BS381_454 = ManimColor("#E8A1A2")
PALE_ROUNDEL_RED = ManimColor("#E8A1A2")
BS381_460 = ManimColor("#BD8F56")
DEEP_BUFF = ManimColor("#BD8F56")
BS381_473 = ManimColor("#793932")
GULF_RED = ManimColor("#793932")
BS381_489 = ManimColor("#8D5B41")
LEAF_BROWN = ManimColor("#8D5B41")
BS381_490 = ManimColor("#573320")
BEECH_BROWN = ManimColor("#573320")
BS381_499 = ManimColor("#59493E")
SERVICE_BROWN = ManimColor("#59493E")
BS381_536 = ManimColor("#BB3016")
POPPY = ManimColor("#bb3016")
BS381_537 = ManimColor("#DD3420")
SIGNAL_RED = ManimColor("#DD3420")
BS381_538 = ManimColor("#C41C22")
POST_OFFICE_RED = ManimColor("#C41C22")
CHERRY = ManimColor("#c41c22")
BS381_539 = ManimColor("#D21E2B")
CURRANT_RED = ManimColor("#D21E2B")
BS381_540 = ManimColor("#8B1A32")
CRIMSON = ManimColor("#8b1a32")
BS381_541 = ManimColor("#471B21")
MAROON = ManimColor("#471b21")
BS381_542 = ManimColor("#982D57")
RUBY = ManimColor("#982d57")
BS381_557 = ManimColor("#EF841E")
LIGHT_ORANGE = ManimColor("#EF841E")
BS381_564 = ManimColor("#DD3524")
BOLD_RED = ManimColor("#DD3524")
BS381_568 = ManimColor("#FB9C06")
APRICOT = ManimColor("#fb9c06")
BS381_570 = ManimColor("#A83C19")
TRAFFIC_RED = ManimColor("#A83C19")
BS381_591 = ManimColor("#D04E09")
DEEP_ORANGE = ManimColor("#D04E09")
BS381_592 = ManimColor("#E45523")
INTERNATIONAL_ORANGE = ManimColor("#E45523")
BS381_593 = ManimColor("#F24816")
RAIL_RED = ManimColor("#F24816")
AZO_ORANGE = ManimColor("#F24816")
BS381_626 = ManimColor("#A0A9AA")
CAMOUFLAGE_GREY = ManimColor("#A0A9AA")
BS381_627 = ManimColor("#BEC0B8")
LIGHT_AIRCRAFT_GREY = ManimColor("#BEC0B8")
BS381_628 = ManimColor("#9D9D7E")
SILVER_GREY = ManimColor("#9D9D7E")
BS381_629 = ManimColor("#7A838B")
DARK_CAMOUFLAGE_GREY = ManimColor("#7A838B")
BS381_630 = ManimColor("#A5AD98")
FRENCH_GREY = ManimColor("#A5AD98")
BS381_631 = ManimColor("#9AAA9F")
LIGHT_GREY = ManimColor("#9AAA9F")
BS381_632 = ManimColor("#6B7477")
DARK_ADMIRALTY_GREY = ManimColor("#6B7477")
BS381_633 = ManimColor("#424C53")
RAF_BLUE_GREY = ManimColor("#424C53")
BS381_634 = ManimColor("#6F7264")
SLATE = ManimColor("#6f7264")
BS381_635 = ManimColor("#525B55")
LEAD = ManimColor("#525b55")
BS381_636 = ManimColor("#5F7682")
PRU_BLUE = ManimColor("#5F7682")
BS381_637 = ManimColor("#8E9B9C")
MEDIUM_SEA_GREY = ManimColor("#8E9B9C")
BS381_638 = ManimColor("#6C7377")
DARK_SEA_GREY = ManimColor("#6C7377")
BS381_639 = ManimColor("#667563")
LIGHT_SLATE_GREY = ManimColor("#667563")
BS381_640 = ManimColor("#566164")
EXTRA_DARK_SEA_GREY = ManimColor("#566164")
BS381_642 = ManimColor("#282B2F")
NIGHT = ManimColor("#282b2f")
BS381_671 = ManimColor("#4E5355")
MIDDLE_GRAPHITE = ManimColor("#4E5355")
BS381_676 = ManimColor("#A9B7B9")
LIGHT_WEATHERWORK_GREY = ManimColor("#A9B7B9")
BS381_677 = ManimColor("#676F76")
DARK_WEATHERWORK_GREY = ManimColor("#676F76")
BS381_692 = ManimColor("#7B93A3")
SMOKE_GREY = ManimColor("#7B93A3")
BS381_693 = ManimColor("#88918D")
AIRCRAFT_GREY = ManimColor("#88918D")
BS381_694 = ManimColor("#909A92")
DOVE_GREY = ManimColor("#909A92")
BS381_697 = ManimColor("#B6D3CC")
LIGHT_ADMIRALTY_GREY = ManimColor("#B6D3CC")
BS381_796 = ManimColor("#6E4A75")
DARK_VIOLET = ManimColor("#6E4A75")
BS381_797 = ManimColor("#C9A8CE")
LIGHT_VIOLET = ManimColor("#C9A8CE")
|
manim_ManimCommunity/manim/utils/color/manim_colors.py
|
"""Colors included in the global name space.
These colors form Manim's default color space.
.. manim:: ColorsOverview
:save_last_frame:
:hide_source:
import manim.utils.color.manim_colors as Colors
class ColorsOverview(Scene):
def construct(self):
def color_group(color):
group = VGroup(
*[
Line(ORIGIN, RIGHT * 1.5, stroke_width=35, color=getattr(Colors, name.upper()))
for name in subnames(color)
]
).arrange_submobjects(buff=0.4, direction=DOWN)
name = Text(color).scale(0.6).next_to(group, UP, buff=0.3)
if any(decender in color for decender in "gjpqy"):
name.shift(DOWN * 0.08)
group.add(name)
return group
def subnames(name):
return [name + "_" + char for char in "abcde"]
color_groups = VGroup(
*[
color_group(color)
for color in [
"blue",
"teal",
"green",
"yellow",
"gold",
"red",
"maroon",
"purple",
]
]
).arrange_submobjects(buff=0.2, aligned_edge=DOWN)
for line, char in zip(color_groups[0], "abcde"):
color_groups.add(Text(char).scale(0.6).next_to(line, LEFT, buff=0.2))
def named_lines_group(length, colors, names, text_colors, align_to_block):
lines = VGroup(
*[
Line(
ORIGIN,
RIGHT * length,
stroke_width=55,
color=getattr(Colors, color.upper()),
)
for color in colors
]
).arrange_submobjects(buff=0.6, direction=DOWN)
for line, name, color in zip(lines, names, text_colors):
line.add(Text(name, color=color).scale(0.6).move_to(line))
lines.next_to(color_groups, DOWN, buff=0.5).align_to(
color_groups[align_to_block], LEFT
)
return lines
other_colors = (
"pink",
"light_pink",
"orange",
"light_brown",
"dark_brown",
"gray_brown",
)
other_lines = named_lines_group(
3.2,
other_colors,
other_colors,
[BLACK] * 4 + [WHITE] * 2,
0,
)
gray_lines = named_lines_group(
6.6,
["white"] + subnames("gray") + ["black"],
[
"white",
"lighter_gray / gray_a",
"light_gray / gray_b",
"gray / gray_c",
"dark_gray / gray_d",
"darker_gray / gray_e",
"black",
],
[BLACK] * 3 + [WHITE] * 4,
2,
)
pure_colors = (
"pure_red",
"pure_green",
"pure_blue",
)
pure_lines = named_lines_group(
3.2,
pure_colors,
pure_colors,
[BLACK, BLACK, WHITE],
6,
)
self.add(color_groups, other_lines, gray_lines, pure_lines)
VGroup(*self.mobjects).move_to(ORIGIN)
.. automanimcolormodule:: manim.utils.color.manim_colors
"""
from typing import List
from .core import ManimColor
WHITE = ManimColor("#FFFFFF")
GRAY_A = ManimColor("#DDDDDD")
GREY_A = ManimColor("#DDDDDD")
GRAY_B = ManimColor("#BBBBBB")
GREY_B = ManimColor("#BBBBBB")
GRAY_C = ManimColor("#888888")
GREY_C = ManimColor("#888888")
GRAY_D = ManimColor("#444444")
GREY_D = ManimColor("#444444")
GRAY_E = ManimColor("#222222")
GREY_E = ManimColor("#222222")
BLACK = ManimColor("#000000")
LIGHTER_GRAY = ManimColor("#DDDDDD")
LIGHTER_GREY = ManimColor("#DDDDDD")
LIGHT_GRAY = ManimColor("#BBBBBB")
LIGHT_GREY = ManimColor("#BBBBBB")
GRAY = ManimColor("#888888")
GREY = ManimColor("#888888")
DARK_GRAY = ManimColor("#444444")
DARK_GREY = ManimColor("#444444")
DARKER_GRAY = ManimColor("#222222")
DARKER_GREY = ManimColor("#222222")
BLUE_A = ManimColor("#C7E9F1")
BLUE_B = ManimColor("#9CDCEB")
BLUE_C = ManimColor("#58C4DD")
BLUE_D = ManimColor("#29ABCA")
BLUE_E = ManimColor("#236B8E")
PURE_BLUE = ManimColor("#0000FF")
BLUE = ManimColor("#58C4DD")
DARK_BLUE = ManimColor("#236B8E")
TEAL_A = ManimColor("#ACEAD7")
TEAL_B = ManimColor("#76DDC0")
TEAL_C = ManimColor("#5CD0B3")
TEAL_D = ManimColor("#55C1A7")
TEAL_E = ManimColor("#49A88F")
TEAL = ManimColor("#5CD0B3")
GREEN_A = ManimColor("#C9E2AE")
GREEN_B = ManimColor("#A6CF8C")
GREEN_C = ManimColor("#83C167")
GREEN_D = ManimColor("#77B05D")
GREEN_E = ManimColor("#699C52")
PURE_GREEN = ManimColor("#00FF00")
GREEN = ManimColor("#83C167")
YELLOW_A = ManimColor("#FFF1B6")
YELLOW_B = ManimColor("#FFEA94")
YELLOW_C = ManimColor("#FFFF00")
YELLOW_D = ManimColor("#F4D345")
YELLOW_E = ManimColor("#E8C11C")
YELLOW = ManimColor("#FFFF00")
GOLD_A = ManimColor("#F7C797")
GOLD_B = ManimColor("#F9B775")
GOLD_C = ManimColor("#F0AC5F")
GOLD_D = ManimColor("#E1A158")
GOLD_E = ManimColor("#C78D46")
GOLD = ManimColor("#F0AC5F")
RED_A = ManimColor("#F7A1A3")
RED_B = ManimColor("#FF8080")
RED_C = ManimColor("#FC6255")
RED_D = ManimColor("#E65A4C")
RED_E = ManimColor("#CF5044")
PURE_RED = ManimColor("#FF0000")
RED = ManimColor("#FC6255")
MAROON_A = ManimColor("#ECABC1")
MAROON_B = ManimColor("#EC92AB")
MAROON_C = ManimColor("#C55F73")
MAROON_D = ManimColor("#A24D61")
MAROON_E = ManimColor("#94424F")
MAROON = ManimColor("#C55F73")
PURPLE_A = ManimColor("#CAA3E8")
PURPLE_B = ManimColor("#B189C6")
PURPLE_C = ManimColor("#9A72AC")
PURPLE_D = ManimColor("#715582")
PURPLE_E = ManimColor("#644172")
PURPLE = ManimColor("#9A72AC")
PINK = ManimColor("#D147BD")
LIGHT_PINK = ManimColor("#DC75CD")
ORANGE = ManimColor("#FF862F")
LIGHT_BROWN = ManimColor("#CD853F")
DARK_BROWN = ManimColor("#8B4513")
GRAY_BROWN = ManimColor("#736357")
GREY_BROWN = ManimColor("#736357")
# Colors used for Manim Community's logo and banner
LOGO_WHITE = ManimColor("#ECE7E2")
LOGO_GREEN = ManimColor("#87C2A5")
LOGO_BLUE = ManimColor("#525893")
LOGO_RED = ManimColor("#E07A5F")
LOGO_BLACK = ManimColor("#343434")
_all_manim_colors: List[ManimColor] = [
x for x in globals().values() if isinstance(x, ManimColor)
]
|
manim_ManimCommunity/manim/utils/testing/__init__.py
|
"""Utilities for Manim tests using `pytest <https://pytest.org>`_.
For more information about Manim testing, see:
- :doc:`/contributing/development`, specifically the ``Tests`` bullet
point under :ref:`polishing-changes-and-submitting-a-pull-request`
- :doc:`/contributing/testing`
.. autosummary::
:toctree: ../reference
frames_comparison
_frames_testers
_show_diff
_test_class_makers
"""
|
manim_ManimCommunity/manim/utils/testing/_test_class_makers.py
|
from __future__ import annotations
from typing import Callable
from manim.scene.scene import Scene
from manim.scene.scene_file_writer import SceneFileWriter
from ._frames_testers import _FramesTester
def _make_test_scene_class(
base_scene: type[Scene],
construct_test: Callable[[Scene], None],
test_renderer,
) -> type[Scene]:
class _TestedScene(base_scene):
def __init__(self, *args, **kwargs):
super().__init__(renderer=test_renderer, *args, **kwargs)
def construct(self):
construct_test(self)
# Manim hack to render the very last frame (normally the last frame is not the very end of the animation)
if self.animations is not None:
self.update_to_time(self.get_run_time(self.animations))
self.renderer.render(self, 1, self.moving_mobjects)
return _TestedScene
def _make_test_renderer_class(from_renderer):
# Just for inheritance.
class _TestRenderer(from_renderer):
pass
return _TestRenderer
class DummySceneFileWriter(SceneFileWriter):
"""Delegate of SceneFileWriter used to test the frames."""
def __init__(self, renderer, scene_name, **kwargs):
super().__init__(renderer, scene_name, **kwargs)
self.i = 0
def init_output_directories(self, scene_name):
pass
def add_partial_movie_file(self, hash_animation):
pass
def begin_animation(self, allow_write=True):
pass
def end_animation(self, allow_write):
pass
def combine_to_movie(self):
pass
def combine_to_section_videos(self):
pass
def clean_cache(self):
pass
def write_frame(self, frame_or_renderer):
self.i += 1
def _make_scene_file_writer_class(tester: _FramesTester) -> type[SceneFileWriter]:
class TestSceneFileWriter(DummySceneFileWriter):
def write_frame(self, frame_or_renderer):
tester.check_frame(self.i, frame_or_renderer)
super().write_frame(frame_or_renderer)
return TestSceneFileWriter
|
manim_ManimCommunity/manim/utils/testing/frames_comparison.py
|
from __future__ import annotations
import functools
import inspect
from pathlib import Path
from typing import Callable
import cairo
import pytest
from _pytest.fixtures import FixtureRequest
from manim import Scene
from manim._config import tempconfig
from manim._config.utils import ManimConfig
from manim.camera.three_d_camera import ThreeDCamera
from manim.renderer.cairo_renderer import CairoRenderer
from manim.scene.three_d_scene import ThreeDScene
from ._frames_testers import _ControlDataWriter, _FramesTester
from ._test_class_makers import (
DummySceneFileWriter,
_make_scene_file_writer_class,
_make_test_renderer_class,
_make_test_scene_class,
)
SCENE_PARAMETER_NAME = "scene"
_tests_root_dir_path = Path(__file__).absolute().parents[2]
PATH_CONTROL_DATA = _tests_root_dir_path / Path("control_data", "graphical_units_data")
MIN_CAIRO_VERSION = 11800
def frames_comparison(
func=None,
*,
last_frame: bool = True,
renderer_class=CairoRenderer,
base_scene=Scene,
**custom_config,
):
"""Compares the frames generated by the test with control frames previously registered.
If there is no control frames for this test, the test will fail. To generate
control frames for a given test, pass ``--set_test`` flag to pytest
while running the test.
Note that this decorator can be use with or without parentheses.
Parameters
----------
last_frame
whether the test should test the last frame, by default True.
renderer_class
The base renderer to use (OpenGLRenderer/CairoRenderer), by default CairoRenderer
base_scene
The base class for the scene (ThreeDScene, etc.), by default Scene
.. warning::
By default, last_frame is True, which means that only the last frame is tested.
If the scene has a moving animation, then the test must set last_frame to False.
"""
def decorator_maker(tested_scene_construct):
if (
SCENE_PARAMETER_NAME
not in inspect.getfullargspec(tested_scene_construct).args
):
raise Exception(
f"Invalid graphical test function test function : must have '{SCENE_PARAMETER_NAME}'as one of the parameters.",
)
# Exclude "scene" from the argument list of the signature.
old_sig = inspect.signature(
functools.partial(tested_scene_construct, scene=None),
)
if "__module_test__" not in tested_scene_construct.__globals__:
raise Exception(
"There is no module test name indicated for the graphical unit test. You have to declare __module_test__ in the test file.",
)
module_name = tested_scene_construct.__globals__.get("__module_test__")
test_name = tested_scene_construct.__name__[len("test_") :]
@functools.wraps(tested_scene_construct)
# The "request" parameter is meant to be used as a fixture by pytest. See below.
def wrapper(*args, request: FixtureRequest, tmp_path, **kwargs):
# check for cairo version
if (
renderer_class is CairoRenderer
and cairo.cairo_version() < MIN_CAIRO_VERSION
):
pytest.skip("Cairo version is too old. Skipping cairo graphical tests.")
# Wraps the test_function to a construct method, to "freeze" the eventual additional arguments (parametrizations fixtures).
construct = functools.partial(tested_scene_construct, *args, **kwargs)
# Kwargs contains the eventual parametrization arguments.
# This modifies the test_name so that it is defined by the parametrization
# arguments too.
# Example: if "length" is parametrized from 0 to 20, the kwargs
# will be once with {"length" : 1}, etc.
test_name_with_param = test_name + "_".join(
f"_{str(tup[0])}[{str(tup[1])}]" for tup in kwargs.items()
)
config_tests = _config_test(last_frame)
config_tests["text_dir"] = tmp_path
config_tests["tex_dir"] = tmp_path
if last_frame:
config_tests["frame_rate"] = 1
config_tests["dry_run"] = True
setting_test = request.config.getoption("--set_test")
try:
test_file_path = tested_scene_construct.__globals__["__file__"]
except Exception:
test_file_path = None
real_test = _make_test_comparing_frames(
file_path=_control_data_path(
test_file_path,
module_name,
test_name_with_param,
setting_test,
),
base_scene=base_scene,
construct=construct,
renderer_class=renderer_class,
is_set_test_data_test=setting_test,
last_frame=last_frame,
show_diff=request.config.getoption("--show_diff"),
size_frame=(config_tests["pixel_height"], config_tests["pixel_width"]),
)
# Isolate the config used for the test, to avoid modifying the global config during the test run.
with tempconfig({**config_tests, **custom_config}):
real_test()
parameters = list(old_sig.parameters.values())
# Adds "request" param into the signature of the wrapper, to use the associated pytest fixture.
# This fixture is needed to have access to flags value and pytest's config. See above.
if "request" not in old_sig.parameters:
parameters += [inspect.Parameter("request", inspect.Parameter.KEYWORD_ONLY)]
if "tmp_path" not in old_sig.parameters:
parameters += [
inspect.Parameter("tmp_path", inspect.Parameter.KEYWORD_ONLY),
]
new_sig = old_sig.replace(parameters=parameters)
wrapper.__signature__ = new_sig
# Reach a bit into pytest internals to hoist the marks from our wrapped
# function.
setattr(wrapper, "pytestmark", [])
new_marks = getattr(tested_scene_construct, "pytestmark", [])
wrapper.pytestmark = new_marks
return wrapper
# Case where the decorator is called with and without parentheses.
# If func is None, callabl(None) returns False
if callable(func):
return decorator_maker(func)
return decorator_maker
def _make_test_comparing_frames(
file_path: Path,
base_scene: type[Scene],
construct: Callable[[Scene], None],
renderer_class: type, # Renderer type, there is no superclass renderer yet .....
is_set_test_data_test: bool,
last_frame: bool,
show_diff: bool,
size_frame: tuple,
) -> Callable[[], None]:
"""Create the real pytest test that will fail if the frames mismatch.
Parameters
----------
file_path
The path of the control frames.
base_scene
The base scene class.
construct
The construct method (= the test function)
renderer_class
The renderer base class.
show_diff
whether to visually show_diff (see --show_diff)
Returns
-------
Callable[[], None]
The pytest test.
"""
if is_set_test_data_test:
frames_tester = _ControlDataWriter(file_path, size_frame=size_frame)
else:
frames_tester = _FramesTester(file_path, show_diff=show_diff)
file_writer_class = (
_make_scene_file_writer_class(frames_tester)
if not last_frame
else DummySceneFileWriter
)
testRenderer = _make_test_renderer_class(renderer_class)
def real_test():
with frames_tester.testing():
sceneTested = _make_test_scene_class(
base_scene=base_scene,
construct_test=construct,
# NOTE this is really ugly but it's due to the very bad design of the two renderers.
# If you pass a custom renderer to the Scene, the Camera class given as an argument in the Scene
# is not passed to the renderer. See __init__ of Scene.
# This potentially prevents OpenGL testing.
test_renderer=testRenderer(file_writer_class=file_writer_class)
if base_scene is not ThreeDScene
else testRenderer(
file_writer_class=file_writer_class,
camera_class=ThreeDCamera,
), # testRenderer(file_writer_class=file_writer_class),
)
scene_tested = sceneTested(skip_animations=True)
scene_tested.render()
if last_frame:
frames_tester.check_frame(-1, scene_tested.renderer.get_frame())
return real_test
def _control_data_path(
test_file_path: str | None, module_name: str, test_name: str, setting_test: bool
) -> Path:
if test_file_path is None:
# For some reason, path to test file containing @frames_comparison could not
# be determined. Use local directory instead.
test_file_path = __file__
path = Path(test_file_path).absolute().parent / "control_data" / module_name
if setting_test:
# Create the directory if not existing.
path.mkdir(exist_ok=True)
if not setting_test and not path.exists():
raise Exception(f"The control frames directory can't be found in {path}")
path = (path / test_name).with_suffix(".npz")
if not setting_test and not path.is_file():
raise Exception(
f"The control frame for the test {test_name} cannot be found in {path.parent}. "
"Make sure you generated the control frames first.",
)
return path
def _config_test(last_frame: bool) -> ManimConfig:
return ManimConfig().digest_file(
str(
Path(__file__).parent
/ (
"config_graphical_tests_monoframe.cfg"
if last_frame
else "config_graphical_tests_multiframes.cfg"
),
),
)
|
manim_ManimCommunity/manim/utils/testing/_show_diff.py
|
from __future__ import annotations
import logging
import warnings
import numpy as np
def show_diff_helper(
frame_number: int,
frame_data: np.ndarray,
expected_frame_data: np.ndarray,
control_data_filename: str,
):
"""Will visually display with matplotlib differences between frame generated and the one expected."""
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
gs = gridspec.GridSpec(2, 2)
fig = plt.figure()
fig.suptitle(f"Test difference summary at frame {frame_number}", fontsize=16)
ax = fig.add_subplot(gs[0, 0])
ax.imshow(frame_data)
ax.set_title("Generated")
ax = fig.add_subplot(gs[0, 1])
ax.imshow(expected_frame_data)
ax.set_title("Expected")
ax = fig.add_subplot(gs[1, :])
diff_im = expected_frame_data.copy()
diff_im = np.where(
frame_data != np.array([0, 0, 0, 255]),
np.array([0, 255, 0, 255], dtype="uint8"),
np.array([0, 0, 0, 255], dtype="uint8"),
) # Set any non-black pixels to green
np.putmask(
diff_im,
expected_frame_data != frame_data,
np.array([255, 0, 0, 255], dtype="uint8"),
) # Set any different pixels to red
ax.imshow(diff_im, interpolation="nearest")
ax.set_title("Difference summary: (green = same, red = different)")
with warnings.catch_warnings():
warnings.simplefilter("error")
try:
plt.show()
except UserWarning:
filename = f"{control_data_filename[:-4]}-diff.pdf"
plt.savefig(filename)
logging.warning(
"Interactive matplotlib interface not available,"
f" diff saved to {filename}."
)
|
manim_ManimCommunity/manim/utils/testing/_frames_testers.py
|
from __future__ import annotations
import contextlib
import warnings
from pathlib import Path
import numpy as np
from manim import logger
from ._show_diff import show_diff_helper
FRAME_ABSOLUTE_TOLERANCE = 1.01
FRAME_MISMATCH_RATIO_TOLERANCE = 1e-5
class _FramesTester:
def __init__(self, file_path: Path, show_diff=False) -> None:
self._file_path = file_path
self._show_diff = show_diff
self._frames: np.ndarray
self._number_frames: int = 0
self._frames_compared = 0
@contextlib.contextmanager
def testing(self):
with np.load(self._file_path) as data:
self._frames = data["frame_data"]
# For backward compatibility, when the control data contains only one frame (<= v0.8.0)
if len(self._frames.shape) != 4:
self._frames = np.expand_dims(self._frames, axis=0)
logger.debug(self._frames.shape)
self._number_frames = np.ma.size(self._frames, axis=0)
yield
assert self._frames_compared == self._number_frames, (
f"The scene tested contained {self._frames_compared} frames, "
f"when there are {self._number_frames} control frames for this test."
)
def check_frame(self, frame_number: int, frame: np.ndarray):
assert frame_number < self._number_frames, (
f"The tested scene is at frame number {frame_number} "
f"when there are {self._number_frames} control frames."
)
try:
np.testing.assert_allclose(
frame,
self._frames[frame_number],
atol=FRAME_ABSOLUTE_TOLERANCE,
err_msg=f"Frame no {frame_number}. You can use --show_diff to visually show the difference.",
verbose=False,
)
self._frames_compared += 1
except AssertionError as e:
number_of_matches = np.isclose(
frame, self._frames[frame_number], atol=FRAME_ABSOLUTE_TOLERANCE
).sum()
number_of_mismatches = frame.size - number_of_matches
if number_of_mismatches / frame.size < FRAME_MISMATCH_RATIO_TOLERANCE:
# we tolerate a small (< 0.001%) amount of pixel value errors
# in the tests, this accounts for minor OS dependent inconsistencies
self._frames_compared += 1
warnings.warn(
f"Mismatch of {number_of_mismatches} pixel values in frame {frame_number} "
f"against control data in {self._file_path}. Below error threshold, "
"continuing..."
)
return
if self._show_diff:
show_diff_helper(
frame_number,
frame,
self._frames[frame_number],
self._file_path.name,
)
raise e
class _ControlDataWriter(_FramesTester):
def __init__(self, file_path: Path, size_frame: tuple) -> None:
self.file_path = file_path
self.frames = np.empty((0, *size_frame, 4))
self._number_frames_written: int = 0
# Actually write a frame.
def check_frame(self, index: int, frame: np.ndarray):
frame = frame[np.newaxis, ...]
self.frames = np.concatenate((self.frames, frame))
self._number_frames_written += 1
@contextlib.contextmanager
def testing(self):
yield
self.save_contol_data()
def save_contol_data(self):
self.frames = self.frames.astype("uint8")
np.savez_compressed(self.file_path, frame_data=self.frames)
logger.info(
f"{self._number_frames_written} control frames saved in {self.file_path}",
)
|
manim_ManimCommunity/manim/camera/moving_camera.py
|
"""A camera able to move through a scene.
.. SEEALSO::
:mod:`.moving_camera_scene`
"""
from __future__ import annotations
__all__ = ["MovingCamera"]
import numpy as np
from .. import config
from ..camera.camera import Camera
from ..constants import DOWN, LEFT, RIGHT, UP
from ..mobject.frame import ScreenRectangle
from ..mobject.mobject import Mobject
from ..utils.color import WHITE
class MovingCamera(Camera):
"""
Stays in line with the height, width and position of it's 'frame', which is a Rectangle
.. SEEALSO::
:class:`.MovingCameraScene`
"""
def __init__(
self,
frame=None,
fixed_dimension=0, # width
default_frame_stroke_color=WHITE,
default_frame_stroke_width=0,
**kwargs,
):
"""
Frame is a Mobject, (should almost certainly be a rectangle)
determining which region of space the camera displays
"""
self.fixed_dimension = fixed_dimension
self.default_frame_stroke_color = default_frame_stroke_color
self.default_frame_stroke_width = default_frame_stroke_width
if frame is None:
frame = ScreenRectangle(height=config["frame_height"])
frame.set_stroke(
self.default_frame_stroke_color,
self.default_frame_stroke_width,
)
self.frame = frame
super().__init__(**kwargs)
# TODO, make these work for a rotated frame
@property
def frame_height(self):
"""Returns the height of the frame.
Returns
-------
float
The height of the frame.
"""
return self.frame.height
@property
def frame_width(self):
"""Returns the width of the frame
Returns
-------
float
The width of the frame.
"""
return self.frame.width
@property
def frame_center(self):
"""Returns the centerpoint of the frame in cartesian coordinates.
Returns
-------
np.array
The cartesian coordinates of the center of the frame.
"""
return self.frame.get_center()
@frame_height.setter
def frame_height(self, frame_height: float):
"""Sets the height of the frame in MUnits.
Parameters
----------
frame_height
The new frame_height.
"""
self.frame.stretch_to_fit_height(frame_height)
@frame_width.setter
def frame_width(self, frame_width: float):
"""Sets the width of the frame in MUnits.
Parameters
----------
frame_width
The new frame_width.
"""
self.frame.stretch_to_fit_width(frame_width)
@frame_center.setter
def frame_center(self, frame_center: np.ndarray | list | tuple | Mobject):
"""Sets the centerpoint of the frame.
Parameters
----------
frame_center
The point to which the frame must be moved.
If is of type mobject, the frame will be moved to
the center of that mobject.
"""
self.frame.move_to(frame_center)
def capture_mobjects(self, mobjects, **kwargs):
# self.reset_frame_center()
# self.realign_frame_shape()
super().capture_mobjects(mobjects, **kwargs)
# Since the frame can be moving around, the cairo
# context used for updating should be regenerated
# at each frame. So no caching.
def get_cached_cairo_context(self, pixel_array):
"""
Since the frame can be moving around, the cairo
context used for updating should be regenerated
at each frame. So no caching.
"""
return None
def cache_cairo_context(self, pixel_array, ctx):
"""
Since the frame can be moving around, the cairo
context used for updating should be regenerated
at each frame. So no caching.
"""
pass
# def reset_frame_center(self):
# self.frame_center = self.frame.get_center()
# def realign_frame_shape(self):
# height, width = self.frame_shape
# if self.fixed_dimension == 0:
# self.frame_shape = (height, self.frame.width
# else:
# self.frame_shape = (self.frame.height, width)
# self.resize_frame_shape(fixed_dimension=self.fixed_dimension)
def get_mobjects_indicating_movement(self):
"""
Returns all mobjects whose movement implies that the camera
should think of all other mobjects on the screen as moving
Returns
-------
list
"""
return [self.frame]
def auto_zoom(
self,
mobjects: list[Mobject],
margin: float = 0,
only_mobjects_in_frame: bool = False,
animate: bool = True,
):
"""Zooms on to a given array of mobjects (or a singular mobject)
and automatically resizes to frame all the mobjects.
.. NOTE::
This method only works when 2D-objects in the XY-plane are considered, it
will not work correctly when the camera has been rotated.
Parameters
----------
mobjects
The mobject or array of mobjects that the camera will focus on.
margin
The width of the margin that is added to the frame (optional, 0 by default).
only_mobjects_in_frame
If set to ``True``, only allows focusing on mobjects that are already in frame.
animate
If set to ``False``, applies the changes instead of returning the corresponding animation
Returns
-------
Union[_AnimationBuilder, ScreenRectangle]
_AnimationBuilder that zooms the camera view to a given list of mobjects
or ScreenRectangle with position and size updated to zoomed position.
"""
scene_critical_x_left = None
scene_critical_x_right = None
scene_critical_y_up = None
scene_critical_y_down = None
for m in mobjects:
if (m == self.frame) or (
only_mobjects_in_frame and not self.is_in_frame(m)
):
# detected camera frame, should not be used to calculate final position of camera
continue
# initialize scene critical points with first mobjects critical points
if scene_critical_x_left is None:
scene_critical_x_left = m.get_critical_point(LEFT)[0]
scene_critical_x_right = m.get_critical_point(RIGHT)[0]
scene_critical_y_up = m.get_critical_point(UP)[1]
scene_critical_y_down = m.get_critical_point(DOWN)[1]
else:
if m.get_critical_point(LEFT)[0] < scene_critical_x_left:
scene_critical_x_left = m.get_critical_point(LEFT)[0]
if m.get_critical_point(RIGHT)[0] > scene_critical_x_right:
scene_critical_x_right = m.get_critical_point(RIGHT)[0]
if m.get_critical_point(UP)[1] > scene_critical_y_up:
scene_critical_y_up = m.get_critical_point(UP)[1]
if m.get_critical_point(DOWN)[1] < scene_critical_y_down:
scene_critical_y_down = m.get_critical_point(DOWN)[1]
# calculate center x and y
x = (scene_critical_x_left + scene_critical_x_right) / 2
y = (scene_critical_y_up + scene_critical_y_down) / 2
# calculate proposed width and height of zoomed scene
new_width = abs(scene_critical_x_left - scene_critical_x_right)
new_height = abs(scene_critical_y_up - scene_critical_y_down)
m_target = self.frame.animate if animate else self.frame
# zoom to fit all mobjects along the side that has the largest size
if new_width / self.frame.width > new_height / self.frame.height:
return m_target.set_x(x).set_y(y).set(width=new_width + margin)
else:
return m_target.set_x(x).set_y(y).set(height=new_height + margin)
|
manim_ManimCommunity/manim/camera/mapping_camera.py
|
"""A camera that allows mapping between objects."""
from __future__ import annotations
__all__ = ["MappingCamera", "OldMultiCamera", "SplitScreenCamera"]
import math
import numpy as np
from ..camera.camera import Camera
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.config_ops import DictAsObject
# TODO: Add an attribute to mobjects under which they can specify that they should just
# map their centers but remain otherwise undistorted (useful for labels, etc.)
class MappingCamera(Camera):
"""Camera object that allows mapping
between objects.
"""
def __init__(
self,
mapping_func=lambda p: p,
min_num_curves=50,
allow_object_intrusion=False,
**kwargs,
):
self.mapping_func = mapping_func
self.min_num_curves = min_num_curves
self.allow_object_intrusion = allow_object_intrusion
super().__init__(**kwargs)
def points_to_pixel_coords(self, mobject, points):
return super().points_to_pixel_coords(
mobject,
np.apply_along_axis(self.mapping_func, 1, points),
)
def capture_mobjects(self, mobjects, **kwargs):
mobjects = self.get_mobjects_to_display(mobjects, **kwargs)
if self.allow_object_intrusion:
mobject_copies = mobjects
else:
mobject_copies = [mobject.copy() for mobject in mobjects]
for mobject in mobject_copies:
if (
isinstance(mobject, VMobject)
and 0 < mobject.get_num_curves() < self.min_num_curves
):
mobject.insert_n_curves(self.min_num_curves)
super().capture_mobjects(
mobject_copies,
include_submobjects=False,
excluded_mobjects=None,
)
# Note: This allows layering of multiple cameras onto the same portion of the pixel array,
# the later cameras overwriting the former
#
# TODO: Add optional separator borders between cameras (or perhaps peel this off into a
# CameraPlusOverlay class)
# TODO, the classes below should likely be deleted
class OldMultiCamera(Camera):
def __init__(self, *cameras_with_start_positions, **kwargs):
self.shifted_cameras = [
DictAsObject(
{
"camera": camera_with_start_positions[0],
"start_x": camera_with_start_positions[1][1],
"start_y": camera_with_start_positions[1][0],
"end_x": camera_with_start_positions[1][1]
+ camera_with_start_positions[0].pixel_width,
"end_y": camera_with_start_positions[1][0]
+ camera_with_start_positions[0].pixel_height,
},
)
for camera_with_start_positions in cameras_with_start_positions
]
super().__init__(**kwargs)
def capture_mobjects(self, mobjects, **kwargs):
for shifted_camera in self.shifted_cameras:
shifted_camera.camera.capture_mobjects(mobjects, **kwargs)
self.pixel_array[
shifted_camera.start_y : shifted_camera.end_y,
shifted_camera.start_x : shifted_camera.end_x,
] = shifted_camera.camera.pixel_array
def set_background(self, pixel_array, **kwargs):
for shifted_camera in self.shifted_cameras:
shifted_camera.camera.set_background(
pixel_array[
shifted_camera.start_y : shifted_camera.end_y,
shifted_camera.start_x : shifted_camera.end_x,
],
**kwargs,
)
def set_pixel_array(self, pixel_array, **kwargs):
super().set_pixel_array(pixel_array, **kwargs)
for shifted_camera in self.shifted_cameras:
shifted_camera.camera.set_pixel_array(
pixel_array[
shifted_camera.start_y : shifted_camera.end_y,
shifted_camera.start_x : shifted_camera.end_x,
],
**kwargs,
)
def init_background(self):
super().init_background()
for shifted_camera in self.shifted_cameras:
shifted_camera.camera.init_background()
# A OldMultiCamera which, when called with two full-size cameras, initializes itself
# as a split screen, also taking care to resize each individual camera within it
class SplitScreenCamera(OldMultiCamera):
def __init__(self, left_camera, right_camera, **kwargs):
Camera.__init__(self, **kwargs) # to set attributes such as pixel_width
self.left_camera = left_camera
self.right_camera = right_camera
half_width = math.ceil(self.pixel_width / 2)
for camera in [self.left_camera, self.right_camera]:
camera.reset_pixel_shape(camera.pixel_height, half_width)
super().__init__(
(left_camera, (0, 0)),
(right_camera, (0, half_width)),
)
|
manim_ManimCommunity/manim/camera/__init__.py
| |
manim_ManimCommunity/manim/camera/three_d_camera.py
|
"""A camera that can be positioned and oriented in three-dimensional space."""
from __future__ import annotations
__all__ = ["ThreeDCamera"]
from typing import Callable
import numpy as np
from manim.mobject.mobject import Mobject
from manim.mobject.three_d.three_d_utils import (
get_3d_vmob_end_corner,
get_3d_vmob_end_corner_unit_normal,
get_3d_vmob_start_corner,
get_3d_vmob_start_corner_unit_normal,
)
from manim.mobject.value_tracker import ValueTracker
from .. import config
from ..camera.camera import Camera
from ..constants import *
from ..mobject.types.point_cloud_mobject import Point
from ..utils.color import get_shaded_rgb
from ..utils.family import extract_mobject_family_members
from ..utils.space_ops import rotation_about_z, rotation_matrix
class ThreeDCamera(Camera):
def __init__(
self,
focal_distance=20.0,
shading_factor=0.2,
default_distance=5.0,
light_source_start_point=9 * DOWN + 7 * LEFT + 10 * OUT,
should_apply_shading=True,
exponential_projection=False,
phi=0,
theta=-90 * DEGREES,
gamma=0,
zoom=1,
**kwargs,
):
"""Initializes the ThreeDCamera
Parameters
----------
*kwargs
Any keyword argument of Camera.
"""
self._frame_center = Point(kwargs.get("frame_center", ORIGIN), stroke_width=0)
super().__init__(**kwargs)
self.focal_distance = focal_distance
self.phi = phi
self.theta = theta
self.gamma = gamma
self.zoom = zoom
self.shading_factor = shading_factor
self.default_distance = default_distance
self.light_source_start_point = light_source_start_point
self.light_source = Point(self.light_source_start_point)
self.should_apply_shading = should_apply_shading
self.exponential_projection = exponential_projection
self.max_allowable_norm = 3 * config["frame_width"]
self.phi_tracker = ValueTracker(self.phi)
self.theta_tracker = ValueTracker(self.theta)
self.focal_distance_tracker = ValueTracker(self.focal_distance)
self.gamma_tracker = ValueTracker(self.gamma)
self.zoom_tracker = ValueTracker(self.zoom)
self.fixed_orientation_mobjects = {}
self.fixed_in_frame_mobjects = set()
self.reset_rotation_matrix()
@property
def frame_center(self):
return self._frame_center.points[0]
@frame_center.setter
def frame_center(self, point):
self._frame_center.move_to(point)
def capture_mobjects(self, mobjects, **kwargs):
self.reset_rotation_matrix()
super().capture_mobjects(mobjects, **kwargs)
def get_value_trackers(self):
"""A list of :class:`ValueTrackers <.ValueTracker>` of phi, theta, focal_distance,
gamma and zoom.
Returns
-------
list
list of ValueTracker objects
"""
return [
self.phi_tracker,
self.theta_tracker,
self.focal_distance_tracker,
self.gamma_tracker,
self.zoom_tracker,
]
def modified_rgbas(self, vmobject, rgbas):
if not self.should_apply_shading:
return rgbas
if vmobject.shade_in_3d and (vmobject.get_num_points() > 0):
light_source_point = self.light_source.points[0]
if len(rgbas) < 2:
shaded_rgbas = rgbas.repeat(2, axis=0)
else:
shaded_rgbas = np.array(rgbas[:2])
shaded_rgbas[0, :3] = get_shaded_rgb(
shaded_rgbas[0, :3],
get_3d_vmob_start_corner(vmobject),
get_3d_vmob_start_corner_unit_normal(vmobject),
light_source_point,
)
shaded_rgbas[1, :3] = get_shaded_rgb(
shaded_rgbas[1, :3],
get_3d_vmob_end_corner(vmobject),
get_3d_vmob_end_corner_unit_normal(vmobject),
light_source_point,
)
return shaded_rgbas
return rgbas
def get_stroke_rgbas(
self,
vmobject,
background=False,
): # NOTE : DocStrings From parent
return self.modified_rgbas(vmobject, vmobject.get_stroke_rgbas(background))
def get_fill_rgbas(self, vmobject): # NOTE : DocStrings From parent
return self.modified_rgbas(vmobject, vmobject.get_fill_rgbas())
def get_mobjects_to_display(self, *args, **kwargs): # NOTE : DocStrings From parent
mobjects = super().get_mobjects_to_display(*args, **kwargs)
rot_matrix = self.get_rotation_matrix()
def z_key(mob):
if not (hasattr(mob, "shade_in_3d") and mob.shade_in_3d):
return np.inf
# Assign a number to a three dimensional mobjects
# based on how close it is to the camera
return np.dot(mob.get_z_index_reference_point(), rot_matrix.T)[2]
return sorted(mobjects, key=z_key)
def get_phi(self):
"""Returns the Polar angle (the angle off Z_AXIS) phi.
Returns
-------
float
The Polar angle in radians.
"""
return self.phi_tracker.get_value()
def get_theta(self):
"""Returns the Azimuthal i.e the angle that spins the camera around the Z_AXIS.
Returns
-------
float
The Azimuthal angle in radians.
"""
return self.theta_tracker.get_value()
def get_focal_distance(self):
"""Returns focal_distance of the Camera.
Returns
-------
float
The focal_distance of the Camera in MUnits.
"""
return self.focal_distance_tracker.get_value()
def get_gamma(self):
"""Returns the rotation of the camera about the vector from the ORIGIN to the Camera.
Returns
-------
float
The angle of rotation of the camera about the vector
from the ORIGIN to the Camera in radians
"""
return self.gamma_tracker.get_value()
def get_zoom(self):
"""Returns the zoom amount of the camera.
Returns
-------
float
The zoom amount of the camera.
"""
return self.zoom_tracker.get_value()
def set_phi(self, value: float):
"""Sets the polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.
Parameters
----------
value
The new value of the polar angle in radians.
"""
self.phi_tracker.set_value(value)
def set_theta(self, value: float):
"""Sets the azimuthal angle i.e the angle that spins the camera around Z_AXIS in radians.
Parameters
----------
value
The new value of the azimuthal angle in radians.
"""
self.theta_tracker.set_value(value)
def set_focal_distance(self, value: float):
"""Sets the focal_distance of the Camera.
Parameters
----------
value
The focal_distance of the Camera.
"""
self.focal_distance_tracker.set_value(value)
def set_gamma(self, value: float):
"""Sets the angle of rotation of the camera about the vector from the ORIGIN to the Camera.
Parameters
----------
value
The new angle of rotation of the camera.
"""
self.gamma_tracker.set_value(value)
def set_zoom(self, value: float):
"""Sets the zoom amount of the camera.
Parameters
----------
value
The zoom amount of the camera.
"""
self.zoom_tracker.set_value(value)
def reset_rotation_matrix(self):
"""Sets the value of self.rotation_matrix to
the matrix corresponding to the current position of the camera
"""
self.rotation_matrix = self.generate_rotation_matrix()
def get_rotation_matrix(self):
"""Returns the matrix corresponding to the current position of the camera.
Returns
-------
np.array
The matrix corresponding to the current position of the camera.
"""
return self.rotation_matrix
def generate_rotation_matrix(self):
"""Generates a rotation matrix based off the current position of the camera.
Returns
-------
np.array
The matrix corresponding to the current position of the camera.
"""
phi = self.get_phi()
theta = self.get_theta()
gamma = self.get_gamma()
matrices = [
rotation_about_z(-theta - 90 * DEGREES),
rotation_matrix(-phi, RIGHT),
rotation_about_z(gamma),
]
result = np.identity(3)
for matrix in matrices:
result = np.dot(matrix, result)
return result
def project_points(self, points: np.ndarray | list):
"""Applies the current rotation_matrix as a projection
matrix to the passed array of points.
Parameters
----------
points
The list of points to project.
Returns
-------
np.array
The points after projecting.
"""
frame_center = self.frame_center
focal_distance = self.get_focal_distance()
zoom = self.get_zoom()
rot_matrix = self.get_rotation_matrix()
points = points - frame_center
points = np.dot(points, rot_matrix.T)
zs = points[:, 2]
for i in 0, 1:
if self.exponential_projection:
# Proper projection would involve multiplying
# x and y by d / (d-z). But for points with high
# z value that causes weird artifacts, and applying
# the exponential helps smooth it out.
factor = np.exp(zs / focal_distance)
lt0 = zs < 0
factor[lt0] = focal_distance / (focal_distance - zs[lt0])
else:
factor = focal_distance / (focal_distance - zs)
factor[(focal_distance - zs) < 0] = 10**6
points[:, i] *= factor * zoom
return points
def project_point(self, point: list | np.ndarray):
"""Applies the current rotation_matrix as a projection
matrix to the passed point.
Parameters
----------
point
The point to project.
Returns
-------
np.array
The point after projection.
"""
return self.project_points(point.reshape((1, 3)))[0, :]
def transform_points_pre_display(
self,
mobject,
points,
): # TODO: Write Docstrings for this Method.
points = super().transform_points_pre_display(mobject, points)
fixed_orientation = mobject in self.fixed_orientation_mobjects
fixed_in_frame = mobject in self.fixed_in_frame_mobjects
if fixed_in_frame:
return points
if fixed_orientation:
center_func = self.fixed_orientation_mobjects[mobject]
center = center_func()
new_center = self.project_point(center)
return points + (new_center - center)
else:
return self.project_points(points)
def add_fixed_orientation_mobjects(
self,
*mobjects: Mobject,
use_static_center_func: bool = False,
center_func: Callable[[], np.ndarray] | None = None,
):
"""This method allows the mobject to have a fixed orientation,
even when the camera moves around.
E.G If it was passed through this method, facing the camera, it
will continue to face the camera even as the camera moves.
Highly useful when adding labels to graphs and the like.
Parameters
----------
*mobjects
The mobject whose orientation must be fixed.
use_static_center_func
Whether or not to use the function that takes the mobject's
center as centerpoint, by default False
center_func
The function which returns the centerpoint
with respect to which the mobject will be oriented, by default None
"""
# This prevents the computation of mobject.get_center
# every single time a projection happens
def get_static_center_func(mobject):
point = mobject.get_center()
return lambda: point
for mobject in mobjects:
if center_func:
func = center_func
elif use_static_center_func:
func = get_static_center_func(mobject)
else:
func = mobject.get_center
for submob in mobject.get_family():
self.fixed_orientation_mobjects[submob] = func
def add_fixed_in_frame_mobjects(self, *mobjects: Mobject):
"""This method allows the mobject to have a fixed position,
even when the camera moves around.
E.G If it was passed through this method, at the top of the frame, it
will continue to be displayed at the top of the frame.
Highly useful when displaying Titles or formulae or the like.
Parameters
----------
**mobjects
The mobject to fix in frame.
"""
for mobject in extract_mobject_family_members(mobjects):
self.fixed_in_frame_mobjects.add(mobject)
def remove_fixed_orientation_mobjects(self, *mobjects: Mobject):
"""If a mobject was fixed in its orientation by passing it through
:meth:`.add_fixed_orientation_mobjects`, then this undoes that fixing.
The Mobject will no longer have a fixed orientation.
Parameters
----------
mobjects
The mobjects whose orientation need not be fixed any longer.
"""
for mobject in extract_mobject_family_members(mobjects):
if mobject in self.fixed_orientation_mobjects:
del self.fixed_orientation_mobjects[mobject]
def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject):
"""If a mobject was fixed in frame by passing it through
:meth:`.add_fixed_in_frame_mobjects`, then this undoes that fixing.
The Mobject will no longer be fixed in frame.
Parameters
----------
mobjects
The mobjects which need not be fixed in frame any longer.
"""
for mobject in extract_mobject_family_members(mobjects):
if mobject in self.fixed_in_frame_mobjects:
self.fixed_in_frame_mobjects.remove(mobject)
|
manim_ManimCommunity/manim/camera/multi_camera.py
|
"""A camera supporting multiple perspectives."""
from __future__ import annotations
__all__ = ["MultiCamera"]
from manim.mobject.types.image_mobject import ImageMobject
from ..camera.moving_camera import MovingCamera
from ..utils.iterables import list_difference_update
class MultiCamera(MovingCamera):
"""Camera Object that allows for multiple perspectives."""
def __init__(
self,
image_mobjects_from_cameras: ImageMobject | None = None,
allow_cameras_to_capture_their_own_display=False,
**kwargs,
):
"""Initialises the MultiCamera
Parameters
----------
image_mobjects_from_cameras
kwargs
Any valid keyword arguments of MovingCamera.
"""
self.image_mobjects_from_cameras = []
if image_mobjects_from_cameras is not None:
for imfc in image_mobjects_from_cameras:
self.add_image_mobject_from_camera(imfc)
self.allow_cameras_to_capture_their_own_display = (
allow_cameras_to_capture_their_own_display
)
super().__init__(**kwargs)
def add_image_mobject_from_camera(self, image_mobject_from_camera: ImageMobject):
"""Adds an ImageMobject that's been obtained from the camera
into the list ``self.image_mobject_from_cameras``
Parameters
----------
image_mobject_from_camera
The ImageMobject to add to self.image_mobject_from_cameras
"""
# A silly method to have right now, but maybe there are things
# we want to guarantee about any imfc's added later.
imfc = image_mobject_from_camera
assert isinstance(imfc.camera, MovingCamera)
self.image_mobjects_from_cameras.append(imfc)
def update_sub_cameras(self):
"""Reshape sub_camera pixel_arrays"""
for imfc in self.image_mobjects_from_cameras:
pixel_height, pixel_width = self.pixel_array.shape[:2]
imfc.camera.frame_shape = (
imfc.camera.frame.height,
imfc.camera.frame.width,
)
imfc.camera.reset_pixel_shape(
int(pixel_height * imfc.height / self.frame_height),
int(pixel_width * imfc.width / self.frame_width),
)
def reset(self):
"""Resets the MultiCamera.
Returns
-------
MultiCamera
The reset MultiCamera
"""
for imfc in self.image_mobjects_from_cameras:
imfc.camera.reset()
super().reset()
return self
def capture_mobjects(self, mobjects, **kwargs):
self.update_sub_cameras()
for imfc in self.image_mobjects_from_cameras:
to_add = list(mobjects)
if not self.allow_cameras_to_capture_their_own_display:
to_add = list_difference_update(to_add, imfc.get_family())
imfc.camera.capture_mobjects(to_add, **kwargs)
super().capture_mobjects(mobjects, **kwargs)
def get_mobjects_indicating_movement(self):
"""Returns all mobjects whose movement implies that the camera
should think of all other mobjects on the screen as moving
Returns
-------
list
"""
return [self.frame] + [
imfc.camera.frame for imfc in self.image_mobjects_from_cameras
]
|
manim_ManimCommunity/manim/camera/camera.py
|
"""A camera converts the mobjects contained in a Scene into an array of pixels."""
from __future__ import annotations
__all__ = ["Camera", "BackgroundColoredVMobjectDisplayer"]
import copy
import itertools as it
import operator as op
import pathlib
from functools import reduce
from typing import Any, Callable, Iterable
import cairo
import numpy as np
from PIL import Image
from scipy.spatial.distance import pdist
from .. import config, logger
from ..constants import *
from ..mobject.mobject import Mobject
from ..mobject.types.image_mobject import AbstractImageMobject
from ..mobject.types.point_cloud_mobject import PMobject
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.color import ManimColor, ParsableManimColor, color_to_int_rgba
from ..utils.family import extract_mobject_family_members
from ..utils.images import get_full_raster_image_path
from ..utils.iterables import list_difference_update
from ..utils.space_ops import angle_of_vector
LINE_JOIN_MAP = {
LineJointType.AUTO: None, # TODO: this could be improved
LineJointType.ROUND: cairo.LineJoin.ROUND,
LineJointType.BEVEL: cairo.LineJoin.BEVEL,
LineJointType.MITER: cairo.LineJoin.MITER,
}
CAP_STYLE_MAP = {
CapStyleType.AUTO: None, # TODO: this could be improved
CapStyleType.ROUND: cairo.LineCap.ROUND,
CapStyleType.BUTT: cairo.LineCap.BUTT,
CapStyleType.SQUARE: cairo.LineCap.SQUARE,
}
class Camera:
"""Base camera class.
This is the object which takes care of what exactly is displayed
on screen at any given moment.
Parameters
----------
background_image
The path to an image that should be the background image.
If not set, the background is filled with :attr:`self.background_color`
background
What :attr:`background` is set to. By default, ``None``.
pixel_height
The height of the scene in pixels.
pixel_width
The width of the scene in pixels.
kwargs
Additional arguments (``background_color``, ``background_opacity``)
to be set.
"""
def __init__(
self,
background_image: str | None = None,
frame_center: np.ndarray = ORIGIN,
image_mode: str = "RGBA",
n_channels: int = 4,
pixel_array_dtype: str = "uint8",
cairo_line_width_multiple: float = 0.01,
use_z_index: bool = True,
background: np.ndarray | None = None,
pixel_height: int | None = None,
pixel_width: int | None = None,
frame_height: float | None = None,
frame_width: float | None = None,
frame_rate: float | None = None,
background_color: ParsableManimColor | None = None,
background_opacity: float | None = None,
**kwargs,
):
self.background_image = background_image
self.frame_center = frame_center
self.image_mode = image_mode
self.n_channels = n_channels
self.pixel_array_dtype = pixel_array_dtype
self.cairo_line_width_multiple = cairo_line_width_multiple
self.use_z_index = use_z_index
self.background = background
if pixel_height is None:
pixel_height = config["pixel_height"]
self.pixel_height = pixel_height
if pixel_width is None:
pixel_width = config["pixel_width"]
self.pixel_width = pixel_width
if frame_height is None:
frame_height = config["frame_height"]
self.frame_height = frame_height
if frame_width is None:
frame_width = config["frame_width"]
self.frame_width = frame_width
if frame_rate is None:
frame_rate = config["frame_rate"]
self.frame_rate = frame_rate
if background_color is None:
self._background_color = ManimColor.parse(config["background_color"])
else:
self._background_color = ManimColor.parse(background_color)
if background_opacity is None:
self._background_opacity = config["background_opacity"]
else:
self._background_opacity = background_opacity
# This one is in the same boat as the above, but it doesn't have the
# same name as the corresponding key so it has to be handled on its own
self.max_allowable_norm = config["frame_width"]
self.rgb_max_val = np.iinfo(self.pixel_array_dtype).max
self.pixel_array_to_cairo_context = {}
# Contains the correct method to process a list of Mobjects of the
# corresponding class. If a Mobject is not an instance of a class in
# this dict (or an instance of a class that inherits from a class in
# this dict), then it cannot be rendered.
self.init_background()
self.resize_frame_shape()
self.reset()
def __deepcopy__(self, memo):
# This is to address a strange bug where deepcopying
# will result in a segfault, which is somehow related
# to the aggdraw library
self.canvas = None
return copy.copy(self)
@property
def background_color(self):
return self._background_color
@background_color.setter
def background_color(self, color):
self._background_color = color
self.init_background()
@property
def background_opacity(self):
return self._background_opacity
@background_opacity.setter
def background_opacity(self, alpha):
self._background_opacity = alpha
self.init_background()
def type_or_raise(self, mobject: Mobject):
"""Return the type of mobject, if it is a type that can be rendered.
If `mobject` is an instance of a class that inherits from a class that
can be rendered, return the super class. For example, an instance of a
Square is also an instance of VMobject, and these can be rendered.
Therefore, `type_or_raise(Square())` returns True.
Parameters
----------
mobject
The object to take the type of.
Notes
-----
For a list of classes that can currently be rendered, see :meth:`display_funcs`.
Returns
-------
Type[:class:`~.Mobject`]
The type of mobjects, if it can be rendered.
Raises
------
:exc:`TypeError`
When mobject is not an instance of a class that can be rendered.
"""
self.display_funcs = {
VMobject: self.display_multiple_vectorized_mobjects,
PMobject: self.display_multiple_point_cloud_mobjects,
AbstractImageMobject: self.display_multiple_image_mobjects,
Mobject: lambda batch, pa: batch, # Do nothing
}
# We have to check each type in turn because we are dealing with
# super classes. For example, if square = Square(), then
# type(square) != VMobject, but isinstance(square, VMobject) == True.
for _type in self.display_funcs:
if isinstance(mobject, _type):
return _type
raise TypeError(f"Displaying an object of class {_type} is not supported")
def reset_pixel_shape(self, new_height: float, new_width: float):
"""This method resets the height and width
of a single pixel to the passed new_height and new_width.
Parameters
----------
new_height
The new height of the entire scene in pixels
new_width
The new width of the entire scene in pixels
"""
self.pixel_width = new_width
self.pixel_height = new_height
self.init_background()
self.resize_frame_shape()
self.reset()
def resize_frame_shape(self, fixed_dimension: int = 0):
"""
Changes frame_shape to match the aspect ratio
of the pixels, where fixed_dimension determines
whether frame_height or frame_width
remains fixed while the other changes accordingly.
Parameters
----------
fixed_dimension
If 0, height is scaled with respect to width
else, width is scaled with respect to height.
"""
pixel_height = self.pixel_height
pixel_width = self.pixel_width
frame_height = self.frame_height
frame_width = self.frame_width
aspect_ratio = pixel_width / pixel_height
if fixed_dimension == 0:
frame_height = frame_width / aspect_ratio
else:
frame_width = aspect_ratio * frame_height
self.frame_height = frame_height
self.frame_width = frame_width
def init_background(self):
"""Initialize the background.
If self.background_image is the path of an image
the image is set as background; else, the default
background color fills the background.
"""
height = self.pixel_height
width = self.pixel_width
if self.background_image is not None:
path = get_full_raster_image_path(self.background_image)
image = Image.open(path).convert(self.image_mode)
# TODO, how to gracefully handle backgrounds
# with different sizes?
self.background = np.array(image)[:height, :width]
self.background = self.background.astype(self.pixel_array_dtype)
else:
background_rgba = color_to_int_rgba(
self.background_color,
self.background_opacity,
)
self.background = np.zeros(
(height, width, self.n_channels),
dtype=self.pixel_array_dtype,
)
self.background[:, :] = background_rgba
def get_image(self, pixel_array: np.ndarray | list | tuple | None = None):
"""Returns an image from the passed
pixel array, or from the current frame
if the passed pixel array is none.
Parameters
----------
pixel_array
The pixel array from which to get an image, by default None
Returns
-------
PIL.Image
The PIL image of the array.
"""
if pixel_array is None:
pixel_array = self.pixel_array
return Image.fromarray(pixel_array, mode=self.image_mode)
def convert_pixel_array(
self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False
):
"""Converts a pixel array from values that have floats in then
to proper RGB values.
Parameters
----------
pixel_array
Pixel array to convert.
convert_from_floats
Whether or not to convert float values to ints, by default False
Returns
-------
np.array
The new, converted pixel array.
"""
retval = np.array(pixel_array)
if convert_from_floats:
retval = np.apply_along_axis(
lambda f: (f * self.rgb_max_val).astype(self.pixel_array_dtype),
2,
retval,
)
return retval
def set_pixel_array(
self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False
):
"""Sets the pixel array of the camera to the passed pixel array.
Parameters
----------
pixel_array
The pixel array to convert and then set as the camera's pixel array.
convert_from_floats
Whether or not to convert float values to proper RGB values, by default False
"""
converted_array = self.convert_pixel_array(pixel_array, convert_from_floats)
if not (
hasattr(self, "pixel_array")
and self.pixel_array.shape == converted_array.shape
):
self.pixel_array = converted_array
else:
# Set in place
self.pixel_array[:, :, :] = converted_array[:, :, :]
def set_background(
self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False
):
"""Sets the background to the passed pixel_array after converting
to valid RGB values.
Parameters
----------
pixel_array
The pixel array to set the background to.
convert_from_floats
Whether or not to convert floats values to proper RGB valid ones, by default False
"""
self.background = self.convert_pixel_array(pixel_array, convert_from_floats)
# TODO, this should live in utils, not as a method of Camera
def make_background_from_func(
self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray]
):
"""
Makes a pixel array for the background by using coords_to_colors_func to determine each pixel's color. Each input
pixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not
pixel coordinates), and each output is expected to be an RGBA array of 4 floats.
Parameters
----------
coords_to_colors_func
The function whose input is an (x,y) pair of coordinates and
whose return values must be the colors for that point
Returns
-------
np.array
The pixel array which can then be passed to set_background.
"""
logger.info("Starting set_background")
coords = self.get_coords_of_all_pixels()
new_background = np.apply_along_axis(coords_to_colors_func, 2, coords)
logger.info("Ending set_background")
return self.convert_pixel_array(new_background, convert_from_floats=True)
def set_background_from_func(
self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray]
):
"""
Sets the background to a pixel array using coords_to_colors_func to determine each pixel's color. Each input
pixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not
pixel coordinates), and each output is expected to be an RGBA array of 4 floats.
Parameters
----------
coords_to_colors_func
The function whose input is an (x,y) pair of coordinates and
whose return values must be the colors for that point
"""
self.set_background(self.make_background_from_func(coords_to_colors_func))
def reset(self):
"""Resets the camera's pixel array
to that of the background
Returns
-------
Camera
The camera object after setting the pixel array.
"""
self.set_pixel_array(self.background)
return self
def set_frame_to_background(self, background):
self.set_pixel_array(background)
####
def get_mobjects_to_display(
self,
mobjects: Iterable[Mobject],
include_submobjects: bool = True,
excluded_mobjects: list | None = None,
):
"""Used to get the list of mobjects to display
with the camera.
Parameters
----------
mobjects
The Mobjects
include_submobjects
Whether or not to include the submobjects of mobjects, by default True
excluded_mobjects
Any mobjects to exclude, by default None
Returns
-------
list
list of mobjects
"""
if include_submobjects:
mobjects = extract_mobject_family_members(
mobjects,
use_z_index=self.use_z_index,
only_those_with_points=True,
)
if excluded_mobjects:
all_excluded = extract_mobject_family_members(
excluded_mobjects,
use_z_index=self.use_z_index,
)
mobjects = list_difference_update(mobjects, all_excluded)
return list(mobjects)
def is_in_frame(self, mobject: Mobject):
"""Checks whether the passed mobject is in
frame or not.
Parameters
----------
mobject
The mobject for which the checking needs to be done.
Returns
-------
bool
True if in frame, False otherwise.
"""
fc = self.frame_center
fh = self.frame_height
fw = self.frame_width
return not reduce(
op.or_,
[
mobject.get_right()[0] < fc[0] - fw / 2,
mobject.get_bottom()[1] > fc[1] + fh / 2,
mobject.get_left()[0] > fc[0] + fw / 2,
mobject.get_top()[1] < fc[1] - fh / 2,
],
)
def capture_mobject(self, mobject: Mobject, **kwargs: Any):
"""Capture mobjects by storing it in :attr:`pixel_array`.
This is a single-mobject version of :meth:`capture_mobjects`.
Parameters
----------
mobject
Mobject to capture.
kwargs
Keyword arguments to be passed to :meth:`get_mobjects_to_display`.
"""
return self.capture_mobjects([mobject], **kwargs)
def capture_mobjects(self, mobjects: Iterable[Mobject], **kwargs):
"""Capture mobjects by printing them on :attr:`pixel_array`.
This is the essential function that converts the contents of a Scene
into an array, which is then converted to an image or video.
Parameters
----------
mobjects
Mobjects to capture.
kwargs
Keyword arguments to be passed to :meth:`get_mobjects_to_display`.
Notes
-----
For a list of classes that can currently be rendered, see :meth:`display_funcs`.
"""
# The mobjects will be processed in batches (or runs) of mobjects of
# the same type. That is, if the list mobjects contains objects of
# types [VMobject, VMobject, VMobject, PMobject, PMobject, VMobject],
# then they will be captured in three batches: [VMobject, VMobject,
# VMobject], [PMobject, PMobject], and [VMobject]. This must be done
# without altering their order. it.groupby computes exactly this
# partition while at the same time preserving order.
mobjects = self.get_mobjects_to_display(mobjects, **kwargs)
for group_type, group in it.groupby(mobjects, self.type_or_raise):
self.display_funcs[group_type](list(group), self.pixel_array)
# Methods associated with svg rendering
# NOTE: None of the methods below have been mentioned outside of their definitions. Their DocStrings are not as
# detailed as possible.
def get_cached_cairo_context(self, pixel_array: np.ndarray):
"""Returns the cached cairo context of the passed
pixel array if it exists, and None if it doesn't.
Parameters
----------
pixel_array
The pixel array to check.
Returns
-------
cairo.Context
The cached cairo context.
"""
return self.pixel_array_to_cairo_context.get(id(pixel_array), None)
def cache_cairo_context(self, pixel_array: np.ndarray, ctx: cairo.Context):
"""Caches the passed Pixel array into a Cairo Context
Parameters
----------
pixel_array
The pixel array to cache
ctx
The context to cache it into.
"""
self.pixel_array_to_cairo_context[id(pixel_array)] = ctx
def get_cairo_context(self, pixel_array: np.ndarray):
"""Returns the cairo context for a pixel array after
caching it to self.pixel_array_to_cairo_context
If that array has already been cached, it returns the
cached version instead.
Parameters
----------
pixel_array
The Pixel array to get the cairo context of.
Returns
-------
cairo.Context
The cairo context of the pixel array.
"""
cached_ctx = self.get_cached_cairo_context(pixel_array)
if cached_ctx:
return cached_ctx
pw = self.pixel_width
ph = self.pixel_height
fw = self.frame_width
fh = self.frame_height
fc = self.frame_center
surface = cairo.ImageSurface.create_for_data(
pixel_array,
cairo.FORMAT_ARGB32,
pw,
ph,
)
ctx = cairo.Context(surface)
ctx.scale(pw, ph)
ctx.set_matrix(
cairo.Matrix(
(pw / fw),
0,
0,
-(ph / fh),
(pw / 2) - fc[0] * (pw / fw),
(ph / 2) + fc[1] * (ph / fh),
),
)
self.cache_cairo_context(pixel_array, ctx)
return ctx
def display_multiple_vectorized_mobjects(
self, vmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple VMobjects in the pixel_array
Parameters
----------
vmobjects
list of VMobjects to display
pixel_array
The pixel array
"""
if len(vmobjects) == 0:
return
batch_image_pairs = it.groupby(vmobjects, lambda vm: vm.get_background_image())
for image, batch in batch_image_pairs:
if image:
self.display_multiple_background_colored_vmobjects(batch, pixel_array)
else:
self.display_multiple_non_background_colored_vmobjects(
batch,
pixel_array,
)
def display_multiple_non_background_colored_vmobjects(
self, vmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple VMobjects in the cairo context, as long as they don't have
background colors.
Parameters
----------
vmobjects
list of the VMobjects
pixel_array
The Pixel array to add the VMobjects to.
"""
ctx = self.get_cairo_context(pixel_array)
for vmobject in vmobjects:
self.display_vectorized(vmobject, ctx)
def display_vectorized(self, vmobject: VMobject, ctx: cairo.Context):
"""Displays a VMobject in the cairo context
Parameters
----------
vmobject
The Vectorized Mobject to display
ctx
The cairo context to use.
Returns
-------
Camera
The camera object
"""
self.set_cairo_context_path(ctx, vmobject)
self.apply_stroke(ctx, vmobject, background=True)
self.apply_fill(ctx, vmobject)
self.apply_stroke(ctx, vmobject)
return self
def set_cairo_context_path(self, ctx: cairo.Context, vmobject: VMobject):
"""Sets a path for the cairo context with the vmobject passed
Parameters
----------
ctx
The cairo context
vmobject
The VMobject
Returns
-------
Camera
Camera object after setting cairo_context_path
"""
points = self.transform_points_pre_display(vmobject, vmobject.points)
# TODO, shouldn't this be handled in transform_points_pre_display?
# points = points - self.get_frame_center()
if len(points) == 0:
return
ctx.new_path()
subpaths = vmobject.gen_subpaths_from_points_2d(points)
for subpath in subpaths:
quads = vmobject.gen_cubic_bezier_tuples_from_points(subpath)
ctx.new_sub_path()
start = subpath[0]
ctx.move_to(*start[:2])
for _p0, p1, p2, p3 in quads:
ctx.curve_to(*p1[:2], *p2[:2], *p3[:2])
if vmobject.consider_points_equals_2d(subpath[0], subpath[-1]):
ctx.close_path()
return self
def set_cairo_context_color(
self, ctx: cairo.Context, rgbas: np.ndarray, vmobject: VMobject
):
"""Sets the color of the cairo context
Parameters
----------
ctx
The cairo context
rgbas
The RGBA array with which to color the context.
vmobject
The VMobject with which to set the color.
Returns
-------
Camera
The camera object
"""
if len(rgbas) == 1:
# Use reversed rgb because cairo surface is
# encodes it in reverse order
ctx.set_source_rgba(*rgbas[0][2::-1], rgbas[0][3])
else:
points = vmobject.get_gradient_start_and_end_points()
points = self.transform_points_pre_display(vmobject, points)
pat = cairo.LinearGradient(*it.chain(*(point[:2] for point in points)))
step = 1.0 / (len(rgbas) - 1)
offsets = np.arange(0, 1 + step, step)
for rgba, offset in zip(rgbas, offsets):
pat.add_color_stop_rgba(offset, *rgba[2::-1], rgba[3])
ctx.set_source(pat)
return self
def apply_fill(self, ctx: cairo.Context, vmobject: VMobject):
"""Fills the cairo context
Parameters
----------
ctx
The cairo context
vmobject
The VMobject
Returns
-------
Camera
The camera object.
"""
self.set_cairo_context_color(ctx, self.get_fill_rgbas(vmobject), vmobject)
ctx.fill_preserve()
return self
def apply_stroke(
self, ctx: cairo.Context, vmobject: VMobject, background: bool = False
):
"""Applies a stroke to the VMobject in the cairo context.
Parameters
----------
ctx
The cairo context
vmobject
The VMobject
background
Whether or not to consider the background when applying this
stroke width, by default False
Returns
-------
Camera
The camera object with the stroke applied.
"""
width = vmobject.get_stroke_width(background)
if width == 0:
return self
self.set_cairo_context_color(
ctx,
self.get_stroke_rgbas(vmobject, background=background),
vmobject,
)
ctx.set_line_width(
width
* self.cairo_line_width_multiple
* (self.frame_width / self.frame_width),
# This ensures lines have constant width as you zoom in on them.
)
if vmobject.joint_type != LineJointType.AUTO:
ctx.set_line_join(LINE_JOIN_MAP[vmobject.joint_type])
if vmobject.cap_style != CapStyleType.AUTO:
ctx.set_line_cap(CAP_STYLE_MAP[vmobject.cap_style])
ctx.stroke_preserve()
return self
def get_stroke_rgbas(self, vmobject: VMobject, background: bool = False):
"""Gets the RGBA array for the stroke of the passed
VMobject.
Parameters
----------
vmobject
The VMobject
background
Whether or not to consider the background when getting the stroke
RGBAs, by default False
Returns
-------
np.ndarray
The RGBA array of the stroke.
"""
return vmobject.get_stroke_rgbas(background)
def get_fill_rgbas(self, vmobject: VMobject):
"""Returns the RGBA array of the fill of the passed VMobject
Parameters
----------
vmobject
The VMobject
Returns
-------
np.array
The RGBA Array of the fill of the VMobject
"""
return vmobject.get_fill_rgbas()
def get_background_colored_vmobject_displayer(self):
"""Returns the background_colored_vmobject_displayer
if it exists or makes one and returns it if not.
Returns
-------
BackGroundColoredVMobjectDisplayer
Object that displays VMobjects that have the same color
as the background.
"""
# Quite wordy to type out a bunch
bcvd = "background_colored_vmobject_displayer"
if not hasattr(self, bcvd):
setattr(self, bcvd, BackgroundColoredVMobjectDisplayer(self))
return getattr(self, bcvd)
def display_multiple_background_colored_vmobjects(
self, cvmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple vmobjects that have the same color as the background.
Parameters
----------
cvmobjects
List of Colored VMobjects
pixel_array
The pixel array.
Returns
-------
Camera
The camera object.
"""
displayer = self.get_background_colored_vmobject_displayer()
cvmobject_pixel_array = displayer.display(*cvmobjects)
self.overlay_rgba_array(pixel_array, cvmobject_pixel_array)
return self
# Methods for other rendering
# NOTE: Out of the following methods, only `transform_points_pre_display` and `points_to_pixel_coords` have been mentioned outside of their definitions.
# As a result, the other methods do not have as detailed docstrings as would be preferred.
def display_multiple_point_cloud_mobjects(
self, pmobjects: list, pixel_array: np.ndarray
):
"""Displays multiple PMobjects by modifying the passed pixel array.
Parameters
----------
pmobjects
List of PMobjects
pixel_array
The pixel array to modify.
"""
for pmobject in pmobjects:
self.display_point_cloud(
pmobject,
pmobject.points,
pmobject.rgbas,
self.adjusted_thickness(pmobject.stroke_width),
pixel_array,
)
def display_point_cloud(
self,
pmobject: PMobject,
points: list,
rgbas: np.ndarray,
thickness: float,
pixel_array: np.ndarray,
):
"""Displays a PMobject by modifying the pixel array suitably.
TODO: Write a description for the rgbas argument.
Parameters
----------
pmobject
Point Cloud Mobject
points
The points to display in the point cloud mobject
rgbas
thickness
The thickness of each point of the PMobject
pixel_array
The pixel array to modify.
"""
if len(points) == 0:
return
pixel_coords = self.points_to_pixel_coords(pmobject, points)
pixel_coords = self.thickened_coordinates(pixel_coords, thickness)
rgba_len = pixel_array.shape[2]
rgbas = (self.rgb_max_val * rgbas).astype(self.pixel_array_dtype)
target_len = len(pixel_coords)
factor = target_len // len(rgbas)
rgbas = np.array([rgbas] * factor).reshape((target_len, rgba_len))
on_screen_indices = self.on_screen_pixels(pixel_coords)
pixel_coords = pixel_coords[on_screen_indices]
rgbas = rgbas[on_screen_indices]
ph = self.pixel_height
pw = self.pixel_width
flattener = np.array([1, pw], dtype="int")
flattener = flattener.reshape((2, 1))
indices = np.dot(pixel_coords, flattener)[:, 0]
indices = indices.astype("int")
new_pa = pixel_array.reshape((ph * pw, rgba_len))
new_pa[indices] = rgbas
pixel_array[:, :] = new_pa.reshape((ph, pw, rgba_len))
def display_multiple_image_mobjects(
self, image_mobjects: list, pixel_array: np.ndarray
):
"""Displays multiple image mobjects by modifying the passed pixel_array.
Parameters
----------
image_mobjects
list of ImageMobjects
pixel_array
The pixel array to modify.
"""
for image_mobject in image_mobjects:
self.display_image_mobject(image_mobject, pixel_array)
def display_image_mobject(
self, image_mobject: AbstractImageMobject, pixel_array: np.ndarray
):
"""Displays an ImageMobject by changing the pixel_array suitably.
Parameters
----------
image_mobject
The imageMobject to display
pixel_array
The Pixel array to put the imagemobject in.
"""
corner_coords = self.points_to_pixel_coords(image_mobject, image_mobject.points)
ul_coords, ur_coords, dl_coords, _ = corner_coords
right_vect = ur_coords - ul_coords
down_vect = dl_coords - ul_coords
center_coords = ul_coords + (right_vect + down_vect) / 2
sub_image = Image.fromarray(image_mobject.get_pixel_array(), mode="RGBA")
# Reshape
pixel_width = max(int(pdist([ul_coords, ur_coords]).item()), 1)
pixel_height = max(int(pdist([ul_coords, dl_coords]).item()), 1)
sub_image = sub_image.resize(
(pixel_width, pixel_height),
resample=image_mobject.resampling_algorithm,
)
# Rotate
angle = angle_of_vector(right_vect)
adjusted_angle = -int(360 * angle / TAU)
if adjusted_angle != 0:
sub_image = sub_image.rotate(
adjusted_angle,
resample=image_mobject.resampling_algorithm,
expand=1,
)
# TODO, there is no accounting for a shear...
# Paste into an image as large as the camera's pixel array
full_image = Image.fromarray(
np.zeros((self.pixel_height, self.pixel_width)),
mode="RGBA",
)
new_ul_coords = center_coords - np.array(sub_image.size) / 2
new_ul_coords = new_ul_coords.astype(int)
full_image.paste(
sub_image,
box=(
new_ul_coords[0],
new_ul_coords[1],
new_ul_coords[0] + sub_image.size[0],
new_ul_coords[1] + sub_image.size[1],
),
)
# Paint on top of existing pixel array
self.overlay_PIL_image(pixel_array, full_image)
def overlay_rgba_array(self, pixel_array: np.ndarray, new_array: np.ndarray):
"""Overlays an RGBA array on top of the given Pixel array.
Parameters
----------
pixel_array
The original pixel array to modify.
new_array
The new pixel array to overlay.
"""
self.overlay_PIL_image(pixel_array, self.get_image(new_array))
def overlay_PIL_image(self, pixel_array: np.ndarray, image: Image):
"""Overlays a PIL image on the passed pixel array.
Parameters
----------
pixel_array
The Pixel array
image
The Image to overlay.
"""
pixel_array[:, :] = np.array(
Image.alpha_composite(self.get_image(pixel_array), image),
dtype="uint8",
)
def adjust_out_of_range_points(self, points: np.ndarray):
"""If any of the points in the passed array are out of
the viable range, they are adjusted suitably.
Parameters
----------
points
The points to adjust
Returns
-------
np.array
The adjusted points.
"""
if not np.any(points > self.max_allowable_norm):
return points
norms = np.apply_along_axis(np.linalg.norm, 1, points)
violator_indices = norms > self.max_allowable_norm
violators = points[violator_indices, :]
violator_norms = norms[violator_indices]
reshaped_norms = np.repeat(
violator_norms.reshape((len(violator_norms), 1)),
points.shape[1],
1,
)
rescaled = self.max_allowable_norm * violators / reshaped_norms
points[violator_indices] = rescaled
return points
def transform_points_pre_display(
self,
mobject,
points,
): # TODO: Write more detailed docstrings for this method.
# NOTE: There seems to be an unused argument `mobject`.
# Subclasses (like ThreeDCamera) may want to
# adjust points further before they're shown
if not np.all(np.isfinite(points)):
# TODO, print some kind of warning about
# mobject having invalid points?
points = np.zeros((1, 3))
return points
def points_to_pixel_coords(
self,
mobject,
points,
): # TODO: Write more detailed docstrings for this method.
points = self.transform_points_pre_display(mobject, points)
shifted_points = points - self.frame_center
result = np.zeros((len(points), 2))
pixel_height = self.pixel_height
pixel_width = self.pixel_width
frame_height = self.frame_height
frame_width = self.frame_width
width_mult = pixel_width / frame_width
width_add = pixel_width / 2
height_mult = pixel_height / frame_height
height_add = pixel_height / 2
# Flip on y-axis as you go
height_mult *= -1
result[:, 0] = shifted_points[:, 0] * width_mult + width_add
result[:, 1] = shifted_points[:, 1] * height_mult + height_add
return result.astype("int")
def on_screen_pixels(self, pixel_coords: np.ndarray):
"""Returns array of pixels that are on the screen from a given
array of pixel_coordinates
Parameters
----------
pixel_coords
The pixel coords to check.
Returns
-------
np.array
The pixel coords on screen.
"""
return reduce(
op.and_,
[
pixel_coords[:, 0] >= 0,
pixel_coords[:, 0] < self.pixel_width,
pixel_coords[:, 1] >= 0,
pixel_coords[:, 1] < self.pixel_height,
],
)
def adjusted_thickness(self, thickness: float) -> float:
"""Computes the adjusted stroke width for a zoomed camera.
Parameters
----------
thickness
The stroke width of a mobject.
Returns
-------
float
The adjusted stroke width that reflects zooming in with
the camera.
"""
# TODO: This seems...unsystematic
big_sum = op.add(config["pixel_height"], config["pixel_width"])
this_sum = op.add(self.pixel_height, self.pixel_width)
factor = big_sum / this_sum
return 1 + (thickness - 1) * factor
def get_thickening_nudges(self, thickness: float):
"""Determine a list of vectors used to nudge
two-dimensional pixel coordinates.
Parameters
----------
thickness
Returns
-------
np.array
"""
thickness = int(thickness)
_range = list(range(-thickness // 2 + 1, thickness // 2 + 1))
return np.array(list(it.product(_range, _range)))
def thickened_coordinates(self, pixel_coords: np.ndarray, thickness: float):
"""Returns thickened coordinates for a passed array of pixel coords and
a thickness to thicken by.
Parameters
----------
pixel_coords
Pixel coordinates
thickness
Thickness
Returns
-------
np.array
Array of thickened pixel coords.
"""
nudges = self.get_thickening_nudges(thickness)
pixel_coords = np.array([pixel_coords + nudge for nudge in nudges])
size = pixel_coords.size
return pixel_coords.reshape((size // 2, 2))
# TODO, reimplement using cairo matrix
def get_coords_of_all_pixels(self):
"""Returns the cartesian coordinates of each pixel.
Returns
-------
np.ndarray
The array of cartesian coordinates.
"""
# These are in x, y order, to help me keep things straight
full_space_dims = np.array([self.frame_width, self.frame_height])
full_pixel_dims = np.array([self.pixel_width, self.pixel_height])
# These are addressed in the same y, x order as in pixel_array, but the values in them
# are listed in x, y order
uncentered_pixel_coords = np.indices([self.pixel_height, self.pixel_width])[
::-1
].transpose(1, 2, 0)
uncentered_space_coords = (
uncentered_pixel_coords * full_space_dims
) / full_pixel_dims
# Could structure above line's computation slightly differently, but figured (without much
# thought) multiplying by frame_shape first, THEN dividing by pixel_shape, is probably
# better than the other order, for avoiding underflow quantization in the division (whereas
# overflow is unlikely to be a problem)
centered_space_coords = uncentered_space_coords - (full_space_dims / 2)
# Have to also flip the y coordinates to account for pixel array being listed in
# top-to-bottom order, opposite of screen coordinate convention
centered_space_coords = centered_space_coords * (1, -1)
return centered_space_coords
# NOTE: The methods of the following class have not been mentioned outside of their definitions.
# Their DocStrings are not as detailed as preferred.
class BackgroundColoredVMobjectDisplayer:
"""Auxiliary class that handles displaying vectorized mobjects with
a set background image.
Parameters
----------
camera
Camera object to use.
"""
def __init__(self, camera: Camera):
self.camera = camera
self.file_name_to_pixel_array_map = {}
self.pixel_array = np.array(camera.pixel_array)
self.reset_pixel_array()
def reset_pixel_array(self):
self.pixel_array[:, :] = 0
def resize_background_array(
self,
background_array: np.ndarray,
new_width: float,
new_height: float,
mode: str = "RGBA",
):
"""Resizes the pixel array representing the background.
Parameters
----------
background_array
The pixel
new_width
The new width of the background
new_height
The new height of the background
mode
The PIL image mode, by default "RGBA"
Returns
-------
np.array
The numpy pixel array of the resized background.
"""
image = Image.fromarray(background_array)
image = image.convert(mode)
resized_image = image.resize((new_width, new_height))
return np.array(resized_image)
def resize_background_array_to_match(
self, background_array: np.ndarray, pixel_array: np.ndarray
):
"""Resizes the background array to match the passed pixel array.
Parameters
----------
background_array
The prospective pixel array.
pixel_array
The pixel array whose width and height should be matched.
Returns
-------
np.array
The resized background array.
"""
height, width = pixel_array.shape[:2]
mode = "RGBA" if pixel_array.shape[2] == 4 else "RGB"
return self.resize_background_array(background_array, width, height, mode)
def get_background_array(self, image: Image.Image | pathlib.Path | str):
"""Gets the background array that has the passed file_name.
Parameters
----------
image
The background image or its file name.
Returns
-------
np.ndarray
The pixel array of the image.
"""
image_key = str(image)
if image_key in self.file_name_to_pixel_array_map:
return self.file_name_to_pixel_array_map[image_key]
if isinstance(image, str):
full_path = get_full_raster_image_path(image)
image = Image.open(full_path)
back_array = np.array(image)
pixel_array = self.pixel_array
if not np.all(pixel_array.shape == back_array.shape):
back_array = self.resize_background_array_to_match(back_array, pixel_array)
self.file_name_to_pixel_array_map[image_key] = back_array
return back_array
def display(self, *cvmobjects: VMobject):
"""Displays the colored VMobjects.
Parameters
----------
*cvmobjects
The VMobjects
Returns
-------
np.array
The pixel array with the `cvmobjects` displayed.
"""
batch_image_pairs = it.groupby(cvmobjects, lambda cv: cv.get_background_image())
curr_array = None
for image, batch in batch_image_pairs:
background_array = self.get_background_array(image)
pixel_array = self.pixel_array
self.camera.display_multiple_non_background_colored_vmobjects(
batch,
pixel_array,
)
new_array = np.array(
(background_array * pixel_array.astype("float") / 255),
dtype=self.camera.pixel_array_dtype,
)
if curr_array is None:
curr_array = new_array
else:
curr_array = np.maximum(curr_array, new_array)
self.reset_pixel_array()
return curr_array
|
manim_ManimCommunity/manim/cli/__init__.py
| |
manim_ManimCommunity/manim/cli/default_group.py
|
"""``DefaultGroup`` allows a subcommand to act as the main command.
In particular, this class is what allows ``manim`` to act as ``manim render``.
.. note::
This is a vendored version of https://github.com/click-contrib/click-default-group/
under the BSD 3-Clause "New" or "Revised" License.
This library isn't used as a dependency as we need to inherit from ``cloup.Group`` instead
of ``click.Group``.
"""
import warnings
import cloup
__all__ = ["DefaultGroup"]
class DefaultGroup(cloup.Group):
"""Invokes a subcommand marked with ``default=True`` if any subcommand not
chosen.
"""
def __init__(self, *args, **kwargs):
# To resolve as the default command.
if not kwargs.get("ignore_unknown_options", True):
raise ValueError("Default group accepts unknown options")
self.ignore_unknown_options = True
self.default_cmd_name = kwargs.pop("default", None)
self.default_if_no_args = kwargs.pop("default_if_no_args", False)
super().__init__(*args, **kwargs)
def set_default_command(self, command):
"""Sets a command function as the default command."""
cmd_name = command.name
self.add_command(command)
self.default_cmd_name = cmd_name
def parse_args(self, ctx, args):
if not args and self.default_if_no_args:
args.insert(0, self.default_cmd_name)
return super().parse_args(ctx, args)
def get_command(self, ctx, cmd_name):
if cmd_name not in self.commands:
# No command name matched.
ctx.arg0 = cmd_name
cmd_name = self.default_cmd_name
return super().get_command(ctx, cmd_name)
def resolve_command(self, ctx, args):
base = super()
cmd_name, cmd, args = base.resolve_command(ctx, args)
if hasattr(ctx, "arg0"):
args.insert(0, ctx.arg0)
cmd_name = cmd.name
return cmd_name, cmd, args
def command(self, *args, **kwargs):
default = kwargs.pop("default", False)
decorator = super().command(*args, **kwargs)
if not default:
return decorator
warnings.warn(
"Use default param of DefaultGroup or set_default_command() instead",
DeprecationWarning,
)
def _decorator(f):
cmd = decorator(f)
self.set_default_command(cmd)
return cmd
return _decorator
|
manim_ManimCommunity/manim/cli/plugins/__init__.py
| |
manim_ManimCommunity/manim/cli/plugins/commands.py
|
"""Manim's plugin subcommand.
Manim's plugin subcommand is accessed in the command-line interface via ``manim
plugin``. Here you can specify options, subcommands, and subgroups for the plugin
group.
"""
from __future__ import annotations
import cloup
from ...constants import CONTEXT_SETTINGS, EPILOG
from ...plugins.plugins_flags import list_plugins
__all__ = ["plugins"]
@cloup.command(
context_settings=CONTEXT_SETTINGS,
no_args_is_help=True,
epilog=EPILOG,
help="Manages Manim plugins.",
)
@cloup.option(
"-l",
"--list",
"list_available",
is_flag=True,
help="List available plugins.",
)
def plugins(list_available):
if list_available:
list_plugins()
|
manim_ManimCommunity/manim/cli/init/__init__.py
| |
manim_ManimCommunity/manim/cli/init/commands.py
|
"""Manim's init subcommand.
Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.
"""
from __future__ import annotations
import configparser
from pathlib import Path
import click
import cloup
from ... import console
from ...constants import CONTEXT_SETTINGS, EPILOG, QUALITIES
from ...utils.file_ops import (
add_import_statement,
copy_template_files,
get_template_names,
get_template_path,
)
CFG_DEFAULTS = {
"frame_rate": 30,
"background_color": "BLACK",
"background_opacity": 1,
"scene_names": "Default",
"resolution": (854, 480),
}
__all__ = ["select_resolution", "update_cfg", "project", "scene"]
def select_resolution():
"""Prompts input of type click.Choice from user. Presents options from QUALITIES constant.
Returns
-------
:class:`tuple`
Tuple containing height and width.
"""
resolution_options = []
for quality in QUALITIES.items():
resolution_options.append(
(quality[1]["pixel_height"], quality[1]["pixel_width"]),
)
resolution_options.pop()
choice = click.prompt(
"\nSelect resolution:\n",
type=cloup.Choice([f"{i[0]}p" for i in resolution_options]),
show_default=False,
default="480p",
)
return [res for res in resolution_options if f"{res[0]}p" == choice][0]
def update_cfg(cfg_dict: dict, project_cfg_path: Path):
"""Updates the manim.cfg file after reading it from the project_cfg_path.
Parameters
----------
cfg_dict
values used to update manim.cfg found project_cfg_path.
project_cfg_path
Path of manim.cfg file.
"""
config = configparser.ConfigParser()
config.read(project_cfg_path)
cli_config = config["CLI"]
for key, value in cfg_dict.items():
if key == "resolution":
cli_config["pixel_height"] = str(value[0])
cli_config["pixel_width"] = str(value[1])
else:
cli_config[key] = str(value)
with project_cfg_path.open("w") as conf:
config.write(conf)
@cloup.command(
context_settings=CONTEXT_SETTINGS,
epilog=EPILOG,
)
@cloup.argument("project_name", type=Path, required=False)
@cloup.option(
"-d",
"--default",
"default_settings",
is_flag=True,
help="Default settings for project creation.",
nargs=1,
)
def project(default_settings, **args):
"""Creates a new project.
PROJECT_NAME is the name of the folder in which the new project will be initialized.
"""
if args["project_name"]:
project_name = args["project_name"]
else:
project_name = click.prompt("Project Name", type=Path)
# in the future when implementing a full template system. Choices are going to be saved in some sort of config file for templates
template_name = click.prompt(
"Template",
type=click.Choice(get_template_names(), False),
default="Default",
)
if project_name.is_dir():
console.print(
f"\nFolder [red]{project_name}[/red] exists. Please type another name\n",
)
else:
project_name.mkdir()
new_cfg = {}
new_cfg_path = Path.resolve(project_name / "manim.cfg")
if not default_settings:
for key, value in CFG_DEFAULTS.items():
if key == "scene_names":
new_cfg[key] = template_name + "Template"
elif key == "resolution":
new_cfg[key] = select_resolution()
else:
new_cfg[key] = click.prompt(f"\n{key}", default=value)
console.print("\n", new_cfg)
if click.confirm("Do you want to continue?", default=True, abort=True):
copy_template_files(project_name, template_name)
update_cfg(new_cfg, new_cfg_path)
else:
copy_template_files(project_name, template_name)
update_cfg(CFG_DEFAULTS, new_cfg_path)
@cloup.command(
context_settings=CONTEXT_SETTINGS,
no_args_is_help=True,
epilog=EPILOG,
)
@cloup.argument("scene_name", type=str, required=True)
@cloup.argument("file_name", type=str, required=False)
def scene(**args):
"""Inserts a SCENE to an existing FILE or creates a new FILE.
SCENE is the name of the scene that will be inserted.
FILE is the name of file in which the SCENE will be inserted.
"""
template_name = click.prompt(
"template",
type=click.Choice(get_template_names(), False),
default="Default",
)
scene = (get_template_path() / f"{template_name}.mtp").resolve().read_text()
scene = scene.replace(template_name + "Template", args["scene_name"], 1)
if args["file_name"]:
file_name = Path(args["file_name"])
if file_name.suffix != ".py":
file_name = file_name.with_suffix(file_name.suffix + ".py")
if file_name.is_file():
# file exists so we are going to append new scene to that file
with file_name.open("a") as f:
f.write("\n\n\n" + scene)
else:
# file does not exist so we create a new file, append the scene and prepend the import statement
file_name.write_text("\n\n\n" + scene)
add_import_statement(file_name)
else:
# file name is not provided so we assume it is main.py
# if main.py does not exist we do not continue
with Path("main.py").open("a") as f:
f.write("\n\n\n" + scene)
@cloup.group(
context_settings=CONTEXT_SETTINGS,
invoke_without_command=True,
no_args_is_help=True,
epilog=EPILOG,
help="Create a new project or insert a new scene.",
)
@cloup.pass_context
def init(ctx):
pass
init.add_command(project)
init.add_command(scene)
|
manim_ManimCommunity/manim/cli/checkhealth/__init__.py
| |
manim_ManimCommunity/manim/cli/checkhealth/commands.py
|
"""A CLI utility helping to diagnose problems with
your Manim installation.
"""
from __future__ import annotations
import sys
import click
import cloup
from .checks import HEALTH_CHECKS
__all__ = ["checkhealth"]
@cloup.command(
context_settings=None,
)
def checkhealth():
"""This subcommand checks whether Manim is installed correctly
and has access to its required (and optional) system dependencies.
"""
click.echo(f"Python executable: {sys.executable}\n")
click.echo("Checking whether your installation of Manim Community is healthy...")
failed_checks = []
for check in HEALTH_CHECKS:
click.echo(f"- {check.description} ... ", nl=False)
if any(
failed_check.__name__ in check.skip_on_failed
for failed_check in failed_checks
):
click.secho("SKIPPED", fg="blue")
continue
check_result = check()
if check_result:
click.secho("PASSED", fg="green")
else:
click.secho("FAILED", fg="red")
failed_checks.append(check)
click.echo()
if failed_checks:
click.echo(
"There are problems with your installation, "
"here are some recommendations to fix them:"
)
for ind, failed_check in enumerate(failed_checks):
click.echo(failed_check.recommendation)
if ind + 1 < len(failed_checks):
click.confirm("Continue with next recommendation?")
else: # no problems detected!
click.echo("No problems detected, your installation seems healthy!")
render_test_scene = click.confirm(
"Would you like to render and preview a test scene?"
)
if render_test_scene:
import manim as mn
class CheckHealthDemo(mn.Scene):
def construct(self):
banner = mn.ManimBanner().shift(mn.UP * 0.5)
self.play(banner.create())
self.wait(0.5)
self.play(banner.expand())
self.wait(0.5)
text_left = mn.Text("All systems operational!")
formula_right = mn.MathTex(r"\oint_{\gamma} f(z)~dz = 0")
text_tex_group = mn.VGroup(text_left, formula_right)
text_tex_group.arrange(mn.RIGHT, buff=1).next_to(banner, mn.DOWN)
self.play(mn.Write(text_tex_group))
self.wait(0.5)
self.play(
mn.FadeOut(banner, shift=mn.UP),
mn.FadeOut(text_tex_group, shift=mn.DOWN),
)
with mn.tempconfig({"preview": True, "disable_caching": True}):
CheckHealthDemo().render()
|
manim_ManimCommunity/manim/cli/checkhealth/checks.py
|
"""Auxiliary module for the checkhealth subcommand, contains
the actual check implementations."""
from __future__ import annotations
import os
import shutil
import subprocess
from typing import Callable
from ..._config import config
__all__ = ["HEALTH_CHECKS"]
HEALTH_CHECKS = []
def healthcheck(
description: str,
recommendation: str,
skip_on_failed: list[Callable | str] | None = None,
post_fail_fix_hook: Callable | None = None,
):
"""Decorator used for declaring health checks.
This decorator attaches some data to a function,
which is then added to a list containing all checks.
Parameters
----------
description
A brief description of this check, displayed when
the checkhealth subcommand is run.
recommendation
Help text which is displayed in case the check fails.
skip_on_failed
A list of check functions which, if they fail, cause
the current check to be skipped.
post_fail_fix_hook
A function that is supposed to (interactively) help
to fix the detected problem, if possible. This is
only called upon explicit confirmation of the user.
Returns
-------
A check function, as required by the checkhealth subcommand.
"""
if skip_on_failed is None:
skip_on_failed = []
skip_on_failed = [
skip.__name__ if callable(skip) else skip for skip in skip_on_failed
]
def decorator(func):
func.description = description
func.recommendation = recommendation
func.skip_on_failed = skip_on_failed
func.post_fail_fix_hook = post_fail_fix_hook
HEALTH_CHECKS.append(func)
return func
return decorator
@healthcheck(
description="Checking whether manim is on your PATH",
recommendation=(
"The command <manim> is currently not on your system's PATH.\n\n"
"You can work around this by calling the manim module directly "
"via <python -m manim> instead of just <manim>.\n\n"
"To fix the PATH issue properly: "
"Usually, the Python package installer pip issues a warning "
"during the installation which contains more information. "
"Consider reinstalling manim via <pip uninstall manim> "
"followed by <pip install manim> to see the warning again, "
"then consult the internet on how to modify your system's "
"PATH variable."
),
)
def is_manim_on_path():
path_to_manim = shutil.which("manim")
return path_to_manim is not None
@healthcheck(
description="Checking whether the executable belongs to manim",
recommendation=(
"The command <manim> does not belong to your installed version "
"of this library, it likely belongs to manimgl / manimlib.\n\n"
"Run manim via <python -m manim> or via <manimce>, or uninstall "
"and reinstall manim via <pip install --upgrade "
"--force-reinstall manim> to fix this."
),
skip_on_failed=[is_manim_on_path],
)
def is_manim_executable_associated_to_this_library():
path_to_manim = shutil.which("manim")
with open(path_to_manim, "rb") as f:
manim_exec = f.read()
# first condition below corresponds to the executable being
# some sort of python script. second condition happens when
# the executable is actually a Windows batch file.
return b"manim.__main__" in manim_exec or b'"%~dp0\\manim"' in manim_exec
@healthcheck(
description="Checking whether ffmpeg is available",
recommendation=(
"Manim does not work without ffmpeg. Please follow our "
"installation instructions "
"at https://docs.manim.community/en/stable/installation.html "
"to download ffmpeg. Then, either ...\n\n"
"(a) ... make the ffmpeg executable available to your system's PATH,\n"
"(b) or, alternatively, use <manim cfg write --open> to create a "
"custom configuration and set the ffmpeg_executable variable to the "
"full absolute path to the ffmpeg executable."
),
)
def is_ffmpeg_available():
path_to_ffmpeg = shutil.which(config.ffmpeg_executable)
return path_to_ffmpeg is not None and os.access(path_to_ffmpeg, os.X_OK)
@healthcheck(
description="Checking whether ffmpeg is working",
recommendation=(
"Your installed version of ffmpeg does not support x264 encoding, "
"which manim requires. Please follow our installation instructions "
"at https://docs.manim.community/en/stable/installation.html "
"to download and install a newer version of ffmpeg."
),
skip_on_failed=[is_ffmpeg_available],
)
def is_ffmpeg_working():
ffmpeg_version = subprocess.run(
[config.ffmpeg_executable, "-version"],
stdout=subprocess.PIPE,
).stdout.decode()
return (
ffmpeg_version.startswith("ffmpeg version")
and "--enable-libx264" in ffmpeg_version
)
@healthcheck(
description="Checking whether latex is available",
recommendation=(
"Manim cannot find <latex> on your system's PATH. "
"You will not be able to use Tex and MathTex mobjects "
"in your scenes.\n\n"
"Consult our installation instructions "
"at https://docs.manim.community/en/stable/installation.html "
"or search the web for instructions on how to install a "
"LaTeX distribution on your operating system."
),
)
def is_latex_available():
path_to_latex = shutil.which("latex")
return path_to_latex is not None and os.access(path_to_latex, os.X_OK)
@healthcheck(
description="Checking whether dvisvgm is available",
recommendation=(
"Manim could find <latex>, but not <dvisvgm> on your system's "
"PATH. Make sure your installed LaTeX distribution comes with "
"dvisvgm and consider installing a larger distribution if it "
"does not."
),
skip_on_failed=[is_latex_available],
)
def is_dvisvgm_available():
path_to_dvisvgm = shutil.which("dvisvgm")
return path_to_dvisvgm is not None and os.access(path_to_dvisvgm, os.X_OK)
|
manim_ManimCommunity/manim/cli/render/render_options.py
|
from __future__ import annotations
import re
from cloup import Choice, option, option_group
from manim.constants import QUALITIES, RendererType
from ... import logger
__all__ = ["render_options"]
def validate_scene_range(ctx, param, value):
try:
start = int(value)
return (start,)
except Exception:
pass
if value:
try:
start, end = map(int, re.split(r"[;,\-]", value))
return start, end
except Exception:
logger.error("Couldn't determine a range for -n option.")
exit()
def validate_resolution(ctx, param, value):
if value:
try:
start, end = map(int, re.split(r"[;,\-]", value))
return (start, end)
except Exception:
logger.error("Resolution option is invalid.")
exit()
render_options = option_group(
"Render Options",
option(
"-n",
"--from_animation_number",
callback=validate_scene_range,
help="Start rendering from n_0 until n_1. If n_1 is left unspecified, "
"renders all scenes after n_0.",
default=None,
),
option(
"-a",
"--write_all",
is_flag=True,
help="Render all scenes in the input file.",
default=None,
),
option(
"--format",
type=Choice(["png", "gif", "mp4", "webm", "mov"], case_sensitive=False),
default=None,
),
option(
"-s",
"--save_last_frame",
default=None,
is_flag=True,
help="Render and save only the last frame of a scene as a PNG image.",
),
option(
"-q",
"--quality",
default=None,
type=Choice(
list(reversed([q["flag"] for q in QUALITIES.values() if q["flag"]])), # type: ignore
case_sensitive=False,
),
help="Render quality at the follow resolution framerates, respectively: "
+ ", ".join(
reversed(
[
f'{q["pixel_width"]}x{q["pixel_height"]} {q["frame_rate"]}FPS'
for q in QUALITIES.values()
if q["flag"]
]
)
),
),
option(
"-r",
"--resolution",
callback=validate_resolution,
default=None,
help='Resolution in "W,H" for when 16:9 aspect ratio isn\'t possible.',
),
option(
"--fps",
"--frame_rate",
"frame_rate",
type=float,
default=None,
help="Render at this frame rate.",
),
option(
"--renderer",
type=Choice(
[renderer_type.value for renderer_type in RendererType],
case_sensitive=False,
),
help="Select a renderer for your Scene.",
default="cairo",
),
option(
"-g",
"--save_pngs",
is_flag=True,
default=None,
help="Save each frame as png (Deprecated).",
),
option(
"-i",
"--save_as_gif",
default=None,
is_flag=True,
help="Save as a gif (Deprecated).",
),
option(
"--save_sections",
default=None,
is_flag=True,
help="Save section videos in addition to movie file.",
),
option(
"-t",
"--transparent",
is_flag=True,
help="Render scenes with alpha channel.",
),
option(
"--use_projection_fill_shaders",
is_flag=True,
help="Use shaders for OpenGLVMobject fill which are compatible with transformation matrices.",
default=None,
),
option(
"--use_projection_stroke_shaders",
is_flag=True,
help="Use shaders for OpenGLVMobject stroke which are compatible with transformation matrices.",
default=None,
),
)
|
manim_ManimCommunity/manim/cli/render/__init__.py
| |
manim_ManimCommunity/manim/cli/render/commands.py
|
"""Manim's default subcommand, render.
Manim's render subcommand is accessed in the command-line interface via
``manim``, but can be more explicitly accessed with ``manim render``. Here you
can specify options, and arguments for the render command.
"""
from __future__ import annotations
import http.client
import json
import sys
import urllib.error
import urllib.request
from pathlib import Path
from typing import cast
import cloup
from ... import __version__, config, console, error_console, logger
from ..._config import tempconfig
from ...constants import EPILOG, RendererType
from ...utils.module_ops import scene_classes_from_file
from .ease_of_access_options import ease_of_access_options
from .global_options import global_options
from .output_options import output_options
from .render_options import render_options
__all__ = ["render"]
@cloup.command(
context_settings=None,
no_args_is_help=True,
epilog=EPILOG,
)
@cloup.argument("file", type=Path, required=True)
@cloup.argument("scene_names", required=False, nargs=-1)
@global_options
@output_options
@render_options # type: ignore
@ease_of_access_options
def render(
**args,
):
"""Render SCENE(S) from the input FILE.
FILE is the file path of the script or a config file.
SCENES is an optional list of scenes in the file.
"""
if args["save_as_gif"]:
logger.warning("--save_as_gif is deprecated, please use --format=gif instead!")
args["format"] = "gif"
if args["save_pngs"]:
logger.warning("--save_pngs is deprecated, please use --format=png instead!")
args["format"] = "png"
if args["show_in_file_browser"]:
logger.warning(
"The short form of show_in_file_browser is deprecated and will be moved to support --format.",
)
class ClickArgs:
def __init__(self, args):
for name in args:
setattr(self, name, args[name])
def _get_kwargs(self):
return list(self.__dict__.items())
def __eq__(self, other):
if not isinstance(other, ClickArgs):
return NotImplemented
return vars(self) == vars(other)
def __contains__(self, key):
return key in self.__dict__
def __repr__(self):
return str(self.__dict__)
click_args = ClickArgs(args)
if args["jupyter"]:
return click_args
config.digest_args(click_args)
file = Path(config.input_file)
if config.renderer == RendererType.OPENGL:
from manim.renderer.opengl_renderer import OpenGLRenderer
try:
renderer = OpenGLRenderer()
keep_running = True
while keep_running:
for SceneClass in scene_classes_from_file(file):
with tempconfig({}):
scene = SceneClass(renderer)
rerun = scene.render()
if rerun or config["write_all"]:
renderer.num_plays = 0
continue
else:
keep_running = False
break
if config["write_all"]:
keep_running = False
except Exception:
error_console.print_exception()
sys.exit(1)
else:
for SceneClass in scene_classes_from_file(file):
try:
with tempconfig({}):
scene = SceneClass()
scene.render()
except Exception:
error_console.print_exception()
sys.exit(1)
if config.notify_outdated_version:
manim_info_url = "https://pypi.org/pypi/manim/json"
warn_prompt = "Cannot check if latest release of manim is installed"
try:
with urllib.request.urlopen(
urllib.request.Request(manim_info_url),
timeout=10,
) as response:
response = cast(http.client.HTTPResponse, response)
json_data = json.loads(response.read())
except urllib.error.HTTPError:
logger.debug("HTTP Error: %s", warn_prompt)
except urllib.error.URLError:
logger.debug("URL Error: %s", warn_prompt)
except json.JSONDecodeError:
logger.debug(
"Error while decoding JSON from %r: %s", manim_info_url, warn_prompt
)
except Exception:
logger.debug("Something went wrong: %s", warn_prompt)
stable = json_data["info"]["version"]
if stable != __version__:
console.print(
f"You are using manim version [red]v{__version__}[/red], but version [green]v{stable}[/green] is available.",
)
console.print(
"You should consider upgrading via [yellow]pip install -U manim[/yellow]",
)
return args
|
manim_ManimCommunity/manim/cli/render/ease_of_access_options.py
|
from __future__ import annotations
from cloup import Choice, option, option_group
__all__ = ["ease_of_access_options"]
ease_of_access_options = option_group(
"Ease of access options",
option(
"--progress_bar",
default=None,
show_default=False,
type=Choice(
["display", "leave", "none"],
case_sensitive=False,
),
help="Display progress bars and/or keep them displayed.",
),
option(
"-p",
"--preview",
is_flag=True,
help="Preview the Scene's animation. OpenGL does a live preview in a "
"popup window. Cairo opens the rendered video file in the system "
"default media player.",
default=None,
),
option(
"-f",
"--show_in_file_browser",
is_flag=True,
help="Show the output file in the file browser.",
default=None,
),
option(
"--jupyter",
is_flag=True,
help="Using jupyter notebook magic.",
default=None,
),
)
|
manim_ManimCommunity/manim/cli/render/global_options.py
|
from __future__ import annotations
import re
from cloup import Choice, option, option_group
from ... import logger
__all__ = ["global_options"]
def validate_gui_location(ctx, param, value):
if value:
try:
x_offset, y_offset = map(int, re.split(r"[;,\-]", value))
return (x_offset, y_offset)
except Exception:
logger.error("GUI location option is invalid.")
exit()
global_options = option_group(
"Global options",
option(
"-c",
"--config_file",
help="Specify the configuration file to use for render settings.",
default=None,
),
option(
"--custom_folders",
is_flag=True,
default=None,
help="Use the folders defined in the [custom_folders] section of the "
"config file to define the output folder structure.",
),
option(
"--disable_caching",
is_flag=True,
default=None,
help="Disable the use of the cache (still generates cache files).",
),
option(
"--flush_cache",
is_flag=True,
help="Remove cached partial movie files.",
default=None,
),
option("--tex_template", help="Specify a custom TeX template file.", default=None),
option(
"-v",
"--verbosity",
type=Choice(
["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
case_sensitive=False,
),
help="Verbosity of CLI output. Changes ffmpeg log level unless 5+.",
default=None,
),
option(
"--notify_outdated_version/--silent",
is_flag=True,
default=None,
help="Display warnings for outdated installation.",
),
option(
"--enable_gui",
is_flag=True,
help="Enable GUI interaction.",
default=None,
),
option(
"--gui_location",
default=None,
callback=validate_gui_location,
help="Starting location for the GUI.",
),
option(
"--fullscreen",
is_flag=True,
help="Expand the window to its maximum possible size.",
default=None,
),
option(
"--enable_wireframe",
is_flag=True,
help="Enable wireframe debugging mode in opengl.",
default=None,
),
option(
"--force_window",
is_flag=True,
help="Force window to open when using the opengl renderer, intended for debugging as it may impact performance",
default=False,
),
option(
"--dry_run",
is_flag=True,
help="Renders animations without outputting image or video files and disables the window",
default=False,
),
option(
"--no_latex_cleanup",
is_flag=True,
help="Prevents deletion of .aux, .dvi, and .log files produced by Tex and MathTex.",
default=False,
),
)
|
manim_ManimCommunity/manim/cli/render/output_options.py
|
from __future__ import annotations
from cloup import IntRange, Path, option, option_group
__all__ = ["output_options"]
output_options = option_group(
"Output options",
option(
"-o",
"--output_file",
type=str,
default=None,
help="Specify the filename(s) of the rendered scene(s).",
),
option(
"-0",
"--zero_pad",
type=IntRange(0, 9),
default=None,
help="Zero padding for PNG file names.",
),
option(
"--write_to_movie",
is_flag=True,
default=None,
help="Write the video rendered with opengl to a file.",
),
option(
"--media_dir",
type=Path(),
default=None,
help="Path to store rendered videos and latex.",
),
option(
"--log_dir",
type=Path(),
help="Path to store render logs.",
default=None,
),
option(
"--log_to_file",
is_flag=True,
default=None,
help="Log terminal output to file.",
),
)
|
manim_ManimCommunity/manim/cli/cfg/__init__.py
| |
manim_ManimCommunity/manim/cli/cfg/group.py
|
"""Manim's cfg subcommand.
Manim's cfg subcommand is accessed in the command-line interface via ``manim
cfg``. Here you can specify options, subcommands, and subgroups for the cfg
group.
"""
from __future__ import annotations
from ast import literal_eval
from pathlib import Path
import cloup
from rich.errors import StyleSyntaxError
from rich.style import Style
from ... import cli_ctx_settings, console
from ..._config.utils import config_file_paths, make_config_parser
from ...constants import EPILOG
from ...utils.file_ops import guarantee_existence, open_file
RICH_COLOUR_INSTRUCTIONS: str = """
[red]The default colour is used by the input statement.
If left empty, the default colour will be used.[/red]
[magenta] For a full list of styles, visit[/magenta] [green]https://rich.readthedocs.io/en/latest/style.html[/green]
"""
RICH_NON_STYLE_ENTRIES: str = ["log.width", "log.height", "log.timestamps"]
__all__ = [
"value_from_string",
"value_from_string",
"is_valid_style",
"replace_keys",
"cfg",
"write",
"show",
"export",
]
def value_from_string(value: str) -> str | int | bool:
"""Extracts the literal of proper datatype from a string.
Parameters
----------
value
The value to check get the literal from.
Returns
-------
Union[:class:`str`, :class:`int`, :class:`bool`]
Returns the literal of appropriate datatype.
"""
try:
value = literal_eval(value)
except (SyntaxError, ValueError):
pass
return value
def _is_expected_datatype(value: str, expected: str, style: bool = False) -> bool:
"""Checks whether `value` is the same datatype as `expected`,
and checks if it is a valid `style` if `style` is true.
Parameters
----------
value
The string of the value to check (obtained from reading the user input).
expected
The string of the literal datatype must be matched by `value`. Obtained from
reading the cfg file.
style
Whether or not to confirm if `value` is a style, by default False
Returns
-------
:class:`bool`
Whether or not `value` matches the datatype of `expected`.
"""
value = value_from_string(value)
expected = type(value_from_string(expected))
return isinstance(value, expected) and (is_valid_style(value) if style else True)
def is_valid_style(style: str) -> bool:
"""Checks whether the entered color is a valid color according to rich
Parameters
----------
style
The style to check whether it is valid.
Returns
-------
Boolean
Returns whether it is valid style or not according to rich.
"""
try:
Style.parse(style)
return True
except StyleSyntaxError:
return False
def replace_keys(default: dict) -> dict:
"""Replaces _ to . and vice versa in a dictionary for rich
Parameters
----------
default
The dictionary to check and replace
Returns
-------
:class:`dict`
The dictionary which is modified by replacing _ with . and vice versa
"""
for key in default:
if "_" in key:
temp = default[key]
del default[key]
key = key.replace("_", ".")
default[key] = temp
else:
temp = default[key]
del default[key]
key = key.replace(".", "_")
default[key] = temp
return default
@cloup.group(
context_settings=cli_ctx_settings,
invoke_without_command=True,
no_args_is_help=True,
epilog=EPILOG,
help="Manages Manim configuration files.",
)
@cloup.pass_context
def cfg(ctx):
"""Responsible for the cfg subcommand."""
pass
@cfg.command(context_settings=cli_ctx_settings, no_args_is_help=True)
@cloup.option(
"-l",
"--level",
type=cloup.Choice(["user", "cwd"], case_sensitive=False),
default="cwd",
help="Specify if this config is for user or the working directory.",
)
@cloup.option("-o", "--open", "openfile", is_flag=True)
def write(level: str = None, openfile: bool = False) -> None:
config_paths = config_file_paths()
console.print(
"[yellow bold]Manim Configuration File Writer[/yellow bold]",
justify="center",
)
USER_CONFIG_MSG = f"""A configuration file at [yellow]{config_paths[1]}[/yellow] has been created with your required changes.
This will be used when running the manim command. If you want to override this config,
you will have to create a manim.cfg in the local directory, where you want those changes to be overridden."""
CWD_CONFIG_MSG = f"""A configuration file at [yellow]{config_paths[2]}[/yellow] has been created.
To save your config please save that file and place it in your current working directory, from where you run the manim command."""
parser = make_config_parser()
if not openfile:
action = "save this as"
for category in parser:
console.print(f"{category}", style="bold green underline")
default = parser[category]
if category == "logger":
console.print(RICH_COLOUR_INSTRUCTIONS)
default = replace_keys(default)
for key in default:
# All the cfg entries for logger need to be validated as styles,
# as long as they aren't setting the log width or height etc
if category == "logger" and key not in RICH_NON_STYLE_ENTRIES:
desc = "style"
style = default[key]
else:
desc = "value"
style = None
console.print(f"Enter the {desc} for {key} ", style=style, end="")
if category != "logger" or key in RICH_NON_STYLE_ENTRIES:
defaultval = (
repr(default[key])
if isinstance(value_from_string(default[key]), str)
else default[key]
)
console.print(f"(defaults to {defaultval}) :", end="")
try:
temp = input()
except EOFError:
raise Exception(
"""Not enough values in input.
You may have added a new entry to default.cfg, in which case you will have to
modify write_cfg_subcmd_input to account for it.""",
)
if temp:
while temp and not _is_expected_datatype(
temp,
default[key],
bool(style),
):
console.print(
f"[red bold]Invalid {desc}. Try again.[/red bold]",
)
console.print(
f"Enter the {desc} for {key}:",
style=style,
end="",
)
temp = input()
default[key] = temp.replace("%", "%%")
default = replace_keys(default) if category == "logger" else default
parser[category] = {
i: v.replace("%", "%%") for i, v in dict(default).items()
}
else:
action = "open"
if level is None:
console.print(
f"Do you want to {action} the default config for this User?(y/n)[[n]]",
style="dim purple",
end="",
)
action_to_userpath = input()
else:
action_to_userpath = ""
if action_to_userpath.lower() == "y" or level == "user":
cfg_file_path = config_paths[1]
guarantee_existence(config_paths[1].parents[0])
console.print(USER_CONFIG_MSG)
else:
cfg_file_path = config_paths[2]
guarantee_existence(config_paths[2].parents[0])
console.print(CWD_CONFIG_MSG)
with cfg_file_path.open("w") as fp:
parser.write(fp)
if openfile:
open_file(cfg_file_path)
@cfg.command(context_settings=cli_ctx_settings)
def show():
parser = make_config_parser()
rich_non_style_entries = [a.replace(".", "_") for a in RICH_NON_STYLE_ENTRIES]
for category in parser:
console.print(f"{category}", style="bold green underline")
for entry in parser[category]:
if category == "logger" and entry not in rich_non_style_entries:
console.print(f"{entry} :", end="")
console.print(
f" {parser[category][entry]}",
style=parser[category][entry],
)
else:
console.print(f"{entry} : {parser[category][entry]}")
console.print("\n")
@cfg.command(context_settings=cli_ctx_settings)
@cloup.option("-d", "--directory", default=Path.cwd())
@cloup.pass_context
def export(ctx, directory):
directory_path = Path(directory)
if directory_path.absolute == Path.cwd().absolute:
console.print(
"""You are reading the config from the same directory you are exporting to.
This means that the exported config will overwrite the config for this directory.
Are you sure you want to continue? (y/n)""",
style="red bold",
end="",
)
proceed = input().lower() == "y"
else:
proceed = True
if proceed:
if not directory_path.is_dir():
console.print(f"Creating folder: {directory}.", style="red bold")
directory_path.mkdir(parents=True)
ctx.invoke(write)
from_path = Path.cwd() / "manim.cfg"
to_path = directory_path / "manim.cfg"
console.print(f"Exported final Config at {from_path} to {to_path}.")
else:
console.print("Aborted...", style="red bold")
|
manim_ManimCommunity/manim/gui/__init__.py
| |
manim_ManimCommunity/manim/gui/gui.py
|
from __future__ import annotations
from pathlib import Path
try:
import dearpygui.dearpygui as dpg
dearpygui_imported = True
except ImportError:
dearpygui_imported = False
from .. import __version__, config
from ..utils.module_ops import scene_classes_from_file
__all__ = ["configure_pygui"]
if dearpygui_imported:
dpg.create_context()
window = dpg.generate_uuid()
def configure_pygui(renderer, widgets, update=True):
if not dearpygui_imported:
raise RuntimeError("Attempted to use DearPyGUI when it isn't imported.")
if update:
dpg.delete_item(window)
else:
dpg.create_viewport()
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.set_viewport_title(title=f"Manim Community v{__version__}")
dpg.set_viewport_width(1015)
dpg.set_viewport_height(540)
def rerun_callback(sender, data):
renderer.scene.queue.put(("rerun_gui", [], {}))
def continue_callback(sender, data):
renderer.scene.queue.put(("exit_gui", [], {}))
def scene_selection_callback(sender, data):
config["scene_names"] = (dpg.get_value(sender),)
renderer.scene.queue.put(("rerun_gui", [], {}))
scene_classes = scene_classes_from_file(Path(config["input_file"]), full_list=True)
scene_names = [scene_class.__name__ for scene_class in scene_classes]
with dpg.window(
id=window,
label="Manim GUI",
pos=[config["gui_location"][0], config["gui_location"][1]],
width=1000,
height=500,
):
dpg.set_global_font_scale(2)
dpg.add_button(label="Rerun", callback=rerun_callback)
dpg.add_button(label="Continue", callback=continue_callback)
dpg.add_combo(
label="Selected scene",
items=scene_names,
callback=scene_selection_callback,
default_value=config["scene_names"][0],
)
dpg.add_separator()
if len(widgets) != 0:
with dpg.collapsing_header(
label=f"{config['scene_names'][0]} widgets",
default_open=True,
):
for widget_config in widgets:
widget_config_copy = widget_config.copy()
name = widget_config_copy["name"]
widget = widget_config_copy["widget"]
if widget != "separator":
del widget_config_copy["name"]
del widget_config_copy["widget"]
getattr(dpg, f"add_{widget}")(label=name, **widget_config_copy)
else:
dpg.add_separator()
if not update:
dpg.start_dearpygui()
|
manim_ManimCommunity/manim/_config/__init__.py
|
"""Set the global config and logger."""
from __future__ import annotations
import logging
from contextlib import contextmanager
from typing import Any, Generator
from .cli_colors import parse_cli_ctx
from .logger_utils import make_logger
from .utils import ManimConfig, ManimFrame, make_config_parser
__all__ = [
"logger",
"console",
"error_console",
"config",
"frame",
"tempconfig",
"cli_ctx_settings",
]
parser = make_config_parser()
# The logger can be accessed from anywhere as manim.logger, or as
# logging.getLogger("manim"). The console must be accessed as manim.console.
# Throughout the codebase, use manim.console.print() instead of print().
# Use error_console to print errors so that it outputs to stderr.
logger, console, error_console = make_logger(
parser["logger"],
parser["CLI"]["verbosity"],
)
cli_ctx_settings = parse_cli_ctx(parser["CLI_CTX"])
# TODO: temporary to have a clean terminal output when working with PIL or matplotlib
logging.getLogger("PIL").setLevel(logging.INFO)
logging.getLogger("matplotlib").setLevel(logging.INFO)
config = ManimConfig().digest_parser(parser)
# TODO: to be used in the future - see PR #620
# https://github.com/ManimCommunity/manim/pull/620
frame = ManimFrame(config)
# This has to go here because it needs access to this module's config
@contextmanager
def tempconfig(temp: ManimConfig | dict[str, Any]) -> Generator[None, None, None]:
"""Context manager that temporarily modifies the global ``config`` object.
Inside the ``with`` statement, the modified config will be used. After
context manager exits, the config will be restored to its original state.
Parameters
----------
temp
Object whose keys will be used to temporarily update the global
``config``.
Examples
--------
Use ``with tempconfig({...})`` to temporarily change the default values of
certain config options.
.. code-block:: pycon
>>> config["frame_height"]
8.0
>>> with tempconfig({"frame_height": 100.0}):
... print(config["frame_height"])
...
100.0
>>> config["frame_height"]
8.0
"""
global config
original = config.copy()
temp = {k: v for k, v in temp.items() if k in original}
# In order to change the config that every module has access to, use
# update(), DO NOT use assignment. Assigning config = some_dict will just
# make the local variable named config point to a new dictionary, it will
# NOT change the dictionary that every module has a reference to.
config.update(temp)
try:
yield
finally:
config.update(original) # update, not assignment!
|
manim_ManimCommunity/manim/_config/logger_utils.py
|
"""Utilities to create and set the logger.
Manim's logger can be accessed as ``manim.logger``, or as
``logging.getLogger("manim")``, once the library has been imported. Manim also
exports a second object, ``console``, which should be used to print on screen
messages that need not be logged.
Both ``logger`` and ``console`` use the ``rich`` library to produce rich text
format.
"""
from __future__ import annotations
import configparser
import copy
import json
import logging
from typing import TYPE_CHECKING
from rich import color, errors
from rich import print as printf
from rich.console import Console
from rich.logging import RichHandler
from rich.theme import Theme
if TYPE_CHECKING:
from pathlib import Path
__all__ = ["make_logger", "parse_theme", "set_file_logger", "JSONFormatter"]
HIGHLIGHTED_KEYWORDS = [ # these keywords are highlighted specially
"Played",
"animations",
"scene",
"Reading",
"Writing",
"script",
"arguments",
"Invalid",
"Aborting",
"module",
"File",
"Rendering",
"Rendered",
]
WRONG_COLOR_CONFIG_MSG = """
[logging.level.error]Your colour configuration couldn't be parsed.
Loading the default color configuration.[/logging.level.error]
"""
def make_logger(
parser: configparser.SectionProxy,
verbosity: str,
) -> tuple[logging.Logger, Console, Console]:
"""Make the manim logger and console.
Parameters
----------
parser
A parser containing any .cfg files in use.
verbosity
The verbosity level of the logger.
Returns
-------
:class:`logging.Logger`, :class:`rich.Console`, :class:`rich.Console`
The manim logger and consoles. The first console outputs
to stdout, the second to stderr. All use the theme returned by
:func:`parse_theme`.
See Also
--------
:func:`~._config.utils.make_config_parser`, :func:`parse_theme`
Notes
-----
The ``parser`` is assumed to contain only the options related to
configuring the logger at the top level.
"""
# Throughout the codebase, use console.print() instead of print()
theme = parse_theme(parser)
console = Console(theme=theme)
error_console = Console(theme=theme, stderr=True)
# set the rich handler
rich_handler = RichHandler(
console=console,
show_time=parser.getboolean("log_timestamps"),
keywords=HIGHLIGHTED_KEYWORDS,
)
# finally, the logger
logger = logging.getLogger("manim")
logger.addHandler(rich_handler)
logger.setLevel(verbosity)
return logger, console, error_console
def parse_theme(parser: configparser.SectionProxy) -> Theme:
"""Configure the rich style of logger and console output.
Parameters
----------
parser
A parser containing any .cfg files in use.
Returns
-------
:class:`rich.Theme`
The rich theme to be used by the manim logger.
See Also
--------
:func:`make_logger`.
"""
theme = {key.replace("_", "."): parser[key] for key in parser}
theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"])
theme["log.height"] = (
None if theme["log.height"] == "-1" else int(theme["log.height"])
)
theme["log.timestamps"] = False
try:
custom_theme = Theme(
{
k: v
for k, v in theme.items()
if k not in ["log.width", "log.height", "log.timestamps"]
},
)
except (color.ColorParseError, errors.StyleSyntaxError):
printf(WRONG_COLOR_CONFIG_MSG)
custom_theme = None
return custom_theme
def set_file_logger(scene_name: str, module_name: str, log_dir: Path) -> None:
"""Add a file handler to manim logger.
The path to the file is built using ``config.log_dir``.
Parameters
----------
scene_name
The name of the scene, used in the name of the log file.
module_name
The name of the module, used in the name of the log file.
log_dir
Path to the folder where log files are stored.
"""
# Note: The log file name will be
# <name_of_animation_file>_<name_of_scene>.log, gotten from config. So it
# can differ from the real name of the scene. <name_of_scene> would only
# appear if scene name was provided when manim was called.
log_file_name = f"{module_name}_{scene_name}.log"
log_file_path = log_dir / log_file_name
file_handler = logging.FileHandler(log_file_path, mode="w")
file_handler.setFormatter(JSONFormatter())
logger = logging.getLogger("manim")
logger.addHandler(file_handler)
logger.info("Log file will be saved in %(logpath)s", {"logpath": log_file_path})
class JSONFormatter(logging.Formatter):
"""A formatter that outputs logs in a custom JSON format.
This class is used internally for testing purposes.
"""
def format(self, record: logging.LogRecord) -> str:
"""Format the record in a custom JSON format."""
record_c = copy.deepcopy(record)
if record_c.args:
for arg in record_c.args:
record_c.args[arg] = "<>"
return json.dumps(
{
"levelname": record_c.levelname,
"module": record_c.module,
"message": super().format(record_c),
},
)
|
manim_ManimCommunity/manim/_config/cli_colors.py
|
from __future__ import annotations
import configparser
from cloup import Context, HelpFormatter, HelpTheme, Style
__all__ = ["parse_cli_ctx"]
def parse_cli_ctx(parser: configparser.SectionProxy) -> Context:
formatter_settings: dict[str, str | int] = {
"indent_increment": int(parser["indent_increment"]),
"width": int(parser["width"]),
"col1_max_width": int(parser["col1_max_width"]),
"col2_min_width": int(parser["col2_min_width"]),
"col_spacing": int(parser["col_spacing"]),
"row_sep": parser["row_sep"] if parser["row_sep"] else None,
}
theme_settings = {}
theme_keys = {
"command_help",
"invoked_command",
"heading",
"constraint",
"section_help",
"col1",
"col2",
"epilog",
}
for k, v in parser.items():
if k in theme_keys and v:
theme_settings.update({k: Style(v)})
formatter = {}
theme = parser["theme"] if parser["theme"] else None
if theme is None:
formatter = HelpFormatter.settings(
theme=HelpTheme(**theme_settings), **formatter_settings # type: ignore[arg-type]
)
elif theme.lower() == "dark":
formatter = HelpFormatter.settings(
theme=HelpTheme.dark().with_(**theme_settings), **formatter_settings # type: ignore[arg-type]
)
elif theme.lower() == "light":
formatter = HelpFormatter.settings(
theme=HelpTheme.light().with_(**theme_settings), **formatter_settings # type: ignore[arg-type]
)
return Context.settings(
align_option_groups=parser["align_option_groups"].lower() == "true",
align_sections=parser["align_sections"].lower() == "true",
show_constraints=True,
formatter_settings=formatter,
)
|
manim_ManimCommunity/manim/_config/utils.py
|
"""Utilities to create and set the config.
The main class exported by this module is :class:`ManimConfig`. This class
contains all configuration options, including frame geometry (e.g. frame
height/width, frame rate), output (e.g. directories, logging), styling
(e.g. background color, transparency), and general behavior (e.g. writing a
movie vs writing a single frame).
See :doc:`/guides/configuration` for an introduction to Manim's configuration system.
"""
from __future__ import annotations
import argparse
import configparser
import copy
import errno
import logging
import os
import re
import sys
from collections.abc import Mapping, MutableMapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Iterable, Iterator, NoReturn
import numpy as np
from manim import constants
from manim.constants import RendererType
from manim.utils.color import ManimColor
from manim.utils.tex import TexTemplate
if TYPE_CHECKING:
from enum import EnumMeta
from typing_extensions import Self
from manim.typing import StrPath, Vector3D
__all__ = ["config_file_paths", "make_config_parser", "ManimConfig", "ManimFrame"]
def config_file_paths() -> list[Path]:
"""The paths where ``.cfg`` files will be searched for.
When manim is first imported, it processes any ``.cfg`` files it finds. This
function returns the locations in which these files are searched for. In
ascending order of precedence, these are: the library-wide config file, the
user-wide config file, and the folder-wide config file.
The library-wide config file determines manim's default behavior. The
user-wide config file is stored in the user's home folder, and determines
the behavior of manim whenever the user invokes it from anywhere in the
system. The folder-wide config file only affects scenes that are in the
same folder. The latter two files are optional.
These files, if they exist, are meant to loaded into a single
:class:`configparser.ConfigParser` object, and then processed by
:class:`ManimConfig`.
Returns
-------
List[:class:`Path`]
List of paths which may contain ``.cfg`` files, in ascending order of
precedence.
See Also
--------
:func:`make_config_parser`, :meth:`ManimConfig.digest_file`,
:meth:`ManimConfig.digest_parser`
Notes
-----
The location of the user-wide config file is OS-specific.
"""
library_wide = Path.resolve(Path(__file__).parent / "default.cfg")
if sys.platform.startswith("win32"):
user_wide = Path.home() / "AppData" / "Roaming" / "Manim" / "manim.cfg"
else:
user_wide = Path.home() / ".config" / "manim" / "manim.cfg"
folder_wide = Path("manim.cfg")
return [library_wide, user_wide, folder_wide]
def make_config_parser(
custom_file: StrPath | None = None,
) -> configparser.ConfigParser:
"""Make a :class:`ConfigParser` object and load any ``.cfg`` files.
The user-wide file, if it exists, overrides the library-wide file. The
folder-wide file, if it exists, overrides the other two.
The folder-wide file can be ignored by passing ``custom_file``. However,
the user-wide and library-wide config files cannot be ignored.
Parameters
----------
custom_file
Path to a custom config file. If used, the folder-wide file in the
relevant directory will be ignored, if it exists. If None, the
folder-wide file will be used, if it exists.
Returns
-------
:class:`ConfigParser`
A parser containing the config options found in the .cfg files that
were found. It is guaranteed to contain at least the config options
found in the library-wide file.
See Also
--------
:func:`config_file_paths`
"""
library_wide, user_wide, folder_wide = config_file_paths()
# From the documentation: "An application which requires initial values to
# be loaded from a file should load the required file or files using
# read_file() before calling read() for any optional files."
# https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read
parser = configparser.ConfigParser()
with library_wide.open() as file:
parser.read_file(file) # necessary file
other_files = [user_wide, Path(custom_file) if custom_file else folder_wide]
parser.read(other_files) # optional files
return parser
def _determine_quality(qual: str) -> str:
for quality, values in constants.QUALITIES.items():
if values["flag"] is not None and values["flag"] == qual:
return quality
return qual
class ManimConfig(MutableMapping):
"""Dict-like class storing all config options.
The global ``config`` object is an instance of this class, and acts as a
single source of truth for all of the library's customizable behavior.
The global ``config`` object is capable of digesting different types of
sources and converting them into a uniform interface. These sources are
(in ascending order of precedence): configuration files, command line
arguments, and programmatic changes. Regardless of how the user chooses to
set a config option, she can access its current value using
:class:`ManimConfig`'s attributes and properties.
Notes
-----
Each config option is implemented as a property of this class.
Each config option can be set via a config file, using the full name of the
property. If a config option has an associated CLI flag, then the flag is
equal to the full name of the property. Those that admit an alternative
flag or no flag at all are documented in the individual property's
docstring.
Examples
--------
We use a copy of the global configuration object in the following
examples for the sake of demonstration; you can skip these lines
and just import ``config`` directly if you actually want to modify
the configuration:
.. code-block:: pycon
>>> from manim import config as global_config
>>> config = global_config.copy()
Each config option allows for dict syntax and attribute syntax. For
example, the following two lines are equivalent,
.. code-block:: pycon
>>> from manim import WHITE
>>> config.background_color = WHITE
>>> config["background_color"] = WHITE
The former is preferred; the latter is provided mostly for backwards
compatibility.
The config options are designed to keep internal consistency. For example,
setting ``frame_y_radius`` will affect ``frame_height``:
.. code-block:: pycon
>>> config.frame_height
8.0
>>> config.frame_y_radius = 5.0
>>> config.frame_height
10.0
There are many ways of interacting with config options. Take for example
the config option ``background_color``. There are three ways to change it:
via a config file, via CLI flags, or programmatically.
To set the background color via a config file, save the following
``manim.cfg`` file with the following contents.
.. code-block::
[CLI]
background_color = WHITE
In order to have this ``.cfg`` file apply to a manim scene, it needs to be
placed in the same directory as the script,
.. code-block:: bash
project/
├─scene.py
└─manim.cfg
Now, when the user executes
.. code-block:: bash
manim scene.py
the background of the scene will be set to ``WHITE``. This applies regardless
of where the manim command is invoked from.
Command line arguments override ``.cfg`` files. In the previous example,
executing
.. code-block:: bash
manim scene.py -c BLUE
will set the background color to BLUE, regardless of the contents of
``manim.cfg``.
Finally, any programmatic changes made within the scene script itself will
override the command line arguments. For example, if ``scene.py`` contains
the following
.. code-block:: python
from manim import *
config.background_color = RED
class MyScene(Scene):
...
the background color will be set to RED, regardless of the contents of
``manim.cfg`` or the CLI arguments used when invoking manim.
"""
_OPTS = {
"assets_dir",
"background_color",
"background_opacity",
"custom_folders",
"disable_caching",
"disable_caching_warning",
"dry_run",
"enable_wireframe",
"ffmpeg_loglevel",
"ffmpeg_executable",
"format",
"flush_cache",
"frame_height",
"frame_rate",
"frame_width",
"frame_x_radius",
"frame_y_radius",
"from_animation_number",
"images_dir",
"input_file",
"media_embed",
"media_width",
"log_dir",
"log_to_file",
"max_files_cached",
"media_dir",
"movie_file_extension",
"notify_outdated_version",
"output_file",
"partial_movie_dir",
"pixel_height",
"pixel_width",
"plugins",
"preview",
"progress_bar",
"quality",
"save_as_gif",
"save_sections",
"save_last_frame",
"save_pngs",
"scene_names",
"show_in_file_browser",
"tex_dir",
"tex_template",
"tex_template_file",
"text_dir",
"upto_animation_number",
"renderer",
"enable_gui",
"gui_location",
"use_projection_fill_shaders",
"use_projection_stroke_shaders",
"verbosity",
"video_dir",
"sections_dir",
"fullscreen",
"window_position",
"window_size",
"window_monitor",
"write_all",
"write_to_movie",
"zero_pad",
"force_window",
"no_latex_cleanup",
}
def __init__(self) -> None:
self._d: dict[str, Any | None] = {k: None for k in self._OPTS}
# behave like a dict
def __iter__(self) -> Iterator[str]:
return iter(self._d)
def __len__(self) -> int:
return len(self._d)
def __contains__(self, key: object) -> bool:
try:
self.__getitem__(key)
return True
except AttributeError:
return False
def __getitem__(self, key: str) -> Any:
return getattr(self, key)
def __setitem__(self, key: str, val: Any) -> None:
getattr(ManimConfig, key).fset(self, val) # fset is the property's setter
def update(self, obj: ManimConfig | dict[str, Any]) -> None: # type: ignore[override]
"""Digest the options found in another :class:`ManimConfig` or in a dict.
Similar to :meth:`dict.update`, replaces the values of this object with
those of ``obj``.
Parameters
----------
obj
The object to copy values from.
Returns
-------
None
Raises
-----
:class:`AttributeError`
If ``obj`` is a dict but contains keys that do not belong to any
config options.
See Also
--------
:meth:`~ManimConfig.digest_file`, :meth:`~ManimConfig.digest_args`,
:meth:`~ManimConfig.digest_parser`
"""
if isinstance(obj, ManimConfig):
self._d.update(obj._d)
if obj.tex_template:
self.tex_template = obj.tex_template
elif isinstance(obj, dict):
# First update the underlying _d, then update other properties
_dict = {k: v for k, v in obj.items() if k in self._d}
for k, v in _dict.items():
self[k] = v
_dict = {k: v for k, v in obj.items() if k not in self._d}
for k, v in _dict.items():
self[k] = v
# don't allow to delete anything
def __delitem__(self, key: str) -> NoReturn:
raise AttributeError("'ManimConfig' object does not support item deletion")
def __delattr__(self, key: str) -> NoReturn:
raise AttributeError("'ManimConfig' object does not support item deletion")
# copy functions
def copy(self) -> Self:
"""Deepcopy the contents of this ManimConfig.
Returns
-------
:class:`ManimConfig`
A copy of this object containing no shared references.
See Also
--------
:func:`tempconfig`
Notes
-----
This is the main mechanism behind :func:`tempconfig`.
"""
return copy.deepcopy(self)
def __copy__(self) -> Self:
"""See ManimConfig.copy()."""
return copy.deepcopy(self)
def __deepcopy__(self, memo: dict[str, Any]) -> Self:
"""See ManimConfig.copy()."""
c = type(self)()
# Deepcopying the underlying dict is enough because all properties
# either read directly from it or compute their value on the fly from
# values read directly from it.
c._d = copy.deepcopy(self._d, memo)
return c
# helper type-checking methods
def _set_from_list(self, key: str, val: Any, values: list[Any]) -> None:
"""Set ``key`` to ``val`` if ``val`` is contained in ``values``."""
if val in values:
self._d[key] = val
else:
raise ValueError(f"attempted to set {key} to {val}; must be in {values}")
def _set_from_enum(self, key: str, enum_value: Any, enum_class: EnumMeta) -> None:
"""Set ``key`` to the enum object with value ``enum_value`` in the given
``enum_class``.
Tests::
>>> from enum import Enum
>>> class Fruit(Enum):
... APPLE = 1
... BANANA = 2
... CANTALOUPE = 3
>>> test_config = ManimConfig()
>>> test_config._set_from_enum("fruit", 1, Fruit)
>>> test_config._d['fruit']
<Fruit.APPLE: 1>
>>> test_config._set_from_enum("fruit", Fruit.BANANA, Fruit)
>>> test_config._d['fruit']
<Fruit.BANANA: 2>
>>> test_config._set_from_enum("fruit", 42, Fruit)
Traceback (most recent call last):
...
ValueError: 42 is not a valid Fruit
"""
self._d[key] = enum_class(enum_value)
def _set_boolean(self, key: str, val: Any) -> None:
"""Set ``key`` to ``val`` if ``val`` is Boolean."""
if val in [True, False]:
self._d[key] = val
else:
raise ValueError(f"{key} must be boolean")
def _set_tuple(self, key: str, val: tuple[Any]) -> None:
if isinstance(val, tuple):
self._d[key] = val
else:
raise ValueError(f"{key} must be tuple")
def _set_str(self, key: str, val: Any) -> None:
"""Set ``key`` to ``val`` if ``val`` is a string."""
if isinstance(val, str):
self._d[key] = val
elif not val:
self._d[key] = ""
else:
raise ValueError(f"{key} must be str or falsy value")
def _set_between(self, key: str, val: float, lo: float, hi: float) -> None:
"""Set ``key`` to ``val`` if lo <= val <= hi."""
if lo <= val <= hi:
self._d[key] = val
else:
raise ValueError(f"{key} must be {lo} <= {key} <= {hi}")
def _set_int_between(self, key: str, val: int, lo: int, hi: int) -> None:
"""Set ``key`` to ``val`` if lo <= val <= hi."""
if lo <= val <= hi:
self._d[key] = val
else:
raise ValueError(
f"{key} must be an integer such that {lo} <= {key} <= {hi}",
)
def _set_pos_number(self, key: str, val: int, allow_inf: bool) -> None:
"""Set ``key`` to ``val`` if ``val`` is a positive integer."""
if isinstance(val, int) and val > -1:
self._d[key] = val
elif allow_inf and val in [-1, float("inf")]:
self._d[key] = float("inf")
else:
raise ValueError(
f"{key} must be a non-negative integer (use -1 for infinity)",
)
def __repr__(self) -> str:
rep = ""
for k, v in sorted(self._d.items(), key=lambda x: x[0]):
rep += f"{k}: {v}, "
return rep
# builders
def digest_parser(self, parser: configparser.ConfigParser) -> Self:
"""Process the config options present in a :class:`ConfigParser` object.
This method processes arbitrary parsers, not only those read from a
single file, whereas :meth:`~ManimConfig.digest_file` can only process one
file at a time.
Parameters
----------
parser
An object reflecting the contents of one or many ``.cfg`` files. In
particular, it may reflect the contents of multiple files that have
been parsed in a cascading fashion.
Returns
-------
self : :class:`ManimConfig`
This object, after processing the contents of ``parser``.
See Also
--------
:func:`make_config_parser`, :meth:`~.ManimConfig.digest_file`,
:meth:`~.ManimConfig.digest_args`,
Notes
-----
If there are multiple ``.cfg`` files to process, it is always more
efficient to parse them into a single :class:`ConfigParser` object
first, and then call this function once (instead of calling
:meth:`~.ManimConfig.digest_file` multiple times).
Examples
--------
To digest the config options set in two files, first create a
ConfigParser and parse both files and then digest the parser:
.. code-block:: python
parser = configparser.ConfigParser()
parser.read([file1, file2])
config = ManimConfig().digest_parser(parser)
In fact, the global ``config`` object is initialized like so:
.. code-block:: python
parser = make_config_parser()
config = ManimConfig().digest_parser(parser)
"""
self._parser = parser
# boolean keys
for key in [
"notify_outdated_version",
"write_to_movie",
"save_last_frame",
"write_all",
"save_pngs",
"save_as_gif",
"save_sections",
"preview",
"show_in_file_browser",
"log_to_file",
"disable_caching",
"disable_caching_warning",
"flush_cache",
"custom_folders",
"enable_gui",
"fullscreen",
"use_projection_fill_shaders",
"use_projection_stroke_shaders",
"enable_wireframe",
"force_window",
"no_latex_cleanup",
]:
setattr(self, key, parser["CLI"].getboolean(key, fallback=False))
# int keys
for key in [
"from_animation_number",
"upto_animation_number",
"max_files_cached",
# the next two must be set BEFORE digesting frame_width and frame_height
"pixel_height",
"pixel_width",
"window_monitor",
"zero_pad",
]:
setattr(self, key, parser["CLI"].getint(key))
# str keys
for key in [
"assets_dir",
"verbosity",
"media_dir",
"log_dir",
"video_dir",
"sections_dir",
"images_dir",
"text_dir",
"tex_dir",
"partial_movie_dir",
"input_file",
"output_file",
"movie_file_extension",
"background_color",
"renderer",
"window_position",
]:
setattr(self, key, parser["CLI"].get(key, fallback="", raw=True))
# float keys
for key in [
"background_opacity",
"frame_rate",
# the next two are floats but have their own logic, applied later
# "frame_width",
# "frame_height",
]:
setattr(self, key, parser["CLI"].getfloat(key))
# tuple keys
gui_location = tuple(
map(int, re.split(r"[;,\-]", parser["CLI"]["gui_location"])),
)
setattr(self, "gui_location", gui_location)
window_size = parser["CLI"][
"window_size"
] # if not "default", get a tuple of the position
if window_size != "default":
window_size = tuple(map(int, re.split(r"[;,\-]", window_size)))
setattr(self, "window_size", window_size)
# plugins
self.plugins = parser["CLI"].get("plugins", fallback="", raw=True).split(",")
# the next two must be set AFTER digesting pixel_width and pixel_height
self["frame_height"] = parser["CLI"].getfloat("frame_height", 8.0)
width = parser["CLI"].getfloat("frame_width", None)
if width is None:
self["frame_width"] = self["frame_height"] * self["aspect_ratio"]
else:
self["frame_width"] = width
# other logic
val = parser["CLI"].get("tex_template_file")
if val:
self.tex_template_file = val
val = parser["CLI"].get("progress_bar")
if val:
setattr(self, "progress_bar", val)
val = parser["ffmpeg"].get("loglevel")
if val:
self.ffmpeg_loglevel = val
# TODO: Fix the mess above and below
val = parser["ffmpeg"].get("ffmpeg_executable")
setattr(self, "ffmpeg_executable", val)
try:
val = parser["jupyter"].getboolean("media_embed")
except ValueError:
val = None
setattr(self, "media_embed", val)
val = parser["jupyter"].get("media_width")
if val:
setattr(self, "media_width", val)
val = parser["CLI"].get("quality", fallback="", raw=True)
if val:
self.quality = _determine_quality(val)
return self
def digest_args(self, args: argparse.Namespace) -> Self:
"""Process the config options present in CLI arguments.
Parameters
----------
args
An object returned by :func:`.main_utils.parse_args()`.
Returns
-------
self : :class:`ManimConfig`
This object, after processing the contents of ``parser``.
See Also
--------
:func:`.main_utils.parse_args()`, :meth:`~.ManimConfig.digest_parser`,
:meth:`~.ManimConfig.digest_file`
Notes
-----
If ``args.config_file`` is a non-empty string, ``ManimConfig`` tries to digest the
contents of said file with :meth:`~ManimConfig.digest_file` before
digesting any other CLI arguments.
"""
# if the input file is a config file, parse it properly
if args.file.suffix == ".cfg":
args.config_file = args.file
# if args.file is `-`, the animation code has to be taken from STDIN, so the
# input file path shouldn't be absolute, since that file won't be read.
if str(args.file) == "-":
self.input_file = args.file
# if a config file has been passed, digest it first so that other CLI
# flags supersede it
if args.config_file:
self.digest_file(args.config_file)
# read input_file from the args if it wasn't set by the config file
if not self.input_file:
self.input_file = Path(args.file).absolute()
self.scene_names = args.scene_names if args.scene_names is not None else []
self.output_file = args.output_file
for key in [
"notify_outdated_version",
"preview",
"show_in_file_browser",
"write_to_movie",
"save_last_frame",
"save_pngs",
"save_as_gif",
"save_sections",
"write_all",
"disable_caching",
"format",
"flush_cache",
"progress_bar",
"transparent",
"scene_names",
"verbosity",
"renderer",
"background_color",
"enable_gui",
"fullscreen",
"use_projection_fill_shaders",
"use_projection_stroke_shaders",
"zero_pad",
"enable_wireframe",
"force_window",
"dry_run",
"no_latex_cleanup",
]:
if hasattr(args, key):
attr = getattr(args, key)
# if attr is None, then no argument was passed and we should
# not change the current config
if attr is not None:
self[key] = attr
for key in [
"media_dir", # always set this one first
"log_dir",
"log_to_file", # always set this one last
]:
if hasattr(args, key):
attr = getattr(args, key)
# if attr is None, then no argument was passed and we should
# not change the current config
if attr is not None:
self[key] = attr
if self["save_last_frame"]:
self["write_to_movie"] = False
# Handle the -n flag.
nflag = args.from_animation_number
if nflag:
self.from_animation_number = nflag[0]
try:
self.upto_animation_number = nflag[1]
except Exception:
logging.getLogger("manim").info(
f"No end scene number specified in -n option. Rendering from {nflag[0]} onwards...",
)
# Handle the quality flags
self.quality = _determine_quality(getattr(args, "quality", None))
# Handle the -r flag.
rflag = args.resolution
if rflag:
self.pixel_width = int(rflag[0])
self.pixel_height = int(rflag[1])
fps = args.frame_rate
if fps:
self.frame_rate = float(fps)
# Handle --custom_folders
if args.custom_folders:
for opt in [
"media_dir",
"video_dir",
"sections_dir",
"images_dir",
"text_dir",
"tex_dir",
"log_dir",
"partial_movie_dir",
]:
self[opt] = self._parser["custom_folders"].get(opt, raw=True)
# --media_dir overrides the default.cfg file
if hasattr(args, "media_dir") and args.media_dir:
self.media_dir = args.media_dir
# Handle --tex_template
if args.tex_template:
self.tex_template = TexTemplate.from_file(args.tex_template)
if (
self.renderer == RendererType.OPENGL
and getattr(args, "write_to_movie") is None
):
# --write_to_movie was not passed on the command line, so don't generate video.
self["write_to_movie"] = False
# Handle --gui_location flag.
if getattr(args, "gui_location") is not None:
self.gui_location = args.gui_location
return self
def digest_file(self, filename: StrPath) -> Self:
"""Process the config options present in a ``.cfg`` file.
This method processes a single ``.cfg`` file, whereas
:meth:`~ManimConfig.digest_parser` can process arbitrary parsers, built
perhaps from multiple ``.cfg`` files.
Parameters
----------
filename
Path to the ``.cfg`` file.
Returns
-------
self : :class:`ManimConfig`
This object, after processing the contents of ``filename``.
See Also
--------
:meth:`~ManimConfig.digest_file`, :meth:`~ManimConfig.digest_args`,
:func:`make_config_parser`
Notes
-----
If there are multiple ``.cfg`` files to process, it is always more
efficient to parse them into a single :class:`ConfigParser` object
first and digesting them with one call to
:meth:`~ManimConfig.digest_parser`, instead of calling this method
multiple times.
"""
if not Path(filename).is_file():
raise FileNotFoundError(
errno.ENOENT,
"Error: --config_file could not find a valid config file.",
str(filename),
)
return self.digest_parser(make_config_parser(filename))
# config options are properties
@property
def preview(self) -> bool:
"""Whether to play the rendered movie (-p)."""
return self._d["preview"] or self._d["enable_gui"]
@preview.setter
def preview(self, value: bool) -> None:
self._set_boolean("preview", value)
@property
def show_in_file_browser(self) -> bool:
"""Whether to show the output file in the file browser (-f)."""
return self._d["show_in_file_browser"]
@show_in_file_browser.setter
def show_in_file_browser(self, value: bool) -> None:
self._set_boolean("show_in_file_browser", value)
@property
def progress_bar(self) -> str:
"""Whether to show progress bars while rendering animations."""
return self._d["progress_bar"]
@progress_bar.setter
def progress_bar(self, value: str) -> None:
self._set_from_list("progress_bar", value, ["none", "display", "leave"])
@property
def log_to_file(self) -> bool:
"""Whether to save logs to a file."""
return self._d["log_to_file"]
@log_to_file.setter
def log_to_file(self, value: bool) -> None:
self._set_boolean("log_to_file", value)
@property
def notify_outdated_version(self) -> bool:
"""Whether to notify if there is a version update available."""
return self._d["notify_outdated_version"]
@notify_outdated_version.setter
def notify_outdated_version(self, value: bool) -> None:
self._set_boolean("notify_outdated_version", value)
@property
def write_to_movie(self) -> bool:
"""Whether to render the scene to a movie file (-w)."""
return self._d["write_to_movie"]
@write_to_movie.setter
def write_to_movie(self, value: bool) -> None:
self._set_boolean("write_to_movie", value)
@property
def save_last_frame(self) -> bool:
"""Whether to save the last frame of the scene as an image file (-s)."""
return self._d["save_last_frame"]
@save_last_frame.setter
def save_last_frame(self, value: bool) -> None:
self._set_boolean("save_last_frame", value)
@property
def write_all(self) -> bool:
"""Whether to render all scenes in the input file (-a)."""
return self._d["write_all"]
@write_all.setter
def write_all(self, value: bool) -> None:
self._set_boolean("write_all", value)
@property
def save_pngs(self) -> bool:
"""Whether to save all frames in the scene as images files (-g)."""
return self._d["save_pngs"]
@save_pngs.setter
def save_pngs(self, value: bool) -> None:
self._set_boolean("save_pngs", value)
@property
def save_as_gif(self) -> bool:
"""Whether to save the rendered scene in .gif format (-i)."""
return self._d["save_as_gif"]
@save_as_gif.setter
def save_as_gif(self, value: bool) -> None:
self._set_boolean("save_as_gif", value)
@property
def save_sections(self) -> bool:
"""Whether to save single videos for each section in addition to the movie file."""
return self._d["save_sections"]
@save_sections.setter
def save_sections(self, value: bool) -> None:
self._set_boolean("save_sections", value)
@property
def enable_wireframe(self) -> bool:
"""Whether to enable wireframe debugging mode in opengl."""
return self._d["enable_wireframe"]
@enable_wireframe.setter
def enable_wireframe(self, value: bool) -> None:
self._set_boolean("enable_wireframe", value)
@property
def force_window(self) -> bool:
"""Whether to force window when using the opengl renderer."""
return self._d["force_window"]
@force_window.setter
def force_window(self, value: bool) -> None:
self._set_boolean("force_window", value)
@property
def no_latex_cleanup(self) -> bool:
"""Prevents deletion of .aux, .dvi, and .log files produced by Tex and MathTex."""
return self._d["no_latex_cleanup"]
@no_latex_cleanup.setter
def no_latex_cleanup(self, value: bool) -> None:
self._set_boolean("no_latex_cleanup", value)
@property
def verbosity(self) -> str:
"""Logger verbosity; "DEBUG", "INFO", "WARNING", "ERROR", or "CRITICAL" (-v)."""
return self._d["verbosity"]
@verbosity.setter
def verbosity(self, val: str) -> None:
self._set_from_list(
"verbosity",
val,
["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
)
logging.getLogger("manim").setLevel(val)
@property
def format(self) -> str:
"""File format; "png", "gif", "mp4", "webm" or "mov"."""
return self._d["format"]
@format.setter
def format(self, val: str) -> None:
self._set_from_list(
"format",
val,
[None, "png", "gif", "mp4", "mov", "webm"],
)
if self.format == "webm":
logging.getLogger("manim").warning(
"Output format set as webm, this can be slower than other formats",
)
@property
def ffmpeg_loglevel(self) -> str:
"""Verbosity level of ffmpeg (no flag)."""
return self._d["ffmpeg_loglevel"]
@ffmpeg_loglevel.setter
def ffmpeg_loglevel(self, val: str) -> None:
self._set_from_list(
"ffmpeg_loglevel",
val,
["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
)
@property
def ffmpeg_executable(self) -> str:
"""Custom path to the ffmpeg executable."""
return self._d["ffmpeg_executable"]
@ffmpeg_executable.setter
def ffmpeg_executable(self, value: str) -> None:
self._set_str("ffmpeg_executable", value)
@property
def media_embed(self) -> bool:
"""Whether to embed videos in Jupyter notebook."""
return self._d["media_embed"]
@media_embed.setter
def media_embed(self, value: bool) -> None:
self._set_boolean("media_embed", value)
@property
def media_width(self) -> str:
"""Media width in Jupyter notebook."""
return self._d["media_width"]
@media_width.setter
def media_width(self, value: str) -> None:
self._set_str("media_width", value)
@property
def pixel_width(self) -> int:
"""Frame width in pixels (--resolution, -r)."""
return self._d["pixel_width"]
@pixel_width.setter
def pixel_width(self, value: int) -> None:
self._set_pos_number("pixel_width", value, False)
@property
def pixel_height(self) -> int:
"""Frame height in pixels (--resolution, -r)."""
return self._d["pixel_height"]
@pixel_height.setter
def pixel_height(self, value: int) -> None:
self._set_pos_number("pixel_height", value, False)
@property
def aspect_ratio(self) -> int:
"""Aspect ratio (width / height) in pixels (--resolution, -r)."""
return self._d["pixel_width"] / self._d["pixel_height"]
@property
def frame_height(self) -> float:
"""Frame height in logical units (no flag)."""
return self._d["frame_height"]
@frame_height.setter
def frame_height(self, value: float) -> None:
self._d.__setitem__("frame_height", value)
@property
def frame_width(self) -> float:
"""Frame width in logical units (no flag)."""
return self._d["frame_width"]
@frame_width.setter
def frame_width(self, value: float) -> None:
self._d.__setitem__("frame_width", value)
@property
def frame_y_radius(self) -> float:
"""Half the frame height (no flag)."""
return self._d["frame_height"] / 2
@frame_y_radius.setter
def frame_y_radius(self, value: float) -> None:
self._d.__setitem__("frame_y_radius", value) or self._d.__setitem__(
"frame_height", 2 * value
)
@property
def frame_x_radius(self) -> float:
"""Half the frame width (no flag)."""
return self._d["frame_width"] / 2
@frame_x_radius.setter
def frame_x_radius(self, value: float) -> None:
self._d.__setitem__("frame_x_radius", value) or self._d.__setitem__(
"frame_width", 2 * value
)
@property
def top(self) -> Vector3D:
"""Coordinate at the center top of the frame."""
return self.frame_y_radius * constants.UP
@property
def bottom(self) -> Vector3D:
"""Coordinate at the center bottom of the frame."""
return self.frame_y_radius * constants.DOWN
@property
def left_side(self) -> Vector3D:
"""Coordinate at the middle left of the frame."""
return self.frame_x_radius * constants.LEFT
@property
def right_side(self) -> Vector3D:
"""Coordinate at the middle right of the frame."""
return self.frame_x_radius * constants.RIGHT
@property
def frame_rate(self) -> float:
"""Frame rate in frames per second."""
return self._d["frame_rate"]
@frame_rate.setter
def frame_rate(self, value: float) -> None:
self._d.__setitem__("frame_rate", value)
# TODO: This was parsed before maybe add ManimColor(val), but results in circular import
@property
def background_color(self) -> ManimColor:
"""Background color of the scene (-c)."""
return self._d["background_color"]
@background_color.setter
def background_color(self, value: Any) -> None:
self._d.__setitem__("background_color", ManimColor(value))
@property
def from_animation_number(self) -> int:
"""Start rendering animations at this number (-n)."""
return self._d["from_animation_number"]
@from_animation_number.setter
def from_animation_number(self, value: int) -> None:
self._d.__setitem__("from_animation_number", value)
@property
def upto_animation_number(self) -> int:
"""Stop rendering animations at this nmber. Use -1 to avoid skipping (-n)."""
return self._d["upto_animation_number"]
@upto_animation_number.setter
def upto_animation_number(self, value: int) -> None:
self._set_pos_number("upto_animation_number", value, True)
@property
def max_files_cached(self) -> int:
"""Maximum number of files cached. Use -1 for infinity (no flag)."""
return self._d["max_files_cached"]
@max_files_cached.setter
def max_files_cached(self, value: int) -> None:
self._set_pos_number("max_files_cached", value, True)
@property
def window_monitor(self) -> int:
"""The monitor on which the scene will be rendered."""
return self._d["window_monitor"]
@window_monitor.setter
def window_monitor(self, value: int) -> None:
self._set_pos_number("window_monitor", value, True)
@property
def flush_cache(self) -> bool:
"""Whether to delete all the cached partial movie files."""
return self._d["flush_cache"]
@flush_cache.setter
def flush_cache(self, value: bool) -> None:
self._set_boolean("flush_cache", value)
@property
def disable_caching(self) -> bool:
"""Whether to use scene caching."""
return self._d["disable_caching"]
@disable_caching.setter
def disable_caching(self, value: bool) -> None:
self._set_boolean("disable_caching", value)
@property
def disable_caching_warning(self) -> bool:
"""Whether a warning is raised if there are too much submobjects to hash."""
return self._d["disable_caching_warning"]
@disable_caching_warning.setter
def disable_caching_warning(self, value: bool) -> None:
self._set_boolean("disable_caching_warning", value)
@property
def movie_file_extension(self) -> str:
"""Either .mp4, .webm or .mov."""
return self._d["movie_file_extension"]
@movie_file_extension.setter
def movie_file_extension(self, value: str) -> None:
self._set_from_list("movie_file_extension", value, [".mp4", ".mov", ".webm"])
@property
def background_opacity(self) -> float:
"""A number between 0.0 (fully transparent) and 1.0 (fully opaque)."""
return self._d["background_opacity"]
@background_opacity.setter
def background_opacity(self, value: float) -> None:
self._set_between("background_opacity", value, 0, 1)
@property
def frame_size(self) -> tuple[int, int]:
"""Tuple with (pixel width, pixel height) (no flag)."""
return (self._d["pixel_width"], self._d["pixel_height"])
@frame_size.setter
def frame_size(self, value: tuple[int, int]) -> None:
self._d.__setitem__("pixel_width", value[0]) or self._d.__setitem__(
"pixel_height", value[1]
)
@property
def quality(self) -> str | None:
"""Video quality (-q)."""
keys = ["pixel_width", "pixel_height", "frame_rate"]
q = {k: self[k] for k in keys}
for qual in constants.QUALITIES:
if all(q[k] == constants.QUALITIES[qual][k] for k in keys):
return qual
return None
@quality.setter
def quality(self, value: str | None) -> None:
if value is None:
return
if value not in constants.QUALITIES:
raise KeyError(f"quality must be one of {list(constants.QUALITIES.keys())}")
q = constants.QUALITIES[value]
self.frame_size = q["pixel_width"], q["pixel_height"]
self.frame_rate = q["frame_rate"]
@property
def transparent(self) -> bool:
"""Whether the background opacity is 0.0 (-t)."""
return self._d["background_opacity"] == 0.0
@transparent.setter
def transparent(self, value: bool) -> None:
self._d["background_opacity"] = float(not value)
self.resolve_movie_file_extension(value)
@property
def dry_run(self) -> bool:
"""Whether dry run is enabled."""
return self._d["dry_run"]
@dry_run.setter
def dry_run(self, val: bool) -> None:
self._d["dry_run"] = val
if val:
self.write_to_movie = False
self.write_all = False
self.save_last_frame = False
self.format = None
@property
def renderer(self) -> RendererType:
"""The currently active renderer.
Populated with one of the available renderers in :class:`.RendererType`.
Tests::
>>> test_config = ManimConfig()
>>> test_config.renderer is None # a new ManimConfig is unpopulated
True
>>> test_config.renderer = 'opengl'
>>> test_config.renderer
<RendererType.OPENGL: 'opengl'>
>>> test_config.renderer = 42
Traceback (most recent call last):
...
ValueError: 42 is not a valid RendererType
Check that capitalization of renderer types is irrelevant::
>>> test_config.renderer = 'OpenGL'
>>> test_config.renderer = 'cAirO'
"""
return self._d["renderer"]
@renderer.setter
def renderer(self, value: str | RendererType) -> None:
"""The setter of the renderer property.
Takes care of switching inheritance bases using the
:class:`.ConvertToOpenGL` metaclass.
"""
if isinstance(value, str):
value = value.lower()
renderer = RendererType(value)
try:
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject
from ..mobject.mobject import Mobject
from ..mobject.types.vectorized_mobject import VMobject
for cls in ConvertToOpenGL._converted_classes:
if renderer == RendererType.OPENGL:
conversion_dict = {
Mobject: OpenGLMobject,
VMobject: OpenGLVMobject,
}
else:
conversion_dict = {
OpenGLMobject: Mobject,
OpenGLVMobject: VMobject,
}
cls.__bases__ = tuple(
conversion_dict.get(base, base) for base in cls.__bases__
)
except ImportError:
# The renderer is set during the initial import of the
# library for the first time. The imports above cause an
# ImportError due to circular imports. However, the
# metaclass sets stuff up correctly in this case, so we
# can just do nothing.
pass
self._set_from_enum("renderer", renderer, RendererType)
@property
def media_dir(self) -> str:
"""Main output directory. See :meth:`ManimConfig.get_dir`."""
return self._d["media_dir"]
@media_dir.setter
def media_dir(self, value: str | Path) -> None:
self._set_dir("media_dir", value)
@property
def window_position(self) -> str:
"""Set the position of preview window. You can use directions, e.g. UL/DR/ORIGIN/LEFT...or the position(pixel) of the upper left corner of the window, e.g. '960,540'."""
return self._d["window_position"]
@window_position.setter
def window_position(self, value: str) -> None:
self._d.__setitem__("window_position", value)
@property
def window_size(self) -> str:
"""The size of the opengl window. 'default' to automatically scale the window based on the display monitor."""
return self._d["window_size"]
@window_size.setter
def window_size(self, value: str) -> None:
self._d.__setitem__("window_size", value)
def resolve_movie_file_extension(self, is_transparent: bool) -> None:
if is_transparent:
self.movie_file_extension = ".webm" if self.format == "webm" else ".mov"
elif self.format == "webm":
self.movie_file_extension = ".webm"
elif self.format == "mov":
self.movie_file_extension = ".mov"
else:
self.movie_file_extension = ".mp4"
@property
def enable_gui(self) -> bool:
"""Enable GUI interaction."""
return self._d["enable_gui"]
@enable_gui.setter
def enable_gui(self, value: bool) -> None:
self._set_boolean("enable_gui", value)
@property
def gui_location(self) -> tuple[Any]:
"""Enable GUI interaction."""
return self._d["gui_location"]
@gui_location.setter
def gui_location(self, value: tuple[Any]) -> None:
self._set_tuple("gui_location", value)
@property
def fullscreen(self) -> bool:
"""Expand the window to its maximum possible size."""
return self._d["fullscreen"]
@fullscreen.setter
def fullscreen(self, value: bool) -> None:
self._set_boolean("fullscreen", value)
@property
def use_projection_fill_shaders(self) -> bool:
"""Use shaders for OpenGLVMobject fill which are compatible with transformation matrices."""
return self._d["use_projection_fill_shaders"]
@use_projection_fill_shaders.setter
def use_projection_fill_shaders(self, value: bool) -> None:
self._set_boolean("use_projection_fill_shaders", value)
@property
def use_projection_stroke_shaders(self) -> bool:
"""Use shaders for OpenGLVMobject stroke which are compatible with transformation matrices."""
return self._d["use_projection_stroke_shaders"]
@use_projection_stroke_shaders.setter
def use_projection_stroke_shaders(self, value: bool) -> None:
self._set_boolean("use_projection_stroke_shaders", value)
@property
def zero_pad(self) -> int:
"""PNG zero padding. A number between 0 (no zero padding) and 9 (9 columns minimum)."""
return self._d["zero_pad"]
@zero_pad.setter
def zero_pad(self, value: int) -> None:
self._set_int_between("zero_pad", value, 0, 9)
def get_dir(self, key: str, **kwargs: Any) -> Path:
"""Resolve a config option that stores a directory.
Config options that store directories may depend on one another. This
method is used to provide the actual directory to the end user.
Parameters
----------
key
The config option to be resolved. Must be an option ending in
``'_dir'``, for example ``'media_dir'`` or ``'video_dir'``.
kwargs
Any strings to be used when resolving the directory.
Returns
-------
:class:`pathlib.Path`
Path to the requested directory. If the path resolves to the empty
string, return ``None`` instead.
Raises
------
:class:`KeyError`
When ``key`` is not a config option that stores a directory and
thus :meth:`~ManimConfig.get_dir` is not appropriate; or when
``key`` is appropriate but there is not enough information to
resolve the directory.
Notes
-----
Standard :meth:`str.format` syntax is used to resolve the paths so the
paths may contain arbitrary placeholders using f-string notation.
However, these will require ``kwargs`` to contain the required values.
Examples
--------
The value of ``config.tex_dir`` is ``'{media_dir}/Tex'`` by default,
i.e. it is a subfolder of wherever ``config.media_dir`` is located. In
order to get the *actual* directory, use :meth:`~ManimConfig.get_dir`.
.. code-block:: pycon
>>> from manim import config as globalconfig
>>> config = globalconfig.copy()
>>> config.tex_dir
'{media_dir}/Tex'
>>> config.media_dir
'./media'
>>> config.get_dir("tex_dir").as_posix()
'media/Tex'
Resolving directories is done in a lazy way, at the last possible
moment, to reflect any changes in other config options:
.. code-block:: pycon
>>> config.media_dir = "my_media_dir"
>>> config.get_dir("tex_dir").as_posix()
'my_media_dir/Tex'
Some directories depend on information that is not available to
:class:`ManimConfig`. For example, the default value of `video_dir`
includes the name of the input file and the video quality
(e.g. 480p15). This informamtion has to be supplied via ``kwargs``:
.. code-block:: pycon
>>> config.video_dir
'{media_dir}/videos/{module_name}/{quality}'
>>> config.get_dir("video_dir")
Traceback (most recent call last):
KeyError: 'video_dir {media_dir}/videos/{module_name}/{quality} requires the following keyword arguments: module_name'
>>> config.get_dir("video_dir", module_name="myfile").as_posix()
'my_media_dir/videos/myfile/1080p60'
Note the quality does not need to be passed as keyword argument since
:class:`ManimConfig` does store information about quality.
Directories may be recursively defined. For example, the config option
``partial_movie_dir`` depends on ``video_dir``, which in turn depends
on ``media_dir``:
.. code-block:: pycon
>>> config.partial_movie_dir
'{video_dir}/partial_movie_files/{scene_name}'
>>> config.get_dir("partial_movie_dir")
Traceback (most recent call last):
KeyError: 'partial_movie_dir {video_dir}/partial_movie_files/{scene_name} requires the following keyword arguments: scene_name'
>>> config.get_dir(
... "partial_movie_dir", module_name="myfile", scene_name="myscene"
... ).as_posix()
'my_media_dir/videos/myfile/1080p60/partial_movie_files/myscene'
Standard f-string syntax is used. Arbitrary names can be used when
defining directories, as long as the corresponding values are passed to
:meth:`ManimConfig.get_dir` via ``kwargs``.
.. code-block:: pycon
>>> config.media_dir = "{dir1}/{dir2}"
>>> config.get_dir("media_dir")
Traceback (most recent call last):
KeyError: 'media_dir {dir1}/{dir2} requires the following keyword arguments: dir1'
>>> config.get_dir("media_dir", dir1="foo", dir2="bar").as_posix()
'foo/bar'
>>> config.media_dir = "./media"
>>> config.get_dir("media_dir").as_posix()
'media'
"""
dirs = [
"assets_dir",
"media_dir",
"video_dir",
"sections_dir",
"images_dir",
"text_dir",
"tex_dir",
"log_dir",
"input_file",
"output_file",
"partial_movie_dir",
]
if key not in dirs:
raise KeyError(
"must pass one of "
"{media,video,images,text,tex,log}_dir "
"or {input,output}_file",
)
dirs.remove(key) # a path cannot contain itself
all_args = {k: self._d[k] for k in dirs}
all_args.update(kwargs)
all_args["quality"] = f"{self.pixel_height}p{self.frame_rate:g}"
path = self._d[key]
while "{" in path:
try:
path = path.format(**all_args)
except KeyError as exc:
raise KeyError(
f"{key} {self._d[key]} requires the following "
+ "keyword arguments: "
+ " ".join(exc.args),
) from exc
return Path(path) if path else None
def _set_dir(self, key: str, val: str | Path) -> None:
if isinstance(val, Path):
self._d.__setitem__(key, str(val))
else:
self._d.__setitem__(key, val)
@property
def assets_dir(self) -> str:
"""Directory to locate video assets (no flag)."""
return self._d["assets_dir"]
@assets_dir.setter
def assets_dir(self, value: str | Path) -> None:
self._set_dir("assets_dir", value)
@property
def log_dir(self) -> str:
"""Directory to place logs. See :meth:`ManimConfig.get_dir`."""
return self._d["log_dir"]
@log_dir.setter
def log_dir(self, value: str | Path) -> None:
self._set_dir("log_dir", value)
@property
def video_dir(self) -> str:
"""Directory to place videos (no flag). See :meth:`ManimConfig.get_dir`."""
return self._d["video_dir"]
@video_dir.setter
def video_dir(self, value: str | Path) -> None:
self._set_dir("video_dir", value)
@property
def sections_dir(self) -> str:
"""Directory to place section videos (no flag). See :meth:`ManimConfig.get_dir`."""
return self._d["sections_dir"]
@sections_dir.setter
def sections_dir(self, value: str | Path) -> None:
self._set_dir("sections_dir", value)
@property
def images_dir(self) -> str:
"""Directory to place images (no flag). See :meth:`ManimConfig.get_dir`."""
return self._d["images_dir"]
@images_dir.setter
def images_dir(self, value: str | Path) -> None:
self._set_dir("images_dir", value)
@property
def text_dir(self) -> str:
"""Directory to place text (no flag). See :meth:`ManimConfig.get_dir`."""
return self._d["text_dir"]
@text_dir.setter
def text_dir(self, value: str | Path) -> None:
self._set_dir("text_dir", value)
@property
def tex_dir(self) -> str:
"""Directory to place tex (no flag). See :meth:`ManimConfig.get_dir`."""
return self._d["tex_dir"]
@tex_dir.setter
def tex_dir(self, value: str | Path) -> None:
self._set_dir("tex_dir", value)
@property
def partial_movie_dir(self) -> str:
"""Directory to place partial movie files (no flag). See :meth:`ManimConfig.get_dir`."""
return self._d["partial_movie_dir"]
@partial_movie_dir.setter
def partial_movie_dir(self, value: str | Path) -> None:
self._set_dir("partial_movie_dir", value)
@property
def custom_folders(self) -> str:
"""Whether to use custom folder output."""
return self._d["custom_folders"]
@custom_folders.setter
def custom_folders(self, value: str | Path) -> None:
self._set_dir("custom_folders", value)
@property
def input_file(self) -> str:
"""Input file name."""
return self._d["input_file"]
@input_file.setter
def input_file(self, value: str | Path) -> None:
self._set_dir("input_file", value)
@property
def output_file(self) -> str:
"""Output file name (-o)."""
return self._d["output_file"]
@output_file.setter
def output_file(self, value: str | Path) -> None:
self._set_dir("output_file", value)
@property
def scene_names(self) -> list[str]:
"""Scenes to play from file."""
return self._d["scene_names"]
@scene_names.setter
def scene_names(self, value: list[str]) -> None:
self._d.__setitem__("scene_names", value)
@property
def tex_template(self) -> TexTemplate:
"""Template used when rendering Tex. See :class:`.TexTemplate`."""
if not hasattr(self, "_tex_template") or not self._tex_template:
fn = self._d["tex_template_file"]
if fn:
self._tex_template = TexTemplate.from_file(fn)
else:
self._tex_template = TexTemplate()
return self._tex_template
@tex_template.setter
def tex_template(self, val: TexTemplate) -> None:
if isinstance(val, TexTemplate):
self._tex_template = val
@property
def tex_template_file(self) -> Path:
"""File to read Tex template from (no flag). See :class:`.TexTemplate`."""
return self._d["tex_template_file"]
@tex_template_file.setter
def tex_template_file(self, val: str) -> None:
if val:
if not os.access(val, os.R_OK):
logging.getLogger("manim").warning(
f"Custom TeX template {val} not found or not readable.",
)
else:
self._d["tex_template_file"] = Path(val)
else:
self._d["tex_template_file"] = val # actually set the falsy value
@property
def plugins(self) -> list[str]:
"""List of plugins to enable."""
return self._d["plugins"]
@plugins.setter
def plugins(self, value: list[str]):
self._d["plugins"] = value
# TODO: to be used in the future - see PR #620
# https://github.com/ManimCommunity/manim/pull/620
class ManimFrame(Mapping):
_OPTS: ClassVar[set[str]] = {
"pixel_width",
"pixel_height",
"aspect_ratio",
"frame_height",
"frame_width",
"frame_y_radius",
"frame_x_radius",
"top",
"bottom",
"left_side",
"right_side",
}
_CONSTANTS: ClassVar[dict[str, Vector3D]] = {
"UP": np.array((0.0, 1.0, 0.0)),
"DOWN": np.array((0.0, -1.0, 0.0)),
"RIGHT": np.array((1.0, 0.0, 0.0)),
"LEFT": np.array((-1.0, 0.0, 0.0)),
"IN": np.array((0.0, 0.0, -1.0)),
"OUT": np.array((0.0, 0.0, 1.0)),
"ORIGIN": np.array((0.0, 0.0, 0.0)),
"X_AXIS": np.array((1.0, 0.0, 0.0)),
"Y_AXIS": np.array((0.0, 1.0, 0.0)),
"Z_AXIS": np.array((0.0, 0.0, 1.0)),
"UL": np.array((-1.0, 1.0, 0.0)),
"UR": np.array((1.0, 1.0, 0.0)),
"DL": np.array((-1.0, -1.0, 0.0)),
"DR": np.array((1.0, -1.0, 0.0)),
}
_c: ManimConfig
def __init__(self, c: ManimConfig) -> None:
if not isinstance(c, ManimConfig):
raise TypeError("argument must be instance of 'ManimConfig'")
# need to use __dict__ directly because setting attributes is not
# allowed (see __setattr__)
self.__dict__["_c"] = c
# there are required by parent class Mapping to behave like a dict
def __getitem__(self, key: str | int) -> Any:
if key in self._OPTS:
return self._c[key]
elif key in self._CONSTANTS:
return self._CONSTANTS[key]
else:
raise KeyError(key)
def __iter__(self) -> Iterable[str]:
return iter(list(self._OPTS) + list(self._CONSTANTS))
def __len__(self) -> int:
return len(self._OPTS)
# make this truly immutable
def __setattr__(self, attr: Any, val: Any) -> NoReturn:
raise TypeError("'ManimFrame' object does not support item assignment")
def __setitem__(self, key: Any, val: Any) -> NoReturn:
raise TypeError("'ManimFrame' object does not support item assignment")
def __delitem__(self, key: Any) -> NoReturn:
raise TypeError("'ManimFrame' object does not support item deletion")
for opt in list(ManimFrame._OPTS) + list(ManimFrame._CONSTANTS):
setattr(ManimFrame, opt, property(lambda self, o=opt: self[o]))
|
manim_ManimCommunity/manim/opengl/__init__.py
|
from __future__ import annotations
try:
from dearpygui import dearpygui as dpg
except ImportError:
pass
from manim.mobject.opengl.dot_cloud import *
from manim.mobject.opengl.opengl_image_mobject import *
from manim.mobject.opengl.opengl_mobject import *
from manim.mobject.opengl.opengl_point_cloud_mobject import *
from manim.mobject.opengl.opengl_surface import *
from manim.mobject.opengl.opengl_three_dimensions import *
from manim.mobject.opengl.opengl_vectorized_mobject import *
from ..renderer.shader import *
from ..utils.opengl import *
|
manim_ManimCommunity/manim/animation/rotation.py
|
"""Animations related to rotation."""
from __future__ import annotations
__all__ = ["Rotating", "Rotate"]
from typing import TYPE_CHECKING, Callable, Sequence
import numpy as np
from ..animation.animation import Animation
from ..animation.transform import Transform
from ..constants import OUT, PI, TAU
from ..utils.rate_functions import linear
if TYPE_CHECKING:
from ..mobject.mobject import Mobject
class Rotating(Animation):
def __init__(
self,
mobject: Mobject,
axis: np.ndarray = OUT,
radians: np.ndarray = TAU,
about_point: np.ndarray | None = None,
about_edge: np.ndarray | None = None,
run_time: float = 5,
rate_func: Callable[[float], float] = linear,
**kwargs,
) -> None:
self.axis = axis
self.radians = radians
self.about_point = about_point
self.about_edge = about_edge
super().__init__(mobject, run_time=run_time, rate_func=rate_func, **kwargs)
def interpolate_mobject(self, alpha: float) -> None:
self.mobject.become(self.starting_mobject)
self.mobject.rotate(
self.rate_func(alpha) * self.radians,
axis=self.axis,
about_point=self.about_point,
about_edge=self.about_edge,
)
class Rotate(Transform):
"""Animation that rotates a Mobject.
Parameters
----------
mobject
The mobject to be rotated.
angle
The rotation angle.
axis
The rotation axis as a numpy vector.
about_point
The rotation center.
about_edge
If ``about_point``is ``None``, this argument specifies
the direction of the bounding box point to be taken as
the rotation center.
Examples
--------
.. manim:: UsingRotate
class UsingRotate(Scene):
def construct(self):
self.play(
Rotate(
Square(side_length=0.5).shift(UP * 2),
angle=2*PI,
about_point=ORIGIN,
rate_func=linear,
),
Rotate(Square(side_length=0.5), angle=2*PI, rate_func=linear),
)
"""
def __init__(
self,
mobject: Mobject,
angle: float = PI,
axis: np.ndarray = OUT,
about_point: Sequence[float] | None = None,
about_edge: Sequence[float] | None = None,
**kwargs,
) -> None:
if "path_arc" not in kwargs:
kwargs["path_arc"] = angle
if "path_arc_axis" not in kwargs:
kwargs["path_arc_axis"] = axis
self.angle = angle
self.axis = axis
self.about_edge = about_edge
self.about_point = about_point
if self.about_point is None:
self.about_point = mobject.get_center()
super().__init__(mobject, path_arc_centers=self.about_point, **kwargs)
def create_target(self) -> Mobject:
target = self.mobject.copy()
target.rotate(
self.angle,
axis=self.axis,
about_point=self.about_point,
about_edge=self.about_edge,
)
return target
|
manim_ManimCommunity/manim/animation/fading.py
|
"""Fading in and out of view.
.. manim:: Fading
class Fading(Scene):
def construct(self):
tex_in = Tex("Fade", "In").scale(3)
tex_out = Tex("Fade", "Out").scale(3)
self.play(FadeIn(tex_in, shift=DOWN, scale=0.66))
self.play(ReplacementTransform(tex_in, tex_out))
self.play(FadeOut(tex_out, shift=DOWN * 2, scale=1.5))
"""
from __future__ import annotations
__all__ = [
"FadeOut",
"FadeIn",
]
import numpy as np
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from ..animation.transform import Transform
from ..constants import ORIGIN
from ..mobject.mobject import Group, Mobject
from ..scene.scene import Scene
class _Fade(Transform):
"""Fade :class:`~.Mobject` s in or out.
Parameters
----------
mobjects
The mobjects to be faded.
shift
The vector by which the mobject shifts while being faded.
target_position
The position to/from which the mobject moves while being faded in. In case
another mobject is given as target position, its center is used.
scale
The factor by which the mobject is scaled initially before being rescaling to
its original size while being faded in.
"""
def __init__(
self,
*mobjects: Mobject,
shift: np.ndarray | None = None,
target_position: np.ndarray | Mobject | None = None,
scale: float = 1,
**kwargs,
) -> None:
if not mobjects:
raise ValueError("At least one mobject must be passed.")
if len(mobjects) == 1:
mobject = mobjects[0]
else:
mobject = Group(*mobjects)
self.point_target = False
if shift is None:
if target_position is not None:
if isinstance(target_position, (Mobject, OpenGLMobject)):
target_position = target_position.get_center()
shift = target_position - mobject.get_center()
self.point_target = True
else:
shift = ORIGIN
self.shift_vector = shift
self.scale_factor = scale
super().__init__(mobject, **kwargs)
def _create_faded_mobject(self, fadeIn: bool) -> Mobject:
"""Create a faded, shifted and scaled copy of the mobject.
Parameters
----------
fadeIn
Whether the faded mobject is used to fade in.
Returns
-------
Mobject
The faded, shifted and scaled copy of the mobject.
"""
faded_mobject = self.mobject.copy()
faded_mobject.fade(1)
direction_modifier = -1 if fadeIn and not self.point_target else 1
faded_mobject.shift(self.shift_vector * direction_modifier)
faded_mobject.scale(self.scale_factor)
return faded_mobject
class FadeIn(_Fade):
"""Fade in :class:`~.Mobject` s.
Parameters
----------
mobjects
The mobjects to be faded in.
shift
The vector by which the mobject shifts while being faded in.
target_position
The position from which the mobject starts while being faded in. In case
another mobject is given as target position, its center is used.
scale
The factor by which the mobject is scaled initially before being rescaling to
its original size while being faded in.
Examples
--------
.. manim :: FadeInExample
class FadeInExample(Scene):
def construct(self):
dot = Dot(UP * 2 + LEFT)
self.add(dot)
tex = Tex(
"FadeIn with ", "shift ", " or target\\_position", " and scale"
).scale(1)
animations = [
FadeIn(tex[0]),
FadeIn(tex[1], shift=DOWN),
FadeIn(tex[2], target_position=dot),
FadeIn(tex[3], scale=1.5),
]
self.play(AnimationGroup(*animations, lag_ratio=0.5))
"""
def __init__(self, *mobjects: Mobject, **kwargs) -> None:
super().__init__(*mobjects, introducer=True, **kwargs)
def create_target(self):
return self.mobject
def create_starting_mobject(self):
return self._create_faded_mobject(fadeIn=True)
class FadeOut(_Fade):
"""Fade out :class:`~.Mobject` s.
Parameters
----------
mobjects
The mobjects to be faded out.
shift
The vector by which the mobject shifts while being faded out.
target_position
The position to which the mobject moves while being faded out. In case another
mobject is given as target position, its center is used.
scale
The factor by which the mobject is scaled while being faded out.
Examples
--------
.. manim :: FadeInExample
class FadeInExample(Scene):
def construct(self):
dot = Dot(UP * 2 + LEFT)
self.add(dot)
tex = Tex(
"FadeOut with ", "shift ", " or target\\_position", " and scale"
).scale(1)
animations = [
FadeOut(tex[0]),
FadeOut(tex[1], shift=DOWN),
FadeOut(tex[2], target_position=dot),
FadeOut(tex[3], scale=0.5),
]
self.play(AnimationGroup(*animations, lag_ratio=0.5))
"""
def __init__(self, *mobjects: Mobject, **kwargs) -> None:
super().__init__(*mobjects, remover=True, **kwargs)
def create_target(self):
return self._create_faded_mobject(fadeIn=False)
def clean_up_from_scene(self, scene: Scene = None) -> None:
super().clean_up_from_scene(scene)
self.interpolate(0)
|
manim_ManimCommunity/manim/animation/composition.py
|
"""Tools for displaying multiple animations at once."""
from __future__ import annotations
import types
from typing import TYPE_CHECKING, Callable, Iterable, Sequence
import numpy as np
from manim.mobject.opengl.opengl_mobject import OpenGLGroup
from manim.utils.parameter_parsing import flatten_iterable_parameters
from .._config import config
from ..animation.animation import Animation, prepare_animation
from ..constants import RendererType
from ..mobject.mobject import Group, Mobject
from ..scene.scene import Scene
from ..utils.iterables import remove_list_redundancies
from ..utils.rate_functions import linear
if TYPE_CHECKING:
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVGroup
from ..mobject.types.vectorized_mobject import VGroup
__all__ = ["AnimationGroup", "Succession", "LaggedStart", "LaggedStartMap"]
DEFAULT_LAGGED_START_LAG_RATIO: float = 0.05
class AnimationGroup(Animation):
"""Plays a group or series of :class:`~.Animation`.
Parameters
----------
animations
Sequence of :class:`~.Animation` objects to be played.
group
A group of multiple :class:`~.Mobject`.
run_time
The duration of the animation in seconds.
rate_func
The function defining the animation progress based on the relative
runtime (see :mod:`~.rate_functions`) .
lag_ratio
Defines the delay after which the animation is applied to submobjects. A lag_ratio of
``n.nn`` means the next animation will play when ``nnn%`` of the current animation has played.
Defaults to 0.0, meaning that all animations will be played together.
This does not influence the total runtime of the animation. Instead the runtime
of individual animations is adjusted so that the complete animation has the defined
run time.
"""
def __init__(
self,
*animations: Animation | Iterable[Animation] | types.GeneratorType[Animation],
group: Group | VGroup | OpenGLGroup | OpenGLVGroup = None,
run_time: float | None = None,
rate_func: Callable[[float], float] = linear,
lag_ratio: float = 0,
**kwargs,
) -> None:
arg_anim = flatten_iterable_parameters(animations)
self.animations = [prepare_animation(anim) for anim in arg_anim]
self.rate_func = rate_func
self.group = group
if self.group is None:
mobjects = remove_list_redundancies(
[anim.mobject for anim in self.animations if not anim.is_introducer()],
)
if config["renderer"] == RendererType.OPENGL:
self.group = OpenGLGroup(*mobjects)
else:
self.group = Group(*mobjects)
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]:
return list(self.group)
def begin(self) -> None:
if self.run_time <= 0:
tmp = (
"Please set the run_time to be positive"
if len(self.animations) != 0
else "Please add at least one Animation with positive run_time"
)
raise ValueError(
f"{self} has a run_time of 0 seconds, this cannot be "
f"rendered correctly. {tmp}."
)
if self.suspend_mobject_updating:
self.group.suspend_updating()
for anim in self.animations:
anim.begin()
def _setup_scene(self, scene) -> None:
for anim in self.animations:
anim._setup_scene(scene)
def finish(self) -> None:
for anim in self.animations:
anim.finish()
if self.suspend_mobject_updating:
self.group.resume_updating()
def clean_up_from_scene(self, scene: Scene) -> None:
self._on_finish(scene)
for anim in self.animations:
if self.remover:
anim.remover = self.remover
anim.clean_up_from_scene(scene)
def update_mobjects(self, dt: float) -> None:
for anim in self.animations:
anim.update_mobjects(dt)
def init_run_time(self, run_time) -> float:
"""Calculates the run time of the animation, if different from ``run_time``.
Parameters
----------
run_time
The duration of the animation in seconds.
Returns
-------
run_time
The duration of the animation in seconds.
"""
self.build_animations_with_timings()
if self.anims_with_timings:
self.max_end_time = np.max([awt[2] for awt in self.anims_with_timings])
else:
self.max_end_time = 0
return self.max_end_time if run_time is None else run_time
def build_animations_with_timings(self) -> None:
"""Creates a list of triplets of the form (anim, start_time, end_time)."""
self.anims_with_timings = []
curr_time: float = 0
for anim in self.animations:
start_time: float = curr_time
end_time: float = start_time + anim.get_run_time()
self.anims_with_timings.append((anim, start_time, end_time))
# Start time of next animation is based on the lag_ratio
curr_time = (1 - self.lag_ratio) * start_time + self.lag_ratio * end_time
def interpolate(self, alpha: float) -> None:
# Note, if the run_time of AnimationGroup has been
# set to something other than its default, these
# 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 = self.rate_func(alpha) * self.max_end_time
for anim, start_time, end_time in self.anims_with_timings:
anim_time = end_time - start_time
if anim_time == 0:
sub_alpha = 0
else:
sub_alpha = np.clip((time - start_time) / anim_time, 0, 1)
anim.interpolate(sub_alpha)
class Succession(AnimationGroup):
"""Plays a series of animations in succession.
Parameters
----------
animations
Sequence of :class:`~.Animation` objects to be played.
lag_ratio
Defines the delay after which the animation is applied to submobjects. A lag_ratio of
``n.nn`` means the next animation will play when ``nnn%`` of the current animation has played.
Defaults to 1.0, meaning that the next animation will begin when 100% of the current
animation has played.
This does not influence the total runtime of the animation. Instead the runtime
of individual animations is adjusted so that the complete animation has the defined
run time.
Examples
--------
.. manim:: SuccessionExample
class SuccessionExample(Scene):
def construct(self):
dot1 = Dot(point=LEFT * 2 + UP * 2, radius=0.16, color=BLUE)
dot2 = Dot(point=LEFT * 2 + DOWN * 2, radius=0.16, color=MAROON)
dot3 = Dot(point=RIGHT * 2 + DOWN * 2, radius=0.16, color=GREEN)
dot4 = Dot(point=RIGHT * 2 + UP * 2, radius=0.16, color=YELLOW)
self.add(dot1, dot2, dot3, dot4)
self.play(Succession(
dot1.animate.move_to(dot2),
dot2.animate.move_to(dot3),
dot3.animate.move_to(dot4),
dot4.animate.move_to(dot1)
))
"""
def __init__(self, *animations: Animation, lag_ratio: float = 1, **kwargs) -> None:
super().__init__(*animations, lag_ratio=lag_ratio, **kwargs)
def begin(self) -> None:
assert len(self.animations) > 0
self.update_active_animation(0)
def finish(self) -> None:
while self.active_animation is not None:
self.next_animation()
def update_mobjects(self, dt: float) -> None:
if self.active_animation:
self.active_animation.update_mobjects(dt)
def _setup_scene(self, scene) -> None:
if scene is None:
return
if self.is_introducer():
for anim in self.animations:
if not anim.is_introducer() and anim.mobject is not None:
scene.add(anim.mobject)
self.scene = scene
def update_active_animation(self, index: int) -> None:
self.active_index = index
if index >= len(self.animations):
self.active_animation: Animation | None = None
self.active_start_time: float | None = None
self.active_end_time: float | None = None
else:
self.active_animation = self.animations[index]
self.active_animation._setup_scene(self.scene)
self.active_animation.begin()
self.active_start_time = self.anims_with_timings[index][1]
self.active_end_time = self.anims_with_timings[index][2]
def next_animation(self) -> None:
"""Proceeds to the next animation.
This method is called right when the active animation finishes.
"""
if self.active_animation is not None:
self.active_animation.finish()
self.update_active_animation(self.active_index + 1)
def interpolate(self, alpha: float) -> None:
current_time = self.rate_func(alpha) * self.max_end_time
while 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:
elapsed = current_time - self.active_start_time
active_run_time = self.active_animation.get_run_time()
subalpha = elapsed / active_run_time if active_run_time != 0.0 else 1.0
self.active_animation.interpolate(subalpha)
class LaggedStart(AnimationGroup):
"""Adjusts the timing of a series of :class:`~.Animation` according to ``lag_ratio``.
Parameters
----------
animations
Sequence of :class:`~.Animation` objects to be played.
lag_ratio
Defines the delay after which the animation is applied to submobjects. A lag_ratio of
``n.nn`` means the next animation will play when ``nnn%`` of the current animation has played.
Defaults to 0.05, meaning that the next animation will begin when 5% of the current
animation has played.
This does not influence the total runtime of the animation. Instead the runtime
of individual animations is adjusted so that the complete animation has the defined
run time.
Examples
--------
.. manim:: LaggedStartExample
class LaggedStartExample(Scene):
def construct(self):
title = Text("lag_ratio = 0.25").to_edge(UP)
dot1 = Dot(point=LEFT * 2 + UP, radius=0.16)
dot2 = Dot(point=LEFT * 2, radius=0.16)
dot3 = Dot(point=LEFT * 2 + DOWN, radius=0.16)
line_25 = DashedLine(
start=LEFT + UP * 2,
end=LEFT + DOWN * 2,
color=RED
)
label = Text("25%", font_size=24).next_to(line_25, UP)
self.add(title, dot1, dot2, dot3, line_25, label)
self.play(LaggedStart(
dot1.animate.shift(RIGHT * 4),
dot2.animate.shift(RIGHT * 4),
dot3.animate.shift(RIGHT * 4),
lag_ratio=0.25,
run_time=4
))
"""
def __init__(
self,
*animations: Animation,
lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO,
**kwargs,
):
super().__init__(*animations, lag_ratio=lag_ratio, **kwargs)
class LaggedStartMap(LaggedStart):
"""Plays a series of :class:`~.Animation` while mapping a function to submobjects.
Parameters
----------
AnimationClass
:class:`~.Animation` to apply to mobject.
mobject
:class:`~.Mobject` whose submobjects the animation, and optionally the function,
are to be applied.
arg_creator
Function which will be applied to :class:`~.Mobject`.
run_time
The duration of the animation in seconds.
Examples
--------
.. manim:: LaggedStartMapExample
class LaggedStartMapExample(Scene):
def construct(self):
title = Tex("LaggedStartMap").to_edge(UP, buff=LARGE_BUFF)
dots = VGroup(
*[Dot(radius=0.16) for _ in range(35)]
).arrange_in_grid(rows=5, cols=7, buff=MED_LARGE_BUFF)
self.add(dots, title)
# Animate yellow ripple effect
for mob in dots, title:
self.play(LaggedStartMap(
ApplyMethod, mob,
lambda m : (m.set_color, YELLOW),
lag_ratio = 0.1,
rate_func = there_and_back,
run_time = 2
))
"""
def __init__(
self,
AnimationClass: Callable[..., Animation],
mobject: Mobject,
arg_creator: Callable[[Mobject], str] = None,
run_time: float = 2,
**kwargs,
) -> None:
args_list = []
for submob in mobject:
if arg_creator:
args_list.append(arg_creator(submob))
else:
args_list.append((submob,))
anim_kwargs = dict(kwargs)
if "lag_ratio" in anim_kwargs:
anim_kwargs.pop("lag_ratio")
animations = [AnimationClass(*args, **anim_kwargs) for args in args_list]
super().__init__(*animations, run_time=run_time, **kwargs)
|
manim_ManimCommunity/manim/animation/__init__.py
| |
manim_ManimCommunity/manim/animation/transform_matching_parts.py
|
"""Animations that try to transform Mobjects while keeping track of identical parts."""
from __future__ import annotations
__all__ = ["TransformMatchingShapes", "TransformMatchingTex"]
from typing import TYPE_CHECKING
import numpy as np
from manim.mobject.opengl.opengl_mobject import OpenGLGroup, OpenGLMobject
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVGroup, OpenGLVMobject
from .._config import config
from ..constants import RendererType
from ..mobject.mobject import Group, Mobject
from ..mobject.types.vectorized_mobject import VGroup, VMobject
from .composition import AnimationGroup
from .fading import FadeIn, FadeOut
from .transform import FadeTransformPieces, Transform
if TYPE_CHECKING:
from ..scene.scene import Scene
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: dict | None = None,
**kwargs,
):
if isinstance(mobject, OpenGLVMobject):
group_type = OpenGLVGroup
elif isinstance(mobject, OpenGLMobject):
group_type = OpenGLGroup
elif 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])
fade_target_copy = fade_target.copy()
if transform_mismatches:
if "replace_mobject_with_target_in_scene" not in kwargs:
kwargs["replace_mobject_with_target_in_scene"] = True
anims.append(Transform(fade_source, fade_target, **kwargs))
elif fade_transform_mismatches:
anims.append(FadeTransformPieces(fade_source, fade_target, **kwargs))
else:
anims.append(FadeOut(fade_source, target_position=fade_target, **kwargs))
anims.append(
FadeIn(fade_target_copy, target_position=fade_target, **kwargs),
)
super().__init__(*anims)
self.to_remove = [mobject, fade_target_copy]
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:
if config["renderer"] == RendererType.OPENGL:
shape_map[key] = OpenGLVGroup()
else:
shape_map[key] = VGroup()
shape_map[key].add(sm)
return shape_map
def clean_up_from_scene(self, scene: Scene) -> None:
# Interpolate all animations back to 0 to ensure source mobjects remain unchanged.
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: dict | None = 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.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):
variables = VGroup(MathTex("a"), MathTex("b"), MathTex("c")).arrange_submobjects().shift(UP)
eq1 = MathTex("{{x}}^2", "+", "{{y}}^2", "=", "{{z}}^2")
eq2 = MathTex("{{a}}^2", "+", "{{b}}^2", "=", "{{c}}^2")
eq3 = MathTex("{{a}}^2", "=", "{{c}}^2", "-", "{{b}}^2")
self.add(eq1)
self.wait(0.5)
self.play(TransformMatchingTex(Group(eq1, variables), eq2))
self.wait(0.5)
self.play(TransformMatchingTex(eq2, eq3))
self.wait(0.5)
"""
def __init__(
self,
mobject: Mobject,
target_mobject: Mobject,
transform_mismatches: bool = False,
fade_transform_mismatches: bool = False,
key_map: dict | None = 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]:
if isinstance(mobject, (Group, VGroup, OpenGLGroup, OpenGLVGroup)):
return [
p
for s in mobject.submobjects
for p in TransformMatchingTex.get_mobject_parts(s)
]
else:
assert hasattr(mobject, "tex_string")
return mobject.submobjects
@staticmethod
def get_mobject_key(mobject: Mobject) -> str:
return mobject.tex_string
|
manim_ManimCommunity/manim/animation/creation.py
|
r"""Animate the display or removal of a mobject from a scene.
.. manim:: CreationModule
:hide_source:
from manim import ManimBanner
class CreationModule(Scene):
def construct(self):
s1 = Square()
s2 = Square()
s3 = Square()
s4 = Square()
VGroup(s1, s2, s3, s4).set_x(0).arrange(buff=1.9).shift(UP)
s5 = Square()
s6 = Square()
s7 = Square()
VGroup(s5, s6, s7).set_x(0).arrange(buff=2.6).shift(2 * DOWN)
t1 = Text("Write", font_size=24).next_to(s1, UP)
t2 = Text("AddTextLetterByLetter", font_size=24).next_to(s2, UP)
t3 = Text("Create", font_size=24).next_to(s3, UP)
t4 = Text("Uncreate", font_size=24).next_to(s4, UP)
t5 = Text("DrawBorderThenFill", font_size=24).next_to(s5, UP)
t6 = Text("ShowIncreasingSubsets", font_size=22).next_to(s6, UP)
t7 = Text("ShowSubmobjectsOneByOne", font_size=22).next_to(s7, UP)
self.add(s1, s2, s3, s4, s5, s6, s7, t1, t2, t3, t4, t5, t6, t7)
texts = [Text("manim", font_size=29), Text("manim", font_size=29)]
texts[0].move_to(s1.get_center())
texts[1].move_to(s2.get_center())
self.add(*texts)
objs = [ManimBanner().scale(0.25) for _ in range(5)]
objs[0].move_to(s3.get_center())
objs[1].move_to(s4.get_center())
objs[2].move_to(s5.get_center())
objs[3].move_to(s6.get_center())
objs[4].move_to(s7.get_center())
self.add(*objs)
self.play(
# text creation
Write(texts[0]),
AddTextLetterByLetter(texts[1]),
# mobject creation
Create(objs[0]),
Uncreate(objs[1]),
DrawBorderThenFill(objs[2]),
ShowIncreasingSubsets(objs[3]),
ShowSubmobjectsOneByOne(objs[4]),
run_time=3,
)
self.wait()
"""
from __future__ import annotations
__all__ = [
"Create",
"Uncreate",
"DrawBorderThenFill",
"Write",
"Unwrite",
"ShowPartial",
"ShowIncreasingSubsets",
"SpiralIn",
"AddTextLetterByLetter",
"RemoveTextLetterByLetter",
"ShowSubmobjectsOneByOne",
"AddTextWordByWord",
]
import itertools as it
from typing import TYPE_CHECKING, Callable, Iterable, Sequence
import numpy as np
if TYPE_CHECKING:
from manim.mobject.text.text_mobject import Text
from manim.mobject.opengl.opengl_surface import OpenGLSurface
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject
from manim.utils.color import ManimColor
from .. import config
from ..animation.animation import Animation
from ..animation.composition import Succession
from ..constants import TAU
from ..mobject.mobject import Group, Mobject
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.bezier import integer_interpolate
from ..utils.rate_functions import double_smooth, linear
class ShowPartial(Animation):
"""Abstract class for Animations that show the VMobject partially.
Raises
------
:class:`TypeError`
If ``mobject`` is not an instance of :class:`~.VMobject`.
See Also
--------
:class:`Create`, :class:`~.ShowPassingFlash`
"""
def __init__(
self,
mobject: VMobject | OpenGLVMobject | OpenGLSurface | None,
**kwargs,
):
pointwise = getattr(mobject, "pointwise_become_partial", None)
if not callable(pointwise):
raise NotImplementedError("This animation is not defined for this Mobject.")
super().__init__(mobject, **kwargs)
def interpolate_submobject(
self,
submobject: Mobject,
starting_submobject: Mobject,
alpha: float,
) -> None:
submobject.pointwise_become_partial(
starting_submobject, *self._get_bounds(alpha)
)
def _get_bounds(self, alpha: float) -> None:
raise NotImplementedError("Please use Create or ShowPassingFlash")
class Create(ShowPartial):
"""Incrementally show a VMobject.
Parameters
----------
mobject
The VMobject to animate.
Raises
------
:class:`TypeError`
If ``mobject`` is not an instance of :class:`~.VMobject`.
Examples
--------
.. manim:: CreateScene
class CreateScene(Scene):
def construct(self):
self.play(Create(Square()))
See Also
--------
:class:`~.ShowPassingFlash`
"""
def __init__(
self,
mobject: VMobject | OpenGLVMobject | OpenGLSurface,
lag_ratio: float = 1.0,
introducer: bool = True,
**kwargs,
) -> None:
super().__init__(mobject, lag_ratio=lag_ratio, introducer=introducer, **kwargs)
def _get_bounds(self, alpha: float) -> tuple[int, float]:
return (0, alpha)
class Uncreate(Create):
"""Like :class:`Create` but in reverse.
Examples
--------
.. manim:: ShowUncreate
class ShowUncreate(Scene):
def construct(self):
self.play(Uncreate(Square()))
See Also
--------
:class:`Create`
"""
def __init__(
self,
mobject: VMobject | OpenGLVMobject,
reverse_rate_function: bool = True,
remover: bool = True,
**kwargs,
) -> None:
super().__init__(
mobject,
reverse_rate_function=reverse_rate_function,
introducer=False,
remover=remover,
**kwargs,
)
class DrawBorderThenFill(Animation):
"""Draw the border first and then show the fill.
Examples
--------
.. manim:: ShowDrawBorderThenFill
class ShowDrawBorderThenFill(Scene):
def construct(self):
self.play(DrawBorderThenFill(Square(fill_opacity=1, fill_color=ORANGE)))
"""
def __init__(
self,
vmobject: VMobject | OpenGLVMobject,
run_time: float = 2,
rate_func: Callable[[float], float] = double_smooth,
stroke_width: float = 2,
stroke_color: str = None,
draw_border_animation_config: dict = {}, # what does this dict accept?
fill_animation_config: dict = {},
introducer: bool = True,
**kwargs,
) -> None:
self._typecheck_input(vmobject)
super().__init__(
vmobject,
run_time=run_time,
introducer=introducer,
rate_func=rate_func,
**kwargs,
)
self.stroke_width = stroke_width
self.stroke_color = stroke_color
self.draw_border_animation_config = draw_border_animation_config
self.fill_animation_config = fill_animation_config
self.outline = self.get_outline()
def _typecheck_input(self, vmobject: VMobject | OpenGLVMobject) -> None:
if not isinstance(vmobject, (VMobject, OpenGLVMobject)):
raise TypeError("DrawBorderThenFill only works for vectorized Mobjects")
def begin(self) -> None:
self.outline = self.get_outline()
super().begin()
def get_outline(self) -> Mobject:
outline = self.mobject.copy()
outline.set_fill(opacity=0)
for sm in outline.family_members_with_points():
sm.set_stroke(color=self.get_stroke_color(sm), width=self.stroke_width)
return outline
def get_stroke_color(self, vmobject: VMobject | OpenGLVMobject) -> ManimColor:
if self.stroke_color:
return self.stroke_color
elif vmobject.get_stroke_width() > 0:
return vmobject.get_stroke_color()
return vmobject.get_color()
def get_all_mobjects(self) -> Sequence[Mobject]:
return [*super().get_all_mobjects(), self.outline]
def interpolate_submobject(
self,
submobject: Mobject,
starting_submobject: Mobject,
outline,
alpha: float,
) -> None: # Fixme: not matching the parent class? What is outline doing here?
index: int
subalpha: int
index, subalpha = integer_interpolate(0, 2, alpha)
if index == 0:
submobject.pointwise_become_partial(outline, 0, subalpha)
submobject.match_style(outline)
else:
submobject.interpolate(outline, starting_submobject, subalpha)
class Write(DrawBorderThenFill):
"""Simulate hand-writing a :class:`~.Text` or hand-drawing a :class:`~.VMobject`.
Examples
--------
.. manim:: ShowWrite
class ShowWrite(Scene):
def construct(self):
self.play(Write(Text("Hello", font_size=144)))
.. manim:: ShowWriteReversed
class ShowWriteReversed(Scene):
def construct(self):
self.play(Write(Text("Hello", font_size=144), reverse=True, remover=False))
Tests
-----
Check that creating empty :class:`.Write` animations works::
>>> from manim import Write, Text
>>> Write(Text(''))
Write(Text(''))
"""
def __init__(
self,
vmobject: VMobject | OpenGLVMobject,
rate_func: Callable[[float], float] = linear,
reverse: bool = False,
**kwargs,
) -> None:
run_time: float | None = kwargs.pop("run_time", None)
lag_ratio: float | None = kwargs.pop("lag_ratio", None)
run_time, lag_ratio = self._set_default_config_from_length(
vmobject,
run_time,
lag_ratio,
)
self.reverse = reverse
if "remover" not in kwargs:
kwargs["remover"] = reverse
super().__init__(
vmobject,
rate_func=rate_func,
run_time=run_time,
lag_ratio=lag_ratio,
introducer=not reverse,
**kwargs,
)
def _set_default_config_from_length(
self,
vmobject: VMobject | OpenGLVMobject,
run_time: float | None,
lag_ratio: float | None,
) -> tuple[float, float]:
length = len(vmobject.family_members_with_points())
if run_time is None:
if length < 15:
run_time = 1
else:
run_time = 2
if lag_ratio is None:
lag_ratio = min(4.0 / max(1.0, length), 0.2)
return run_time, lag_ratio
def reverse_submobjects(self) -> None:
self.mobject.invert(recursive=True)
def begin(self) -> None:
if self.reverse:
self.reverse_submobjects()
super().begin()
def finish(self) -> None:
super().finish()
if self.reverse:
self.reverse_submobjects()
class Unwrite(Write):
"""Simulate erasing by hand a :class:`~.Text` or a :class:`~.VMobject`.
Parameters
----------
reverse
Set True to have the animation start erasing from the last submobject first.
Examples
--------
.. manim :: UnwriteReverseTrue
class UnwriteReverseTrue(Scene):
def construct(self):
text = Tex("Alice and Bob").scale(3)
self.add(text)
self.play(Unwrite(text))
.. manim:: UnwriteReverseFalse
class UnwriteReverseFalse(Scene):
def construct(self):
text = Tex("Alice and Bob").scale(3)
self.add(text)
self.play(Unwrite(text, reverse=False))
"""
def __init__(
self,
vmobject: VMobject,
rate_func: Callable[[float], float] = linear,
reverse: bool = True,
**kwargs,
) -> None:
run_time: float | None = kwargs.pop("run_time", None)
lag_ratio: float | None = kwargs.pop("lag_ratio", None)
run_time, lag_ratio = self._set_default_config_from_length(
vmobject,
run_time,
lag_ratio,
)
super().__init__(
vmobject,
run_time=run_time,
lag_ratio=lag_ratio,
reverse_rate_function=True,
reverse=reverse,
**kwargs,
)
class SpiralIn(Animation):
r"""Create the Mobject with sub-Mobjects flying in on spiral trajectories.
Parameters
----------
shapes
The Mobject on which to be operated.
scale_factor
The factor used for scaling the effect.
fade_in_fraction
Fractional duration of initial fade-in of sub-Mobjects as they fly inward.
Examples
--------
.. manim :: SpiralInExample
class SpiralInExample(Scene):
def construct(self):
pi = MathTex(r"\pi").scale(7)
pi.shift(2.25 * LEFT + 1.5 * UP)
circle = Circle(color=GREEN_C, fill_opacity=1).shift(LEFT)
square = Square(color=BLUE_D, fill_opacity=1).shift(UP)
shapes = VGroup(pi, circle, square)
self.play(SpiralIn(shapes))
"""
def __init__(
self,
shapes: Mobject,
scale_factor: float = 8,
fade_in_fraction=0.3,
**kwargs,
) -> None:
self.shapes = shapes
self.scale_factor = scale_factor
self.shape_center = shapes.get_center()
self.fade_in_fraction = fade_in_fraction
for shape in shapes:
shape.final_position = shape.get_center()
shape.initial_position = (
shape.final_position
+ (shape.final_position - self.shape_center) * self.scale_factor
)
shape.move_to(shape.initial_position)
shape.save_state()
super().__init__(shapes, introducer=True, **kwargs)
def interpolate_mobject(self, alpha: float) -> None:
alpha = self.rate_func(alpha)
for shape in self.shapes:
shape.restore()
shape.save_state()
opacity = shape.get_fill_opacity()
new_opacity = min(opacity, alpha * opacity / self.fade_in_fraction)
shape.shift((shape.final_position - shape.initial_position) * alpha)
shape.rotate(TAU * alpha, about_point=self.shape_center)
shape.rotate(-TAU * alpha, about_point=shape.get_center_of_mass())
shape.set_opacity(new_opacity)
class ShowIncreasingSubsets(Animation):
"""Show one submobject at a time, leaving all previous ones displayed on screen.
Examples
--------
.. manim:: ShowIncreasingSubsetsScene
class ShowIncreasingSubsetsScene(Scene):
def construct(self):
p = VGroup(Dot(), Square(), Triangle())
self.add(p)
self.play(ShowIncreasingSubsets(p))
self.wait()
"""
def __init__(
self,
group: Mobject,
suspend_mobject_updating: bool = False,
int_func: Callable[[np.ndarray], np.ndarray] = np.floor,
reverse_rate_function=False,
**kwargs,
) -> None:
self.all_submobs = list(group.submobjects)
self.int_func = int_func
for mobj in self.all_submobs:
mobj.set_opacity(0)
super().__init__(
group,
suspend_mobject_updating=suspend_mobject_updating,
reverse_rate_function=reverse_rate_function,
**kwargs,
)
def interpolate_mobject(self, alpha: float) -> None:
n_submobs = len(self.all_submobs)
value = (
1 - self.rate_func(alpha)
if self.reverse_rate_function
else self.rate_func(alpha)
)
index = int(self.int_func(value * n_submobs))
self.update_submobject_list(index)
def update_submobject_list(self, index: int) -> None:
for mobj in self.all_submobs[:index]:
mobj.set_opacity(1)
for mobj in self.all_submobs[index:]:
mobj.set_opacity(0)
class AddTextLetterByLetter(ShowIncreasingSubsets):
"""Show a :class:`~.Text` letter by letter on the scene.
Parameters
----------
time_per_char
Frequency of appearance of the letters.
.. tip::
This is currently only possible for class:`~.Text` and not for class:`~.MathTex`
"""
def __init__(
self,
text: Text,
suspend_mobject_updating: bool = False,
int_func: Callable[[np.ndarray], np.ndarray] = np.ceil,
rate_func: Callable[[float], float] = linear,
time_per_char: float = 0.1,
run_time: float | None = None,
reverse_rate_function=False,
introducer=True,
**kwargs,
) -> None:
self.time_per_char = time_per_char
# Check for empty text using family_members_with_points()
if not text.family_members_with_points():
raise ValueError(
f"The text mobject {text} does not seem to contain any characters."
)
if run_time is None:
# minimum time per character is 1/frame_rate, otherwise
# the animation does not finish.
run_time = np.max((1 / config.frame_rate, self.time_per_char)) * len(text)
super().__init__(
text,
suspend_mobject_updating=suspend_mobject_updating,
int_func=int_func,
rate_func=rate_func,
run_time=run_time,
reverse_rate_function=reverse_rate_function,
introducer=introducer,
**kwargs,
)
class RemoveTextLetterByLetter(AddTextLetterByLetter):
"""Remove a :class:`~.Text` letter by letter from the scene.
Parameters
----------
time_per_char
Frequency of appearance of the letters.
.. tip::
This is currently only possible for class:`~.Text` and not for class:`~.MathTex`
"""
def __init__(
self,
text: Text,
suspend_mobject_updating: bool = False,
int_func: Callable[[np.ndarray], np.ndarray] = np.ceil,
rate_func: Callable[[float], float] = linear,
time_per_char: float = 0.1,
run_time: float | None = None,
reverse_rate_function=True,
introducer=False,
remover=True,
**kwargs,
) -> None:
super().__init__(
text,
suspend_mobject_updating=suspend_mobject_updating,
int_func=int_func,
rate_func=rate_func,
time_per_char=time_per_char,
run_time=run_time,
reverse_rate_function=reverse_rate_function,
introducer=introducer,
remover=remover,
**kwargs,
)
class ShowSubmobjectsOneByOne(ShowIncreasingSubsets):
"""Show one submobject at a time, removing all previously displayed ones from screen."""
def __init__(
self,
group: Iterable[Mobject],
int_func: Callable[[np.ndarray], np.ndarray] = np.ceil,
**kwargs,
) -> None:
new_group = Group(*group)
super().__init__(new_group, int_func=int_func, **kwargs)
def update_submobject_list(self, index: int) -> None:
current_submobjects = self.all_submobs[:index]
for mobj in current_submobjects[:-1]:
mobj.set_opacity(0)
if len(current_submobjects) > 0:
current_submobjects[-1].set_opacity(1)
# TODO, this is broken...
class AddTextWordByWord(Succession):
"""Show a :class:`~.Text` word by word on the scene. Note: currently broken."""
def __init__(
self,
text_mobject: Text,
run_time: float = None,
time_per_char: float = 0.06,
**kwargs,
) -> None:
self.time_per_char = time_per_char
tpc = self.time_per_char
anims = it.chain(
*(
[
ShowIncreasingSubsets(word, run_time=tpc * len(word)),
Animation(word, run_time=0.005 * len(word) ** 1.5),
]
for word in text_mobject
)
)
super().__init__(*anims, **kwargs)
|
manim_ManimCommunity/manim/animation/movement.py
|
"""Animations related to movement."""
from __future__ import annotations
__all__ = [
"Homotopy",
"SmoothedVectorizedHomotopy",
"ComplexHomotopy",
"PhaseFlow",
"MoveAlongPath",
]
from typing import TYPE_CHECKING, Any, Callable
import numpy as np
from ..animation.animation import Animation
from ..utils.rate_functions import linear
if TYPE_CHECKING:
from ..mobject.mobject import Mobject, VMobject
class Homotopy(Animation):
"""A Homotopy.
This is an animation transforming the points of a mobject according
to the specified transformation function. With the parameter :math:`t`
moving from 0 to 1 throughout the animation and :math:`(x, y, z)`
describing the coordinates of the point of a mobject,
the function passed to the ``homotopy`` keyword argument should
transform the tuple :math:`(x, y, z, t)` to :math:`(x', y', z')`,
the coordinates the original point is transformed to at time :math:`t`.
Parameters
----------
homotopy
A function mapping :math:`(x, y, z, t)` to :math:`(x', y', z')`.
mobject
The mobject transformed under the given homotopy.
run_time
The run time of the animation.
apply_function_kwargs
Keyword arguments propagated to :meth:`.Mobject.apply_function`.
kwargs
Further keyword arguments passed to the parent class.
"""
def __init__(
self,
homotopy: Callable[[float, float, float, float], tuple[float, float, float]],
mobject: Mobject,
run_time: float = 3,
apply_function_kwargs: dict[str, Any] | None = None,
**kwargs,
) -> None:
self.homotopy = homotopy
self.apply_function_kwargs = (
apply_function_kwargs if apply_function_kwargs is not None else {}
)
super().__init__(mobject, run_time=run_time, **kwargs)
def function_at_time_t(self, t: float) -> tuple[float, float, float]:
return lambda p: self.homotopy(*p, t)
def interpolate_submobject(
self,
submobject: Mobject,
starting_submobject: Mobject,
alpha: float,
) -> None:
submobject.points = starting_submobject.points
submobject.apply_function(
self.function_at_time_t(alpha), **self.apply_function_kwargs
)
class SmoothedVectorizedHomotopy(Homotopy):
def interpolate_submobject(
self,
submobject: Mobject,
starting_submobject: Mobject,
alpha: float,
) -> None:
super().interpolate_submobject(submobject, starting_submobject, alpha)
submobject.make_smooth()
class ComplexHomotopy(Homotopy):
def __init__(
self, complex_homotopy: Callable[[complex], float], mobject: Mobject, **kwargs
) -> None:
"""
Complex Homotopy a function Cx[0, 1] to C
"""
def homotopy(
x: float,
y: float,
z: float,
t: float,
) -> tuple[float, float, float]:
c = complex_homotopy(complex(x, y), t)
return (c.real, c.imag, z)
super().__init__(homotopy, mobject, **kwargs)
class PhaseFlow(Animation):
def __init__(
self,
function: Callable[[np.ndarray], np.ndarray],
mobject: Mobject,
virtual_time: float = 1,
suspend_mobject_updating: bool = False,
rate_func: Callable[[float], float] = linear,
**kwargs,
) -> None:
self.virtual_time = virtual_time
self.function = function
super().__init__(
mobject,
suspend_mobject_updating=suspend_mobject_updating,
rate_func=rate_func,
**kwargs,
)
def interpolate_mobject(self, alpha: float) -> None:
if hasattr(self, "last_alpha"):
dt = self.virtual_time * (
self.rate_func(alpha) - self.rate_func(self.last_alpha)
)
self.mobject.apply_function(lambda p: p + dt * self.function(p))
self.last_alpha = alpha
class MoveAlongPath(Animation):
"""Make one mobject move along the path of another mobject.
.. manim:: MoveAlongPathExample
class MoveAlongPathExample(Scene):
def construct(self):
d1 = Dot().set_color(ORANGE)
l1 = Line(LEFT, RIGHT)
l2 = VMobject()
self.add(d1, l1, l2)
l2.add_updater(lambda x: x.become(Line(LEFT, d1.get_center()).set_color(ORANGE)))
self.play(MoveAlongPath(d1, l1), rate_func=linear)
"""
def __init__(
self,
mobject: Mobject,
path: VMobject,
suspend_mobject_updating: bool | None = False,
**kwargs,
) -> None:
self.path = path
super().__init__(
mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs
)
def interpolate_mobject(self, alpha: float) -> None:
point = self.path.point_from_proportion(self.rate_func(alpha))
self.mobject.move_to(point)
|
manim_ManimCommunity/manim/animation/changing.py
|
"""Animation of a mobject boundary and tracing of points."""
from __future__ import annotations
__all__ = ["AnimatedBoundary", "TracedPath"]
from typing import Callable
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.types.vectorized_mobject import VGroup, VMobject
from manim.utils.color import (
BLUE_B,
BLUE_D,
BLUE_E,
GREY_BROWN,
WHITE,
ParsableManimColor,
)
from manim.utils.rate_functions import smooth
class AnimatedBoundary(VGroup):
"""Boundary of a :class:`.VMobject` with animated color change.
Examples
--------
.. manim:: AnimatedBoundaryExample
class AnimatedBoundaryExample(Scene):
def construct(self):
text = Text("So shiny!")
boundary = AnimatedBoundary(text, colors=[RED, GREEN, BLUE],
cycle_rate=3)
self.add(text, boundary)
self.wait(2)
"""
def __init__(
self,
vmobject,
colors=[BLUE_D, BLUE_B, BLUE_E, GREY_BROWN],
max_stroke_width=3,
cycle_rate=0.5,
back_and_forth=True,
draw_rate_func=smooth,
fade_rate_func=smooth,
**kwargs,
):
super().__init__(**kwargs)
self.colors = colors
self.max_stroke_width = max_stroke_width
self.cycle_rate = cycle_rate
self.back_and_forth = back_and_forth
self.draw_rate_func = draw_rate_func
self.fade_rate_func = fade_rate_func
self.vmobject = vmobject
self.boundary_copies = [
vmobject.copy().set_style(stroke_width=0, fill_opacity=0) for x in range(2)
]
self.add(*self.boundary_copies)
self.total_time = 0
self.add_updater(lambda m, dt: self.update_boundary_copies(dt))
def update_boundary_copies(self, dt):
# Not actual time, but something which passes at
# an altered rate to make the implementation below
# cleaner
time = self.total_time * self.cycle_rate
growing, fading = self.boundary_copies
colors = self.colors
msw = self.max_stroke_width
vmobject = self.vmobject
index = int(time % len(colors))
alpha = time % 1
draw_alpha = self.draw_rate_func(alpha)
fade_alpha = self.fade_rate_func(alpha)
if self.back_and_forth and int(time) % 2 == 1:
bounds = (1 - draw_alpha, 1)
else:
bounds = (0, draw_alpha)
self.full_family_become_partial(growing, vmobject, *bounds)
growing.set_stroke(colors[index], width=msw)
if time >= 1:
self.full_family_become_partial(fading, vmobject, 0, 1)
fading.set_stroke(color=colors[index - 1], width=(1 - fade_alpha) * msw)
self.total_time += dt
def full_family_become_partial(self, mob1, mob2, a, b):
family1 = mob1.family_members_with_points()
family2 = mob2.family_members_with_points()
for sm1, sm2 in zip(family1, family2):
sm1.pointwise_become_partial(sm2, a, b)
return self
class TracedPath(VMobject, metaclass=ConvertToOpenGL):
"""Traces the path of a point returned by a function call.
Parameters
----------
traced_point_func
The function to be traced.
stroke_width
The width of the trace.
stroke_color
The color of the trace.
dissipating_time
The time taken for the path to dissipate. Default set to ``None``
which disables dissipation.
Examples
--------
.. manim:: TracedPathExample
class TracedPathExample(Scene):
def construct(self):
circ = Circle(color=RED).shift(4*LEFT)
dot = Dot(color=RED).move_to(circ.get_start())
rolling_circle = VGroup(circ, dot)
trace = TracedPath(circ.get_start)
rolling_circle.add_updater(lambda m: m.rotate(-0.3))
self.add(trace, rolling_circle)
self.play(rolling_circle.animate.shift(8*RIGHT), run_time=4, rate_func=linear)
.. manim:: DissipatingPathExample
class DissipatingPathExample(Scene):
def construct(self):
a = Dot(RIGHT * 2)
b = TracedPath(a.get_center, dissipating_time=0.5, stroke_opacity=[0, 1])
self.add(a, b)
self.play(a.animate(path_arc=PI / 4).shift(LEFT * 2))
self.play(a.animate(path_arc=-PI / 4).shift(LEFT * 2))
self.wait()
"""
def __init__(
self,
traced_point_func: Callable,
stroke_width: float = 2,
stroke_color: ParsableManimColor | None = WHITE,
dissipating_time: float | None = None,
**kwargs,
):
super().__init__(stroke_color=stroke_color, stroke_width=stroke_width, **kwargs)
self.traced_point_func = traced_point_func
self.dissipating_time = dissipating_time
self.time = 1 if self.dissipating_time else None
self.add_updater(self.update_path)
def update_path(self, mob, dt):
new_point = self.traced_point_func()
if not self.has_points():
self.start_new_path(new_point)
self.add_line_to(new_point)
if self.dissipating_time:
self.time += dt
if self.time - 1 > self.dissipating_time:
nppcc = self.n_points_per_curve
self.set_points(self.points[nppcc:])
|
manim_ManimCommunity/manim/animation/growing.py
|
"""Animations that introduce mobjects to scene by growing them from points.
.. manim:: Growing
class Growing(Scene):
def construct(self):
square = Square()
circle = Circle()
triangle = Triangle()
arrow = Arrow(LEFT, RIGHT)
star = Star()
VGroup(square, circle, triangle).set_x(0).arrange(buff=1.5).set_y(2)
VGroup(arrow, star).move_to(DOWN).set_x(0).arrange(buff=1.5).set_y(-2)
self.play(GrowFromPoint(square, ORIGIN))
self.play(GrowFromCenter(circle))
self.play(GrowFromEdge(triangle, DOWN))
self.play(GrowArrow(arrow))
self.play(SpinInFromNothing(star))
"""
from __future__ import annotations
__all__ = [
"GrowFromPoint",
"GrowFromCenter",
"GrowFromEdge",
"GrowArrow",
"SpinInFromNothing",
]
import typing
import numpy as np
from ..animation.transform import Transform
from ..constants import PI
from ..utils.paths import spiral_path
if typing.TYPE_CHECKING:
from manim.mobject.geometry.line import Arrow
from ..mobject.mobject import Mobject
class GrowFromPoint(Transform):
"""Introduce an :class:`~.Mobject` by growing it from a point.
Parameters
----------
mobject
The mobjects to be introduced.
point
The point from which the mobject grows.
point_color
Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.
Examples
--------
.. manim :: GrowFromPointExample
class GrowFromPointExample(Scene):
def construct(self):
dot = Dot(3 * UR, color=GREEN)
squares = [Square() for _ in range(4)]
VGroup(*squares).set_x(0).arrange(buff=1)
self.add(dot)
self.play(GrowFromPoint(squares[0], ORIGIN))
self.play(GrowFromPoint(squares[1], [-2, 2, 0]))
self.play(GrowFromPoint(squares[2], [3, -2, 0], RED))
self.play(GrowFromPoint(squares[3], dot, dot.get_color()))
"""
def __init__(
self, mobject: Mobject, point: np.ndarray, point_color: str = None, **kwargs
) -> None:
self.point = point
self.point_color = point_color
super().__init__(mobject, introducer=True, **kwargs)
def create_target(self) -> Mobject:
return self.mobject
def create_starting_mobject(self) -> Mobject:
start = super().create_starting_mobject()
start.scale(0)
start.move_to(self.point)
if self.point_color:
start.set_color(self.point_color)
return start
class GrowFromCenter(GrowFromPoint):
"""Introduce an :class:`~.Mobject` by growing it from its center.
Parameters
----------
mobject
The mobjects to be introduced.
point_color
Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.
Examples
--------
.. manim :: GrowFromCenterExample
class GrowFromCenterExample(Scene):
def construct(self):
squares = [Square() for _ in range(2)]
VGroup(*squares).set_x(0).arrange(buff=2)
self.play(GrowFromCenter(squares[0]))
self.play(GrowFromCenter(squares[1], point_color=RED))
"""
def __init__(self, mobject: Mobject, point_color: str = None, **kwargs) -> None:
point = mobject.get_center()
super().__init__(mobject, point, point_color=point_color, **kwargs)
class GrowFromEdge(GrowFromPoint):
"""Introduce an :class:`~.Mobject` by growing it from one of its bounding box edges.
Parameters
----------
mobject
The mobjects to be introduced.
edge
The direction to seek bounding box edge of mobject.
point_color
Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.
Examples
--------
.. manim :: GrowFromEdgeExample
class GrowFromEdgeExample(Scene):
def construct(self):
squares = [Square() for _ in range(4)]
VGroup(*squares).set_x(0).arrange(buff=1)
self.play(GrowFromEdge(squares[0], DOWN))
self.play(GrowFromEdge(squares[1], RIGHT))
self.play(GrowFromEdge(squares[2], UR))
self.play(GrowFromEdge(squares[3], UP, point_color=RED))
"""
def __init__(
self, mobject: Mobject, edge: np.ndarray, point_color: str = None, **kwargs
) -> None:
point = mobject.get_critical_point(edge)
super().__init__(mobject, point, point_color=point_color, **kwargs)
class GrowArrow(GrowFromPoint):
"""Introduce an :class:`~.Arrow` by growing it from its start toward its tip.
Parameters
----------
arrow
The arrow to be introduced.
point_color
Initial color of the arrow before growing to its full size. Leave empty to match arrow's color.
Examples
--------
.. manim :: GrowArrowExample
class GrowArrowExample(Scene):
def construct(self):
arrows = [Arrow(2 * LEFT, 2 * RIGHT), Arrow(2 * DR, 2 * UL)]
VGroup(*arrows).set_x(0).arrange(buff=2)
self.play(GrowArrow(arrows[0]))
self.play(GrowArrow(arrows[1], point_color=RED))
"""
def __init__(self, arrow: Arrow, point_color: str = None, **kwargs) -> None:
point = arrow.get_start()
super().__init__(arrow, point, point_color=point_color, **kwargs)
def create_starting_mobject(self) -> Mobject:
start_arrow = self.mobject.copy()
start_arrow.scale(0, scale_tips=True, about_point=self.point)
if self.point_color:
start_arrow.set_color(self.point_color)
return start_arrow
class SpinInFromNothing(GrowFromCenter):
"""Introduce an :class:`~.Mobject` spinning and growing it from its center.
Parameters
----------
mobject
The mobjects to be introduced.
angle
The amount of spinning before mobject reaches its full size. E.g. 2*PI means
that the object will do one full spin before being fully introduced.
point_color
Initial color of the mobject before growing to its full size. Leave empty to match mobject's color.
Examples
--------
.. manim :: SpinInFromNothingExample
class SpinInFromNothingExample(Scene):
def construct(self):
squares = [Square() for _ in range(3)]
VGroup(*squares).set_x(0).arrange(buff=2)
self.play(SpinInFromNothing(squares[0]))
self.play(SpinInFromNothing(squares[1], angle=2 * PI))
self.play(SpinInFromNothing(squares[2], point_color=RED))
"""
def __init__(
self, mobject: Mobject, angle: float = PI / 2, point_color: str = None, **kwargs
) -> None:
self.angle = angle
super().__init__(
mobject, path_func=spiral_path(angle), point_color=point_color, **kwargs
)
|
manim_ManimCommunity/manim/animation/numbers.py
|
"""Animations for changing numbers."""
from __future__ import annotations
__all__ = ["ChangingDecimal", "ChangeDecimalToValue"]
import typing
from manim.mobject.text.numbers import DecimalNumber
from ..animation.animation import Animation
from ..utils.bezier import interpolate
class ChangingDecimal(Animation):
def __init__(
self,
decimal_mob: DecimalNumber,
number_update_func: typing.Callable[[float], float],
suspend_mobject_updating: bool | None = False,
**kwargs,
) -> None:
self.check_validity_of_input(decimal_mob)
self.number_update_func = number_update_func
super().__init__(
decimal_mob, suspend_mobject_updating=suspend_mobject_updating, **kwargs
)
def check_validity_of_input(self, decimal_mob: DecimalNumber) -> None:
if not isinstance(decimal_mob, DecimalNumber):
raise TypeError("ChangingDecimal can only take in a DecimalNumber")
def interpolate_mobject(self, alpha: float) -> None:
self.mobject.set_value(self.number_update_func(self.rate_func(alpha)))
class ChangeDecimalToValue(ChangingDecimal):
def __init__(
self, decimal_mob: DecimalNumber, target_number: int, **kwargs
) -> None:
start_number = decimal_mob.number
super().__init__(
decimal_mob, lambda a: interpolate(start_number, target_number, a), **kwargs
)
|
manim_ManimCommunity/manim/animation/specialized.py
|
from __future__ import annotations
__all__ = ["Broadcast"]
from typing import Any, Sequence
from manim.animation.transform import Restore
from ..constants import *
from .composition import LaggedStart
class Broadcast(LaggedStart):
"""Broadcast a mobject starting from an ``initial_width``, up to the actual size of the mobject.
Parameters
----------
mobject
The mobject to be broadcast.
focal_point
The center of the broadcast, by default ORIGIN.
n_mobs
The number of mobjects that emerge from the focal point, by default 5.
initial_opacity
The starting stroke opacity of the mobjects emitted from the broadcast, by default 1.
final_opacity
The final stroke opacity of the mobjects emitted from the broadcast, by default 0.
initial_width
The initial width of the mobjects, by default 0.0.
remover
Whether the mobjects should be removed from the scene after the animation, by default True.
lag_ratio
The time between each iteration of the mobject, by default 0.2.
run_time
The total duration of the animation, by default 3.
kwargs
Additional arguments to be passed to :class:`~.LaggedStart`.
Examples
---------
.. manim:: BroadcastExample
class BroadcastExample(Scene):
def construct(self):
mob = Circle(radius=4, color=TEAL_A)
self.play(Broadcast(mob))
"""
def __init__(
self,
mobject,
focal_point: Sequence[float] = ORIGIN,
n_mobs: int = 5,
initial_opacity: float = 1,
final_opacity: float = 0,
initial_width: float = 0.0,
remover: bool = True,
lag_ratio: float = 0.2,
run_time: float = 3,
**kwargs: Any,
):
self.focal_point = focal_point
self.n_mobs = n_mobs
self.initial_opacity = initial_opacity
self.final_opacity = final_opacity
self.initial_width = initial_width
anims = []
# Works by saving the mob that is passed into the animation, scaling it to 0 (or the initial_width) and then restoring the original mob.
if mobject.fill_opacity:
fill_o = True
else:
fill_o = False
for _ in range(self.n_mobs):
mob = mobject.copy()
if fill_o:
mob.set_opacity(self.final_opacity)
else:
mob.set_stroke(opacity=self.final_opacity)
mob.move_to(self.focal_point)
mob.save_state()
mob.set(width=self.initial_width)
if fill_o:
mob.set_opacity(self.initial_opacity)
else:
mob.set_stroke(opacity=self.initial_opacity)
anims.append(Restore(mob, remover=remover))
super().__init__(*anims, run_time=run_time, lag_ratio=lag_ratio, **kwargs)
|
manim_ManimCommunity/manim/animation/speedmodifier.py
|
"""Utilities for modifying the speed at which animations are played."""
from __future__ import annotations
import inspect
import types
from typing import Callable
from numpy import piecewise
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
__all__ = ["ChangeSpeed"]
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(
cls,
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`
"""
if "dt" in inspect.signature(update_function).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)
|
manim_ManimCommunity/manim/animation/transform.py
|
"""Animations transforming one mobject into another."""
from __future__ import annotations
__all__ = [
"Transform",
"ReplacementTransform",
"TransformFromCopy",
"ClockwiseTransform",
"CounterclockwiseTransform",
"MoveToTarget",
"ApplyMethod",
"ApplyPointwiseFunction",
"ApplyPointwiseFunctionToCenter",
"FadeToColor",
"FadeTransform",
"FadeTransformPieces",
"ScaleInPlace",
"ShrinkToCenter",
"Restore",
"ApplyFunction",
"ApplyMatrix",
"ApplyComplexFunction",
"CyclicReplace",
"Swap",
"TransformAnimations",
]
import inspect
import types
from typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence
import numpy as np
from manim.mobject.opengl.opengl_mobject import OpenGLGroup, OpenGLMobject
from .. import config
from ..animation.animation import Animation
from ..constants import (
DEFAULT_POINTWISE_FUNCTION_RUN_TIME,
DEGREES,
ORIGIN,
OUT,
RendererType,
)
from ..mobject.mobject import Group, Mobject
from ..utils.paths import path_along_arc, path_along_circles
from ..utils.rate_functions import smooth, squish_rate_func
if TYPE_CHECKING:
from ..scene.scene import Scene
class Transform(Animation):
"""A Transform transforms a Mobject into a target Mobject.
Parameters
----------
mobject
The :class:`.Mobject` to be transformed. It will be mutated to become the ``target_mobject``.
target_mobject
The target of the transformation.
path_func
A function defining the path that the points of the ``mobject`` are being moved
along until they match the points of the ``target_mobject``, see :mod:`.utils.paths`.
path_arc
The arc angle (in radians) that the points of ``mobject`` will follow to reach
the points of the target if using a circular path arc, see ``path_arc_centers``.
See also :func:`manim.utils.paths.path_along_arc`.
path_arc_axis
The axis to rotate along if using a circular path arc, see ``path_arc_centers``.
path_arc_centers
The center of the circular arcs along which the points of ``mobject`` are
moved by the transformation.
If this is set and ``path_func`` is not set, then a ``path_along_circles`` path will be generated
using the ``path_arc`` parameters and stored in ``path_func``. If ``path_func`` is set, this and the
other ``path_arc`` fields are set as attributes, but a ``path_func`` is not generated from it.
replace_mobject_with_target_in_scene
Controls which mobject is replaced when the transformation is complete.
If set to True, ``mobject`` will be removed from the scene and ``target_mobject`` will
replace it. Otherwise, ``target_mobject`` is never added and ``mobject`` just takes its shape.
Examples
--------
.. manim :: TransformPathArc
class TransformPathArc(Scene):
def construct(self):
def make_arc_path(start, end, arc_angle):
points = []
p_fn = path_along_arc(arc_angle)
# alpha animates between 0.0 and 1.0, where 0.0
# is the beginning of the animation and 1.0 is the end.
for alpha in range(0, 11):
points.append(p_fn(start, end, alpha / 10.0))
path = VMobject(stroke_color=YELLOW)
path.set_points_smoothly(points)
return path
left = Circle(stroke_color=BLUE_E, fill_opacity=1.0, radius=0.5).move_to(LEFT * 2)
colors = [TEAL_A, TEAL_B, TEAL_C, TEAL_D, TEAL_E, GREEN_A]
# Positive angles move counter-clockwise, negative angles move clockwise.
examples = [-90, 0, 30, 90, 180, 270]
anims = []
for idx, angle in enumerate(examples):
left_c = left.copy().shift((3 - idx) * UP)
left_c.fill_color = colors[idx]
right_c = left_c.copy().shift(4 * RIGHT)
path_arc = make_arc_path(left_c.get_center(), right_c.get_center(),
arc_angle=angle * DEGREES)
desc = Text('%d°' % examples[idx]).next_to(left_c, LEFT)
# Make the circles in front of the text in front of the arcs.
self.add(
path_arc.set_z_index(1),
desc.set_z_index(2),
left_c.set_z_index(3),
)
anims.append(Transform(left_c, right_c, path_arc=angle * DEGREES))
self.play(*anims, run_time=2)
self.wait()
"""
def __init__(
self,
mobject: Mobject | None,
target_mobject: Mobject | None = None,
path_func: Callable | None = None,
path_arc: float = 0,
path_arc_axis: np.ndarray = OUT,
path_arc_centers: np.ndarray = None,
replace_mobject_with_target_in_scene: bool = False,
**kwargs,
) -> None:
self.path_arc_axis: np.ndarray = path_arc_axis
self.path_arc_centers: np.ndarray = path_arc_centers
self.path_arc: float = path_arc
# path_func is a property a few lines below so it doesn't need to be set in any case
if path_func is not None:
self.path_func: Callable = path_func
elif self.path_arc_centers is not None:
self.path_func = path_along_circles(
path_arc,
self.path_arc_centers,
self.path_arc_axis,
)
self.replace_mobject_with_target_in_scene: bool = (
replace_mobject_with_target_in_scene
)
self.target_mobject: Mobject = (
target_mobject if target_mobject is not None else Mobject()
)
super().__init__(mobject, **kwargs)
@property
def path_arc(self) -> float:
return self._path_arc
@path_arc.setter
def path_arc(self, path_arc: float) -> None:
self._path_arc = path_arc
self._path_func = path_along_arc(
arc_angle=self._path_arc,
axis=self.path_arc_axis,
)
@property
def path_func(
self,
) -> Callable[
[Iterable[np.ndarray], Iterable[np.ndarray], float],
Iterable[np.ndarray],
]:
return self._path_func
@path_func.setter
def path_func(
self,
path_func: Callable[
[Iterable[np.ndarray], Iterable[np.ndarray], float],
Iterable[np.ndarray],
],
) -> None:
if path_func is not None:
self._path_func = path_func
def begin(self) -> None:
# Use a copy of target_mobject for the align_data
# call so that the actual target_mobject stays
# preserved.
self.target_mobject = self.create_target()
self.target_copy = self.target_mobject.copy()
# Note, this potentially changes the structure
# of both mobject and target_mobject
if config.renderer == RendererType.OPENGL:
self.mobject.align_data_and_family(self.target_copy)
else:
self.mobject.align_data(self.target_copy)
super().begin()
def create_target(self) -> Mobject:
# Has no meaningful effect here, but may be useful
# in subclasses
return self.target_mobject
def clean_up_from_scene(self, scene: Scene) -> None:
super().clean_up_from_scene(scene)
if self.replace_mobject_with_target_in_scene:
scene.replace(self.mobject, self.target_mobject)
def get_all_mobjects(self) -> Sequence[Mobject]:
return [
self.mobject,
self.starting_mobject,
self.target_mobject,
self.target_copy,
]
def get_all_families_zipped(self) -> Iterable[tuple]: # more precise typing?
mobs = [
self.mobject,
self.starting_mobject,
self.target_copy,
]
if config.renderer == RendererType.OPENGL:
return zip(*(mob.get_family() for mob in mobs))
return zip(*(mob.family_members_with_points() for mob in mobs))
def interpolate_submobject(
self,
submobject: Mobject,
starting_submobject: Mobject,
target_copy: Mobject,
alpha: float,
) -> Transform:
submobject.interpolate(starting_submobject, target_copy, alpha, self.path_func)
return self
class ReplacementTransform(Transform):
"""Replaces and morphs a mobject into a target mobject.
Parameters
----------
mobject
The starting :class:`~.Mobject`.
target_mobject
The target :class:`~.Mobject`.
kwargs
Further keyword arguments that are passed to :class:`Transform`.
Examples
--------
.. manim:: ReplacementTransformOrTransform
:quality: low
class ReplacementTransformOrTransform(Scene):
def construct(self):
# set up the numbers
r_transform = VGroup(*[Integer(i) for i in range(1,4)])
text_1 = Text("ReplacementTransform", color=RED)
r_transform.add(text_1)
transform = VGroup(*[Integer(i) for i in range(4,7)])
text_2 = Text("Transform", color=BLUE)
transform.add(text_2)
ints = VGroup(r_transform, transform)
texts = VGroup(text_1, text_2).scale(0.75)
r_transform.arrange(direction=UP, buff=1)
transform.arrange(direction=UP, buff=1)
ints.arrange(buff=2)
self.add(ints, texts)
# The mobs replace each other and none are left behind
self.play(ReplacementTransform(r_transform[0], r_transform[1]))
self.play(ReplacementTransform(r_transform[1], r_transform[2]))
# The mobs linger after the Transform()
self.play(Transform(transform[0], transform[1]))
self.play(Transform(transform[1], transform[2]))
self.wait()
"""
def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs) -> None:
super().__init__(
mobject, target_mobject, replace_mobject_with_target_in_scene=True, **kwargs
)
class TransformFromCopy(Transform):
"""
Performs a reversed Transform
"""
def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs) -> None:
super().__init__(target_mobject, mobject, **kwargs)
def interpolate(self, alpha: float) -> None:
super().interpolate(1 - alpha)
class ClockwiseTransform(Transform):
"""Transforms the points of a mobject along a clockwise oriented arc.
See also
--------
:class:`.Transform`, :class:`.CounterclockwiseTransform`
Examples
--------
.. manim:: ClockwiseExample
class ClockwiseExample(Scene):
def construct(self):
dl, dr = Dot(), Dot()
sl, sr = Square(), Square()
VGroup(dl, sl).arrange(DOWN).shift(2*LEFT)
VGroup(dr, sr).arrange(DOWN).shift(2*RIGHT)
self.add(dl, dr)
self.wait()
self.play(
ClockwiseTransform(dl, sl),
Transform(dr, sr)
)
self.wait()
"""
def __init__(
self,
mobject: Mobject,
target_mobject: Mobject,
path_arc: float = -np.pi,
**kwargs,
) -> None:
super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs)
class CounterclockwiseTransform(Transform):
"""Transforms the points of a mobject along a counterclockwise oriented arc.
See also
--------
:class:`.Transform`, :class:`.ClockwiseTransform`
Examples
--------
.. manim:: CounterclockwiseTransform_vs_Transform
class CounterclockwiseTransform_vs_Transform(Scene):
def construct(self):
# set up the numbers
c_transform = VGroup(DecimalNumber(number=3.141, num_decimal_places=3), DecimalNumber(number=1.618, num_decimal_places=3))
text_1 = Text("CounterclockwiseTransform", color=RED)
c_transform.add(text_1)
transform = VGroup(DecimalNumber(number=1.618, num_decimal_places=3), DecimalNumber(number=3.141, num_decimal_places=3))
text_2 = Text("Transform", color=BLUE)
transform.add(text_2)
ints = VGroup(c_transform, transform)
texts = VGroup(text_1, text_2).scale(0.75)
c_transform.arrange(direction=UP, buff=1)
transform.arrange(direction=UP, buff=1)
ints.arrange(buff=2)
self.add(ints, texts)
# The mobs move in clockwise direction for ClockwiseTransform()
self.play(CounterclockwiseTransform(c_transform[0], c_transform[1]))
# The mobs move straight up for Transform()
self.play(Transform(transform[0], transform[1]))
"""
def __init__(
self,
mobject: Mobject,
target_mobject: Mobject,
path_arc: float = np.pi,
**kwargs,
) -> None:
super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs)
class MoveToTarget(Transform):
"""Transforms a mobject to the mobject stored in its ``target`` attribute.
After calling the :meth:`~.Mobject.generate_target` method, the :attr:`target`
attribute of the mobject is populated with a copy of it. After modifying the attribute,
playing the :class:`.MoveToTarget` animation transforms the original mobject
into the modified one stored in the :attr:`target` attribute.
Examples
--------
.. manim:: MoveToTargetExample
class MoveToTargetExample(Scene):
def construct(self):
c = Circle()
c.generate_target()
c.target.set_fill(color=GREEN, opacity=0.5)
c.target.shift(2*RIGHT + UP).scale(0.5)
self.add(c)
self.play(MoveToTarget(c))
"""
def __init__(self, mobject: Mobject, **kwargs) -> None:
self.check_validity_of_input(mobject)
super().__init__(mobject, mobject.target, **kwargs)
def check_validity_of_input(self, mobject: Mobject) -> None:
if not hasattr(mobject, "target"):
raise ValueError(
"MoveToTarget called on mobject" "without attribute 'target'",
)
class _MethodAnimation(MoveToTarget):
def __init__(self, mobject, methods):
self.methods = methods
super().__init__(mobject)
def finish(self) -> None:
for method, method_args, method_kwargs in self.methods:
method.__func__(self.mobject, *method_args, **method_kwargs)
super().finish()
class ApplyMethod(Transform):
"""Animates a mobject by applying a method.
Note that only the method needs to be passed to this animation,
it is not required to pass the corresponding mobject. Furthermore,
this animation class only works if the method returns the modified
mobject.
Parameters
----------
method
The method that will be applied in the animation.
args
Any positional arguments to be passed when applying the method.
kwargs
Any keyword arguments passed to :class:`~.Transform`.
"""
def __init__(
self, method: Callable, *args, **kwargs
) -> None: # method typing (we want to specify Mobject method)? for args?
self.check_validity_of_input(method)
self.method = method
self.method_args = args
super().__init__(method.__self__, **kwargs)
def check_validity_of_input(self, method: Callable) -> None:
if not inspect.ismethod(method):
raise ValueError(
"Whoops, looks like you accidentally invoked "
"the method you want to animate",
)
assert isinstance(method.__self__, (Mobject, OpenGLMobject))
def create_target(self) -> Mobject:
method = self.method
# Make sure it's a list so that args.pop() works
args = list(self.method_args)
if len(args) > 0 and isinstance(args[-1], dict):
method_kwargs = args.pop()
else:
method_kwargs = {}
target = method.__self__.copy()
method.__func__(target, *args, **method_kwargs)
return target
class ApplyPointwiseFunction(ApplyMethod):
"""Animation that applies a pointwise function to a mobject.
Examples
--------
.. manim:: WarpSquare
:quality: low
class WarpSquare(Scene):
def construct(self):
square = Square()
self.play(
ApplyPointwiseFunction(
lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square
)
)
self.wait()
"""
def __init__(
self,
function: types.MethodType,
mobject: Mobject,
run_time: float = DEFAULT_POINTWISE_FUNCTION_RUN_TIME,
**kwargs,
) -> None:
super().__init__(mobject.apply_function, function, run_time=run_time, **kwargs)
class ApplyPointwiseFunctionToCenter(ApplyPointwiseFunction):
def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None:
self.function = function
super().__init__(mobject.move_to, **kwargs)
def begin(self) -> None:
self.method_args = [self.function(self.mobject.get_center())]
super().begin()
class FadeToColor(ApplyMethod):
"""Animation that changes color of a mobject.
Examples
--------
.. manim:: FadeToColorExample
class FadeToColorExample(Scene):
def construct(self):
self.play(FadeToColor(Text("Hello World!"), color=RED))
"""
def __init__(self, mobject: Mobject, color: str, **kwargs) -> None:
super().__init__(mobject.set_color, color, **kwargs)
class ScaleInPlace(ApplyMethod):
"""Animation that scales a mobject by a certain factor.
Examples
--------
.. manim:: ScaleInPlaceExample
class ScaleInPlaceExample(Scene):
def construct(self):
self.play(ScaleInPlace(Text("Hello World!"), 2))
"""
def __init__(self, mobject: Mobject, scale_factor: float, **kwargs) -> None:
super().__init__(mobject.scale, scale_factor, **kwargs)
class ShrinkToCenter(ScaleInPlace):
"""Animation that makes a mobject shrink to center.
Examples
--------
.. manim:: ShrinkToCenterExample
class ShrinkToCenterExample(Scene):
def construct(self):
self.play(ShrinkToCenter(Text("Hello World!")))
"""
def __init__(self, mobject: Mobject, **kwargs) -> None:
super().__init__(mobject, 0, **kwargs)
class Restore(ApplyMethod):
"""Transforms a mobject to its last saved state.
To save the state of a mobject, use the :meth:`~.Mobject.save_state` method.
Examples
--------
.. manim:: RestoreExample
class RestoreExample(Scene):
def construct(self):
s = Square()
s.save_state()
self.play(FadeIn(s))
self.play(s.animate.set_color(PURPLE).set_opacity(0.5).shift(2*LEFT).scale(3))
self.play(s.animate.shift(5*DOWN).rotate(PI/4))
self.wait()
self.play(Restore(s), run_time=2)
"""
def __init__(self, mobject: Mobject, **kwargs) -> None:
super().__init__(mobject.restore, **kwargs)
class ApplyFunction(Transform):
def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None:
self.function = function
super().__init__(mobject, **kwargs)
def create_target(self) -> Any:
target = self.function(self.mobject.copy())
if not isinstance(target, (Mobject, OpenGLMobject)):
raise TypeError(
"Functions passed to ApplyFunction must return object of type Mobject",
)
return target
class ApplyMatrix(ApplyPointwiseFunction):
"""Applies a matrix transform to an mobject.
Parameters
----------
matrix
The transformation matrix.
mobject
The :class:`~.Mobject`.
about_point
The origin point for the transform. Defaults to ``ORIGIN``.
kwargs
Further keyword arguments that are passed to :class:`ApplyPointwiseFunction`.
Examples
--------
.. manim:: ApplyMatrixExample
class ApplyMatrixExample(Scene):
def construct(self):
matrix = [[1, 1], [0, 2/3]]
self.play(ApplyMatrix(matrix, Text("Hello World!")), ApplyMatrix(matrix, NumberPlane()))
"""
def __init__(
self,
matrix: np.ndarray,
mobject: Mobject,
about_point: np.ndarray = ORIGIN,
**kwargs,
) -> None:
matrix = self.initialize_matrix(matrix)
def func(p):
return np.dot(p - about_point, matrix.T) + about_point
super().__init__(func, mobject, **kwargs)
def initialize_matrix(self, matrix: np.ndarray) -> np.ndarray:
matrix = np.array(matrix)
if matrix.shape == (2, 2):
new_matrix = np.identity(3)
new_matrix[:2, :2] = matrix
matrix = new_matrix
elif matrix.shape != (3, 3):
raise ValueError("Matrix has bad dimensions")
return matrix
class ApplyComplexFunction(ApplyMethod):
def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None:
self.function = function
method = mobject.apply_complex_function
super().__init__(method, function, **kwargs)
def _init_path_func(self) -> None:
func1 = self.function(complex(1))
self.path_arc = np.log(func1).imag
super()._init_path_func()
###
class CyclicReplace(Transform):
"""An animation moving mobjects cyclically.
In particular, this means: the first mobject takes the place
of the second mobject, the second one takes the place of
the third mobject, and so on. The last mobject takes the
place of the first one.
Parameters
----------
mobjects
List of mobjects to be transformed.
path_arc
The angle of the arc (in radians) that the mobjects will follow to reach
their target.
kwargs
Further keyword arguments that are passed to :class:`.Transform`.
Examples
--------
.. manim :: CyclicReplaceExample
class CyclicReplaceExample(Scene):
def construct(self):
group = VGroup(Square(), Circle(), Triangle(), Star())
group.arrange(RIGHT)
self.add(group)
for _ in range(4):
self.play(CyclicReplace(*group))
"""
def __init__(
self, *mobjects: Mobject, path_arc: float = 90 * DEGREES, **kwargs
) -> None:
self.group = Group(*mobjects)
super().__init__(self.group, path_arc=path_arc, **kwargs)
def create_target(self) -> Group:
target = self.group.copy()
cycled_targets = [target[-1], *target[:-1]]
for m1, m2 in zip(cycled_targets, self.group):
m1.move_to(m2)
return target
class Swap(CyclicReplace):
pass # Renaming, more understandable for two entries
# TODO, this may be deprecated...worth reimplementing?
class TransformAnimations(Transform):
def __init__(
self,
start_anim: Animation,
end_anim: Animation,
rate_func: Callable = squish_rate_func(smooth),
**kwargs,
) -> None:
self.start_anim = start_anim
self.end_anim = end_anim
if "run_time" in kwargs:
self.run_time = kwargs.pop("run_time")
else:
self.run_time = max(start_anim.run_time, end_anim.run_time)
for anim in start_anim, end_anim:
anim.set_run_time(self.run_time)
if (
start_anim.starting_mobject is not None
and end_anim.starting_mobject is not None
and start_anim.starting_mobject.get_num_points()
!= end_anim.starting_mobject.get_num_points()
):
start_anim.starting_mobject.align_data(end_anim.starting_mobject)
for anim in start_anim, end_anim:
if isinstance(anim, Transform) and anim.starting_mobject is not None:
anim.starting_mobject.align_data(anim.target_mobject)
super().__init__(
start_anim.mobject, end_anim.mobject, rate_func=rate_func, **kwargs
)
# Rewire starting and ending mobjects
start_anim.mobject = self.starting_mobject
end_anim.mobject = self.target_mobject
def interpolate(self, alpha: float) -> None:
self.start_anim.interpolate(alpha)
self.end_anim.interpolate(alpha)
super().interpolate(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()
if config.renderer == RendererType.OPENGL:
group = OpenGLGroup(mobject, target_mobject.copy())
else:
group = Group(mobject, target_mobject.copy())
super().__init__(group, **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.
If the provided target has no points, and thus a location of [0, 0, 0]
the source will simply fade out where it currently is.
"""
# mobject.replace() does not work if the target has no points.
if target.get_num_points() or target.submobjects:
source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match)
source.set_opacity(0)
def get_all_mobjects(self) -> Sequence[Mobject]:
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)
|
manim_ManimCommunity/manim/animation/animation.py
|
"""Animate mobjects."""
from __future__ import annotations
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from .. import config, logger
from ..constants import RendererType
from ..mobject import mobject
from ..mobject.mobject import Mobject
from ..mobject.opengl import opengl_mobject
from ..utils.rate_functions import linear, smooth
__all__ = ["Animation", "Wait", "override_animation"]
from copy import deepcopy
from typing import TYPE_CHECKING, Callable, Iterable, Sequence
from typing_extensions import Self
if TYPE_CHECKING:
from manim.scene.scene import Scene
DEFAULT_ANIMATION_RUN_TIME: float = 1.0
DEFAULT_ANIMATION_LAG_RATIO: float = 0.0
class Animation:
"""An animation.
Animations have a fixed time span.
Parameters
----------
mobject
The mobject to be animated. This is not required for all types of animations.
lag_ratio
Defines the delay after which the animation is applied to submobjects. This lag
is relative to the duration of the animation.
This does not influence the total
runtime of the animation. Instead the runtime of individual animations is
adjusted so that the complete animation has the defined run time.
run_time
The duration of the animation in seconds.
rate_func
The function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`) .
For example ``rate_func(0.5)`` is the proportion of the animation that is done
after half of the animations run time.
reverse_rate_function
Reverses the rate function of the animation. Setting ``reverse_rate_function``
does not have any effect on ``remover`` or ``introducer``. These need to be
set explicitly if an introducer-animation should be turned into a remover one
and vice versa.
name
The name of the animation. This gets displayed while rendering the animation.
Defaults to <class-name>(<Mobject-name>).
remover
Whether the given mobject should be removed from the scene after this animation.
suspend_mobject_updating
Whether updaters of the mobject should be suspended during the animation.
.. NOTE::
In the current implementation of this class, the specified rate function is applied
within :meth:`.Animation.interpolate_mobject` call as part of the call to
:meth:`.Animation.interpolate_submobject`. For subclasses of :class:`.Animation`
that are implemented by overriding :meth:`interpolate_mobject`, the rate function
has to be applied manually (e.g., by passing ``self.rate_func(alpha)`` instead
of just ``alpha``).
Examples
--------
.. manim:: LagRatios
class LagRatios(Scene):
def construct(self):
ratios = [0, 0.1, 0.5, 1, 2] # demonstrated lag_ratios
# Create dot groups
group = VGroup(*[Dot() for _ in range(4)]).arrange_submobjects()
groups = VGroup(*[group.copy() for _ in ratios]).arrange_submobjects(buff=1)
self.add(groups)
# Label groups
self.add(Text("lag_ratio = ", font_size=36).next_to(groups, UP, buff=1.5))
for group, ratio in zip(groups, ratios):
self.add(Text(str(ratio), font_size=36).next_to(group, UP))
#Animate groups with different lag_ratios
self.play(AnimationGroup(*[
group.animate(lag_ratio=ratio, run_time=1.5).shift(DOWN * 2)
for group, ratio in zip(groups, ratios)
]))
# lag_ratio also works recursively on nested submobjects:
self.play(groups.animate(run_time=1, lag_ratio=0.1).shift(UP * 2))
"""
def __new__(
cls,
mobject=None,
*args,
use_override=True,
**kwargs,
) -> Self:
if isinstance(mobject, Mobject) and use_override:
func = mobject.animation_override_for(cls)
if func is not None:
anim = func(mobject, *args, **kwargs)
logger.debug(
f"The {cls.__name__} animation has been is overridden for "
f"{type(mobject).__name__} mobjects. use_override = False can "
f" be used as keyword argument to prevent animation overriding.",
)
return anim
return super().__new__(cls)
def __init__(
self,
mobject: Mobject | None,
lag_ratio: float = DEFAULT_ANIMATION_LAG_RATIO,
run_time: float = DEFAULT_ANIMATION_RUN_TIME,
rate_func: Callable[[float], float] = smooth,
reverse_rate_function: bool = False,
name: str = None,
remover: bool = False, # remove a mobject from the screen?
suspend_mobject_updating: bool = True,
introducer: bool = False,
*,
_on_finish: Callable[[], None] = lambda _: None,
**kwargs,
) -> None:
self._typecheck_input(mobject)
self.run_time: float = run_time
self.rate_func: Callable[[float], float] = rate_func
self.reverse_rate_function: bool = reverse_rate_function
self.name: str | None = name
self.remover: bool = remover
self.introducer: bool = introducer
self.suspend_mobject_updating: bool = suspend_mobject_updating
self.lag_ratio: float = lag_ratio
self._on_finish: Callable[[Scene], None] = _on_finish
if config["renderer"] == RendererType.OPENGL:
self.starting_mobject: OpenGLMobject = OpenGLMobject()
self.mobject: OpenGLMobject = (
mobject if mobject is not None else OpenGLMobject()
)
else:
self.starting_mobject: Mobject = Mobject()
self.mobject: Mobject = mobject if mobject is not None else Mobject()
if kwargs:
logger.debug("Animation received extra kwargs: %s", kwargs)
if hasattr(self, "CONFIG"):
logger.error(
(
"CONFIG has been removed from ManimCommunity.",
"Please use keyword arguments instead.",
),
)
def _typecheck_input(self, mobject: Mobject | None) -> None:
if mobject is None:
logger.debug("Animation with empty mobject")
elif not isinstance(mobject, (Mobject, OpenGLMobject)):
raise TypeError("Animation only works on Mobjects")
def __str__(self) -> str:
if self.name:
return self.name
return f"{self.__class__.__name__}({str(self.mobject)})"
def __repr__(self) -> str:
return str(self)
def begin(self) -> None:
"""Begin the animation.
This method is called right as an animation is being played. As much
initialization as possible, especially any mobject copying, should live in this
method.
"""
if self.run_time <= 0:
raise ValueError(
f"{self} has a run_time of <= 0 seconds, this cannot be rendered correctly. "
"Please set the run_time to be positive"
)
self.starting_mobject = self.create_starting_mobject()
if self.suspend_mobject_updating:
# All calls to self.mobject's internal updaters
# during the animation, either from this Animation
# or from the surrounding scene, should do nothing.
# It is, however, okay and desirable to call
# the internal updaters of self.starting_mobject,
# or any others among self.get_all_mobjects()
self.mobject.suspend_updating()
self.interpolate(0)
def finish(self) -> None:
# TODO: begin and finish should require a scene as parameter.
# That way Animation.clean_up_from_screen and Scene.add_mobjects_from_animations
# could be removed as they fulfill basically the same purpose.
"""Finish the animation.
This method gets called when the animation is over.
"""
self.interpolate(1)
if self.suspend_mobject_updating and self.mobject is not None:
self.mobject.resume_updating()
def clean_up_from_scene(self, scene: Scene) -> None:
"""Clean up the :class:`~.Scene` after finishing the animation.
This includes to :meth:`~.Scene.remove` the Animation's
:class:`~.Mobject` if the animation is a remover.
Parameters
----------
scene
The scene the animation should be cleaned up from.
"""
self._on_finish(scene)
if self.is_remover():
scene.remove(self.mobject)
def _setup_scene(self, scene: Scene) -> None:
"""Setup up the :class:`~.Scene` before starting the animation.
This includes to :meth:`~.Scene.add` the Animation's
:class:`~.Mobject` if the animation is an introducer.
Parameters
----------
scene
The scene the animation should be cleaned up from.
"""
if scene is None:
return
if (
self.is_introducer()
and self.mobject not in scene.get_mobject_family_members()
):
scene.add(self.mobject)
def create_starting_mobject(self) -> Mobject:
# Keep track of where the mobject starts
return self.mobject.copy()
def get_all_mobjects(self) -> Sequence[Mobject]:
"""Get all mobjects involved in the animation.
Ordering must match the ordering of arguments to interpolate_submobject
Returns
-------
Sequence[Mobject]
The sequence of mobjects.
"""
return self.mobject, self.starting_mobject
def get_all_families_zipped(self) -> Iterable[tuple]:
if config["renderer"] == RendererType.OPENGL:
return zip(*(mob.get_family() for mob in self.get_all_mobjects()))
return zip(
*(mob.family_members_with_points() for mob in self.get_all_mobjects())
)
def update_mobjects(self, dt: float) -> None:
"""
Updates things like starting_mobject, and (for
Transforms) target_mobject. Note, since typically
(always?) self.mobject will have its updating
suspended during the animation, this will do
nothing to self.mobject.
"""
for mob in self.get_all_mobjects_to_update():
mob.update(dt)
def get_all_mobjects_to_update(self) -> list[Mobject]:
"""Get all mobjects to be updated during the animation.
Returns
-------
List[Mobject]
The list of mobjects to be updated during the animation.
"""
# The surrounding scene typically handles
# updating of self.mobject. Besides, in
# most cases its updating is suspended anyway
return list(filter(lambda m: m is not self.mobject, self.get_all_mobjects()))
def copy(self) -> Animation:
"""Create a copy of the animation.
Returns
-------
Animation
A copy of ``self``
"""
return deepcopy(self)
# Methods for interpolation, the mean of an Animation
# TODO: stop using alpha as parameter name in different meanings.
def interpolate(self, alpha: float) -> None:
"""Set the animation progress.
This method gets called for every frame during an animation.
Parameters
----------
alpha
The relative time to set the animation to, 0 meaning the start, 1 meaning
the end.
"""
self.interpolate_mobject(alpha)
def interpolate_mobject(self, alpha: float) -> None:
"""Interpolates the mobject of the :class:`Animation` based on alpha value.
Parameters
----------
alpha
A float between 0 and 1 expressing the ratio to which the animation
is completed. For example, alpha-values of 0, 0.5, and 1 correspond
to the animation being completed 0%, 50%, and 100%, respectively.
"""
families = list(self.get_all_families_zipped())
for i, mobs in enumerate(families):
sub_alpha = self.get_sub_alpha(alpha, i, len(families))
self.interpolate_submobject(*mobs, sub_alpha)
def interpolate_submobject(
self,
submobject: Mobject,
starting_submobject: Mobject,
# target_copy: Mobject, #Todo: fix - signature of interpolate_submobject differs in Transform().
alpha: float,
) -> Animation:
# Typically implemented by subclass
pass
def get_sub_alpha(self, alpha: float, index: int, num_submobjects: int) -> float:
"""Get the animation progress of any submobjects subanimation.
Parameters
----------
alpha
The overall animation progress
index
The index of the subanimation.
num_submobjects
The total count of subanimations.
Returns
-------
float
The progress of the subanimation.
"""
# TODO, make this more understandable, and/or combine
# its functionality with AnimationGroup's method
# build_animations_with_timings
lag_ratio = self.lag_ratio
full_length = (num_submobjects - 1) * lag_ratio + 1
value = alpha * full_length
lower = index * lag_ratio
if self.reverse_rate_function:
return self.rate_func(1 - (value - lower))
else:
return self.rate_func(value - lower)
# Getters and setters
def set_run_time(self, run_time: float) -> Animation:
"""Set the run time of the animation.
Parameters
----------
run_time
The new time the animation should take in seconds.
.. note::
The run_time of an animation should not be changed while it is already
running.
Returns
-------
Animation
``self``
"""
self.run_time = run_time
return self
def get_run_time(self) -> float:
"""Get the run time of the animation.
Returns
-------
float
The time the animation takes in seconds.
"""
return self.run_time
def set_rate_func(
self,
rate_func: Callable[[float], float],
) -> Animation:
"""Set the rate function of the animation.
Parameters
----------
rate_func
The new function defining the animation progress based on the
relative runtime (see :mod:`~.rate_functions`).
Returns
-------
Animation
``self``
"""
self.rate_func = rate_func
return self
def get_rate_func(
self,
) -> Callable[[float], float]:
"""Get the rate function of the animation.
Returns
-------
Callable[[float], float]
The rate function of the animation.
"""
return self.rate_func
def set_name(self, name: str) -> Animation:
"""Set the name of the animation.
Parameters
----------
name
The new name of the animation.
Returns
-------
Animation
``self``
"""
self.name = name
return self
def is_remover(self) -> bool:
"""Test if the animation is a remover.
Returns
-------
bool
``True`` if the animation is a remover, ``False`` otherwise.
"""
return self.remover
def is_introducer(self) -> bool:
"""Test if the animation is an introducer.
Returns
-------
bool
``True`` if the animation is an introducer, ``False`` otherwise.
"""
return self.introducer
def prepare_animation(
anim: Animation | mobject._AnimationBuilder,
) -> Animation:
r"""Returns either an unchanged animation, or the animation built
from a passed animation factory.
Examples
--------
::
>>> from manim import Square, FadeIn
>>> s = Square()
>>> prepare_animation(FadeIn(s))
FadeIn(Square)
::
>>> prepare_animation(s.animate.scale(2).rotate(42))
_MethodAnimation(Square)
::
>>> prepare_animation(42)
Traceback (most recent call last):
...
TypeError: Object 42 cannot be converted to an animation
"""
if isinstance(anim, mobject._AnimationBuilder):
return anim.build()
if isinstance(anim, opengl_mobject._AnimationBuilder):
return anim.build()
if isinstance(anim, Animation):
return anim
raise TypeError(f"Object {anim} cannot be converted to an animation")
class Wait(Animation):
"""A "no operation" animation.
Parameters
----------
run_time
The amount of time that should pass.
stop_condition
A function without positional arguments that evaluates to a boolean.
The function is evaluated after every new frame has been rendered.
Playing the animation stops after the return value is truthy, or
after the specified ``run_time`` has passed.
frozen_frame
Controls whether or not the wait animation is static, i.e., corresponds
to a frozen frame. If ``False`` is passed, the render loop still
progresses through the animation as usual and (among other things)
continues to call updater functions. If ``None`` (the default value),
the :meth:`.Scene.play` call tries to determine whether the Wait call
can be static or not itself via :meth:`.Scene.should_mobjects_update`.
kwargs
Keyword arguments to be passed to the parent class, :class:`.Animation`.
"""
def __init__(
self,
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:
raise ValueError("A static Wait animation cannot have a stop condition.")
self.duration: float = run_time
self.stop_condition = stop_condition
self.is_static_wait: bool = frozen_frame
super().__init__(None, run_time=run_time, rate_func=rate_func, **kwargs)
# quick fix to work in opengl setting:
self.mobject.shader_wrapper_list = []
def begin(self) -> None:
pass
def finish(self) -> None:
pass
def clean_up_from_scene(self, scene: Scene) -> None:
pass
def update_mobjects(self, dt: float) -> None:
pass
def interpolate(self, alpha: float) -> None:
pass
def override_animation(
animation_class: type[Animation],
) -> Callable[[Callable], Callable]:
"""Decorator used to mark methods as overrides for specific :class:`~.Animation` types.
Should only be used to decorate methods of classes derived from :class:`~.Mobject`.
``Animation`` overrides get inherited to subclasses of the ``Mobject`` who defined
them. They don't override subclasses of the ``Animation`` they override.
See Also
--------
:meth:`~.Mobject.add_animation_override`
Parameters
----------
animation_class
The animation to be overridden.
Returns
-------
Callable[[Callable], Callable]
The actual decorator. This marks the method as overriding an animation.
Examples
--------
.. manim:: OverrideAnimationExample
class MySquare(Square):
@override_animation(FadeIn)
def _fade_in_override(self, **kwargs):
return Create(self, **kwargs)
class OverrideAnimationExample(Scene):
def construct(self):
self.play(FadeIn(MySquare()))
"""
def decorator(func):
func._override_animation = animation_class
return func
return decorator
|
manim_ManimCommunity/manim/animation/indication.py
|
"""Animations drawing attention to particular mobjects.
Examples
--------
.. manim:: Indications
class Indications(Scene):
def construct(self):
indications = [ApplyWave,Circumscribe,Flash,FocusOn,Indicate,ShowPassingFlash,Wiggle]
names = [Tex(i.__name__).scale(3) for i in indications]
self.add(names[0])
for i in range(len(names)):
if indications[i] is Flash:
self.play(Flash(UP))
elif indications[i] is ShowPassingFlash:
self.play(ShowPassingFlash(Underline(names[i])))
else:
self.play(indications[i](names[i]))
self.play(AnimationGroup(
FadeOut(names[i], shift=UP*1.5),
FadeIn(names[(i+1)%len(names)], shift=UP*1.5),
))
"""
__all__ = [
"FocusOn",
"Indicate",
"Flash",
"ShowPassingFlash",
"ShowPassingFlashWithThinningStrokeWidth",
"ShowCreationThenFadeOut",
"ApplyWave",
"Circumscribe",
"Wiggle",
]
from typing import Callable, Iterable, Optional, Tuple, Type, Union
import numpy as np
from manim.mobject.geometry.arc import Circle, Dot
from manim.mobject.geometry.line import Line
from manim.mobject.geometry.polygram import Rectangle
from manim.mobject.geometry.shape_matchers import SurroundingRectangle
from manim.scene.scene import Scene
from .. import config
from ..animation.animation import Animation
from ..animation.composition import AnimationGroup, Succession
from ..animation.creation import Create, ShowPartial, Uncreate
from ..animation.fading import FadeIn, FadeOut
from ..animation.movement import Homotopy
from ..animation.transform import Transform
from ..constants import *
from ..mobject.mobject import Mobject
from ..mobject.types.vectorized_mobject import VGroup, VMobject
from ..utils.bezier import interpolate, inverse_interpolate
from ..utils.color import GREY, YELLOW, ParsableManimColor
from ..utils.deprecation import deprecated
from ..utils.rate_functions import smooth, there_and_back, wiggle
from ..utils.space_ops import normalize
class FocusOn(Transform):
"""Shrink a spotlight to a position.
Parameters
----------
focus_point
The point at which to shrink the spotlight. If it is a :class:`.~Mobject` its center will be used.
opacity
The opacity of the spotlight.
color
The color of the spotlight.
run_time
The duration of the animation.
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples
--------
.. manim:: UsingFocusOn
class UsingFocusOn(Scene):
def construct(self):
dot = Dot(color=YELLOW).shift(DOWN)
self.add(Tex("Focusing on the dot below:"), dot)
self.play(FocusOn(dot))
self.wait()
"""
def __init__(
self,
focus_point: Union[np.ndarray, Mobject],
opacity: float = 0.2,
color: str = GREY,
run_time: float = 2,
**kwargs
) -> None:
self.focus_point = focus_point
self.color = color
self.opacity = opacity
remover = True
starting_dot = Dot(
radius=config["frame_x_radius"] + config["frame_y_radius"],
stroke_width=0,
fill_color=self.color,
fill_opacity=0,
)
super().__init__(starting_dot, run_time=run_time, remover=remover, **kwargs)
def create_target(self) -> Dot:
little_dot = Dot(radius=0)
little_dot.set_fill(self.color, opacity=self.opacity)
little_dot.add_updater(lambda d: d.move_to(self.focus_point))
return little_dot
class Indicate(Transform):
"""Indicate a Mobject by temporarily resizing and recoloring it.
Parameters
----------
mobject
The mobject to indicate.
scale_factor
The factor by which the mobject will be temporally scaled
color
The color the mobject temporally takes.
rate_func
The function defining the animation progress at every point in time.
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples
--------
.. manim:: UsingIndicate
class UsingIndicate(Scene):
def construct(self):
tex = Tex("Indicate").scale(3)
self.play(Indicate(tex))
self.wait()
"""
def __init__(
self,
mobject: Mobject,
scale_factor: float = 1.2,
color: str = YELLOW,
rate_func: Callable[[float, Optional[float]], np.ndarray] = there_and_back,
**kwargs
) -> None:
self.color = color
self.scale_factor = scale_factor
super().__init__(mobject, rate_func=rate_func, **kwargs)
def create_target(self) -> Mobject:
target = self.mobject.copy()
target.scale(self.scale_factor)
target.set_color(self.color)
return target
class Flash(AnimationGroup):
"""Send out lines in all directions.
Parameters
----------
point
The center of the flash lines. If it is a :class:`.~Mobject` its center will be used.
line_length
The length of the flash lines.
num_lines
The number of flash lines.
flash_radius
The distance from `point` at which the flash lines start.
line_stroke_width
The stroke width of the flash lines.
color
The color of the flash lines.
time_width
The time width used for the flash lines. See :class:`.~ShowPassingFlash` for more details.
run_time
The duration of the animation.
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples
--------
.. manim:: UsingFlash
class UsingFlash(Scene):
def construct(self):
dot = Dot(color=YELLOW).shift(DOWN)
self.add(Tex("Flash the dot below:"), dot)
self.play(Flash(dot))
self.wait()
.. manim:: FlashOnCircle
class FlashOnCircle(Scene):
def construct(self):
radius = 2
circle = Circle(radius)
self.add(circle)
self.play(Flash(
circle, line_length=1,
num_lines=30, color=RED,
flash_radius=radius+SMALL_BUFF,
time_width=0.3, run_time=2,
rate_func = rush_from
))
"""
def __init__(
self,
point: Union[np.ndarray, Mobject],
line_length: float = 0.2,
num_lines: int = 12,
flash_radius: float = 0.1,
line_stroke_width: int = 3,
color: str = YELLOW,
time_width: float = 1,
run_time: float = 1.0,
**kwargs
) -> None:
if isinstance(point, Mobject):
self.point = point.get_center()
else:
self.point = point
self.color = color
self.line_length = line_length
self.num_lines = num_lines
self.flash_radius = flash_radius
self.line_stroke_width = line_stroke_width
self.run_time = run_time
self.time_width = time_width
self.animation_config = kwargs
self.lines = self.create_lines()
animations = self.create_line_anims()
super().__init__(*animations, group=self.lines)
def create_lines(self) -> VGroup:
lines = VGroup()
for angle in np.arange(0, TAU, TAU / self.num_lines):
line = Line(self.point, self.point + self.line_length * RIGHT)
line.shift((self.flash_radius) * RIGHT)
line.rotate(angle, about_point=self.point)
lines.add(line)
lines.set_color(self.color)
lines.set_stroke(width=self.line_stroke_width)
return lines
def create_line_anims(self) -> Iterable["ShowPassingFlash"]:
return [
ShowPassingFlash(
line,
time_width=self.time_width,
run_time=self.run_time,
**self.animation_config,
)
for line in self.lines
]
class ShowPassingFlash(ShowPartial):
"""Show only a sliver of the VMobject each frame.
Parameters
----------
mobject
The mobject whose stroke is animated.
time_width
The length of the sliver relative to the length of the stroke.
Examples
--------
.. manim:: TimeWidthValues
class TimeWidthValues(Scene):
def construct(self):
p = RegularPolygon(5, color=DARK_GRAY, stroke_width=6).scale(3)
lbl = VMobject()
self.add(p, lbl)
p = p.copy().set_color(BLUE)
for time_width in [0.2, 0.5, 1, 2]:
lbl.become(Tex(r"\\texttt{time\\_width={{%.1f}}}"%time_width))
self.play(ShowPassingFlash(
p.copy().set_color(BLUE),
run_time=2,
time_width=time_width
))
See Also
--------
:class:`~.Create`
"""
def __init__(self, mobject: "VMobject", time_width: float = 0.1, **kwargs) -> None:
self.time_width = time_width
super().__init__(mobject, remover=True, introducer=True, **kwargs)
def _get_bounds(self, alpha: float) -> Tuple[float]:
tw = self.time_width
upper = interpolate(0, 1 + tw, alpha)
lower = upper - tw
upper = min(upper, 1)
lower = max(lower, 0)
return (lower, upper)
def clean_up_from_scene(self, scene: Scene) -> None:
super().clean_up_from_scene(scene)
for submob, start in self.get_all_families_zipped():
submob.pointwise_become_partial(start, 0, 1)
class ShowPassingFlashWithThinningStrokeWidth(AnimationGroup):
def __init__(self, vmobject, n_segments=10, time_width=0.1, remover=True, **kwargs):
self.n_segments = n_segments
self.time_width = time_width
self.remover = remover
max_stroke_width = vmobject.get_stroke_width()
max_time_width = kwargs.pop("time_width", self.time_width)
super().__init__(
*(
ShowPassingFlash(
vmobject.copy().set_stroke(width=stroke_width),
time_width=time_width,
**kwargs,
)
for stroke_width, time_width in zip(
np.linspace(0, max_stroke_width, self.n_segments),
np.linspace(max_time_width, 0, self.n_segments),
)
),
)
@deprecated(
since="v0.15.0",
until="v0.16.0",
message="Use Create then FadeOut to achieve this effect.",
)
class ShowCreationThenFadeOut(Succession):
def __init__(self, mobject: Mobject, remover: bool = True, **kwargs) -> None:
super().__init__(Create(mobject), FadeOut(mobject), remover=remover, **kwargs)
class ApplyWave(Homotopy):
"""Send a wave through the Mobject distorting it temporarily.
Parameters
----------
mobject
The mobject to be distorted.
direction
The direction in which the wave nudges points of the shape
amplitude
The distance points of the shape get shifted
wave_func
The function defining the shape of one wave flank.
time_width
The length of the wave relative to the width of the mobject.
ripples
The number of ripples of the wave
run_time
The duration of the animation.
Examples
--------
.. manim:: ApplyingWaves
class ApplyingWaves(Scene):
def construct(self):
tex = Tex("WaveWaveWaveWaveWave").scale(2)
self.play(ApplyWave(tex))
self.play(ApplyWave(
tex,
direction=RIGHT,
time_width=0.5,
amplitude=0.3
))
self.play(ApplyWave(
tex,
rate_func=linear,
ripples=4
))
"""
def __init__(
self,
mobject: Mobject,
direction: np.ndarray = UP,
amplitude: float = 0.2,
wave_func: Callable[[float], float] = smooth,
time_width: float = 1,
ripples: int = 1,
run_time: float = 2,
**kwargs
) -> None:
x_min = mobject.get_left()[0]
x_max = mobject.get_right()[0]
vect = amplitude * normalize(direction)
def wave(t):
# Creates a wave with n ripples from a simple rate_func
# This wave is build up as follows:
# The time is split into 2*ripples phases. In every phase the amplitude
# either rises to one or goes down to zero. Consecutive ripples will have
# their amplitudes in opposing directions (first ripple from 0 to 1 to 0,
# second from 0 to -1 to 0 and so on). This is how two ripples would be
# divided into phases:
# ####|#### | |
# ## | ## | |
# ## | ## | |
# #### | ####|#### | ####
# | | ## | ##
# | | ## | ##
# | | ####|####
# However, this looks weird in the middle between two ripples. Therefore the
# middle phases do actually use only one appropriately scaled version of the
# rate like this:
# 1 / 4 Time | 2 / 4 Time | 1 / 4 Time
# ####|###### |
# ## | ### |
# ## | ## |
# #### | # | ####
# | ## | ##
# | ### | ##
# | ######|####
# Mirrored looks better in the way the wave is used.
t = 1 - t
# Clamp input
if t >= 1 or t <= 0:
return 0
phases = ripples * 2
phase = int(t * phases)
if phase == 0:
# First rising ripple
return wave_func(t * phases)
elif phase == phases - 1:
# last ripple. Rising or falling depending on the number of ripples
# The (ripples % 2)-term is used to make this distinction.
t -= phase / phases # Time relative to the phase
return (1 - wave_func(t * phases)) * (2 * (ripples % 2) - 1)
else:
# Longer phases:
phase = int((phase - 1) / 2)
t -= (2 * phase + 1) / phases
# Similar to last ripple:
return (1 - 2 * wave_func(t * ripples)) * (1 - 2 * ((phase) % 2))
def homotopy(
x: float,
y: float,
z: float,
t: float,
) -> Tuple[float, float, float]:
upper = interpolate(0, 1 + time_width, t)
lower = upper - time_width
relative_x = inverse_interpolate(x_min, x_max, x)
wave_phase = inverse_interpolate(lower, upper, relative_x)
nudge = wave(wave_phase) * vect
return np.array([x, y, z]) + nudge
super().__init__(homotopy, mobject, run_time=run_time, **kwargs)
class Wiggle(Animation):
"""Wiggle a Mobject.
Parameters
----------
mobject
The mobject to wiggle.
scale_value
The factor by which the mobject will be temporarily scaled.
rotation_angle
The wiggle angle.
n_wiggles
The number of wiggles.
scale_about_point
The point about which the mobject gets scaled.
rotate_about_point
The point around which the mobject gets rotated.
run_time
The duration of the animation
Examples
--------
.. manim:: ApplyingWaves
class ApplyingWaves(Scene):
def construct(self):
tex = Tex("Wiggle").scale(3)
self.play(Wiggle(tex))
self.wait()
"""
def __init__(
self,
mobject: Mobject,
scale_value: float = 1.1,
rotation_angle: float = 0.01 * TAU,
n_wiggles: int = 6,
scale_about_point: Optional[np.ndarray] = None,
rotate_about_point: Optional[np.ndarray] = None,
run_time: float = 2,
**kwargs
) -> None:
self.scale_value = scale_value
self.rotation_angle = rotation_angle
self.n_wiggles = n_wiggles
self.scale_about_point = scale_about_point
self.rotate_about_point = rotate_about_point
super().__init__(mobject, run_time=run_time, **kwargs)
def get_scale_about_point(self) -> np.ndarray:
if self.scale_about_point is None:
return self.mobject.get_center()
return self.scale_about_point
def get_rotate_about_point(self) -> np.ndarray:
if self.rotate_about_point is None:
return self.mobject.get_center()
return self.rotate_about_point
def interpolate_submobject(
self,
submobject: Mobject,
starting_submobject: Mobject,
alpha: float,
) -> None:
submobject.points[:, :] = starting_submobject.points
submobject.scale(
interpolate(1, self.scale_value, there_and_back(alpha)),
about_point=self.get_scale_about_point(),
)
submobject.rotate(
wiggle(alpha, self.n_wiggles) * self.rotation_angle,
about_point=self.get_rotate_about_point(),
)
class Circumscribe(Succession):
"""Draw a temporary line surrounding the mobject.
Parameters
----------
mobject
The mobject to be circumscribed.
shape
The shape with which to surrond the given mobject. Should be either
:class:`~.Rectangle` or :class:`~.Circle`
fade_in
Whether to make the surrounding shape to fade in. It will be drawn otherwise.
fade_out
Whether to make the surrounding shape to fade out. It will be undrawn otherwise.
time_width
The time_width of the drawing and undrawing. Gets ignored if either `fade_in` or `fade_out` is `True`.
buff
The distance between the surrounding shape and the given mobject.
color
The color of the surrounding shape.
run_time
The duration of the entire animation.
kwargs
Additional arguments to be passed to the :class:`~.Succession` constructor
Examples
--------
.. manim:: UsingCircumscribe
class UsingCircumscribe(Scene):
def construct(self):
lbl = Tex(r"Circum-\\\\scribe").scale(2)
self.add(lbl)
self.play(Circumscribe(lbl))
self.play(Circumscribe(lbl, Circle))
self.play(Circumscribe(lbl, fade_out=True))
self.play(Circumscribe(lbl, time_width=2))
self.play(Circumscribe(lbl, Circle, True))
"""
def __init__(
self,
mobject: Mobject,
shape: Type = Rectangle,
fade_in=False,
fade_out=False,
time_width=0.3,
buff: float = SMALL_BUFF,
color: ParsableManimColor = YELLOW,
run_time=1,
stroke_width=DEFAULT_STROKE_WIDTH,
**kwargs
):
if shape is Rectangle:
frame = SurroundingRectangle(
mobject,
color,
buff,
stroke_width=stroke_width,
)
elif shape is Circle:
frame = Circle(color=color, stroke_width=stroke_width).surround(
mobject,
buffer_factor=1,
)
radius = frame.width / 2
frame.scale((radius + buff) / radius)
else:
raise ValueError("shape should be either Rectangle or Circle.")
if fade_in and fade_out:
super().__init__(
FadeIn(frame, run_time=run_time / 2),
FadeOut(frame, run_time=run_time / 2),
**kwargs,
)
elif fade_in:
frame.reverse_direction()
super().__init__(
FadeIn(frame, run_time=run_time / 2),
Uncreate(frame, run_time=run_time / 2),
**kwargs,
)
elif fade_out:
super().__init__(
Create(frame, run_time=run_time / 2),
FadeOut(frame, run_time=run_time / 2),
**kwargs,
)
else:
super().__init__(
ShowPassingFlash(frame, time_width, run_time=run_time), **kwargs
)
|
manim_ManimCommunity/manim/animation/updaters/__init__.py
|
"""Animations and utility mobjects related to update functions.
Modules
=======
.. autosummary::
:toctree: ../reference
~mobject_update_utils
~update
"""
|
manim_ManimCommunity/manim/animation/updaters/update.py
|
"""Animations that update mobjects."""
from __future__ import annotations
__all__ = ["UpdateFromFunc", "UpdateFromAlphaFunc", "MaintainPositionRelativeTo"]
import operator as op
import typing
from manim.animation.animation import Animation
if typing.TYPE_CHECKING:
from manim.mobject.mobject import Mobject
class UpdateFromFunc(Animation):
"""
update_function of the form func(mobject), presumably
to be used when the state of one mobject is dependent
on another simultaneously animated mobject
"""
def __init__(
self,
mobject: Mobject,
update_function: typing.Callable[[Mobject], typing.Any],
suspend_mobject_updating: bool = False,
**kwargs,
) -> None:
self.update_function = update_function
super().__init__(
mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs
)
def interpolate_mobject(self, alpha: float) -> None:
self.update_function(self.mobject)
class UpdateFromAlphaFunc(UpdateFromFunc):
def interpolate_mobject(self, alpha: float) -> None:
self.update_function(self.mobject, self.rate_func(alpha))
class MaintainPositionRelativeTo(Animation):
def __init__(self, mobject: Mobject, tracked_mobject: Mobject, **kwargs) -> None:
self.tracked_mobject = tracked_mobject
self.diff = op.sub(
mobject.get_center(),
tracked_mobject.get_center(),
)
super().__init__(mobject, **kwargs)
def interpolate_mobject(self, alpha: float) -> None:
target = self.tracked_mobject.get_center()
location = self.mobject.get_center()
self.mobject.shift(target - location + self.diff)
|
manim_ManimCommunity/manim/animation/updaters/mobject_update_utils.py
|
"""Utility functions for continuous animation of mobjects."""
from __future__ import annotations
__all__ = [
"assert_is_mobject_method",
"always",
"f_always",
"always_redraw",
"always_shift",
"always_rotate",
"turn_animation_into_updater",
"cycle_animation",
]
import inspect
from typing import TYPE_CHECKING, Callable
import numpy as np
from manim.constants import DEGREES, RIGHT
from manim.mobject.mobject import Mobject
from manim.opengl import OpenGLMobject
from manim.utils.space_ops import normalize
if TYPE_CHECKING:
from manim.animation.animation import Animation
def assert_is_mobject_method(method: Callable) -> None:
assert inspect.ismethod(method)
mobject = method.__self__
assert isinstance(mobject, (Mobject, OpenGLMobject))
def always(method: Callable, *args, **kwargs) -> Mobject:
assert_is_mobject_method(method)
mobject = method.__self__
func = method.__func__
mobject.add_updater(lambda m: func(m, *args, **kwargs))
return mobject
def f_always(method: Callable[[Mobject], None], *arg_generators, **kwargs) -> Mobject:
"""
More functional version of always, where instead
of taking in args, it takes in functions which output
the relevant arguments.
"""
assert_is_mobject_method(method)
mobject = method.__self__
func = method.__func__
def updater(mob):
args = [arg_generator() for arg_generator in arg_generators]
func(mob, *args, **kwargs)
mobject.add_updater(updater)
return mobject
def always_redraw(func: Callable[[], Mobject]) -> Mobject:
"""Redraw the mobject constructed by a function every frame.
This function returns a mobject with an attached updater that
continuously regenerates the mobject according to the
specified function.
Parameters
----------
func
A function without (required) input arguments that returns
a mobject.
Examples
--------
.. manim:: TangentAnimation
class TangentAnimation(Scene):
def construct(self):
ax = Axes()
sine = ax.plot(np.sin, color=RED)
alpha = ValueTracker(0)
point = always_redraw(
lambda: Dot(
sine.point_from_proportion(alpha.get_value()),
color=BLUE
)
)
tangent = always_redraw(
lambda: TangentLine(
sine,
alpha=alpha.get_value(),
color=YELLOW,
length=4
)
)
self.add(ax, sine, point, tangent)
self.play(alpha.animate.set_value(1), rate_func=linear, run_time=2)
"""
mob = func()
mob.add_updater(lambda _: mob.become(func()))
return mob
def always_shift(
mobject: Mobject, direction: np.ndarray[np.float64] = RIGHT, rate: float = 0.1
) -> Mobject:
"""A mobject which is continuously shifted along some direction
at a certain rate.
Parameters
----------
mobject
The mobject to shift.
direction
The direction to shift. The vector is normalized, the specified magnitude
is not relevant.
rate
Length in Manim units which the mobject travels in one
second along the specified direction.
Examples
--------
.. manim:: ShiftingSquare
class ShiftingSquare(Scene):
def construct(self):
sq = Square().set_fill(opacity=1)
tri = Triangle()
VGroup(sq, tri).arrange(LEFT)
# construct a square which is continuously
# shifted to the right
always_shift(sq, RIGHT, rate=5)
self.add(sq)
self.play(tri.animate.set_fill(opacity=1))
"""
mobject.add_updater(lambda m, dt: m.shift(dt * rate * normalize(direction)))
return mobject
def always_rotate(mobject: Mobject, rate: float = 20 * DEGREES, **kwargs) -> Mobject:
"""A mobject which is continuously rotated at a certain rate.
Parameters
----------
mobject
The mobject to be rotated.
rate
The angle which the mobject is rotated by
over one second.
kwags
Further arguments to be passed to :meth:`.Mobject.rotate`.
Examples
--------
.. manim:: SpinningTriangle
class SpinningTriangle(Scene):
def construct(self):
tri = Triangle().set_fill(opacity=1).set_z_index(2)
sq = Square().to_edge(LEFT)
# will keep spinning while there is an animation going on
always_rotate(tri, rate=2*PI, about_point=ORIGIN)
self.add(tri, sq)
self.play(sq.animate.to_edge(RIGHT), rate_func=linear, run_time=1)
"""
mobject.add_updater(lambda m, dt: m.rotate(dt * rate, **kwargs))
return mobject
def turn_animation_into_updater(
animation: Animation, cycle: bool = False, **kwargs
) -> Mobject:
"""
Add an updater to the animation's mobject which applies
the interpolation and update functions of the animation
If cycle is True, this repeats over and over. Otherwise,
the updater will be popped upon completion
Examples
--------
.. manim:: WelcomeToManim
class WelcomeToManim(Scene):
def construct(self):
words = Text("Welcome to")
banner = ManimBanner().scale(0.5)
VGroup(words, banner).arrange(DOWN)
turn_animation_into_updater(Write(words, run_time=0.9))
self.add(words)
self.wait(0.5)
self.play(banner.expand(), run_time=0.5)
"""
mobject = animation.mobject
animation.suspend_mobject_updating = False
animation.begin()
animation.total_time = 0
def update(m: Mobject, dt: float):
run_time = animation.get_run_time()
time_ratio = animation.total_time / run_time
if cycle:
alpha = time_ratio % 1
else:
alpha = np.clip(time_ratio, 0, 1)
if alpha >= 1:
animation.finish()
m.remove_updater(update)
return
animation.interpolate(alpha)
animation.update_mobjects(dt)
animation.total_time += dt
mobject.add_updater(update)
return mobject
def cycle_animation(animation: Animation, **kwargs) -> Mobject:
return turn_animation_into_updater(animation, cycle=True, **kwargs)
|
manim_ManimCommunity/tests/conftest.py
|
from __future__ import annotations
import sys
from pathlib import Path
import pytest
from manim import config, tempconfig
def pytest_addoption(parser):
parser.addoption(
"--skip_slow",
action="store_true",
default=False,
help="Will skip all the slow marked tests. Slow tests are arbitrarily marked as such.",
)
parser.addoption(
"--show_diff",
action="store_true",
default=False,
help="Will show a visual comparison if a graphical unit test fails.",
)
parser.addoption(
"--set_test",
action="store_true",
default=False,
help="Will create the control data for EACH running tests. ",
)
def pytest_configure(config):
config.addinivalue_line("markers", "skip_end_to_end: mark test as end_to_end test")
def pytest_collection_modifyitems(config, items):
if not config.getoption("--skip_slow"):
return
else:
slow_skip = pytest.mark.skip(
reason="Slow test skipped due to --disable_slow flag.",
)
for item in items:
if "slow" in item.keywords:
item.add_marker(slow_skip)
@pytest.fixture(scope="session")
def python_version():
# use the same python executable as it is running currently
# rather than randomly calling using python or python3, which
# may create problems.
return sys.executable
@pytest.fixture
def reset_cfg_file():
cfgfilepath = Path(__file__).parent / "test_cli" / "manim.cfg"
original = cfgfilepath.read_text()
yield
cfgfilepath.write_text(original)
@pytest.fixture
def using_opengl_renderer():
"""Standard fixture for running with opengl that makes tests use a standard_config.cfg with a temp dir."""
with tempconfig({"renderer": "opengl"}):
yield
# as a special case needed to manually revert back to cairo
# due to side effects of setting the renderer
config.renderer = "cairo"
|
manim_ManimCommunity/tests/__init__.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.