Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Implement metaclass approach in geometry module to make mobjects compatible with cairo and opengl rendering (#1272)

Benjamin Hacklbb92f4b27db8
diff --git a/manim/__init__.py b/manim/__init__.py
index bd5bb6225..903fb922b 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -1,5 +1,7 @@
#!/usr/bin/env python
+# flake8: noqa
+
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
@@ -8,9 +10,29 @@ except ModuleNotFoundError:
__version__ = importlib_metadata.version(__name__)
+import sys
+
# Importing the config module should be the first thing we do, since other
# modules depend on the global config dict for initialization.
from ._config import *
+
+# Workaround to set the renderer passed via CLI args *before* importing
+# Manim's classes (as long as the metaclass approach for switching
+# between OpenGL and cairo rendering is in place, classes depend
+# on the value of config.renderer).
+for i, arg in enumerate(sys.argv):
+ if arg.startswith("--renderer"):
+ if "=" in arg:
+ _, parsed_renderer = arg.split("=")
+ else:
+ parsed_renderer = sys.argv[i + 1]
+ config.renderer = parsed_renderer
+ elif arg == "--use_opengl_renderer":
+ config.renderer = "opengl"
+ elif arg == "--use_webgl_renderer":
+ config.renderer = "webgl"
+
+
from .animation.animation import *
from .animation.composition import *
from .animation.creation import *
diff --git a/manim/mobject/geometry.py b/manim/mobject/geometry.py
index 22882e312..6190708a0 100644
--- a/manim/mobject/geometry.py
+++ b/manim/mobject/geometry.py
@@ -64,10 +64,15 @@ from typing import Sequence
import numpy as np
-from .. import logger
+from .. import config, logger
from ..constants import *
from ..mobject.mobject import Mobject
-from ..mobject.types.vectorized_mobject import DashedVMobject, VGroup, VMobject
+from ..mobject.types.vectorized_mobject import (
+ DashedVMobject,
+ MetaVMobject,
+ VGroup,
+ VMobject,
+)
from ..utils.color import *
from ..utils.iterables import adjacent_n_tuples, adjacent_pairs
from ..utils.simple_functions import fdiv
@@ -81,7 +86,7 @@ from ..utils.space_ops import (
)
-class TipableVMobject(VMobject):
+class TipableVMobject(metaclass=MetaVMobject):
"""
Meant for shared functionality between Arc and Line.
Functionality can be classified broadly into these groups:
@@ -111,7 +116,7 @@ class TipableVMobject(VMobject):
self.tip_length = tip_length
self.normal_vector = normal_vector
self.tip_style = tip_style
- VMobject.__init__(self, **kwargs)
+ super().__init__(**kwargs)
# Adding, Creating, Modifying tips
@@ -197,7 +202,7 @@ class TipableVMobject(VMobject):
def pop_tips(self):
start, end = self.get_start_and_end()
- result = VGroup()
+ result = self.get_group_class()()
if self.has_tip():
result.add(self.tip)
self.remove(self.tip)
@@ -212,7 +217,7 @@ class TipableVMobject(VMobject):
Returns a VGroup (collection of VMobjects) containing
the TipableVMObject instance's tips.
"""
- result = VGroup()
+ result = self.get_group_class()()
if hasattr(self, "tip"):
result.add(self.tip)
if hasattr(self, "start_tip"):
@@ -232,22 +237,22 @@ class TipableVMobject(VMobject):
return self.tip_length
def get_first_handle(self):
- return self.points[1]
+ return self.get_points()[1]
def get_last_handle(self):
- return self.points[-2]
+ return self.get_points()[-2]
def get_end(self):
if self.has_tip():
return self.tip.get_start()
else:
- return VMobject.get_end(self)
+ return super().get_end()
def get_start(self):
if self.has_start_tip():
return self.start_tip.get_start()
else:
- return VMobject.get_start(self)
+ return super().get_start()
def get_length(self):
start, end = self.get_start_and_end()
@@ -276,13 +281,48 @@ class Arc(TipableVMobject):
self.start_angle = start_angle
self.angle = angle
self._failed_to_get_center = False
- TipableVMobject.__init__(self, **kwargs)
+ super().__init__(**kwargs)
def generate_points(self):
self.set_pre_positioned_points()
self.scale(self.radius, about_point=ORIGIN)
self.shift(self.arc_center)
+ # Points are set a bit differently when rendering via OpenGL.
+ # TODO: refactor Arc so that only one strategy for setting points
+ # has to be used.
+ def init_points(self):
+ self.set_points(
+ Arc.create_quadratic_bezier_points(
+ angle=self.angle,
+ start_angle=self.start_angle,
+ n_components=self.num_components,
+ )
+ )
+ self.scale(self.radius, about_point=ORIGIN)
+ self.shift(self.arc_center)
+
+ @staticmethod
+ def create_quadratic_bezier_points(angle, start_angle=0, n_components=8):
+ samples = np.array(
+ [
+ [np.cos(a), np.sin(a), 0]
+ for a in np.linspace(
+ start_angle,
+ start_angle + angle,
+ 2 * n_components + 1,
+ )
+ ]
+ )
+ theta = angle / n_components
+ samples[1::2] /= np.cos(theta / 2)
+
+ points = np.zeros((3 * n_components, 3))
+ points[0::3] = samples[0:-1:2]
+ points[1::3] = samples[1::2]
+ points[2::3] = samples[2::2]
+ return points
+
def set_pre_positioned_points(self):
anchors = np.array(
[
@@ -310,7 +350,7 @@ class Arc(TipableVMobject):
anchors, and finds their intersection points
"""
# First two anchors and handles
- a1, h1, h2, a2 = self.points[:4]
+ a1, h1, h2, a2 = self.get_points()[:4]
if np.all(a1 == a2):
# For a1 and a2 to lie at the same point arc radius
@@ -336,7 +376,7 @@ class Arc(TipableVMobject):
return self
def stop_angle(self):
- return angle_of_vector(self.points[-1] - self.get_arc_center()) % TAU
+ return angle_of_vector(self.get_points()[-1] - self.get_arc_center()) % TAU
class ArcBetweenPoints(Arc):
@@ -376,7 +416,7 @@ class ArcBetweenPoints(Arc):
class CurvedArrow(ArcBetweenPoints):
def __init__(self, start_point, end_point, **kwargs):
- ArcBetweenPoints.__init__(self, start_point, end_point, **kwargs)
+ super().__init__(start_point, end_point, **kwargs)
self.add_tip(tip_shape=kwargs.pop("tip_shape", ArrowTriangleFilledTip))
@@ -385,7 +425,7 @@ class CurvedDoubleArrow(CurvedArrow):
if "tip_shape_end" in kwargs:
kwargs["tip_shape"] = kwargs.pop("tip_shape_end")
tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip)
- CurvedArrow.__init__(self, start_point, end_point, **kwargs)
+ super().__init__(start_point, end_point, **kwargs)
self.add_tip(at_start=True, tip_shape=tip_shape_start)
@@ -516,7 +556,7 @@ class Circle(Arc):
The location of the point along the circle's circumference.
"""
- start_angle = angle_of_vector(self.points[0] - self.get_center())
+ start_angle = angle_of_vector(self.get_points()[0] - self.get_center())
return self.point_from_proportion((angle - start_angle) / TAU)
@@ -561,8 +601,7 @@ class Dot(Circle):
color=WHITE,
**kwargs
):
- Circle.__init__(
- self,
+ super().__init__(
arc_center=point,
radius=radius,
stroke_width=stroke_width,
@@ -585,8 +624,7 @@ class AnnotationDot(Dot):
fill_color=BLUE,
**kwargs
):
- Dot.__init__(
- self,
+ super().__init__(
radius=radius,
stroke_width=stroke_width,
stroke_color=stroke_color,
@@ -673,7 +711,7 @@ class Ellipse(Circle):
"""
def __init__(self, width=2, height=1, **kwargs):
- Circle.__init__(self, **kwargs)
+ super().__init__(**kwargs)
self.stretch_to_fit_width(width)
self.stretch_to_fit_height(height)
@@ -692,8 +730,7 @@ class AnnularSector(Arc):
):
self.inner_radius = inner_radius
self.outer_radius = outer_radius
- Arc.__init__(
- self,
+ super().__init__(
start_angle=start_angle,
angle=angle,
fill_opacity=fill_opacity,
@@ -713,17 +750,17 @@ class AnnularSector(Arc):
for radius in (self.inner_radius, self.outer_radius)
]
outer_arc.reverse_points()
- self.append_points(inner_arc.points)
- self.add_line_to(outer_arc.points[0])
- self.append_points(outer_arc.points)
- self.add_line_to(inner_arc.points[0])
+ self.append_points(inner_arc.get_points())
+ self.add_line_to(outer_arc.get_points()[0])
+ self.append_points(outer_arc.get_points())
+ self.add_line_to(inner_arc.get_points()[0])
+
+ init_points = generate_points
class Sector(AnnularSector):
def __init__(self, outer_radius=1, inner_radius=0, **kwargs):
- AnnularSector.__init__(
- self, inner_radius=inner_radius, outer_radius=outer_radius, **kwargs
- )
+ super().__init__(inner_radius=inner_radius, outer_radius=outer_radius, **kwargs)
class Annulus(Circle):
@@ -740,12 +777,8 @@ class Annulus(Circle):
self.mark_paths_closed = mark_paths_closed # is this even used?
self.inner_radius = inner_radius
self.outer_radius = outer_radius
- Circle.__init__(
- self,
- fill_opacity=fill_opacity,
- stroke_width=stroke_width,
- color=color,
- **kwargs
+ super().__init__(
+ fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs
)
def generate_points(self):
@@ -753,32 +786,43 @@ class Annulus(Circle):
outer_circle = Circle(radius=self.outer_radius)
inner_circle = Circle(radius=self.inner_radius)
inner_circle.reverse_points()
- self.append_points(outer_circle.points)
- self.append_points(inner_circle.points)
+ self.append_points(outer_circle.get_points())
+ self.append_points(inner_circle.get_points())
self.shift(self.arc_center)
+ init_points = generate_points
+
class Line(TipableVMobject):
def __init__(self, start=LEFT, end=RIGHT, buff=0, path_arc=None, **kwargs):
+ self.dim = 3
self.buff = buff
self.path_arc = path_arc
self.set_start_and_end_attrs(start, end)
- TipableVMobject.__init__(self, **kwargs)
+ super().__init__(**kwargs)
def generate_points(self):
- if self.path_arc:
+ self.set_points_by_ends(
+ start=self.start, end=self.end, buff=self.buff, path_arc=self.path_arc
+ )
+
+ def set_points_by_ends(self, start, end, buff=0, path_arc=0):
+ if path_arc:
arc = ArcBetweenPoints(self.start, self.end, angle=self.path_arc)
- self.set_points(arc.points)
+ self.set_points(arc.get_points())
else:
- self.set_points_as_corners([self.start, self.end])
- self.account_for_buff()
+ self.set_points_as_corners([start, end])
+
+ self.account_for_buff(buff)
+
+ init_points = generate_points
def set_path_arc(self, new_value):
self.path_arc = new_value
- self.generate_points()
+ self.init_points()
- def account_for_buff(self):
- if self.buff == 0:
+ def account_for_buff(self, buff):
+ if buff == 0:
return
#
if self.path_arc == 0:
@@ -786,9 +830,9 @@ class Line(TipableVMobject):
else:
length = self.get_arc_length()
#
- if length < 2 * self.buff:
+ if length < 2 * buff:
return
- buff_proportion = self.buff / length
+ buff_proportion = buff / length
self.pointwise_become_partial(self, buff_proportion, 1 - buff_proportion)
return self
@@ -799,7 +843,7 @@ class Line(TipableVMobject):
rough_end = self.pointify(end)
vect = normalize(rough_end - rough_start)
# Now that we know the direction between them,
- # we can the appropriate boundary point from
+ # we can find the appropriate boundary point from
# start and end, if they're mobjects
self.start = self.pointify(start, vect)
self.end = self.pointify(end, -vect)
@@ -870,8 +914,16 @@ class Line(TipableVMobject):
def get_slope(self):
return np.tan(self.get_angle())
- def set_angle(self, angle):
- return self.rotate(angle - self.get_angle(), about_point=self.get_start())
+ def set_angle(self, angle, about_point=None):
+ if about_point is None:
+ about_point = self.get_start()
+
+ self.rotate(
+ angle - self.get_angle(),
+ about_point=about_point,
+ )
+
+ return self
def set_length(self, length):
return self.scale(length / self.get_length())
@@ -933,7 +985,7 @@ class DashedLine(Line):
self.dash_length = dash_length
self.dash_spacing = (dash_spacing,)
self.positive_space_ratio = positive_space_ratio
- Line.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
dashes = DashedVMobject(
self,
num_dashes=self.calculate_num_dashes(),
@@ -992,7 +1044,7 @@ class DashedLine(Line):
if len(self.submobjects) > 0:
return self.submobjects[-1].get_end()
else:
- return Line.get_end(self)
+ return super().get_end()
def get_first_handle(self) -> np.ndarray:
"""Returns the point of the first handle.
@@ -1005,7 +1057,7 @@ class DashedLine(Line):
array([-0.98333333, 0. , 0. ])
"""
- return self.submobjects[0].points[1]
+ return self.submobjects[0].get_points()[1]
def get_last_handle(self) -> np.ndarray:
"""Returns the point of the last handle.
@@ -1018,7 +1070,7 @@ class DashedLine(Line):
array([0.98205128, 0. , 0. ])
"""
- return self.submobjects[-1].points[-2]
+ return self.submobjects[-1].get_points()[-2]
class TangentLine(Line):
@@ -1067,7 +1119,7 @@ class TangentLine(Line):
self.scale(self.length / self.get_length())
-class Elbow(VMobject):
+class Elbow(metaclass=MetaVMobject):
"""Two lines that create a right angle about each other: L-shape.
Parameters
@@ -1101,7 +1153,7 @@ class Elbow(VMobject):
def __init__(self, width=0.2, angle=0, **kwargs):
self.angle = angle
- VMobject.__init__(self, **kwargs)
+ super().__init__(**kwargs)
self.set_points_as_corners([UP, UP + RIGHT, RIGHT])
self.scale_to_fit_width(width, about_point=ORIGIN)
self.rotate(self.angle, about_point=ORIGIN)
@@ -1175,7 +1227,7 @@ class Arrow(Line):
preserve_tip_size_when_scaling # is this used anywhere
)
tip_shape = kwargs.pop("tip_shape", ArrowTriangleFilledTip)
- Line.__init__(self, *args, buff=buff, stroke_width=stroke_width, **kwargs)
+ super().__init__(*args, buff=buff, stroke_width=stroke_width, **kwargs)
# TODO, should this be affected when
# Arrow.set_stroke is called?
self.initial_stroke_width = self.stroke_width
@@ -1214,7 +1266,7 @@ class Arrow(Line):
return self
if scale_tips:
- VMobject.scale(self, factor, **kwargs)
+ super().scale(factor, **kwargs)
self.set_stroke_width_from_length()
return self
@@ -1223,7 +1275,7 @@ class Arrow(Line):
if has_tip or has_start_tip:
old_tips = self.pop_tips()
- VMobject.scale(self, factor, **kwargs)
+ super().scale(factor, **kwargs)
self.set_stroke_width_from_length()
if has_tip:
@@ -1269,10 +1321,16 @@ class Arrow(Line):
def set_stroke_width_from_length(self):
"""Used internally. Sets stroke width based on length."""
max_ratio = self.max_stroke_width_to_length_ratio
- self.set_stroke(
- width=min(self.initial_stroke_width, max_ratio * self.get_length()),
- family=False,
- )
+ if config.renderer == "opengl":
+ self.set_stroke(
+ width=min(self.initial_stroke_width, max_ratio * self.get_length()),
+ recurse=False,
+ )
+ else:
+ self.set_stroke(
+ width=min(self.initial_stroke_width, max_ratio * self.get_length()),
+ family=False,
+ )
return self
@@ -1305,8 +1363,9 @@ class Vector(Arrow):
def __init__(self, direction=RIGHT, buff=0, **kwargs):
self.buff = buff
if len(direction) == 2:
- direction = np.append(np.array(direction), 0)
- Arrow.__init__(self, ORIGIN, direction, buff=buff, **kwargs)
+ direction = np.hstack([direction, 0])
+
+ super().__init__(ORIGIN, direction, buff=buff, **kwargs)
def coordinate_label(
self, integer_labels: bool = True, n_dim: int = 2, color: str = WHITE
@@ -1396,11 +1455,11 @@ class DoubleArrow(Arrow):
if "tip_shape_end" in kwargs:
kwargs["tip_shape"] = kwargs.pop("tip_shape_end")
tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip)
- Arrow.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
self.add_tip(at_start=True, tip_shape=tip_shape_start)
-class CubicBezier(VMobject):
+class CubicBezier(metaclass=MetaVMobject):
"""
Example
-------
@@ -1424,11 +1483,11 @@ class CubicBezier(VMobject):
"""
def __init__(self, start_anchor, start_handle, end_handle, end_anchor, **kwargs):
- VMobject.__init__(self, **kwargs)
- self.set_points([start_anchor, start_handle, end_handle, end_anchor])
+ super().__init__(**kwargs)
+ self.add_cubic_bezier_curve(start_anchor, start_handle, end_handle, end_anchor)
-class Polygon(VMobject):
+class Polygon(metaclass=MetaVMobject):
"""A shape created by defining its vertices.
Parameters
@@ -1462,8 +1521,7 @@ class Polygon(VMobject):
"""
def __init__(self, *vertices, color=BLUE, **kwargs):
- VMobject.__init__(self, color=color, **kwargs)
- # There are actually four corners, and the first one is repeated twice to form the four vertices.
+ super().__init__(color=color, **kwargs)
self.set_points_as_corners([*vertices, vertices[0]])
def get_vertices(self):
@@ -1545,7 +1603,7 @@ class Polygon(VMobject):
# To ensure that we loop through starting with last
arcs = [arcs[-1], *arcs[:-1]]
for arc1, arc2 in adjacent_pairs(arcs):
- self.append_points(arc1.points)
+ self.append_points(arc1.get_points())
line = Line(arc1.get_end(), arc2.get_start())
# Make sure anchors are evenly distributed
len_ratio = line.get_length() / arc1.get_arc_length()
@@ -1591,10 +1649,10 @@ class RegularPolygon(Polygon):
self.start_angle = 90 * DEGREES
start_vect = rotate_vector(RIGHT, self.start_angle)
vertices = compass_directions(n, start_vect)
- Polygon.__init__(self, *vertices, **kwargs)
+ super().__init__(*vertices, **kwargs)
-class ArcPolygon(VMobject):
+class ArcPolygon(metaclass=MetaVMobject):
"""A generalized polygon allowing for points to be connected with arcs.
This version tries to stick close to the way :class:`Polygon` is used. Points
@@ -1697,14 +1755,14 @@ class ArcPolygon(VMobject):
# the arcs, so that their new values are usable.
self.add(*arcs)
for arc in arcs:
- self.append_points(arc.points)
+ self.append_points(arc.get_points())
# This enables the use of ArcPolygon.arcs as a convenience
# because ArcPolygon[0] returns itself, not the first Arc.
self.arcs = arcs
-class ArcPolygonFromArcs(VMobject):
+class ArcPolygonFromArcs(metaclass=MetaVMobject):
"""A generalized polygon allowing for points to be connected with arcs.
This version takes in pre-defined arcs to generate the arcpolygon and introduces
@@ -1855,7 +1913,7 @@ class Triangle(RegularPolygon):
"""
def __init__(self, **kwargs):
- RegularPolygon.__init__(self, n=3, **kwargs)
+ super().__init__(n=3, **kwargs)
class Rectangle(Polygon):
@@ -1902,7 +1960,7 @@ class Rectangle(Polygon):
):
self.mark_paths_closed = mark_paths_closed
self.close_new_points = close_new_points
- Polygon.__init__(self, UR, UL, DL, DR, color=color, **kwargs)
+ super().__init__(UR, UL, DL, DR, color=color, **kwargs)
self.stretch_to_fit_width(width)
self.stretch_to_fit_height(height)
@@ -1933,7 +1991,7 @@ class Square(Rectangle):
def __init__(self, side_length=2.0, **kwargs):
self.side_length = side_length
- Rectangle.__init__(self, height=side_length, width=side_length, **kwargs)
+ super().__init__(height=side_length, width=side_length, **kwargs)
class RoundedRectangle(Rectangle):
@@ -1963,11 +2021,11 @@ class RoundedRectangle(Rectangle):
def __init__(self, corner_radius=0.5, **kwargs):
self.corner_radius = corner_radius
- Rectangle.__init__(self, **kwargs)
+ super().__init__(**kwargs)
self.round_corners(self.corner_radius)
-class ArrowTip(VMobject):
+class ArrowTip(metaclass=MetaVMobject):
r"""Base class for arrow tips.
See Also
@@ -2071,7 +2129,7 @@ class ArrowTip(VMobject):
array([2., 0., 0.])
"""
- return self.points[0]
+ return self.get_points()[0]
@property
def vector(self):
@@ -2148,9 +2206,7 @@ class ArrowTriangleFilledTip(ArrowTriangleTip):
"""
def __init__(self, fill_opacity=1, stroke_width=0, **kwargs):
- ArrowTriangleTip.__init__(
- self, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs
- )
+ super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs)
class ArrowCircleTip(ArrowTip, Circle):
@@ -2176,9 +2232,7 @@ class ArrowCircleFilledTip(ArrowCircleTip):
r"""Circular arrow tip with filled tip."""
def __init__(self, fill_opacity=1, stroke_width=0, **kwargs):
- ArrowCircleTip.__init__(
- self, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs
- )
+ super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs)
class ArrowSquareTip(ArrowTip, Square):
@@ -2208,12 +2262,10 @@ class ArrowSquareFilledTip(ArrowSquareTip):
r"""Square arrow tip with filled tip."""
def __init__(self, fill_opacity=1, stroke_width=0, **kwargs):
- ArrowSquareTip.__init__(
- self, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs
- )
+ super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs)
-class Cutout(VMobject):
+class Cutout(metaclass=MetaVMobject):
"""A shape with smaller cutouts.
.. warning::
@@ -2249,7 +2301,7 @@ class Cutout(VMobject):
"""
def __init__(self, main_shape, *mobjects, **kwargs):
- VMobject.__init__(self, **kwargs)
+ super().__init__(**kwargs)
self.append_points(main_shape.get_points())
if main_shape.get_direction() == "CW":
sub_direction = "CCW"
@@ -2259,7 +2311,7 @@ class Cutout(VMobject):
self.append_points(mobject.force_direction(sub_direction).get_points())
-class Angle(Arc, Elbow):
+class Angle(metaclass=MetaVMobject):
"""A circular arc or elbow-type mobject representing an angle of two lines.
Parameters
@@ -2382,6 +2434,7 @@ class Angle(Arc, Elbow):
elbow=False,
**kwargs
):
+ super().__init__(**kwargs)
self.quadrant = quadrant
self.dot_distance = dot_distance
self.elbow = elbow
@@ -2414,8 +2467,10 @@ class Angle(Arc, Elbow):
+ quadrant[0] * radius * line1.get_unit_vector()
+ quadrant[1] * radius * line2.get_unit_vector()
)
- Elbow.__init__(self, **kwargs)
- self.set_points_as_corners([anchor_angle_1, anchor_middle, anchor_angle_2])
+ angle_mobject = Elbow(**kwargs)
+ angle_mobject.set_points_as_corners(
+ [anchor_angle_1, anchor_middle, anchor_angle_2]
+ )
else:
angle_1 = angle_of_vector(anchor_angle_1 - inter)
angle_2 = angle_of_vector(anchor_angle_2 - inter)
@@ -2433,14 +2488,14 @@ class Angle(Arc, Elbow):
else:
angle_fin = -2 * np.pi + (angle_2 - angle_1)
- Arc.__init__(
- self,
+ angle_mobject = Arc(
radius=radius,
angle=angle_fin,
start_angle=start_angle,
arc_center=inter,
**kwargs
)
+
if dot:
if dot_radius is None:
dot_radius = radius / 10
@@ -2457,11 +2512,7 @@ class Angle(Arc, Elbow):
right_dot.move_to(dot_anchor)
self.add(right_dot)
- def generate_points(self):
- if self.elbow:
- Elbow.generate_points(self)
- else:
- Arc.generate_points(self)
+ self.set_points(angle_mobject.get_points())
class RightAngle(Angle):
@@ -2503,4 +2554,4 @@ class RightAngle(Angle):
"""
def __init__(self, line1, line2, length=None, **kwargs):
- Angle.__init__(self, line1, line2, radius=length, elbow=True, **kwargs)
+ super().__init__(line1, line2, radius=length, elbow=True, **kwargs)
diff --git a/manim/mobject/opengl_mobject.py b/manim/mobject/opengl_mobject.py
index 4a5ab9f63..a4003bdd4 100644
--- a/manim/mobject/opengl_mobject.py
+++ b/manim/mobject/opengl_mobject.py
@@ -886,9 +886,13 @@ class OpenGLMobject:
def set_width(self, width, stretch=False, **kwargs):
return self.rescale_to_fit(width, 0, stretch=stretch, **kwargs)
+ scale_to_fit_width = set_width
+
def set_height(self, height, stretch=False, **kwargs):
return self.rescale_to_fit(height, 1, stretch=stretch, **kwargs)
+ scale_to_fit_height = set_height
+
def set_depth(self, depth, stretch=False, **kwargs):
return self.rescale_to_fit(depth, 2, stretch=stretch, **kwargs)
diff --git a/manim/mobject/shape_matchers.py b/manim/mobject/shape_matchers.py
index 633917c80..b1df0c45f 100644
--- a/manim/mobject/shape_matchers.py
+++ b/manim/mobject/shape_matchers.py
@@ -59,8 +59,7 @@ class BackgroundRectangle(SurroundingRectangle):
family=True,
):
# Unchangeable style, except for fill_opacity
- VMobject.set_style(
- self,
+ super().set_style(
stroke_color=BLACK,
stroke_width=0,
fill_color=BLACK,
diff --git a/manim/mobject/types/opengl_vectorized_mobject.py b/manim/mobject/types/opengl_vectorized_mobject.py
index e6eb5250a..8dfd294b5 100644
--- a/manim/mobject/types/opengl_vectorized_mobject.py
+++ b/manim/mobject/types/opengl_vectorized_mobject.py
@@ -29,6 +29,7 @@ from ...utils.space_ops import (
cross2d,
earclip_triangulation,
get_unit_normal,
+ shoelace_direction,
z_to_vector,
)
@@ -514,6 +515,19 @@ class OpenGLVMobject(OpenGLMobject):
return np.linalg.norm(p1 - p0) < self.tolerance_for_point_equality
# Information about the curve
+ def force_direction(self, target_direction):
+ if target_direction not in ("CW", "CCW"):
+ raise ValueError('Invalid input for force_direction. Use "CW" or "CCW"')
+
+ if self.get_direction() != target_direction:
+ self.reverse_points()
+
+ return self
+
+ def reverse_direction(self):
+ self.set_points(self.get_points()[::-1])
+ return self
+
def get_bezier_tuples_from_points(self, points):
nppc = self.n_points_per_curve
remainder = len(points) % nppc
@@ -762,6 +776,9 @@ class OpenGLVMobject(OpenGLMobject):
]
)
+ def get_direction(self):
+ return shoelace_direction(self.get_start_anchors())
+
def get_unit_normal(self, recompute=False):
if not recompute:
return self.data["unit_normal"][0]
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index 7e512949a..9050062bf 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -14,12 +14,14 @@ __all__ = [
import itertools as it
import sys
import typing
+from abc import ABCMeta
from typing import Optional, Sequence, Union
import colour
import numpy as np
from PIL.Image import Image
+from ... import config
from ...constants import *
from ...mobject.mobject import Mobject
from ...mobject.three_d_utils import get_3d_vmob_gradient_start_and_end_points
@@ -34,6 +36,7 @@ from ...utils.color import BLACK, WHITE, color_to_rgba
from ...utils.iterables import make_even, stretch_array_to_length, tuplify
from ...utils.simple_functions import clip_in_place
from ...utils.space_ops import rotate_vector, shoelace_direction
+from .opengl_vectorized_mobject import OpenGLVMobject
# TODO
# - Change cubic curve groups to have 4 points instead of 3
@@ -44,6 +47,26 @@ from ...utils.space_ops import rotate_vector, shoelace_direction
# That's kind of weird.
+class MetaVMobject(ABCMeta):
+ """Metaclass for initializing corresponding classes as either inheriting from
+ VMobject or OpenGLVMobject, depending on the value of ``config.renderer`` at
+ initialization time.
+
+ Note that with this implementation, changing the value of ``config.renderer``
+ after Manim has been imported won't have the desired effect and will lead to
+ spurious errors.
+ """
+
+ def __new__(cls, name, bases, namespace):
+ if len(bases) == 0:
+ if config.renderer == "opengl":
+ bases = (OpenGLVMobject,)
+ else:
+ bases = (VMobject,)
+
+ return super().__new__(cls, name, bases, namespace)
+
+
class VMobject(Mobject):
def __init__(
self,
@@ -1909,13 +1932,13 @@ class CurvesAsSubmobjects(VGroup):
self.add(part)
-class DashedVMobject(VMobject):
+class DashedVMobject(metaclass=MetaVMobject):
def __init__(
self, vmobject, num_dashes=15, positive_space_ratio=0.5, color=WHITE, **kwargs
):
self.num_dashes = num_dashes
self.positive_space_ratio = positive_space_ratio
- VMobject.__init__(self, color=color, **kwargs)
+ super().__init__(color=color, **kwargs)
ps_ratio = self.positive_space_ratio
if num_dashes > 0:
# End points of the unit interval for division
@@ -1944,4 +1967,7 @@ class DashedVMobject(VMobject):
)
# Family is already taken care of by get_subcurve
# implementation
- self.match_style(vmobject, family=False)
+ if config.renderer == "opengl":
+ self.match_style(vmobject, recurse=False)
+ else:
+ self.match_style(vmobject, family=False)
diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.py
index aae9d1a98..2dbcc93c9 100644
--- a/manim/utils/space_ops.py
+++ b/manim/utils/space_ops.py
@@ -51,7 +51,7 @@ def get_norm(vect):
def norm_squared(v):
- return np.linalg.dot(v, v)
+ return np.dot(v, v)
# Quaternions