Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Implement mobject core and shapes

Sina Atalay4aa70db5d3cc
diff --git a/src/manimgx/drawing/geometry.py b/src/manimgx/drawing/geometry.py
index 679a67ca..f5aea8e0 100644
--- a/src/manimgx/drawing/geometry.py
+++ b/src/manimgx/drawing/geometry.py
@@ -19,7 +19,8 @@ import math
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field
from types import ModuleType
-from typing import TYPE_CHECKING, Final, Literal
+from typing import TYPE_CHECKING, Final, Literal, NamedTuple
+from warnings import deprecated
import numpy as np
import numpy.typing as npt
@@ -161,6 +162,7 @@ def rotation_matrix(angle: float, axis: Vector3DLike = _OUT) -> MatrixMN:
)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def rotation_about_z(angle: float) -> MatrixMN:
"""The matrix of a rotation about the z axis.
@@ -193,6 +195,7 @@ def rotate_vector(
return rotation_matrix(angle, axis) @ v
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def z_to_vector(vector: Vector3DLike) -> MatrixMN:
"""A rotation that takes the z axis to a vector's direction.
@@ -262,6 +265,7 @@ def turn_between(v1: Vector3DLike, v2: Vector3DLike) -> tuple[float, Vector3D]:
)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_unit_normal(v1: Vector3DLike, v2: Vector3DLike, tol: float = 1e-6) -> Vector3D:
"""A unit vector perpendicular to two vectors: their cross product, normalized.
@@ -297,6 +301,7 @@ def get_unit_normal(v1: Vector3DLike, v2: Vector3DLike, tol: float = 1e-6) -> Ve
return cp / np.linalg.norm(cp)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def compass_directions(n: int = 4, start_vect: Vector3DLike = _RIGHT) -> Point3D_Array:
"""Vectors evenly spread around the z axis, counterclockwise from a first one.
@@ -317,6 +322,7 @@ def compass_directions(n: int = 4, start_vect: Vector3DLike = _RIGHT) -> Point3D
)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def regular_vertices(
n: int, *, radius: float = 1, start_angle: float | None = None
) -> tuple[Point3D_Array, float]:
@@ -363,6 +369,7 @@ def line_intersection(line1: Point3DLike_Array, line2: Point3DLike_Array) -> Poi
return np.array([x / z, y / z, 0])
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def find_intersection(
p0s: Point3DLike_Array,
v0s: Point3DLike_Array,
@@ -447,6 +454,7 @@ def spherical_to_cartesian(spherical: np.ndarray) -> Vector3D:
)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def shoelace(xy: np.ndarray) -> float:
"""The signed area of the polygon through points in turn, back to the first: the
integral of y dx around it.
@@ -464,6 +472,7 @@ def shoelace(xy: np.ndarray) -> float:
return float((np.roll(x, -1) - x) @ (np.roll(y, -1) + y) / 2)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def shoelace_direction(xy: np.ndarray) -> str:
"""Which way a polygon runs around: "CW" (clockwise) if its
[shoelace][manimgx.shoelace] area is positive, "CCW" (counterclockwise) otherwise.
@@ -497,6 +506,7 @@ def perpendicular_bisector(
return np.array([m + direction, m - direction])
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def cross2d(a: np.ndarray, b: np.ndarray) -> npt.NDArray[np.float64] | float:
"""The z of the cross product of vectors in the xy plane: `a.x·b.y − a.y·b.x`.
@@ -512,6 +522,7 @@ def cross2d(a: np.ndarray, b: np.ndarray) -> npt.NDArray[np.float64] | float:
return a[0] * b[1] - b[0] * a[1]
+@deprecated("use numpy: np.mean(points, axis=0)", category=None)
def center_of_mass(points: Point3D_Array) -> Point3D:
"""The average of points.
@@ -521,6 +532,7 @@ def center_of_mass(points: Point3D_Array) -> Point3D:
return np.average(np.asarray(points), 0)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def angle_axis_from_quaternion(quaternion: np.ndarray) -> tuple[float, Vector3D]:
"""The angle and axis of a unit quaternion (w, x, y, z): the angle 2·arccos(w),
taken from 2π when it is larger than π, and the axis (x, y, z), normalized.
@@ -538,6 +550,7 @@ def angle_axis_from_quaternion(quaternion: np.ndarray) -> tuple[float, Vector3D]
return angle, axis
+@deprecated("use numpy: 1 / (1 + np.exp(-x))", category=None)
def sigmoid(x: float) -> float:
"""The logistic function, 1 / (1 + e^(−x)): from 0 to 1, 1/2 at 0.
@@ -579,6 +592,7 @@ def complex_func_to_R3_func(
return lambda p: complex_to_R3(complex_func(R3_to_complex(p)))
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def norm_squared(v: Vector3DLike) -> float:
"""A vector's length, squared.
@@ -592,6 +606,7 @@ def norm_squared(v: Vector3DLike) -> float:
return float(np.dot(v, v))
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def rotation_matrix_transpose(angle: float, axis: Vector3DLike) -> MatrixMN:
"""The transpose of [rotation_matrix][manimgx.rotation_matrix]: the rotation by
`-angle`.
@@ -606,6 +621,7 @@ def rotation_matrix_transpose(angle: float, axis: Vector3DLike) -> MatrixMN:
return rotation_matrix(angle, axis).T
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def rotation_matrix_from_quaternion(quat: np.ndarray) -> MatrixMN:
"""The matrix of the rotation by a unit quaternion.
@@ -625,6 +641,7 @@ def rotation_matrix_from_quaternion(quat: np.ndarray) -> MatrixMN:
)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_winding_number(points: Point3DLike_Array) -> float:
"""How many times the closed polygon through points winds counterclockwise around
the origin, in the xy plane.
@@ -646,6 +663,7 @@ def get_winding_number(points: Point3DLike_Array) -> float:
return total / (2 * np.pi)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def quaternion_mult(*quats: Sequence[float] | npt.NDArray[np.float64]) -> list[float]:
"""The product of quaternions (w, x, y, z), in order: the first times the second,
and so on.
@@ -668,11 +686,14 @@ def quaternion_mult(*quats: Sequence[float] | npt.NDArray[np.float64]) -> list[f
return result
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def quaternion_from_angle_axis(
angle: float, axis: np.ndarray, axis_normalized: bool = False
) -> list[float]:
"""The unit quaternion (w, x, y, z) of a rotation about an axis.
+ Raises ValueError for a zero axis: a turn about no axis is no turn at all.
+
Args:
angle: The angle, in radians.
axis: The axis's direction.
@@ -681,12 +702,13 @@ def quaternion_from_angle_axis(
Returns:
The quaternion, cos(angle/2) followed by the axis times sin(angle/2).
"""
- return [
- np.cos(angle / 2),
- *np.sin(angle / 2) * (axis if axis_normalized else normalize(axis)),
- ]
+ unit = axis if axis_normalized else normalize(axis)
+ if not np.any(unit):
+ raise ValueError(f"a rotation's axis must not be zero, not {axis}")
+ return [np.cos(angle / 2), *np.sin(angle / 2) * unit]
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def quaternion_conjugate(
quaternion: Sequence[float] | npt.NDArray[np.float64],
) -> Vec:
@@ -700,6 +722,7 @@ def quaternion_conjugate(
return result
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def rotation_matrix_transpose_from_quaternion(quat: np.ndarray) -> list[Vec]:
"""The transpose of the matrix of the rotation by a unit quaternion: its rows are
where the x, y and z axes go.
@@ -717,6 +740,7 @@ def rotation_matrix_transpose_from_quaternion(quat: np.ndarray) -> list[Vec]:
]
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def thick_diagonal(dim: int, thickness: int = 2) -> npt.NDArray[np.uint8]:
"""A square matrix of ones in a band along its diagonal, and zeros elsewhere.
@@ -731,6 +755,7 @@ def thick_diagonal(dim: int, thickness: int = 2) -> npt.NDArray[np.uint8]:
return (np.abs(rows - rows.T) < thickness).astype("uint8")
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def normalize_along_axis(array: np.ndarray, axis: int) -> npt.NDArray[np.float64]:
"""Divide the vectors along an array's last axis by their lengths, in place (zero
vectors are left as they are).
@@ -749,6 +774,7 @@ def normalize_along_axis(array: np.ndarray, axis: int) -> npt.NDArray[np.float64
return array
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def earclip_triangulation(
verts: Point3DLike_Array, ring_ends: Sequence[int]
) -> list[int]:
@@ -1014,6 +1040,10 @@ class Horizon:
self.boundary: list[SubFacet] = []
+@deprecated(
+ "Manim CE's machinery for ConvexHull: use ConvexHull, or ConvexHull3D",
+ category=None,
+)
class QuickHull:
"""The convex hull of points, in two dimensions or more, by the Quickhull algorithm.
@@ -1071,9 +1101,9 @@ class QuickHull:
them the farthest, the next point to add; [build][manimgx.QuickHull.build] calls
it for each facet it makes.
"""
- assert (
- self.unclaimed is not None
- ), "Call .initialize() before using .classify()."
+ assert self.unclaimed is not None, (
+ "Call .initialize() before using .classify()."
+ )
if not self.unclaimed.size:
self.outside[facet] = (None, None)
@@ -1187,9 +1217,7 @@ def interpolate[T](start: T, end: T, alpha: float | np.ndarray) -> T:
Returns:
The value between.
"""
- return (
- 1 - alpha
- ) * start + alpha * end # pyright: ignore[reportOperatorIssue] # ty: ignore[unsupported-operator] # T: numbers, arrays
+ return (1 - alpha) * start + alpha * end # pyright: ignore[reportOperatorIssue] # ty: ignore[unsupported-operator] # T: numbers, arrays
def integer_interpolate(start: float, end: float, alpha: float) -> tuple[int, float]:
@@ -1600,8 +1628,8 @@ class Path:
angle: The angle an "arc" or "spiral" path turns through, in radians,
counterclockwise about `axis`.
axis: The axis the path turns about.
- steps: The steps of a "motion" path, taken in order (see
- [carried][manimgx.carried]).
+ steps: The steps of a "motion" path, taken in order: each a move (a vector), a
+ move along a curve, or a turn about a pivot.
"""
kind: Literal["motion", "arc", "spiral"] = "motion"
@@ -1610,6 +1638,7 @@ class Path:
steps: tuple[Step, ...] = ()
_end: list[Floats] = field(default_factory=list, init=False, repr=False) # G(1)
+ @deprecated("manimgx's machinery: a transform calls it", category=None)
def coefficients(self, alpha: float) -> Coefficients:
"""The path's rule at a moment: each point goes to Lₛ·start + Lₑ·end + k.
@@ -1645,6 +1674,7 @@ class Path:
cs, ce = 0.5 * _EYE - k, 0.5 * _EYE + k
return (_EYE - rot) @ cs + rot - along, (_EYE - rot) @ ce + along, _ZERO
+ @deprecated("manimgx's machinery: a transform calls it", category=None)
def motion(self, alpha: float) -> Floats:
"""The motion the path's steps have carried the shape by at a moment.
@@ -1663,6 +1693,7 @@ class Path:
return start @ ls.T + end @ le.T + k
+@deprecated("manimgx's machinery: a transform calls it", category=None)
def carried(steps: Iterable[tuple[Step, float]]) -> Floats:
"""The motion of steps taken in order, each as far as its own fraction.
@@ -1813,13 +1844,13 @@ class Shape:
def box(self, curves: bool) -> Floats:
"""(2, 3): the box of what the points make — for a path (`curves`), its curves' tight box
- (`curve_box`). Kept, as the shape never changes."""
+ (`curve_box`). Kept, as the shape never changes, and read-only: a value."""
boxes = self._boxes
if boxes is None:
boxes = self._boxes = {}
box = boxes.get(curves)
if box is None:
- box = boxes[curves] = extent(self.array, curves)
+ box = boxes[curves] = _frozen(extent(self.array, curves))
return box
def extended(self, rows: Floats) -> Shape:
@@ -1967,6 +1998,12 @@ SEGMENT: Final = Shape(
)
+def _frozen(array: Floats) -> Floats:
+ """`array`, read-only: what is cached is handed out as a value."""
+ array.setflags(write=False) # (cheaper than `flags.writeable`: no flags object)
+ return array
+
+
def curve_box(points: Floats) -> Floats:
"""(2, D): the tight box of cubic Bézier curves (control points in fours). The anchors lie on
the curves, and each curve lies in its control points' hull, so the anchors' box is tight
@@ -2041,13 +2078,13 @@ class Blend:
def box(self, curves: bool) -> Floats:
"""(2, 3): the box of what the points make — for a path (`curves`), its curves' tight box:
not its anchors' (a curve bulges between them), not its handles' (they overshoot).
- Cached: a blend never changes."""
+ Cached, as a blend never changes, and read-only: a value."""
boxes = self._boxes
if boxes is None:
boxes = self._boxes = {}
box = boxes.get(curves)
if box is None:
- box = boxes[curves] = (
+ box = boxes[curves] = _frozen(
placed_box(*self.terms[0], curves) # one shape placed
if len(self.terms) == 1
else extent(self.points(), curves)
@@ -2099,7 +2136,7 @@ class Blend:
moved[:, 3] += vector
blend = Blend(((moved, shape), *rest), self.n)
if self._boxes:
- blend._boxes = {k: box + vector for k, box in self._boxes.items()}
+ blend._boxes = {k: _frozen(box + vector) for k, box in self._boxes.items()}
return blend
def scaled(self, factor: float, about: Floats) -> Blend:
@@ -2114,7 +2151,7 @@ class Blend:
blend._boxes = {}
for k, box in self._boxes.items():
ends = (box - about) * factor + about
- blend._boxes[k] = ends if factor >= 0 else ends[::-1].copy()
+ blend._boxes[k] = _frozen(ends if factor >= 0 else ends[::-1].copy())
return blend
def transformed(self, m: Matrix) -> Blend:
@@ -2130,7 +2167,9 @@ class Blend:
blend._boxes = {}
for k, box in self._boxes.items():
ends = box * d + m[:, 3]
- blend._boxes[k] = np.array([ends.min(axis=0), ends.max(axis=0)])
+ blend._boxes[k] = _frozen(
+ np.array([ends.min(axis=0), ends.max(axis=0)])
+ )
return blend
@staticmethod
@@ -2221,3 +2260,32 @@ def grid_triangles(u: int, v: int) -> np.ndarray:
triangles = np.stack([a, b, c, a, c, d], axis=-1).reshape(-1, 3)
triangles.flags.writeable = False
return triangles
+
+
+class Lattice(NamedTuple):
+ """A sampled surface's topology: its samples a (u + 1) by (v + 1) grid, its faces the
+ u by v cells between them in u-major order, of which it draws `first` to `end`: all,
+ or a part's (the faces a reveal over the part's stretch shows)."""
+
+ u: int
+ v: int
+ first: int
+ end: int
+
+ @classmethod
+ def of(cls, u: int, v: int) -> Lattice:
+ """All the faces of a u by v lattice."""
+ return cls(u, v, 0, u * v)
+
+ def triangles(self) -> np.ndarray:
+ """The faces it draws, two triangles each: indices into its samples, read-only,
+ and one array for equal lattices."""
+ return _lattice_triangles(*self)
+
+
+@forgets
+def _lattice_triangles(u: int, v: int, first: int, end: int) -> np.ndarray:
+ """A lattice's drawn faces' triangles: the whole grid's array when it draws them all."""
+ every = grid_triangles(u, v)
+ return every if (first, end) == (0, u * v) else every[2 * first : 2 * end]
diff --git a/src/manimgx/mobject.py b/src/manimgx/mobject.py
new file mode 100644
index 00000000..5bfb1afd
--- /dev/null
+++ b/src/manimgx/mobject.py
@@ -0,0 +1,6548 @@
+"Mutable scene objects: one family graph, shared geometry and paint, and path, point and mesh leaf rules."
+
+import copy
+import functools
+import inspect
+import itertools as it
+import math
+import pathlib
+import random
+import types
+import weakref
+from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping, Sequence
+from fractions import Fraction
+from functools import reduce
+from typing import (
+ TYPE_CHECKING,
+ ClassVar,
+ Concatenate,
+ Final,
+ Literal,
+ Never,
+ Self,
+ TypedDict,
+ TypeIs,
+ Unpack,
+ cast,
+ overload,
+)
+
+import numpy as np
+import numpy.typing as npt
+
+from manimgx import caches
+from manimgx.animation import clock
+from manimgx.caches import Memo, unchanged
+from manimgx.config import config
+from manimgx.constants import (
+ DEFAULT_MOBJECT_TO_EDGE_BUFFER,
+ DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
+ DEFAULT_POINT_DENSITY_1D,
+ DEFAULT_STROKE_WIDTH,
+ DL,
+ DOWN,
+ IN,
+ LEFT,
+ MED_SMALL_BUFF,
+ ORIGIN,
+ OUT,
+ RIGHT,
+ TAU,
+ UL,
+ UP,
+ CapStyleType,
+ LineJointType,
+)
+from manimgx.drawing.geometry import (
+ _NPPCC,
+ EMPTY,
+ Blend,
+ Path,
+ _pathops,
+ bezier,
+ bezier_remap,
+ get_smooth_cubic_bezier_handle_points,
+ grid_triangles,
+ integer_interpolate,
+ interpolate,
+ linear_about,
+ normalize,
+ partial_bezier_points,
+ rotation_matrix,
+ segment,
+ shoelace_direction,
+ straight_path,
+ subpath_ranges,
+ turn_between,
+)
+from manimgx.drawing.paint import (
+ BLACK,
+ WHITE,
+ Colors,
+ Look,
+ ManimColor,
+ Material,
+ Paint,
+ PaintAttribute,
+ ParsableManimColor,
+ SimpleStyle,
+ Style,
+ StyleBase,
+ StyleSnapshot,
+ color_gradient,
+ frozen,
+ interpolate_color,
+ key_of,
+ parse_colors,
+ stretch_array,
+)
+from manimgx.typing import (
+ MatrixMN,
+ PathFunc,
+ Point3D,
+ Point3D_Array,
+ Point3DLike,
+ Point3DLike_Array,
+ PointsFunc,
+ RGBA_Array,
+ Vector3D,
+ Vector3DLike,
+)
+
+__all__ = [
+ "ComplexValueTracker",
+ "Group",
+ "MeshMobject",
+ "Mobject",
+ "Mobject1D",
+ "PGroup",
+ "PMobject",
+ "Point",
+ "VDict",
+ "VGroup",
+ "VMobject",
+ "ValueTracker",
+ "VectorizedPoint",
+ "override_animate",
+ "override_animation",
+ "remove_list_redundancies",
+]
+
+if TYPE_CHECKING:
+ from manimgx.animation.timeline import Animation
+ from manimgx.animation.transform import Always, Animate
+
+type Updater[M] = Callable[[M], object] | Callable[[M, float], object]
+"""A function that keeps a mobject updated: called with the mobject once a frame, or, if
+it has a parameter named `dt`, with the mobject and the seconds since it last ran. What
+it returns is ignored; see [add_updater][manimgx.Mobject.add_updater]."""
+
+type _Recorder = tuple[
+ "Mobject", Callable[..., object], Sequence[Callable[..., object]]
+]
+
+
+def axis_factors(factor: float | Vector3DLike) -> np.ndarray:
+ """A scale's factors along x, y and z.
+
+ Args:
+ factor: One factor for every axis, or one per axis.
+
+ Returns:
+ The three factors.
+ """
+ return np.broadcast_to(np.asarray(factor, dtype=float), 3)
+
+
+def length_factor(factor: float | Vector3DLike) -> float:
+ """How a scale changes a length that has no direction, such as a stroke's width or a
+ font's size.
+
+ Args:
+ factor: The scale's factor, or its factors along x, y and z.
+
+ Returns:
+ The factor itself; for one factor per axis, the geometric mean of the sizes of
+ x's and y's.
+ """
+ x, y, _ = np.abs(axis_factors(factor))
+ return float(np.sqrt(x * y))
+
+
+# CE's override decorators, as data: a mobject method → the animation class it plays instead
+# (`override_animation`), and a mobject method → the method whose animation its `.animate`
+# call plays (`override_animate`)
+_plays_instead: dict[Callable[..., object], type["Animation"]] = {}
+_animate_plays: dict[Callable[..., object], Callable[..., "Animation"]] = {}
+
+# What an updater is, known per function (a method's is its function's) and held weakly:
+# a function outlives no scene for being an updater, nor a method's object
+_TIME_BASED: "weakref.WeakKeyDictionary[Callable[..., object], bool]" = (
+ weakref.WeakKeyDictionary()
+)
+_FLOWS: "weakref.WeakSet[Callable[..., object]]" = weakref.WeakSet()
+
+
+def _has_updater(
+ updaters: Iterable[Callable[..., object]], updater: Callable[..., object]
+) -> bool:
+ """Whether this exact callable remains in the active updater list."""
+ return any(active is updater for active in updaters)
+
+
+def _function(updater: Callable[..., object]) -> Callable[..., object]:
+ """The function an updater runs: a method's function, else the updater itself."""
+ return getattr(updater, "__func__", updater)
+
+
+def _per_frame[M](updater: Updater[M]) -> TypeIs[Callable[[M], object]]:
+ """Does the updater take the mobject alone (no `dt`)? CE inspects the signature on every
+ call; the answer is kept per function."""
+ function = _function(updater)
+ try:
+ known = _TIME_BASED.get(function)
+ except TypeError: # held by no weak reference (a builtin): asked each time
+ return "dt" not in inspect.signature(updater).parameters
+ if known is None:
+ known = _TIME_BASED[function] = "dt" in inspect.signature(updater).parameters
+ return not known
+
+
+def _flows(updater: Callable[..., object]) -> bool:
+ """Is the updater a [flow][manimgx.mobject.flow] (or a method whose function is)?"""
+ return _function(updater) in _FLOWS
+
+
+def flow[U: Callable[..., object]](updater: U) -> U:
+ """Declare a time-based updater a flow: one that does the same over some time
+ however that time is split into steps.
+
+ A time-based updater is handed `dt`, the seconds since it last ran. Most compose:
+ one that moves the mobject at a rate (`mob.shift(dt * velocity)`), or sets it by a
+ function of the time it has run, does the same in one step of `dt` as in two of
+ `dt / 2`. A flow runs at every instant the scene computes — each frame, and the end
+ of each play and wait — handed exactly the time since, so every frame shows it at
+ that frame's instant.
+
+ Any other time-based updater is simulated, since what it does may depend on its
+ steps (an integrator, a ball that bounces): it steps on a clock of its own,
+ `config.simulation_rate` ticks a second (60) and the end of each play and wait, so
+ it takes the same steps at any frame rate, and a frame shows it as its last tick
+ left it. While one is in the scene, the scene computes every tick, between frames
+ too. Declare an updater that composes a flow to make it exact at every frame and to
+ spare those ticks; [always_shift][manimgx.always_shift] and
+ [always_rotate][manimgx.always_rotate] add flows. An updater that only reads the
+ world, as a traced path's does, is a [recorder][manimgx.mobject.record].
+
+ Args:
+ updater: A time-based updater: a function of the mobject and `dt`.
+
+ Returns:
+ The same updater, declared a flow, to add with
+ [add_updater][manimgx.Mobject.add_updater].
+
+ Examples:
+ ```python
+ import manimgx as m
+ from manimgx.mobject import flow
+
+
+ @flow
+ def orbit(dot: m.Mobject, dt: float) -> None:
+ dot.rotate(dt * m.PI / 2, about_point=m.ORIGIN) # a quarter turn a second
+
+
+ class FlowExample(m.Scene):
+ def construct(self) -> None:
+ dot = m.Dot(3 * m.RIGHT, radius=0.25, color=m.YELLOW)
+ dot.add_updater(orbit)
+ self.add(m.Circle(radius=3, color=m.BLUE), dot)
+ self.wait(3)
+ ```
+ """
+ _FLOWS.add(_function(updater))
+ return updater
+
+
+_RECORDERS: "weakref.WeakSet[Callable[..., object]]" = weakref.WeakSet()
+
+
+def record[U: Callable[..., object]](updater: U) -> U:
+ """Declare a time-based updater a recorder: one that reads the world and changes
+ only its own mobject, as a [TracedPath][manimgx.TracedPath]'s does.
+
+ The scene runs a recorder at every instant it computes — each tick of the
+ simulation clock, each frame, and the end of each play and wait — once everything
+ else is there: the animations playing, the mobjects' updaters and the scene's. At a
+ frame or at the end of a play or wait, it runs twice: first on the world as time
+ alone brought it there, as a tick sees it, then once the per-frame updaters have
+ run, so it can tell their change apart (a traced path spreads it over the frame
+ that ends there). A recorder is simulated (see [flow][manimgx.mobject.flow]):
+ while one is in the scene, the scene computes the simulation clock's ticks.
+
+ Args:
+ updater: A time-based updater: a function of the mobject and `dt`, or such a
+ method, decorated where its class defines it.
+
+ Returns:
+ The same updater, declared a recorder, to add with
+ [add_updater][manimgx.Mobject.add_updater].
+ """
+ # the scene computes a frame or an event in two passes (`Scene._instant`) only while
+ # a recorder is in it; the second pass is `clock.framing`
+ _RECORDERS.add(_function(updater))
+ return updater
+
+
+def records(updater: Callable[..., object]) -> bool:
+ """Whether an updater is a [recorder][manimgx.mobject.record].
+
+ The scene asks, to know whether it must compute each frame in two passes.
+
+ Args:
+ updater: An updater; a method is a recorder if its function is.
+ """
+ return _function(updater) in _RECORDERS
+
+
+def simulated(updater: Updater[Never]) -> bool:
+ """Whether an updater steps on the simulation clock: it is time-based and not a
+ [flow][manimgx.mobject.flow].
+
+ The scene asks, to know whether it must compute the ticks of its simulation clock.
+
+ Args:
+ updater: An updater, of a mobject or of a scene.
+ """
+ return not _per_frame(updater) and not _flows(updater)
+
+
+_SHARED: frozenset[type] = frozenset(
+ {
+ int,
+ float,
+ bool,
+ str,
+ bytes,
+ Blend,
+ Paint,
+ ManimColor,
+ np.float64,
+ np.int64,
+ np.bool_,
+ types.FunctionType, # a function (not a bound method: that is rebound to the copy)
+ pathlib.PosixPath,
+ pathlib.WindowsPath,
+ }
+)
+
+
+def copied[T](value: T) -> T:
+ """A deep copy of a value that holds mobjects.
+
+ Lists, tuples and dicts are rebuilt, each mobject is copied once (so two references
+ to one mobject refer to one copy), and plain values are shared.
+
+ Args:
+ value: A mobject, or a container of mobjects and plain values.
+ """
+ # see `_copied`
+ return cast("T", _copied(value, {}))
+
+
+def _copied(value: object, memo: dict[int, object]) -> object:
+ """A deep copy that knows the common shapes: values shared, containers rebuilt, mobjects
+ copied through the memo (aliases stay aliases)."""
+ kind = type(value)
+ if value is None or kind in _SHARED:
+ return value
+ if kind is list:
+ return [_copied(v, memo) for v in cast("list[object]", value)]
+ if kind is dict:
+ return {
+ k: _copied(v, memo) for k, v in cast("dict[object, object]", value).items()
+ }
+ if kind is tuple:
+ return tuple(_copied(v, memo) for v in cast("tuple[object, ...]", value))
+ if isinstance(value, Mobject):
+ known = memo.get(id(value))
+ return known if known is not None else value.__deepcopy__(memo)
+ if kind is np.ndarray: # read-only, an array is a value: shared
+ array = cast("np.ndarray", value)
+ return array.copy() if array.flags.writeable else array
+ return copy.deepcopy(value, memo)
+
+
+_CASCADES: Memo[type, Style] = Memo(1 << 12)
+_UNPAINTED: Final = Paint() # every mobject's paint until its style is applied
+_PAINT_STYLE: Final = (
+ "color",
+ "fill_color",
+ "fill_opacity",
+ "stroke_color",
+ "stroke_width",
+ "stroke_opacity",
+ "background_stroke_color",
+ "background_stroke_width",
+ "background_stroke_opacity",
+ "sheen_factor",
+ "sheen_direction",
+ "joint_type",
+ "cap_style",
+ "shade_in_3d",
+ "material",
+)
+# a style's paint, as the first `init_colors` makes it: (the mobject's, a fresh member's)
+_STYLED: Memo[tuple[object, ...], tuple[Paint, Paint | None]] = Memo(1 << 12)
+_PROTOTYPES: Memo[tuple[object, ...], "Mobject"] = Memo(1 << 12)
+
+
+def _copy_state(source: "Mobject", target: "Mobject", memo: dict[int, object]) -> None:
+ """Copy fields in order, with active clock stamps owned by the copied updaters."""
+ shared = type(source).shared
+ copied = target.__dict__
+ for name, value in source.__dict__.items():
+ if value is None or type(value) in _SHARED or name in shared:
+ copied[name] = value
+ elif name == "_since_":
+ stamps = cast("dict[object, Fraction]", value)
+ copied[name] = {
+ (updater if "updaters" in shared else _copied(updater, memo)): stamps[
+ updater
+ ]
+ for updater in source.updaters
+ if updater in stamps
+ }
+ else:
+ copied[name] = _copied(value, memo)
+
+
+def prototype[S: "Mobject", **P](
+ init: Callable[Concatenate[S, P], None],
+) -> Callable[Concatenate[S, P], None]:
+ """Make a mobject class's construction run once per distinct call: a decorator for
+ its `__init__`.
+
+ Construction is a value: an `__init__` given the same arguments (and the same
+ configuration) makes the same mobject. So it runs once per distinct call, and every
+ later construction takes a copy of what it made; an expensive mobject (typeset text,
+ an arrow tip) is made once. A call with an argument that is not a plain value (a
+ mobject, a function) constructs as usual.
+
+ Args:
+ init: The class's `__init__`.
+
+ Returns:
+ The `__init__`, remembering what it makes.
+ """
+
+ # a later construction adopts the made mobject's attributes: whatever named the made
+ # mobject names the new one
+
+ @functools.wraps(init)
+ def construct(self: S, *args: P.args, **kwargs: P.kwargs) -> None:
+ if self.__dict__:
+ init(self, *args, **kwargs)
+ return
+ try:
+ key = (
+ init,
+ type(self),
+ key_of(args),
+ key_of(sorted(kwargs.items())),
+ key_of(tuple(vars(config).values())),
+ )
+ except TypeError:
+ init(self, *args, **kwargs)
+ return
+ made = _PROTOTYPES.get(key)
+ if made is None:
+ init(self, *args, **kwargs)
+ _PROTOTYPES.keep(key, self.copy())
+ return
+ _copy_state(made, self, {id(made): self})
+
+ return construct
+
+
+def _anchors(points: Point3D_Array) -> Point3D_Array:
+ """A path's anchors: the first and last point of every cubic curve."""
+ if len(points) < 4:
+ return points
+ return points[np.r_[0 : len(points) : 4, 3 : len(points) : 4]]
+
+
+def _style_key(style: Style) -> tuple[object, ...] | None:
+ try:
+ key = tuple(key_of(style.get(name)) for name in _PAINT_STYLE)
+ except TypeError:
+ return None
+ return key
+
+
+_STRAIGHT = straight_path() # a default (paths are immutable)
+
+
+class GridArrangement(TypedDict, total=False):
+ """How [arrange_in_grid][manimgx.Mobject.arrange_in_grid] lays mobjects out: its
+ keywords, for the classes that pass them on (tables)."""
+
+ rows: int | None
+ """How many rows (default None: as many as `row_alignments` or `row_heights` lists,
+ else as many as the mobjects need; with neither `rows` nor `cols`, a grid as square
+ as it can be)."""
+ cols: int | None
+ """How many columns (default None: as many as `col_alignments` or `col_widths`
+ lists, else as many as the mobjects need; with neither `rows` nor `cols`, a grid as
+ square as it can be)."""
+ buff: float | tuple[float, float]
+ """The gap between cells, in scene units: one for both directions, or (horizontal,
+ vertical) (default 0.25)."""
+ cell_alignment: Vector3DLike
+ """Where each mobject sits in its cell, as a direction: UL for its top left corner
+ (default ORIGIN: centered)."""
+ row_alignments: str | None
+ """Each row's vertical alignment, top to bottom: a letter per row, "u" (up), "c"
+ (center) or "d" (down) (default None: as `cell_alignment`'s vertical part says)."""
+ col_alignments: str | None
+ """Each column's horizontal alignment, left to right: a letter per column, "l"
+ (left), "c" (center) or "r" (right) (default None: as `cell_alignment`'s horizontal
+ part says)."""
+ row_heights: Iterable[float | None] | None
+ """Each row's height, top to bottom, in scene units; None for the height of its
+ tallest mobject (default None: all measured)."""
+ col_widths: Iterable[float | None] | None
+ """Each column's width, left to right, in scene units; None for the width of its
+ widest mobject (default None: all measured)."""
+ flow_order: str
+ """The order the cells are filled in: two letters, the direction a line of cells
+ fills and then the direction the lines follow each other — "r" (right), "l" (left),
+ "u" (up) or "d" (down) (default "rd": rows left to right, from the top down; "dr"
+ fills columns top to bottom, from the left)."""
+
+
+class Beside(TypedDict, total=False):
+ """How [next_to][manimgx.Mobject.next_to] aligns a mobject beside another: its
+ keywords but the direction and the gap, for the methods that pass them on
+ ([arrange][manimgx.Mobject.arrange])."""
+
+ aligned_edge: Vector3DLike
+ """The edge, as a direction, along which the two line up besides the side they meet
+ at: with the direction RIGHT and UP here, their tops line up (default ORIGIN:
+ centered)."""
+ submobject_to_align: "Mobject | None"
+ """A part of the mobject to put beside the other in its place; the rest moves with
+ it (default None: the whole mobject)."""
+ index_of_submobject_to_align: int | None
+ """The index of the part of each mobject to line up: this one's part goes beside the
+ other's (default None: the whole of each)."""
+ coor_mask: Vector3DLike
+ """Which coordinates may change: 1 for each axis the mobject moves along, 0 for one
+ it keeps (default (1, 1, 1))."""
+
+
+class Placement(Beside, total=False):
+ """How [next_to][manimgx.Mobject.next_to] places a mobject beside another: its
+ keywords but the direction, for the methods that pass them on."""
+
+ buff: float
+ """The gap between the two, in scene units (default 0.25)."""
+
+
+class BackgroundOptions(Look, total=False):
+ """A background rectangle's keywords but its color and opacity: those of
+ [add_background_rectangle][manimgx.Mobject.add_background_rectangle] and its
+ variants."""
+
+ buff: float | tuple[float, float]
+ """The margin around the mobject, in scene units: one for both directions, or
+ (horizontal, vertical) (default 0)."""
+ corner_radius: float
+ """The radius of the rectangle's corners, in scene units (default 0: square
+ corners)."""
+ stroke_width: float
+ """The width of the rectangle's outline, in hundredths of a scene unit (default 0:
+ none)."""
+ stroke_opacity: float
+ """The outline's opacity, from 0 to 1 (default 0)."""
+ stroke_color: Colors | None
+ """The outline's color (default: the rectangle's color)."""
+
+
+class Pivot(TypedDict, total=False):
+ """The point a transformation keeps fixed: given, or a point of the mobject's
+ bounding box.
+
+ With neither keyword, a scale, a rotation or a stretch keeps the mobject's center
+ fixed, and a function or a matrix is applied about the origin.
+ """
+
+ about_point: Point3DLike | None
+ """The point that stays fixed, in scene coordinates; it takes precedence over
+ `about_edge`."""
+ about_edge: Vector3DLike | None
+ """The point of the mobject's bounding box that stays fixed, named by a direction:
+ UP for the middle of its top edge, UR for its top right corner, ORIGIN for its
+ center."""
+
+
+def style_defaults(cls: "type[Mobject]") -> Style:
+ """A mobject class's style defaults: the [defaults][manimgx.Mobject.defaults] of
+ every class in its hierarchy, each class's over its parents'.
+
+ Args:
+ cls: A mobject class.
+
+ Returns:
+ The defaults of its style keywords.
+ """
+ # each class in the hierarchy adds only what it changes; cached per class
+ cached = _CASCADES.get(cls)
+ if cached is None:
+ cached = Style()
+ for klass in reversed(cls.__mro__):
+ if issubclass(klass, Mobject) and "defaults" in vars(klass):
+ cached = cached | klass.defaults
+ _CASCADES.keep(cls, cached)
+ return cached
+
+
+def remove_list_redundancies[T](items: Sequence[T]) -> list[T]:
+ """The items without repeats: each one once, where it last occurs.
+
+ Items are the same when they are the same object.
+
+ Args:
+ items: The items, in order.
+
+ Returns:
+ A new list.
+ """
+ # the last occurrence of each is kept (CE semantics)
+ seen: set[int] = set()
+ out: list[T] = []
+ for x in reversed(items):
+ if id(x) not in seen:
+ seen.add(id(x))
+ out.append(x)
+ out.reverse()
+ return out
+
+
+def _family(roots: Iterable["Mobject"]) -> list["Mobject"]:
+ """Preorder from these roots, each member once at its last occurrence."""
+ # Right-to-left postorder is reversed preorder. Keep its first occurrences,
+ # skipping already visited subtrees, then reverse to keep preorder's last ones.
+ family: list[Mobject] = []
+ seen: set[int] = set()
+ pending: list[Mobject | tuple[Mobject]] = list(roots)
+ while pending:
+ item = pending.pop()
+ if isinstance(item, tuple):
+ family.append(item[0])
+ elif id(item) not in seen:
+ seen.add(id(item))
+ if item.submobjects:
+ pending.append((item,))
+ pending.extend(item.submobjects)
+ else:
+ family.append(item)
+ family.reverse()
+ return family
+
+
+def _family_box(family: Iterable["Mobject"]) -> np.ndarray | None:
+ """Combine the selected family's own geometry boxes without constructing a group."""
+ # A member's box belongs to its geometry; paths use their curves' tight bounds.
+ boxes = [m._geometry.box(m._curves) for m in family if m._geometry.n]
+ if len(boxes) < 2:
+ return boxes[0] if boxes else None
+ stacked = np.array(boxes)
+ return np.array([stacked[:, 0].min(axis=0), stacked[:, 1].max(axis=0)])
+
+
+class Mobject:
+ """The object everything in a scene is made of: shapes, text, groups, trackers.
+
+ A mobject has points in scene coordinates (x to the right, y up, z out of the
+ screen; the frame is 8 units tall and about 14.2 wide, centered on the origin);
+ submobjects, a tree drawn and moved with it; a style: its fill, its stroke and their
+ colors; updaters, which change it as time passes; and a z-index, its place in the
+ drawing order. You make one through its subclasses — [`Circle`][manimgx.Circle],
+ [`Text`][manimgx.Text], [`VGroup`][manimgx.VGroup] and the rest — and they all share
+ the methods here: to transform it ([`shift`][manimgx.Mobject.shift],
+ [`scale`][manimgx.Mobject.scale], [`rotate`][manimgx.Mobject.rotate]), lay it out
+ ([`next_to`][manimgx.Mobject.next_to], [`arrange`][manimgx.Mobject.arrange]), style
+ it ([`set_color`][manimgx.Mobject.set_color]), keep it updated
+ ([`add_updater`][manimgx.Mobject.add_updater]), and animate any of that
+ ([`animate`][manimgx.Mobject.animate]).
+
+ A transformation or a style acts on the mobject's whole family — the mobject, its
+ submobjects, theirs, and so on — and returns the mobject, so calls chain:
+ `Square().scale(2).set_color(BLUE)`. Size and layout go by the mobject's
+ [bounding box][manimgx.Mobject.boundary_box]: the smallest box, aligned with the
+ axes, around what it draws.
+ """
+
+ animation_overrides: ClassVar[
+ dict[type["Animation"], Callable[..., "Animation"]]
+ ] = {}
+ """The animations the class plays another in place of: each animation class, with
+ the function that makes the one played instead (see
+ [override_animation][manimgx.override_animation])."""
+ defaults: ClassVar[Style] = {}
+ """The style keywords whose defaults the class changes: a subclass lists only what
+ it changes (`defaults = {"color": BLUE}`), and takes the rest from its parents (see
+ [style_defaults][manimgx.mobject.style_defaults])."""
+ shared: ClassVar[frozenset[str]] = frozenset(
+ {"style", "__orig_class__", "_film_record"}
+ )
+ """The attributes a copy shares with its original instead of copying them: values
+ that are never changed in place."""
+
+ # CE's style attributes, kept in the paint: each reads and sets the mobject's own,
+ # not its family's
+ joint_type = PaintAttribute[LineJointType]("joint")
+ """How the mobject's own stroke is joined where its path turns: round, beveled or
+ mitered (see [LineJointType][manimgx.LineJointType])."""
+ cap_style = PaintAttribute[CapStyleType]("cap")
+ """How the mobject's own stroke ends, at each end it shows: round, butt or square
+ (see [CapStyleType][manimgx.CapStyleType])."""
+ shade_in_3d = PaintAttribute[bool]("shade_in_3d")
+ """Whether a three-dimensional scene's light shades the mobject's own paint."""
+ material = PaintAttribute[Material | None]("material")
+ """How the mobject's own surface reflects the scene's lights (see
+ [Material][manimgx.Material]); None: Manim's shading."""
+ sheen_factor = PaintAttribute[float]("sheen_factor")
+ """How much the mobject's own colors lighten toward its `sheen_direction`, from -1
+ to 1 (0: none; negative: they darken); see
+ [set_sheen][manimgx.Mobject.set_sheen]."""
+ sheen_direction = PaintAttribute[Vector3D, Vector3DLike]("sheen_direction")
+ """The direction the mobject's own colors lighten toward, which its color gradients
+ run along too."""
+ fill_rgbas = PaintAttribute[RGBA_Array, npt.ArrayLike]("fill")
+ """The mobject's own fill colors, as rows of red, green, blue and opacity, from 0 to
+ 1: one row per gradient stop."""
+ stroke_rgbas = PaintAttribute[RGBA_Array, npt.ArrayLike]("stroke")
+ """The mobject's own stroke colors, as rows of red, green, blue and opacity, from 0
+ to 1."""
+ background_stroke_rgbas = PaintAttribute[RGBA_Array, npt.ArrayLike]("background")
+ """The colors of the mobject's own background stroke (an outline drawn behind its
+ fill), as rows of red, green, blue and opacity, from 0 to 1."""
+ background_stroke_width = PaintAttribute[float]("background_width")
+ """The width of the mobject's own background stroke, in hundredths of a scene
+ unit."""
+ z_index_group: "Mobject | None" = None
+ """The group the mobject is ordered with in a three-dimensional scene, if any: set
+ by `set_shade_in_3d(z_index_as_group=True)`. Kept for Manim compatibility: the
+ renderer draws a three-dimensional scene by depth."""
+
+ def __init_subclass__(cls, **kwargs: object) -> None:
+ super().__init_subclass__(**kwargs)
+ own = {
+ _plays_instead[f]: f
+ for f in vars(cls).values()
+ if inspect.isfunction(f) and f in _plays_instead
+ }
+ if own: # a class's overrides are its bases' and its own
+ cls.animation_overrides = cls.animation_overrides | own
+
+ def __init__(self, **kwargs: Unpack[Style]) -> None:
+ if (
+ "color" in kwargs and kwargs["color"] is None
+ ): # not given: the class's default
+ del kwargs["color"]
+ self.style = style_defaults(type(self)) | kwargs
+ """Pending constructor style, including the class's defaults. Base color
+ initialization consumes this instance entry; current appearance is kept in
+ [paint][manimgx.Mobject.paint]. Point clouds retain their defaults for later points."""
+ name = self.style.get("name")
+ self.name = type(self).__name__ if name is None else name
+ """The mobject's name: its class's name, unless it was made with one."""
+ self.dim = 3
+ """How many coordinates each of its points has: 3."""
+ self.target: Mobject | None = self.style.get("target")
+ """The state [MoveToTarget][manimgx.MoveToTarget] moves the mobject to: made by
+ [generate_target][manimgx.Mobject.generate_target], or given when the mobject
+ was made; None if neither."""
+ self.z_index = self.style.get("z_index", 0.0)
+ """The mobject's place in the drawing order: a higher index is drawn over a
+ lower one (default 0); see [set_z_index][manimgx.Mobject.set_z_index]."""
+ self.submobjects: list[Mobject] = []
+ """The mobject's children, in drawing order: each is drawn over those before it,
+ at an equal z-index."""
+ self.updaters: list[Updater[Self]] = []
+ """The mobject's own updaters, in the order they run; see
+ [add_updater][manimgx.Mobject.add_updater]."""
+ self.updating_suspended = False
+ """Whether the mobject's updaters are suspended; see
+ [suspend_updating][manimgx.Mobject.suspend_updating]."""
+ self.paint = _UNPAINTED
+ """The mobject's own style as it is now, as one value: its colors, opacities,
+ stroke widths and sheen. The style methods replace it; it is never changed in
+ place."""
+ self.reset_points()
+ self.generate_points()
+ self.init_colors()
+
+ # ── kind hooks ─────────────────────────────────────────────────────────
+ def generate_points(self) -> Self:
+ """Build the mobject's points: its shape.
+
+ The constructor calls it. A class with a shape of its own overrides it; a plain
+ mobject has no points.
+ """
+ return self
+
+ def init_points(self) -> Self:
+ """Build the mobject's points: the same as
+ [generate_points][manimgx.Mobject.generate_points], by another name.
+ """
+ # CE's other name for `generate_points`
+ self.generate_points()
+ return self
+
+ def init_colors(self, propagate_colors: bool = True) -> Self:
+ """Paint the mobject with its style.
+
+ The constructor calls it once its points are built: the first call paints the
+ style keywords the mobject was made with, then consumes those inputs. A later
+ call paints its present style again — its first fill and stroke colors, their
+ opacities, its stroke widths and its sheen. A subclass can read its instance's
+ pending `style` before delegating; successful initialization removes that entry.
+
+ Args:
+ propagate_colors: Whether its whole family is painted (so the parts
+ [generate_points][manimgx.Mobject.generate_points] made), or the mobject
+ alone.
+ """
+ # CE semantics: the first call paints the constructor style onto the family,
+ # later calls re-apply the current style to it
+ family = propagate_colors
+ p = self.paint
+ s: Style | None = self.__dict__.get("style")
+ if s is None:
+ self.set_fill(self.get_fill_color(), p.fill[0, 3], family)
+ self.set_stroke(
+ self.get_stroke_color(), p.stroke_width, p.stroke[0, 3], family=family
+ )
+ self.set_stroke(
+ self.get_stroke_color(background=True),
+ p.background_width,
+ p.background[0, 3],
+ background=True,
+ family=family,
+ )
+ return self.set_sheen(p.sheen_factor, p.sheen_direction, family)
+ members = self._each(family)
+ key = _style_key(s)
+ if key is not None and any(m.paint is not _UNPAINTED for m in members):
+ key = None # a family painted already is painted over, not looked up
+ if key is not None: # the paint a style makes is a value: made once, shared
+ styled = _STYLED.get(key)
+ if styled is not None and (len(members) == 1 or styled[1] is not None):
+ self.paint, rest = styled
+ if rest is not None:
+ for m in members[1:]:
+ m.paint = rest
+ del self.style
+ return self
+ color = s.get("color", WHITE)
+ fill, stroke, joint = (
+ s.get("fill_color"),
+ s.get("stroke_color"),
+ s.get("joint_type"),
+ )
+ self.paint = p.but(
+ joint=LineJointType.AUTO if joint is None else joint,
+ cap=s.get("cap_style", CapStyleType.AUTO),
+ shade_in_3d=s.get("shade_in_3d", False),
+ material=s.get("material"),
+ )
+ self.set_fill(
+ color if fill is None else fill, s.get("fill_opacity", 0.0), family
+ )
+ self.set_stroke(
+ color if stroke is None else stroke,
+ s.get("stroke_width", DEFAULT_STROKE_WIDTH),
+ s.get("stroke_opacity", 1.0),
+ family=family,
+ )
+ self.set_stroke(
+ s.get("background_stroke_color", BLACK),
+ s.get("background_stroke_width", 0.0),
+ s.get("background_stroke_opacity", 1.0),
+ background=True,
+ family=family,
+ )
+ self.set_sheen(s.get("sheen_factor", 0.0), s.get("sheen_direction", UL), family)
+ del self.style
+ if key is not None:
+ _STYLED.keep(
+ key, (self.paint, members[1].paint if len(members) > 1 else None)
+ )
+ return self
+
+ # its points are cubic curves' control points (a path): its box is its curves' tight box
+ _curves: ClassVar[bool] = False
+
+ def get_points_defining_boundary(self) -> Point3D_Array:
+ """The points [get_boundary_point][manimgx.Mobject.get_boundary_point] chooses
+ among: every point of the mobject's family — or, for a path, its members'
+ anchors, the ends of its curves (a path's handles need not lie on it).
+
+ The mobject's bounding box is not made from them: it is
+ [boundary_box][manimgx.Mobject.boundary_box], around what the family draws.
+
+ Returns:
+ The points, as an (n, 3) array.
+ """
+ if not self._curves:
+ return self.get_all_points()
+ arrays = [
+ _anchors(m.points)
+ for m in self.get_family()
+ if m._curves and m.has_points()
+ ]
+ return np.concatenate(arrays) if arrays else np.zeros((0, 3))
+
+ def align_points_with_larger(self, larger: "Mobject") -> Self:
+ """Give the mobject as many points as `larger`, its shape unchanged, so the two
+ can be blended point by point.
+
+ [align_points][manimgx.Mobject.align_points] calls it on the one of two mobjects
+ with fewer points. Each kind implements it (a path divides its curves); a
+ mobject of no kind cannot.
+
+ Args:
+ larger: The mobject with more points.
+ """
+ raise NotImplementedError(f"{type(self).__name__} cannot align points")
+
+ def get_point_mobject(self, center: Point3DLike | None = None) -> "Mobject":
+ """The mobject shrunk to a point: what it grows from, or shrinks to, when a
+ transform makes it appear or disappear.
+
+ A kind returns a point of its own kind and style; a mobject of no kind, the
+ group of its members' points.
+
+ Args:
+ center: Where the point is; None for the mobject's center.
+
+ Returns:
+ A new mobject.
+ """
+ c = self.get_center() if center is None else center
+ return Group(*(m.get_point_mobject(c) for m in self.submobjects))
+
+ def pointwise_become_partial(self, mobject: "Mobject", a: float, b: float) -> Self:
+ """Become a part of another mobject: its points from proportion `a` of the way
+ along it to proportion `b` (a path's, by its curves).
+
+ [get_pieces][manimgx.Mobject.get_pieces] calls it. Each kind implements it; a
+ mobject of no kind stays as it is.
+
+ Args:
+ mobject: The mobject to take a part of (this one, or one of its kind).
+ a: Where the part starts, from 0 to 1.
+ b: Where the part ends, from `a` to 1.
+ """
+ return self
+
+ def reveal_pace(self) -> tuple[np.ndarray, np.ndarray] | None:
+ """How a reveal ([Create][manimgx.Create], [Write][manimgx.Write], …) moves
+ through the mobject: evenly by its parts, or, for a path, by arc length, so it
+ is drawn at a steady speed.
+
+ The reveal animations read it for each drawn member.
+
+ Returns:
+ None for evenly by part (points in order, triangles in order); for a path,
+ fractions of its length and the curve parameters where they are reached.
+ """
+ return None
+
+ # ── points ────────────────────────────────────────────────────────────
+ @property
+ def points(self) -> Point3D_Array:
+ """The mobject's own points, in scene coordinates: an (n, 3) array, read-only.
+
+ A path's are the control points of its cubic Bézier curves, four per curve.
+ Assign an array to reshape the mobject; its submobjects keep theirs. Assigning the
+ points it has changes nothing (it keeps its geometry, and all that was derived from
+ it), unless they are a blend of shapes, as mid-morph, which become one; assigning
+ them with more after them grows it.
+ """
+ # the geometry blend, materialized (cached, hence read-only)
+ return self._geometry.points()
+
+ @points.setter
+ def points(self, value: Point3DLike_Array) -> None:
+ array = np.asarray(value, dtype=float).reshape(-1, self.dim)
+ g = self.__dict__.get("_geometry", EMPTY) # (none yet, while constructing)
+ # one shape: the points it was given again, or more after them, compared as the
+ # geometry holds them (their last point first: points that changed are told at once),
+ # are unchanged, or grown; so are the points it was read as (never read for this: a
+ # change would pay for it). A blend of more shapes becomes one again, which the
+ # player draws directly.
+ if 0 < g.n <= len(array) and len(g.terms) == 1:
+ m, shape = g.terms[0]
+ if (
+ np.array_equal(m[:, :3], np.eye(3))
+ and np.array_equal(array[g.n - 1] - m[:, 3], shape.array[-1])
+ and np.array_equal(array[: g.n] - m[:, 3], shape.array)
+ ):
+ if len(array) > g.n:
+ self._geometry = Blend(
+ ((m, shape.extended(array[g.n :] - m[:, 3])),), len(array)
+ )
+ return
+ if g.n == len(array) and unchanged(array, g.cached):
+ return
+ self._geometry = Blend.of(array, self.dim)
+
+ def reset_points(self) -> Self:
+ """Remove the mobject's own points; its submobjects keep theirs."""
+ self._geometry: Blend = EMPTY
+ return self
+
+ def set_points(self, points: Point3DLike_Array) -> Self:
+ """Give the mobject new points of its own, in place of its present ones.
+
+ Args:
+ points: The points, in scene coordinates: an (n, 3) array.
+ """
+ self.points = np.array(points, dtype=float)
+ return self
+
+ def get_points(self) -> Point3D_Array:
+ """The mobject's own [points][manimgx.Mobject.points].
+
+ Returns:
+ An (n, 3) array, read-only.
+ """
+ return self.points
+
+ def has_points(self) -> bool:
+ """Whether the mobject has points of its own (a group has none: its members do)."""
+ return self._geometry.n > 0
+
+ def has_no_points(self) -> bool:
+ """Whether the mobject has no points of its own."""
+ return self._geometry.n == 0
+
+ def get_num_points(self) -> int:
+ """How many points of its own the mobject has.
+
+ Returns:
+ The number of points.
+ """
+ return self._geometry.n
+
+ def get_all_points(self) -> Point3D_Array:
+ """Every point of the mobject's family, member after member.
+
+ Returns:
+ An (n, 3) array.
+ """
+ arrays = [m.points for m in self.get_family()]
+ return np.concatenate(arrays) if arrays else np.zeros((0, 3))
+
+ def get_start(self) -> Point3D:
+ """The mobject's first point: where a path starts.
+
+ Raises an exception if the mobject has no points of its own.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ self._require_points()
+ return np.array(self.points[0])
+
+ def get_end(self) -> Point3D:
+ """The mobject's last point: where a path ends.
+
+ Raises an exception if the mobject has no points of its own.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ self._require_points()
+ return np.array(self.points[-1])
+
+ def get_start_and_end(self) -> tuple[Point3D, Point3D]:
+ """The mobject's first and last points.
+
+ Returns:
+ Its [start][manimgx.Mobject.get_start] and its
+ [end][manimgx.Mobject.get_end], in scene coordinates.
+ """
+ return self.get_start(), self.get_end()
+
+ def _require_points(self) -> None:
+ if self.has_no_points():
+ raise Exception(
+ f"Cannot call this method on a {type(self).__name__} with no points"
+ )
+
+ # ── family ────────────────────────────────────────────────────────────
+ def add(self, *mobjects: "Mobject") -> Self:
+ """Add submobjects after the ones the mobject has: they move with it, and are
+ drawn over those before them (at an equal z-index).
+
+ A mobject that is a submobject already moves to the end. Adding anything but a
+ mobject, or the mobject itself or one that holds it, raises an exception (a
+ mobject cannot hold itself).
+
+ Args:
+ *mobjects: The mobjects to add, in order.
+ """
+ return self._place(None, mobjects)
+
+ def add_to_back(self, *mobjects: "Mobject") -> Self:
+ """Add submobjects before the ones the mobject has: they are drawn under them
+ (at an equal z-index).
+
+ A mobject that is a submobject already moves to the front; what `add` refuses,
+ this refuses too.
+
+ Args:
+ *mobjects: The mobjects to add, in order.
+ """
+ return self._place(0, mobjects)
+
+ def insert(self, index: int, mobject: "Mobject") -> Self:
+ """Insert a submobject at a place among the mobject's other submobjects.
+
+ A mobject that is a submobject already moves there; what `add` refuses, this
+ refuses too.
+
+ Args:
+ index: Its place in the list of the other submobjects, as `list.insert`
+ takes it.
+ mobject: The mobject to insert.
+ """
+ return self._place(index, (mobject,))
+
+ def _place(self, index: int | None, mobjects: Sequence["Mobject"]) -> Self:
+ """The one way submobjects join: each a mobject that neither is this one nor holds
+ it, once (where it last occurs), at `index` among the others (None: last)."""
+ for i, m in enumerate(mobjects):
+ if not isinstance(m, Mobject):
+ raise TypeError(
+ f"Only Mobjects can be added to {type(self).__name__}, got"
+ f" {type(m).__name__} at index {i}"
+ )
+ if m is self or (
+ m.submobjects and any(member is self for member in m.get_family())
+ ):
+ raise ValueError(
+ f"Cannot add {type(m).__name__} to {type(self).__name__}: a"
+ " mobject cannot hold itself"
+ )
+ new = remove_list_redundancies(list(mobjects))
+ joining = {id(m) for m in new}
+ others = [m for m in self.submobjects if id(m) not in joining]
+ at = len(others) if index is None else index
+ self.submobjects = others[:at] + new + others[at:]
+ return self
+
+ def remove(self, *mobjects: "Mobject") -> Self:
+ """Remove submobjects: those given that are among the mobject's own submobjects
+ (not its submobjects' submobjects); the rest are ignored.
+
+ Args:
+ *mobjects: The mobjects to remove.
+ """
+ for m in mobjects:
+ if m in self.submobjects:
+ self.submobjects.remove(m)
+ return self
+
+ def get_family(self) -> list["Mobject"]:
+ """The mobject and all its descendants: itself, then each submobject's family in
+ turn, each member once (where it last occurs, if the tree holds it twice).
+
+ Returns:
+ A new list.
+ """
+ if not self.submobjects:
+ return [self]
+ return _family((self,))
+
+ def family_members_with_points(self) -> list["Mobject"]:
+ """The members of the mobject's family that have points of their own: the ones
+ that are drawn.
+
+ Returns:
+ A new list, in family order.
+ """
+ return [m for m in self.get_family() if m.has_points()]
+
+ def split(self) -> list["Mobject"]:
+ """The mobject's parts: itself, if it has points of its own, then its
+ submobjects.
+
+ Indexing the mobject (`mobject[0]`), slicing it, iterating over it and its `len`
+ go through the same parts.
+
+ Returns:
+ A new list.
+ """
+ return list(self)
+
+ def get_group_class(self) -> type["Group"]:
+ """The class of the groups the mobject's parts are gathered in: slicing it
+ (`mobject[1:3]`) makes one.
+
+ Returns:
+ [Group][manimgx.Group].
+ """
+ return Group
+
+ def __iter__(self) -> Iterator["Mobject"]:
+ return it.chain([self] if self.has_points() else [], self.submobjects)
+
+ def __len__(self) -> int:
+ return len(self.submobjects) + (1 if self.has_points() else 0)
+
+ @overload
+ def __getitem__(self, value: int) -> "Mobject": ...
+ @overload
+ def __getitem__(self, value: slice) -> "Mobject": ...
+ def __getitem__(self, value: int | slice) -> "Mobject":
+ items = list(self)
+ if isinstance(value, slice):
+ return self.get_group_class()(*items[value])
+ return items[value]
+
+ # ── copying ───────────────────────────────────────────────────────────
+ def __deepcopy__(self, memo: dict[int, object]) -> Self:
+ """A copy shares what cannot change (geometry and paint are values, and what the class
+ names in `shared`) and deep-copies the rest."""
+ cls = type(self)
+ result = cls.__new__(cls)
+ memo[id(self)] = result
+ _copy_state(self, result, memo)
+ return result
+
+ def copy(self) -> Self:
+ """A copy of the mobject, with its whole family.
+
+ Every mobject its attributes refer to is copied once, so an attribute that
+ refers to one of its members refers to the copy's member. The copy runs the same
+ updater functions, on itself, and is not in the scene. Copying is cheap: the
+ copy shares the original's points and style until either one changes them.
+ """
+ return copy.deepcopy(self)
+
+ def generate_target(self) -> Self:
+ """Make the mobject's [target][manimgx.Mobject.target]: a copy of it, which you
+ change into the state [MoveToTarget][manimgx.MoveToTarget] then animates the
+ mobject to.
+
+ Using [animate][manimgx.Mobject.animate] makes a new target too, in place of
+ this one.
+
+ Returns:
+ The target.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectGenerateTargetExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=1.5, color=m.BLUE).shift(3 * m.LEFT)
+ target = circle.generate_target()
+ target.set_fill(m.GREEN, opacity=0.5).shift(6 * m.RIGHT + m.UP)
+ target.scale(0.5)
+ self.add(circle)
+ self.play(m.MoveToTarget(circle))
+ ```
+ """
+ self.target = None # not copied into the new target
+ self.target = self.copy()
+ return self.target
+
+ def save_state(self) -> Self:
+ """Keep a copy of the mobject as it is now, to return to with
+ [restore][manimgx.Mobject.restore] or the [Restore][manimgx.Restore] animation.
+
+ The copy is the mobject's `saved_state`; saving again replaces it.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSaveStateExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(color=m.BLUE, fill_opacity=0.5)
+ square.save_state()
+ self.add(square)
+ self.play(square.animate.set_color(m.YELLOW).shift(3 * m.LEFT))
+ self.play(square.animate.rotate(m.PI / 4).scale(2))
+ self.play(m.Restore(square))
+ ```
+ """
+ self.saved_state = None # not copied into the new saved state
+ self.saved_state = self.copy()
+ return self
+
+ def restore(self) -> Self:
+ """Make the mobject what it was when [save_state][manimgx.Mobject.save_state]
+ last kept it: its points and its style, member by member (see
+ [become][manimgx.Mobject.become]).
+
+ Raises an exception if its state was never saved.
+ """
+ saved = getattr(self, "saved_state", None)
+ if saved is None:
+ raise Exception("Trying to restore without having saved")
+ self.become(saved)
+ return self
+
+ # ── updaters ──────────────────────────────────────────────────────────
+ # A time-based updater integrates the time it is live: `advance(t)` hands it the time since
+ # it was last brought forward — or attached, joined the scene, or resumed — on its clock:
+ # scene time, unless the updater carries a `clock` (ChangeSpeed's do).
+ def update(self, dt: float = 0, recursive: bool = True) -> Self:
+ """Run each of the mobject's updaters once, now; nothing runs while its updating
+ is suspended.
+
+ The scene brings updaters forward itself (see
+ [advance][manimgx.Mobject.advance]): this runs them by hand.
+
+ Args:
+ dt: The seconds handed to its time-based updaters.
+ recursive: Whether its submobjects' updaters run too, after its own.
+ """
+ # CE's; the scene uses `advance`
+ if self.updating_suspended:
+ return self
+ updaters = self.updaters
+ for updater in updaters:
+ if updaters is not self.updaters and not _has_updater(
+ self.updaters, updater
+ ):
+ continue
+ if _per_frame(updater):
+ updater(self)
+ else:
+ cast("Callable[[Self, float], object]", updater)(self, dt)
+ if recursive:
+ for sub in self.submobjects:
+ sub.update(dt, recursive)
+ return self
+
+ def advance(
+ self,
+ t: Fraction,
+ recursive: bool = True,
+ recorders: "list[_Recorder] | None" = None,
+ ) -> Self:
+ """Bring the mobject's updaters to scene time `t`.
+
+ An engine hook: the scene calls it on each of its mobjects at every instant it
+ computes, and an animation on the copy of its mobject that the updaters run on
+ while it plays. Each time-based updater is handed the time since it last ran —
+ on its own clock, if it has one (as [ChangeSpeed][manimgx.ChangeSpeed]'s
+ updaters do). A simulated one (time-based, not a
+ [flow][manimgx.mobject.flow]) runs only at the ticks of the simulation
+ clock and at the ends of plays and waits; a per-frame one only at frames and
+ those ends. Nothing runs while the mobject's updating is suspended.
+
+ Args:
+ t: The scene time, in seconds, exact.
+ recursive: Whether its submobjects' updaters are brought there too, after
+ its own.
+ recorders: Where the scene collects the
+ [recorders][manimgx.mobject.record], each with its mobject
+ and the updater list it came from, to run them once everything
+ else is at `t`; None: they run here, as the
+ simulated updaters they are.
+ """
+ # a simulated updater runs only where it steps (`clock.stepping`: between the
+ # simulation clock's ticks it stays where it was); a per-frame one only at a
+ # frame or an event (`clock.framing`)
+ if self.updating_suspended:
+ return self
+ updaters = self.updaters
+ for updater in updaters:
+ if updaters is not self.updaters and not _has_updater(
+ self.updaters, updater
+ ):
+ continue
+ if _per_frame(updater):
+ if clock.framing:
+ updater(self)
+ elif recorders is not None and records(updater):
+ recorders.append((self, updater, updaters))
+ elif clock.stepping or _flows(updater):
+ self._bring(updater, t)
+ if recursive:
+ for sub in self.submobjects:
+ sub.advance(t, recursive, recorders)
+ return self
+
+ def _bring(self, updater: Callable[..., object], t: Fraction) -> None:
+ """Run a time-based updater with the time its clock ran since it was last brought
+ forward."""
+ since = self._since
+ start = since.get(updater, t)
+ since[updater] = t
+ on = cast("clock.Clock | None", getattr(updater, "clock", None))
+ dt = float(t - start) if on is None else on.at(float(t)) - on.at(float(start))
+ updater(self, dt)
+
+ @property
+ def _since(self) -> dict[object, Fraction]:
+ """When each time-based updater was last brought forward (made on first use)."""
+ since = self.__dict__.get("_since_")
+ if since is None:
+ since = self.__dict__["_since_"] = {}
+ return since
+
+ def _stamp(self, t: Fraction, recursive: bool = True) -> None:
+ """The time-based updaters start (again) from `t`: they joined the scene, or resumed."""
+ for updater in self.updaters:
+ if not _per_frame(updater):
+ self._since[updater] = t
+ if recursive:
+ for sub in self.submobjects:
+ sub._stamp(t, recursive)
+
+ @overload
+ def add_updater(
+ self,
+ update_function: Callable[[Self], object],
+ index: int | None = None,
+ call_updater: bool = False,
+ ) -> Self: ...
+ @overload
+ def add_updater(
+ self,
+ update_function: Callable[[Self, float], object],
+ index: int | None = None,
+ call_updater: bool = False,
+ ) -> Self: ...
+ def add_updater(
+ self,
+ update_function: Updater[Self],
+ index: int | None = None,
+ call_updater: bool = False,
+ ) -> Self:
+ """Add an updater: a function that keeps the mobject updated as time passes.
+
+ An updater is a function of the mobject, run once a frame — to keep a relation,
+ such as a label beside a dot — or, if it has a parameter named `dt`, of the
+ mobject and `dt`: the seconds of scene time since it last ran, or since it was
+ added, the mobject joined the scene, or its updating resumed. A time-based
+ updater moves the mobject by the time that passed:
+ `lambda mob, dt: mob.rotate(dt * PI)` turns it half a turn a second, at any
+ frame rate. What an updater returns is ignored.
+
+ The scene runs the updaters of the mobjects in it at every frame, after the
+ animations playing have moved them to the frame's instant, and at the end of
+ each play and wait: mobject by mobject in the order they were added to the
+ scene, a mobject's own before its submobjects', and a
+ [recorder][manimgx.mobject.record] after all the rest. So add a mobject
+ that follows another after it, or it sees where the other's updaters left it at
+ the instant before. Updaters keep running while an animation plays the mobject,
+ beneath the animation (see `suspend_mobject_updating` among the
+ [animation options][manimgx.animation.timeline.AnimationOptions]). A time-based
+ updater steps on the scene's simulation clock, `config.simulation_rate` ticks a
+ second, so it takes the same steps at any frame rate; declare one that does the
+ same however its time is split a [flow][manimgx.mobject.flow], and it runs
+ exactly at every frame instead.
+
+ Args:
+ update_function: The updater: a function of the mobject, or of the mobject
+ and `dt`.
+ index: Where it goes among the mobject's updaters, which run in order; None
+ for last.
+ call_updater: Whether to run it once right away; a time-based one is handed
+ a `dt` of 0.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectAddUpdaterExample(m.Scene):
+ def construct(self) -> None:
+ hand = m.Line(m.ORIGIN, 3 * m.RIGHT, color=m.BLUE)
+ # time-based: a quarter turn about the origin every second
+ hand.add_updater(
+ lambda mob, dt: mob.rotate(dt * m.PI / 2, about_point=m.ORIGIN)
+ )
+ dot = m.Dot(radius=0.2, color=m.YELLOW)
+ # per frame: at the hand's end, wherever it is
+ dot.add_updater(lambda mob: mob.move_to(hand.get_end()))
+ self.add(hand, dot)
+ self.wait(3)
+ ```
+ """
+ if index is None:
+ self.updaters.append(update_function)
+ else:
+ self.updaters.insert(index, update_function)
+ if not _per_frame(update_function):
+ self._since[update_function] = clock.now # it integrates from now
+ if call_updater:
+ if _per_frame(update_function):
+ update_function(self)
+ else:
+ cast("Callable[[Self, float], object]", update_function)(self, 0)
+ return self
+
+ def remove_updater(self, update_function: Updater[Never]) -> Self:
+ """Remove an updater from the mobject, every time it was added.
+
+ This also cancels calls that have not yet run in the current update,
+ including a recorder waiting for the other updaters to finish.
+
+ Args:
+ update_function: The updater to remove.
+ """
+ self.updaters = [u for u in self.updaters if u is not update_function]
+ since = self.__dict__.get("_since_")
+ if since is not None and update_function not in self.updaters:
+ since.pop(update_function, None)
+ return self
+
+ def clear_updaters(self, recursive: bool = True) -> Self:
+ """Remove every updater of the mobject, including calls still waiting
+ to run in the current update.
+
+ Args:
+ recursive: Whether its whole family's updaters are removed too.
+ """
+ self.updaters = []
+ self.__dict__.pop("_since_", None)
+ if recursive:
+ for sub in self.submobjects:
+ sub.clear_updaters()
+ return self
+
+ def get_updaters(self) -> list[Updater[Self]]:
+ """The mobject's own updaters, in the order they run.
+
+ Returns:
+ The list itself, so changing it changes the mobject's updaters.
+ """
+ return self.updaters
+
+ def get_family_updaters(self) -> list[Updater[Never]]: # each of its own kind
+ """Every updater of the mobject's family: its own, then its descendants', in
+ family order.
+
+ Returns:
+ A new list.
+ """
+ return [u for m in self.get_family() for u in m.updaters]
+
+ def has_time_based_updater(self) -> bool:
+ """Whether any of the mobject's own updaters is time-based: it takes `dt`."""
+ return not all(_per_frame(u) for u in self.updaters)
+
+ def get_time_based_updaters(self) -> list[Updater[Self]]:
+ """The mobject's own time-based updaters: those that take `dt`.
+
+ Returns:
+ A new list, in the order they run.
+ """
+ return [u for u in self.updaters if not _per_frame(u)]
+
+ @property
+ def always(self) -> "Always[Self]":
+ """A proxy that turns each method call made on it into an updater: the call is
+ made again every frame.
+
+ `label.always.next_to(dot, UP)` keeps the label above the dot, wherever the dot
+ goes. Each call is also made right away, and adds one per-frame updater (see
+ [add_updater][manimgx.Mobject.add_updater]); the proxy returns itself, so calls
+ chain. The arguments are taken once, as written: pass the mobject to follow
+ (`dot`), not its position (`dot.get_center()`), which stays where it was.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectAlwaysExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(color=m.BLUE, fill_opacity=0.5).shift(4 * m.LEFT)
+ label = m.Text("always above")
+ label.always.next_to(square, m.UP)
+ self.add(square, label)
+ self.play(square.animate.shift(8 * m.RIGHT), run_time=2)
+ ```
+ """
+ # CE's
+ from manimgx.animation.transform import Always
+
+ return Always(self)
+
+ def match_updaters(self, mobject: "Mobject") -> Self:
+ """Give the mobject another's updaters in place of its own, and clear its
+ submobjects'.
+
+ They are the same functions, now run on this mobject too; the time-based ones
+ start from now.
+
+ Args:
+ mobject: The mobject whose updaters to take (its own, not its family's).
+ """
+ self.clear_updaters()
+ self.updaters.extend(
+ mobject.get_updaters() # ty: ignore[invalid-argument-type] # CE: another mobject's updaters, applied to this one
+ )
+ self._stamp(clock.now, recursive=False)
+ return self
+
+ def suspend_updating(self, recursive: bool = True) -> Self:
+ """Stop the mobject's updaters from running, until
+ [resume_updating][manimgx.Mobject.resume_updating].
+
+ An animation suspends the updating of the mobject it plays while it plays, and
+ runs the updaters beneath it instead (see
+ [add_updater][manimgx.Mobject.add_updater]).
+
+ Args:
+ recursive: Whether its whole family's updaters stop too.
+ """
+ self.updating_suspended = True
+ if recursive:
+ for sub in self.submobjects:
+ sub.suspend_updating(recursive)
+ return self
+
+ def resume_updating(self, recursive: bool = True) -> Self:
+ """Let the mobject's updaters run again, from now: the time they were suspended
+ is not made up.
+
+ They are not run here: the scene runs them where it next brings the world — at
+ the instant it is computing, when an animation resumes them as it finishes,
+ else at the next one, such as the next frame.
+
+ Args:
+ recursive: Whether its whole family's updaters resume too.
+ """
+ # not run here as well: the instant's own pass runs them, and a per-frame
+ # updater would run twice at one instant
+ self.updating_suspended = False
+ if recursive:
+ for sub in self.submobjects:
+ sub.resume_updating(recursive)
+ self._stamp(clock.now, recursive)
+ return self
+
+ # ── the one transform primitive ────────────────────────────────────────
+ def apply_points_function_about_point(
+ self,
+ func: PointsFunc,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """Apply a function to the points of the mobject's whole family, about a point:
+ each drawn member's points become `func(points - about_point) + about_point`.
+
+ It moves the points alone, and a path's curves follow its control points: they
+ are exactly their image under an affine map (a move, a scale, a rotation, a
+ matrix), but stray from it under a function that bends them.
+ [apply_function][manimgx.Mobject.apply_function] maps a path's curves
+ themselves, cutting them where a function bends them.
+
+ Args:
+ func: A function of an (n, 3) array of points, relative to the point, that
+ returns their new places.
+ about_point: The point the function is applied about; None: see
+ `about_edge`.
+ about_edge: The point of the mobject's bounding box it is applied about,
+ named by a direction (UL for its top left corner); None for its center.
+ """
+ if about_point is None:
+ about_point = self.get_critical_point(
+ ORIGIN if about_edge is None else about_edge
+ )
+ about = np.array(about_point, dtype=float)
+ for mob in self.family_members_with_points():
+ mob.points = func(mob.points - about) + about
+ return self
+
+ def shift(self, *vectors: Vector3DLike) -> Self:
+ """Move the mobject and its whole family by a vector.
+
+ Args:
+ *vectors: The vector, in scene units (`2 * RIGHT` moves it two units right);
+ several are added into one.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectShiftExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(color=m.BLUE, fill_opacity=0.5)
+ self.add(square)
+ self.play(square.animate.shift(4 * m.LEFT))
+ self.play(square.animate.shift(2 * m.UP, 8 * m.RIGHT))
+ ```
+ """
+ # one vector (a (1, 3) array too, as CE takes it)
+ vector = vectors[0] if len(vectors) == 1 else reduce(np.add, vectors)
+ total = np.asarray(vector, dtype=float).reshape(-1)
+ for mob in self.family_members_with_points():
+ mob._geometry = mob._geometry.translated(total)
+ return self
+
+ def _apply_linear(
+ self,
+ linear: MatrixMN,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """x ↦ L(x − about) + about on every member: a matrix composed into the geometry."""
+ if about_point is None:
+ about_point = self.get_critical_point(
+ ORIGIN if about_edge is None else about_edge
+ )
+ m = linear_about(
+ np.asarray(linear, dtype=float), np.array(about_point, dtype=float)
+ )
+ for mob in self.family_members_with_points():
+ mob._geometry = mob._geometry.transformed(m)
+ return self
+
+ def scale(
+ self,
+ scale_factor: float | Vector3DLike,
+ scale_stroke: bool = False,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """Scale the mobject and its whole family about a point: by one factor, or by
+ one per axis.
+
+ Stroke widths stay as they are, unless `scale_stroke`.
+
+ Args:
+ scale_factor: The factor: 2 doubles the mobject's size, 0.5 halves it, and a
+ negative factor also reflects it through the point; or its factors along
+ x, y and z.
+ scale_stroke: Whether stroke widths scale too, by the factor (for factors
+ per axis, the geometric mean of the sizes of x's and y's).
+ about_point: The point that stays fixed; None: see `about_edge`.
+ about_edge: The point of the mobject's bounding box that stays fixed, named
+ by a direction (DL for its bottom left corner); None for its center.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectScaleExample(m.Scene):
+ def construct(self) -> None:
+ a = m.Square(color=m.BLUE, fill_opacity=0.5)
+ b, c = a.copy(), a.copy()
+ m.VGroup(a, b, c).arrange(buff=2.5)
+ for square, text in zip(
+ (a, b, c), ("scale(2)", "about_edge=DL", "[0.5, 1.5, 1]")
+ ):
+ self.add(m.Text(text, font_size=32).next_to(square, m.DOWN, 2))
+ self.add(a, b, c)
+ self.play(
+ a.animate.scale(2),
+ b.animate.scale(2, about_edge=m.DL),
+ c.animate.scale([0.5, 1.5, 1]),
+ )
+ ```
+ """
+ if scale_stroke:
+ length = length_factor(scale_factor)
+ for mob in self.get_family():
+ mob.paint = mob.paint.but(
+ stroke_width=length * mob.get_stroke_width(),
+ background_width=length * mob.get_stroke_width(background=True),
+ )
+ if isinstance(scale_factor, (int, float)): # one factor: a scale about a point
+ if about_point is None:
+ edge = ORIGIN if about_edge is None else about_edge
+ about_point = self.get_critical_point(edge)
+ about = np.array(about_point, dtype=float)
+ for mob in self.family_members_with_points():
+ mob._geometry = mob._geometry.scaled(float(scale_factor), about)
+ return self
+ return self._apply_linear(
+ np.diag(axis_factors(scale_factor)), about_point, about_edge
+ )
+
+ def rotate(
+ self,
+ angle: float,
+ axis: Vector3DLike = OUT,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """Rotate the mobject and its whole family by an angle, about an axis through a
+ point.
+
+ Its sheen direction turns with it. Through [animate][manimgx.Mobject.animate],
+ the mobject turns rigidly through the whole angle.
+
+ Args:
+ angle: The angle, in radians: counterclockwise as seen from where `axis`
+ points (on the screen, for the default axis).
+ axis: The axis's direction (default OUT, out of the screen: a turn in the
+ plane).
+ about_point: The point the axis goes through; None: see `about_edge`.
+ about_edge: The point of the mobject's bounding box the axis goes through,
+ named by a direction (DL for its bottom left corner); None for its
+ center.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectRotateExample(m.Scene):
+ def construct(self) -> None:
+ a = m.Square(side_length=2.5, color=m.BLUE, fill_opacity=0.5)
+ b = m.Square(side_length=2.5, color=m.YELLOW, fill_opacity=0.5)
+ m.VGroup(a, b).arrange(buff=4)
+ pivot = m.Dot(b.get_corner(m.DL), radius=0.12, color=m.RED)
+ self.add(a, b, pivot)
+ self.play(
+ a.animate.rotate(m.PI / 4),
+ b.animate.rotate(m.PI / 2, about_edge=m.DL),
+ )
+ ```
+ """
+ rot = rotation_matrix(angle, axis)
+ self._rotate_direction_state(rot)
+ return self._apply_linear(rot, about_point, about_edge)
+
+ def _rotate_direction_state(self, rot: MatrixMN) -> None:
+ for mob in self.get_family():
+ mob.paint = mob.paint.but(sheen_direction=rot @ mob.paint.sheen_direction)
+
+ def rotate_about_origin(self, angle: float, axis: Vector3DLike = OUT) -> Self:
+ """Rotate the mobject and its whole family by an angle, about an axis through
+ the origin.
+
+ Args:
+ angle: The angle, in radians: counterclockwise as seen from where `axis`
+ points.
+ axis: The axis's direction (default OUT: a turn in the plane of the screen).
+ """
+ return self.rotate(angle, axis, about_point=ORIGIN)
+
+ def flip(
+ self,
+ axis: Vector3DLike = UP,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """Flip the mobject and its whole family over: turn it half around an axis
+ through a point, which mirrors it across that axis.
+
+ About the default UP axis, it is mirrored left to right; about RIGHT, upside
+ down. Through [animate][manimgx.Mobject.animate], it turns over, through space.
+
+ Args:
+ axis: The axis's direction (default UP).
+ about_point: The point the axis goes through; None: see `about_edge`.
+ about_edge: The point of the mobject's bounding box the axis goes through,
+ named by a direction; None for its center.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectFlipExample(m.Scene):
+ def construct(self) -> None:
+ word = m.Text("flip", font_size=160, color=m.YELLOW)
+ self.add(word)
+ self.play(word.animate.flip())
+ self.play(word.animate.flip(m.RIGHT))
+ ```
+ """
+ return self.rotate(
+ TAU / 2, axis, about_point=about_point, about_edge=about_edge
+ )
+
+ def stretch_about_point(self, factor: float, dim: int, point: Point3DLike) -> Self:
+ """Stretch the mobject and its whole family along one axis, keeping a point
+ fixed (see [stretch][manimgx.Mobject.stretch]).
+
+ Args:
+ factor: The factor along the axis.
+ dim: The axis: 0 for x, 1 for y, 2 for z.
+ point: The point that stays fixed.
+ """
+ return self.stretch(factor, dim, about_point=point)
+
+ def stretch(
+ self,
+ factor: float,
+ dim: int,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """Stretch the mobject and its whole family along one axis: scale that
+ coordinate of every point, about a point, and keep the others.
+
+ Stroke widths stay as they are.
+
+ Args:
+ factor: The factor: 2 makes the mobject twice as long along the axis.
+ dim: The axis: 0 for x (its width), 1 for y (its height), 2 for z.
+ about_point: The point that stays fixed; None: see `about_edge`.
+ about_edge: The point of the mobject's bounding box that stays fixed, named
+ by a direction (DOWN for the middle of its bottom edge); None for its
+ center.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectStretchExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=1.5, color=m.BLUE, fill_opacity=0.5)
+ self.add(circle)
+ self.play(circle.animate.stretch(3, 0))
+ self.play(circle.animate.stretch(0.5, 1, about_edge=m.DOWN))
+ ```
+ """
+ linear = np.eye(3)
+ linear[dim, dim] = factor
+ return self._apply_linear(linear, about_point, about_edge)
+
+ def apply_matrix(
+ self,
+ matrix: MatrixMN,
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """Transform the mobject and its whole family by a matrix: each point, taken
+ relative to a fixed point, is multiplied by it.
+
+ Args:
+ matrix: A 3 × 3 matrix, or a smaller one (2 × 2) that acts on the first
+ coordinates and keeps the rest.
+ about_point: The point that stays fixed; with neither this nor `about_edge`,
+ the origin.
+ about_edge: The point of the mobject's bounding box that stays fixed, named
+ by a direction.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectApplyMatrixExample(m.Scene):
+ def construct(self) -> None:
+ grid = m.NumberPlane()
+ square = m.Square(color=m.YELLOW, fill_opacity=0.5).shift(m.UR)
+ shear = [[1, 1], [0, 1]]
+ self.add(grid, square)
+ self.play(
+ grid.animate.apply_matrix(shear),
+ square.animate.apply_matrix(shear),
+ run_time=2,
+ )
+ ```
+ """
+ if about_point is None and about_edge is None:
+ about_point = ORIGIN
+ full = np.identity(self.dim)
+ m = np.array(matrix)
+ full[: m.shape[0], : m.shape[1]] = m
+ return self._apply_linear(full, about_point, about_edge)
+
+ def apply_function(
+ self,
+ function: Callable[[Point3D], Point3D],
+ *,
+ about_point: Point3DLike | None = None,
+ about_edge: Vector3DLike | None = None,
+ ) -> Self:
+ """Move the mobject's whole family through a function, about a point: each
+ drawn member becomes its image under the function.
+
+ A path's curves are mapped to the curves of their image. Each curve is mapped to
+ the curve through the images of its ends, along the images of its directions
+ there; where one strays from the true image halfway along it by more than 0.001
+ scene units (a quarter of a pixel at 4K), every curve of the path is cut into 2,
+ 4, 8, … equal pieces (at most 256 each), and the pieces are mapped instead. Any
+ other kind maps its points. Through [animate][manimgx.Mobject.animate], each
+ point of the path, cut the same way, moves straight to its image.
+
+ Args:
+ function: A function of a point, relative to the fixed point, that returns
+ its new place.
+ about_point: The point the function is applied about; with neither this nor
+ `about_edge`, the origin, so the function sees scene coordinates.
+ about_edge: The point of the mobject's bounding box it is applied about,
+ named by a direction.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ def wave(p: np.ndarray) -> np.ndarray:
+ return p + 0.5 * np.array([np.sin(p[1]), np.sin(p[0]), 0])
+
+
+ class MobjectApplyFunctionExample(m.Scene):
+ def construct(self) -> None:
+ grid = m.NumberPlane()
+ grid.prepare_for_nonlinear_transform()
+ self.add(grid)
+ self.play(grid.animate.apply_function(wave), run_time=2)
+ ```
+ """
+ # each leaf becomes its image its own way (`_map_points`): a mobject's points
+ # map; a path's curves become the curves of their image (`VMobject._map_points`)
+ if about_point is None:
+ about_point = (
+ ORIGIN if about_edge is None else self.get_critical_point(about_edge)
+ )
+ about = np.array(about_point, dtype=float)
+ for mob in self.family_members_with_points():
+ mob._map_points(function, about)
+ return self
+
+ def _map_points(
+ self, function: Callable[[Point3D], Point3D], about: np.ndarray
+ ) -> None:
+ """This leaf's image under `function`, about `about`: each point mapped."""
+ self.points = np.apply_along_axis(function, 1, self.points - about) + about
+
+ def apply_complex_function(
+ self, function: Callable[[complex], complex], **kwargs: Unpack[Pivot]
+ ) -> Self:
+ """Move the mobject's whole family through a function of a complex number: the
+ point (x, y, z) is x + iy, and goes where `function` sends it, keeping its z.
+
+ A path's curves are mapped as [apply_function][manimgx.Mobject.apply_function]
+ maps them.
+
+ Args:
+ function: A function of a complex number, returning one.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point the
+ function is applied about (default: the origin).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectApplyComplexFunctionExample(m.Scene):
+ def construct(self) -> None:
+ grid = m.ComplexPlane(x_range=(-4, 4, 0.5), y_range=(-4, 4, 0.5))
+ grid.prepare_for_nonlinear_transform()
+ self.add(grid)
+ self.play(
+ grid.animate.apply_complex_function(lambda z: z**2 / 4),
+ run_time=2,
+ )
+ ```
+ """
+
+ def r3(point: Point3D) -> Point3D:
+ z = function(complex(point[0], point[1]))
+ return np.array([z.real, z.imag, point[2]])
+
+ return self.apply_function(r3, **kwargs)
+
+ def apply_function_to_position(
+ self, function: Callable[[Point3D], Point3D]
+ ) -> Self:
+ """Move the mobject so its center goes where a function sends it; its shape
+ stays.
+
+ Args:
+ function: A function of a point, in scene coordinates, that returns its new
+ place.
+ """
+ return self.move_to(function(self.get_center()))
+
+ def apply_function_to_submobject_positions(
+ self, function: Callable[[Point3D], Point3D]
+ ) -> Self:
+ """Move each submobject so its center goes where a function sends it; their
+ shapes stay.
+
+ Args:
+ function: A function of a point, in scene coordinates, that returns its new
+ place.
+ """
+ for sub in self.submobjects:
+ sub.apply_function_to_position(function)
+ return self
+
+ def reverse_points(self) -> Self:
+ """Reverse the order of the points of each drawn member of the family: a path
+ then runs the other way, from its end to its start.
+ """
+ for mob in self.family_members_with_points():
+ mob.points = mob.points[::-1].copy()
+ return self
+
+ # ── bounds: one box, what the family draws ───────────────────────────────
+ def length_over_dim(self, dim: int) -> float:
+ """The mobject's extent along one axis, in scene units: its
+ [bounding box][manimgx.Mobject.boundary_box]'s, from its lowest coordinate to
+ its highest.
+
+ Args:
+ dim: The axis: 0 for x (its width), 1 for y (its height), 2 for z (its
+ depth).
+
+ Returns:
+ The extent; 0 if it has no points.
+ """
+ box = self.boundary_box()
+ return 0 if box is None else float(box[1, dim] - box[0, dim])
+
+ def get_extremum_along_dim(
+ self, points: Point3D_Array | None = None, dim: int = 0, key: float = 0
+ ) -> float:
+ """The lowest, the middle or the highest coordinate along one axis, of some
+ points or of the mobject's [bounding box][manimgx.Mobject.boundary_box].
+
+ Args:
+ points: The points, as an (n, 3) array; None for the mobject's bounding box.
+ dim: The axis: 0 for x, 1 for y, 2 for z.
+ key: Which: negative for the lowest, 0 for the middle of the range, positive
+ for the highest.
+
+ Returns:
+ The coordinate; 0 for the box of a mobject with no points.
+ """
+ if points is None:
+ box = self.boundary_box()
+ lo, hi = (0.0, 0.0) if box is None else (box[0, dim], box[1, dim])
+ else:
+ lo, hi = np.min(points[:, dim]), np.max(points[:, dim])
+ return float(lo if key < 0 else hi if key > 0 else (lo + hi) / 2)
+
+ def boundary_box(self) -> np.ndarray | None:
+ """The mobject's bounding box: the smallest box, aligned with the axes, around
+ what its family draws.
+
+ A path is measured by its curves themselves, not by their control points (a
+ curve bulges past its anchors where it turns, and its handles reach past the
+ curve); any other kind by its points. A stroke's width is not counted. It is
+ the one box every measure reads: [width][manimgx.Mobject.width] and
+ [height][manimgx.Mobject.height], the corners, edges and center
+ ([get_critical_point][manimgx.Mobject.get_critical_point]), `get_x` and `get_y`,
+ alignment and layout, and the extent of a color gradient. It joins the boxes of
+ the family's members, so a member spans the same in whatever group holds it.
+
+ Returns:
+ A 2 × 3 array, the lowest (x, y, z) then the highest; None if the family has
+ no points.
+ """
+ return _family_box(self.get_family())
+
+ def get_critical_point(self, direction: Vector3DLike) -> Point3D:
+ """A point of the mobject's bounding box, named by a direction: its center, the
+ middle of an edge, or a corner.
+
+ Each coordinate is the box's lowest where the direction's is negative, its
+ highest where it is positive, and its middle where it is 0: UR names the top
+ right corner, UP the middle of the top edge, ORIGIN the center. The box is
+ [boundary_box][manimgx.Mobject.boundary_box], around what the mobject draws: a
+ path's curves themselves, not their control points.
+
+ Args:
+ direction: The direction, such as UP, UR or ORIGIN.
+
+ Returns:
+ The point, in scene coordinates; the origin if the mobject has no points.
+ """
+ box = self.boundary_box()
+ if box is None:
+ return np.zeros(self.dim)
+ lo, hi = box.tolist()
+ return np.array(
+ [
+ lo[k] if d < 0 else hi[k] if d > 0 else (lo[k] + hi[k]) / 2
+ for k, d in enumerate(np.asarray(direction).tolist()[: self.dim])
+ ]
+ )
+
+ get_edge_center = get_critical_point
+ """The middle of an edge of the mobject's bounding box, named by a direction
+ (`get_edge_center(UP)`): another name for
+ [get_critical_point][manimgx.Mobject.get_critical_point]."""
+ get_corner = get_critical_point
+ """A corner of the mobject's bounding box, named by a direction (`get_corner(UR)`):
+ another name for [get_critical_point][manimgx.Mobject.get_critical_point]."""
+
+ def get_center(self) -> Point3D:
+ """The center of the mobject's bounding box.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.get_critical_point(np.zeros(self.dim))
+
+ def get_center_of_mass(self) -> Point3D:
+ """The mean of all the points of the mobject's family: every control point of a
+ path, its handles too.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return np.mean(self.get_all_points(), axis=0)
+
+ def get_boundary_point(self, direction: Vector3DLike) -> Point3D:
+ """The point of the mobject farthest in a direction: of its
+ [boundary points][manimgx.Mobject.get_points_defining_boundary], the one
+ farthest along `direction`.
+
+ Unlike [get_critical_point][manimgx.Mobject.get_critical_point], it is one of
+ those points (for a path, an end of one of its curves), not a point of the
+ mobject's bounding box.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ points = self.get_points_defining_boundary()
+ return points[np.argmax(points @ np.asarray(direction))]
+
+ def get_top(self) -> Point3D:
+ """The middle of the top edge of the mobject's bounding box.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.get_edge_center(UP)
+
+ def get_bottom(self) -> Point3D:
+ """The middle of the bottom edge of the mobject's bounding box.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.get_edge_center(DOWN)
+
+ def get_right(self) -> Point3D:
+ """The middle of the right edge of the mobject's bounding box.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.get_edge_center(RIGHT)
+
+ def get_left(self) -> Point3D:
+ """The middle of the left edge of the mobject's bounding box.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.get_edge_center(LEFT)
+
+ def get_zenith(self) -> Point3D:
+ """The middle of the face of the mobject's bounding box farthest out of the
+ screen (toward OUT: its highest z).
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.get_edge_center(OUT)
+
+ def get_nadir(self) -> Point3D:
+ """The middle of the face of the mobject's bounding box farthest into the screen
+ (toward IN: its lowest z).
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.get_edge_center(IN)
+
+ def get_coord(self, dim: int, direction: Vector3DLike = ORIGIN) -> float:
+ """One coordinate of a point of the mobject's bounding box: along axis `dim`,
+ its lowest, middle or highest, as `direction`'s coordinate there is negative, 0
+ or positive.
+
+ Args:
+ dim: The axis: 0 for x, 1 for y, 2 for z.
+ direction: A direction such as LEFT, ORIGIN or RIGHT (default ORIGIN: the
+ middle).
+ """
+ return self.get_extremum_along_dim(dim=dim, key=np.asarray(direction)[dim])
+
+ def get_x(self, direction: Vector3DLike = ORIGIN) -> float:
+ """The x coordinate of the mobject's center, or of an edge of its bounding box.
+
+ Args:
+ direction: LEFT for its left edge, RIGHT for its right edge; ORIGIN
+ (default) for its center.
+ """
+ return self.get_coord(0, direction)
+
+ def get_y(self, direction: Vector3DLike = ORIGIN) -> float:
+ """The y coordinate of the mobject's center, or of an edge of its bounding box.
+
+ Args:
+ direction: DOWN for its bottom edge, UP for its top edge; ORIGIN (default)
+ for its center.
+ """
+ return self.get_coord(1, direction)
+
+ def get_z(self, direction: Vector3DLike = ORIGIN) -> float:
+ """The z coordinate of the mobject's center, or of a face of its bounding box.
+
+ Args:
+ direction: IN for its lowest z, OUT for its highest; ORIGIN (default) for
+ its center.
+ """
+ return self.get_coord(2, direction)
+
+ def get_midpoint(self) -> Point3D:
+ """The point halfway along the mobject: for a path, half its length from its
+ start.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self.point_from_proportion(0.5)
+
+ def point_from_proportion(self, alpha: float) -> Point3D:
+ """The point a proportion of the way along the mobject, from its start (0) to
+ its end (1): for a path, by its length.
+
+ Each kind implements it; a mobject of no kind has no way along it, and raises an
+ exception.
+
+ Args:
+ alpha: The proportion, from 0 to 1.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ raise NotImplementedError(f"{type(self).__name__} has no parametrization")
+
+ @property
+ def width(self) -> float:
+ """The mobject's width, in scene units: its
+ [bounding box][manimgx.Mobject.boundary_box]'s extent along x, from the leftmost
+ of what it draws to the rightmost. Set it to scale the mobject to that width, in
+ proportion, about its center."""
+ return self.length_over_dim(0)
+
+ @width.setter
+ def width(self, value: float) -> None:
+ self.scale_to_fit_width(value)
+
+ @property
+ def height(self) -> float:
+ """The mobject's height, in scene units: its
+ [bounding box][manimgx.Mobject.boundary_box]'s extent along y, from the lowest
+ of what it draws to the highest. Set it to scale the mobject to that height, in
+ proportion, about its center."""
+ return self.length_over_dim(1)
+
+ @height.setter
+ def height(self, value: float) -> None:
+ self.scale_to_fit_height(value)
+
+ def get_width(self) -> float:
+ """The mobject's [width][manimgx.Mobject.width].
+
+ Returns:
+ The width, in scene units.
+ """
+ return self.width
+
+ # ── layout ────────────────────────────────────────────────────────────
+ def center(self) -> Self:
+ """Move the mobject so the center of its bounding box is at the origin."""
+ return self.shift(-self.get_center())
+
+ def move_to(
+ self,
+ point_or_mobject: "Point3DLike | Mobject",
+ aligned_edge: Vector3DLike = ORIGIN,
+ coor_mask: Vector3DLike = (1, 1, 1),
+ ) -> Self:
+ """Move the mobject to a point, or onto another mobject: its center, or the
+ point of its bounding box `aligned_edge` names, goes there.
+
+ Args:
+ point_or_mobject: A point, in scene coordinates, or a mobject: then the
+ point of its bounding box `aligned_edge` names (its center, by default).
+ aligned_edge: The point of the mobject that goes there, named by a
+ direction: ORIGIN (default) for its center, DL for its bottom left
+ corner.
+ coor_mask: Which coordinates change: 1 for each axis the mobject moves
+ along, 0 for one it keeps (`(1, 0, 0)` moves it horizontally only).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectMoveToExample(m.Scene):
+ def construct(self) -> None:
+ dot = m.Dot([3, 1.5, 0], radius=0.15, color=m.YELLOW)
+ origin = m.Dot(radius=0.15, color=m.RED)
+ square = m.Square(color=m.BLUE, fill_opacity=0.5).shift(4 * m.LEFT)
+ self.add(dot, origin, square)
+ self.play(square.animate.move_to(dot))
+ self.play(square.animate.move_to(m.ORIGIN, aligned_edge=m.DL))
+ ```
+ """
+ if isinstance(point_or_mobject, Mobject):
+ target = point_or_mobject.get_critical_point(aligned_edge)
+ else:
+ target = np.asarray(point_or_mobject, dtype=float)
+ return self.shift(
+ (target - self.get_critical_point(aligned_edge)) * np.asarray(coor_mask)
+ )
+
+ def next_to(
+ self,
+ mobject_or_point: "Mobject | Point3DLike",
+ direction: Vector3DLike = RIGHT,
+ buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
+ aligned_edge: Vector3DLike = ORIGIN,
+ submobject_to_align: "Mobject | None" = None,
+ index_of_submobject_to_align: int | None = None,
+ coor_mask: Vector3DLike = (1, 1, 1),
+ ) -> Self:
+ """Put the mobject beside another, or beside a point, `buff` away in a
+ direction.
+
+ The side of the mobject facing back along `direction` goes to the other's side
+ facing along it, `buff` farther on: with RIGHT, the middle of its left edge goes
+ `buff` to the right of the middle of the other's right edge. A diagonal
+ direction (UR) puts corner to corner.
+
+ Args:
+ mobject_or_point: The mobject (its bounding box) or the point to put it
+ beside.
+ direction: The side: RIGHT (default), UP, DL, …
+ buff: The gap, in scene units, along `direction` (default 0.25).
+ aligned_edge: The edge along which the two line up besides the side they
+ meet at, named by a direction: with the direction RIGHT and UP here,
+ their tops line up (default ORIGIN: centered).
+ submobject_to_align: A part of the mobject to put beside the other in its
+ place; the rest moves with it.
+ index_of_submobject_to_align: The index of the part of each mobject to line
+ up: this one's part goes beside the other's.
+ coor_mask: Which coordinates change: 1 for each axis the mobject moves
+ along, 0 for one it keeps.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectNextToExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
+ right = m.Text("RIGHT").next_to(square, m.RIGHT)
+ up = m.Text("UP, aligned LEFT").next_to(
+ square, m.UP, aligned_edge=m.LEFT
+ )
+ down = m.Text("DOWN, buff=1").next_to(square, m.DOWN, buff=1)
+ dot = m.Dot(radius=0.2, color=m.YELLOW)
+ dot.next_to(square, m.UL, buff=0)
+ self.add(square, right, up, down, dot)
+ ```
+ """
+ d, edge = np.asarray(direction, dtype=float), np.asarray(
+ aligned_edge, dtype=float
+ )
+ if isinstance(mobject_or_point, Mobject):
+ target_aligner = (
+ mobject_or_point
+ if index_of_submobject_to_align is None
+ else mobject_or_point[index_of_submobject_to_align]
+ )
+ target = target_aligner.get_critical_point(edge + d)
+ else:
+ target = np.asarray(mobject_or_point, dtype=float)
+ if submobject_to_align is not None:
+ aligner: Mobject = submobject_to_align
+ elif index_of_submobject_to_align is not None:
+ aligner = self[index_of_submobject_to_align]
+ else:
+ aligner = self
+ point_to_align = aligner.get_critical_point(edge - d)
+ return self.shift((target - point_to_align + buff * d) * np.asarray(coor_mask))
+
+ def align_on_border(
+ self, direction: Vector3DLike, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER
+ ) -> Self:
+ """Move the mobject to an edge or a corner of the frame, `buff` in from it.
+
+ Only the coordinates along which `direction` points change: sent to the top
+ edge, the mobject moves up or down only. The frame is the configured one,
+ centered on the origin, wherever the camera looks.
+
+ Args:
+ direction: The edge (UP, LEFT, …) or the corner (UR, DL, …) of the frame.
+ buff: The margin between the mobject and the frame's edge, in scene units
+ (default 0.5).
+ """
+ d = np.asarray(direction, dtype=float)
+ target = np.sign(d) * (config.frame_x_radius, config.frame_y_radius, 0)
+ shift = (target - self.get_critical_point(d) - buff * d) * np.abs(np.sign(d))
+ return self.shift(shift)
+
+ def to_corner(
+ self, corner: Vector3DLike = DL, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER
+ ) -> Self:
+ """Move the mobject into a corner of the frame, `buff` in from both its edges.
+
+ The frame is the configured one, centered on the origin, wherever the camera
+ looks.
+
+ Args:
+ corner: The corner: UL, UR, DL (default) or DR.
+ buff: The margin between the mobject and each edge of the frame, in scene
+ units (default 0.5).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectToCornerExample(m.Scene):
+ def construct(self) -> None:
+ self.add(m.Text("UL").to_corner(m.UL))
+ self.add(m.Text("UR, buff=0").to_corner(m.UR, buff=0))
+ self.add(m.Circle(color=m.BLUE).to_corner(m.DL))
+ self.add(m.Square(color=m.YELLOW).to_corner(m.DR, buff=1))
+ ```
+ """
+ return self.align_on_border(corner, buff)
+
+ def to_edge(
+ self, edge: Vector3DLike = LEFT, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER
+ ) -> Self:
+ """Move the mobject to an edge of the frame, `buff` in from it; along the edge,
+ it stays where it is.
+
+ The frame is the configured one, centered on the origin, wherever the camera
+ looks.
+
+ Args:
+ edge: The edge: UP, DOWN, LEFT (default) or RIGHT.
+ buff: The margin between the mobject and the edge, in scene units (default
+ 0.5).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectToEdgeExample(m.Scene):
+ def construct(self) -> None:
+ top = m.Text("to_edge(UP)").to_edge(m.UP)
+ left = m.Text("to_edge(LEFT)").to_edge(m.LEFT)
+ circle = m.Circle(color=m.BLUE).shift(2 * m.DOWN)
+ circle.to_edge(m.RIGHT, buff=0)
+ self.add(top, left, circle)
+ ```
+ """
+ return self.align_on_border(edge, buff)
+
+ def is_off_screen(self) -> bool:
+ """Whether the mobject is wholly outside the frame: the configured one, centered
+ on the origin.
+
+ Returns:
+ True if its bounding box lies wholly past an edge of the frame.
+ """
+ x, y = config.frame_x_radius, config.frame_y_radius
+ return bool(
+ self.get_left()[0] > x
+ or self.get_right()[0] < -x
+ or self.get_bottom()[1] > y
+ or self.get_top()[1] < -y
+ )
+
+ def shift_onto_screen(self, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER) -> Self:
+ """Move the mobject back into the frame where it reaches past an edge, or nearer
+ to it than `buff`: to that edge, `buff` in (see
+ [to_edge][manimgx.Mobject.to_edge]).
+
+ Args:
+ buff: The margin to keep from the frame's edges, in scene units (default
+ 0.5).
+ """
+ radii = (config.frame_x_radius, config.frame_y_radius)
+ for vect in (UP, DOWN, LEFT, RIGHT):
+ dim = int(np.argmax(np.abs(vect)))
+ if np.dot(self.get_edge_center(vect), vect) > radii[dim] - buff:
+ self.to_edge(vect, buff=buff)
+ return self
+
+ background_rectangle: "Mobject | None" = None
+ """The rectangle last put behind the mobject (see
+ [add_background_rectangle][manimgx.Mobject.add_background_rectangle]); None if
+ none."""
+
+ def add_background_rectangle(
+ self,
+ color: ParsableManimColor | None = None,
+ opacity: float = 0.75,
+ **kwargs: Unpack[BackgroundOptions],
+ ) -> Self:
+ """Put a rectangle behind the mobject, to set it off from whatever is behind it:
+ a [BackgroundRectangle][manimgx.BackgroundRectangle] around it, added as its
+ first submobject.
+
+ The rectangle moves with the mobject; it is the mobject's
+ [background_rectangle][manimgx.Mobject.background_rectangle].
+
+ Args:
+ color: The rectangle's color; None for the scene's background color.
+ opacity: The rectangle's opacity, from 0 to 1 (default 0.75).
+ **kwargs: [Background keywords][manimgx.mobject.BackgroundOptions]: its
+ margin, corners and outline.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectAddBackgroundRectangleExample(m.Scene):
+ def construct(self) -> None:
+ label = m.Text("set off from the grid", font_size=64)
+ label.add_background_rectangle(color=m.BLACK, opacity=0.9, buff=0.2)
+ self.add(m.NumberPlane(), label)
+ ```
+ """
+ from manimgx.mobjects.annotations import BackgroundRectangle
+
+ self.background_rectangle = BackgroundRectangle(
+ self, color=color, fill_opacity=opacity, **kwargs
+ )
+ return self.add_to_back(self.background_rectangle)
+
+ def align_to(
+ self,
+ mobject_or_point: "Mobject | Point3DLike",
+ direction: Vector3DLike = ORIGIN,
+ ) -> Self:
+ """Move the mobject so a side of it lines up with another's: along each axis on
+ which `direction` is not 0, the side of its bounding box in that direction goes
+ where the other's is.
+
+ `align_to(other, UP)` puts its top at the height of the other's top, moving it
+ up or down only; `align_to(other, UL)` lines up both tops and both left sides.
+ With the default ORIGIN, nothing moves.
+
+ Args:
+ mobject_or_point: The mobject to line up with (the side of its bounding box
+ `direction` names), or a point.
+ direction: The side, named by a direction: UP, DL, …
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectAlignToExample(m.Scene):
+ def construct(self) -> None:
+ floor = m.Line(6 * m.LEFT, 6 * m.RIGHT).shift(3 * m.DOWN)
+ shapes = m.VGroup(
+ m.Circle(color=m.BLUE),
+ m.Square(side_length=3, color=m.GREEN),
+ m.Triangle(color=m.YELLOW),
+ m.Star(color=m.RED),
+ ).arrange(buff=1)
+ self.add(floor, shapes)
+ self.play(*(s.animate.align_to(floor, m.DOWN) for s in shapes))
+ ```
+ """
+ point = (
+ mobject_or_point.get_critical_point(direction)
+ if isinstance(mobject_or_point, Mobject)
+ else np.asarray(mobject_or_point)
+ )
+ for dim in range(self.dim):
+ if direction[dim] != 0:
+ self.set_coord(point[dim], dim, direction)
+ return self
+
+ def set_coord(
+ self, value: float, dim: int, direction: Vector3DLike = ORIGIN
+ ) -> Self:
+ """Move the mobject along one axis so a coordinate of its bounding box is
+ `value`: its lowest, middle or highest, as `direction`'s coordinate there is
+ negative, 0 or positive.
+
+ Args:
+ value: The coordinate, in scene units.
+ dim: The axis: 0 for x, 1 for y, 2 for z.
+ direction: A direction such as LEFT, ORIGIN or RIGHT (default ORIGIN: the
+ center).
+ """
+ shift = np.zeros(self.dim)
+ shift[dim] = value - self.get_coord(dim, direction)
+ return self.shift(shift)
+
+ def set_x(self, x: float, direction: Vector3DLike = ORIGIN) -> Self:
+ """Move the mobject left or right so its center, or an edge of its bounding box,
+ is at `x`.
+
+ Args:
+ x: The x coordinate, in scene units.
+ direction: LEFT to place its left edge, RIGHT its right edge; ORIGIN
+ (default) its center.
+ """
+ return self.set_coord(x, 0, direction)
+
+ def set_y(self, y: float, direction: Vector3DLike = ORIGIN) -> Self:
+ """Move the mobject up or down so its center, or an edge of its bounding box, is
+ at `y`.
+
+ Args:
+ y: The y coordinate, in scene units.
+ direction: DOWN to place its bottom edge, UP its top edge; ORIGIN (default)
+ its center.
+ """
+ return self.set_coord(y, 1, direction)
+
+ def set_z(self, z: float, direction: Vector3DLike = ORIGIN) -> Self:
+ """Move the mobject in or out so its center, or a face of its bounding box, is
+ at `z`.
+
+ Args:
+ z: The z coordinate, in scene units.
+ direction: IN to place its lowest z, OUT its highest; ORIGIN (default) its
+ center.
+ """
+ return self.set_coord(z, 2, direction)
+
+ def rescale_to_fit(
+ self, length: float, dim: int, stretch: bool = False, **kwargs: Unpack[Pivot]
+ ) -> Self:
+ """Scale the mobject so its extent along one axis is `length`: in proportion, or
+ along that axis only.
+
+ A mobject with no extent along the axis stays as it is.
+
+ Args:
+ length: The extent, in scene units.
+ dim: The axis: 0 for x (its width), 1 for y (its height), 2 for z (its
+ depth).
+ stretch: Whether to stretch it along that axis only, instead of scaling it
+ in proportion.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ old = self.length_over_dim(dim)
+ if old == 0:
+ return self
+ return (
+ self.stretch(length / old, dim, **kwargs)
+ if stretch
+ else self.scale(length / old, **kwargs)
+ )
+
+ def scale_to_fit_width(self, width: float, **kwargs: Unpack[Pivot]) -> Self:
+ """Scale the mobject in proportion to a width.
+
+ Args:
+ width: The width, in scene units.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.rescale_to_fit(width, 0, stretch=False, **kwargs)
+
+ def stretch_to_fit_width(self, width: float, **kwargs: Unpack[Pivot]) -> Self:
+ """Stretch the mobject horizontally to a width; its height stays.
+
+ Args:
+ width: The width, in scene units.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.rescale_to_fit(width, 0, stretch=True, **kwargs)
+
+ def scale_to_fit_height(self, height: float, **kwargs: Unpack[Pivot]) -> Self:
+ """Scale the mobject in proportion to a height.
+
+ Args:
+ height: The height, in scene units.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.rescale_to_fit(height, 1, stretch=False, **kwargs)
+
+ def stretch_to_fit_height(self, height: float, **kwargs: Unpack[Pivot]) -> Self:
+ """Stretch the mobject vertically to a height; its width stays.
+
+ Args:
+ height: The height, in scene units.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.rescale_to_fit(height, 1, stretch=True, **kwargs)
+
+ def match_dim_size(
+ self, mobject: "Mobject", dim: int, **kwargs: Unpack[Pivot]
+ ) -> Self:
+ """Scale the mobject in proportion so its extent along one axis is another's.
+
+ Args:
+ mobject: The mobject to match.
+ dim: The axis: 0 for x (width), 1 for y (height), 2 for z (depth).
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.rescale_to_fit(mobject.length_over_dim(dim), dim, **kwargs)
+
+ def match_width(self, mobject: "Mobject", **kwargs: Unpack[Pivot]) -> Self:
+ """Scale the mobject in proportion to another's width.
+
+ Args:
+ mobject: The mobject to match.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.match_dim_size(mobject, 0, **kwargs)
+
+ def match_height(self, mobject: "Mobject", **kwargs: Unpack[Pivot]) -> Self:
+ """Scale the mobject in proportion to another's height.
+
+ Args:
+ mobject: The mobject to match.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.match_dim_size(mobject, 1, **kwargs)
+
+ def match_depth(self, mobject: "Mobject", **kwargs: Unpack[Pivot]) -> Self:
+ """Scale the mobject in proportion to another's depth, its extent along z.
+
+ Args:
+ mobject: The mobject to match.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+ """
+ return self.match_dim_size(mobject, 2, **kwargs)
+
+ def match_coord(
+ self, mobject: "Mobject", dim: int, direction: Vector3DLike = ORIGIN
+ ) -> Self:
+ """Move the mobject along one axis to another's coordinate there: the same point
+ of each one's bounding box, as `direction` names it, gets the same coordinate.
+
+ Args:
+ mobject: The mobject to match.
+ dim: The axis: 0 for x, 1 for y, 2 for z.
+ direction: Which point along the axis: the lowest, the middle (ORIGIN,
+ default) or the highest, as its coordinate there is negative, 0 or
+ positive.
+ """
+ return self.set_coord(mobject.get_coord(dim, direction), dim, direction)
+
+ def match_x(self, mobject: "Mobject", direction: Vector3DLike = ORIGIN) -> Self:
+ """Move the mobject left or right to another's x: centers, or left or right
+ edges, lined up.
+
+ Args:
+ mobject: The mobject to match.
+ direction: LEFT to line up the left edges, RIGHT the right ones; ORIGIN
+ (default) the centers.
+ """
+ return self.match_coord(mobject, 0, direction)
+
+ def match_y(self, mobject: "Mobject", direction: Vector3DLike = ORIGIN) -> Self:
+ """Move the mobject up or down to another's y: centers, or top or bottom edges,
+ lined up.
+
+ Args:
+ mobject: The mobject to match.
+ direction: DOWN to line up the bottom edges, UP the top ones; ORIGIN
+ (default) the centers.
+ """
+ return self.match_coord(mobject, 1, direction)
+
+ def match_z(self, mobject: "Mobject", direction: Vector3DLike = ORIGIN) -> Self:
+ """Move the mobject in or out to another's z: centers, or faces, lined up.
+
+ Args:
+ mobject: The mobject to match.
+ direction: IN to line up the lowest z, OUT the highest; ORIGIN (default) the
+ centers.
+ """
+ return self.match_coord(mobject, 2, direction)
+
+ def replace(
+ self, mobject: "Mobject", dim_to_match: int = 0, stretch: bool = False
+ ) -> Self:
+ """Put the mobject in another's place: scaled to its extent along one axis (or
+ stretched to its width and height), and centered on it.
+
+ The other mobject stays where it is.
+
+ Args:
+ mobject: The mobject whose place it takes.
+ dim_to_match: The axis whose extent it takes, in proportion: 0 for x (the
+ width), 1 for y (the height), 2 for z.
+ stretch: Whether to stretch it to the other's width and height instead.
+ """
+ if stretch:
+ self.stretch_to_fit_width(mobject.width)
+ self.stretch_to_fit_height(mobject.height)
+ else:
+ self.rescale_to_fit(mobject.length_over_dim(dim_to_match), dim_to_match)
+ return self.shift(mobject.get_center() - self.get_center())
+
+ def put_start_and_end_on(self, start: Point3DLike, end: Point3DLike) -> Self:
+ """Move, turn and scale the mobject so its first point is at `start` and its
+ last at `end`; its shape stays, scaled in proportion.
+
+ A mobject whose first and last points coincide is only moved.
+
+ Args:
+ start: Where its first point goes.
+ end: Where its last point goes.
+ """
+ cur_start, cur_end = self.get_start_and_end()
+ cur_vec = cur_end - cur_start
+ if np.all(cur_vec == 0):
+ return self.shift(np.asarray(start) - cur_start)
+ target_vec = np.asarray(end) - np.asarray(start)
+ angle, axis = turn_between(cur_vec, target_vec)
+ self.scale(
+ np.linalg.norm(target_vec) / np.linalg.norm(cur_vec), about_point=cur_start
+ )
+ self.rotate(angle, about_point=cur_start, axis=axis)
+ return self.shift(np.asarray(start) - cur_start)
+
+ def arrange(
+ self,
+ direction: Vector3DLike = RIGHT,
+ buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
+ center: bool = True,
+ **kwargs: Unpack[Beside],
+ ) -> Self:
+ """Lay the submobjects out in a row: each one beside the one before it (see
+ [next_to][manimgx.Mobject.next_to]), `buff` apart; then center the whole at the
+ origin.
+
+ Args:
+ direction: The way the row goes: RIGHT (default), DOWN for a column, …
+ buff: The gap between neighbours, in scene units (default 0.25).
+ center: Whether to center the mobject at the origin afterwards; if not, the
+ first submobject stays where it was.
+ **kwargs: [Beside keywords][manimgx.mobject.Beside]: how neighbours
+ line up (`aligned_edge=DOWN` puts their bottoms on one line).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectArrangeExample(m.Scene):
+ def construct(self) -> None:
+ sizes = (0.5, 1, 2)
+ squares = m.VGroup(*(m.Square(s, color=m.BLUE) for s in sizes))
+ squares.arrange(buff=0.5, aligned_edge=m.DOWN)
+ words = m.VGroup(m.Text("one"), m.Text("three"), m.Text("eleven"))
+ words.arrange(m.DOWN, aligned_edge=m.LEFT)
+ self.add(m.VGroup(squares, words).arrange(buff=1.5))
+ ```
+ """
+ for m1, m2 in zip(self.submobjects[:-1], self.submobjects[1:], strict=True):
+ m2.next_to(m1, direction, buff, **kwargs)
+ return self.center() if center else self
+
+ arrange_submobjects = arrange
+ """Another name for [arrange][manimgx.Mobject.arrange]."""
+
+ def arrange_in_grid(
+ self,
+ rows: int | None = None,
+ cols: int | None = None,
+ buff: float | tuple[float, float] = MED_SMALL_BUFF,
+ cell_alignment: Vector3DLike = ORIGIN,
+ row_alignments: str | None = None,
+ col_alignments: str | None = None,
+ row_heights: Iterable[float | None] | None = None,
+ col_widths: Iterable[float | None] | None = None,
+ flow_order: str = "rd",
+ ) -> Self:
+ """Lay the submobjects out in a grid of rows and columns, centered where the
+ mobject was.
+
+ Each row is as tall as its tallest mobject and each column as wide as its
+ widest, unless given. Each mobject sits in its cell as `cell_alignment` says,
+ but vertically as `row_alignments` says for its row and horizontally as
+ `col_alignments` says for its column, where they are given. Too few rows and
+ columns for the submobjects raise an exception.
+
+ Args:
+ rows: How many rows; None for as many as `row_alignments` or `row_heights`
+ lists, else as many as the submobjects need. With neither `rows` nor
+ `cols`, the grid is as square as it can be.
+ cols: How many columns; None for as many as `col_alignments` or `col_widths`
+ lists, else as many as the submobjects need.
+ buff: The gap between cells, in scene units: one for both directions, or
+ (horizontal, vertical) (default 0.25).
+ cell_alignment: Where each mobject sits in its cell, named by a direction:
+ UL for its top left corner (default ORIGIN: centered).
+ row_alignments: Each row's vertical alignment, top to bottom: a letter per
+ row, "u" (up), "c" (center) or "d" (down); None: as the vertical part of
+ `cell_alignment` says (UL: up).
+ col_alignments: Each column's horizontal alignment, left to right: a letter
+ per column, "l" (left), "c" (center) or "r" (right); None: as the
+ horizontal part of `cell_alignment` says (UL: left).
+ row_heights: Each row's height, top to bottom, in scene units; None (for the
+ grid or a row) for the height of the row's tallest mobject.
+ col_widths: Each column's width, left to right, in scene units; None (for
+ the grid or a column) for the width of the column's widest mobject.
+ flow_order: The order the cells are filled in: two letters, the direction a
+ line of cells fills and then the direction the lines follow each other,
+ "r" (right), "l" (left), "u" (up) or "d" (down). The default "rd" fills
+ rows left to right, from the top down; "dr" fills columns top to bottom,
+ from the left.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ def cells() -> m.VGroup:
+ return m.VGroup(
+ *(
+ m.Square(0.9, color=m.BLUE).add(m.Text(str(i), font_size=36))
+ for i in range(1, 11)
+ )
+ )
+
+
+ class MobjectArrangeInGridExample(m.Scene):
+ def construct(self) -> None:
+ by_rows = cells().arrange_in_grid(rows=3, buff=0.2)
+ by_cols = cells().arrange_in_grid(rows=3, buff=0.2, flow_order="dr")
+ self.add(m.VGroup(by_rows, by_cols).arrange(buff=1.5))
+ ```
+ """
+ mobs = list(self.submobjects)
+ start_pos = self.get_center()
+ heights_in = list(row_heights) if row_heights is not None else None
+ widths_in = list(col_widths) if col_widths is not None else None
+ cols = cols or (
+ len(col_alignments)
+ if col_alignments
+ else len(widths_in) if widths_in else None
+ )
+ rows = rows or (
+ len(row_alignments)
+ if row_alignments
+ else len(heights_in) if heights_in else None
+ )
+ if rows is None:
+ cols = math.ceil(math.sqrt(len(mobs))) if cols is None else cols
+ rows = math.ceil(len(mobs) / cols)
+ elif cols is None:
+ cols = math.ceil(len(mobs) / rows)
+ if rows * cols < len(mobs):
+ raise ValueError("Too few rows and columns to fit all submobjetcs.")
+ bx, by = buff if isinstance(buff, tuple) else (buff, buff)
+ cell = np.asarray(cell_alignment, dtype=float)
+ rdirs = ( # a row aligns its cells vertically, a column horizontally
+ [cell * UP] * rows
+ if row_alignments is None
+ else [{"u": UP, "c": ORIGIN, "d": DOWN}[c] for c in row_alignments]
+ )
+ cdirs = (
+ [cell * RIGHT] * cols
+ if col_alignments is None
+ else [{"l": LEFT, "c": ORIGIN, "r": RIGHT}[c] for c in col_alignments]
+ )
+ index = {
+ "dr": lambda r, c: rows - r - 1 + c * rows,
+ "dl": lambda r, c: rows - r - 1 + (cols - c - 1) * rows,
+ "ur": lambda r, c: r + c * rows,
+ "ul": lambda r, c: r + (cols - c - 1) * rows,
+ "rd": lambda r, c: (rows - r - 1) * cols + c,
+ "ld": lambda r, c: (rows - r - 1) * cols + (cols - c - 1),
+ "ru": lambda r, c: r * cols + c,
+ "lu": lambda r, c: r * cols + (cols - c - 1),
+ }[flow_order]
+ rdirs.reverse()
+ heights_given = list(reversed(heights_in)) if heights_in else [None] * rows
+ placeholder = Mobject()
+ mobs.extend([placeholder] * (rows * cols - len(mobs)))
+ grid = [[mobs[index(r, c)] for c in range(cols)] for r in range(rows)]
+ heights = [
+ h if h is not None else max(grid[r][c].height for c in range(cols))
+ for r, h in enumerate(heights_given)
+ ]
+ widths = [
+ w if w is not None else max(grid[r][c].width for r in range(rows))
+ for c, w in enumerate(widths_in or [None] * cols)
+ ]
+ y = 0.0
+ for r in range(rows):
+ x = 0.0
+ for c in range(cols):
+ if grid[r][c] is not placeholder:
+ lo, hi = np.array([x, y, 0.0]), np.array(
+ [x + widths[c], y + heights[r], 0.0]
+ )
+ align = rdirs[r] + cdirs[c]
+ corner = np.where(
+ align < 0, lo, np.where(align > 0, hi, (lo + hi) / 2)
+ )
+ grid[r][c].move_to(corner, align)
+ x += widths[c] + bx
+ y += heights[r] + by
+ return self.move_to(start_pos)
+
+ def sort(
+ self,
+ point_to_num_func: Callable[[Point3D], float] = lambda p: p[0],
+ submob_func: Callable[["Mobject"], float] | None = None,
+ ) -> Self:
+ """Sort the submobjects by a number: one computed from each one's center (by
+ default its x coordinate, so left to right), or from each one itself.
+
+ Their order is the order they are drawn in (at an equal z-index), and the order
+ a `lag_ratio` staggers their animation in.
+
+ Args:
+ point_to_num_func: A function of a submobject's center, giving the number to
+ sort it by.
+ submob_func: A function of a submobject, giving the number to sort it by, in
+ place of `point_to_num_func`.
+ """
+ key = submob_func or (lambda m: point_to_num_func(m.get_center()))
+ self.submobjects.sort(key=key)
+ return self
+
+ def shuffle(self, recursive: bool = False) -> Self:
+ """Put the submobjects in a random order, drawn from Python's `random`.
+
+ Args:
+ recursive: Whether each submobject's submobjects are shuffled too, and
+ theirs.
+ """
+ if recursive:
+ for sub in self.submobjects:
+ sub.shuffle(recursive=True)
+ random.shuffle(self.submobjects)
+ return self
+
+ def invert(self, recursive: bool = False) -> Self:
+ """Reverse the order of the submobjects.
+
+ Args:
+ recursive: Whether each submobject's submobjects are reversed too, and
+ theirs.
+ """
+ if recursive:
+ for sub in self.submobjects:
+ sub.invert(recursive=True)
+ self.submobjects.reverse()
+ return self
+
+ def space_out_submobjects(
+ self, factor: float = 1.5, **kwargs: Unpack[Pivot]
+ ) -> Self:
+ """Spread the submobjects apart, each keeping its size: the mobject is scaled by
+ `factor`, then each submobject back by 1 / `factor`, about its own center.
+
+ Args:
+ factor: How much farther apart their centers go (1.5: half as far again).
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point they
+ spread out from (default: the mobject's center).
+ """
+ self.scale(factor, **kwargs)
+ for sub in self.submobjects:
+ sub.scale(1.0 / factor)
+ return self
+
+ def set_z_index(self, z_index_value: float, family: bool = True) -> Self:
+ """Set the mobject's place in the drawing order: a higher z-index is drawn over
+ a lower one, anywhere in the scene.
+
+ Mobjects of an equal z-index are drawn in the scene's order: the ones added
+ later over the ones added earlier, and a mobject's submobjects each over those
+ before it. Every mobject's z-index is 0 unless set.
+
+ Args:
+ z_index_value: The z-index.
+ family: Whether its whole family gets it, or the mobject alone (which orders
+ only its own points).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSetZIndexExample(m.Scene):
+ def construct(self) -> None:
+ red = m.Square(3, color=m.RED, fill_opacity=1).shift(m.LEFT + m.UP)
+ blue = m.Square(3, color=m.BLUE, fill_opacity=1)
+ green = m.Square(3, color=m.GREEN, fill_opacity=1)
+ green.shift(m.RIGHT + m.DOWN)
+ red.set_z_index(1) # added first, drawn on top
+ self.add(red, blue, green)
+ ```
+ """
+ if family:
+ for sub in self.submobjects:
+ sub.set_z_index(z_index_value, family)
+ self.z_index = z_index_value
+ return self
+
+ # ── style: written once for every kind, through Paint ──────────────────
+ def _each(self, family: bool) -> list["Mobject"]:
+ return self.get_family() if family else [self]
+
+ def set_fill(
+ self,
+ color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
+ opacity: float | Iterable[float] | None = None,
+ family: bool = True,
+ ) -> Self:
+ """Set the mobject's fill: its color, its opacity, or both.
+
+ Args:
+ color: The color; several make a gradient across the mobject, from the first
+ to the last toward its sheen direction (UL unless set). None keeps the
+ present one.
+ opacity: The opacity, from 0 (no fill) to 1 (opaque); several make a
+ gradient of opacities. None keeps the present one.
+ family: Whether its whole family is filled, or the mobject alone.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSetFillExample(m.Scene):
+ def construct(self) -> None:
+ a, b, c = (m.Square(side_length=2.5) for _ in range(3))
+ m.VGroup(a, b, c).arrange(buff=1)
+ a.set_fill(m.BLUE, opacity=1)
+ b.set_fill(m.GREEN, opacity=0.4)
+ c.set_fill([m.YELLOW, m.RED], opacity=1)
+ self.add(a, b, c)
+ ```
+ """
+ for mob in reversed(self._each(family)):
+ mob.paint = mob.paint.updated("fill", color, opacity)
+ return self
+
+ def set_stroke(
+ self,
+ color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
+ width: float | None = None,
+ opacity: float | Iterable[float] | None = None,
+ background: bool = False,
+ family: bool = True,
+ ) -> Self:
+ """Set the mobject's stroke, its outline: its color, width and opacity, any of
+ them.
+
+ Args:
+ color: The color; several make a gradient, from the first to the last toward
+ the mobject's sheen direction (UL unless set). None keeps the present
+ one.
+ width: The width, in hundredths of a scene unit (4 unless styled; 0: no
+ stroke); None keeps the present one.
+ opacity: The opacity, from 0 to 1; several make a gradient of opacities.
+ None keeps the present one.
+ background: Whether to set the background stroke instead: an outline drawn
+ behind the fill.
+ family: Whether its whole family is stroked, or the mobject alone.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSetStrokeExample(m.Scene):
+ def construct(self) -> None:
+ a = m.Circle(radius=1.5, color=m.BLUE, fill_opacity=0.3)
+ b, c = a.copy(), a.copy()
+ m.VGroup(a, b, c).arrange(buff=1)
+ a.set_stroke(m.YELLOW, width=2)
+ b.set_stroke(m.YELLOW, width=16)
+ c.set_stroke(m.YELLOW, width=16, opacity=0.3)
+ self.add(a, b, c)
+ ```
+ """
+ channel = "background" if background else "stroke"
+ for mob in reversed(self._each(family)):
+ paint = mob.paint.updated(channel, color, opacity)
+ if width is not None:
+ paint = (
+ paint.but(background_width=width)
+ if background
+ else paint.but(stroke_width=width)
+ )
+ mob.paint = paint
+ return self
+
+ def set_style(
+ self,
+ fill_color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
+ fill_opacity: float | Iterable[float] | None = None,
+ stroke_color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
+ stroke_width: float | None = None,
+ stroke_opacity: float | Iterable[float] | None = None,
+ background_stroke_color: (
+ ParsableManimColor | Iterable[ParsableManimColor] | None
+ ) = None,
+ background_stroke_width: float | None = None,
+ background_stroke_opacity: float | Iterable[float] | None = None,
+ sheen_factor: float | None = None,
+ sheen_direction: Vector3DLike | None = None,
+ family: bool = True,
+ ) -> Self:
+ """Set any of the mobject's style at once: what is None stays as it is.
+
+ See [set_fill][manimgx.Mobject.set_fill],
+ [set_stroke][manimgx.Mobject.set_stroke] and
+ [set_sheen][manimgx.Mobject.set_sheen]; the sheen changes only with a nonzero
+ `sheen_factor`.
+
+ Args:
+ fill_color: The fill's color; several make a gradient.
+ fill_opacity: The fill's opacity, from 0 to 1.
+ stroke_color: The stroke's color; several make a gradient.
+ stroke_width: The stroke's width, in hundredths of a scene unit.
+ stroke_opacity: The stroke's opacity, from 0 to 1.
+ background_stroke_color: The color of the outline drawn behind the fill.
+ background_stroke_width: That outline's width, in hundredths of a scene
+ unit.
+ background_stroke_opacity: That outline's opacity, from 0 to 1.
+ sheen_factor: How much the colors lighten toward `sheen_direction`, from -1
+ to 1; None or 0 leaves the sheen as it is.
+ sheen_direction: The direction they lighten toward, set with `sheen_factor`.
+ family: Whether its whole family is styled, or the mobject alone.
+ """
+ self.set_fill(fill_color, fill_opacity, family)
+ self.set_stroke(stroke_color, stroke_width, stroke_opacity, family=family)
+ self.set_stroke(
+ background_stroke_color,
+ background_stroke_width,
+ background_stroke_opacity,
+ background=True,
+ family=family,
+ )
+ if sheen_factor:
+ self.set_sheen(sheen_factor, sheen_direction, family)
+ return self
+
+ def set_material(self, material: Material | None, family: bool = True) -> Self:
+ """Give the mobject a surface the scene's lights reflect from, in a three-dimensional
+ scene: its fill color is the surface's base color.
+
+ Args:
+ material: How the surface reflects light (see [Material][manimgx.Material]); None
+ for Manim's shading.
+ family: Whether its whole family takes the material, or the mobject alone.
+
+ Returns:
+ This mobject, for chaining.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSetMaterialExample(m.ThreeDScene):
+ def construct(self) -> None:
+ self.set_camera_orientation(phi=65 * m.DEGREES, theta=-50 * m.DEGREES)
+ self.add(m.SunLight(4 * m.LEFT + 6 * m.OUT), m.AmbientLight(intensity=0.15))
+ torus = m.Torus(resolution=(48, 24)).set_color(m.TEAL)
+ self.add(torus.set_material(m.Material(roughness=0.25)))
+ self.play(torus.animate.set_material(m.Material(metallic=1, roughness=0.6)))
+ ```
+ """
+ for mob in self.get_family() if family else [self]:
+ mob.paint = mob.paint.but(material=material)
+ return self
+
+ def set_color(
+ self,
+ color: ParsableManimColor | Iterable[ParsableManimColor],
+ family: bool = True,
+ ) -> Self:
+ """Color the mobject: its fill and its stroke, which keep their opacities (an
+ unfilled shape stays unfilled).
+
+ Args:
+ color: The color; several make a gradient across the mobject, from the first
+ to the last toward its sheen direction (UL unless set).
+ family: Whether its whole family is colored, or the mobject alone.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSetColorExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=1.5)
+ square = m.Square(side_length=3, fill_opacity=0.5)
+ shapes = m.VGroup(circle, square).arrange(buff=2)
+ self.add(shapes)
+ self.play(shapes.animate.set_color(m.YELLOW))
+ self.play(square.animate.set_color([m.BLUE, m.GREEN]))
+ ```
+ """
+ self.set_fill(color, family=family)
+ return self.set_stroke(color, family=family)
+
+ def set_opacity(self, opacity: float, family: bool = True) -> Self:
+ """Set the opacity of the mobject's fill, stroke and background stroke alike —
+ so an unfilled shape gets a fill of that opacity.
+
+ Args:
+ opacity: The opacity, from 0 (invisible) to 1 (opaque).
+ family: Whether its whole family gets it, or the mobject alone.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSetOpacityExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(side_length=3, color=m.BLUE, fill_opacity=1)
+ circle = m.Circle(radius=1.5, color=m.YELLOW, fill_opacity=1)
+ square.shift(m.LEFT)
+ circle.shift(m.RIGHT)
+ self.add(square, circle)
+ self.play(circle.animate.set_opacity(0.3))
+ ```
+ """
+ self.set_fill(opacity=opacity, family=family)
+ self.set_stroke(opacity=opacity, family=family)
+ return self.set_stroke(opacity=opacity, background=True, family=family)
+
+ def fade(self, darkness: float = 0.5, family: bool = True) -> Self:
+ """Make the mobject fainter: its fill's, stroke's and background stroke's
+ opacities each times 1 − `darkness`.
+
+ Args:
+ darkness: How much fainter, from 0 (as it is) to 1 (invisible).
+ family: Whether its whole family fades, or the mobject alone.
+ """
+ factor = 1.0 - darkness
+ if factor == 1.0:
+ return self
+ for mob in self._each(family):
+ p, faded = mob.paint, {}
+ for name in ("fill", "stroke", "background"): # every row: stops, points
+ rows = getattr(p, name)
+ if len(rows):
+ faded[name] = rows * [1.0, 1.0, 1.0, factor]
+ mob.paint = p.but(**faded)
+ return self
+
+ def set_sheen(
+ self, factor: float, direction: Vector3DLike | None = None, family: bool = True
+ ) -> Self:
+ """Give the mobject a sheen: its colors lighten across it, toward a direction.
+
+ With a nonzero factor, its fill and its stroke each become a gradient from their
+ color to that color lightened by the factor.
+
+ Args:
+ factor: How much the colors lighten, from -1 to 1: 0 for no sheen, a
+ negative factor darkens.
+ direction: The direction they lighten toward, copied as a value; None
+ keeps the present one (UL unless styled). The caller's array is
+ unchanged.
+ family: Whether its whole family gets it, or the mobject alone.
+ """
+ if direction is not None:
+ direction = frozen(np.array(direction, dtype=float, copy=True))
+ for mob in self._each(family):
+ mob.paint = (
+ mob.paint.but(sheen_factor=factor)
+ if direction is None
+ else mob.paint.but(sheen_factor=factor, sheen_direction=direction)
+ )
+ if factor != 0:
+ mob.paint = mob.paint.updated("stroke", mob.get_stroke_color(), None)
+ mob.paint = mob.paint.updated("fill", mob.get_fill_color(), None)
+ return self
+
+ def set_sheen_direction(self, direction: Vector3DLike, family: bool = True) -> Self:
+ """Set the direction the mobject's colors lighten toward, which its gradients
+ run along too.
+
+ Args:
+ direction: The direction, copied as a value without changing the
+ caller's array.
+ family: Whether its whole family gets it, or the mobject alone.
+ """
+ direction = frozen(np.array(direction, dtype=float, copy=True))
+ for mob in self._each(family):
+ mob.paint = mob.paint.but(sheen_direction=direction)
+ return self
+
+ def get_stroke_rgbas(self, background: bool = False) -> np.ndarray:
+ """The mobject's own stroke colors, one row per gradient stop.
+
+ Args:
+ background: Whether to read the background stroke's instead.
+
+ Returns:
+ An (n, 4) array of red, green, blue and opacity, from 0 to 1.
+ """
+ return self.paint.background if background else self.paint.stroke
+
+ def get_fill_color(self) -> ManimColor:
+ """The mobject's own fill color (for a gradient, its first)."""
+ return ManimColor(self.paint.fill[0, :3])
+
+ def get_fill_opacity(self) -> float:
+ """The opacity of the mobject's own fill (for a gradient, its first color's).
+
+ Returns:
+ The opacity, from 0 to 1.
+ """
+ return float(self.paint.fill[0, 3])
+
+ def get_stroke_color(self, background: bool = False) -> ManimColor:
+ """The mobject's own stroke color (for a gradient, its first).
+
+ Args:
+ background: Whether to read the background stroke's instead.
+ """
+ return ManimColor(self.get_stroke_rgbas(background)[0, :3])
+
+ def get_stroke_width(self, background: bool = False) -> float:
+ """The width of the mobject's own stroke.
+
+ Args:
+ background: Whether to read the background stroke's instead.
+
+ Returns:
+ The width, in hundredths of a scene unit.
+ """
+ return max(
+ 0.0, self.paint.background_width if background else self.paint.stroke_width
+ )
+
+ def get_stroke_opacity(self, background: bool = False) -> float:
+ """The opacity of the mobject's own stroke (for a gradient, its first color's).
+
+ Args:
+ background: Whether to read the background stroke's instead.
+
+ Returns:
+ The opacity, from 0 to 1.
+ """
+ return float(self.get_stroke_rgbas(background)[0, 3])
+
+ def get_color(self) -> ManimColor:
+ """The mobject's own color: its fill's, or its stroke's if it has no fill (its
+ fill wholly transparent).
+ """
+ if np.all(self.paint.fill[:, 3] == 0):
+ return self.get_stroke_color()
+ return self.get_fill_color()
+
+ @property
+ def color(self) -> ManimColor:
+ """The mobject's own color: its fill's, or its stroke's if it has no fill. Set
+ it to color the whole family (see [set_color][manimgx.Mobject.set_color])."""
+ return self.get_color()
+
+ @color.setter
+ def color(self, value: ParsableManimColor) -> None:
+ self.set_color(value)
+
+ fill_color = property(get_fill_color, lambda self, c: self.set_fill(c))
+ """The mobject's own fill color (for a gradient, its first). Set it to fill the
+ whole family with a color (see [set_fill][manimgx.Mobject.set_fill])."""
+ stroke_color = property(get_stroke_color, lambda self, c: self.set_stroke(c))
+ """The mobject's own stroke color (for a gradient, its first). Set it to stroke the
+ whole family with a color (see [set_stroke][manimgx.Mobject.set_stroke])."""
+ fill_opacity = property(get_fill_opacity, lambda self, o: self.set_fill(opacity=o))
+ """The opacity of the mobject's own fill, from 0 to 1. Set it to set the whole
+ family's."""
+ stroke_opacity = property(
+ get_stroke_opacity, lambda self, o: self.set_stroke(opacity=o)
+ )
+ """The opacity of the mobject's own stroke, from 0 to 1. Set it to set the whole
+ family's."""
+ stroke_width = property(get_stroke_width, lambda self, w: self.set_stroke(width=w))
+ """The width of the mobject's own stroke, in hundredths of a scene unit. Set it to
+ set the whole family's."""
+
+ def match_style(self, mobject: "Mobject", family: bool = True) -> Self:
+ """Give the mobject another's style: its colors, opacities, stroke widths, sheen
+ and the rest of its look, all but how much of it a reveal shows.
+
+ Args:
+ mobject: The mobject whose style to take.
+ family: Whether the submobjects take the style of the other's too, in order:
+ paired evenly when their numbers differ, and each taking the other
+ mobject's own if it has none.
+ """
+ self.paint = mobject.paint.but(trim=self.paint.trim)
+ if family:
+ subs1, subs2 = self.submobjects, mobject.submobjects
+ if subs1:
+ subs2 = subs2 or [mobject]
+ n = max(len(subs1), len(subs2))
+ for i in range(n):
+ subs1[i * len(subs1) // n].match_style(subs2[i * len(subs2) // n])
+ return self
+
+ def match_color(self, mobject: "Mobject") -> Self:
+ """Color the mobject and its whole family with another's color (see
+ [get_color][manimgx.Mobject.get_color]).
+
+ Args:
+ mobject: The mobject whose color to take.
+ """
+ return self.set_color(mobject.get_color())
+
+ def set_color_by_gradient(self, *colors: ParsableManimColor) -> Self:
+ """Color the drawn members of the family along a gradient: in family order, each
+ one solid, from the first color to the last.
+
+ One color colors them all; none raises an exception.
+
+ Args:
+ *colors: The colors the gradient runs through, evenly.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectSetColorByGradientExample(m.Scene):
+ def construct(self) -> None:
+ dots = m.VGroup(*(m.Dot(radius=0.35) for _ in range(9)))
+ dots.arrange(buff=0.5)
+ dots.set_color_by_gradient(m.BLUE, m.GREEN, m.YELLOW)
+ word = m.Text("gradient", font_size=120)
+ word.set_color_by_gradient(m.RED, m.YELLOW)
+ self.add(m.VGroup(dots, word).arrange(m.DOWN, buff=1))
+ ```
+ """
+ return self.set_submobject_colors_by_gradient(*colors)
+
+ def set_submobject_colors_by_radial_gradient(
+ self,
+ center: Point3DLike | None = None,
+ radius: float = 1,
+ inner_color: ParsableManimColor = WHITE,
+ outer_color: ParsableManimColor = "#000000",
+ ) -> Self:
+ """Color the drawn members of the family by how far their centers are from a
+ point: `inner_color` there, blending to `outer_color` at `radius` and beyond;
+ each member one solid color.
+
+ Args:
+ center: The point; None for the mobject's center.
+ radius: The distance at which the color is `outer_color`, in scene units.
+ inner_color: The color at the point.
+ outer_color: The color at `radius` and beyond.
+ """
+ c = self.get_center() if center is None else np.asarray(center)
+ for mob in self.family_members_with_points():
+ t = min(float(np.linalg.norm(mob.get_center() - c)) / radius, 1.0)
+ mob.set_color(
+ interpolate_color(ManimColor(inner_color), ManimColor(outer_color), t),
+ family=False,
+ )
+ return self
+
+ def sort_submobjects(
+ self,
+ point_to_num_func: Callable[[Point3D], float] = lambda p: p[0],
+ submob_func: "Callable[[Mobject], float] | None" = None,
+ ) -> Self:
+ """Sort the submobjects by a number: the same as [sort][manimgx.Mobject.sort].
+
+ Args:
+ point_to_num_func: A function of a submobject's center, giving the number to
+ sort it by (default: its x coordinate).
+ submob_func: A function of a submobject, giving the number to sort it by, in
+ place of `point_to_num_func`.
+ """
+ return self.sort(point_to_num_func, submob_func)
+
+ def to_original_color(self) -> Self:
+ """Color the whole family with the mobject's own [color][manimgx.Mobject.color]."""
+ return self.set_color(self.color)
+
+ def apply_to_family(self, func: Callable[["Mobject"], object]) -> None:
+ """Call a function on each drawn member of the family, in family order.
+
+ Args:
+ func: A function of a mobject; what it returns is ignored.
+ """
+ for mob in self.family_members_with_points():
+ func(mob)
+
+ def set_submobject_colors_by_gradient(self, *colors: ParsableManimColor) -> Self:
+ """Color the drawn members of the family along a gradient: the same as
+ [set_color_by_gradient][manimgx.Mobject.set_color_by_gradient].
+
+ Args:
+ *colors: The colors the gradient runs through, evenly.
+ """
+ if len(colors) == 0:
+ raise ValueError("Need at least one color")
+ if len(colors) == 1:
+ return self.set_color(colors[0])
+ mobs = self.family_members_with_points()
+ for mob, color in zip(mobs, color_gradient(colors, len(mobs)), strict=True):
+ mob.set_color(color, family=False)
+ return self
+
+ def set_colors_by_radial_gradient(
+ self,
+ center: Point3DLike | None = None,
+ radius: float = 1,
+ inner_color: ParsableManimColor = WHITE,
+ outer_color: ParsableManimColor = "#000000",
+ ) -> Self:
+ """Color the mobject by distance from a point: `inner_color` there, blending to
+ `outer_color` at `radius` and beyond.
+
+ Each drawn member of the family is one solid color, by its center's distance.
+
+ Args:
+ center: The point; None for the mobject's center.
+ radius: The distance at which the color is `outer_color`, in scene units.
+ inner_color: The color at the point.
+ outer_color: The color at `radius` and beyond.
+ """
+ c = self.get_center() if center is None else np.asarray(center)
+ for mob in self.family_members_with_points():
+ t = min(float(np.linalg.norm(mob.get_center() - c)) / radius, 1)
+ mob.set_color(
+ interpolate_color(ManimColor(inner_color), ManimColor(outer_color), t),
+ family=False,
+ )
+ return self
+
+ def fade_to(
+ self, color: ParsableManimColor, alpha: float, family: bool = True
+ ) -> Self:
+ """Blend the mobject's color toward another: each drawn member's own color,
+ mixed `alpha` of the way to `color`.
+
+ Args:
+ color: The color to blend toward.
+ alpha: How far, from 0 (as it is) to 1 (`color`).
+ family: Whether its whole family blends, or the mobject alone.
+ """
+ if self.has_points():
+ self.set_color(
+ interpolate_color(self.get_color(), ManimColor(color), alpha),
+ family=False,
+ )
+ if family:
+ for sub in self.submobjects:
+ sub.fade_to(color, alpha)
+ return self
+
+ # ── structural alignment + interpolation (the Transform engine) ─────────
+ def align_data(
+ self, mobject: "Mobject", skip_point_alignment: bool = False
+ ) -> Self:
+ """Give this mobject's family and another's the same structure, so the two can
+ be blended member by member: the same number of members, level by level, and,
+ unless skipped, the same number of points in each pair.
+
+ A transform calls it on its keyframes; both mobjects change, but neither's look
+ does.
+
+ Args:
+ mobject: The other mobject.
+ skip_point_alignment: Whether to leave the numbers of points as they are
+ ([become][manimgx.Mobject.become] does: it takes the other's points as
+ they are).
+ """
+ self.null_point_align(mobject)
+ self.align_submobjects(mobject)
+ if not skip_point_alignment:
+ self.align_points(mobject)
+ for m1, m2 in zip(self.submobjects, mobject.submobjects, strict=True):
+ m1.align_data(m2, skip_point_alignment)
+ return self
+
+ def align_points(self, mobject: "Mobject") -> Self:
+ """Give this mobject and another the same number of points of their own, and of
+ color rows: the one with fewer is refined, its shape and look unchanged (see
+ [align_points_with_larger][manimgx.Mobject.align_points_with_larger]).
+
+ Args:
+ mobject: The other mobject.
+ """
+ self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
+ n1, n2 = self.get_num_points(), mobject.get_num_points()
+ if n1 < n2:
+ self.align_points_with_larger(mobject)
+ elif n2 < n1:
+ mobject.align_points_with_larger(self)
+ return self
+
+ def align_submobjects(self, mobject: "Mobject") -> Self:
+ """Give this mobject and another the same number of submobjects.
+
+ The one with fewer repeats its own (see
+ [add_n_more_submobjects][manimgx.Mobject.add_n_more_submobjects]); one with none
+ grows, at its center, the point of each of the other's — of that one's kind and
+ style, so what appears from nothing appears as itself.
+
+ Args:
+ mobject: The other mobject.
+ """
+ # (CE's VGroup lent a grown point the group's own, never-drawn style)
+ for a, b in ((self, mobject), (mobject, self)):
+ if not a.submobjects and b.submobjects:
+ center = a.get_center()
+ a.submobjects = [m.get_point_mobject(center) for m in b.submobjects]
+ else:
+ a.add_n_more_submobjects(
+ max(0, len(b.submobjects) - len(a.submobjects))
+ )
+ return self
+
+ def null_point_align(self, mobject: "Mobject") -> Self:
+ """If one of this mobject and another has no points of its own and the other
+ has, move the other's points into a submobject of its own, so the two families
+ line up (see
+ [push_self_into_submobjects][manimgx.Mobject.push_self_into_submobjects]).
+
+ Args:
+ mobject: The other mobject.
+ """
+ for m1, m2 in ((self, mobject), (mobject, self)):
+ if m1.has_no_points() and m2.has_points():
+ m2.push_self_into_submobjects()
+ return self
+
+ def push_self_into_submobjects(self) -> Self:
+ """Move the mobject's own points into a new submobject, added last: a copy of it
+ without submobjects. The mobject keeps its submobjects, and has no points of its
+ own.
+ """
+ clone = self.copy()
+ clone.submobjects = []
+ self.reset_points()
+ return self.add(clone)
+
+ def add_n_more_submobjects(self, n: int) -> Self:
+ """Add `n` submobjects, for a transform that splits parts: a mobject with none
+ gets `n` points of itself, at its center (see
+ [get_point_mobject][manimgx.Mobject.get_point_mobject]); otherwise each
+ submobject is followed by invisible copies of itself, spread as evenly as can
+ be.
+
+ Args:
+ n: How many to add.
+ """
+ if n == 0:
+ return self
+ cur = len(self.submobjects)
+ if cur == 0:
+ self.submobjects = [self.get_point_mobject() for _ in range(n)]
+ return self
+ target = cur + n
+ # Count the integer indices in each child's interval.
+ split = [
+ int(((i + 1) * target + cur - 1) // cur - (i * target + cur - 1) // cur)
+ for i in range(cur)
+ ]
+ new: list[Mobject] = []
+ for sub, sf in zip(self.submobjects, split, strict=True):
+ new.append(sub)
+ new.extend(sub.copy().fade(1) for _ in range(1, sf))
+ self.submobjects = new
+ return self
+
+ def interpolate(
+ self,
+ mobject1: "Mobject",
+ mobject2: "Mobject",
+ alpha: float,
+ path_func: PathFunc = _STRAIGHT,
+ ) -> Self:
+ """Make the mobject a blend of two others: `mobject1` at 0, `mobject2` at 1.
+
+ Its own points go from the first's to the second's along `path_func`, and its
+ style blends from the first's to the second's; its submobjects are left as they
+ are. A transform calls it on each drawn member, with its aligned keyframes (see
+ [align_data][manimgx.Mobject.align_data]), which have as many points as each
+ other.
+
+ Args:
+ mobject1: The mobject it is at 0.
+ mobject2: The mobject it is at 1.
+ alpha: How far from the first to the second, from 0 to 1.
+ path_func: The path each point takes (default: straight).
+ """
+ g1, g2 = mobject1._geometry, mobject2._geometry
+ if (
+ isinstance(path_func, Path) and g1.n == g2.n
+ ): # a linear path moves shapes, not points
+ self._geometry = Blend.mix(g1, g2, path_func.coefficients(alpha))
+ else:
+ self.points = path_func(mobject1.points, mobject2.points, alpha)
+ self.paint = self.paint.mixed(mobject1.paint, mobject2.paint, alpha)
+ return self
+
+ def interpolate_color(
+ self, mobject1: "Mobject", mobject2: "Mobject", alpha: float
+ ) -> Self:
+ """Make the mobject's own style a blend of two others': `mobject1`'s at 0,
+ `mobject2`'s at 1; its points stay.
+
+ Args:
+ mobject1: The mobject whose style it has at 0.
+ mobject2: The mobject whose style it has at 1.
+ alpha: How far from the first to the second, from 0 to 1.
+ """
+ self.paint = self.paint.mixed(mobject1.paint, mobject2.paint, alpha)
+ return self
+
+ def become(
+ self,
+ mobject: "Mobject",
+ match_height: bool = False,
+ match_width: bool = False,
+ match_depth: bool = False,
+ match_center: bool = False,
+ stretch: bool = False,
+ ) -> Self:
+ """Make the mobject look like another, at once, while staying itself: the same
+ object in the scene, with its updaters.
+
+ The two families are first given the same structure (see
+ [align_data][manimgx.Mobject.align_data]); then each member takes its
+ counterpart's points and its colors, opacities, stroke widths, sheen and
+ texture (its joint and cap styles and 3D shading stay its own, unless they are
+ the same). With a `match_*` flag or `stretch`, a copy of `mobject` is first
+ fitted to this mobject.
+
+ Args:
+ mobject: The mobject to look like.
+ match_height: Whether the copy is first scaled, in proportion, to this
+ mobject's height.
+ match_width: Whether it is first scaled to this mobject's width.
+ match_depth: Whether it is first scaled to this mobject's depth.
+ match_center: Whether it is first moved to this mobject's center.
+ stretch: Whether it is first stretched to this mobject's width, height and
+ depth, in place of the `match_*` scalings.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectBecomeExample(m.Scene):
+ def construct(self) -> None:
+ shape = m.Circle(radius=2, color=m.RED, fill_opacity=0.8)
+ shape.add_updater(lambda mob, dt: mob.rotate(dt))
+ self.add(shape)
+ self.wait()
+ square = m.Square(side_length=4, color=m.BLUE, fill_opacity=0.8)
+ shape.become(square)
+ self.wait(2) # the same mobject: its updater still turns it
+ ```
+ """
+ if stretch or match_height or match_width or match_depth or match_center:
+ mobject = mobject.copy()
+ for dim, match in ((1, match_height), (0, match_width), (2, match_depth)):
+ if stretch or match:
+ mobject.rescale_to_fit(self.length_over_dim(dim), dim, stretch)
+ if match_center:
+ mobject.move_to(self.get_center())
+ self.align_data(mobject, skip_point_alignment=True)
+ for sm1, sm2 in zip(self.get_family(), mobject.get_family(), strict=True):
+ sm1._geometry = sm2._geometry # immutable: shared, not copied
+ sm1._take_shape(sm2)
+ a, b = sm1.paint, sm2.paint
+ # (the rest — colors, widths, windows, dashes — `mixed` takes from b at 1); a
+ # picture is what the mobject shows, so it becomes b's too (a texture is an array
+ # or a camera: compared by identity)
+ same = (a.joint, a.cap, a.shade_in_3d) == (b.joint, b.cap, b.shade_in_3d)
+ sm1.paint = ( # a value: shared, not copied
+ b
+ if same and a.texture is b.texture
+ else a.mixed(a, b, 1).but(texture=b.texture)
+ )
+ return self
+
+ def match_points(self, mobject: "Mobject") -> Self:
+ """Take another mobject's shape: its points, member by member in family order;
+ this mobject's style stays its own.
+
+ Members past the end of the shorter family stay as they are.
+
+ Args:
+ mobject: The mobject whose shape to take.
+ """
+ for sm1, sm2 in zip(self.get_family(), mobject.get_family(), strict=False):
+ sm1._geometry = sm2._geometry
+ sm1._take_shape(sm2)
+ return self
+
+ def _take_shape(self, mobject: "Mobject") -> None:
+ """What goes with another mobject's points when this one takes them (a kind whose
+ shape is more than points — a mesh's triangles — takes that too)."""
+
+ @classmethod
+ def add_animation_override(
+ cls,
+ animation_class: type["Animation"],
+ override_func: Callable[..., "Animation"],
+ ) -> None:
+ """Make the class play another animation in place of one: playing
+ `animation_class(mobject, …)` on a mobject of the class plays what
+ `override_func` returns instead.
+
+ [override_animation][manimgx.override_animation] does this for a method of the
+ class. Overriding one animation twice raises an exception.
+
+ Args:
+ animation_class: The animation to play another in place of.
+ override_func: A function of the mobject, then the animation's other
+ arguments and keywords, that returns the animation to play.
+ """
+ if animation_class in cls.animation_overrides:
+ raise Exception(
+ f"The animation {animation_class.__name__} for {cls.__name__} is"
+ " overridden by more than one method"
+ )
+ cls.animation_overrides = cls.animation_overrides | {
+ animation_class: override_func
+ }
+
+ @classmethod
+ def set_default(cls, **kwargs: object) -> None:
+ """Change the defaults of the class's constructor keywords, for every mobject of
+ the class made from then on; with none given, restore them.
+
+ After `Text.set_default(font_size=100)`, a `Text` is 100 points unless it is
+ made with another size. The keywords are checked when a mobject is made.
+
+ Changing or restoring defaults discards remembered constructions. Existing
+ mobjects keep their state; later construction reads the current defaults.
+
+ Repeated calls replace this class's keyword defaults. Reset restores its
+ original constructor descriptor, or normal inheritance if it had no
+ constructor of its own. A new override uses the current inherited defaults.
+
+ Args:
+ **kwargs: Keywords of the class's constructor, with their new defaults.
+ """
+ # The constructor checks the keywords when it runs: a partial
+ # application of a signature has no static type
+ from functools import partialmethod
+
+ if kwargs:
+ configured = "_original__init__" in cls.__dict__
+ original = cls.__dict__.get(
+ "_original__init__", cls.__dict__.get("__init__")
+ )
+ init = original
+ if original is None and (configured or "__init__" not in cls.__dict__):
+ init = super(cls, cls).__init__
+ init = partialmethod(init, **kwargs)
+ setattr(cls, "_original__init__", original) # noqa: B010
+ setattr(cls, "__init__", init) # noqa: B010
+ elif "_original__init__" in cls.__dict__:
+ original = cls.__dict__["_original__init__"]
+ delattr(cls, "_original__init__")
+ if original is None:
+ delattr(cls, "__init__")
+ else:
+ setattr(cls, "__init__", original) # noqa: B010
+ caches.clear()
+
+ def get_pieces(self, n_pieces: int) -> "Group":
+ """Split the mobject into pieces: copies of it, each an equal part of it in
+ turn, from its start to its end (a path's, by its curves).
+
+ Only the mobject's own points are split; its submobjects are left out.
+
+ Args:
+ n_pieces: How many pieces.
+
+ Returns:
+ A new group of the pieces, in order.
+ """
+ template = self.copy()
+ template.submobjects = []
+ alphas = np.linspace(0, 1, n_pieces + 1)
+ return Group(
+ *(
+ template.copy().pointwise_become_partial(self, a1, a2)
+ for a1, a2 in it.pairwise(alphas)
+ )
+ )
+
+ # ── animation hooks ───────────────────────────────────────────────────
+ @property
+ def animate(self) -> "Animate[Self]":
+ """An animation of the mobject, built from the method calls made on it.
+
+ `square.animate.shift(RIGHT).scale(2)` is an animation that moves the square
+ right and doubles its size: pass it to [Scene.play][manimgx.Scene.play]. Each
+ call is recorded — and tried at once on a copy, so a wrong call fails where it
+ is written — and returns the animation, so calls chain. The calls are carried
+ out on the mobject as it is when the animation begins, and the animation tweens
+ it from that state to the result: in
+ `Succession(square.animate.shift(RIGHT), square.animate.rotate(PI / 2))`, the
+ square turns about its center where the shift left it. When the animation
+ finishes, the calls are carried out on the mobject itself.
+
+ The motion follows the calls: a turn among them (`rotate`, `flip`,
+ `rotate_about_origin`) turns the mobject rigidly about its pivot, through its
+ whole angle (`rotate(TAU)` is a full turn); every other call moves its center
+ straight; and the rest of the change (a size, a color, a new shape) blends along
+ the way. Call `animate` with options before any method —
+ `square.animate(run_time=2, rate_func=linear).shift(UP)` — to set the
+ animation's [Transform options][manimgx.animation.transform.TransformOptions]; a
+ `path_arc` or a `path_func` among them replaces the motion. Call it with a
+ function — `square.animate(lambda s: s.shift(UP))` — to record that function as
+ a call. A method decorated with [override_animate][manimgx.override_animate]
+ plays the animation it makes instead, and cannot be chained.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectAnimateExample(m.Scene):
+ def construct(self) -> None:
+ triangle = m.Triangle(color=m.BLUE, fill_opacity=0.5)
+ self.add(triangle)
+ self.play(triangle.animate.shift(3 * m.LEFT).scale(1.5))
+ self.play(triangle.animate.rotate(m.PI).set_color(m.YELLOW))
+ self.play(triangle.animate(path_arc=m.PI).move_to(3 * m.RIGHT))
+ ```
+ """
+ from manimgx.animation.transform import Animate
+
+ return Animate(self)
+
+ @classmethod
+ def animation_override_for(
+ cls, animation_class: type["Animation"]
+ ) -> Callable[..., "Animation"] | None:
+ """The function that makes the animation the class plays in place of
+ `animation_class` (see [override_animation][manimgx.override_animation]).
+
+ An animation asks, when it is played.
+
+ Returns:
+ The function; None if the class plays `animation_class` itself.
+ """
+ return cls.animation_overrides.get(animation_class)
+
+ def set(self, **kwargs: object) -> Self:
+ """Set attributes of the mobject by name: its properties, such as `width`,
+ `height` or `color` (or a text's `font_size`), or any other attribute.
+
+ Through [animate][manimgx.Mobject.animate] it animates the change:
+ `mobject.animate.set(width=4)`.
+
+ Args:
+ **kwargs: The attributes' names, with their values.
+ """
+ # CE's
+ for attr, value in kwargs.items():
+ setattr(self, attr, value)
+ return self
+
+ def __repr__(self) -> str:
+ return str(self.name)
+
+
+def _members(items: Iterable[Mobject | Iterable[Mobject]]) -> list[Mobject]:
+ """Mobjects and iterables of mobjects, flattened one level."""
+ flat: list[Mobject] = []
+ for i, m in enumerate(items):
+ if isinstance(m, Mobject):
+ flat.append(m)
+ elif isinstance(m, Iterable):
+ flat.extend(m)
+ else:
+ raise TypeError(
+ f"Only mobjects can be grouped, got {type(m).__name__} at index {i}"
+ )
+ return flat
+
+
+class Group[T: Mobject = Mobject](Mobject):
+ """Mobjects together, of any kinds: paths, text, images, point clouds, other groups.
+
+ A group has no points of its own: its members are its submobjects, and whatever is
+ done to the group — moving, scaling, styling, animating — is done to them all.
+ [VGroup][manimgx.VGroup] and [PGroup][manimgx.PGroup] are other names for it. A
+ group can be indexed (`group[0]`), sliced (`group[1:3]` is a new group of those
+ members) and iterated over, and `group + mobject`, `group - mobject`, `+=` and `-=`
+ add and remove members.
+
+ Its member type is inferred from what it is made with; a group meant to hold several
+ kinds says so once, as `Group[Mobject](…)`, and `Group[Integer](…)` holds integers
+ only, so `group[0]` is an [Integer][manimgx.Integer] to a type checker.
+
+ Args:
+ *mobjects: The members, in drawing order: mobjects, or iterables of mobjects
+ (each of their mobjects a member).
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself: as it
+ has no points, they do not restyle its members (the style methods do).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class GroupExample(m.Scene):
+ def construct(self) -> None:
+ shapes = m.Group(
+ m.Circle(color=m.BLUE), m.Square(color=m.GREEN), m.Triangle()
+ ).arrange(buff=1)
+ self.play(m.Create(shapes))
+ self.play(shapes.animate.scale(1.5).set_fill(opacity=0.5))
+ self.play(shapes[1].animate.shift(m.UP))
+ ```
+ """
+
+ # a kind (path, points, mesh) belongs to a leaf, never to a container — so CE's
+ # Group, VGroup and PGroup are this one class
+
+ # a Group[T] only ever adds T
+ submobjects: list[T] # pyright: ignore[reportIncompatibleVariableOverride]
+ """The group's members, in drawing order."""
+
+ @overload # `Group(a, b)`: members of any kinds
+ def __init__(
+ self: "Group[Mobject]",
+ *mobjects: Mobject | Iterable[Mobject],
+ **kwargs: Unpack[Style],
+ ) -> None: ...
+ @overload # `Group[Integer](a, b)`: declared, so checked on the way in and precise on the way out
+ def __init__(self, *mobjects: T | Iterable[T], **kwargs: Unpack[Style]) -> None: ...
+ def __init__(
+ self, *mobjects: Mobject | Iterable[Mobject], **kwargs: Unpack[Style]
+ ) -> None:
+ super().__init__(**kwargs)
+ Mobject.add(self, *_members(mobjects))
+
+ def add( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # a Group[T] adds T
+ self, *mobjects: T | Iterable[T]
+ ) -> Self:
+ """Add members after the ones the group has: mobjects, or iterables of mobjects
+ (each of their mobjects a member).
+
+ A member already in the group moves to the end. Adding anything but mobjects, or
+ the group to itself, raises an exception.
+
+ Args:
+ *mobjects: The members to add, in order.
+ """
+ return super().add(*_members(mobjects))
+
+ def __iter__(self) -> Iterator[T]:
+ return iter(self.submobjects)
+
+ @overload
+ def __getitem__(self, value: int) -> T: ...
+ @overload
+ def __getitem__(self, value: slice) -> "Group[T]": ...
+ def __getitem__(self, value: int | slice) -> "T | Group[T]":
+ if isinstance(value, slice):
+ return self._group(self.submobjects[value])
+ return self.submobjects[value]
+
+ def __add__(self, mobject: T) -> "Group[T]":
+ return self._group([*self.submobjects, mobject])
+
+ def __iadd__(self, mobject: T) -> Self:
+ return self.add(mobject)
+
+ def __sub__(self, mobject: T) -> "Group[T]":
+ rest = self._group(self.submobjects)
+ rest.remove(mobject)
+ return rest
+
+ def __isub__(self, mobject: T) -> Self:
+ return self.remove(mobject)
+
+ def _group(self, members: Iterable[T]) -> "Group[T]":
+ """A plain group of members of this group's type (`Group(…)` alone would say Mobject)."""
+ return cast("Group[T]", Group(*members))
+
+
+def override_animate[F: Callable[..., "Animation"]](
+ method: Callable[..., object],
+) -> Callable[[F], F]:
+ """Decorate a mobject class's method that makes the animation to play when another
+ method is called through [animate][manimgx.Mobject.animate].
+
+ Then `mobject.animate.method(*args, **kwargs)` is the animation the decorated method
+ returns, called with the mobject, the same arguments, and `anim_args`: the options
+ given to `animate(...)` (an empty dict if none). It is made when the call is
+ written, and cannot be chained with other calls.
+
+ Args:
+ method: The method whose `animate` call plays the decorated method's animation.
+
+ Returns:
+ The decorator, which returns the decorated method as it is.
+
+ Examples:
+ ```python
+ import manimgx as m
+ from manimgx.animation.motion import TransformOptions
+
+
+ class Tally(m.VGroup):
+ def add_mark(self) -> "Tally":
+ mark = m.Line(1.5 * m.UP, 1.5 * m.DOWN, stroke_width=12)
+ return self.add(mark.shift(0.7 * (len(self) - 2) * m.RIGHT))
+
+ @m.override_animate(add_mark)
+ def _add_mark_animation(self, anim_args: TransformOptions) -> m.Animation:
+ self.add_mark()
+ return m.GrowFromCenter(self[-1], **anim_args)
+
+
+ class OverrideAnimateExample(m.Scene):
+ def construct(self) -> None:
+ tally = Tally().add_mark()
+ self.add(tally)
+ for _ in range(4):
+ self.play(tally.animate(run_time=0.5).add_mark())
+ ```
+ """
+ # CE's decorator
+
+ def decorator(animation_method: F) -> F:
+ _animate_plays[method] = animation_method
+ return animation_method
+
+ return decorator
+
+
+def override_animation[F: Callable[..., "Animation"]](
+ animation_class: type["Animation"],
+) -> Callable[[F], F]:
+ """Decorate a mobject class's method that makes the animation to play in place of
+ `animation_class`.
+
+ Then playing `animation_class(mobject, *args, **kwargs)` on a mobject of the class,
+ or of a subclass, plays what the decorated method returns, called with the mobject
+ and the same arguments. An animation made with `use_override=False` plays itself.
+
+ Args:
+ animation_class: The animation to play another in place of.
+
+ Returns:
+ The decorator, which returns the decorated method as it is.
+
+ Examples:
+ ```python
+ from typing import Unpack
+
+ import manimgx as m
+ from manimgx.animation.timeline import AnimationOptions
+
+
+ class DrawnSquare(m.Square):
+ @m.override_animation(m.FadeIn)
+ def _fade_in(self, **kwargs: Unpack[AnimationOptions]) -> m.Animation:
+ return m.Create(self, **kwargs)
+
+
+ class OverrideAnimationExample(m.Scene):
+ def construct(self) -> None:
+ square = DrawnSquare(side_length=4, color=m.BLUE, fill_opacity=0.5)
+ self.play(m.FadeIn(square, run_time=2)) # drawn, not faded in
+ ```
+ """
+ # CE's decorator
+
+ def decorator(func: F) -> F:
+ _plays_instead[func] = animation_class
+ return func
+
+ return decorator
+
+
+class ValueTracker[V: (float, complex) = float](Mobject):
+ """A number that animations can change and updaters can read.
+
+ The number is kept as the x coordinate of the tracker's one point, so whatever moves
+ a mobject changes it: `tracker.animate.set_value(5)` takes it to 5 at the pace of
+ the animation's rate function, and the updaters of other mobjects read it with
+ [`get_value`][manimgx.ValueTracker.get_value]. A tracker is never drawn; add it to
+ the scene only if it has updaters of its own. `tracker += 1` and `tracker -= 1`
+ change the number at once.
+
+ Args:
+ value: The number it starts with.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style], as any mobject takes (a
+ tracker is not drawn).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ValueTrackerExample(m.Scene):
+ def construct(self) -> None:
+ x = m.ValueTracker(-4)
+ line = m.NumberLine(x_range=(-6, 6, 1), length=12).add_numbers()
+ pointer = m.Vector(1.5 * m.DOWN, color=m.YELLOW)
+ pointer.add_updater(lambda p: p.next_to(line.n2p(x.get_value()), m.UP))
+ label = m.MathTex("x", font_size=72, color=m.YELLOW)
+ label.add_updater(lambda t: t.next_to(pointer, m.UP))
+ self.add(line, pointer, label)
+ self.play(x.animate.set_value(5), run_time=2)
+ x -= 3
+ self.wait(0.5)
+ self.play(x.animate.increment_value(-5))
+ ```
+ """
+
+ def __init__(self, value: V = 0, **kwargs: Unpack[Style]) -> None:
+ super().__init__(**kwargs)
+ self.points = np.zeros((1, 3))
+ self.set_value(value)
+
+ def get_value(self) -> V:
+ """The number the tracker holds."""
+ return float(
+ self.points[0, 0]
+ ) # pyright: ignore[reportReturnType] # V is float here
+
+ def set_value(self, value: V) -> Self:
+ """Set the number the tracker holds; through
+ [`animate`][manimgx.Mobject.animate], animate it there.
+
+ Args:
+ value: The new number.
+ """
+ points = np.array(self.points)
+ points[0, 0] = value
+ self.points = points
+ return self
+
+ def increment_value(self, d_value: V) -> Self:
+ """Add to the number the tracker holds; through
+ [`animate`][manimgx.Mobject.animate], animate the change.
+
+ Args:
+ d_value: The amount to add; a negative one subtracts.
+ """
+ return self.set_value(self.get_value() + d_value)
+
+ def __iadd__(self, d_value: V) -> Self:
+ return self.increment_value(d_value)
+
+ def __isub__(self, d_value: V) -> Self:
+ return self.increment_value(-d_value)
+
+
+class ComplexValueTracker(ValueTracker[complex]):
+ """A complex number that animations can change and updaters can read.
+
+ The number is kept as the tracker's one point, its real part as x and its imaginary
+ part as y, so an animation takes it along a straight line of the complex plane:
+ `tracker.animate.set_value(3 + 2j)`. `+=` and `-=` change it at once, in complex
+ arithmetic.
+
+ Args:
+ value: The number it starts with.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style], as any mobject takes (a
+ tracker is not drawn).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ComplexValueTrackerExample(m.Scene):
+ def construct(self) -> None:
+ plane = m.ComplexPlane().add_coordinates()
+ z = m.ComplexValueTracker(2 + 1j)
+ dot = m.Dot(radius=0.15, color=m.YELLOW)
+ dot.add_updater(lambda d: d.move_to(plane.n2p(z.get_value())))
+ self.add(plane, dot)
+ self.play(z.animate.set_value(-3 + 2j))
+ self.play(z.animate.set_value(z.get_value() * 1j))
+ self.play(z.animate.set_value(z.get_value() / (1 + 1j)))
+ ```
+ """
+
+ def get_value(self) -> complex:
+ """The complex number the tracker holds."""
+ return complex(*self.points[0, :2])
+
+ def set_value(self, value: complex) -> Self:
+ """Set the complex number the tracker holds; through
+ [`animate`][manimgx.Mobject.animate], animate it there, in a straight line.
+
+ Args:
+ value: The new number; a real one is taken as complex.
+ """
+ z = complex(value)
+ points = np.array(self.points)
+ points[0, :2] = (z.real, z.imag)
+ self.points = points
+ return self
+
+
+_T_VALUES = np.linspace(0, 1, _NPPCC)
+_IMAGE_TOLERANCE = 1e-3
+"""How far a curve's image may stray from the true image of the curve at a third and two
+thirds of each piece (scene units): a quarter of a pixel at 4K."""
+_IMAGE_MAX_DEPTH = 8
+"""At most 2**8 pieces per curve for an image (a map that blows up somewhere stops there)."""
+_CHECKS = np.array([1 / 3, 2 / 3])[:, None]
+# where an image is checked, in each piece: the middle alone passes an image that strays both
+# ways about it (a wave, a curve of no handles); with its ends, two points inside pin a cubic
+_AT_CHECKS = np.hstack(
+ [
+ (1 - _CHECKS) ** 3,
+ 3 * (1 - _CHECKS) ** 2 * _CHECKS,
+ 3 * (1 - _CHECKS) * _CHECKS**2,
+ _CHECKS**3,
+ ]
+)
+
+
+def _checked(curves: np.ndarray) -> np.ndarray:
+ """Each cubic's points at a third and two thirds of its parameter: (curves, 2, dim)."""
+ return np.einsum("tk,ckd->ctd", _AT_CHECKS, curves)
+
+
+class VMobject(Mobject):
+ """A path: cubic Bézier curves, stroked in white and unfilled unless styled.
+
+ Each curve has four control points: it starts at an anchor, bends toward two handles
+ and ends at the next anchor. The path's [points][manimgx.Mobject.points] are its
+ curves' control points, four by four, and a new subpath starts wherever a curve does
+ not begin where the one before it ends. The stroke follows the curves; the fill
+ closes each subpath with a straight line back to its start, and where subpaths
+ overlap, a point is filled unless their windings around it cancel: a subpath inside
+ another that runs the other way cuts a hole.
+
+ Circles, polygons, text and graphs are all paths. A plain `VMobject` has no points
+ until it is given a shape: set its points as corners, or start it at a point and add
+ lines and curves.
+
+ Args:
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectExample(m.Scene):
+ def construct(self) -> None:
+ path = m.VMobject(color=m.BLUE, fill_opacity=0.5, stroke_width=8)
+ path.set_points_as_corners([[-3, -2, 0], [-3, 2, 0], [0, 2, 0]])
+ path.add_cubic_bezier_curve_to([3, 2, 0], [3, -2, 0], [0, -2, 0])
+ path.close_path()
+ self.play(m.Create(path, run_time=2))
+ ```
+ """
+
+ _curves = True # a path: its box is its curves' tight box
+ # CE's per-instance options, which no scene sets: constants a subclass may override.
+ pre_function_handle_to_anchor_scale_factor: float = 0.01
+ """Where along each handle [apply_function][manimgx.Mobject.apply_function] samples
+ the function, as a fraction of the handle's length (default 0.01): the handle then
+ follows how the function stretches the path at its anchor, so the curves stay
+ smooth."""
+ make_smooth_after_applying_functions: bool = False
+ """Whether [apply_function][manimgx.Mobject.apply_function] makes the path smooth
+ after mapping its curves (default False; see
+ [make_smooth][manimgx.VMobject.make_smooth])."""
+ tolerance_for_point_equality: float = 1e-6
+ """How far apart, in scene units, two points of the path may be and still count as
+ one, where a subpath ends and whether the path is closed (default 1e-6, plus 1e-5 of
+ their coordinates)."""
+
+ @property
+ def n_points_per_curve(self) -> int:
+ """The number of control points of each of the path's curves: 4."""
+ return _NPPCC
+
+ def set_cap_style(self, cap_style: CapStyleType) -> Self:
+ """Set how the strokes of the path and its family end, at each end they show:
+ an open path's ends, a reveal's moving end, each dash's ends.
+
+ A two-dimensional scene draws the caps; a three-dimensional scene ends every
+ stroke flat (see [CapStyleType][manimgx.CapStyleType]).
+
+ Args:
+ cap_style: The cap: round, butt or square.
+ """
+ for mob in self.get_family():
+ mob.paint = mob.paint.but(cap=cap_style)
+ return self
+
+ def set_shade_in_3d(
+ self, value: bool = True, z_index_as_group: bool = False
+ ) -> Self:
+ """Set whether a three-dimensional scene's light shades the path and its family.
+
+ Args:
+ value: Whether the light shades them.
+ z_index_as_group: Whether each member of the family also takes the path as
+ its [z_index_group][manimgx.Mobject.z_index_group], which is kept for
+ Manim compatibility (the renderer draws a three-dimensional scene by
+ depth).
+ """
+ for mob in self.get_family():
+ mob.paint = mob.paint.but(shade_in_3d=value)
+ if z_index_as_group:
+ mob.z_index_group = self
+ return self
+
+ def get_sheen_direction(self) -> np.ndarray:
+ """The direction the path's own colors lighten toward, which its gradients run
+ along too (see [set_sheen][manimgx.Mobject.set_sheen]).
+
+ Returns:
+ A copy of the direction.
+ """
+ return np.array(self.paint.sheen_direction)
+
+ gradient_frame: Mobject | None = None
+ """The mobject whose bounding box the path's color gradients span; None for the
+ path's own. Parts that share one show a single gradient across them all."""
+
+ def get_gradient_start_and_end_points(self) -> tuple[Point3D, Point3D]:
+ """Where the path's color gradients start and end: a gradient spans its
+ [bounding box][manimgx.Mobject.boundary_box], along its sheen direction.
+
+ They are the box's center, less and plus the sheen direction scaled by half the
+ box's size along each axis: with the default direction, [UL][manimgx.UL], the
+ box's lower right and upper left corners. The box is the
+ [gradient_frame][manimgx.VMobject.gradient_frame]'s, if the path has one. The
+ renderer reads them for a path whose fill or stroke has several colors.
+
+ Returns:
+ The start and the end, in scene coordinates; the origin twice if the box has
+ no points.
+ """
+ box = (self.gradient_frame or self).boundary_box()
+ if box is None:
+ return np.zeros(3), np.zeros(3)
+ lo, hi = box
+ center, offset = (lo + hi) / 2, (hi - lo) / 2 * self.get_sheen_direction()
+ return center - offset, center + offset
+
+ # ── path building ─────────────────────────────────────────────────────
+ def set_anchors_and_handles(
+ self,
+ anchors1: Point3D_Array,
+ handles1: Point3D_Array,
+ handles2: Point3D_Array,
+ anchors2: Point3D_Array,
+ ) -> Self:
+ """Give the path new curves, in place of its points, from their control points
+ listed kind by kind.
+
+ Curve `i` runs from `anchors1[i]` to `anchors2[i]`, bending toward `handles1[i]`
+ and then `handles2[i]`: the four arrays have one row per curve.
+
+ Args:
+ anchors1: Where each curve starts, in scene coordinates.
+ handles1: Each curve's first handle.
+ handles2: Each curve's second handle.
+ anchors2: Where each curve ends.
+ """
+ n = _NPPCC * len(anchors1)
+ points = np.empty((n, self.dim))
+ for i, array in enumerate((anchors1, handles1, handles2, anchors2)):
+ points[i::_NPPCC] = array
+ self.points = points
+ return self
+
+ def clear_points(self) -> Self:
+ """Remove the path's own points: the same as
+ [reset_points][manimgx.Mobject.reset_points].
+ """
+ return self.reset_points()
+
+ def append_points(self, new_points: Point3DLike_Array) -> Self:
+ """Add control points after the path's own: taken four by four, the path's
+ points are its curves.
+
+ Args:
+ new_points: The points, in scene coordinates: an (n, 3) array.
+ """
+ # the path grows in place (its shape is a prefix of an append-only log), so a
+ # traced path grows by what it gains, not by a copy of all it has
+ rows = np.asarray(new_points, dtype=float).reshape(-1, self.dim)
+ g = self._geometry
+ if len(g.terms) == 1 and np.array_equal(g.terms[0][0][:, :3], np.eye(3)):
+ m, shape = g.terms[0]
+ self._geometry = Blend(
+ ((m, shape.extended(rows - m[:, 3])),), g.n + len(rows)
+ )
+ return self
+ self.points = np.concatenate([self.points, rows])
+ return self
+
+ def start_new_path(self, point: Point3DLike) -> Self:
+ """Start a new subpath at a point: the next curve added begins there, not where
+ the path ends.
+
+ A curve left unfinished (a subpath started and given no curve yet) is completed
+ with copies of its first point, as a curve of no length. Started where the path
+ ends, the subpath just goes on.
+
+ Args:
+ point: Where the new subpath starts, in scene coordinates.
+ """
+ n = self._geometry.n
+ if n % _NPPCC != 0:
+ last = self._geometry.point(n // _NPPCC * _NPPCC)
+ self.append_points([last] * (_NPPCC - n % _NPPCC) + [point])
+ else:
+ self.append_points([point])
+ return self
+
+ def add_cubic_bezier_curve(
+ self,
+ anchor1: Point3DLike,
+ handle1: Point3DLike,
+ handle2: Point3DLike,
+ anchor2: Point3DLike,
+ ) -> Self:
+ """Add a curve from `anchor1` to `anchor2`, bending toward two handles: a new
+ subpath, unless `anchor1` is where the path ends.
+
+ Its four points are appended as they are, so the path's curves must all be
+ whole: after [start_new_path][manimgx.VMobject.start_new_path], use
+ [add_cubic_bezier_curve_to][manimgx.VMobject.add_cubic_bezier_curve_to].
+
+ Args:
+ anchor1: Where the curve starts, in scene coordinates.
+ handle1: The handle it leaves `anchor1` heading toward.
+ handle2: The handle it arrives at `anchor2` heading away from.
+ anchor2: Where it ends.
+ """
+ return self.append_points([anchor1, handle1, handle2, anchor2])
+
+ def add_cubic_bezier_curve_to(
+ self, handle1: Point3DLike, handle2: Point3DLike, anchor: Point3DLike
+ ) -> Self:
+ """Add a curve from where the path ends to `anchor`, bending toward two handles.
+
+ The curve leaves the path's last point heading toward `handle1`, and arrives at
+ `anchor` heading away from `handle2`. The path must have a point to start from.
+
+ Args:
+ handle1: The first handle, in scene coordinates.
+ handle2: The second handle.
+ anchor: Where the curve ends.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectAddCubicBezierCurveToExample(m.Scene):
+ def construct(self) -> None:
+ start, h1, h2, end = [-4, -2, 0], [-2, 3, 0], [2, 3, 0], [4, -2, 0]
+ path = m.VMobject(color=m.YELLOW, stroke_width=8)
+ path.start_new_path(start).add_cubic_bezier_curve_to(h1, h2, end)
+ handles = m.VGroup(m.Line(start, h1), m.Line(h2, end))
+ dots = [m.Dot(p, radius=0.12) for p in (start, h1, h2, end)]
+ self.add(handles.set_color(m.GREY), *dots)
+ self.play(m.Create(path, run_time=2))
+ ```
+ """
+ self._require_points()
+ new = [handle1, handle2, anchor]
+ return self.append_points(
+ new if self.has_new_path_started() else [self.get_last_point(), *new]
+ )
+
+ def add_cubic_bezier_curves(self, curves: Point3DLike_Array) -> Self:
+ """Add curves after the path's own, given by their control points, four per
+ curve: anchor, handle, handle, anchor.
+
+ Args:
+ curves: The curves' control points, in scene coordinates: an (n, 4, 3)
+ array, or the points one after another.
+ """
+ return self.append_points(np.asarray(curves).reshape(-1, 3))
+
+ def add_quadratic_bezier_curve_to(
+ self, handle: Point3DLike, anchor: Point3DLike
+ ) -> Self:
+ """Add a quadratic Bézier curve from where the path ends to `anchor`, bending
+ toward one handle.
+
+ It is added as the cubic curve of the same shape. The path must have a point to
+ start from.
+
+ Args:
+ handle: The handle, in scene coordinates: the curve leaves the path's last
+ point heading toward it, and arrives at `anchor` heading away from it.
+ anchor: Where the curve ends.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectAddQuadraticBezierCurveToExample(m.Scene):
+ def construct(self) -> None:
+ start, handle, end = [-4, -2, 0], [0, 3, 0], [4, -2, 0]
+ path = m.VMobject(color=m.TEAL, stroke_width=8)
+ path.start_new_path(start)
+ path.add_quadratic_bezier_curve_to(handle, end)
+ handles = m.VGroup(m.Line(start, handle), m.Line(handle, end))
+ dots = [m.Dot(p, radius=0.12) for p in (start, handle, end)]
+ self.add(handles.set_color(m.GREY), *dots)
+ self.play(m.Create(path, run_time=2))
+ ```
+ """
+ h, a, last = np.asarray(handle), np.asarray(anchor), self.get_last_point()
+ return self.add_cubic_bezier_curve_to(
+ 2 / 3 * h + 1 / 3 * last, 2 / 3 * h + 1 / 3 * a, a
+ )
+
+ def add_line_to(self, point: Point3DLike) -> Self:
+ """Add a straight line from where the path ends to a point.
+
+ The path must have a point to start from.
+
+ Args:
+ point: Where the line ends, in scene coordinates.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectAddLineToExample(m.Scene):
+ def construct(self) -> None:
+ stairs = m.VMobject(color=m.BLUE, stroke_width=8)
+ stairs.start_new_path([-5, -3, 0])
+ for _ in range(5):
+ stairs.add_line_to(stairs.get_last_point() + 1.2 * m.UP)
+ stairs.add_line_to(stairs.get_last_point() + 2 * m.RIGHT)
+ self.play(m.Create(stairs, run_time=3))
+ ```
+ """
+ last = self.get_last_point()
+ p = np.asarray(point, dtype=float)
+ return self.add_cubic_bezier_curve_to(
+ *(interpolate(last, p, t) for t in _T_VALUES[1:])
+ )
+
+ def add_smooth_curve_to(self, *points: Point3DLike) -> Self:
+ """Add a curve that continues the path smoothly: it leaves where the path ends
+ in the direction the path arrives there.
+
+ Its first handle is the path's last handle mirrored through the path's end.
+ Given only the anchor, the curve arrives there as the mirror image of how it
+ leaves (mirrored across the perpendicular bisector of the line between its
+ ends); given a second handle first, it arrives heading away from that. With no
+ curve to continue, after [start_new_path][manimgx.VMobject.start_new_path], it
+ is a straight line to the anchor.
+
+ Args:
+ *points: The anchor where the curve ends, or the second handle and then the
+ anchor, in scene coordinates.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectAddSmoothCurveToExample(m.Scene):
+ def construct(self) -> None:
+ wave = m.VMobject(color=m.YELLOW, stroke_width=8)
+ wave.start_new_path([-6, 0, 0])
+ wave.add_cubic_bezier_curve_to([-6, 2, 0], [-4, 2, 0], [-4, 0, 0])
+ for x in (-2, 0, 2, 4, 6):
+ wave.add_smooth_curve_to([x, 0, 0])
+ self.play(m.Create(wave, run_time=3))
+ ```
+ """
+ if len(points) == 1:
+ handle2, new_anchor = None, np.asarray(points[0])
+ elif len(points) == 2:
+ handle2, new_anchor = np.asarray(points[0]), np.asarray(points[1])
+ else:
+ raise ValueError("Only call add_smooth_curve_to with 1 or 2 points")
+ if self.has_new_path_started():
+ return self.add_line_to(new_anchor)
+ last_h2, last_a2 = self.points[-2:]
+ tangent = last_a2 - last_h2
+ handle1 = last_a2 + tangent
+ if handle2 is None: # the tangent mirrored across the ends' bisector
+ chord = normalize(new_anchor - last_a2)
+ handle2 = new_anchor + tangent - 2 * (tangent @ chord) * chord
+ return self.append_points([last_a2, handle1, handle2, new_anchor])
+
+ def has_new_path_started(self) -> bool:
+ """Whether the path ends in a subpath just started: a point that begins no curve
+ yet, where the next curve added starts.
+
+ Returns:
+ True after [start_new_path][manimgx.VMobject.start_new_path], until a curve
+ is added.
+ """
+ return self._geometry.n % _NPPCC == 1
+
+ def get_last_point(self) -> Point3D:
+ """The path's last point: where it ends, and where the next curve added begins.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ return self._geometry.point(-1)
+
+ def is_closed(self) -> bool:
+ """Whether the path ends where it starts: its first and last points coincide,
+ within its
+ [tolerance_for_point_equality][manimgx.VMobject.tolerance_for_point_equality].
+ """
+ return self.consider_points_equals(
+ self._geometry.point(0), self._geometry.point(-1)
+ )
+
+ def close_path(self) -> Self:
+ """Close the path: add a straight line from where it ends back to where its last
+ subpath starts, unless it ends where it starts.
+
+ The fill closes every subpath anyway; closing one makes its stroke go all the
+ way around.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectClosePathExample(m.Scene):
+ def construct(self) -> None:
+ corners = [[-2, -1.5, 0], [0, 1.5, 0], [2, -1.5, 0]]
+ style = {"fill_opacity": 0.5, "stroke_width": 8}
+ open_path = m.VMobject(color=m.GREEN, **style)
+ closed_path = m.VMobject(color=m.YELLOW, **style)
+ open_path.set_points_as_corners(corners)
+ closed_path.set_points_as_corners(corners).close_path()
+ self.add(m.VGroup(open_path, closed_path).arrange(buff=2))
+ ```
+ """
+ if not self.is_closed():
+ self.add_line_to(self.get_subpaths()[-1][0])
+ return self
+
+ def add_subpath(self, points: Point3DLike_Array) -> Self:
+ """Add curves after the path's own, by their control points, four per curve: a
+ new subpath, unless they start where the path ends.
+
+ Args:
+ points: The curves' control points, in scene coordinates.
+ """
+ return self.append_points(points)
+
+ def append_vectorized_mobject(self, vmobject: "VMobject") -> Self:
+ """Add another path's curves after this path's own: its points, not its
+ submobjects.
+
+ A subpath just started and given no curve yet (see
+ [start_new_path][manimgx.VMobject.start_new_path]) is dropped for them.
+
+ Args:
+ vmobject: The path whose points to add.
+ """
+ if self.has_new_path_started(): # its start begins the path that was begun
+ self.points = self.points[:-1]
+ return self.append_points(vmobject.points)
+
+ def add_points_as_corners(self, points: Point3DLike_Array) -> Self:
+ """Add straight lines from where the path ends through each point in turn.
+
+ The path must have a point to start from.
+
+ Args:
+ points: The corners, in scene coordinates, in order: the path then ends at
+ the last.
+ """
+ self._require_points()
+ pts = np.asarray(points, dtype=float).reshape(-1, self.dim)
+ if len(pts) == 0:
+ return self
+ starts = np.vstack([self.points[-1:], pts[:-1]])
+ if self.has_new_path_started():
+ self.points = self.points[:-1]
+ new = np.empty((_NPPCC * len(starts), self.dim))
+ for i, t in enumerate(_T_VALUES):
+ new[i::_NPPCC] = interpolate(starts, pts, t)
+ return self.append_points(new)
+
+ def set_points_as_corners(self, points: Point3DLike_Array) -> Self:
+ """Give the path new points, in place of its own: straight lines through the
+ given points in turn.
+
+ The path is open: to close it, end with its first point again.
+
+ Args:
+ points: The corners, in scene coordinates, in order.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectSetPointsAsCornersExample(m.Scene):
+ def construct(self) -> None:
+ zigzag = m.VMobject(color=m.YELLOW, stroke_width=8)
+ zigzag.set_points_as_corners(
+ [[-3, -1.5, 0], [-1.5, 1.5, 0], [0, -1.5, 0], [1.5, 1.5, 0]]
+ )
+ triangle = m.VMobject(color=m.BLUE, fill_opacity=0.5)
+ triangle.set_points_as_corners(
+ [[-2, -1.5, 0], [0, 2, 0], [2, -1.5, 0], [-2, -1.5, 0]]
+ )
+ self.add(m.VGroup(zigzag, triangle).arrange(buff=2))
+ ```
+ """
+ pts = np.asarray(points, dtype=float)
+ if len(pts) == 2: # a segment: the one segment, placed
+ self._geometry = segment(pts[0], pts[1])
+ return self
+ return self.set_anchors_and_handles(
+ *(interpolate(pts[:-1], pts[1:], t) for t in _T_VALUES)
+ )
+
+ def set_points_smoothly(self, points: Point3DLike_Array) -> Self:
+ """Give the path new points, in place of its own: a smooth curve through the
+ given points in turn.
+
+ The curve passes through each point, bending smoothly there, with no change of
+ curvature (a cubic spline); if the last point is the first, it closes smoothly.
+
+ Args:
+ points: The points it passes through, in scene coordinates, in order.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectSetPointsSmoothlyExample(m.Scene):
+ def construct(self) -> None:
+ points = [[-5, -1, 0], [-3, 2, 0], [-1, -2, 0], [1, 2, 0]]
+ points += [[3, -1, 0], [5, 1, 0]]
+ corners = m.VMobject(color=m.GREY).set_points_as_corners(points)
+ curve = m.VMobject(color=m.YELLOW, stroke_width=8)
+ curve.set_points_smoothly(points)
+ self.add(corners, *(m.Dot(p, radius=0.12) for p in points))
+ self.play(m.Create(curve, run_time=2))
+ ```
+ """
+ self.set_points_as_corners(points)
+ return self.make_smooth()
+
+ def change_anchor_mode(self, mode: Literal["jagged", "smooth"]) -> Self:
+ """Set anew the handles of every subpath in the family, for a smooth curve
+ through its anchors or straight lines between them; the anchors stay.
+
+ Args:
+ mode: "smooth" for a smooth curve (see
+ [make_smooth][manimgx.VMobject.make_smooth]); "jagged" for straight
+ lines ([make_jagged][manimgx.VMobject.make_jagged]).
+ """
+ for sub in self.family_members_with_points():
+ assert isinstance(sub, VMobject)
+ subpaths = sub.get_subpaths()
+ sub.clear_points()
+ for subpath in subpaths:
+ anchors = np.append(subpath[::_NPPCC], subpath[-1:], 0)
+ if mode == "smooth":
+ h1, h2 = get_smooth_cubic_bezier_handle_points(anchors)
+ else:
+ h1, h2 = interpolate(anchors[:-1], anchors[1:], 1 / 3), interpolate(
+ anchors[:-1], anchors[1:], 2 / 3
+ )
+ new = np.array(subpath)
+ new[1::_NPPCC], new[2::_NPPCC] = h1, h2
+ sub.append_points(new)
+ return self
+
+ def make_smooth(self) -> Self:
+ """Make every subpath in the family a smooth curve through its anchors, with no
+ change of curvature at any (a cubic spline); a closed subpath closes smoothly.
+
+ The anchors stay and the handles move: a polygon becomes a rounded loop through
+ its corners.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectMakeSmoothExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(side_length=4, color=m.BLUE, stroke_width=8)
+ self.add(square.copy().set_stroke(m.GREY, 3))
+ self.play(square.animate.make_smooth(), run_time=2)
+ ```
+ """
+ return self.change_anchor_mode("smooth")
+
+ def make_jagged(self) -> Self:
+ """Make every subpath in the family straight lines between its anchors: a curve
+ through points becomes the polygon through them.
+ """
+ return self.change_anchor_mode("jagged")
+
+ def _map_points(
+ self, function: Callable[[Point3D], Point3D], about: np.ndarray
+ ) -> None:
+ """This leaf's image under `function` (about `about`): each curve its image, to within
+ `_IMAGE_TOLERANCE`. A cubic's image is the cubic through the images of its ends along
+ the images of its tangents (its handles shrunk by
+ `pre_function_handle_to_anchor_scale_factor`, mapped, and grown back); where that is
+ not within the tolerance of the true image a third and two thirds of the way along
+ it, every cubic of the leaf is cut into 2, 4, … equal pieces first: the same number
+ for all, so a tween from the leaf as it was (cut to match by `align_points`) moves
+ each point straight to its image."""
+
+ def image(points: np.ndarray) -> np.ndarray:
+ return np.apply_along_axis(function, 1, points - about) + about
+
+ n = len(self.points) // _NPPCC * _NPPCC
+ if n == 0:
+ super()._map_points(function, about)
+ return
+ factor = self.pre_function_handle_to_anchor_scale_factor
+ curves = self.points[:n].reshape(-1, _NPPCC, 3)
+ for depth in range(_IMAGE_MAX_DEPTH + 1):
+ pieces = (
+ curves if depth == 0 else bezier_remap(curves, len(curves) << depth)
+ )
+ k = len(pieces)
+ a1, h1, h2, a2 = (pieces[:, i] for i in range(_NPPCC))
+ # where the path runs on, a piece's end is the next one's start: mapped once
+ loose = np.ones(k, dtype=bool)
+ loose[:-1] = np.any(a2[:-1] != a1[1:], axis=1)
+ mapped = image(
+ np.concatenate(
+ (
+ a1,
+ a1 + factor * (h1 - a1),
+ a2 + factor * (h2 - a2),
+ a2[loose],
+ _checked(pieces).reshape(-1, 3),
+ )
+ )
+ )
+ b1 = mapped[:k]
+ b2 = np.empty_like(b1)
+ b2[:-1] = b1[1:]
+ b2[loose] = mapped[3 * k : -2 * k]
+ result = np.stack(
+ (
+ b1,
+ b1 + (1.0 / factor) * (mapped[k : 2 * k] - b1),
+ b2 + (1.0 / factor) * (mapped[2 * k : 3 * k] - b2),
+ b2,
+ ),
+ axis=1,
+ )
+ with np.errstate(invalid="ignore"): # a map that blows up: nan, refined on
+ true = mapped[-2 * k :].reshape(k, 2, 3)
+ stray = np.linalg.norm(true - _checked(result), axis=2).max()
+ if depth == _IMAGE_MAX_DEPTH or stray <= _IMAGE_TOLERANCE:
+ break
+ tail = self.points[n:] # a path just started: its point
+ self.points = np.concatenate(
+ (result.reshape(-1, 3), image(tail) if len(tail) else tail)
+ )
+ if self.make_smooth_after_applying_functions:
+ self.make_smooth()
+
+ def scale_handle_to_anchor_distances(self, factor: float) -> Self:
+ """Move the handles of every path in the family toward their anchors, or away
+ from them, scaling their distances by a factor.
+
+ The curves flatten toward straight lines (below 1) or bulge (above 1); the
+ anchors stay.
+
+ Args:
+ factor: The factor: 0 makes each curve a straight line between its anchors,
+ 1 leaves it as it is.
+ """
+ for sub in self.family_members_with_points():
+ if len(sub.points) < _NPPCC or not isinstance(sub, VMobject):
+ continue
+ a1, h1, h2, a2 = sub.get_anchors_and_handles()
+ sub.set_anchors_and_handles(
+ a1, a1 + factor * (h1 - a1), a2 + factor * (h2 - a2), a2
+ )
+ return self
+
+ # ── curves and subpaths ───────────────────────────────────────────────
+ def consider_points_equals(self, p0: Point3DLike, p1: Point3DLike) -> bool:
+ """Whether two points count as one: equal within
+ [tolerance_for_point_equality][manimgx.VMobject.tolerance_for_point_equality].
+
+ Args:
+ p0: A point.
+ p1: Another point.
+ """
+ return bool(np.allclose(p0, p1, atol=self.tolerance_for_point_equality))
+
+ def get_cubic_bezier_tuples_from_points(self, points: Point3D_Array) -> np.ndarray:
+ """Split control points into curves, four points each; an unfinished last curve
+ is left out.
+
+ Args:
+ points: The control points: an (n, 3) array.
+
+ Returns:
+ The curves, as an array of shape (curves, 4, 3).
+ """
+ n = len(points) - len(points) % _NPPCC
+ return np.asarray(points[:n]).reshape(
+ -1, _NPPCC, points.shape[1] if len(points) else 3
+ )
+
+ def get_cubic_bezier_tuples(self) -> np.ndarray:
+ """The path's curves, by their control points.
+
+ Returns:
+ An array of shape (curves, 4, 3), each curve's anchor, two handles and
+ anchor.
+ """
+ return self.get_cubic_bezier_tuples_from_points(self.points)
+
+ def get_subpaths_from_points(self, points: Point3D_Array) -> list[Point3D_Array]:
+ """Split control points into subpaths: a subpath starts wherever a curve does
+ not begin where the one before it ends.
+
+ Args:
+ points: The control points, four per curve: an (n, 3) array.
+
+ Returns:
+ The subpaths, each an array of its control points.
+ """
+ return [
+ points[a:b]
+ for a, b, _ in subpath_ranges(points, self.tolerance_for_point_equality)
+ ]
+
+ def consider_points_equals_2d(self, p0: Point3DLike, p1: Point3DLike) -> bool:
+ """Whether two points count as one seen along the z axis: their x and y
+ coordinates equal within
+ [tolerance_for_point_equality][manimgx.VMobject.tolerance_for_point_equality].
+
+ Args:
+ p0: A point.
+ p1: Another point.
+ """
+ return bool(
+ np.allclose(
+ np.asarray(p0)[:2],
+ np.asarray(p1)[:2],
+ atol=self.tolerance_for_point_equality,
+ )
+ )
+
+ def gen_cubic_bezier_tuples_from_points(
+ self, points: Point3D_Array
+ ) -> tuple[Point3D_Array, ...]:
+ """Split control points into curves, four points each; an unfinished last curve
+ is left out.
+
+ Args:
+ points: The control points: an (n, 3) array.
+
+ Returns:
+ The curves, each a (4, 3) array.
+ """
+ n = len(points) - len(points) % _NPPCC
+ return tuple(points[i : i + _NPPCC] for i in range(0, n, _NPPCC))
+
+ def gen_subpaths_from_points_2d(
+ self, points: Point3D_Array
+ ) -> Iterator[Point3D_Array]:
+ """Split control points into subpaths, comparing points by their x and y only: a
+ subpath starts wherever a curve does not begin where the one before it ends.
+
+ Args:
+ points: The control points, four per curve: an (n, 3) array.
+
+ Returns:
+ The subpaths, one after another, each an array of its control points.
+ """
+ return (
+ points[a:b]
+ for a, b, _ in subpath_ranges(
+ points, self.tolerance_for_point_equality, dims=2
+ )
+ )
+
+ def get_subpaths(self) -> list[Point3D_Array]:
+ """The path's subpaths: a subpath starts wherever a curve does not begin where
+ the one before it ends.
+
+ Returns:
+ The subpaths, each an array of its control points, four per curve.
+ """
+ return self.get_subpaths_from_points(self.points)
+
+ def get_nth_curve_points(self, n: int) -> Point3D_Array:
+ """The control points of one of the path's curves.
+
+ Args:
+ n: Which curve, counting from 0.
+
+ Returns:
+ Its anchor, two handles and anchor, as a (4, 3) array.
+ """
+ return self.points[_NPPCC * n : _NPPCC * (n + 1)]
+
+ def get_nth_curve_function(self, n: int) -> Callable[[float], Point3D]:
+ """One of the path's curves, as a function from 0, its start, to 1, its end.
+
+ Args:
+ n: Which curve, counting from 0.
+
+ Returns:
+ A function of the curve's parameter, from 0 to 1, giving its point there.
+ """
+ return bezier(self.get_nth_curve_points(n))
+
+ def get_nth_curve_length_pieces(
+ self, n: int, sample_points: int | None = None
+ ) -> np.ndarray:
+ """The lengths of the straight pieces between points along one of the path's
+ curves, taken at evenly spaced values of its parameter.
+
+ Args:
+ n: Which curve, counting from 0.
+ sample_points: How many points to take, its ends included; None for 10,
+ the path's own measure (the one its reveals and proportions go by).
+
+ Returns:
+ The pieces' lengths, in scene units, one fewer than the points.
+ """
+ if sample_points in (None, 10): # the path's own, measured once
+ return self._geometry.piece_lengths()[n].copy()
+ curve = self.get_nth_curve_function(n)
+ pts = np.array([curve(a) for a in np.linspace(0, 1, sample_points)])
+ return np.linalg.norm(np.diff(pts, axis=0), axis=1)
+
+ def get_nth_curve_length(self, n: int, sample_points: int | None = None) -> float:
+ """The length of one of the path's curves, measured along straight pieces
+ between points on it.
+
+ Args:
+ n: Which curve, counting from 0.
+ sample_points: How many points to measure through, its ends included (evenly
+ spaced in its parameter); None for 10.
+
+ Returns:
+ The length, in scene units.
+ """
+ return float(np.sum(self.get_nth_curve_length_pieces(n, sample_points)))
+
+ def get_num_curves(self) -> int:
+ """How many curves the path has: its points, four per curve.
+
+ Returns:
+ The number of curves.
+ """
+ return self._geometry.n // _NPPCC
+
+ def get_curve_functions_with_lengths(
+ self, sample_points: int | None = None
+ ) -> Iterator[tuple[Callable[[float], Point3D], float]]:
+ """Each of the path's curves, as a function, with its length.
+
+ Args:
+ sample_points: How many points each curve's length is measured through (see
+ [get_nth_curve_length][manimgx.VMobject.get_nth_curve_length]); None for
+ 10.
+
+ Yields:
+ Each curve's function of its parameter, from 0 to 1, and its length in scene
+ units.
+ """
+ for n in range(self.get_num_curves()):
+ yield self.get_nth_curve_function(n), self.get_nth_curve_length(
+ n, sample_points
+ )
+
+ def point_from_proportion(self, alpha: float) -> Point3D:
+ """The point a proportion of the way along the path, by length: 0 is its start,
+ 1 its end.
+
+ The length is the path's own measure, the one a reveal draws by (nine straight
+ pieces per curve), so it is where a [Create][manimgx.Create] at that proportion
+ has drawn to, and a [MoveAlongPath][manimgx.MoveAlongPath] moves at a steady
+ speed. Raises an exception if `alpha` is outside [0, 1] or the path has no
+ points.
+
+ Args:
+ alpha: The proportion, from 0 to 1.
+
+ Returns:
+ The point, in scene coordinates.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectPointFromProportionExample(m.Scene):
+ def construct(self) -> None:
+ points = [[-5, -2, 0], [-2, 2, 0], [1, -1, 0], [5, 2, 0]]
+ curve = m.VMobject(color=m.BLUE, stroke_width=6)
+ curve.set_points_smoothly(points)
+ self.add(curve)
+ for alpha in (0, 0.25, 0.5, 0.75, 1):
+ point = curve.point_from_proportion(alpha)
+ dot = m.Dot(point, radius=0.15, color=m.YELLOW)
+ label = m.Text(str(alpha), font_size=32).next_to(dot, m.DOWN)
+ self.add(dot, label)
+ ```
+ """
+ if alpha < 0 or alpha > 1:
+ raise ValueError(f"Alpha {alpha} not between 0 and 1.")
+ self._require_points()
+ curves = self.get_num_curves()
+ if curves == 0: # a point, or a subpath just started
+ return self.points[-1]
+ at = self._geometry.parameter_at(alpha)
+ n = min(int(at), curves - 1)
+ return self.get_nth_curve_function(n)(at - n)
+
+ def get_arc_length(self, sample_points_per_curve: int | None = None) -> float:
+ """The path's length: the sum of its curves' lengths, each measured along
+ straight pieces between points on it.
+
+ Args:
+ sample_points_per_curve: How many points each curve is measured through, its
+ ends included; None for 10, the path's own measure.
+
+ Returns:
+ The length, in scene units.
+ """
+ if sample_points_per_curve in (None, 10):
+ return float(self._geometry.curve_lengths().sum())
+ return sum(
+ length
+ for _, length in self.get_curve_functions_with_lengths(
+ sample_points_per_curve
+ )
+ )
+
+ def get_anchors_and_handles(self) -> list[Point3D_Array]:
+ """The path's control points, kind by kind: its curves' first anchors, first
+ handles, second handles and second anchors.
+
+ Returns:
+ Four arrays, one row per curve, in the order
+ [set_anchors_and_handles][manimgx.VMobject.set_anchors_and_handles] takes
+ them.
+ """
+ return [self.points[i::_NPPCC] for i in range(_NPPCC)]
+
+ def get_start_anchors(self) -> Point3D_Array:
+ """Where each of the path's curves starts.
+
+ Returns:
+ An array of one point per curve, in scene coordinates.
+ """
+ return self.points[::_NPPCC]
+
+ def get_end_anchors(self) -> Point3D_Array:
+ """Where each of the path's curves ends.
+
+ Returns:
+ An array of one point per curve, in scene coordinates.
+ """
+ return self.points[_NPPCC - 1 :: _NPPCC]
+
+ def get_anchors(self) -> Point3D_Array:
+ """The path's anchors, curve by curve: each curve's start, then its end, so an
+ anchor two curves share is listed twice.
+
+ Returns:
+ An array of points, in scene coordinates; for a path of one point, that
+ point.
+ """
+ if self.points.shape[0] == 1:
+ return self.points
+ s, e = self.get_start_anchors(), self.get_end_anchors()
+ out = np.empty((len(s) + len(e), self.dim))
+ out[0::2], out[1::2] = s, e
+ return out
+
+ # ── the Path kind's alignment and partial rules ────────────────────────
+ def align_points(self, mobject: Mobject) -> Self:
+ self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
+ if (
+ not isinstance(mobject, VMobject)
+ or self.get_num_points() == mobject.get_num_points()
+ ):
+ return self
+ vmobject = mobject
+ for mob in (self, vmobject):
+ if mob.has_no_points():
+ mob.start_new_path(mob.get_center())
+ if mob.has_new_path_started():
+ mob.add_line_to(mob.get_last_point())
+ subpaths1, subpaths2 = self.get_subpaths(), vmobject.get_subpaths()
+ new1, new2 = [], []
+
+ def nth(paths: list[Point3D_Array], n: int) -> Point3D_Array:
+ """Subpath n without its trailing null curves (a curve all at the point before it)
+ — but its first — or its last point, held, when it has no subpath n."""
+ if n >= len(paths):
+ return np.tile(paths[-1][-1] if paths else np.zeros(3), (_NPPCC, 1))
+ path = paths[n]
+ k = len(path) // _NPPCC
+ if k > 1:
+ curves = path[: k * _NPPCC].reshape(k, _NPPCC, -1)[1:]
+ before = path[_NPPCC - 1 : (k - 1) * _NPPCC : _NPPCC][:, None]
+ null = np.all( # np.allclose, curve by curve
+ np.abs(curves - before)
+ <= self.tolerance_for_point_equality + 1e-5 * np.abs(before),
+ axis=(1, 2),
+ )
+ kept = len(null) - int(np.argmin(null[::-1])) if not null.all() else 0
+ path = path[: (kept + 1) * _NPPCC]
+ return path
+
+ for n in range(max(len(subpaths1), len(subpaths2))):
+ sp1, sp2 = nth(subpaths1, n), nth(subpaths2, n)
+ new1.append(
+ self.insert_n_curves_to_point_list(
+ max(0, (len(sp2) - len(sp1)) // _NPPCC), sp1
+ )
+ )
+ new2.append(
+ self.insert_n_curves_to_point_list(
+ max(0, (len(sp1) - len(sp2)) // _NPPCC), sp2
+ )
+ )
+ self.set_points(np.concatenate(new1))
+ vmobject.set_points(np.concatenate(new2))
+ return self
+
+ def align_points_with_larger(self, larger: Mobject) -> Self:
+ return self.align_points(larger)
+
+ def insert_n_curves(self, n: int) -> Self:
+ """Divide the path's curves into more curves, its shape unchanged.
+
+ Each curve is split into equal stretches of its parameter, the new curves
+ spread among the curves as evenly as can be (curve i of m gets the new curves j
+ of n with j·m // n = i): the way a transform gives two paths as many curves as
+ each other.
+
+ Args:
+ n: How many curves to add.
+ """
+ new_path_point = self.get_last_point() if self.has_new_path_started() else None
+ self.set_points(self.insert_n_curves_to_point_list(n, self.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
+ ) -> Point3D_Array:
+ """Divide the curves of a list of control points into more curves, their shape
+ unchanged (see [insert_n_curves][manimgx.VMobject.insert_n_curves]).
+
+ Args:
+ n: How many curves to add.
+ points: The control points, four per curve; a single point gives `n` curves
+ of no length at it.
+
+ Returns:
+ The new control points.
+ """
+ if len(points) == 1:
+ return np.repeat(points, _NPPCC * n, 0)
+ tuples = self.get_cubic_bezier_tuples_from_points(points)
+ return bezier_remap(tuples, len(tuples) + n).reshape(-1, 3)
+
+ def reveal_pace(self) -> tuple[np.ndarray, np.ndarray]:
+ return self._geometry.pace()
+
+ def get_point_mobject(self, center: Point3DLike | None = None) -> "VectorizedPoint":
+ point = VectorizedPoint(self.get_center() if center is None else center)
+ point.match_style(self)
+ return point
+
+ def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
+ vmobject = mobject
+ if a <= 0 and b >= 1:
+ return self.set_points(vmobject.points)
+ num_curves = len(vmobject.points) // _NPPCC
+ if num_curves == 0:
+ return self
+ lo, lo_res = integer_interpolate(0, num_curves, a)
+ hi, hi_res = integer_interpolate(0, num_curves, b)
+ src = vmobject.points.copy() if self is vmobject else vmobject.points
+ n = _NPPCC
+ if lo == hi:
+ self.points = partial_bezier_points(
+ src[n * lo : n * (lo + 1)], lo_res, hi_res
+ )
+ else:
+ pts = np.empty((n * (hi - lo + 1), self.dim))
+ pts[:n] = partial_bezier_points(src[n * lo : n * (lo + 1)], lo_res, 1)
+ pts[n:-n] = src[n * (lo + 1) : n * hi]
+ pts[-n:] = partial_bezier_points(src[n * hi : n * (hi + 1)], 0, hi_res)
+ self.points = pts
+ return self
+
+ def get_subcurve(self, a: float, b: float) -> Self:
+ """A copy of the path cut down to its part from proportion `a` of the way along
+ it to proportion `b`.
+
+ The proportions go by the path's curves, each an equal share whatever its
+ length, and along each curve by its parameter
+ ([point_from_proportion][manimgx.VMobject.point_from_proportion] goes by
+ length). The copy's submobjects are copied whole.
+
+ Args:
+ a: Where the part starts, from 0 to 1.
+ b: Where it ends, from `a` to 1.
+
+ Returns:
+ A new path.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectGetSubcurveExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=2.5, color=m.GREY)
+ half = circle.get_subcurve(0.25, 0.75).set_stroke(m.YELLOW, 12)
+ self.add(circle)
+ self.play(m.Create(half))
+ ```
+ """
+ return self.copy().pointwise_become_partial(self, a, b)
+
+ def get_direction(self) -> str:
+ """Which way the path turns: "CW" (clockwise) or "CCW" (counterclockwise), by
+ the sign of [shoelace][manimgx.shoelace] over its curves' start anchors.
+
+ Returns:
+ "CW" or "CCW".
+ """
+ return shoelace_direction(self.get_start_anchors())
+
+ def reverse_direction(self) -> Self:
+ """Reverse the order of the path's own points, so it runs the other way: from
+ its end to its start.
+
+ Its submobjects stay as they are (see
+ [reverse_points][manimgx.Mobject.reverse_points] for the whole family). A
+ drawing animation then draws it the other way, and a subpath inside another cuts
+ a hole in the fill only if the two run opposite ways.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VMobjectReverseDirectionExample(m.Scene):
+ def construct(self) -> None:
+ outer, inner = m.Square(side_length=4), m.Square(side_length=2)
+ same = m.VMobject(color=m.BLUE, fill_opacity=0.8)
+ same.append_vectorized_mobject(outer)
+ same.append_vectorized_mobject(inner)
+ opposite = m.VMobject(color=m.YELLOW, fill_opacity=0.8)
+ opposite.append_vectorized_mobject(outer)
+ opposite.append_vectorized_mobject(inner.reverse_direction())
+ self.add(m.VGroup(same, opposite).arrange(buff=2))
+ ```
+ """
+ self.points = self.points[::-1].copy()
+ return self
+
+ def force_direction(self, target_direction: Literal["CW", "CCW"]) -> Self:
+ """Make the path run clockwise or counterclockwise: reverse it if it runs the
+ other way (see [get_direction][manimgx.VMobject.get_direction]).
+
+ Args:
+ target_direction: "CW" for clockwise, "CCW" for counterclockwise.
+ """
+ if self.get_direction() != target_direction:
+ self.reverse_direction()
+ return self
+
+ @overload
+ def get_style(self, simple: Literal[True]) -> SimpleStyle: ...
+ @overload
+ def get_style(self, simple: Literal[False] = False) -> StyleSnapshot: ...
+ def get_style(self, simple: bool = False) -> SimpleStyle | StyleSnapshot:
+ """The path's own style, as keywords: `set_style(**style)` gives it back.
+
+ Args:
+ simple: Whether to give only the first color and opacity of the fill and
+ the stroke, and the stroke's width, in place of every color (each stop
+ of a gradient) of the fill, stroke and background stroke, their widths
+ and the sheen.
+
+ Returns:
+ A dictionary of [set_style][manimgx.Mobject.set_style]'s keywords.
+ """
+ if simple:
+ return SimpleStyle(
+ fill_color=self.get_fill_color(),
+ fill_opacity=self.get_fill_opacity(),
+ stroke_color=self.get_stroke_color(),
+ stroke_opacity=self.get_stroke_opacity(),
+ stroke_width=self.get_stroke_width(),
+ )
+ p = self.paint
+ return StyleSnapshot(
+ fill_color=[ManimColor(c[:3]) for c in p.fill],
+ fill_opacity=[float(c[3]) for c in p.fill],
+ stroke_color=[ManimColor(c[:3]) for c in p.stroke],
+ stroke_opacity=[float(c[3]) for c in p.stroke],
+ stroke_width=self.get_stroke_width(),
+ background_stroke_color=[ManimColor(c[:3]) for c in p.background],
+ background_stroke_opacity=[float(c[3]) for c in p.background],
+ background_stroke_width=self.get_stroke_width(background=True),
+ sheen_factor=self.paint.sheen_factor,
+ sheen_direction=self.get_sheen_direction(),
+ )
+
+ @staticmethod
+ def get_mobject_type_class() -> type[Mobject]:
+ """The class of the paths' kind: `VMobject`, whatever a path's own class.
+
+ Returns:
+ [VMobject][manimgx.VMobject].
+ """
+ return VMobject
+
+ def proportion_from_point(
+ self, point: Point3DLike, tolerance: float = 1e-6
+ ) -> float:
+ """How far along the path a point on it lies, by length: the inverse of
+ [point_from_proportion][manimgx.VMobject.point_from_proportion].
+
+ The first curve the point lies on counts. Raises an exception if the point is
+ not on the path.
+
+ Args:
+ point: The point, in scene coordinates.
+ tolerance: How near the path the point must be: within 100 times this, in
+ scene units, along each axis.
+
+ Returns:
+ The proportion, from 0 (the path's start) to 1 (its end).
+ """
+ p = np.asarray(point, dtype=float)
+ for n in range(self.get_num_curves()):
+ curve = self.get_nth_curve_points(n)
+ dim = int(
+ np.argmax(np.ptp(curve, axis=0))
+ ) # solve along the curve's widest coordinate, then check all
+ c = [
+ curve[0],
+ 3 * (curve[1] - curve[0]),
+ 3 * (curve[2] - 2 * curve[1] + curve[0]),
+ curve[3] - 3 * curve[2] + 3 * curve[1] - curve[0],
+ ]
+ coeffs = np.array([ci[dim] for ci in c])
+ coeffs[0] -= p[dim]
+ roots = [
+ r.real
+ for r in (
+ np.polynomial.Polynomial(coeffs).roots()
+ if coeffs[1:].any()
+ else [0.0] # constant along its widest coordinate: a point
+ )
+ # candidates, each checked below: a double root (a stationary end) comes
+ # back as a complex pair with parts near √ε
+ if abs(r.imag) < 1e-4 and -1e-4 <= r.real <= 1 + 1e-4
+ ]
+ hits = [
+ t
+ for t in roots
+ if np.allclose(
+ bezier(curve)(min(max(t, 0), 1)), p, atol=tolerance * 100
+ )
+ ]
+ if hits: # by the path's own measure: the inverse of point_from_proportion
+ return self._geometry.fraction_at(n + min(max(max(hits), 0.0), 1.0))
+ raise ValueError(f"Point {point} does not lie on this curve.")
+
+
+VGroup = Group # a group is a group: kinds belong to leaves
+"""Another name for [Group][manimgx.Group], which holds mobjects of any kind."""
+
+
+class VectorizedPoint(VMobject):
+ """A path of one point: unseen, a place to put things by, or to grow them from.
+
+ It is black, with no stroke and no fill. Its width and height are numbers of its
+ own, not measured from its point.
+
+ Args:
+ location: Where the point is, in scene coordinates.
+ artificial_width: The width it reports, in scene units.
+ artificial_height: The height it reports, in scene units.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VectorizedPointExample(m.Scene):
+ def construct(self) -> None:
+ point = m.VectorizedPoint(4 * m.LEFT)
+ square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
+ self.play(m.ReplacementTransform(point, square.shift(2 * m.RIGHT)))
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"color": BLACK, "fill_opacity": 0.0, "stroke_width": 0}
+
+ def __init__(
+ self,
+ location: Point3DLike = ORIGIN,
+ artificial_width: float = 0.01,
+ artificial_height: float = 0.01,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self.artificial_width = artificial_width
+ self.artificial_height = artificial_height
+ super().__init__(**kwargs)
+ self.set_points(np.array([location], dtype=float))
+
+ @property
+ def width(self) -> float:
+ """The point's width, in scene units: its `artificial_width`, not measured.
+ Setting it changes that number and nothing else."""
+ return self.artificial_width
+
+ @width.setter
+ def width(self, value: float) -> None:
+ self.artificial_width = value
+
+ @property
+ def height(self) -> float:
+ """The point's height, in scene units: its `artificial_height`, not measured.
+ Setting it changes that number and nothing else."""
+ return self.artificial_height
+
+ @height.setter
+ def height(self, value: float) -> None:
+ self.artificial_height = value
+
+ def get_location(self) -> Point3D:
+ """Where the point is.
+
+ Returns:
+ A copy of the point, in scene coordinates.
+ """
+ return np.array(self.points[0])
+
+ def set_location(self, new_loc: Point3DLike) -> Self:
+ """Move the point.
+
+ Args:
+ new_loc: Where it goes, in scene coordinates.
+ """
+ return self.set_points(np.array([new_loc], dtype=float))
+
+
+class VDict[T: Mobject = Mobject](Mobject):
+ """A group whose members have keys, as a dictionary has: `vdict[key]` is a member.
+
+ Members of any kind are added, replaced (`vdict[key] = mobject`) and removed by key;
+ like any group, it draws, moves and styles them together, in the order they were
+ added. With `show_keys`, each member is labeled with its key.
+
+ Args:
+ mapping_or_iterable: The first members: a dictionary of keys and mobjects, or
+ (key, mobject) pairs.
+ show_keys: Whether each member, added now or later, is labeled with its key: a
+ [Tex][manimgx.Tex] of `str(key)` at its left, added to the member itself,
+ so the label moves, animates and leaves with it, and counts in its size.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself: as it
+ has no points, they do not restyle its members (the style methods do).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VDictExample(m.Scene):
+ def construct(self) -> None:
+ shapes = m.VDict(
+ {
+ "circle": m.Circle(radius=0.9, color=m.RED),
+ "square": m.Square(side_length=1.8, color=m.GREEN),
+ },
+ show_keys=True,
+ )
+ shapes["triangle"] = m.Triangle(color=m.BLUE)
+ self.add(shapes.arrange(buff=1))
+ self.play(shapes["square"].animate.set_color(m.YELLOW))
+ ```
+ """
+
+ @overload # `VDict({...})`: members of any kinds
+ def __init__(
+ self: "VDict[Mobject]",
+ mapping_or_iterable: (
+ Mapping[Hashable, Mobject] | Iterable[tuple[Hashable, Mobject]]
+ ) = {},
+ show_keys: bool = False,
+ **kwargs: Unpack[Style],
+ ) -> None: ...
+ @overload # `VDict[Circle]({...})`: declared
+ def __init__(
+ self,
+ mapping_or_iterable: Mapping[Hashable, T] | Iterable[tuple[Hashable, T]] = {},
+ show_keys: bool = False,
+ **kwargs: Unpack[Style],
+ ) -> None: ...
+ def __init__(
+ self,
+ mapping_or_iterable: (
+ Mapping[Hashable, Mobject] | Iterable[tuple[Hashable, Mobject]]
+ ) = {},
+ show_keys: bool = False,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ super().__init__(**kwargs)
+ self.show_keys = show_keys
+ self.submob_dict: dict[Hashable, T] = {}
+ """The members, by key."""
+ self.add(
+ mapping_or_iterable # ty: ignore[invalid-argument-type] # a VDict[T] is given T
+ )
+
+ def add( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: by key
+ self, mapping_or_iterable: Mapping[Hashable, T] | Iterable[tuple[Hashable, T]]
+ ) -> Self:
+ """Add members by key, after the group's.
+
+ Each is added as [add_key_value_pair][manimgx.VDict.add_key_value_pair] adds it,
+ labeled with its key if the group shows its keys. A key the group has already
+ is given the new mobject, but the old one stays in the group: to replace a
+ member, set it (`vdict[key] = mobject`).
+
+ Args:
+ mapping_or_iterable: A dictionary of keys and mobjects, or (key, mobject)
+ pairs.
+ """
+ for key, value in dict(mapping_or_iterable).items():
+ self.add_key_value_pair(key, value)
+ return self
+
+ def remove( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: by key
+ self, key: Hashable
+ ) -> Self:
+ """Remove the member with a key from the group.
+
+ Raises an exception if the group has no such key.
+
+ Args:
+ key: The member's key.
+ """
+ super().remove(self.submob_dict.pop(key))
+ return self
+
+ def __getitem__(
+ self, key: Hashable
+ ) -> T: # ty: ignore[invalid-method-override] # CE's: by key
+ return self.submob_dict[key]
+
+ def __setitem__(self, key: Hashable, value: T) -> None:
+ if key in self.submob_dict:
+ self.remove(key)
+ self.add([(key, value)])
+
+ def add_key_value_pair(self, key: Hashable, value: T) -> Self:
+ """Add a member with a key, after the group's.
+
+ The constructor, [add][manimgx.VDict.add] and `vdict[key] = mobject` all add
+ members this way. If the group shows its keys (`show_keys`), the member is
+ labeled first: a [Tex][manimgx.Tex] of `str(key)`, at its left, is added to the
+ member itself, so the label moves, animates and leaves with it.
+
+ Args:
+ key: Its key.
+ value: The mobject.
+ """
+ if self.show_keys:
+ from manimgx.mobjects.text import Tex
+
+ value.add(Tex(str(key)).next_to(value, LEFT))
+ self.submob_dict[key] = value
+ Mobject.add(self, value)
+ return self
+
+ def get_all_submobjects(self) -> list[T]:
+ """The members, in the order of their keys.
+
+ Returns:
+ A list of the mobjects.
+ """
+ return list(self.submob_dict.values())
+
+
+class PMobject(Mobject):
+ """A point cloud: a mobject drawn as points, each a dot of its own color.
+
+ Points are added with [add_points][manimgx.PMobject.add_points], each with a color;
+ the style methods color them all. Each point is a disk `stroke_width` / 135 scene
+ units across: at the default width, 4, about 3 pixels of a 720p frame.
+
+ Args:
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `color` colors the points
+ added without a color (white unless given), and `stroke_width` sizes them;
+ the other paint keywords are not used.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class PMobjectExample(m.Scene):
+ def construct(self) -> None:
+ t = np.linspace(0, 1, 300)
+ spiral = np.column_stack(
+ [3.5 * t * np.cos(20 * t), 3.5 * t * np.sin(20 * t), 0 * t]
+ )
+ colors = m.color_gradient([m.BLUE, m.GREEN, m.YELLOW], len(t))
+ rgbas = np.array([color.to_rgba() for color in colors])
+ cloud = m.PMobject(stroke_width=15).add_points(spiral, rgbas=rgbas)
+ self.add(cloud)
+ ```
+ """
+
+ def init_colors(self, propagate_colors: bool = True) -> Self:
+ # a point's color is its row in `rgbas`, set as points are added; style gives
+ # its size
+ self.paint = self.paint.but(
+ stroke_width=self.style.get("stroke_width", DEFAULT_STROKE_WIDTH)
+ )
+ return self
+
+ def _color(self) -> ManimColor:
+ return parse_colors(self.style.get("color", WHITE))[0]
+
+ def reset_points(self) -> Self:
+ self.points = np.zeros((0, 3))
+ self.paint = self.paint.but(fill=np.zeros((0, 4)))
+ return self
+
+ def add_points(
+ self,
+ points: Point3DLike_Array,
+ rgbas: np.ndarray | None = None,
+ color: ParsableManimColor | None = None,
+ alpha: float = 1.0,
+ ) -> Self:
+ """Add points to the cloud, after its own, with their colors.
+
+ Args:
+ points: The points, in scene coordinates: an (n, 3) array.
+ rgbas: Their colors, one row of red, green, blue and opacity (from 0 to 1)
+ per point; None to give them all `color`.
+ color: Their color, when `rgbas` is None; None for the cloud's (its `color`
+ style keyword, white unless given).
+ alpha: Their opacity, from 0 to 1, when `rgbas` is None.
+ """
+ points = np.asarray(points, dtype=float).reshape(-1, 3)
+ if rgbas is None:
+ c = ManimColor(color) if color else self._color()
+ rgbas = np.repeat([c.to_rgba_with_alpha(alpha)], len(points), axis=0)
+ elif len(rgbas) != len(points):
+ raise ValueError("points and rgbas must have same length")
+ self.points = np.append(self.points, points, axis=0)
+ self.paint = self.paint.but(fill=np.append(self.paint.fill, rgbas, axis=0))
+ return self
+
+ def get_all_rgbas(self) -> RGBA_Array:
+ """The colors of every point of the cloud's family, member after member.
+
+ Returns:
+ An (n, 4) array of red, green, blue and opacity, from 0 to 1.
+ """
+ return np.concatenate(
+ [m.paint.fill for m in self.family_members_with_points()]
+ or [np.zeros((0, 4))]
+ )
+
+ def match_colors(self, mobject: Mobject) -> Self:
+ """Give the cloud another cloud's colors, point for point.
+
+ The two are first aligned as a transform aligns them: the one with fewer points
+ is given more, repeating its points, so `mobject` may change too.
+
+ Args:
+ mobject: The cloud whose colors to take.
+ """
+ Mobject.align_data(self, mobject)
+ self.paint = self.paint.but(fill=mobject.paint.fill)
+ return self
+
+ def thin_out(self, factor: int = 5) -> Self:
+ """Keep one point in every `factor` of each cloud in the family, from its first.
+
+ Args:
+ factor: One point is kept in this many; must be positive.
+ """
+ if factor < 1:
+ raise ValueError("factor must be positive")
+ for mob in self.family_members_with_points():
+ mob.points, mob.paint = mob.points[::factor], mob.paint.but(
+ fill=mob.paint.fill[::factor].copy()
+ )
+ return self
+
+ # ── the Points kind's alignment and partial rules ──────────────────────
+ def align_points_with_larger(self, larger: Mobject) -> Self:
+ n = larger.get_num_points()
+ self.points = stretch_array(self.points, n)
+ self.paint = self.paint.but(fill=stretch_array(self.paint.fill, n))
+ return self
+
+ def get_point_mobject(self, center: Point3DLike | None = None) -> "Point":
+ return Point(self.get_center() if center is None else center)
+
+ def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
+ lo, hi = (int(x * mobject.get_num_points()) for x in (a, b))
+ self.points = mobject.points[lo:hi]
+ self.paint = self.paint.but(fill=mobject.paint.fill[lo:hi])
+ return self
+
+
+class Mobject1D(PMobject):
+ """A point cloud of lines: points evenly spaced along each, `density` to a unit.
+
+ Lines are added with [add_line][manimgx.Mobject1D.add_line].
+
+ Args:
+ density: How many points a line gets per scene unit of its length.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `color` colors the points
+ added without a color (white unless given), and `stroke_width` sizes them.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class Mobject1DExample(m.Scene):
+ def construct(self) -> None:
+ cloud = m.Mobject1D(density=6, stroke_width=12)
+ cloud.add_line([-4, -2, 0], [4, -2, 0], color=m.BLUE)
+ cloud.add_line([4, -2, 0], [0, 2.5, 0], color=m.YELLOW)
+ cloud.add_line([0, 2.5, 0], [-4, -2, 0], color=m.RED)
+ self.add(cloud)
+ ```
+ """
+
+ def __init__(
+ self, density: int = DEFAULT_POINT_DENSITY_1D, **kwargs: Unpack[Style]
+ ) -> None:
+ self.density = density
+ self.epsilon = 1.0 / density
+ super().__init__(**kwargs)
+
+ def add_line(
+ self,
+ start: Point3DLike,
+ end: Point3DLike,
+ color: ParsableManimColor | None = None,
+ ) -> Self:
+ """Add a line of points from `start` toward `end`, 1/`density` scene units
+ apart.
+
+ The line stops short of `end`, where another may start; a line of no length is
+ one point.
+
+ Args:
+ start: Where the line starts, in scene coordinates.
+ end: Where it ends.
+ color: The points' color; None for the cloud's.
+ """
+ s, e = np.asarray(start, dtype=float), np.asarray(end, dtype=float)
+ length = np.linalg.norm(e - s)
+ points = (
+ np.array([s])
+ if length == 0
+ else interpolate(s, e, np.arange(0, 1, self.epsilon / length)[:, None])
+ )
+ return self.add_points(points, color=color)
+
+
+PGroup = Group # a group is a group: kinds belong to leaves
+"""Another name for [Group][manimgx.Group], which holds mobjects of any kind."""
+
+
+class Point(PMobject):
+ """A point cloud of one point, black unless colored: unseen on the default black
+ background.
+
+ Args:
+ location: Where the point is, in scene coordinates.
+ color: Its color, which may be given by position (`Point(ORIGIN, RED)`); None
+ for black.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `stroke_width` sizes the
+ point.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class PointExample(m.Scene):
+ def construct(self) -> None:
+ colors = [m.RED, m.YELLOW, m.GREEN, m.BLUE, m.PURPLE]
+ for i, color in enumerate(colors):
+ self.add(m.Point([2.5 * i - 5, 0, 0], color, stroke_width=60))
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"color": BLACK}
+
+ def __init__(
+ self,
+ location: Point3DLike = ORIGIN,
+ color: Colors | None = None,
+ **kwargs: Unpack[StyleBase],
+ ) -> None:
+ self.location = location
+ super().__init__(
+ **(Style(**kwargs) if color is None else Style(**kwargs, color=color))
+ )
+
+ def generate_points(self) -> Self:
+ return self.reset_points().add_points(np.array([self.location]))
+
+
+if TYPE_CHECKING:
+ from manimgx.scene import Camera
+
+
+_MESH_STRAIGHT = straight_path() # a default (paths are immutable)
+
+
+def _value(array: np.ndarray, held: np.ndarray | None = None) -> np.ndarray:
+ """An owned read-only snapshot; an equal value keeps the array already held."""
+ if held is not None and unchanged(array, held):
+ return held
+ array = array.copy()
+ array.flags.writeable = False
+ return array
+
+
+class MeshMobject(Mobject):
+ """A mesh: triangles between vertices, filled with one color, a color per vertex, or
+ a picture; white and opaque unless styled.
+
+ Any two meshes can morph into each other, whatever their triangles: the one with
+ fewer gains some, collapsed to points. Drawn in ([Create][manimgx.Create]), a mesh
+ appears triangle by triangle, in their order. A three-dimensional scene's light
+ shades it only with `shade_in_3d=True`.
+
+ Args:
+ vertices: The vertices, in scene coordinates: an (n, 3) array; None for an empty
+ mesh.
+ triangles: The triangles: an (m, 3) array of indices into `vertices`.
+ vertex_colors: A color for each vertex, blended across each triangle: an (n, 4)
+ array of red, green, blue and opacity, from 0 to 1; None for the style's
+ color.
+ uvs: Where each vertex is in the picture: an (n, 2) array of coordinates from 0
+ to 1, (0, 0) the picture's top left.
+ texture: The picture: an (h, w, 4) array of RGBA values from 0 to 255, or a
+ [Camera][manimgx.Camera], whose view is drawn anew every frame.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class MeshMobjectExample(m.Scene):
+ def construct(self) -> None:
+ vertices = np.array([[-3, -2.5, 0], [3, -2.5, 0], [0, 3, 0]])
+ colors = np.array([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]])
+ triangle = m.MeshMobject(
+ vertices, np.array([[0, 1, 2]]), vertex_colors=colors
+ )
+ self.play(m.FadeIn(triangle))
+ ```
+ """
+
+ defaults: ClassVar[Style] = {
+ "fill_opacity": 1.0,
+ "stroke_opacity": 0.0,
+ "stroke_width": 0.0,
+ }
+
+ def __init__(
+ self,
+ vertices: Point3D_Array | None = None,
+ triangles: np.ndarray | None = None,
+ *,
+ vertex_colors: np.ndarray | None = None,
+ uvs: np.ndarray | None = None,
+ texture: "np.ndarray | Camera | None" = None,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self._init_mesh = (vertices, triangles, uvs)
+ self._vertex_colors = vertex_colors
+ self._texture = texture
+ super().__init__(**kwargs)
+
+ @property
+ def triangles(self) -> np.ndarray:
+ """The mesh's readonly (m, 3) triangle indices; for a lattice these are its
+ coarse cell triangles.
+
+ Equal assignment is a no-op. Ordinary meshes snapshot replacement indices;
+ a sampled lattice requires constructing an explicit MeshMobject instead.
+ """
+ return (
+ grid_triangles(*self._topology)
+ if isinstance(self._topology, tuple)
+ else self._topology
+ )
+
+ @triangles.setter
+ def triangles(self, value: npt.ArrayLike) -> None:
+ array = np.asarray(value, dtype=np.int64)
+ array = array if array.shape[1:] == (3,) else array.reshape(-1, 3)
+ held = self.__dict__.get("_topology")
+ if isinstance(held, tuple):
+ if np.array_equal(array, self.triangles):
+ return
+ raise ValueError(
+ "A lattice's derived triangles cannot be replaced; construct "
+ "MeshMobject(vertices, triangles, vertex_colors=...) explicitly"
+ )
+ self._topology = _value(array, held)
+
+ @property
+ def uvs(self) -> np.ndarray | None:
+ """Where each vertex is in the mesh's picture: an (n, 2) array of coordinates
+ from 0 to 1, read-only; None for a mesh without them. Assignments snapshot
+ the supplied coordinates; equal values keep the current array."""
+ return self._uvs
+
+ @uvs.setter
+ def uvs(self, value: npt.ArrayLike | None) -> None:
+ self._uvs = (
+ None
+ if value is None
+ else _value(np.asarray(value, dtype=float), self.__dict__.get("_uvs"))
+ )
+
+ @property
+ def grid(self) -> tuple[int, int] | None:
+ """The numbers of lattice cells along u and v, or None for explicit triangles.
+
+ A (u, v) lattice has (u + 1) * (v + 1) samples. Its fill rows belong to cells
+ and UVs to samples; ordinary mesh fill rows belong to vertices. match_points
+ adopts this domain while retaining its recipient's style.
+ """
+ return self._topology if isinstance(self._topology, tuple) else None
+
+ def generate_points(self) -> Self:
+ vertices, triangles, uvs = self._init_mesh
+ if vertices is not None:
+ self.points = np.asarray(vertices, dtype=float)
+ self._topology = _value(
+ np.asarray(triangles, dtype=np.int64).reshape(-1, 3), self.triangles
+ )
+ self.uvs = uvs
+ return self
+
+ def reset_points(self) -> Self:
+ super().reset_points()
+ self._topology = _value(np.zeros((0, 3), dtype=np.int64))
+ self.uvs = None
+ return self
+
+ def init_colors(self, propagate_colors: bool = True) -> Self:
+ super().init_colors(propagate_colors)
+ if self._vertex_colors is not None:
+ self.paint = self.paint.but(fill=np.array(self._vertex_colors, dtype=float))
+ self.paint = self.paint.but(texture=self._texture)
+ return self
+
+ # ── the Mesh kind's alignment and partial rules ────────────────────────
+ def _as_soup(self) -> None:
+ """Convert to explicit triangles, giving each corner its own point and paint row."""
+ index = self.triangles.ravel()
+ if len(self.points) == len(index) and np.array_equal(
+ index, np.arange(len(index))
+ ):
+ return
+ grid = self.grid
+ if grid is not None:
+ if len(self.paint.fill) > 1:
+ cells = stretch_array(self.paint.fill, grid[0] * grid[1])
+ self.paint = self.paint.but(fill=np.repeat(cells, 6, axis=0))
+ elif len(self.paint.fill) == len(self.points) > 1:
+ self.paint = self.paint.but(fill=self.paint.fill[index])
+ self.points = self.points[index]
+ if self.uvs is not None:
+ self.uvs = self.uvs[index]
+ self._topology = _value(np.arange(len(index)).reshape(-1, 3))
+
+ def align_points(self, mobject: Mobject) -> Self:
+ # Equal topology shares the existing domain. Different topology becomes explicit
+ # triangle soup; the smaller mesh gains copies collapsed to their centers.
+ if not isinstance(mobject, MeshMobject):
+ self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
+ return self
+ if len(self.points) != len(mobject.points) or not np.array_equal(
+ self._topology, mobject._topology
+ ):
+ for mesh in (self, mobject):
+ mesh._as_soup()
+ small, large = sorted((self, mobject), key=lambda m: len(m.points))
+ n = len(large.points) // 3
+ if len(small.points) == 0:
+ small.points = np.repeat(small.get_center()[None], n * 3, axis=0)
+ else:
+ pieces = small.points.reshape(-1, 3, 3)
+ index = np.arange(n) * len(pieces) // n
+ first = np.r_[True, index[1:] != index[:-1]]
+ padded = pieces[index].copy()
+ padded[~first] = padded[~first].mean(axis=1, keepdims=True)
+ if len(small.paint.fill) == len(small.points) > 1:
+ colors = small.paint.fill.reshape(-1, 3, 4)[index].reshape(-1, 4)
+ small.paint = small.paint.but(fill=colors)
+ if small.uvs is not None:
+ small.uvs = small.uvs.reshape(-1, 3, 2)[index].reshape(-1, 2)
+ small.points = padded.reshape(-1, 3)
+ small._topology = large._topology
+ for a, b in ((self, mobject), (mobject, self)):
+ if len(a.paint.fill) == len(a.points) > 1 and len(b.paint.fill) == 1:
+ b.paint = b.paint.but(
+ fill=np.repeat(b.paint.fill, len(b.points), axis=0)
+ )
+ self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
+ return self
+
+ def _take_shape(self, mobject: Mobject) -> None:
+ if isinstance(mobject, MeshMobject):
+ self._topology, self._uvs = mobject._topology, mobject.uvs
+
+ def get_point_mobject(self, center: Point3DLike | None = None) -> "MeshMobject":
+ c = self.get_center() if center is None else np.asarray(center, dtype=float)
+ point = MeshMobject(np.repeat(c[None], 3, axis=0), np.array([[0, 1, 2]]))
+ point.paint = self.paint
+ return point
+
+ def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
+ """Take a source's geometry and paint, then select a fraction of its triangles.
+
+ A whole interval retains lattice topology; an actual subset uses explicit
+ triangles with each corner's paint and UV. Repeated calls restart from source.
+ """
+ if isinstance(mobject, MeshMobject):
+ self._geometry = mobject._geometry
+ self._take_shape(mobject)
+ self.paint = mobject.paint
+ if not (a <= 0 and b >= 1):
+ self._as_soup()
+ t = len(self.triangles)
+ self._topology = self.triangles[int(a * t) : int(np.ceil(b * t))]
+ return self
+
+ def interpolate(
+ self,
+ mobject1: Mobject,
+ mobject2: Mobject,
+ alpha: float,
+ path_func: PathFunc = _MESH_STRAIGHT,
+ ) -> Self:
+ super().interpolate(mobject1, mobject2, alpha, path_func)
+ if isinstance(mobject1, MeshMobject) and isinstance(mobject2, MeshMobject):
+ self._topology = mobject2._topology if alpha >= 1 else mobject1._topology
+ return self
+
+
+if TYPE_CHECKING:
+ from pathops import Path as SkiaPath
+
+
+def _append_path(target: "VMobject", path: "SkiaPath") -> "None":
+ """Append a planar path through the existing cubic builder, preserving its arithmetic."""
+ start = np.zeros(3)
+ verb = _pathops().PathVerb
+ for kind, points in path:
+ parts = np.array([(*point, 0.0) for point in points], dtype=float)
+ if kind == verb.MOVE:
+ for part in parts:
+ start = part
+ target.start_new_path(part)
+ elif kind == verb.CUBIC:
+ first, second, end = parts
+ target.add_cubic_bezier_curve_to(first, second, end)
+ elif kind == verb.LINE:
+ target.add_line_to(parts[0])
+ elif kind == verb.CLOSE:
+ target.add_line_to(start)
+ elif kind == verb.QUAD:
+ control, end = parts
+ target.add_quadratic_bezier_curve_to(control, end)
+ else:
+ raise Exception(f"Unsupported: {kind}")
diff --git a/src/manimgx/mobjects/shapes.py b/src/manimgx/mobjects/shapes.py
new file mode 100644
index 00000000..e257dfbf
--- /dev/null
+++ b/src/manimgx/mobjects/shapes.py
@@ -0,0 +1,4063 @@
+# SPDX-FileCopyrightText: 2026 Academa, Inc.
+# SPDX-FileCopyrightText: 2024 the Manim Community Developers
+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
+# SPDX-License-Identifier: MIT
+
+"Geometric figures: cubic paths, planar region operations, arrow tips and sampled point disks."
+
+from __future__ import annotations
+
+import itertools
+import warnings
+from collections.abc import Iterator, Sequence
+from functools import reduce
+from math import ceil
+from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpack, cast
+
+import numpy as np
+
+from manimgx.config import config
+from manimgx.constants import (
+ DEFAULT_ARROW_TIP_LENGTH,
+ DEFAULT_DASH_LENGTH,
+ DEFAULT_DOT_RADIUS,
+ DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
+ DEFAULT_POINT_DENSITY_1D,
+ DEGREES,
+ DL,
+ DOWN,
+ DR,
+ LARGE_BUFF,
+ LEFT,
+ MED_SMALL_BUFF,
+ ORIGIN,
+ OUT,
+ PI,
+ RIGHT,
+ TAU,
+ UL,
+ UP,
+ UR,
+)
+from manimgx.drawing.geometry import (
+ Blend,
+ QuickHull,
+ _pathops,
+ _to_path,
+ angle_between_vectors,
+ angle_of_vector,
+ cartesian_to_spherical,
+ defined,
+ line_intersection,
+ normalize,
+ perpendicular_bisector,
+ regular_vertices,
+ rotation_matrix,
+ segment,
+ turn_between,
+)
+from manimgx.drawing.paint import (
+ BLUE,
+ PURE_YELLOW,
+ RED,
+ WHITE,
+ Colors,
+ Style,
+ StyleBase,
+)
+from manimgx.mobject import (
+ Mobject,
+ Mobject1D,
+ Pivot,
+ VGroup,
+ VMobject,
+ _append_path,
+ prototype,
+ style_defaults,
+)
+from manimgx.typing import Point3DLike
+
+__all__ = [
+ "Angle",
+ "AnnotationDot",
+ "AnnularSector",
+ "Annulus",
+ "Arc",
+ "ArcBetweenPoints",
+ "ArcPolygon",
+ "ArcPolygonFromArcs",
+ "Arrow",
+ "ArrowCircleFilledTip",
+ "ArrowCircleTip",
+ "ArrowSquareFilledTip",
+ "ArrowSquareTip",
+ "ArrowTip",
+ "ArrowTriangleFilledTip",
+ "ArrowTriangleTip",
+ "Circle",
+ "ConvexHull",
+ "CubicBezier",
+ "CurvedArrow",
+ "CurvedDoubleArrow",
+ "CurvesAsSubmobjects",
+ "Cutout",
+ "DashedLine",
+ "DashedVMobject",
+ "Difference",
+ "Dot",
+ "DoubleArrow",
+ "Elbow",
+ "Ellipse",
+ "Exclusion",
+ "FullScreenRectangle",
+ "Intersection",
+ "Line",
+ "PointCloudDot",
+ "Polygon",
+ "Polygram",
+ "Rectangle",
+ "RegularPolygon",
+ "RegularPolygram",
+ "RightAngle",
+ "RoundedRectangle",
+ "ScreenRectangle",
+ "Sector",
+ "Square",
+ "Star",
+ "StealthTip",
+ "TangentLine",
+ "TipableVMobject",
+ "Triangle",
+ "Union",
+ "Vector",
+ "adjacent_n_tuples",
+ "adjacent_pairs",
+]
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+ from typing import Self
+
+ import numpy.typing as npt
+
+ from manimgx.drawing.paint import ParsableManimColor
+ from manimgx.mobject import Mobject
+ from manimgx.mobjects.grid import Matrix, MatrixOptions
+ from manimgx.typing import (
+ MatrixMN,
+ Point3D,
+ Point3D_Array,
+ Point3DLike,
+ Point3DLike_Array,
+ Vector2DLike,
+ Vector3D,
+ Vector3DLike,
+ )
+
+ type AngleQuadrant = tuple[Literal[-1, 1], Literal[-1, 1]]
+ "Which way along each of two crossing lines a side of an angle goes from the\n crossing: a sign for each line, the first line's first; 1 along the line's\n direction (from its start toward its end), -1 back toward its start."
+
+
+class TippedBase(StyleBase, total=False):
+ """Every style keyword but `color`, and those of a path that can end in arrow tips
+ (see [TipableVMobject][manimgx.TipableVMobject]).
+
+ A class that takes `color` by position declares it itself, and the rest with this.
+ """
+
+ tip_length: float
+ """The length of the tips [add_tip][manimgx.TipableVMobject.add_tip] makes, in
+ scene units (default 0.35; an [Arrow][manimgx.Arrow]'s may be shorter)."""
+ normal_vector: Vector3DLike
+ """The normal of the plane the path lies in (default OUT). Accepted for Manim
+ compatibility; ignored and not retained."""
+ tip_style: Style | None
+ """Style keywords for the tips the path makes (default None: none). A tip's
+ `fill_color` and `stroke_color` are the path's color unless given here."""
+
+
+class Tipped(TippedBase, total=False):
+ """The style keywords, and those of a path that can end in arrow tips (see
+ [TipableVMobject][manimgx.TipableVMobject])."""
+
+ color: Colors | None
+ """The color of both fill and stroke (default white; a [Circle][manimgx.Circle]'s is
+ red); None for the class's default."""
+
+
+class ArcOptions(Tipped, total=False):
+ """An arc's keywords, for the classes that build one and pass them on: how finely
+ and where it is built, with the style and tip keywords."""
+
+ num_components: int
+ """How many anchor points the arc is drawn through: it is one fewer cubic Bézier
+ curves (default 9)."""
+ arc_center: Point3DLike
+ """Where the center of the arc's circle goes, in scene coordinates (default
+ ORIGIN)."""
+
+
+class SectorOptions(ArcOptions, total=False):
+ """A [Sector][manimgx.Sector]'s keywords but its radius: its angles, with the arc
+ keywords."""
+
+ angle: float
+ """The angle the sector spans, in radians: counterclockwise from `start_angle`, or
+ clockwise if negative (default TAU / 4: a quarter turn)."""
+ start_angle: float
+ """The angle of its first edge, in radians, counterclockwise from the positive
+ x-axis (default 0)."""
+
+
+class ArcBetweenOptions(Tipped, total=False):
+ """An [ArcBetweenPoints][manimgx.ArcBetweenPoints]'s keywords but its ends: its
+ angle or its radius, with the style and tip keywords (for the classes that pass
+ them on)."""
+
+ angle: float
+ """The angle the arc turns through on its way, in radians: counterclockwise if
+ positive, bending it to the right of the straight way; clockwise if negative; a
+ straight segment if 0 (default TAU / 4)."""
+ radius: float | None
+ """The radius of the arc's circle, in scene units, in place of `angle`: the shorter
+ arc of that radius, bending right, or left if negative; at least half the distance
+ between the ends (default None: set by `angle`)."""
+
+
+def _similarity(
+ a: Point3D, b: Point3D, c: Point3D, d: Point3D
+) -> tuple[MatrixMN, MatrixMN]:
+ """(the 3×4 map, its rotation) taking segment a→b onto c→d, as CE's `put_start_and_end_on`:
+ scale and turn about a, then move."""
+ ab, cd = b - a, d - c
+ turn = rotation_matrix(*turn_between(ab, cd))
+ linear = turn * (np.linalg.norm(cd) / np.linalg.norm(ab))
+ return np.hstack([linear, (c - linear @ a)[:, None]]), turn
+
+
+class TipableVMobject(VMobject):
+ """A path that can end in arrow tips: what lines, arcs and arrows have in common.
+
+ A tip is a small shape (an [ArrowTip][manimgx.ArrowTip]) added to the path as a
+ submobject, at its end or its start, pointing along it. The tip's point goes where
+ the path ended, and the path is fitted to stop at the tip's base. With tips, the
+ path's [start][manimgx.TipableVMobject.get_start] and
+ [end][manimgx.TipableVMobject.get_end] are the tips' points.
+
+ Args:
+ tip_length: The length of the tips [add_tip][manimgx.TipableVMobject.add_tip]
+ makes, in scene units (default 0.35).
+ normal_vector: The normal of the plane the path lies in. Accepted for Manim
+ compatibility; ignored and not retained as an instance attribute. An
+ [Arrow.reset_normal_vector][manimgx.Arrow.reset_normal_vector] call can
+ explicitly record its tip's current normal.
+ tip_style: Style keywords for the tips the path makes; a tip's `fill_color` and
+ `stroke_color` are the path's color unless given here.
+ """
+
+ _tip_positioned = False
+
+ tip: ArrowTip
+ """The tip at the path's end, once [add_tip][manimgx.TipableVMobject.add_tip] has
+ made one."""
+ start_tip: ArrowTip
+ """The tip at the path's start, once `add_tip(at_start=True)` has made one."""
+
+ def __init__(
+ self,
+ tip_length: float = DEFAULT_ARROW_TIP_LENGTH,
+ normal_vector: Vector3DLike = OUT,
+ tip_style: Style | None = None,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self.tip_length: float = tip_length
+ self.tip_style: Style = tip_style if tip_style is not None else {}
+ super().__init__(**kwargs)
+
+ def add_tip(
+ self,
+ tip: ArrowTip | None = None,
+ tip_shape: type[ArrowTip] | None = None,
+ tip_length: float | None = None,
+ tip_width: float | None = None,
+ at_start: bool = False,
+ ) -> Self:
+ """Add an arrow tip at the path's end, or its start, pointing along the path
+ there.
+
+ The tip's point goes where the path ended, and the path is scaled and turned
+ about its other end to stop at the tip's base. The tip is a submobject, named
+ [tip][manimgx.TipableVMobject.tip] (or `start_tip`), in the path's color unless
+ `tip_style` gives it another.
+
+ Args:
+ tip: A tip made beforehand, to turn and move into place; None to make one.
+ tip_shape: The class of the tip to make, an [ArrowTip][manimgx.ArrowTip]
+ subclass; None for
+ [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
+ tip_length: The length of the tip to make, in scene units; None for the
+ path's [default][manimgx.TipableVMobject.get_default_tip_length].
+ tip_width: The width of the tip to make, if it is the default filled
+ triangle, in scene units; None for the default length. Other shapes take
+ no width: they are made at `tip_length` alone.
+ at_start: Whether the tip goes at the path's start, pointing back along it.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TipableVMobjectAddTipExample(m.Scene):
+ def construct(self) -> None:
+ line = m.Line(3 * m.LEFT, 3 * m.RIGHT, color=m.BLUE).add_tip()
+ both = m.Line(3 * m.LEFT, 3 * m.RIGHT, color=m.GREEN)
+ both.add_tip(tip_shape=m.StealthTip)
+ both.add_tip(tip_shape=m.ArrowCircleFilledTip, at_start=True)
+ arc = m.Arc(radius=2, angle=m.PI, color=m.YELLOW)
+ arc.add_tip(tip_length=0.5, tip_width=0.5)
+ self.add(m.VGroup(line, both, arc).arrange(m.DOWN, buff=1))
+ ```
+ """
+ if tip is None:
+ tip = self.create_tip(tip_shape, tip_length, tip_width, at_start)
+ else:
+ self.position_tip(tip, at_start)
+ self.reset_endpoints_based_on_tip(tip, at_start)
+ self.assign_tip_attr(tip, at_start)
+ self.add(tip)
+ return self
+
+ def create_tip(
+ self,
+ tip_shape: type[ArrowTip] | None = None,
+ tip_length: float | None = None,
+ tip_width: float | None = None,
+ at_start: bool = False,
+ ) -> ArrowTip:
+ """Make a tip for the path's end, or its start, pointing along the path there;
+ the tip is not added (see [add_tip][manimgx.TipableVMobject.add_tip]).
+
+ Args:
+ tip_shape: The class of the tip, an [ArrowTip][manimgx.ArrowTip] subclass;
+ None for [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
+ tip_length: Its length, in scene units; None for the path's
+ [default][manimgx.TipableVMobject.get_default_tip_length].
+ tip_width: Its width, if it is the default filled triangle, in scene units;
+ None for the default length.
+ at_start: Whether it is for the path's start, pointing back along it.
+
+ Returns:
+ A new tip, in place.
+ """
+ tip = self.get_unpositioned_tip(tip_shape, tip_length, tip_width)
+ self.position_tip(tip, at_start)
+ return tip
+
+ def get_unpositioned_tip(
+ self,
+ tip_shape: type[ArrowTip] | None = None,
+ tip_length: float | None = None,
+ tip_width: float | None = None,
+ ) -> ArrowTip:
+ """Make a tip in the path's style, not yet in place: what
+ [add_tip][manimgx.TipableVMobject.add_tip] makes before it turns and moves it to
+ an end.
+
+ The tip's `fill_color` and `stroke_color` are the path's color, with the path's
+ `tip_style` over them. The default filled triangle is made `tip_length` long and
+ `tip_width` wide; another shape is made at `tip_length`, as its class makes it.
+
+ Args:
+ tip_shape: The class of the tip; None for
+ [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
+ tip_length: Its length, in scene units; None for the path's
+ [default][manimgx.TipableVMobject.get_default_tip_length].
+ tip_width: The width of the default filled triangle, in scene units; None
+ for the default length.
+
+ Returns:
+ A new tip.
+ """
+ # The default tip is given its width too (the default length unless given, as
+ # in CE), and a triangle scales with its two sides: it is the unit triangle of
+ # their ratio, scaled, one prototype per ratio whatever the size. Another
+ # class's shape need not scale with its length (ArrowTriangleTip's width does
+ # not), so its tip is made at its size.
+
+ default = self.get_default_tip_length()
+ length = default if tip_length is None else tip_length
+ color = self.get_color()
+ style: Style = {"fill_color": color, "stroke_color": color}
+ style.update(self.tip_style)
+ if tip_shape is not None and tip_shape is not ArrowTriangleFilledTip:
+ return tip_shape(length=length, **style)
+ width = default if tip_width is None else tip_width
+ if length <= 0:
+ return ArrowTriangleFilledTip(length=length, width=width, **style)
+ unit = ArrowTriangleFilledTip(length=1.0, width=width / length, **style)
+ return unit.scale(length)
+
+ def position_tip(self, tip: ArrowTip, at_start: bool = False) -> ArrowTip:
+ """Turn and move a tip onto the path's end, or its start: pointing along the
+ path there, its point on the end.
+
+ [add_tip][manimgx.TipableVMobject.add_tip] and
+ [create_tip][manimgx.TipableVMobject.create_tip] call it; the path does not
+ change.
+
+ Args:
+ tip: The tip to place.
+ at_start: Whether to place it at the path's start, pointing back along it.
+
+ Returns:
+ The tip, in place.
+ """
+ anchor = self.get_start() if at_start else self.get_end()
+ angles = cartesian_to_spherical(self._toward(at_start) - anchor)
+ turn = rotation_matrix(angles[1] - PI - tip.tip_angle, OUT)
+ if not self._tip_positioned:
+ axis = np.array([np.sin(angles[1]), -np.cos(angles[1]), 0])
+ turn = rotation_matrix(-angles[2] + PI / 2, axis) @ turn
+ self._tip_positioned = True
+ # one rigid map, x ↦ R(x − tip point) + anchor: the tip turns to point along the curve,
+ # and its tip point, a point of its own, lands on the curve's end (CE's turns about the
+ # center and its move are this map)
+ point = tip.tip_point
+ tip._geometry = tip._geometry.transformed(
+ np.hstack([turn, (anchor - turn @ point)[:, None]])
+ )
+ tip._rotate_direction_state(turn)
+ return tip
+
+ def reset_endpoints_based_on_tip(self, tip: ArrowTip, at_start: bool) -> Self:
+ """Fit the path to stop at a tip's base: scale and turn it about its other end,
+ which stays.
+
+ [add_tip][manimgx.TipableVMobject.add_tip] calls it once the tip is in place. A
+ path of no length stays as it is.
+
+ Args:
+ tip: The tip, in place at the path's end (or its start).
+ at_start: Whether the tip is at the path's start.
+ """
+ # `put_start_and_end_on`, one map — on the curve alone while no tip is on it yet
+ # (a class's own `scale` is not called: it is the curve that is fitted, not the
+ # object resized)
+ if self.get_length() == 0:
+ return self
+ start, end = (
+ (tip.base, self.get_end()) if at_start else (self.get_start(), tip.base)
+ )
+ if self.submobjects: # tips already on it move with it, as CE moves them
+ return self.put_start_and_end_on(start, end)
+ m, turn = _similarity(*self.get_start_and_end(), start, end)
+ self._geometry = self._geometry.transformed(m)
+ self._rotate_direction_state(turn)
+ return self
+
+ def assign_tip_attr(self, tip: ArrowTip, at_start: bool) -> Self:
+ """Name a tip as the path's [tip][manimgx.TipableVMobject.tip], or its
+ [start_tip][manimgx.TipableVMobject.start_tip]; the tip is not added.
+
+ [add_tip][manimgx.TipableVMobject.add_tip] calls it.
+
+ Args:
+ at_start: Whether it is the tip at the path's start.
+ """
+ if at_start:
+ self.start_tip = tip
+ else:
+ self.tip = tip
+ return self
+
+ def has_tip(self) -> bool:
+ """Whether the path has a tip at its end: its
+ [tip][manimgx.TipableVMobject.tip], among its submobjects.
+ """
+ tip = self.__dict__.get("tip")
+ return tip is not None and any(m is tip for m in self.submobjects)
+
+ def has_start_tip(self) -> bool:
+ """Whether the path has a tip at its start: its
+ [start_tip][manimgx.TipableVMobject.start_tip], among its submobjects.
+ """
+ tip = self.__dict__.get("start_tip")
+ return tip is not None and any(m is tip for m in self.submobjects)
+
+ def pop_tips(self) -> VGroup[ArrowTip]:
+ """Remove the path's tips, and fit the path back between its start and its end
+ as they were: the tips' points.
+
+ Returns:
+ The tips removed, the end tip first, in a new group (empty if there were
+ none).
+ """
+
+ start, end = self.get_start_and_end()
+ result = VGroup[ArrowTip]()
+ if self.has_tip():
+ result.add(self.tip)
+ self.remove(self.tip)
+ if self.has_start_tip():
+ result.add(self.start_tip)
+ self.remove(self.start_tip)
+ if result.submobjects:
+ self.put_start_and_end_on(start, end)
+ return result
+
+ def get_tips(self) -> VGroup[ArrowTip]:
+ """The tips the path has been given: its [tip][manimgx.TipableVMobject.tip] and
+ its [start_tip][manimgx.TipableVMobject.start_tip], those it has had.
+
+ A tip [pop_tips][manimgx.TipableVMobject.pop_tips] removed is still named, and
+ listed here; [has_tip][manimgx.TipableVMobject.has_tip] tells whether it is on
+ the path.
+
+ Returns:
+ The tips, the end tip first, in a new group.
+ """
+
+ result = VGroup[ArrowTip]()
+ if hasattr(self, "tip"):
+ result.add(self.tip)
+ if hasattr(self, "start_tip"):
+ result.add(self.start_tip)
+ return result
+
+ def get_tip(self) -> ArrowTip:
+ """The path's tip: the one at its end, or the one at its start if it has none
+ there.
+
+ It is the first of [get_tips][manimgx.TipableVMobject.get_tips]; a path never
+ given a tip raises an exception.
+ """
+ tips = self.get_tips()
+ if not tips.submobjects:
+ raise Exception("tip not found")
+ return tips[0]
+
+ def get_default_tip_length(self) -> float:
+ """The length of the tips the path makes unless given one: its `tip_length`.
+
+ Returns:
+ The length, in scene units.
+ """
+ return self.tip_length
+
+ def get_first_handle(self) -> Point3D:
+ """The path's first handle: the control point after its first point, toward
+ which it leaves its start.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ first_handle: Point3D = self.points[1]
+ return first_handle
+
+ def _toward(self, at_start: bool) -> Point3D:
+ """The point the path leaves its start toward, or comes into its end from: the
+ nearest of the end curve's control points apart from its end, so a tip points
+ along the path where a handle has no length (a curve arrives along P3 − P1 when
+ P2 = P3)."""
+ curve = self.points[:4] if at_start else self.points[-4:][::-1]
+ end = curve[0]
+ for point in curve[1:]:
+ if np.linalg.norm(point - end) > 1e-9 * (1 + np.abs(end).max()):
+ return point
+ return curve[1]
+
+ def get_last_handle(self) -> Point3D:
+ """The path's last handle: the control point before its last point, from which
+ it comes into its end.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ last_handle: Point3D = self.points[-2]
+ return last_handle
+
+ def get_end(self) -> Point3D:
+ """Where the path ends: its end tip's point, if it has an end tip, and otherwise
+ its last point.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ if self.has_tip():
+ return np.array(self.tip.tip_point)
+ else:
+ return super().get_end()
+
+ def get_start(self) -> Point3D:
+ """Where the path starts: its start tip's point, if it has a start tip, and
+ otherwise its first point.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ if self.has_start_tip():
+ return np.array(self.start_tip.tip_point)
+ else:
+ return super().get_start()
+
+ def get_length(self) -> float:
+ """The distance from the path's start to its end, tips included: straight
+ across, so an arc's chord, not the length along it.
+
+ Returns:
+ The distance, in scene units.
+ """
+ start, end = self.get_start_and_end()
+ return float(np.linalg.norm(start - end))
+
+
+def _unit_arc(start: float, angle: float, n: int) -> np.ndarray:
+ """CE's arc on the unit circle: n anchors, handles along the tangents."""
+ a = np.linspace(start, start + angle, n)
+ anchors = np.stack([np.cos(a), np.sin(a), np.zeros(n)], axis=1)
+ tangents = np.stack([-anchors[:, 1], anchors[:, 0], np.zeros(n)], axis=1)
+ factor = 4 / 3 * np.tan(angle / (n - 1.0) / 4)
+ curves = np.empty((n - 1, 4, 3))
+ curves[:, 0], curves[:, 3] = anchors[:-1], anchors[1:]
+ curves[:, 1] = anchors[:-1] + factor * tangents[:-1]
+ curves[:, 2] = anchors[1:] - factor * tangents[1:]
+ return curves.reshape(-1, 3)
+
+
+class Arc(TipableVMobject):
+ r"""An arc of a circle: from the angle `start_angle` through `angle`,
+ counterclockwise if `angle` is positive; white unless styled.
+
+ Angles are in radians, about the arc's center, counterclockwise from the positive
+ x-axis. The arc is drawn through `num_components` points spaced evenly along it,
+ joined by cubic Bézier curves.
+
+ Args:
+ radius: The radius, in scene units; None for 1.
+ start_angle: The angle of the arc's first point.
+ angle: How far the arc goes: counterclockwise if positive, clockwise if
+ negative; TAU for a whole circle.
+ num_components: How many anchor points it is drawn through: the arc is one
+ fewer cubic Bézier curves.
+ arc_center: Where the center of its circle goes.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArcExample(m.Scene):
+ def construct(self) -> None:
+ arcs = m.VGroup(
+ m.Arc(radius=1.5, angle=m.PI, color=m.BLUE),
+ m.Arc(radius=1.5, start_angle=m.PI / 2, angle=3 * m.PI / 2),
+ m.Arc(radius=1.5, angle=-m.PI / 2, color=m.YELLOW),
+ ).arrange(buff=1.5)
+ labels = ("angle=PI", "start_angle=PI/2\nangle=3*PI/2", "angle=-PI/2")
+ for arc, label in zip(arcs, labels):
+ self.add(m.Text(label, font_size=28).next_to(arc, m.DOWN))
+ self.play(m.Create(arcs, run_time=3))
+ ```
+ """
+
+ def __init__(
+ self,
+ radius: float | None = 1.0,
+ start_angle: float = 0,
+ angle: float = TAU / 4,
+ num_components: int = 9,
+ arc_center: Point3DLike = ORIGIN,
+ **kwargs: Unpack[Tipped],
+ ):
+ if radius is None:
+ radius = 1.0
+ self.radius = radius
+ self.num_components = num_components
+ self.arc_center: Point3D = np.asarray(arc_center)
+ self.start_angle = start_angle
+ self.angle = angle
+ self._failed_to_get_center: bool = False
+ super().__init__(**kwargs)
+
+ def generate_points(self) -> Self:
+ # the unit arc of this start, angle and number of pieces (a defined shape),
+ # placed by radius and center
+ start, angle, n = self.start_angle, self.angle, self.num_components
+ shape = defined(("arc", start, angle, n), lambda: _unit_arc(start, angle, n))
+ m = np.zeros((3, 4))
+ m[0, 0] = m[1, 1] = m[2, 2] = self.radius
+ m[:, 3] = self.arc_center
+ self._geometry = Blend(((m, shape),), len(shape.array))
+ return self
+
+ def get_arc_center(self, warning: bool = True) -> Point3D:
+ """The center of the arc's circle, where it is now, in whatever plane it lies:
+ the center of the circle through its first curve's ends and middle.
+
+ If there is none (a straight path), it is the origin, with a warning.
+
+ Args:
+ warning: Whether to warn when the center cannot be found.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ a1, h1, h2, a2 = self.points[:4]
+ if np.all(a1 == a2):
+ return np.copy(a1)
+ middle = (a1 + 3 * (h1 + h2) + a2) / 8 # on the circle, as an arc's curve is
+ u, v = a1 - middle, a2 - middle
+ normal = np.cross(u, v)
+ if np.linalg.norm(normal) <= 1e-12 * max(u @ u, v @ v):
+ if warning:
+ warnings.warn(
+ "Can't find Arc center, using ORIGIN instead", stacklevel=1
+ )
+ self._failed_to_get_center = True
+ return np.array(ORIGIN)
+ return middle + np.cross((u @ u) * v - (v @ v) * u, normal) / (
+ 2 * normal @ normal
+ )
+
+ def move_arc_center_to(self, point: Point3DLike) -> Self:
+ """Move the arc so the center of its circle is at a point.
+
+ Args:
+ point: Where the center goes, in scene coordinates.
+ """
+ self.shift(point - self.get_arc_center())
+ return self
+
+ def stop_angle(self) -> float:
+ """The angle at which the arc ends: the angle of its last point about its
+ [center][manimgx.Arc.get_arc_center].
+
+ Returns:
+ The angle, in radians, counterclockwise from the positive x-axis, from 0 up
+ to TAU.
+ """
+ return angle_of_vector(self.points[-1] - self.get_arc_center()) % TAU
+
+
+class ArcBetweenPoints(Arc):
+ """An arc from one point to another, through an angle or of a radius; white unless
+ styled.
+
+ Going from `start` to `end`, a positive angle turns counterclockwise, bending the
+ arc to the right of the straight way; a negative angle bends it to the left, and 0
+ makes it a straight segment.
+
+ Args:
+ start: Where the arc starts.
+ end: Where it ends.
+ angle: The angle it turns through on its way, in radians.
+ radius: The radius of its circle, in scene units, in place of `angle`: the
+ shorter arc of that radius, bending right, or left if negative. It must be
+ at least half the distance between the ends. None to use `angle`.
+ **kwargs: [Arc keywords][manimgx.mobjects.shapes.ArcOptions]; `arc_center`
+ has no effect, as the ends place the arc.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArcBetweenPointsExample(m.Scene):
+ def construct(self) -> None:
+ start, end = 3 * m.LEFT + m.DOWN, 3 * m.RIGHT + m.DOWN
+ arcs = m.VGroup(
+ m.ArcBetweenPoints(start, end, color=m.BLUE),
+ m.ArcBetweenPoints(start, end, radius=-4, color=m.GREEN),
+ m.ArcBetweenPoints(start, end, angle=-m.PI, color=m.YELLOW),
+ )
+ self.add(m.Dot(start, radius=0.12), m.Dot(end, radius=0.12))
+ self.play(m.Create(arcs, run_time=3))
+ ```
+ """
+
+ def __init__(
+ self,
+ start: Point3DLike,
+ end: Point3DLike,
+ angle: float = TAU / 4,
+ radius: float | None = None,
+ **kwargs: Unpack[ArcOptions],
+ ) -> None:
+ if radius is not None:
+ self.radius = radius
+ if radius < 0:
+ sign = -2
+ radius *= -1
+ else:
+ sign = 2
+ halfdist = np.linalg.norm(np.array(start) - np.array(end)) / 2
+ if radius < halfdist:
+ raise ValueError(
+ "ArcBetweenPoints called with a radius that is\n "
+ " smaller than half the distance between the points."
+ )
+ arc_height = radius - np.sqrt(radius**2 - halfdist**2)
+ angle = np.arccos((radius - arc_height) / radius) * sign
+ super().__init__(radius=radius, angle=angle, **kwargs)
+ if angle == 0:
+ self.set_points_as_corners(np.array([LEFT, RIGHT]))
+ self.put_start_and_end_on(start, end)
+ if radius is None:
+ center = self.get_arc_center(warning=False)
+ if not self._failed_to_get_center:
+ self.radius = cast(
+ float, np.linalg.norm(np.array(start) - np.array(center))
+ )
+ else:
+ self.radius = np.inf
+
+
+class CurvedArrow(ArcBetweenPoints):
+ """An arrow along an arc: an [ArcBetweenPoints][manimgx.ArcBetweenPoints] with a tip
+ at its end, bending right on its way by default; white unless styled.
+
+ Args:
+ start_point: Where the arrow starts.
+ end_point: Where it points to: its tip's point.
+ tip_shape: The class of its tip; None for
+ [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
+ **kwargs:
+ [ArcBetweenPoints keywords][manimgx.mobjects.shapes.ArcBetweenOptions]:
+ its angle (a quarter turn unless given) or its radius, style and tips.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class CurvedArrowExample(m.Scene):
+ def construct(self) -> None:
+ start, end = 3 * m.LEFT + 0.5 * m.UP, 3 * m.RIGHT + 0.5 * m.UP
+ arrows = m.VGroup(
+ m.CurvedArrow(start, end, color=m.BLUE),
+ m.CurvedArrow(start, end, angle=m.PI, color=m.YELLOW),
+ m.CurvedArrow(end, start, color=m.GREEN),
+ m.CurvedArrow(end, start, radius=3.2, tip_shape=m.StealthTip),
+ )
+ self.add(m.Dot(start, radius=0.12), m.Dot(end, radius=0.12))
+ self.play(m.Create(arrows, run_time=4))
+ ```
+ """
+
+ def __init__(
+ self,
+ start_point: Point3DLike,
+ end_point: Point3DLike,
+ *,
+ tip_shape: type[ArrowTip] | None = None,
+ **kwargs: Unpack[ArcBetweenOptions],
+ ) -> None:
+
+ super().__init__(start_point, end_point, **kwargs)
+ self.add_tip(tip_shape=tip_shape or ArrowTriangleFilledTip)
+
+
+class CurvedDoubleArrow(CurvedArrow):
+ """An arrow along an arc with a tip at each end: an
+ [ArcBetweenPoints][manimgx.ArcBetweenPoints] with two tips, bending right on its way
+ by default; white unless styled.
+
+ Args:
+ start_point: Where the arrow starts: its start tip's point.
+ end_point: Where it ends: its end tip's point.
+ tip_shape_start: The class of the tip at its start; None for
+ [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
+ tip_shape_end: The class of the tip at its end; None for
+ [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
+ **kwargs:
+ [ArcBetweenPoints keywords][manimgx.mobjects.shapes.ArcBetweenOptions]:
+ its angle (a quarter turn unless given) or its radius, style and tips.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class CurvedDoubleArrowExample(m.Scene):
+ def construct(self) -> None:
+ left = m.Circle(radius=1, color=m.BLUE).shift(4 * m.LEFT)
+ right = m.Square(side_length=2, color=m.GREEN).shift(4 * m.RIGHT)
+ top = left.get_top(), right.get_top()
+ arrows = m.VGroup(
+ m.CurvedDoubleArrow(*top, angle=-m.PI / 3),
+ m.CurvedDoubleArrow(
+ left.get_bottom(),
+ right.get_bottom(),
+ tip_shape_start=m.ArrowCircleFilledTip,
+ tip_shape_end=m.StealthTip,
+ color=m.YELLOW,
+ ),
+ )
+ self.add(left, right)
+ self.play(m.Create(arrows, run_time=2))
+ ```
+ """
+
+ def __init__(
+ self,
+ start_point: Point3DLike,
+ end_point: Point3DLike,
+ *,
+ tip_shape_start: type[ArrowTip] | None = None,
+ tip_shape_end: type[ArrowTip] | None = None,
+ **kwargs: Unpack[ArcBetweenOptions],
+ ) -> None:
+
+ super().__init__(start_point, end_point, tip_shape=tip_shape_end, **kwargs)
+ self.add_tip(at_start=True, tip_shape=tip_shape_start or ArrowTriangleFilledTip)
+
+
+class Circle(Arc):
+ """A circle: drawn counterclockwise from its rightmost point, red unless styled.
+
+ Args:
+ radius: The radius, in scene units; None for 1.
+ color: The color, which may be given by position (`Circle(1, BLUE)`); None for
+ red.
+ num_components: How many anchor points it is drawn through: the circle is one
+ fewer cubic Bézier arcs.
+ arc_center: Where its center goes.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class CircleExample(m.Scene):
+ def construct(self) -> None:
+ circles = m.VGroup(
+ m.Circle(color=m.BLUE),
+ m.Circle(radius=1.5, color=m.GREEN, fill_opacity=0.5),
+ m.Circle(radius=2, color=m.YELLOW, stroke_width=12),
+ ).arrange(buff=1)
+ self.play(m.Create(circles))
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"color": RED}
+
+ def __init__(
+ self,
+ radius: float | None = None,
+ color: Colors | None = None,
+ *,
+ num_components: int = 9,
+ arc_center: Point3DLike = ORIGIN,
+ **kwargs: Unpack[TippedBase],
+ ) -> None:
+ style = Tipped(**kwargs) if color is None else Tipped(**kwargs, color=color)
+ super().__init__(
+ radius=radius,
+ start_angle=0,
+ angle=TAU,
+ num_components=num_components,
+ arc_center=arc_center,
+ **style,
+ )
+
+ def surround(
+ self,
+ mobject: Mobject,
+ dim_to_match: int = 0,
+ stretch: bool = False,
+ buff: float = 0,
+ *,
+ buffer_factor: float = 1.2,
+ ) -> Self:
+ """Fit the circle around a mobject: through the corners of its bounding box, enlarged
+ by `buffer_factor`, then `buff` farther out.
+
+ Args:
+ mobject: The mobject to surround.
+ dim_to_match: The dimension (0, 1 or 2) of `mobject` the circle is first fitted
+ to, before it grows to the corners.
+ stretch: Whether that first fit stretches the circle into an ellipse matching the
+ bounding box.
+ buff: How much farther out the circle goes, in scene units.
+ buffer_factor: How much larger than through the corners the circle is.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class CircleSurroundExample(m.Scene):
+ def construct(self) -> None:
+ word = m.Text("manimgx", font_size=120)
+ ring = m.Circle(color=m.YELLOW).surround(word)
+ self.add(word)
+ self.play(m.Create(ring))
+ ```
+ """
+ self.replace(mobject, dim_to_match, stretch)
+ self.width = np.sqrt(mobject.width**2 + mobject.height**2)
+ self.scale(buffer_factor)
+ return self.scale((self.width / 2 + buff) / (self.width / 2)) if buff else self
+
+ def point_at_angle(self, angle: float) -> Point3D:
+ """The point of the circle at an angle from its start, its rightmost point.
+
+ Args:
+ angle: The angle, in radians, counterclockwise; any angle wraps around.
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ proportion = angle / TAU
+ proportion -= np.floor(proportion)
+ return self.point_from_proportion(proportion)
+
+ @staticmethod
+ def from_three_points(
+ p1: Point3DLike, p2: Point3DLike, p3: Point3DLike, **kwargs: Unpack[Tipped]
+ ) -> Circle:
+ """The circle through three points.
+
+ Args:
+ p1: A point on the circle.
+ p2: A second point on it.
+ p3: A third point on it, not on the line through the other two.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Returns:
+ A new circle.
+ """
+ center = line_intersection(
+ perpendicular_bisector([np.asarray(p1), np.asarray(p2)]),
+ perpendicular_bisector([np.asarray(p2), np.asarray(p3)]),
+ )
+ radius = float(np.linalg.norm(np.asarray(p1, dtype=float) - center))
+ return Circle(radius=radius, **kwargs).shift(center)
+
+
+class Dot(Circle):
+ """A dot: a small filled disc, white and without an outline unless styled.
+
+ Args:
+ point: Where its center goes.
+ radius: Its radius, in scene units (default 0.08).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class DotExample(m.Scene):
+ def construct(self) -> None:
+ self.add(
+ m.Dot([-5, 0, 0]),
+ m.Dot([-3.5, 0, 0], radius=0.2, color=m.BLUE),
+ m.Dot([-1, 0, 0], radius=0.6, color=m.YELLOW),
+ m.Dot([3, 0, 0], radius=1.5, color=m.GREEN, fill_opacity=0.5),
+ )
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"stroke_width": 0, "fill_opacity": 1.0, "color": WHITE}
+
+ def __init__(
+ self,
+ point: Point3DLike = ORIGIN,
+ radius: float = DEFAULT_DOT_RADIUS,
+ **kwargs: Unpack[Tipped],
+ ) -> None:
+ super().__init__(radius=radius, arc_center=point, **kwargs)
+
+
+class AnnotationDot(Dot):
+ """A dot to mark a point with: a little larger than a [Dot][manimgx.Dot], blue with
+ a thick white outline unless styled.
+
+ Its colors are its `fill_color` and its `stroke_color`, which `color` does not
+ change.
+
+ Args:
+ radius: Its radius, in scene units (default 0.104, 1.3 times a dot's).
+ point: Where its center goes.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class AnnotationDotExample(m.Scene):
+ def construct(self) -> None:
+ arc = m.Arc(radius=3, angle=m.PI, color=m.GREY).shift(1.5 * m.DOWN)
+ start = m.AnnotationDot(point=arc.get_start())
+ end = m.AnnotationDot(point=arc.get_end())
+ top = m.AnnotationDot(
+ 0.25, point=arc.get_top(), fill_color=m.YELLOW, stroke_color=m.RED
+ )
+ self.add(arc, start, end, top)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {
+ "stroke_width": 5,
+ "stroke_color": WHITE,
+ "fill_color": BLUE,
+ }
+
+ def __init__(
+ self,
+ radius: float = DEFAULT_DOT_RADIUS * 1.3,
+ *,
+ point: Point3DLike = ORIGIN,
+ **kwargs: Unpack[Tipped],
+ ) -> None:
+ super().__init__(point=point, radius=radius, **kwargs)
+
+
+class Ellipse(Circle):
+ """An ellipse: a circle stretched to a width and a height, red unless styled.
+
+ Like a circle, it is drawn counterclockwise from its rightmost point.
+
+ Args:
+ width: Its width, in scene units: its extent along x.
+ height: Its height, in scene units: its extent along y.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class EllipseExample(m.Scene):
+ def construct(self) -> None:
+ ellipses = m.VGroup(
+ m.Ellipse(),
+ m.Ellipse(width=2, height=4, color=m.BLUE),
+ m.Ellipse(width=5, height=2, color=m.YELLOW, fill_opacity=0.5),
+ ).arrange(buff=1)
+ self.add(ellipses)
+ ```
+ """
+
+ def __init__(
+ self, width: float = 2, height: float = 1, **kwargs: Unpack[ArcOptions]
+ ) -> None:
+ super().__init__(**kwargs)
+ self.stretch_to_fit_width(width)
+ self.stretch_to_fit_height(height)
+
+
+class AnnularSector(Arc):
+ """A sector of a ring: the region between two arcs of one center, over one angle;
+ white and filled, without an outline, unless styled.
+
+ Args:
+ inner_radius: The inner arc's radius, in scene units.
+ outer_radius: The outer arc's radius, in scene units.
+ angle: The angle it spans, in radians: counterclockwise from `start_angle`, or
+ clockwise if negative.
+ start_angle: The angle of its first edge, in radians, counterclockwise from the
+ positive x-axis.
+ **kwargs: [Arc keywords][manimgx.mobjects.shapes.ArcOptions];
+ `num_components` has no effect.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class AnnularSectorExample(m.Scene):
+ def construct(self) -> None:
+ sectors = m.VGroup(
+ m.AnnularSector(),
+ m.AnnularSector(1.5, 2, angle=m.PI, color=m.BLUE),
+ m.AnnularSector(
+ 0.5, 2, angle=-3 * m.PI / 2, start_angle=m.PI, color=m.YELLOW
+ ),
+ ).arrange(buff=1)
+ self.add(sectors)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0, "color": WHITE}
+
+ def __init__(
+ self,
+ inner_radius: float = 1,
+ outer_radius: float = 2,
+ angle: float = TAU / 4,
+ start_angle: float = 0,
+ **kwargs: Unpack[ArcOptions],
+ ) -> None:
+ self.inner_radius = inner_radius
+ self.outer_radius = outer_radius
+ super().__init__(start_angle=start_angle, angle=angle, **kwargs)
+
+ def generate_points(self) -> Self:
+ arc = _unit_arc(self.start_angle, self.angle, 9)
+ inner = arc * self.inner_radius + self.arc_center
+ outer = arc[::-1] * self.outer_radius + self.arc_center
+ self.append_points(inner)
+ self.add_line_to(outer[0])
+ self.append_points(outer)
+ self.add_line_to(inner[0])
+ return self
+
+
+class Sector(AnnularSector):
+ """A sector of a disc, a slice of pie: the region between two radii and the arc
+ joining them; white and filled, without an outline, unless styled.
+
+ Args:
+ radius: Its radius, in scene units.
+ **kwargs: [Sector keywords][manimgx.mobjects.shapes.SectorOptions]: its
+ angles (a quarter turn from the positive x-axis unless given), style and
+ center; `num_components` has no effect.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class SectorExample(m.Scene):
+ def construct(self) -> None:
+ sectors = m.VGroup(
+ m.Sector(radius=2),
+ m.Sector(radius=2, angle=m.PI / 3, start_angle=m.PI, color=m.BLUE),
+ m.Sector(radius=2, angle=-5 * m.PI / 3, color=m.YELLOW),
+ ).arrange(buff=1)
+ self.add(sectors)
+ ```
+ """
+
+ def __init__(self, radius: float = 1, **kwargs: Unpack[SectorOptions]) -> None:
+ super().__init__(inner_radius=0, outer_radius=radius, **kwargs)
+
+
+class Annulus(Circle):
+ """A ring: the region between two circles of one center; white and filled, without
+ an outline, unless styled.
+
+ The inner circle runs clockwise, the other way around from the outer one, so it is
+ a hole in the fill.
+
+ Args:
+ inner_radius: The inner circle's radius, in scene units.
+ outer_radius: The outer circle's radius, in scene units.
+ mark_paths_closed: Accepted for Manim compatibility; ignored.
+ **kwargs: [Arc keywords][manimgx.mobjects.shapes.ArcOptions];
+ `num_components` has no effect.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class AnnulusExample(m.Scene):
+ def construct(self) -> None:
+ rings = m.VGroup(
+ m.Annulus(),
+ m.Annulus(inner_radius=1.5, outer_radius=2, color=m.BLUE),
+ m.Annulus(inner_radius=0.5, outer_radius=1.5, color=m.YELLOW),
+ ).arrange(buff=1)
+ self.add(rings)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0, "color": WHITE}
+
+ def __init__(
+ self,
+ inner_radius: float = 1,
+ outer_radius: float = 2,
+ mark_paths_closed: bool = False,
+ **kwargs: Unpack[ArcOptions],
+ ) -> None:
+ self.mark_paths_closed = mark_paths_closed
+ self.inner_radius = inner_radius
+ self.outer_radius = outer_radius
+ super().__init__(**kwargs)
+
+ def generate_points(self) -> Self:
+ self.radius = self.outer_radius
+ arc = _unit_arc(0, TAU, 9)
+ self.append_points(arc * self.outer_radius)
+ self.append_points(arc[::-1] * self.inner_radius)
+ self.shift(self.arc_center)
+ return self
+
+
+class CubicBezier(VMobject):
+ """A cubic Bézier curve: from one anchor to another, pulled toward two handles;
+ white unless styled.
+
+ The curve leaves its start heading toward `start_handle` and comes into its end
+ from the direction of `end_handle`; the farther a handle, the longer the curve
+ keeps to its direction. It passes through neither handle.
+
+ Args:
+ start_anchor: Where the curve starts.
+ start_handle: The handle of its start.
+ end_handle: The handle of its end.
+ end_anchor: Where the curve ends.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class CubicBezierExample(m.Scene):
+ def construct(self) -> None:
+ start, end = [-5, -2, 0], [5, -2, 0]
+ handle1, handle2 = [-3, 3, 0], [6, 3, 0]
+ curve = m.CubicBezier(start, handle1, handle2, end, color=m.YELLOW)
+ levers = m.VGroup(m.Line(start, handle1), m.Line(end, handle2))
+ levers.set_stroke(m.GREY, width=2)
+ anchors = m.VGroup(m.Dot(start), m.Dot(end)).set_color(m.BLUE)
+ handles = m.VGroup(m.Dot(handle1), m.Dot(handle2)).set_color(m.RED)
+ self.add(levers, anchors, handles)
+ self.play(m.Create(curve, run_time=2))
+ ```
+ """
+
+ def __init__(
+ self,
+ start_anchor: Point3DLike,
+ start_handle: Point3DLike,
+ end_handle: Point3DLike,
+ end_anchor: Point3DLike,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ super().__init__(**kwargs)
+ self.add_cubic_bezier_curve(start_anchor, start_handle, end_handle, end_anchor)
+
+
+class ArcPolygon(VMobject):
+ """A polygon whose sides are arcs: an [ArcBetweenPoints][manimgx.ArcBetweenPoints]
+ from each vertex to the next, and from the last back to the first; white unless
+ styled.
+
+ Going around the vertices counterclockwise, arcs of a positive angle bulge out, and
+ arcs of a negative one bend in. Its outline runs along the arcs, and is filled and
+ stroked in its style. The arcs are also its submobjects, its
+ [arcs][manimgx.ArcPolygon.arcs], drawn over its outline in their own style (white
+ unless `arc_config` styles them): to color the whole, style them too, as a family
+ method such as [set_color][manimgx.Mobject.set_color] does.
+
+ Args:
+ *vertices: The vertices, in order around it.
+ angle: The angle every arc turns through, in radians, unless `radius` or
+ `arc_config` is given.
+ radius: The radius of every arc, in scene units, in place of `angle`, unless
+ `arc_config` is given; None (or 0) to use `angle`.
+ arc_config: The arcs' [ArcBetweenPoints
+ keywords][manimgx.mobjects.shapes.ArcBetweenOptions], in place of
+ `angle` and `radius`: one set for every arc, or a list of one per side, the
+ first vertex's side first.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArcPolygonExample(m.Scene):
+ def construct(self) -> None:
+ a, b, c = [0, 0, 0], [2.5, 0, 0], [0, 2.5, 0]
+ sides = [{"radius": 2, "color": m.RED}, {"angle": 0}, {"angle": 1}]
+ shapes = m.VGroup(
+ m.ArcPolygon(a, b, c),
+ m.ArcPolygon(a, b, c, radius=2, fill_opacity=0.5).set_color(m.BLUE),
+ m.ArcPolygon(a, b, c, angle=-m.PI / 3).set_color(m.GREEN),
+ m.ArcPolygon(a, b, c, arc_config=sides),
+ ).arrange(buff=0.6)
+ self.play(m.Create(shapes, run_time=4))
+ ```
+ """
+
+ def __init__(
+ self,
+ *vertices: Point3DLike,
+ angle: float = PI / 4,
+ radius: float | None = None,
+ arc_config: ArcBetweenOptions | list[ArcBetweenOptions] | None = None,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ n = len(vertices)
+ point_pairs = [(vertices[k], vertices[(k + 1) % n]) for k in range(n)]
+ all_arc_configs: Iterable[ArcBetweenOptions]
+ if not arc_config:
+ config_: ArcBetweenOptions = (
+ {"radius": radius} if radius else {"angle": angle}
+ )
+ all_arc_configs = itertools.repeat(config_, len(point_pairs))
+ elif isinstance(arc_config, list):
+ assert len(arc_config) == n
+ all_arc_configs = arc_config
+ else:
+ all_arc_configs = itertools.repeat(arc_config, len(point_pairs))
+ arcs = [
+ ArcBetweenPoints(*pair, **conf)
+ for pair, conf in zip(point_pairs, all_arc_configs, strict=True)
+ ]
+ super().__init__(**kwargs)
+ self.add(*arcs)
+ for arc in arcs:
+ self.append_points(arc.points)
+ self.arcs = arcs
+ """The arcs, one per side, the first vertex's side first; they are also its
+ submobjects."""
+
+
+class ArcPolygonFromArcs(VMobject):
+ """A closed shape made of arcs: each arc in turn, joined to the next by a straight
+ line where they do not meet, and the last to the first; white unless styled.
+
+ Its outline is filled and stroked in its style. The arcs are also its submobjects,
+ its [arcs][manimgx.ArcPolygonFromArcs.arcs], drawn over its outline in their own
+ style: to color the whole, style them too, as a family method such as
+ [set_color][manimgx.Mobject.set_color] does.
+
+ Args:
+ *arcs: The arcs, in order around it: [Arc][manimgx.Arc]s, or
+ [ArcBetweenPoints][manimgx.ArcBetweenPoints].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArcPolygonFromArcsExample(m.Scene):
+ def construct(self) -> None:
+ a, b, c = [-5.5, -1.3, 0], [-2.5, -1.3, 0], [-4, 1.3, 0]
+ pairs = (a, b), (b, c), (c, a)
+ sides = [m.ArcBetweenPoints(p, q, radius=3) for p, q in pairs]
+ reuleaux = m.ArcPolygonFromArcs(*sides, fill_opacity=0.5)
+ left = m.Arc(start_angle=m.PI / 2, angle=m.PI).shift(1.5 * m.RIGHT)
+ right = m.Arc(start_angle=-m.PI / 2, angle=m.PI).shift(4.5 * m.RIGHT)
+ stadium = m.ArcPolygonFromArcs(left, right, fill_opacity=0.5)
+ reuleaux.set_color(m.BLUE)
+ stadium.set_color(m.GREEN)
+ self.play(m.Create(reuleaux), m.Create(stadium))
+ ```
+ """
+
+ def __init__(self, *arcs: Arc | ArcBetweenPoints, **kwargs: Unpack[Style]) -> None:
+ if not all(isinstance(m, (Arc, ArcBetweenPoints)) for m in arcs):
+ raise ValueError(
+ "All ArcPolygon submobjects must be of type Arc/ArcBetweenPoints"
+ )
+ super().__init__(**kwargs)
+ self.add(*arcs)
+ self.arcs = [*arcs]
+ """The arcs, in order; they are also its submobjects."""
+
+ for arc1, arc2 in adjacent_pairs(arcs):
+ self.append_points(arc1.points)
+ # the joining line is divided into curves about as long as the arc's, so
+ # the outline's points are spread evenly along it
+ line = Line(arc1.get_end(), arc2.get_start())
+ len_ratio = line.get_length() / arc1.get_arc_length()
+ if np.isnan(len_ratio) or np.isinf(len_ratio):
+ continue
+ line.insert_n_curves(int(arc1.get_num_curves() * len_ratio))
+ self.append_points(line.points)
+
+
+class Polygram(VMobject):
+ """A shape of straight sides through groups of vertices: each group a closed path,
+ from vertex to vertex and back to its first; blue unless styled.
+
+ The groups make one mobject, filled and stroked together. Where they overlap, the
+ fill counts how many times its paths wind around each point: a group inside another
+ that runs the other way around is a hole.
+
+ Vertices are copied before the corner hook runs. `add_points_as_corners` receives
+ one owned array per group, including the closing vertex; edits to the input vertices
+ do not change the finished shape.
+
+ Args:
+ *vertex_groups: The groups of vertices, each in order around its path.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class PolygramExample(m.Scene):
+ def construct(self) -> None:
+ r = np.sqrt(3)
+ hexagram = m.Polygram(
+ [[0, 2, 0], [-r, -1, 0], [r, -1, 0]],
+ [[-r, 1, 0], [0, -2, 0], [r, 1, 0]],
+ )
+ framed = m.Polygram(
+ [[-2, -2, 0], [2, -2, 0], [2, 2, 0], [-2, 2, 0]],
+ [[-1, -1, 0], [-1, 1, 0], [1, 1, 0], [1, -1, 0]],
+ color=m.YELLOW,
+ fill_opacity=0.5,
+ )
+ self.play(m.Create(m.VGroup(hexagram, framed).arrange(buff=2)))
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"color": BLUE}
+
+ def __init__(
+ self, *vertex_groups: Point3DLike_Array, **kwargs: Unpack[Style]
+ ) -> None:
+ super().__init__(**kwargs)
+ for vertices in vertex_groups:
+ first_vertex, *vertices = vertices
+ first_vertex = np.array(first_vertex)
+ self.start_new_path(first_vertex)
+ self.add_points_as_corners(np.array([*vertices, first_vertex]))
+
+ def get_vertices(self) -> Point3D_Array:
+ """The polygram's vertices, group after group: where each of its curves starts
+ (the arcs and sides too, once its corners are rounded).
+
+ Returns:
+ An (n, 3) array of points, in scene coordinates.
+ """
+ return self.get_start_anchors()
+
+ def get_vertex_groups(self) -> list[Point3D_Array]:
+ """The polygram's vertices, grouped by the closed paths they are on.
+
+ Returns:
+ A list of (n, 3) arrays of points, one per closed path.
+ """
+ vertex_groups = []
+ group = []
+ for start, end in zip(
+ self.get_start_anchors(), self.get_end_anchors(), strict=True
+ ):
+ group.append(start)
+ if self.consider_points_equals(end, group[0]):
+ vertex_groups.append(np.array(group))
+ group = []
+ return vertex_groups
+
+ def round_corners(
+ self,
+ radius: float | list[float] = 0.5,
+ evenly_distribute_anchors: bool = False,
+ components_per_rounded_corner: int = 2,
+ ) -> Self:
+ """Round the polygram's corners: replace each with an arc of `radius` tangent to
+ its two sides.
+
+ An arc touches each side at most halfway along it: a radius too large for a
+ corner is made smaller. A negative radius rounds a corner the other way,
+ cutting a concave arc into it.
+
+ Args:
+ radius: The arcs' radius, in scene units; or a list of radii, one per
+ corner of each group, from its second vertex's on (its first vertex's
+ last), repeated over the corners: its length must divide their number.
+ evenly_distribute_anchors: Whether to divide the straight sides into curves
+ about as long as the arcs' curves, so the outline's points are spread
+ evenly along it (a transform then moves them more evenly).
+ components_per_rounded_corner: How many anchor points each arc is drawn
+ through: 2 for one cubic Bézier curve.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class PolygramRoundCornersExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(2.8, color=m.YELLOW)
+ shapes = m.VGroup(
+ m.Star(outer_radius=1.5),
+ m.Star(outer_radius=1.5).round_corners(0.25),
+ square.round_corners([0.1, 0.4, 0.8, 1.2]),
+ m.Triangle(radius=1.6, color=m.GREEN).round_corners(-0.5),
+ ).arrange(buff=0.5)
+ self.add(shapes)
+ ```
+ """
+ if radius == 0:
+ return self
+ new_points: list[Point3D_Array] = []
+ for vertex_group in self.get_vertex_groups():
+ arcs = []
+ if isinstance(radius, (int, float)):
+ radius_list = [radius] * len(vertex_group)
+ else:
+ radius_list = radius * ceil(len(vertex_group) / len(radius))
+ for current_radius, (v1, v2, v3) in zip(
+ radius_list, adjacent_n_tuples(list(vertex_group), 3), strict=True
+ ):
+ vect1 = v2 - v1
+ vect2 = v3 - v2
+ unit_vect1 = normalize(vect1)
+ unit_vect2 = normalize(vect2)
+ angle = angle_between_vectors(vect1, vect2)
+ angle *= np.sign(current_radius)
+ cut_off_length = current_radius * np.tan(angle / 2)
+ max_cut_off = min(np.linalg.norm(vect1), np.linalg.norm(vect2)) / 2
+ cut_off_length = np.clip(cut_off_length, -max_cut_off, max_cut_off)
+ sign = np.sign(np.cross(vect1, vect2)[2])
+ arc = ArcBetweenPoints(
+ v2 - unit_vect1 * cut_off_length,
+ v2 + unit_vect2 * cut_off_length,
+ angle=sign * angle,
+ num_components=components_per_rounded_corner,
+ )
+ arcs.append(arc)
+ average_arc_length = 1.0
+ if evenly_distribute_anchors:
+ nonzero_length_arcs = [arc for arc in arcs if len(arc.points) > 4]
+ if len(nonzero_length_arcs) > 0:
+ total_arc_length = sum(
+ [arc.get_arc_length() for arc in nonzero_length_arcs]
+ )
+ num_curves = (
+ sum([len(arc.points) for arc in nonzero_length_arcs]) / 4
+ )
+ average_arc_length = total_arc_length / num_curves
+ arcs = [arcs[-1], *arcs[:-1]]
+
+ for arc1, arc2 in adjacent_pairs(arcs):
+ new_points.append(arc1.points)
+ line = Line(arc1.get_end(), arc2.get_start())
+ if evenly_distribute_anchors:
+ line.insert_n_curves(ceil(line.get_length() / average_arc_length))
+ new_points.append(line.points)
+ self.set_points(np.concatenate(new_points) if new_points else np.array([]))
+ return self
+
+
+class Polygon(Polygram):
+ """A polygon: straight sides from each vertex to the next, and from the last back to
+ the first; blue unless styled.
+
+ Args:
+ *vertices: The vertices, in order around it.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class PolygonExample(m.Scene):
+ def construct(self) -> None:
+ triangle = m.Polygon([-6, -2, 0], [-1.5, -2, 0], [-3.5, 2.5, 0])
+ arrowhead = m.Polygon(
+ [1, -2.5, 0],
+ [6, 0, 0],
+ [1, 2.5, 0],
+ [2.5, 0, 0],
+ color=m.YELLOW,
+ fill_opacity=0.5,
+ )
+ self.play(m.Create(triangle), m.Create(arrowhead))
+ ```
+ """
+
+ def __init__(self, *vertices: Point3DLike, **kwargs: Unpack[Style]) -> None:
+ super().__init__(vertices, **kwargs)
+
+
+class RegularPolygonOptions(Style, total=False):
+ """A [RegularPolygon][manimgx.RegularPolygon]'s keywords but its number of vertices,
+ for the classes that pass them on: its size and turn, with the style keywords."""
+
+ radius: float
+ """The radius of the circle its vertices are on, in scene units (default 1)."""
+ start_angle: float | None
+ """The angle of its first vertex, in radians, counterclockwise from the positive
+ x-axis (default None: a vertex straight up if their number is odd, to the right if
+ it is even)."""
+
+
+class RegularPolygram(Polygram):
+ """A regular star polygon: points evenly spaced on a circle, each joined to the one
+ `density` steps on; blue unless styled.
+
+ With a density of 1 it is a regular polygon; five points at density 2 make a
+ pentagram. When the number of points and the density share a factor, the points
+ make that many polygrams, each turned from the last: six points at density 2 make
+ two triangles, a hexagram.
+
+ Args:
+ num_vertices: How many points there are on the circle.
+ density: How many steps on each point is joined to: 1 for a polygon.
+ radius: The radius of the circle, in scene units.
+ start_angle: The angle of the first point, in radians, counterclockwise from
+ the positive x-axis; None for a point straight up if each polygram has an
+ odd number of points, to the right if even.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class RegularPolygramExample(m.Scene):
+ def construct(self) -> None:
+ polygrams = m.VGroup(
+ m.RegularPolygram(5, radius=2),
+ m.RegularPolygram(7, density=3, radius=2, color=m.YELLOW),
+ m.RegularPolygram(6, radius=2, color=m.GREEN),
+ ).arrange(buff=1)
+ self.play(m.Create(polygrams, run_time=3))
+ ```
+ """
+
+ def __init__(
+ self,
+ num_vertices: int,
+ *,
+ density: int = 2,
+ radius: float = 1,
+ start_angle: float | None = None,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ num_gons = np.gcd(num_vertices, density)
+ num_vertices //= num_gons
+ density //= num_gons
+
+ vertices, self.start_angle = regular_vertices(
+ num_vertices, radius=radius, start_angle=start_angle
+ )
+ order = np.arange(num_vertices) * (density % num_vertices) % num_vertices
+ vertex_groups = [vertices[order]]
+ for i in range(1, num_gons):
+ start_angle = self.start_angle + i / num_gons * TAU / num_vertices
+ vertices, _ = regular_vertices(
+ num_vertices, radius=radius, start_angle=start_angle
+ )
+ vertex_groups.append(vertices[order])
+ super().__init__(*vertex_groups, **kwargs)
+
+
+class RegularPolygon(RegularPolygram):
+ """A regular polygon: `n` vertices evenly spaced on a circle, joined in turn; blue
+ unless styled.
+
+ Args:
+ n: How many vertices, and sides, it has.
+ **kwargs: [Regular polygon
+ keywords][manimgx.mobjects.shapes.RegularPolygonOptions]: its
+ radius (1 unless given), its turn and its style.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class RegularPolygonExample(m.Scene):
+ def construct(self) -> None:
+ polygons = m.VGroup(
+ m.RegularPolygon(radius=1.5),
+ m.RegularPolygon(radius=1.5, start_angle=m.PI / 6, color=m.GREEN),
+ m.RegularPolygon(5, radius=1.5, color=m.YELLOW),
+ m.RegularPolygon(10, radius=1.5, color=m.RED),
+ ).arrange(buff=0.5)
+ self.add(polygons)
+ ```
+ """
+
+ def __init__(self, n: int = 6, **kwargs: Unpack[RegularPolygonOptions]) -> None:
+ super().__init__(n, density=1, **kwargs)
+
+
+class Star(Polygon):
+ """A star: `n` points on a circle, and between each two a vertex on a smaller
+ circle; blue unless styled.
+
+ Unless given, the inner radius is the one that makes the star the outline of the
+ [RegularPolygram][manimgx.RegularPolygram] of its `n` points at `density`: its
+ edges lie along the polygram's lines.
+
+ Args:
+ n: How many points it has.
+ outer_radius: The radius of the circle its points are on, in scene units.
+ inner_radius: The radius of the circle its inner vertices are on, in scene
+ units; None to set it by `density`.
+ density: Without `inner_radius`, the density of the polygram whose outline it
+ is: the higher, the thinner its points. It must be above 0 and below
+ `n / 2`.
+ start_angle: The angle of its first point, in radians, counterclockwise from
+ the positive x-axis (default a quarter turn: straight up); None for a
+ point straight up if `n` is odd, to the right if even.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class StarExample(m.Scene):
+ def construct(self) -> None:
+ stars = m.VGroup(
+ m.Star(outer_radius=1.5),
+ m.Star(7, outer_radius=1.5, color=m.YELLOW),
+ m.Star(7, outer_radius=1.5, density=3, color=m.RED),
+ m.Star(12, outer_radius=1.5, inner_radius=1, color=m.GREEN),
+ ).arrange(buff=0.5)
+ self.play(m.Create(stars, run_time=3))
+ ```
+ """
+
+ def __init__(
+ self,
+ n: int = 5,
+ *,
+ outer_radius: float = 1,
+ inner_radius: float | None = None,
+ density: int = 2,
+ start_angle: float | None = TAU / 4,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ inner_angle = TAU / (2 * n)
+ if (
+ inner_radius is None
+ ): # the radius that makes the star's edges lines through `density` points
+ if density <= 0 or density >= n / 2:
+ raise ValueError(
+ f"Incompatible density {density} for number of points {n}"
+ )
+ outer_angle = TAU * density / n
+ inverse_x = 1 - np.tan(inner_angle) * (
+ (np.cos(outer_angle) - 1) / np.sin(outer_angle)
+ )
+ inner_radius = float(outer_radius / (np.cos(inner_angle) * inverse_x))
+ outer_vertices, self.start_angle = regular_vertices(
+ n, radius=outer_radius, start_angle=start_angle
+ )
+ inner_vertices, _ = regular_vertices(
+ n, radius=inner_radius, start_angle=self.start_angle + inner_angle
+ )
+ vertices: list[npt.NDArray] = []
+ for pair in zip(outer_vertices, inner_vertices, strict=True):
+ vertices.extend(pair)
+ super().__init__(*vertices, **kwargs)
+
+
+class Triangle(RegularPolygon):
+ """An equilateral triangle, pointing up, its vertices on a circle of radius 1 unless
+ given another; blue unless styled.
+
+ Args:
+ **kwargs: [Regular polygon
+ keywords][manimgx.mobjects.shapes.RegularPolygonOptions]: its
+ radius, its turn and its style.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TriangleExample(m.Scene):
+ def construct(self) -> None:
+ triangles = m.VGroup(
+ m.Triangle(),
+ m.Triangle(radius=2, color=m.YELLOW, fill_opacity=0.5),
+ m.Triangle(radius=2, start_angle=-m.PI / 2, color=m.GREEN),
+ ).arrange(buff=1)
+ self.add(triangles)
+ ```
+ """
+
+ def __init__(self, **kwargs: Unpack[RegularPolygonOptions]) -> None:
+ super().__init__(n=3, **kwargs)
+
+
+class GridOptions(Style, total=False):
+ """A [Rectangle][manimgx.Rectangle]'s grid, with the style keywords (for the classes
+ that pass them on)."""
+
+ grid_xstep: float | None
+ """The distance between the vertical lines of its grid, from its left edge, in
+ scene units (default None: no vertical lines)."""
+ grid_ystep: float | None
+ """The distance between the horizontal lines of its grid, from its top edge, in
+ scene units (default None: no horizontal lines)."""
+ mark_paths_closed: bool
+ """Accepted for Manim compatibility; ignored."""
+
+
+class RectangleOptions(GridOptions, total=False):
+ """A [Rectangle][manimgx.Rectangle]'s keywords, for the classes that pass them on:
+ its size and its grid, with the style keywords."""
+
+ height: float
+ """Its height, in scene units (default 2)."""
+ width: float
+ """Its width, in scene units (default 4)."""
+
+
+class Rectangle(Polygon):
+ """A rectangle, 4 wide and 2 tall unless sized, centered at the origin; white unless
+ styled.
+
+ Its vertices run counterclockwise from its top right corner. With `grid_xstep` or
+ `grid_ystep` it is ruled into a grid: lines across it, its
+ [grid_lines][manimgx.Rectangle.grid_lines], in its `color`.
+
+ Args:
+ color: Its color, which may be given by position (`Rectangle(BLUE)`); None for
+ white.
+ height: Its height, in scene units.
+ width: Its width, in scene units.
+ grid_xstep: The distance between the vertical lines of its grid, from its left
+ edge, in scene units; None for none.
+ grid_ystep: The distance between the horizontal lines of its grid, from its top
+ edge, in scene units; None for none.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class RectangleExample(m.Scene):
+ def construct(self) -> None:
+ grid = m.Rectangle(
+ m.YELLOW, height=3, width=4, grid_xstep=1, grid_ystep=0.5
+ )
+ rectangles = m.VGroup(
+ m.Rectangle(),
+ m.Rectangle(m.BLUE, height=4, width=1.5, fill_opacity=0.5),
+ grid,
+ ).arrange(buff=1)
+ self.add(rectangles)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"color": WHITE}
+
+ def __init__(
+ self,
+ color: Colors | None = None,
+ height: float = 2.0,
+ width: float = 4.0,
+ grid_xstep: float | None = None,
+ grid_ystep: float | None = None,
+ **kwargs: Unpack[StyleBase],
+ ) -> None:
+ style = Style(**kwargs) if color is None else Style(**kwargs, color=color)
+ color = (style_defaults(type(self)) | style).get("color", WHITE)
+ super().__init__(UR, UL, DL, DR, **style)
+ self.stretch_to_fit_width(width)
+ self.stretch_to_fit_height(height)
+
+ v = self.get_vertices()
+ line_color = color or WHITE
+ self.grid_lines = VGroup()
+ """The lines of its grid: a group of the vertical lines, then one of the
+ horizontal lines, those it has; a submobject, unless it is empty (without a
+ grid)."""
+ if grid_xstep:
+ grid_xstep = abs(grid_xstep)
+ count = int(width / grid_xstep)
+ grid = VGroup(
+ *(
+ Line(
+ v[1] + i * grid_xstep * RIGHT,
+ v[1] + i * grid_xstep * RIGHT + height * DOWN,
+ color=line_color,
+ )
+ for i in range(1, count)
+ )
+ )
+ self.grid_lines.add(grid)
+ if grid_ystep:
+ grid_ystep = abs(grid_ystep)
+ count = int(height / grid_ystep)
+ grid = VGroup(
+ *(
+ Line(
+ v[1] + i * grid_ystep * DOWN,
+ v[1] + i * grid_ystep * DOWN + width * RIGHT,
+ color=line_color,
+ )
+ for i in range(1, count)
+ )
+ )
+ self.grid_lines.add(grid)
+ if self.grid_lines:
+ self.add(self.grid_lines)
+
+
+class ScreenOptions(Style, total=False):
+ """A [ScreenRectangle][manimgx.ScreenRectangle]'s keywords, for the rectangles that
+ pass them on: its proportions and its height, with the style keywords."""
+
+ aspect_ratio: float
+ """Its width over its height (default 16 / 9)."""
+ height: float
+ """Its height, in scene units (default 4)."""
+
+
+class ScreenRectangle(Rectangle):
+ """A rectangle with a screen's proportions, 16:9 and 4 tall unless given others,
+ centered at the origin; white unless styled.
+
+ Args:
+ aspect_ratio: Its width over its height.
+ height: Its height, in scene units.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ScreenRectangleExample(m.Scene):
+ def construct(self) -> None:
+ screens = m.VGroup(
+ m.ScreenRectangle(),
+ m.ScreenRectangle(aspect_ratio=4 / 3, height=3, color=m.BLUE),
+ ).arrange(buff=1)
+ self.add(screens)
+ ```
+ """
+
+ def __init__(
+ self,
+ aspect_ratio: float = 16.0 / 9.0,
+ height: float = 4,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ super().__init__(width=aspect_ratio * height, height=height, **kwargs)
+
+ @property
+ def aspect_ratio(self) -> float:
+ """The rectangle's width over its height. Set it to stretch the rectangle's
+ width to that proportion, about its center; its height stays."""
+ return self.width / self.height
+
+ @aspect_ratio.setter
+ def aspect_ratio(self, value: float) -> None:
+ self.stretch_to_fit_width(value * self.height)
+
+
+class FullScreenRectangle(ScreenRectangle):
+ """A screen rectangle as tall as the frame, centered at the origin: with the 16:9
+ proportions it has unless given others, the frame's own outline; white unless
+ styled.
+
+ Its height is the frame's (8 units unless configured otherwise), whatever `height`
+ is given.
+
+ Args:
+ **kwargs: [Screen rectangle keywords][manimgx.mobjects.shapes.ScreenOptions];
+ `height` has no effect.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class FullScreenRectangleExample(m.Scene):
+ def construct(self) -> None:
+ backdrop = m.FullScreenRectangle(
+ fill_color=m.DARK_BLUE, fill_opacity=1, stroke_color=m.YELLOW
+ )
+ self.add(backdrop, m.Text("A backdrop", font_size=96))
+ ```
+ """
+
+ def __init__(self, **kwargs: Unpack[ScreenOptions]) -> None:
+ super().__init__(**kwargs)
+ self.height = config.frame_height
+
+
+class Square(Rectangle):
+ """A square, 2 on a side unless sized, centered at the origin; white unless styled.
+
+ Args:
+ side_length: The length of its sides, in scene units.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class SquareExample(m.Scene):
+ def construct(self) -> None:
+ squares = m.VGroup(
+ m.Square(),
+ m.Square(3, color=m.BLUE, fill_opacity=0.5),
+ m.Square(4, color=m.YELLOW, grid_xstep=1, grid_ystep=1),
+ ).arrange(buff=1)
+ self.add(squares)
+ ```
+ """
+
+ def __init__(self, side_length: float = 2.0, **kwargs: Unpack[GridOptions]) -> None:
+ super().__init__(height=side_length, width=side_length, **kwargs)
+
+ @property
+ def side_length(self) -> float:
+ """The length of the square's sides, in scene units: the distance between its
+ first two vertices. Set it to scale the square to that side, about its
+ center."""
+ return float(np.linalg.norm(self.get_vertices()[0] - self.get_vertices()[1]))
+
+ @side_length.setter
+ def side_length(self, value: float) -> None:
+ self.scale(value / self.side_length)
+
+
+class RoundedRectangle(Rectangle):
+ """A rectangle with rounded corners, 4 wide and 2 tall unless sized; white unless
+ styled.
+
+ Args:
+ corner_radius: The radius of its corners, in scene units; or a list of radii
+ for its top left, bottom left, bottom right and top right corners, in that
+ order, repeated if there are one or two (see
+ [round_corners][manimgx.Polygram.round_corners]).
+ **kwargs: [Rectangle
+ keywords][manimgx.mobjects.shapes.RectangleOptions]: its size,
+ its grid and its style.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class RoundedRectangleExample(m.Scene):
+ def construct(self) -> None:
+ leaf = m.RoundedRectangle([0, 1.2, 0, 1.2], height=3, width=3)
+ rectangles = m.VGroup(
+ m.RoundedRectangle(),
+ m.RoundedRectangle(1.5, height=4, width=4, color=m.BLUE),
+ leaf.set_color(m.YELLOW),
+ ).arrange(buff=1)
+ self.add(rectangles)
+ ```
+ """
+
+ def __init__(
+ self,
+ corner_radius: float | list[float] = 0.5,
+ **kwargs: Unpack[RectangleOptions],
+ ) -> None:
+ super().__init__(**kwargs)
+ self.corner_radius = corner_radius
+ self.round_corners(self.corner_radius)
+
+
+class Cutout(VMobject):
+ """A shape with holes cut out of it: the main shape's outline, with the other
+ shapes' outlines as holes; white unless styled.
+
+ Each hole's path runs the other way around from the main shape's, so the fill
+ leaves it out: the shapes given as holes are turned to run that way, in place. Only
+ the shapes' own paths are used, not their submobjects', and the cutout has a style
+ of its own.
+
+ Args:
+ main_shape: The shape to cut the holes out of.
+ *mobjects: The shapes of the holes, inside it.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class CutoutExample(m.Scene):
+ def construct(self) -> None:
+ holes = [
+ m.Circle(0.7).shift(1.3 * m.UL),
+ m.Square(1.4).shift(1.3 * m.UR),
+ m.Triangle(radius=0.8).shift(1.3 * m.DL),
+ m.Star(outer_radius=0.8).shift(1.3 * m.DR),
+ ]
+ card = m.Cutout(m.Square(5), *holes, color=m.BLUE, fill_opacity=1)
+ behind = m.Circle(radius=2.2, color=m.YELLOW, fill_opacity=1)
+ self.add(behind, card)
+ ```
+ """
+
+ def __init__(
+ self, main_shape: VMobject, *mobjects: VMobject, **kwargs: Unpack[Style]
+ ) -> None:
+ super().__init__(**kwargs)
+ self.append_points(main_shape.points)
+ sub_direction: Literal["CCW", "CW"] = (
+ "CCW" if main_shape.get_direction() == "CW" else "CW"
+ )
+ for mobject in mobjects:
+ self.append_points(mobject.force_direction(sub_direction).points)
+
+
+class ConvexHull(Polygram):
+ """The convex hull of points: the smallest convex polygon around them all, its
+ vertices among them; blue unless styled.
+
+ It is found in the plane of the screen: the points' z coordinates are ignored.
+
+ Args:
+ *points: The points: at least three, not all on one line.
+ tolerance: How far outside the hull a point may be and still not be made a
+ vertex of it, in scene units.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class ConvexHullExample(m.Scene):
+ def construct(self) -> None:
+ points = np.random.default_rng(7).uniform(-3, 3, (20, 3)) * [1.5, 1, 0]
+ hull = m.ConvexHull(*points, color=m.YELLOW, fill_opacity=0.3)
+ self.add(hull, *(m.Dot(point, radius=0.1) for point in points))
+ ```
+ """
+
+ def __init__(
+ self, *points: Point3DLike, tolerance: float = 1e-05, **kwargs: Unpack[Style]
+ ) -> None:
+ array = np.array(points)[:, :2]
+ hull = QuickHull(tolerance)
+ hull.build(array)
+ facets = set(hull.facets) - hull.removed
+ facet = facets.pop()
+ subfacets = list(facet.subfacets)
+ while len(subfacets) <= len(facets):
+ sf = subfacets[-1]
+ (facet,) = hull.neighbors[sf] - {facet}
+ (sf,) = facet.subfacets - {sf}
+ subfacets.append(sf)
+ coordinates = np.vstack([sf.coordinates for sf in subfacets])
+ vertices = np.hstack((coordinates, np.zeros((len(coordinates), 1))))
+ super().__init__(vertices, **kwargs)
+
+
+class ArrowTip(VMobject):
+ """The base of arrow tips: a small shape with two points of its own, its
+ [tip_point][manimgx.ArrowTip.tip_point], where the path it ends points to, and its
+ [base][manimgx.ArrowTip.base], where the path stops.
+
+ A path makes its tip as `tip_shape(length=…, **style)` (see
+ [add_tip][manimgx.TipableVMobject.add_tip]), then turns and moves it into place: the
+ tip is what its class makes at that length. It is not made itself: its subclasses
+ are the tips. To make a tip of your own, subclass it and a shape, made at the length
+ given: the shape's first point is the tip point, and the point halfway around its
+ outline is the base. Both are read from its points, so they move with it; a
+ subclass that names other points of its shape does so as properties, never stored.
+
+ Args:
+ length: The tip's length, in scene units.
+ """
+
+ @prototype
+ def __init__(
+ self, length: float = DEFAULT_ARROW_TIP_LENGTH, **kwargs: Unpack[Style]
+ ) -> None:
+ raise NotImplementedError("Has to be implemented in inheriting subclasses.")
+
+ @property
+ def base(self) -> Point3D:
+ """The point where the path meets the tip, and stops: halfway around the tip's
+ outline from its tip point."""
+ return self.point_from_proportion(0.5)
+
+ @property
+ def tip_point(self) -> Point3D:
+ """The tip's point, where the path points to: the first point of its
+ outline."""
+ tip_point: Point3D = self.points[0]
+ return tip_point
+
+ @property
+ def vector(self) -> Vector3D:
+ """The vector from the tip's base to its tip point: the way it points."""
+ return self.tip_point - self.base
+
+ @property
+ def tip_angle(self) -> float:
+ """The direction the tip points in: the angle of its
+ [vector][manimgx.ArrowTip.vector], in radians, counterclockwise from the
+ positive x-axis."""
+ return angle_of_vector(self.vector)
+
+ @property
+ def length(self) -> float:
+ """The tip's length, in scene units: the distance from its base to its tip
+ point."""
+ return float(np.linalg.norm(self.vector))
+
+
+class StealthTip(ArrowTip):
+ """A dart-shaped tip: a sharp point with two barbs swept back from it and a notch
+ between them, where the path stops; filled, with a stroke 3 wide.
+
+ Its length runs from its barbs to its point; the notch is 5/8 of the way back from
+ the point. It is half as long as the other tips unless given a length.
+
+ Args:
+ length: Its length, from its barbs to its point, in scene units (default
+ 0.175).
+ start_angle: Accepted for Manim compatibility; ignored.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class StealthTipExample(m.Scene):
+ def construct(self) -> None:
+ tip = m.StealthTip
+ a, b = 3 * m.LEFT, 3 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b, tip_shape=tip),
+ m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
+ m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
+ m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
+ ).arrange(m.DOWN, buff=0.8)
+ self.add(arrows)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 3}
+
+ @prototype
+ def __init__(
+ self,
+ length: float = DEFAULT_ARROW_TIP_LENGTH / 2,
+ start_angle: float = PI,
+ **kwargs: Unpack[Style],
+ ):
+ self.start_angle = start_angle
+ VMobject.__init__(self, **kwargs)
+ self.set_points_as_corners(
+ np.array([[2, 0, 0], [-1.2, 1.6, 0], [0, 0, 0], [-1.2, -1.6, 0], [2, 0, 0]])
+ )
+ self.scale(length / self.length)
+
+ @property
+ def length(self) -> float:
+ """The tip's whole length, in scene units: from its barbs to its point, 1.6
+ times the distance from its notch to its point."""
+ return float(np.linalg.norm(self.vector) * 1.6)
+
+
+class ArrowTriangleTip(ArrowTip, Triangle):
+ """A triangular tip, outlined: an isosceles triangle `length` long and `width` wide,
+ its outline 3 wide and not filled.
+
+ Args:
+ length: Its length, from its base to its point, in scene units.
+ width: Its width, across its base, in scene units.
+ start_angle: The direction its point faces as made, in radians (default PI:
+ left); a path turns the tip to point along itself.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowTriangleTipExample(m.Scene):
+ def construct(self) -> None:
+ tip = m.ArrowTriangleTip
+ a, b = 3 * m.LEFT, 3 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b, tip_shape=tip),
+ m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
+ m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
+ m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
+ ).arrange(m.DOWN, buff=0.8)
+ self.add(arrows)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 0.0, "stroke_width": 3}
+
+ @prototype
+ def __init__(
+ self,
+ length: float = DEFAULT_ARROW_TIP_LENGTH,
+ width: float = DEFAULT_ARROW_TIP_LENGTH,
+ start_angle: float = PI,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ Triangle.__init__(self, start_angle=start_angle, **kwargs)
+ self.width = width
+ self.stretch_to_fit_width(length)
+ self.stretch_to_fit_height(width)
+
+
+class ArrowTriangleFilledTip(ArrowTriangleTip):
+ """A triangular tip, filled and without an outline: the default tip of lines, arcs
+ and arrows.
+
+ Args:
+ length: Its length, from its base to its point, in scene units.
+ width: Its width, across its base, in scene units.
+ start_angle: The direction its point faces as made, in radians (default PI:
+ left); a path turns the tip to point along itself.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowTriangleFilledTipExample(m.Scene):
+ def construct(self) -> None:
+ tip = m.ArrowTriangleFilledTip
+ a, b = 3 * m.LEFT, 3 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b, tip_shape=tip),
+ m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
+ m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
+ m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
+ ).arrange(m.DOWN, buff=0.8)
+ self.add(arrows)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0}
+
+
+class ArrowCircleTip(ArrowTip, Circle):
+ """A round tip, outlined: a circle `length` across, from where the path stops to
+ where it ended; its outline 3 wide and not filled.
+
+ Args:
+ length: Its diameter, in scene units.
+ start_angle: Accepted for Manim compatibility; ignored.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowCircleTipExample(m.Scene):
+ def construct(self) -> None:
+ tip = m.ArrowCircleTip
+ a, b = 3 * m.LEFT, 3 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b, tip_shape=tip),
+ m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
+ m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
+ m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
+ ).arrange(m.DOWN, buff=0.8)
+ self.add(arrows)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 0.0, "stroke_width": 3}
+
+ @prototype
+ def __init__(
+ self,
+ length: float = DEFAULT_ARROW_TIP_LENGTH,
+ start_angle: float = PI,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self.start_angle = start_angle
+ Circle.__init__(self, **kwargs)
+ self.width = length
+ self.stretch_to_fit_height(length)
+
+
+class ArrowCircleFilledTip(ArrowCircleTip):
+ """A round tip, filled and without an outline: a disc `length` across, from where
+ the path stops to where it ended.
+
+ Args:
+ length: Its diameter, in scene units.
+ start_angle: Accepted for Manim compatibility; ignored.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowCircleFilledTipExample(m.Scene):
+ def construct(self) -> None:
+ tip = m.ArrowCircleFilledTip
+ a, b = 3 * m.LEFT, 3 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b, tip_shape=tip),
+ m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
+ m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
+ m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
+ ).arrange(m.DOWN, buff=0.8)
+ self.add(arrows)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0}
+
+
+class ArrowSquareTip(ArrowTip, Square):
+ """A square tip, outlined: a square `length` on a side, set on a corner, its
+ diagonal along the path from where the path stops to where it ended; its outline 3
+ wide and not filled.
+
+ Its [length][manimgx.ArrowTip.length] is that diagonal's.
+
+ Args:
+ length: The length of its sides, in scene units.
+ start_angle: Accepted for Manim compatibility; ignored.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowSquareTipExample(m.Scene):
+ def construct(self) -> None:
+ tip = m.ArrowSquareTip
+ a, b = 3 * m.LEFT, 3 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b, tip_shape=tip),
+ m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
+ m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
+ m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
+ ).arrange(m.DOWN, buff=0.8)
+ self.add(arrows)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 0.0, "stroke_width": 3}
+
+ @prototype
+ def __init__(
+ self,
+ length: float = DEFAULT_ARROW_TIP_LENGTH,
+ start_angle: float = PI,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self.start_angle = start_angle
+ Square.__init__(self, side_length=length, **kwargs)
+ self.width = length
+ self.stretch_to_fit_height(length)
+
+
+class ArrowSquareFilledTip(ArrowSquareTip):
+ """A square tip, filled and without an outline: a square `length` on a side, set on
+ a corner, its diagonal along the path from where the path stops to where it ended.
+
+ Its [length][manimgx.ArrowTip.length] is that diagonal's.
+
+ Args:
+ length: The length of its sides, in scene units.
+ start_angle: Accepted for Manim compatibility; ignored.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowSquareFilledTipExample(m.Scene):
+ def construct(self) -> None:
+ tip = m.ArrowSquareFilledTip
+ a, b = 3 * m.LEFT, 3 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b, tip_shape=tip),
+ m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
+ m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
+ m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
+ ).arrange(m.DOWN, buff=0.8)
+ self.add(arrows)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0}
+
+
+class ArcedBase(TippedBase, total=False):
+ """A line's bend, with the tip keywords and every style keyword but `color`."""
+
+ path_arc: float
+ """The angle the line bends through, in radians: 0 for straight; otherwise it is an
+ arc from its start to its end, turning counterclockwise if positive (bending right
+ on its way), clockwise if negative (default 0)."""
+
+
+class Arced(ArcedBase, Tipped, total=False):
+ """A line's bend, with the style and tip keywords (for the lines that set the buffer
+ themselves)."""
+
+
+class LineOptions(Arced, total=False):
+ """A [Line][manimgx.Line]'s keywords but its ends, for the classes that pass them
+ on: its buffer and its bend, with the style and tip keywords."""
+
+ buff: float
+ """How far the line stops short of each end, in scene units; a line shorter than
+ twice it keeps its ends (default 0)."""
+
+
+class DashedLineOptions(LineOptions, total=False):
+ """A [DashedLine][manimgx.DashedLine]'s keywords but its ends: its dashes, with the
+ line keywords."""
+
+ dash_length: float
+ """The length of each dash, in scene units: about it, as a whole number of dashes
+ spans the line (default 0.05)."""
+ dashed_ratio: float
+ """The fraction of the line the dashes cover, from 0 to 1; the rest is gaps
+ (default 0.5: dashes and gaps as long)."""
+
+
+class ArrowTipsBase(ArcedBase, total=False):
+ """An [Arrow][manimgx.Arrow]'s keywords but its ends, its buffer and its color (for
+ the methods that set those): its tip, how it shrinks when short, and its bend."""
+
+ max_tip_length_to_length_ratio: float
+ """The longest its tip may be, as a fraction of its length: a short arrow's tip is
+ shorter (default 0.25)."""
+ max_stroke_width_to_length_ratio: float
+ """The widest its stroke may be, in hundredths of a scene unit, per scene unit of
+ its length: a short arrow is thinner (default 5)."""
+ tip_shape: type[ArrowTip]
+ """The class of its tip (default
+ [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip])."""
+
+
+class ArrowTips(ArrowTipsBase, Tipped, total=False):
+ """An [Arrow][manimgx.Arrow]'s keywords but its ends and its buffer (for the arrows
+ that set it: vectors)."""
+
+
+class ArrowOptions(ArrowTips, total=False):
+ """An [Arrow][manimgx.Arrow]'s keywords but its ends, for the classes that pass them
+ on."""
+
+ buff: float
+ """How far the arrow stops short of each end, in scene units (default 0.25)."""
+
+
+class Line(TipableVMobject):
+ """A straight line from one point to another, white unless styled; or an arc
+ between them, bent through `path_arc`.
+
+ An end may be a mobject: the line then starts (or ends) at its point farthest
+ toward the other end (see [get_boundary_point][manimgx.Mobject.get_boundary_point]),
+ so a line between two shapes runs from outline to outline. The line is placed when
+ it is made, and does not follow the mobjects afterwards.
+
+ Args:
+ start: Where the line starts: a point, or a mobject.
+ end: Where it ends: a point, or a mobject.
+ buff: How far it stops short of each end, in scene units (along it, if bent);
+ a line shorter than twice it keeps its ends.
+ path_arc: The angle it bends through, in radians: 0 for straight; otherwise it
+ is an arc, turning counterclockwise if positive, bending right on its way
+ (see [ArcBetweenPoints][manimgx.ArcBetweenPoints]).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LineExample(m.Scene):
+ def construct(self) -> None:
+ straight = m.Line(4 * m.LEFT, 4 * m.RIGHT, color=m.BLUE)
+ bent = m.Line(4 * m.LEFT, 4 * m.RIGHT, path_arc=-m.PI / 3)
+ m.VGroup(straight, bent).arrange(m.DOWN, buff=1).shift(m.UP)
+ left = m.Circle(radius=1, color=m.GREEN).move_to([-4.5, -2, 0])
+ right = m.Circle(radius=0.5, color=m.RED).move_to([4.5, -2.5, 0])
+ link = m.Line(left, right, buff=0.2, color=m.YELLOW)
+ self.add(straight, bent, left, right, link)
+ ```
+ """
+
+ def __init__(
+ self,
+ start: Point3DLike | Mobject = LEFT,
+ end: Point3DLike | Mobject = RIGHT,
+ buff: float = 0,
+ path_arc: float = 0,
+ **kwargs: Unpack[Tipped],
+ ) -> None:
+ self.dim = 3
+ self.buff = buff
+ self.path_arc = path_arc
+ self._set_start_and_end_attrs(start, end)
+ super().__init__(**kwargs)
+
+ def generate_points(self) -> Self:
+ self.set_points_by_ends(
+ start=self.start, end=self.end, buff=self.buff, path_arc=self.path_arc
+ )
+ return self
+
+ def set_points_by_ends(
+ self,
+ start: Point3DLike | Mobject,
+ end: Point3DLike | Mobject,
+ buff: float = 0,
+ path_arc: float = 0,
+ ) -> Self:
+ """Rebuild the line between two ends, straight or bent.
+
+ Its tips, if it has any, stay where they are.
+
+ Args:
+ start: Where it starts: a point, or a mobject (see [Line][manimgx.Line]).
+ end: Where it ends: a point, or a mobject.
+ buff: How far it stops short of each end, in scene units.
+ path_arc: 0 for straight; otherwise the line is bent through its own
+ `path_arc` (see [set_path_arc][manimgx.Line.set_path_arc]).
+ """
+ self._set_start_and_end_attrs(start, end)
+ if path_arc:
+ arc = ArcBetweenPoints(self.start, self.end, angle=self.path_arc)
+ self.set_points(arc.points)
+ else:
+ self._geometry = segment(self.start, self.end)
+ self._account_for_buff(buff)
+ return self
+
+ def _account_for_buff(self, buff: float) -> None:
+ if buff <= 0:
+ return
+ length = self.get_length() if self.path_arc == 0 else self.get_arc_length()
+ if length < 2 * buff:
+ return
+ if self.path_arc == 0: # straight: the segment between the ends brought in
+ start, end = self.get_start_and_end()
+ inward = (end - start) * (buff / length)
+ self._geometry = segment(start + inward, end - inward)
+ return
+ buff_proportion = buff / length
+ self.pointwise_become_partial(self, buff_proportion, 1 - buff_proportion)
+
+ def _set_start_and_end_attrs(
+ self, start: Point3DLike | Mobject, end: Point3DLike | Mobject
+ ) -> None:
+ rough_start = self._pointify(start)
+ rough_end = self._pointify(end)
+ vect = normalize(rough_end - rough_start)
+ self.start = self._pointify(start, vect)
+ self.end = self._pointify(end, -vect)
+
+ def _pointify(
+ self, mob_or_point: Mobject | Point3DLike, direction: Vector3DLike | None = None
+ ) -> Point3D:
+ if isinstance(mob_or_point, Mobject):
+ mob = mob_or_point
+ if direction is None:
+ return mob.get_center()
+ else:
+ return mob.get_boundary_point(direction)
+ return np.array(mob_or_point)
+
+ def set_path_arc(self, new_value: float) -> Self:
+ """Bend the line through a new angle: rebuild it, straight or as an arc, between
+ the ends it was made with.
+
+ It is rebuilt where it was made (or last rebuilt), wherever it has moved since,
+ and keeps its buffer.
+
+ Args:
+ new_value: The angle, in radians: 0 for straight; otherwise an arc, turning
+ counterclockwise if positive.
+ """
+ self.path_arc = new_value
+ self.init_points()
+ return self
+
+ def put_start_and_end_on(self, start: Point3DLike, end: Point3DLike) -> Self:
+ """Move, turn and scale the line so it runs from `start` to `end`, tips
+ included; its shape stays, scaled in proportion (an arrow's tips keep their
+ size).
+
+ A line whose ends coincide is rebuilt between the new ends.
+
+ Args:
+ start: Where its start goes: its start tip's point, if it has one.
+ end: Where its end goes: its end tip's point, if it has one.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LinePutStartAndEndOnExample(m.Scene):
+ def construct(self) -> None:
+ a, b, c = [-4, -2, 0], [0, 2.5, 0], [4, -2, 0]
+ dots = m.VGroup(*(m.Dot(p, radius=0.12) for p in (a, b, c)))
+ line = m.Line(a, b, color=m.BLUE)
+ self.add(dots, line)
+ self.play(line.animate.put_start_and_end_on(b, c))
+ self.play(line.animate.put_start_and_end_on(c, a))
+ ```
+ """
+ curr_start, curr_end = self.get_start_and_end()
+ if np.all(curr_start == curr_end):
+ self.start = np.asarray(start)
+ self.end = np.asarray(end)
+ self.generate_points()
+ return super().put_start_and_end_on(start, end)
+
+ def get_vector(self) -> Vector3D:
+ """The vector from the line's start to its end, tips included.
+
+ Returns:
+ The vector, in scene units.
+ """
+ return self.get_end() - self.get_start()
+
+ def get_unit_vector(self) -> Vector3D:
+ """The line's direction: the unit vector from its start toward its end.
+
+ Returns:
+ A vector of length 1; zero for a line of no length.
+ """
+ return normalize(self.get_vector())
+
+ def get_angle(self) -> float:
+ """The line's angle: the direction from its start to its end, counterclockwise
+ from the positive x-axis.
+
+ Returns:
+ The angle, in radians, from -PI to PI.
+ """
+ return angle_of_vector(self.get_vector())
+
+ def get_projection(self, point: Point3DLike) -> Point3D:
+ """The point of the line nearest a point: the point's orthogonal projection onto
+ the line, extended past its ends.
+
+ Args:
+ point: The point to project.
+
+ Returns:
+ The point on the line, in scene coordinates.
+ """
+ start = self.get_start()
+ end = self.get_end()
+ unit_vect = normalize(end - start)
+ return start + float(np.dot(point - start, unit_vect)) * unit_vect
+
+ def get_slope(self) -> float:
+ """The line's slope: how far it rises for each unit it runs to the right, the
+ tangent of its [angle][manimgx.Line.get_angle].
+
+ Returns:
+ The slope; very large for a line nearly upright.
+ """
+ return float(np.tan(self.get_angle()))
+
+ def set_angle(self, angle: float, about_point: Point3DLike | None = None) -> Self:
+ """Turn the line so its [angle][manimgx.Line.get_angle] is `angle`: about its
+ start, unless given another point.
+
+ Args:
+ angle: The new angle, in radians, counterclockwise from the positive x-axis.
+ about_point: The point it turns about; None for its start.
+ """
+ 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: float) -> Self:
+ """Scale the line about its center to a length, tips included (an arrow's tips
+ keep their size).
+
+ Args:
+ length: The new length, from its start to its end, in scene units.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class LineSetLengthExample(m.Scene):
+ def construct(self) -> None:
+ line = m.Line(m.LEFT, m.RIGHT, color=m.BLUE).shift(m.UP)
+ arrow = m.Arrow(m.LEFT, m.RIGHT, color=m.YELLOW).shift(m.DOWN)
+ self.add(line, arrow)
+ self.play(line.animate.set_length(10), arrow.animate.set_length(10))
+ self.play(line.animate.set_length(4), arrow.animate.set_length(4))
+ ```
+ """
+ scale_factor: float = length / self.get_length()
+ return self.scale(scale_factor)
+
+
+class CurvesAsSubmobjects(VGroup[VMobject]):
+ """A path split into its curves: a group of one path per curve, each styled as the
+ path is.
+
+ Each part can then be styled or animated on its own: a gradient across the parts
+ colors the path along its length. Only the path's own curves are taken, not its
+ submobjects'.
+
+ Args:
+ vmobject: The path to split.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself: as it
+ has no points, they do not restyle its parts, which take the path's style.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class CurvesAsSubmobjectsExample(m.Scene):
+ def construct(self) -> None:
+ curve = m.ParametricFunction(
+ lambda t: [2 * t, 2 * np.sin(t), 0], t_range=(-3, 3, 0.1)
+ )
+ parts = m.CurvesAsSubmobjects(curve.set_stroke(width=12))
+ parts.set_color_by_gradient(m.BLUE, m.YELLOW, m.RED)
+ self.play(m.Create(parts, run_time=2))
+ ```
+ """
+
+ def __init__(self, vmobject: VMobject, **kwargs: Unpack[Style]) -> None:
+ super().__init__(**kwargs)
+ for tup in vmobject.get_cubic_bezier_tuples():
+ part = VMobject()
+ part.set_points(tup)
+ part.match_style(vmobject)
+ self.add(part)
+
+
+def dash_pattern(
+ n: int, ratio: float, offset: float, closed: bool
+) -> tuple[float, float, float]:
+ """CE's dashes as a periodic window over the path (period, duty, phase — fractions of it): an
+ open path starts and ends with a dash; a closed one repeats every 1/n."""
+ dash = ratio / n
+ void = (
+ (1 - ratio) / n if closed else (1 - ratio if n == 1 else (1 - ratio) / (n - 1))
+ )
+ period = dash + void
+ return period, dash / period, offset % 1 * period
+
+
+def _even(vmobject: VMobject) -> bool:
+ """Whether a path's curves are all one length (so its parameter measures its length: a
+ dash window over it has equal dashes)."""
+ lengths = vmobject._geometry.curve_lengths()
+ return len(lengths) > 0 and float(np.ptp(lengths)) <= 1e-3 * float(lengths.max())
+
+
+class DashedVMobject(VMobject):
+ """A path drawn in dashes: evenly spaced dashes along another path, in its style.
+
+ An open path starts and ends with a dash; a closed one has as many gaps as dashes,
+ all the way around. Each dash ends as the path's `cap_style` says, and an arrow's
+ tips are drawn whole.
+
+ Args:
+ vmobject: The path to draw in dashes.
+ num_dashes: How many dashes; 0 draws none.
+ dashed_ratio: The fraction of the path the dashes cover, from 0 to 1; the gaps
+ take the rest.
+ dash_offset: How far the dashes are moved along the path, toward its end, as a
+ fraction of a dash and the gap after it.
+ equal_lengths: Whether the dashes are equally long; if False they are equal
+ stretches of the path's parameter, longer where the path runs faster.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style]; the dashes take the path's
+ paint over them.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class DashedVMobjectExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=1.5, color=m.BLUE, stroke_width=6)
+ square = m.Square(side_length=3, color=m.GREEN, stroke_width=6)
+ arc = m.Arc(radius=2, angle=m.PI, color=m.YELLOW, stroke_width=6)
+ shapes = m.VGroup(
+ m.DashedVMobject(circle, num_dashes=12),
+ m.DashedVMobject(square, num_dashes=16, dashed_ratio=0.7),
+ m.DashedVMobject(arc, num_dashes=7, dashed_ratio=0.3),
+ ).arrange(buff=1)
+ self.play(m.Create(shapes, run_time=2))
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"color": WHITE}
+
+ def __init__(
+ self,
+ vmobject: VMobject,
+ num_dashes: int = 15,
+ dashed_ratio: float = 0.5,
+ dash_offset: float = 0,
+ equal_lengths: bool = True,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self.dashed_ratio = dashed_ratio
+ self.num_dashes = num_dashes
+ super().__init__(**kwargs)
+ base = vmobject
+
+ tips = base.get_tips().submobjects if isinstance(base, TipableVMobject) else []
+ whole = all(any(m is t for t in tips) for m in base.submobjects)
+ # the path itself, drawn in dashes (a window over it; its tips drawn whole)
+ if (
+ num_dashes > 0
+ and whole
+ and base.has_points()
+ and (not equal_lengths or _even(base))
+ ):
+ self._geometry = base._geometry
+ self.match_style(base, family=False)
+ self.paint = self.paint.but(
+ dash=dash_pattern(
+ num_dashes, dashed_ratio, dash_offset, base.is_closed()
+ )
+ )
+ self.add(*(tip.copy() for tip in tips))
+ return
+ vmobject = base.copy()
+
+ tips = vmobject.pop_tips() if isinstance(vmobject, TipableVMobject) else None
+ r, n = dashed_ratio, num_dashes
+ if n > 0:
+ closed = vmobject.is_closed()
+ dash_len = r / n
+ void_len = (
+ (1 - r) / n if closed else (1 - r if n == 1 else (1 - r) / (n - 1))
+ )
+ period = dash_len + void_len
+ phase = dash_offset % 1 * period
+ pattern_len = 1 if closed else 1 + void_len
+ starts = [(i * period + phase) % pattern_len for i in range(n)]
+ ends = [(i * period + dash_len + phase) % pattern_len for i in range(n)]
+ if not closed:
+ if ends[-1] > 1 and starts[-1] > 1:
+ ends.pop()
+ starts.pop()
+ elif ends[-1] < dash_len:
+ if starts[-1] < 1:
+ starts.append(0)
+ ends.append(ends[-1])
+ ends[-2] = 1
+ else:
+ starts[-1] = 0
+ elif starts[-1] > 1 - dash_len:
+ ends[-1] = 1
+ if equal_lengths:
+ lengths = np.cumsum(
+ np.r_[0.0, vmobject._geometry.piece_lengths().ravel()]
+ )
+ refs = np.linspace(0, 1, lengths.size)
+ total = lengths[-1]
+ self.add(
+ *(
+ vmobject.get_subcurve(
+ np.interp(s * total, lengths, refs),
+ np.interp(e * total, lengths, refs),
+ )
+ for s, e in zip(starts, ends, strict=True)
+ )
+ )
+ else:
+ self.add(
+ *(
+ vmobject.get_subcurve(s, e)
+ for s, e in zip(starts, ends, strict=True)
+ )
+ )
+ self.match_style(base, family=False)
+ if tips is not None and tips.submobjects:
+ self.add(*tips.submobjects)
+
+
+class DashedLine(Line):
+ """A line drawn in dashes, white unless styled.
+
+ The dashes are the line's stroke drawn in pieces: a whole number of them, at least
+ two, spread evenly from end to end, each about `dash_length` long, each ended as
+ the line's `cap_style` says. It stays one path, placed, bent and tipped as a
+ [Line][manimgx.Line] is: its start, end and handles are the line's. Its dashes are
+ counted when it is made, and scale with it.
+
+ Args:
+ start: Where the line starts: a point, or a mobject (see [Line][manimgx.Line]).
+ end: Where it ends: a point, or a mobject.
+ buff: How far it stops short of each end, in scene units.
+ path_arc: The angle it bends through, in radians: 0 for straight.
+ dash_length: The length of each dash, in scene units (default 0.05): about it,
+ as a whole number of dashes spans the line.
+ dashed_ratio: The fraction of the line the dashes cover, from 0 to 1; the rest
+ is gaps.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class DashedLineExample(m.Scene):
+ def construct(self) -> None:
+ start, end = 5 * m.LEFT, 5 * m.RIGHT
+ lines = m.VGroup(
+ m.DashedLine(start, end),
+ m.DashedLine(start, end, dash_length=0.4, color=m.BLUE),
+ m.DashedLine(start, end, dash_length=0.4, dashed_ratio=0.2),
+ m.DashedLine(start, end, path_arc=m.PI / 4, color=m.YELLOW),
+ ).arrange(m.DOWN, buff=1)
+ lines[2].set_color(m.GREEN)
+ self.add(lines)
+ ```
+ """
+
+ def __init__(
+ self,
+ start: Point3DLike | Mobject = LEFT,
+ end: Point3DLike | Mobject = RIGHT,
+ buff: float = 0,
+ path_arc: float = 0,
+ *,
+ dash_length: float = DEFAULT_DASH_LENGTH,
+ dashed_ratio: float = 0.5,
+ **kwargs: Unpack[Tipped],
+ ) -> None:
+ self.dash_length = dash_length
+ self.dashed_ratio = dashed_ratio
+ super().__init__(start, end, buff, path_arc, **kwargs)
+ self.paint = self.paint.but( # a line drawn in dashes: one path, a dash window
+ dash=dash_pattern(self._calculate_num_dashes(), dashed_ratio, 0, False)
+ )
+
+ def _calculate_num_dashes(self) -> int:
+ return max(
+ 2, int(np.ceil(self.get_length() / self.dash_length * self.dashed_ratio))
+ )
+
+
+class TangentLine(Line):
+ """A line tangent to a path at a point along it, `length` long and centered on the
+ point; white unless styled.
+
+ Its direction is that of the chord between the points `d_alpha` before and after
+ the point.
+
+ Args:
+ vmob: The path.
+ alpha: Where along the path, as a proportion of its length: 0 at its start, 1
+ at its end.
+ length: The line's length, in scene units.
+ d_alpha: The proportion of the path's length before and after the point whose
+ chord sets the direction.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TangentLineExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=2.5, color=m.BLUE)
+ self.add(circle)
+ for alpha in (0, 0.2, 0.45, 0.7):
+ self.add(m.TangentLine(circle, alpha, length=4, color=m.YELLOW))
+ self.add(m.Dot(circle.point_from_proportion(alpha)))
+ ```
+ """
+
+ def __init__(
+ self,
+ vmob: VMobject,
+ alpha: float,
+ length: float = 1,
+ d_alpha: float = 1e-06,
+ **kwargs: Unpack[LineOptions],
+ ) -> None:
+ self.length = length
+ self.d_alpha = d_alpha
+ da = self.d_alpha
+ a1 = np.clip(alpha - da, 0, 1)
+ a2 = np.clip(alpha + da, 0, 1)
+ super().__init__(
+ vmob.point_from_proportion(a1), vmob.point_from_proportion(a2), **kwargs
+ )
+ self.scale(self.length / self.get_length())
+
+
+class Elbow(VMobject):
+ """The mark of a right angle: two segments `width` long meeting at a square corner;
+ white unless styled.
+
+ Made at the origin, it marks the right angle between the positive x and y axes:
+ from (0, `width`) across to its corner at (`width`, `width`), and down to
+ (`width`, 0); `angle` turns it about the origin. To mark the angle between two
+ lines, see [RightAngle][manimgx.RightAngle].
+
+ Args:
+ width: The length of each segment, in scene units.
+ angle: The angle it is turned through about the origin, in radians,
+ counterclockwise.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ElbowExample(m.Scene):
+ def construct(self) -> None:
+ elbows = m.VGroup(
+ m.Elbow(),
+ m.Elbow(width=1.5, color=m.BLUE),
+ m.Elbow(width=2, angle=5 * m.PI / 4, color=m.YELLOW),
+ ).arrange(buff=1.5)
+ self.add(elbows)
+ ```
+ """
+
+ def __init__(
+ self, width: float = 0.2, angle: float = 0, **kwargs: Unpack[Style]
+ ) -> None:
+ self.angle = angle
+ super().__init__(**kwargs)
+ self.set_points_as_corners(np.array([UP, UP + RIGHT, RIGHT]))
+ self.scale_to_fit_width(width, about_point=ORIGIN)
+ self.rotate(self.angle, about_point=ORIGIN)
+
+
+class Arrow(Line):
+ """An arrow: a line with a tip at its end, stopping `buff` short of the two points
+ it joins; white, with a stroke 6 wide, unless styled.
+
+ A short arrow is drawn in proportion: its tip is at most
+ `max_tip_length_to_length_ratio` of its length, and its stroke at most
+ `max_stroke_width_to_length_ratio` wide per unit of its length. Scaled, it keeps
+ its tip's size (see [scale][manimgx.Arrow.scale]).
+
+ Args:
+ start: Where the arrow starts: a point, or a mobject (see [Line][manimgx.Line]).
+ end: Where it points to: a point, or a mobject.
+ buff: How far it stops short of each end, in scene units (default 0.25): an
+ arrow between two mobjects leaves a gap at each.
+ max_tip_length_to_length_ratio: The longest its tip may be, as a fraction of
+ its length.
+ max_stroke_width_to_length_ratio: The widest its stroke may be, in hundredths
+ of a scene unit, per scene unit of its length.
+ tip_shape: The class of its tip.
+ **kwargs: [Style, tip and bend keywords][manimgx.mobjects.shapes.Arced]:
+ its `path_arc` bends it.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowExample(m.Scene):
+ def construct(self) -> None:
+ a, b = 2.5 * m.LEFT, 2.5 * m.RIGHT
+ arrows = m.VGroup(
+ m.Arrow(a, b),
+ m.Arrow(a, b, buff=0, color=m.BLUE),
+ m.Arrow(a, b, path_arc=-m.PI / 3, color=m.GREEN),
+ m.Arrow(a, b, tip_shape=m.StealthTip, color=m.YELLOW),
+ ).arrange(m.DOWN, buff=0.8, aligned_edge=m.LEFT)
+ shorts = m.VGroup()
+ for length in (0.5, 1, 2, 4, 6):
+ shorts.add(m.Arrow(m.ORIGIN, length * m.UP, buff=0, color=m.RED))
+ shorts.arrange(aligned_edge=m.DOWN)
+ self.add(m.VGroup(arrows, shorts).arrange(buff=1.5))
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"stroke_width": 6}
+
+ def __init__(
+ self,
+ start: Point3DLike | Mobject = LEFT,
+ end: Point3DLike | Mobject = RIGHT,
+ *,
+ buff: float = MED_SMALL_BUFF,
+ max_tip_length_to_length_ratio: float = 0.25,
+ max_stroke_width_to_length_ratio: float = 5,
+ tip_shape: type[ArrowTip] = ArrowTriangleFilledTip,
+ **kwargs: Unpack[Arced],
+ ) -> None:
+ self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio
+ self.max_stroke_width_to_length_ratio = max_stroke_width_to_length_ratio
+ super().__init__(start, end, buff=buff, **kwargs)
+ self.initial_stroke_width = self.stroke_width
+ self.add_tip(tip_shape=tip_shape)
+ self._set_stroke_width_from_length()
+
+ def scale(
+ self,
+ scale_factor: float | Vector3DLike,
+ scale_stroke: bool = False,
+ scale_tips: bool = False,
+ **kwargs: Unpack[Pivot],
+ ) -> Self:
+ """Scale the arrow, keeping its tips' size unless `scale_tips`.
+
+ The shaft is scaled, and the tips are put back on its ends. Then the shaft's
+ stroke width is set from its new length, as when the arrow was made: the smaller
+ of the width it was made with and `max_stroke_width_to_length_ratio` times its
+ length. An arrow of no length stays as it is.
+
+ Args:
+ scale_factor: The factor: one, or one per axis (see
+ [Mobject.scale][manimgx.Mobject.scale]).
+ scale_stroke: Whether stroke widths scale too; the shaft's is then set from
+ its length all the same.
+ scale_tips: Whether the tips scale with the shaft.
+ **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
+ fixed (default: its center).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ArrowScaleExample(m.Scene):
+ def construct(self) -> None:
+ kept = m.Arrow(m.LEFT, m.RIGHT, color=m.BLUE).shift(1.5 * m.UP)
+ scaled = m.Arrow(m.LEFT, m.RIGHT, color=m.YELLOW).shift(m.DOWN)
+ top = m.Text("scale(3)").move_to(2.8 * m.UP)
+ bottom = m.Text("scale(3, scale_tips=True)").move_to(2.5 * m.DOWN)
+ self.add(top, bottom, kept, scaled)
+ self.play(
+ kept.animate.scale(3), scaled.animate.scale(3, scale_tips=True)
+ )
+ ```
+ """
+ if self.get_length() == 0:
+ return self
+ if scale_tips:
+ super().scale(scale_factor, scale_stroke, **kwargs)
+ self._set_stroke_width_from_length()
+ return self
+ has_tip = self.has_tip()
+ order = list(self.submobjects) # the tips come back to their places among them
+ old_tips = self.pop_tips()
+ super().scale(scale_factor, scale_stroke, **kwargs)
+ self._set_stroke_width_from_length()
+ for tip, at_start in zip(
+ old_tips, (False, True) if has_tip else (True,), strict=False
+ ):
+ self.add_tip(tip=tip, at_start=at_start)
+ place = {id(m): i for i, m in enumerate(order)}
+ self.submobjects.sort(key=lambda m: place.get(id(m), len(order)))
+ return self
+
+ def get_normal_vector(self) -> Vector3D:
+ """The normal of the plane the arrow's tip lies in, from its first three
+ anchors.
+
+ Returns:
+ A unit vector: IN for an arrow in the plane of the screen.
+ """
+ p0, p1, p2 = self.tip.get_start_anchors()[:3]
+ return normalize(np.cross(p2 - p1, p1 - p0))
+
+ def reset_normal_vector(self) -> Self:
+ """Set the arrow's `normal_vector` to its
+ [tip's normal][manimgx.Arrow.get_normal_vector].
+
+ Kept for Manim compatibility: nothing reads `normal_vector`.
+ """
+ self.normal_vector = self.get_normal_vector()
+ return self
+
+ def get_default_tip_length(self) -> float:
+ """The length of the tips the arrow makes unless given one: its `tip_length`,
+ or `max_tip_length_to_length_ratio` times its length if that is shorter.
+
+ Returns:
+ The length, in scene units.
+ """
+ max_ratio = self.max_tip_length_to_length_ratio
+ return min(self.tip_length, max_ratio * self.get_length())
+
+ def _set_stroke_width_from_length(self) -> Self:
+ 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,
+ )
+ return self
+
+
+class Vector(Arrow):
+ """A vector: an arrow from the origin to a point; white unless styled.
+
+ Args:
+ direction: Where it points to, from the origin: two coordinates, or three.
+ buff: How far it stops short of the origin and of its end, in scene units.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VectorExample(m.Scene):
+ def construct(self) -> None:
+ vectors = m.VGroup(
+ m.Vector([2, 1], color=m.YELLOW),
+ m.Vector([-3, 2], color=m.BLUE),
+ m.Vector([1, -3, 0], color=m.GREEN),
+ )
+ self.add(m.NumberPlane(), vectors)
+ ```
+ """
+
+ def __init__(
+ self,
+ direction: Vector2DLike | Vector3DLike = RIGHT,
+ buff: float = 0,
+ **kwargs: Unpack[ArrowTips],
+ ) -> None:
+ self.buff = buff
+ end = np.asarray(direction, dtype=float)
+ if len(end) == 2:
+ end = np.hstack([end, 0])
+ super().__init__(ORIGIN, end, buff=buff, **kwargs)
+
+ def coordinate_label(
+ self,
+ integer_labels: bool = True,
+ n_dim: int = 2,
+ **kwargs: Unpack[MatrixOptions],
+ ) -> Matrix:
+ """Make a label of the vector's coordinates: a column matrix beside its tip.
+
+ The label, at 0.8 of a matrix's size, is placed 0.25 beyond the vector's end,
+ centered on it vertically: to its right if the vector points right (or straight
+ up or down), to its left otherwise. It is not added to the vector.
+
+ Args:
+ integer_labels: Whether to round the coordinates to integers.
+ n_dim: How many coordinates to show: 2 for x and y, 3 for z too.
+ **kwargs: [Matrix keywords][manimgx.mobjects.grid.MatrixOptions]; `color`
+ colors the whole label.
+
+ Returns:
+ A new matrix.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class VectorCoordinateLabelExample(m.Scene):
+ def construct(self) -> None:
+ right = m.Vector([3, 2], color=m.YELLOW)
+ left = m.Vector([-4, -2], color=m.BLUE)
+ self.add(m.NumberPlane(), right, left)
+ self.add(right.coordinate_label())
+ self.add(left.coordinate_label(color=m.BLUE))
+ ```
+ """
+ from manimgx.mobjects.grid import Matrix
+
+ vect = np.array(self.get_end())
+ if integer_labels:
+ vect = np.round(vect).astype(int)
+ vect = vect[:n_dim]
+ vect = vect.reshape((n_dim, 1))
+ color = kwargs.pop("color", None)
+ label = Matrix(vect, **kwargs)
+ label.scale(LARGE_BUFF - 0.2)
+ shift_dir = np.array(self.get_end())
+ if shift_dir[0] >= 0:
+ shift_dir -= label.get_left() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * LEFT
+ else:
+ shift_dir -= label.get_right() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * RIGHT
+ label.shift(shift_dir)
+ if color is not None:
+ label.set_color(color)
+ return label
+
+
+class DoubleArrow(Arrow):
+ """An arrow with a tip at each end; white, with a stroke 6 wide, unless styled.
+
+ Its tips and its stroke are sized from its length, tip to tip, as an
+ [Arrow][manimgx.Arrow]'s are.
+
+ Args:
+ start: Where it starts: a point, or a mobject (see [Line][manimgx.Line]).
+ end: Where it ends: a point, or a mobject.
+ tip_shape_start: The class of the tip at its start.
+ tip_shape_end: The class of the tip at its end; None for the `tip_shape`
+ keyword's, or else [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class DoubleArrowExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=2, color=m.BLUE).shift(3 * m.LEFT)
+ diameter = m.DoubleArrow(circle.get_left(), circle.get_right(), buff=0)
+ mixed = m.DoubleArrow(
+ m.RIGHT,
+ 6 * m.RIGHT,
+ tip_shape_start=m.ArrowCircleFilledTip,
+ tip_shape_end=m.StealthTip,
+ color=m.YELLOW,
+ )
+ self.add(circle, diameter, mixed)
+ ```
+ """
+
+ def __init__(
+ self,
+ start: Point3DLike | Mobject = LEFT,
+ end: Point3DLike | Mobject = RIGHT,
+ *,
+ tip_shape_start: type[ArrowTip] = ArrowTriangleFilledTip,
+ tip_shape_end: type[ArrowTip] | None = None,
+ **kwargs: Unpack[ArrowOptions],
+ ) -> None:
+ if tip_shape_end is not None:
+ kwargs["tip_shape"] = tip_shape_end
+ super().__init__(start, end, **kwargs)
+ self.add_tip(at_start=True, tip_shape=tip_shape_start)
+ self._set_stroke_width_from_length() # as an arrow's: by its length, tip to tip
+
+
+class AngleShape(Style, total=False):
+ """An [Angle][manimgx.Angle]'s keywords but its radius and its elbow (for right
+ angles, which set them): which angle it marks, and its dot, with the style
+ keywords."""
+
+ quadrant: AngleQuadrant
+ """Which way each side of the angle goes from the crossing: a sign for each line,
+ the first line's first; 1 along the line's direction (from its start toward its
+ end), -1 back toward its start (default (1, 1))."""
+ other_angle: bool
+ """Whether the arc runs clockwise from the first side to the second, instead of
+ counterclockwise: it then marks the rest of the full turn (default False)."""
+ dot: bool
+ """Whether to put a dot inside the arc, as a right angle is sometimes marked
+ (default False; an elbow has none)."""
+ dot_radius: float | None
+ """The dot's radius, in scene units (default None: a tenth of the arc's radius)."""
+ dot_distance: float
+ """How far the dot is from the crossing, as a fraction of the arc's radius (default
+ 0.55)."""
+ dot_color: ParsableManimColor
+ """The dot's color (default white)."""
+
+
+class AngleOptions(AngleShape, total=False):
+ """An [Angle][manimgx.Angle]'s keywords but its lines (for the methods that make
+ one)."""
+
+ radius: float | None
+ """The arc's radius, or the elbow's side, in scene units (default None: 0.4, or
+ for short lines two thirds of the distance from the crossing to the nearer of the
+ line ends the sides point to, when that is less than 0.6)."""
+ elbow: bool
+ """Whether to mark the angle with an elbow, two segments making a corner between
+ its sides, instead of an arc (default False)."""
+
+
+class Angle(VMobject):
+ """The mark of an angle between two lines: an arc about the point where they cross,
+ counterclockwise from a side along the first line to a side along the second; white
+ unless styled.
+
+ The lines are taken as infinite, so they need not reach the point where they cross.
+ From there, `quadrant` picks the way each side goes along its line, and
+ `other_angle` turns the arc clockwise instead, marking the rest of the full turn:
+ together they pick the angle marked, which may be more than half a turn. With
+ `elbow`, the mark is two segments instead, making a corner between the two sides,
+ as a right angle is marked. Parallel lines in the plane of the screen make an empty
+ mark, of value 0.
+
+ Args:
+ line1: The line the angle is measured from.
+ line2: The line it is measured to.
+ radius: The arc's radius, or the elbow's side, in scene units; None for 0.4, or
+ for short lines two thirds of the distance from the crossing to the nearer
+ of the line ends the sides point to, when that is less than 0.6.
+ quadrant: Which way each side goes from the crossing: a sign for each line,
+ `line1`'s first; 1 along the line's direction (from its start toward its
+ end), -1 back toward its start.
+ other_angle: Whether the arc runs clockwise from the first side to the second
+ instead, marking the rest of the full turn.
+ dot: Whether to put a dot inside the arc (an elbow has none).
+ dot_radius: The dot's radius, in scene units; None for a tenth of the arc's
+ radius.
+ dot_distance: How far the dot is from the crossing, as a fraction of the arc's
+ radius.
+ dot_color: The dot's color.
+ elbow: Whether to mark the angle with an elbow instead of an arc.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class AngleExample(m.Scene):
+ def construct(self) -> None:
+ line1 = m.Line(1.2 * m.LEFT, 1.2 * m.RIGHT)
+ line2 = m.Line(1.2 * m.DOWN, 1.2 * m.UP).rotate(-30 * m.DEGREES)
+ angles = [
+ m.Angle(line1, line2, color=m.YELLOW),
+ m.Angle(line1, line2, quadrant=(-1, 1), color=m.BLUE),
+ m.Angle(line1, line2, other_angle=True, color=m.GREEN),
+ m.Angle(line1, line2, dot=True, color=m.RED),
+ ]
+ labels = ["default", "quadrant=(-1, 1)", "other_angle=True", "dot=True"]
+ panels = m.VGroup()
+ for angle in angles:
+ panels.add(m.VGroup(line1.copy(), line2.copy(), angle))
+ panels.arrange(buff=1)
+ for panel, label in zip(panels, labels):
+ text = m.Text(label, font_size=24).next_to(panel, m.DOWN)
+ self.add(panel, text)
+ ```
+ """
+
+ def __init__(
+ self,
+ line1: Line,
+ line2: Line,
+ radius: float | None = None,
+ quadrant: AngleQuadrant = (1, 1),
+ other_angle: bool = False,
+ dot: bool = False,
+ dot_radius: float | None = None,
+ dot_distance: float = 0.55,
+ dot_color: ParsableManimColor = WHITE,
+ elbow: bool = False,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ super().__init__(**kwargs)
+ self.lines = (line1, line2)
+ self.quadrant = quadrant
+ self.dot_distance = dot_distance
+ self.elbow = elbow
+ try:
+ inter = line_intersection(
+ [line1.get_start(), line1.get_end()],
+ [line2.get_start(), line2.get_end()],
+ )
+ except ValueError:
+ lines_are_in_xy_plane = all(
+ point[2] == 0
+ for line in (line1, line2)
+ for point in (line.get_start(), line.get_end())
+ )
+ directions_are_parallel = (
+ np.cross(line1.get_vector(), line2.get_vector())[2] == 0
+ )
+ if not (lines_are_in_xy_plane and directions_are_parallel):
+ raise
+ self.angle_value = 0.0
+ return
+ if radius is None:
+ if quadrant[0] == 1:
+ dist_1 = np.linalg.norm(line1.get_end() - inter)
+ else:
+ dist_1 = np.linalg.norm(line1.get_start() - inter)
+ if quadrant[1] == 1:
+ dist_2 = np.linalg.norm(line2.get_end() - inter)
+ else:
+ dist_2 = np.linalg.norm(line2.get_start() - inter)
+ radius = (
+ float(2 / 3 * min(dist_1, dist_2)) if min(dist_1, dist_2) < 0.6 else 0.4
+ )
+ else:
+ self.radius = radius
+ anchor_angle_1 = inter + quadrant[0] * radius * line1.get_unit_vector()
+ anchor_angle_2 = inter + quadrant[1] * radius * line2.get_unit_vector()
+ if elbow:
+ anchor_middle = (
+ inter
+ + quadrant[0] * radius * line1.get_unit_vector()
+ + quadrant[1] * radius * line2.get_unit_vector()
+ )
+ angle_mobject: VMobject = Elbow(**kwargs)
+ angle_mobject.set_points_as_corners(
+ np.array([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)
+ if not other_angle:
+ start_angle = angle_1
+ if angle_2 > angle_1:
+ angle_fin = angle_2 - angle_1
+ else:
+ angle_fin = 2 * np.pi - (angle_1 - angle_2)
+ else:
+ start_angle = angle_1
+ if angle_2 < angle_1:
+ angle_fin = -angle_1 + angle_2
+ else:
+ angle_fin = -2 * np.pi + (angle_2 - angle_1)
+ self.angle_value = angle_fin
+ angle_mobject = Arc(
+ radius=radius,
+ angle=self.angle_value,
+ start_angle=start_angle,
+ arc_center=inter,
+ **kwargs,
+ )
+ if dot:
+ if dot_radius is None:
+ dot_radius = radius / 10
+ else:
+ self.dot_radius = dot_radius
+ right_dot = Dot(ORIGIN, radius=dot_radius, color=dot_color)
+ dot_anchor = (
+ inter
+ + (angle_mobject.get_center() - inter)
+ / np.linalg.norm(angle_mobject.get_center() - inter)
+ * radius
+ * dot_distance
+ )
+ right_dot.move_to(dot_anchor)
+ self.add(right_dot)
+ self.set_points(angle_mobject.points)
+
+ def get_lines(self) -> VGroup:
+ """The two lines the angle is between.
+
+ Returns:
+ A new group of the two lines, `line1` first.
+ """
+ return VGroup(*self.lines)
+
+ def get_value(self, degrees: bool = False) -> float:
+ """The size of the angle marked: counterclockwise from its first side to its
+ second, or clockwise, and negative, with `other_angle`.
+
+ An angle marked with an elbow has no value: asking for it raises an exception.
+
+ Args:
+ degrees: Whether to give it in degrees instead of radians.
+
+ Returns:
+ The angle, in radians (or degrees), from -TAU to TAU.
+ """
+ return self.angle_value / DEGREES if degrees else self.angle_value
+
+ @staticmethod
+ def from_three_points(
+ A: Point3DLike, B: Point3DLike, C: Point3DLike, **kwargs: Unpack[AngleOptions]
+ ) -> Angle:
+ """The mark of the angle ABC: at `B`, from the line toward `A` counterclockwise
+ to the line toward `C`.
+
+ Args:
+ A: A point on the first side.
+ B: The vertex.
+ C: A point on the second side.
+ **kwargs: [Angle keywords][manimgx.mobjects.shapes.AngleOptions].
+
+ Returns:
+ A new angle.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class AngleFromThreePointsExample(m.Scene):
+ def construct(self) -> None:
+ a, b, c = [-4, -2, 0], [3, -2, 0], [-1, 2.5, 0]
+ angles = m.VGroup(
+ m.Angle.from_three_points(b, a, c, radius=0.8, color=m.YELLOW),
+ m.Angle.from_three_points(c, b, a, radius=0.8, color=m.BLUE),
+ m.Angle.from_three_points(a, c, b, radius=0.8, color=m.GREEN),
+ )
+ self.add(m.Polygon(a, b, c, color=m.WHITE), angles)
+ ```
+ """
+ return Angle(Line(B, A), Line(B, C), **kwargs)
+
+
+class RightAngle(Angle):
+ """The mark of a right angle between two lines: an [Angle][manimgx.Angle] marked
+ with an elbow; white unless styled.
+
+ The lines need not be perpendicular: the elbow is then a corner of a
+ parallelogram.
+
+ Args:
+ line1: The first line.
+ line2: The second line.
+ length: The length of the elbow's sides, in scene units; None for 0.4, or less
+ for short lines (see [Angle][manimgx.Angle]).
+ **kwargs: [Angle keywords][manimgx.mobjects.shapes.AngleShape]; the dot
+ keywords have no effect.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class RightAngleExample(m.Scene):
+ def construct(self) -> None:
+ a, b, c = [-6, -2, 0], [-1, -2, 0], [-6, 2, 0]
+ triangle = m.Polygon(a, b, c, color=m.BLUE)
+ corner = m.RightAngle(m.Line(a, b), m.Line(a, c), color=m.YELLOW)
+ line1 = m.Line([1, -2, 0], [6, 3, 0])
+ line2 = m.Line([1, 3, 0], [6, -2, 0])
+ marks = m.VGroup(
+ m.RightAngle(line1, line2),
+ m.RightAngle(line1, line2, length=0.7, quadrant=(-1, -1)),
+ ).set_color(m.GREEN)
+ self.add(triangle, corner, line1, line2, marks)
+ ```
+ """
+
+ def __init__(
+ self,
+ line1: Line,
+ line2: Line,
+ length: float | None = None,
+ **kwargs: Unpack[AngleShape],
+ ) -> None:
+ super().__init__(line1, line2, radius=length, elbow=True, **kwargs)
+
+
+def adjacent_n_tuples[T](objects: Sequence[T], n: int) -> Iterator[tuple[T, ...]]:
+ """Each run of `n` items in a row, wrapping around at the end: for `[a, b, c]` and
+ 2, `(a, b)`, `(b, c)` and `(c, a)`.
+
+ Args:
+ objects: The items.
+ n: How many items each run has.
+
+ Returns:
+ The runs, as tuples, one starting at each item.
+ """
+ return zip(*(list(objects[k:]) + list(objects[:k]) for k in range(n)), strict=True)
+
+
+def adjacent_pairs[T](objects: Sequence[T]) -> Iterator[tuple[T, ...]]:
+ """Each item with the next, wrapping around at the end (see
+ [adjacent_n_tuples][manimgx.adjacent_n_tuples]).
+
+ Args:
+ objects: The items.
+
+ Returns:
+ The pairs, as tuples, one starting at each item.
+ """
+ return adjacent_n_tuples(objects, 2)
+
+
+if TYPE_CHECKING:
+ from pathops import Path as SkiaPath
+ from pathops import PathOp
+
+ from manimgx.typing import Point3D_Array
+
+
+def _combine(operation: PathOp, *vmobjects: VMobject) -> SkiaPath:
+ """Fold an operation over the operands' own outlines, left to right."""
+ paths = [_to_path(m.points, m.tolerance_for_point_equality) for m in vmobjects]
+ return reduce(lambda a, b: _pathops().op(a, b, operation), paths)
+
+
+class Union(VMobject):
+ """The union of shapes: the region any of them covers, as a new path; white unless
+ styled.
+
+ It is found from the shapes' own paths (not their submobjects'), each the region
+ its fill covers, in the plane of the screen: their z coordinates are dropped. The
+ shapes stay as they are.
+
+ Args:
+ *vmobjects: The shapes: at least two.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class UnionExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
+ circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
+ circle.shift(3 * m.LEFT + m.UP)
+ union = m.Union(square, circle, color=m.GREEN, fill_opacity=0.8)
+ self.add(square, circle, union.shift(7 * m.RIGHT))
+ ```
+ """
+
+ def __init__(self, *vmobjects: VMobject, **kwargs: Unpack[Style]) -> None:
+ if len(vmobjects) < 2:
+ raise ValueError("At least 2 mobjects needed for Union.")
+ super().__init__(**kwargs)
+ outpen = _pathops().Path()
+ _pathops().union(
+ [
+ _to_path(vmobject.points, vmobject.tolerance_for_point_equality)
+ for vmobject in vmobjects
+ ],
+ outpen.getPen(),
+ )
+ _append_path(self, outpen)
+
+
+class Difference(VMobject):
+ """The difference of two shapes: the region the first covers and the second does
+ not, as a new path; white unless styled.
+
+ It is found from the shapes' own paths (not their submobjects'), each the region
+ its fill covers, in the plane of the screen: their z coordinates are dropped. The
+ shapes stay as they are.
+
+ Args:
+ subject: The shape to take a part of.
+ clip: The shape whose region is left out of it.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class DifferenceExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
+ circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
+ circle.shift(3 * m.LEFT + m.UP)
+ cut = m.Difference(square, circle, color=m.GREEN, fill_opacity=0.8)
+ self.add(square, circle, cut.shift(7 * m.RIGHT))
+ ```
+ """
+
+ def __init__(
+ self, subject: VMobject, clip: VMobject, **kwargs: Unpack[Style]
+ ) -> None:
+ super().__init__(**kwargs)
+ _append_path(self, _combine(_pathops().PathOp.DIFFERENCE, subject, clip))
+
+
+class Intersection(VMobject):
+ """The intersection of shapes: the region all of them cover, as a new path; white
+ unless styled.
+
+ It is found from the shapes' own paths (not their submobjects'), each the region
+ its fill covers, in the plane of the screen: their z coordinates are dropped. The
+ shapes stay as they are.
+
+ Args:
+ *vmobjects: The shapes: at least two.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class IntersectionExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
+ circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
+ circle.shift(3 * m.LEFT + m.UP)
+ common = m.Intersection(square, circle, color=m.GREEN, fill_opacity=0.8)
+ self.add(square, circle, common.shift(7 * m.RIGHT))
+ ```
+ """
+
+ def __init__(self, *vmobjects: VMobject, **kwargs: Unpack[Style]) -> None:
+ if len(vmobjects) < 2:
+ raise ValueError("At least 2 mobjects needed for Intersection.")
+ super().__init__(**kwargs)
+ _append_path(self, _combine(_pathops().PathOp.INTERSECTION, *vmobjects))
+
+
+class Exclusion(VMobject):
+ """The exclusive or of two shapes: the region one of them covers but not both, as a
+ new path; white unless styled.
+
+ It is found from the shapes' own paths (not their submobjects'), each the region
+ its fill covers, in the plane of the screen: their z coordinates are dropped. The
+ shapes stay as they are.
+
+ Args:
+ subject: The first shape.
+ clip: The second shape.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ExclusionExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
+ circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
+ circle.shift(3 * m.LEFT + m.UP)
+ either = m.Exclusion(square, circle, color=m.GREEN, fill_opacity=0.8)
+ self.add(square, circle, either.shift(7 * m.RIGHT))
+ ```
+ """
+
+ def __init__(
+ self, subject: VMobject, clip: VMobject, **kwargs: Unpack[Style]
+ ) -> None:
+ super().__init__(**kwargs)
+ _append_path(self, _combine(_pathops().PathOp.XOR, subject, clip))
+
+
+class PointCloudDot(Mobject1D):
+ """A disk of points: rings of points around a center, pure yellow unless styled.
+
+ The rings are 1/`density` scene units apart, from that far from the center out to
+ just inside `radius`, and the points along each ring about as far apart. Its points
+ are small: `stroke_width` 2.
+
+ Args:
+ center: Where its center is, in scene coordinates.
+ radius: How far out its points reach, in scene units.
+ density: How many rings, and points along a ring, per scene unit.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `color` colors its points,
+ and `stroke_width` sizes them.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class PointCloudDotExample(m.Scene):
+ def construct(self) -> None:
+ clouds = m.Group(
+ m.PointCloudDot(),
+ m.PointCloudDot(density=5, stroke_width=8, color=m.BLUE),
+ m.PointCloudDot(density=15, stroke_width=4, color=m.RED),
+ ).arrange(buff=0.6)
+ self.add(clouds)
+ ```
+ """
+
+ defaults: ClassVar[Style] = {"stroke_width": 2, "color": PURE_YELLOW}
+
+ def __init__(
+ self,
+ center: Point3DLike = ORIGIN,
+ radius: float = 2.0,
+ *,
+ density: int = DEFAULT_POINT_DENSITY_1D,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self.radius = radius
+ self.epsilon = 1.0 / density
+ super().__init__(density=density, **kwargs)
+ self.shift(center)
+
+ def generate_points(self) -> Self:
+ rings = []
+ for r in np.arange(self.epsilon, self.radius, self.epsilon):
+ theta = np.linspace(
+ 0,
+ 2 * np.pi,
+ num=int(2 * np.pi * (r + self.epsilon) / self.epsilon),
+ )[:, None]
+ rings.append(r * (np.cos(theta) * RIGHT + np.sin(theta) * UP))
+ return self.add_points(np.concatenate(rings) if rings else np.empty((0, 3)))
diff --git a/tests/unit/mobjects/test_shapes.py b/tests/unit/mobjects/test_shapes.py
new file mode 100644
index 00000000..9e03b410
--- /dev/null
+++ b/tests/unit/mobjects/test_shapes.py
@@ -0,0 +1,409 @@
+"""Shapes are where their parameters put them.
+
+- An arc runs on its circle from its start angle through its angle: its ends exactly there,
+ its points within a thousandth of the radius of the circle; a circle is the arc of a whole
+ turn about its center; an arc's center is its circle's, in whatever plane it has been turned
+ into. An annulus's boundaries are two circles wound opposite ways; a sector joins its inner
+ arc to its outer one, reversed. An arc between two points starts at one and ends at the
+ other.
+- A tip points along the path at the end it is on, its point on that end: in the plane of the
+ screen however the path bends, in space where it ends straight, and where the path's last
+ handle has no length too.
+- A line's ends, length, vector and angle are its own; `put_start_and_end_on` puts a line's or
+ an arrow's ends anywhere, a segment turned back on itself too. An arrow's tip point is where
+ it ends, its shaft stops at the tip's base, and scaled, its tip keeps its size.
+- A dashed line's ends are the line's, tipped or not, and its handles those of the dashes it
+ draws, cut out of its path: its first dash's first and its last dash's last, straight or
+ bent; drawn solid, the line's own.
+- A screen rectangle keeps its height and its center as its aspect ratio changes; a
+ full-screen one is the screen rectangle as tall as the frame.
+- A regular polygram walks its vertices in groups, by its density.
+- Rounding a polygram's corners cuts each with an arc of the radius tangent to its two sides
+ (for a negative radius, that arc mirrored across its chord, into the corner), joined by what
+ is left of the sides: each outline closed and apart from the others, in its paint; a radius
+ of 0 changes nothing.
+"""
+
+import math
+
+import numpy as np
+import pytest
+from hypothesis import assume, example, given
+from hypothesis import strategies as st
+from tests import oracles
+from tests.strategies import arrays, curves
+
+import manimgx as m
+from manimgx.mobjects.shapes import TipableVMobject
+
+radii = st.floats(0.1, 10)
+
+
+turns = st.floats(0.05, 2 * np.pi).flatmap(lambda a: st.sampled_from([a, -a]))
+
+
+@given(radius=radii, start=st.floats(-7, 7), angle=turns, center=arrays(3, 5))
+def test_an_arc_runs_on_its_circle(
+ radius: float, start: float, angle: float, center: np.ndarray
+) -> None:
+ arc = m.Arc(radius=radius, start_angle=start, angle=angle, arc_center=center)
+ at = lambda a: center + radius * np.array([np.cos(a), np.sin(a), 0]) # noqa: E731
+ np.testing.assert_allclose(arc.points[0], at(start), atol=1e-9 * radius)
+ np.testing.assert_allclose(arc.points[-1], at(start + angle), atol=1e-9 * radius)
+ drawn = oracles.sample(arc.points, 50)
+ np.testing.assert_allclose(
+ np.linalg.norm(drawn - center, axis=1), radius, rtol=1e-3
+ )
+ np.testing.assert_allclose(arc.get_arc_center(), center, atol=1e-9 * (1 + radius))
+
+
+@given(
+ radius=radii,
+ angle=turns,
+ turn=st.floats(-3, 3),
+ axis=arrays(3, 1),
+ about=arrays(3, 5),
+)
+def test_an_arcs_center_turns_with_it(
+ radius: float, angle: float, turn: float, axis: np.ndarray, about: np.ndarray
+) -> None:
+ assume(np.linalg.norm(axis) > 1e-2 and abs(angle) < 2 * np.pi - 1e-2)
+ arc = m.Arc(radius=radius, angle=angle).rotate(turn, axis, about_point=about)
+ expected = m.rotation_matrix(turn, axis) @ (np.zeros(3) - about) + about
+ np.testing.assert_allclose(
+ arc.get_arc_center(), expected, atol=1e-7 * (1 + radius + np.abs(about).max())
+ )
+
+
+@given(radius=radii, center=arrays(3, 5))
+def test_a_circle_is_a_whole_turn_about_its_center(
+ radius: float, center: np.ndarray
+) -> None:
+ circle = m.Circle(radius=radius).move_to(center)
+ np.testing.assert_allclose(circle.get_center(), center, atol=1e-9 * (1 + radius))
+ assert circle.width == pytest.approx(2 * radius, rel=1e-9)
+ assert circle.is_closed()
+
+
+@given(radius=radii, width=st.floats(0.2, 3), center=arrays(3, 5))
+def test_an_annulus_has_oppositely_wound_circular_boundaries(
+ radius: float, width: float, center: np.ndarray
+) -> None:
+ ring = m.Annulus(
+ inner_radius=radius, outer_radius=radius + width, arc_center=center
+ )
+ outer, inner = ring.get_subpaths()
+ for points, size, winding in [(outer, radius + width, 1), (inner, radius, -1)]:
+ anchors = points[::4] - center
+ np.testing.assert_allclose(np.linalg.norm(anchors, axis=1), size, atol=1e-12)
+ area = np.cross(anchors, np.roll(anchors, -1, axis=0)).sum(axis=0)[2]
+ assert winding * area > 0
+ np.testing.assert_allclose(points[0], points[-1], atol=1e-12)
+
+
[email protected]("solid", [False, True])
+@given(radius=radii, start=st.floats(-7, 7), angle=turns, center=arrays(3, 5))
+def test_a_sector_joins_its_inner_and_reversed_outer_arcs(
+ solid: bool, radius: float, start: float, angle: float, center: np.ndarray
+) -> None:
+ sector = (
+ m.Sector(radius=radius, start_angle=start, angle=angle, arc_center=center)
+ if solid
+ else m.AnnularSector(
+ inner_radius=radius / 2,
+ outer_radius=radius,
+ start_angle=start,
+ angle=angle,
+ arc_center=center,
+ )
+ )
+ unit = m.Arc(start_angle=start, angle=angle).points
+ n = len(unit)
+ np.testing.assert_allclose(
+ sector.points[:n], unit * (0 if solid else radius / 2) + center, atol=1e-12
+ )
+ np.testing.assert_allclose(
+ sector.points[n + 4 : -4], unit[::-1] * radius + center, atol=1e-12
+ )
+ curves = sector.get_cubic_bezier_tuples()
+ np.testing.assert_allclose(curves[:, 3], np.roll(curves[:, 0], -1, axis=0))
+
+
+@given(start=arrays(3, 5), end=arrays(3, 5), angle=turns)
+def test_an_arc_between_points_joins_them(
+ start: np.ndarray, end: np.ndarray, angle: float
+) -> None:
+ start[2] = end[2] = 0
+ assume(np.linalg.norm(end - start) > 1e-2 and abs(angle) < 2 * np.pi - 1e-2)
+ arc = m.ArcBetweenPoints(start, end, angle=angle)
+ np.testing.assert_allclose(arc.get_start(), start, atol=1e-9)
+ np.testing.assert_allclose(arc.get_end(), end, atol=1e-9)
+
+
+def arriving(points: np.ndarray) -> np.ndarray:
+ """The direction a path comes into its end: from the curve's Taylor expansion there,
+ B(1 − s) ≈ B(1) − s B′ + s²/2 B″ − s³/6 B‴, its first derivative at the end that does
+ not vanish (none shorter than the tip's tolerance), as the path travels."""
+ p0, p1, p2, p3 = points[-4:]
+ tolerance = 1e-9 * (1 + np.abs(p3).max())
+ for sign, d in (
+ (1, p3 - p2),
+ (-1, p3 - 2 * p2 + p1),
+ (1, p3 - 3 * p2 + 3 * p1 - p0),
+ ):
+ if np.linalg.norm(d) > tolerance: # (each a multiple of B′, B″, B‴ at the end)
+ return sign * d / np.linalg.norm(d)
+ raise AssertionError("a curve of one point has no direction")
+
+
+@given(points=curves(max_curves=3), collapse=st.booleans(), straight=st.booleans())
+def test_a_tip_points_along_the_path_at_its_end(
+ points: np.ndarray, collapse: bool, straight: bool
+) -> None:
+ if straight: # (its last curve straight, anywhere in space)
+ start, end = points[-4], points[-1]
+ points[-3], points[-2] = (
+ start + (end - start) / 3,
+ start + 2 * (end - start) / 3,
+ )
+ else: # (bending, in the plane of the screen)
+ points[:, 2] = 0
+ if collapse:
+ points[-2] = points[-1] # a last handle of no length
+ path = TipableVMobject()
+ path.points = points
+ assume(
+ np.linalg.norm(
+ oracles.bezier_points(points[-4:], np.array([0.0, 1.0]))[0][1] - points[-4]
+ )
+ > 1e-3
+ )
+ direction = arriving(points)
+ assume(np.linalg.norm(points[-1] - points[-4]) > 1e-3)
+ end = points[-1].copy()
+ path.add_tip()
+ tip = path.tip
+ along = tip.tip_point - tip.base
+ np.testing.assert_allclose(tip.tip_point, end, atol=1e-9 * (1 + np.abs(end).max()))
+ np.testing.assert_allclose(
+ along / np.linalg.norm(along), direction, atol=1e-9 if straight else 2e-3
+ )
+
+
+@given(ends=arrays((2, 3), 10))
+def test_a_line_is_its_ends(ends: np.ndarray) -> None:
+ start, end = ends
+ assume(np.linalg.norm(end - start) > 1e-3)
+ line = m.Line(start, end)
+ np.testing.assert_allclose(line.get_start(), start, atol=1e-9)
+ np.testing.assert_allclose(line.get_end(), end, atol=1e-9)
+ assert line.get_length() == pytest.approx(np.linalg.norm(end - start), rel=1e-9)
+ np.testing.assert_allclose(line.get_vector(), end - start, atol=1e-9)
+ assert line.get_angle() == pytest.approx(
+ np.arctan2(*(end - start)[1::-1]), abs=1e-9
+ )
+
+
+@given(ends=arrays((2, 3), 10), new=arrays((2, 3), 10))
+@example( # (turned back on itself along z: it used to keep its direction)
+ ends=np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]),
+ new=np.array([[0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]),
+)
+@example(
+ ends=np.array([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]),
+ new=np.array([[1.0, 2.0, 3.0], [0.0, 0.0, 0.0]]),
+)
+def test_put_start_and_end_on_puts_the_ends_there(
+ ends: np.ndarray, new: np.ndarray
+) -> None:
+ for make in (m.Line, lambda a, b: m.Arrow(a, b, buff=0)):
+ assume(
+ np.linalg.norm(ends[1] - ends[0]) > 1e-2
+ and np.linalg.norm(new[1] - new[0]) > 1e-2
+ )
+ line = make(*ends)
+ line.put_start_and_end_on(*new)
+ np.testing.assert_allclose(line.get_start(), new[0], atol=1e-7)
+ np.testing.assert_allclose(line.get_end(), new[1], atol=1e-7)
+
+
+@given(ends=arrays((2, 3), 10))
+def test_an_arrows_tip_is_where_it_ends(ends: np.ndarray) -> None:
+ start, end = ends
+ start[2] = end[2] = 0
+ assume(np.linalg.norm(end - start) > 0.5)
+ arrow = m.Arrow(start, end, buff=0)
+ np.testing.assert_allclose(arrow.tip.tip_point, end, atol=1e-9)
+ shaft_end = arrow.points[-1]
+ np.testing.assert_allclose(shaft_end, arrow.tip.base, atol=1e-6)
+ length = arrow.tip.length
+ arrow.scale(2)
+ assert arrow.tip.length == pytest.approx(length, rel=1e-9)
+
+
+@given(
+ ends=arrays((2, 3), 10),
+ path_arc=st.floats(-3, 3).map(lambda a: a if abs(a) >= 0.1 else 0.0),
+ dash_length=st.floats(0.01, 4),
+ dashed_ratio=st.floats(0.05, 0.95),
+ tipped=st.booleans(),
+ solid=st.booleans(),
+)
+@example( # (60 dashes, each 0.05 long)
+ ends=np.array([[-3.0, 0.0, 0.0], [3.0, 0.0, 0.0]]),
+ path_arc=0.0,
+ dash_length=0.05,
+ dashed_ratio=0.5,
+ tipped=True,
+ solid=False,
+)
+def test_a_dashed_lines_handles_are_its_end_dashes(
+ ends: np.ndarray,
+ path_arc: float,
+ dash_length: float,
+ dashed_ratio: float,
+ tipped: bool,
+ solid: bool,
+) -> None:
+ start, end = ends
+ start[2] = end[2] = 0
+ assume(np.linalg.norm(end - start) > 0.5)
+ line = m.DashedLine(
+ start,
+ end,
+ path_arc=path_arc,
+ dash_length=dash_length,
+ dashed_ratio=dashed_ratio,
+ )
+ if tipped:
+ line.add_tip()
+ if solid:
+ line.match_style(m.Line())
+ # the pieces it draws, cut out of its path: its parameter u where
+ # frac((u − phase) / period) < duty, or all of it if it is drawn solid
+ period, duty, phase = line.paint.dash or (1.0, 1.0, 0.0)
+ starts = phase + period * np.arange(-1, 1 / period + 1)
+ windows = np.stack([starts, starts + duty * period], axis=1)
+ pieces = np.clip(windows[(windows[:, 0] < 1) & (windows[:, 1] > 0)], 0, 1)
+ (a, b), (c, d) = pieces[0], pieces[-1]
+ first, last = line.get_subcurve(a, b), line.get_subcurve(c, d)
+ np.testing.assert_allclose(line.get_first_handle(), first.points[1], atol=1e-9)
+ np.testing.assert_allclose(line.get_last_handle(), last.points[-2], atol=1e-9)
+ np.testing.assert_allclose(
+ line.get_start(), start, atol=1e-9
+ ) # (its ends: the line's)
+ np.testing.assert_allclose(line.get_end(), end, atol=1e-9)
+
+
[email protected](frame_height=7.3)
[email protected](("ratio", "height"), [(16 / 9, 4), (4 / 3, 3), (0.7, 2.6)])
+def test_a_screen_rectangle_keeps_its_height_as_its_aspect_changes(
+ ratio: float, height: float
+) -> None:
+ screen = m.ScreenRectangle(aspect_ratio=ratio, height=height, color=m.BLUE)
+ assert screen.width == pytest.approx(ratio * height)
+ assert screen.height == pytest.approx(height)
+ screen.shift((1, 2, 0))
+ screen.aspect_ratio = 1.5
+ np.testing.assert_allclose(screen.get_center(), (1, 2, 0))
+ assert screen.width == pytest.approx(1.5 * height)
+ assert screen.height == pytest.approx(height)
+ full = m.FullScreenRectangle(aspect_ratio=ratio, height=height, color=m.BLUE)
+ expected = m.ScreenRectangle(aspect_ratio=ratio, height=height, color=m.BLUE)
+ expected.height = m.config.frame_height
+ np.testing.assert_array_equal(full.points, expected.points)
+ np.testing.assert_array_equal(full.paint.fill, expected.paint.fill)
+ assert full.height == pytest.approx(7.3)
+ assert full.aspect_ratio == pytest.approx(ratio)
+
+
+ ("n", "density"),
+ [(5, 2), (6, 2), (12, 8), (7, -2), (9, 0), (61, 2**60), (61, -(2**60))],
+)
[email protected]("start", [None, 0.31])
+def test_polygram_groups_walk_their_vertices_in_density_order(
+ n: int, density: int, start: float | None
+) -> None:
+ shape = m.RegularPolygram(n, density=density, radius=2.3, start_angle=start)
+ group_count = math.gcd(n, density)
+ group_size = n // group_count
+ groups = shape.get_vertex_groups()
+ assert len(groups) == group_count
+ first = start if start is not None else 0 if group_size % 2 == 0 else np.pi / 2
+ assert shape.start_angle == first
+ for i, vertices in enumerate(groups):
+ index = [(k * (density // group_count)) % group_size for k in range(group_size)]
+ angles = first + i * m.TAU / n + m.TAU * np.array(index) / group_size
+ expected = 2.3 * np.column_stack(
+ (np.cos(angles), np.sin(angles), np.zeros(group_size))
+ )
+ np.testing.assert_allclose(vertices, expected, atol=1e-12)
+
+
+@given(
+ n=st.integers(3, 8),
+ size=st.floats(0.5, 3),
+ turn=st.floats(0, 2 * np.pi),
+ fraction=st.floats(0.05, 0.9),
+ sign=st.sampled_from([1, -1]),
+ components=st.integers(2, 6),
+ framed=st.booleans(),
+)
+@example( # (a square with a square hole: two outlines)
+ n=4, size=2**0.5, turn=np.pi / 4, fraction=0.25, sign=1, components=5, framed=True
+)
+def test_rounding_cuts_each_corner_with_an_arc_tangent_to_its_sides(
+ n: int,
+ size: float,
+ turn: float,
+ fraction: float,
+ sign: int,
+ components: int,
+ framed: bool,
+) -> None:
+ groups = [m.RegularPolygon(n, radius=size, start_angle=turn).get_vertices()]
+ if framed: # (a hole, wound the other way)
+ hole = m.RegularPolygon(n, radius=size / 3, start_angle=turn)
+ groups.append(hole.get_vertices()[::-1])
+ shape = m.Polygram(*groups, color=m.BLUE, fill_opacity=0.4)
+ paint, before = shape.paint, shape.points.copy()
+ assert shape.round_corners(0) is shape
+ np.testing.assert_array_equal(shape.points, before)
+ exterior = 2 * np.pi / n # (each corner turns the outline by it)
+ side = min(np.linalg.norm(group[1] - group[0]) for group in groups)
+ # (small enough that each arc touches its sides at most halfway along them)
+ radius = sign * fraction * side / 2 / np.tan(exterior / 2)
+ cut = abs(radius) * np.tan(exterior / 2)
+ assert (
+ shape.round_corners(radius, components_per_rounded_corner=components) is shape
+ )
+ assert shape.paint is paint
+ paths = shape.get_subpaths()
+ assert len(paths) == len(groups)
+ for path, corners in zip(paths, groups, strict=True):
+ curves = path.reshape(-1, 4, 3)
+ assert len(curves) == len(corners) * components
+ np.testing.assert_allclose(curves[1:, 0], curves[:-1, 3], atol=1e-9)
+ np.testing.assert_allclose(curves[-1, 3], curves[0, 0], atol=1e-9)
+ for i, corner in enumerate(corners):
+ nearby = corners[i - 1], corners[(i + 1) % len(corners)]
+ incoming = (corner - nearby[0]) / np.linalg.norm(corner - nearby[0])
+ outgoing = (nearby[1] - corner) / np.linalg.norm(nearby[1] - corner)
+ arc = curves[i * components : (i + 1) * components - 1]
+ np.testing.assert_allclose(arc[0, 0], corner - cut * incoming, atol=1e-9)
+ np.testing.assert_allclose(arc[-1, 3], corner + cut * outgoing, atol=1e-9)
+ inward = np.cross(m.OUT, incoming) * np.sign(
+ np.cross(incoming, outgoing)[2]
+ )
+ center = arc[0, 0] + abs(radius) * inward # (tangent to the sides there)
+ if radius < 0: # (the same arc, mirrored across its chord)
+ center = arc[0, 0] + arc[-1, 3] - center
+ anchors = np.vstack([arc[:, 0], arc[-1:, 3]])
+ np.testing.assert_allclose(
+ np.linalg.norm(anchors - center, axis=1), abs(radius), atol=1e-9
+ )
+ remainder = curves[(i + 1) * components - 1] # (what is left of the side)
+ np.testing.assert_allclose(
+ remainder[3], nearby[1] - cut * outgoing, atol=1e-9
+ )
diff --git a/tests/unit/test_mobject.py b/tests/unit/test_mobject.py
new file mode 100644
index 00000000..e61dd57e
--- /dev/null
+++ b/tests/unit/test_mobject.py
@@ -0,0 +1,2687 @@
+"""A mobject is a tree of parts with points, a paint and updaters.
+
+- Its family is a tree: whatever is added, removed, inserted or assigned, and however, no mobject
+ holds itself (not even through another), and the family lists each member once, in preorder,
+ where it last occurs. Adding anything else is an error.
+- A transform is the same transform of its points: shifts, scales, turns, stretches and
+ matrices, about the points their docstrings name (its box's center or edge by default), in
+ any order, leave the family's points where plain arithmetic puts them.
+- Its box is what it draws: for every public class, the tight box of its family's curves (by
+ their derivatives' roots) and points; width, height, corners, center and coordinates all read
+ that box, and a member spans the same in whatever group holds it.
+- Layout does what it says: `next_to` leaves `buff` between the two, `arrange` spaces its parts
+ by `buff` and centers them, `arrange_in_grid` puts each part in its cell where its row's,
+ its column's or the grid's alignment says, `to_edge` puts the box `buff` in from the frame's
+ edge, `replace` fits one box into another, `move_to` puts the named point there.
+- Styles read back what they set, every paint attribute as the mobject's own (`family=False`
+ paints the mobject alone); `fade` takes a fraction of every opacity.
+- A replica is an independent, isomorphic copy that does not reach its original. `copy`,
+ `generate_target`, `save_state`, the target of `.animate`, and a construction made again
+ (which a class may take from what it made before: `prototype`) give, for every public class
+ and for the states bugs were found in (updaters, trackers, flowing lines, generator inputs,
+ shared cells, opaque keys, color maps), a mobject that looks the same; that holds the same
+ graph of parts, aliases kept and plain values equal; that shares no mutable part with the
+ original and reaches nothing of its family; and that changes as the original does when both
+ are updated and their trackers nudged.
+- Updaters keep one clock (a model runs beside a host and its part): a time-based updater is
+ handed the time its clock ran since it was added, last ran or resumed (`advance`), or the
+ `dt` given (`update`); a mobject's own run before its parts'; nothing in a suspended subtree
+ runs; a removed updater runs no more, not even later in the pass that removed it, and
+ nothing the mobject holds keeps its owner alive; a copy goes on as the original would have.
+ The updaters change only through the mobject's methods: `get_updaters()` is a snapshot.
+- Its inputs are values: changing what was passed in, afterwards, changes neither the mobject
+ nor what it later makes of it, and making it changes no input; an input it does not show it
+ does not keep, nor what an edit replaces; an iterator gives what the list of its items gives;
+ an option kept for Manim's sake and ignored is ignored, and not kept. Its outputs are values:
+ changing what a query returns changes nothing. Nothing it holds is one of manimgx's writable
+ constants.
+- Defaults are partial application: after `C.set_default(**d)`, `C()` makes what `C(**d)` makes,
+ each class's defaults over those of the classes it inherits from, as they are when `C()`
+ runs; `C.set_default()` brings the class's own back. What manimgx remembers is invisible: a
+ construction made after any defaults and any other constructions, its memories warm, is what
+ it is made from nothing, and mobjects made before keep their look.
+- Its points are a value: assigned others, it takes them. A family grown for a transform
+ (`add_n_more_submobjects`) follows each part with invisible copies of itself, spread as
+ evenly as can be, the parts themselves kept.
+
+A VMobject is a path: cubic curves, four control points each.
+
+- It has one measure of length (nine straight pieces per curve), which its reveals, its
+ proportions and its length all go by: `point_from_proportion` is by length (it used to go
+ by each curve's parameter, 16% of the way at 0.5 on an uneven curve), `proportion_from_point`
+ is its inverse, a reveal at a proportion has drawn exactly to that point, and the length is
+ within the pieces' error of the true arc length, never over it.
+- Built curve by curve, a path is the curves it was given: lines are straight curves with
+ handles at the thirds, a quadratic is its cubic, a closed path ends where its last subpath
+ starts, and subpaths split where a curve does not start at the one before it.
+- Refining keeps the shape: `insert_n_curves` and `align_points` split curves into pieces of
+ equal parameter, each exactly a part of the curve it came from.
+- A part (`pointwise_become_partial`) is the path between its two proportions, by curves.
+- An image under `apply_function`, of a path or of a group holding it, is within 1.5e-3 of the
+ true image all along each curve (its tolerance, 1e-3, holds where it is checked, a third and
+ two thirds along), not only at its control points (checked at the middle alone, a wave
+ through a straight piece passed 0.6 off).
+- Its orientation does not depend on where it is; reversed, it runs the other way.
+
+A point cloud thins to every k-th point of each member, colors and all, and a point added later
+takes the color it was made with. A cloud's part is every point its stretch reaches into, as a
+reveal over the stretch shows.
+
+A mesh's part is the triangles a reveal over its stretch shows, every one it reaches into, each
+corner keeping its paint, and no other corner: its box is theirs. A surface's part is a surface:
+its whole lattice, drawing the faces its stretch reaches into, its box theirs; its pieces share
+its faces out. A lattice's triangles are derived from its grid, and replacing them with others is
+an error.
+
+A VDict that shows its keys labels each value with its key, however the value was added."""
+
+import random
+from collections.abc import Callable, Iterator
+from dataclasses import dataclass, field
+from fractions import Fraction
+from pathlib import Path
+from typing import cast
+
+import numpy as np
+import pytest
+import svgelements as se
+from hypothesis import assume, example, given, settings
+from hypothesis import strategies as st
+from hypothesis.stateful import (
+ Bundle,
+ RuleBasedStateMachine,
+ initialize,
+ invariant,
+ precondition,
+ rule,
+)
+from tests import oracles
+from tests.oracles import assert_replica, look, reachable, reaches
+from tests.strategies import (
+ MOBJECTS,
+ angles,
+ arrays,
+ curves,
+ drawn,
+ mobjects,
+ paths,
+ vectors,
+)
+
+import manimgx as m
+from manimgx import caches
+from manimgx.animation import clock
+from manimgx.animation.easing import linear
+from manimgx.drawing.geometry import bezier, partial_bezier_points
+from manimgx.drawing.paint import Style
+from manimgx.mobject import GridArrangement, ValueTracker, prototype
+from manimgx.mobjects.shapes import LineOptions
+
+DIRECTIONS = [m.RIGHT, m.LEFT, m.UP, m.DOWN, m.UR, m.UL, m.DR, m.DL]
+
+resizable = drawn.filter(
+ lambda mob: (
+ not isinstance(mob, (m.Arrow, m.VectorizedPoint))
+ and "Arrow" not in type(mob).__name__
+ )
+)
+
+
+def path(points: np.ndarray) -> m.VMobject:
+ mob = m.VMobject()
+ mob.points = points
+ return mob
+
+
+def last_preorder(mob: m.Mobject) -> list[m.Mobject]:
+ """A family by its definition: preorder, each member where it last occurs."""
+
+ def preorder(x: m.Mobject) -> list[m.Mobject]:
+ return [x, *(part for child in x.submobjects for part in preorder(child))]
+
+ expanded = preorder(mob)
+ last = {id(x): i for i, x in enumerate(expanded)}
+ return [x for i, x in enumerate(expanded) if last[id(x)] == i]
+
+
+class Family(RuleBasedStateMachine):
+ """Every way a family changes keeps it a tree, listed in last-occurrence preorder."""
+
+ mobs = Bundle("mobs")
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.made: list[m.Mobject] = []
+ self.assigned: set[int] = (
+ set()
+ ) # given a list by hand, which may hold a part twice
+
+ def keep(self, mob: m.Mobject) -> m.Mobject:
+ self.made.append(mob)
+ return mob
+
+ @initialize(target=mobs)
+ def root(self) -> m.Mobject:
+ return self.keep(m.Mobject())
+
+ @rule(target=mobs)
+ def new(self) -> m.Mobject:
+ return self.keep(m.Dot())
+
+ @rule(target=mobs, original=mobs)
+ def copy(self, original: m.Mobject) -> m.Mobject:
+ copy = self.keep(original.copy())
+ if id(original) in self.assigned: # (its list, copied, holds a part twice too)
+ self.assigned.add(id(copy))
+ return copy
+
+ def refused(self, parent: m.Mobject, children: list[m.Mobject]) -> bool:
+ return any(
+ parent is c or any(x is parent for x in c.get_family()) for c in children
+ )
+
+ @staticmethod
+ def once(children: list[m.Mobject]) -> list[m.Mobject]:
+ """Each child once, where it last occurs."""
+ return [
+ c
+ for i, c in enumerate(children)
+ if all(c is not d for d in children[i + 1 :])
+ ]
+
+ @rule(parent=mobs, children=st.lists(mobs, min_size=1, max_size=3))
+ def add(self, parent: m.Mobject, children: list[m.Mobject]) -> None:
+ if self.refused(parent, children):
+ with pytest.raises(ValueError, match="cannot hold itself"):
+ parent.add(*children)
+ else:
+ parent.add(*children)
+ new = self.once(children)
+ assert parent.submobjects[len(parent.submobjects) - len(new) :] == new
+
+ @rule(parent=mobs, children=st.lists(mobs, min_size=1, max_size=3))
+ def add_to_back(self, parent: m.Mobject, children: list[m.Mobject]) -> None:
+ if self.refused(parent, children):
+ with pytest.raises(ValueError, match="cannot hold itself"):
+ parent.add_to_back(*children)
+ else:
+ parent.add_to_back(*children)
+ new = self.once(children)
+ assert parent.submobjects[: len(new)] == new
+
+ @rule(parent=mobs, child=mobs, index=st.integers(-4, 4))
+ def insert(self, parent: m.Mobject, child: m.Mobject, index: int) -> None:
+ if self.refused(parent, [child]):
+ with pytest.raises(ValueError, match="cannot hold itself"):
+ parent.insert(index, child)
+ else:
+ others = [x for x in parent.submobjects if x is not child]
+ parent.insert(index, child)
+ others.insert(index, child)
+ assert parent.submobjects == others
+
+ @rule(parent=mobs, children=st.lists(mobs, max_size=3))
+ def assign(self, parent: m.Mobject, children: list[m.Mobject]) -> None:
+ if not self.refused(parent, children):
+ parent.submobjects = list(children)
+ self.assigned.add(id(parent))
+
+ @rule(parent=mobs, child=mobs)
+ def remove(self, parent: m.Mobject, child: m.Mobject) -> None:
+ parent.remove(child)
+ if (
+ id(parent) not in self.assigned
+ ): # (a list given by hand loses one occurrence)
+ assert all(x is not child for x in parent.submobjects)
+
+ @invariant()
+ def it_is_a_tree(self) -> None:
+ for mob in self.made:
+ ids = [id(x) for x in mob.submobjects]
+ if id(mob) not in self.assigned:
+ assert len(ids) == len(set(ids)), "a part held twice"
+ stack: list[tuple[m.Mobject, frozenset[int]]] = [(mob, frozenset())]
+ while stack:
+ x, above = stack.pop()
+ assert id(x) not in above, "a mobject holds itself"
+ stack.extend((c, above | {id(x)}) for c in x.submobjects)
+ assert mob.get_family() == last_preorder(mob)
+
+
+TestFamily = Family.TestCase
+TestFamily.settings = settings(stateful_step_count=25)
+
+
[email protected]("value", [1, "a", None, np.zeros(3)])
+def test_only_mobjects_join_a_family(value: object) -> None:
+ for join in (
+ lambda g: g.add(value),
+ lambda g: g.add_to_back(value),
+ lambda g: g.insert(0, value),
+ ):
+ with pytest.raises(TypeError):
+ join(m.VGroup())
+
+
+class Transforms(RuleBasedStateMachine):
+ """A group of paths under any chain of transforms has the points plain arithmetic gives,
+ about the pivots the docstrings name."""
+
+ @initialize(parts=st.lists(curves(max_curves=3), min_size=1, max_size=3))
+ def begin(self, parts: list[np.ndarray]) -> None:
+ self.mob = m.VGroup(*(path(p) for p in parts))
+ self.model = [p.copy() for p in parts]
+
+ def pivot(self, direction: np.ndarray) -> np.ndarray:
+ boxes = np.array([oracles.curve_box(p) for p in self.model])
+ low, high = boxes[:, 0].min(axis=0), boxes[:, 1].max(axis=0)
+ return np.where(
+ direction < 0, low, np.where(direction > 0, high, (low + high) / 2)
+ )
+
+ def apply(self, linear: np.ndarray, about: np.ndarray) -> None:
+ self.model = [(p - about) @ linear.T + about for p in self.model]
+
+ @rule(vector=arrays(3, 10))
+ def shift(self, vector: np.ndarray) -> None:
+ self.mob.shift(vector)
+ self.model = [p + vector for p in self.model]
+
+ @rule(
+ factor=st.floats(-3, 3).filter(lambda f: abs(f) > 1e-3),
+ edge=st.sampled_from([m.ORIGIN, *DIRECTIONS]),
+ )
+ def scale(self, factor: float, edge: np.ndarray) -> None:
+ about = self.pivot(edge)
+ self.mob.scale(factor, about_edge=edge)
+ self.apply(factor * np.eye(3), about)
+
+ @rule(factors=arrays(3, 3).filter(lambda f: np.all(np.abs(f) > 1e-3)))
+ def scale_each_axis(self, factors: np.ndarray) -> None:
+ about = self.pivot(m.ORIGIN)
+ self.mob.scale(factors)
+ self.apply(np.diag(factors), about)
+
+ @rule(angle=angles(), axis=vectors(), about=arrays(3, 10) | st.none())
+ def rotate(self, angle: float, axis: np.ndarray, about: np.ndarray | None) -> None:
+ pivot = self.pivot(m.ORIGIN) if about is None else about
+ self.mob.rotate(angle, axis, about_point=about)
+ self.apply(m.rotation_matrix(angle, axis), pivot)
+
+ @rule(axis=vectors())
+ def flip(self, axis: np.ndarray) -> None:
+ about = self.pivot(m.ORIGIN)
+ self.mob.flip(axis)
+ self.apply(m.rotation_matrix(np.pi, axis), about)
+
+ @rule(
+ factor=st.floats(-3, 3).filter(lambda f: abs(f) > 1e-3), dim=st.integers(0, 2)
+ )
+ def stretch(self, factor: float, dim: int) -> None:
+ about = self.pivot(m.ORIGIN)
+ self.mob.stretch(factor, dim)
+ linear = np.eye(3)
+ linear[dim, dim] = factor
+ self.apply(linear, about)
+
+ @rule(matrix=arrays((3, 3), 2))
+ def apply_matrix(self, matrix: np.ndarray) -> None:
+ self.mob.apply_matrix(matrix) # about the origin
+ self.apply(matrix, np.zeros(3))
+
+ @invariant()
+ def its_points_are_the_arithmetic(self) -> None:
+ for part, expected in zip(self.mob.submobjects, self.model, strict=True):
+ scale = 1 + np.abs(expected).max()
+ np.testing.assert_allclose(part.points, expected, atol=1e-9 * scale)
+
+ @invariant()
+ def its_box_is_what_it_draws(self) -> None:
+ drawn = np.concatenate([oracles.sample(p, 50) for p in self.model])
+ box = self.mob.boundary_box()
+ assert box is not None
+ low, high = box
+ tolerance = 1e-9 * (1 + np.abs(drawn).max())
+ assert np.all(drawn >= low - tolerance)
+ assert np.all(drawn <= high + tolerance)
+ np.testing.assert_allclose(
+ [low, high],
+ [self.pivot(-np.ones(3)), self.pivot(np.ones(3))],
+ atol=tolerance,
+ )
+
+
+TestTransforms = Transforms.TestCase
+
+TestTransforms.settings = settings(stateful_step_count=10)
+
+
+class TestBox:
+ @given(parts=st.lists(curves(max_curves=2), min_size=1, max_size=4))
+ def test_a_groups_box_joins_its_members_boxes(
+ self, parts: list[np.ndarray]
+ ) -> None:
+ group = m.VGroup(*(path(p) for p in parts))
+ boxes = np.array([path(p).boundary_box() for p in parts])
+ np.testing.assert_array_equal(
+ group.boundary_box(), [boxes[:, 0].min(0), boxes[:, 1].max(0)]
+ )
+
+ @given(
+ points=curves(), direction=st.sampled_from([m.ORIGIN, *DIRECTIONS, m.OUT, m.IN])
+ )
+ def test_its_critical_points_are_its_boxs(
+ self, points: np.ndarray, direction: np.ndarray
+ ) -> None:
+ mob = path(points)
+ low, high = oracles.curve_box(points)
+ expected = np.where(
+ direction < 0, low, np.where(direction > 0, high, (low + high) / 2)
+ )
+ np.testing.assert_allclose(
+ mob.get_critical_point(direction),
+ expected,
+ atol=1e-9 * (1 + np.abs(points).max()),
+ )
+
+ @given(
+ points=curves(),
+ size=st.floats(0.1, 20),
+ dim=st.sampled_from(["width", "height"]),
+ )
+ def test_setting_a_size_scales_to_it_about_the_center(
+ self, points: np.ndarray, size: float, dim: str
+ ) -> None:
+ mob = path(points)
+ assume(getattr(mob, dim) > 1e-3)
+ center = mob.get_center()
+ setattr(mob, dim, size)
+ assert getattr(mob, dim) == pytest.approx(size, rel=1e-9)
+ np.testing.assert_allclose(
+ mob.get_center(), center, atol=1e-9 * (1 + np.abs(points).max() + size)
+ )
+
+
+PERPENDICULAR_EDGES = { # an aligned edge across the direction a mobject is put in
+ tuple(m.RIGHT): [m.ORIGIN, m.UP, m.DOWN],
+ tuple(m.LEFT): [m.ORIGIN, m.UP, m.DOWN],
+ tuple(m.UP): [m.ORIGIN, m.LEFT, m.RIGHT],
+ tuple(m.DOWN): [m.ORIGIN, m.LEFT, m.RIGHT],
+}
+
+
+class TestLayout:
+ @given(
+ a=drawn,
+ b=drawn,
+ direction=st.sampled_from([m.RIGHT, m.LEFT, m.UP, m.DOWN]),
+ buff=st.floats(0, 3),
+ data=st.data(),
+ )
+ def test_next_to_leaves_buff_between_the_two(
+ self,
+ a: m.Mobject,
+ b: m.Mobject,
+ direction: np.ndarray,
+ buff: float,
+ data: st.DataObject,
+ ) -> None:
+ edge = data.draw(st.sampled_from(PERPENDICULAR_EDGES[tuple(direction)]))
+ a.next_to(b, direction, buff=buff, aligned_edge=edge)
+ k = 0 if direction[0] else 1
+ gap = (
+ a.get_critical_point(-direction)[k] - b.get_critical_point(direction)[k]
+ ) * direction[k]
+ assert gap == pytest.approx(buff, abs=1e-9)
+ across = 1 - k
+ assert a.get_critical_point(edge)[across] == pytest.approx(
+ b.get_critical_point(edge)[across], abs=1e-9
+ )
+
+ @given(
+ parts=st.lists(drawn, min_size=1, max_size=5),
+ buff=st.floats(0, 1),
+ direction=st.sampled_from([m.RIGHT, m.DOWN]),
+ )
+ def test_arrange_spaces_its_parts_by_buff_and_centers_them(
+ self, parts: list[m.Mobject], buff: float, direction: np.ndarray
+ ) -> None:
+ group = m.Group(*parts).arrange(direction, buff=buff)
+ k = 0 if direction[0] else 1
+ for before, after in zip(group.submobjects, group.submobjects[1:]):
+ gap = (
+ after.get_critical_point(-direction)[k]
+ - before.get_critical_point(direction)[k]
+ ) * direction[k]
+ assert gap == pytest.approx(buff, abs=1e-9)
+ np.testing.assert_allclose(group.get_center(), 0, atol=1e-9)
+
+ @given(mob=drawn, direction=st.sampled_from(DIRECTIONS), buff=st.floats(0, 1))
+ def test_to_edge_puts_the_box_buff_in_from_the_frames_edge(
+ self, mob: m.Mobject, direction: np.ndarray, buff: float
+ ) -> None:
+ mob.to_edge(direction, buff=buff)
+ edges = np.array([m.config.frame_x_radius, m.config.frame_y_radius])
+ for k in (0, 1):
+ if direction[k]:
+ reached = mob.get_critical_point(direction)[k] * direction[k]
+ assert reached == pytest.approx(edges[k] - buff, abs=1e-9)
+
+ @given(mob=resizable, target=resizable)
+ def test_replace_fits_one_box_into_the_other(
+ self, mob: m.Mobject, target: m.Mobject
+ ) -> None:
+ # (an arrow scales its shaft and keeps its tips: its box does not scale with it)
+ assume(mob.width > 1e-3 and target.width > 1e-3)
+ mob.replace(target)
+ np.testing.assert_allclose(mob.get_center(), target.get_center(), atol=1e-9)
+ assert mob.width == pytest.approx(target.width, rel=1e-9)
+
+ @given(mob=drawn, point=arrays(3, 5), edge=st.sampled_from([m.ORIGIN, *DIRECTIONS]))
+ def test_move_to_puts_the_named_point_there(
+ self, mob: m.Mobject, point: np.ndarray, edge: np.ndarray
+ ) -> None:
+ mob.move_to(point, aligned_edge=edge)
+ np.testing.assert_allclose(mob.get_critical_point(edge), point, atol=1e-9)
+
+ @given(
+ sizes=st.lists(
+ st.tuples(st.floats(0.1, 2), st.floats(0.1, 2)), min_size=1, max_size=9
+ ),
+ cols=st.integers(1, 3),
+ buff=st.floats(0, 1) | st.tuples(st.floats(0, 1), st.floats(0, 1)),
+ cell=st.sampled_from([m.ORIGIN, *DIRECTIONS]),
+ data=st.data(),
+ )
+ def test_arrange_in_grid_puts_each_part_in_its_cell(
+ self,
+ sizes: list[tuple[float, float]],
+ cols: int,
+ buff: float | tuple[float, float],
+ cell: np.ndarray,
+ data: st.DataObject,
+ ) -> None:
+ # rows top down and columns left to right, each as tall and as wide as its largest
+ # part, `buff` apart; a part sits in its cell as its row's letter says vertically,
+ # its column's horizontally, else as `cell_alignment` does
+ rows = -(-len(sizes) // cols)
+ row_letters = data.draw(
+ st.none() | st.text("ucd", min_size=rows, max_size=rows)
+ )
+ col_letters = data.draw(
+ st.none() | st.text("lcr", min_size=cols, max_size=cols)
+ )
+ parts = [m.Rectangle(width=w, height=h) for w, h in sizes]
+ m.VGroup(*parts).arrange_in_grid(
+ rows=rows,
+ cols=cols,
+ buff=buff,
+ cell_alignment=cell,
+ row_alignments=row_letters,
+ col_alignments=col_letters,
+ )
+ bx, by = buff if isinstance(buff, tuple) else (buff, buff)
+ widths = [max((w for w, _ in sizes[c::cols]), default=0.0) for c in range(cols)]
+ heights = [
+ max(h for _, h in sizes[r * cols : (r + 1) * cols]) for r in range(rows)
+ ]
+ offsets = []
+ for i, part in enumerate(parts):
+ r, c = divmod(i, cols)
+ h = {"l": -1, "c": 0, "r": 1}[col_letters[c]] if col_letters else cell[0]
+ v = {"u": 1, "c": 0, "d": -1}[row_letters[r]] if row_letters else cell[1]
+ left = sum(widths[:c]) + c * bx
+ top = -(sum(heights[:r]) + r * by)
+ corner = [left + (h + 1) / 2 * widths[c], top - (1 - v) / 2 * heights[r], 0]
+ offsets.append(part.get_critical_point([h, v, 0]) - corner)
+ np.testing.assert_allclose(
+ np.array(offsets), np.array([offsets[0]] * len(parts)), atol=1e-9
+ )
+
+
+PAINT_ATTRIBUTES: dict[
+ str, object
+] = { # each paint attribute, with a value to set it to
+ "joint_type": m.LineJointType.ROUND,
+ "cap_style": m.CapStyleType.ROUND,
+ "shade_in_3d": True,
+ "sheen_factor": 0.5,
+ "sheen_direction": np.array([0.5, -0.25, 0.125]),
+ "background_stroke_width": 2.0,
+ "fill_rgbas": np.array([[0.1, 0.2, 0.3, 0.4]]),
+ "stroke_rgbas": np.array([[0.7, 0.6, 0.5, 0.8], [0.1, 0.2, 0.3, 1.0]]),
+ "background_stroke_rgbas": np.array([[0.2, 0.3, 0.4, 1.0]]),
+}
+
+
+def own(mob: m.Mobject) -> tuple[object, ...]:
+ """What a mobject shows of its own (its first row of `look`)."""
+ return look(mob)[0]
+
+
+class TestStyle:
+ @given(
+ mob=drawn,
+ color=st.sampled_from([m.RED, m.BLUE, m.ManimColor("#123456")]),
+ opacity=st.floats(0, 1),
+ )
+ def test_what_is_set_reads_back(
+ self, mob: m.Mobject, color: m.ManimColor, opacity: float
+ ) -> None:
+ mob.set_fill(color, opacity).set_stroke(color, 3, opacity)
+ for part in mob.get_family():
+ assert part.get_fill_color().to_rgb().tolist() == color.to_rgb().tolist()
+ assert part.get_fill_opacity() == opacity
+ assert part.get_stroke_width() == 3
+
+ @given(mob=drawn, name=st.sampled_from(sorted(PAINT_ATTRIBUTES)))
+ def test_a_paint_attribute_reads_back_as_the_mobjects_own(
+ self, mob: m.Mobject, name: str
+ ) -> None:
+ value = PAINT_ATTRIBUTES[name]
+ others = [own(part) for part in mob.get_family()[1:]]
+ setattr(mob, name, value)
+ read = getattr(mob, name)
+ if isinstance(value, np.ndarray):
+ np.testing.assert_array_equal(read, value)
+ else:
+ assert read == value
+ assert [own(part) for part in mob.get_family()[1:]] == others
+ direction = mob.sheen_direction # (a factor alone keeps the direction)
+ mob.set_sheen(0.25, family=False)
+ np.testing.assert_array_equal(mob.sheen_direction, direction)
+ mob.set_sheen_direction(m.UP, family=False).set_fill(m.RED, 0.5, family=False)
+ assert [own(part) for part in mob.get_family()[1:]] == others
+
+ @given(
+ mob=mobjects,
+ darkness=st.floats(0, 1),
+ opacities=st.lists(st.floats(0, 1), min_size=2, max_size=4),
+ )
+ def test_fade_takes_a_fraction_of_every_opacity(
+ self, mob: m.Mobject, darkness: float, opacities: list[float]
+ ) -> None:
+ # (it set every row, a gradient's stops or a cloud's points, to the first one's)
+ mob.set_fill([m.RED, m.BLUE, m.GREEN, m.GOLD][: len(opacities)], opacities)
+ before = [
+ (p.paint.fill[:, 3].copy(), p.paint.stroke[:, 3].copy())
+ for p in mob.get_family()
+ ]
+ mob.fade(darkness)
+ for part, (fill, stroke) in zip(mob.get_family(), before, strict=True):
+ np.testing.assert_allclose(
+ part.paint.fill[:, 3], fill * (1 - darkness), atol=1e-12
+ )
+ np.testing.assert_allclose(
+ part.paint.stroke[:, 3], stroke * (1 - darkness), atol=1e-12
+ )
+
+
+def points_of(mob: m.Mobject) -> list[np.ndarray]:
+ return [member.points for member in mob.get_family()]
+
+
+def assert_points_close(a: m.Mobject, b: m.Mobject, scale: float = 1.0) -> None:
+ pa, pb = points_of(a), points_of(b)
+ assert [len(x) for x in pa] == [len(x) for x in pb]
+ for x, y in zip(pa, pb, strict=True):
+ np.testing.assert_allclose(x, y, atol=1e-9 * (scale + np.abs(y).max(initial=0)))
+
+
+every = pytest.mark.parametrize("name", sorted(MOBJECTS))
+
+
+def _arc_and_its_brace() -> m.Mobject:
+ arc = m.Arc(radius=0.2, start_angle=0.3, angle=4.7)
+ return m.VGroup(arc, m.ArcBrace(arc))
+
+
+BOXES: dict[str, Callable[[], m.Mobject]] = { # boxes no registry entry shows
+ "rounded pentagon": lambda: m.RegularPolygon(5).round_corners(0.3),
+ "arc and its brace": _arc_and_its_brace,
+}
+
+
+class TestEveryMobject:
+ """The laws of the Mobject contract, for every public class (a subclass that overrides a
+ method keeps them)."""
+
+ @every
+ def test_its_family_holds_it_once_first_and_its_points_are_finite(
+ self, name: str
+ ) -> None:
+ mob = MOBJECTS[name]()
+ family = mob.get_family()
+ assert family[0] is mob
+ assert sum(x is mob for x in family) == 1
+ assert all(np.isfinite(points).all() for points in points_of(mob))
+
+ @every
+ def test_a_shift_moves_its_box_and_back_is_where_it_was(self, name: str) -> None:
+ mob = MOBJECTS[name]()
+ box, start = mob.boundary_box(), mob.copy()
+ vector = np.array([1.25, -0.5, 0.75])
+ mob.shift(vector)
+ if box is not None:
+ moved = mob.boundary_box()
+ assert moved is not None
+ np.testing.assert_allclose(moved, box + vector, atol=1e-9)
+ assert_points_close(mob.shift(-vector), start)
+
+ @every
+ def test_a_turn_and_a_scale_undone_leave_it_where_it_was(self, name: str) -> None:
+ mob = MOBJECTS[name]()
+ start, about = mob.copy(), np.array([0.3, -0.2, 0.1])
+ mob.rotate(0.7, m.OUT, about_point=about).rotate(-0.7, m.OUT, about_point=about)
+ assert_points_close(mob, start)
+ mob.scale(2, about_point=about).scale(0.5, about_point=about)
+ assert_points_close(mob, start)
+
+ @every
+ def test_restore_undoes_whatever_came_between(self, name: str) -> None:
+ mob = MOBJECTS[name]()
+ mob.save_state()
+ saved = oracles.look(mob)
+ mob.shift(m.DL).rotate(1.1).scale(0.7).set_color(m.TEAL).set_opacity(0.4)
+ assert oracles.look(mob.restore()) == saved
+
+ @every
+ def test_become_takes_what_another_shows(self, name: str) -> None:
+ mob, other = MOBJECTS[name](), MOBJECTS[name]().shift(m.UP).set_color(m.GOLD)
+ mob.become(other)
+ assert oracles.look(mob) == oracles.look(other)
+
+ @pytest.mark.parametrize("name", [*sorted(MOBJECTS), *sorted(BOXES)])
+ def test_its_box_is_what_it_draws(self, name: str) -> None:
+ mob = (MOBJECTS.get(name) or BOXES[name])().rotate(0.3, axis=[1.0, 2.0, 3.0])
+ box, expected = mob.boundary_box(), oracles.drawn_box(mob)
+ if expected is None:
+ assert box is None
+ return
+ assert box is not None
+ tolerance = 1e-9 * (1 + np.abs(expected).max())
+ np.testing.assert_allclose(box, expected, atol=tolerance)
+ if not isinstance(
+ mob, m.VectorizedPoint
+ ): # (whose size is a number of its own)
+ np.testing.assert_allclose(
+ [mob.width, mob.height], (box[1] - box[0])[:2], atol=tolerance
+ )
+ np.testing.assert_allclose(
+ mob.get_corner(m.UL)[:2], [box[0, 0], box[1, 1]], atol=tolerance
+ )
+ np.testing.assert_allclose([mob.get_x(), mob.get_y()], mob.get_center()[:2])
+ for member in mob.submobjects: # a member spans the same, grouped or not
+ mine = member.boundary_box()
+ if mine is None:
+ continue
+ assert np.all(mine[0] >= box[0] - tolerance)
+ assert np.all(mine[1] <= box[1] + tolerance)
+ drawn_by_member = oracles.drawn_box(member)
+ assert drawn_by_member is not None
+ np.testing.assert_allclose(mine, drawn_by_member, atol=tolerance)
+
+
+# ── replicas ──────────────────────────────────────────────────────────────────────────────
+class _Decimal(m.DecimalNumber):
+ def _get_num_string(self, number: float | complex) -> str:
+ return "v=" + super()._get_num_string(number)
+
+
+class _Owner(m.Mobject): # a mobject whose method is an updater of another
+ def follow(self, mob: m.Mobject, dt: float) -> None:
+ mob.shift(dt * m.RIGHT)
+
+
+class _Kept(_Owner): # a kept construction that updates itself
+ @prototype
+ def __init__(self) -> None:
+ super().__init__()
+ self.add(m.Dot())
+ self.add_updater(self.follow)
+
+
+class _Opaque: # a key: an identity, never copied
+ def __deepcopy__(self, memo: dict[int, object]) -> "_Opaque":
+ raise AssertionError("a key is an identity, never copied")
+
+
+_KEYS = (_Opaque(), _Opaque())
+_SVG = Path(__file__).parents[1] / "integration/cases/svg_mobject_example/shapes.svg"
+
+
+def _numbers() -> Iterator[float]:
+ yield from (1.0, 2.0)
+
+
+def _flowing() -> m.StreamLines:
+ lines = m.StreamLines(
+ lambda p: np.array([0.2, 0.3, 0.0]),
+ x_range=[0, 0, 1],
+ y_range=[0, 0, 1],
+ noise_factor=0,
+ virtual_time=0.2,
+ )
+ random.seed(1)
+ lines.start_animation(warm_up=False, flow_speed=1.5)
+ return lines
+
+
+def _shared_cells() -> m.MobjectTable:
+ s = m.Square(0.3)
+ return m.MobjectTable(
+ [[s, s], [m.Circle(0.2), s]],
+ row_labels=[m.Dot(), m.Dot()],
+ col_labels=[m.Dot(), m.Dot()],
+ include_outer_lines=True,
+ add_background_rectangles_to_entries=True,
+ )
+
+
+def _shared_entries() -> m.MobjectMatrix:
+ s = m.Square(0.4)
+ return m.MobjectMatrix([[s, s], [m.Circle(0.3), s]])
+
+
+def _divided() -> m.SampleSpace:
+ space = m.SampleSpace().divide_vertically(0.4)
+ first = space.vertical_parts[0]
+ assert isinstance(first, m.SampleSpace)
+ first.divide_vertically(0.3)
+ return space
+
+
+def _tipped() -> m.Line:
+ line = m.Line(m.ORIGIN, [1, 2, 3]).add_tip()
+ line.create_tip(at_start=True)
+ return line
+
+
+def _with_history() -> m.Dot:
+ dot = m.Dot(m.LEFT, color=m.RED).save_state()
+ dot.shift(m.RIGHT).generate_target()
+ return dot
+
+
+def _aliased() -> m.VGroup:
+ dot = m.Dot()
+ group = m.VGroup(dot, m.Square())
+ vars(group)["label"] = dot # an attribute naming a member
+ return group
+
+
+def _updated() -> m.Mobject:
+ owner = _Owner()
+ host = m.Square().add_updater(owner.follow)
+ host.add_updater(lambda mob: mob.set_opacity(0.5))
+ host.advance(Fraction(1))
+ return host
+
+
+def _key_and_drawing() -> m.Graph:
+ key = m.Dot()
+ return m.Graph(
+ [key, 1],
+ [(key, 1)],
+ layout={key: m.LEFT, 1: m.RIGHT},
+ vertex_mobjects={key: key},
+ )
+
+
+class _Provider(m.Scene):
+ def point(self, t: float) -> np.ndarray:
+ return np.array([t, t * t, 0.0])
+
+
+# every state a copy once went wrong in, made in one line or two
+STATES: dict[str, Callable[[], m.Mobject]] = {
+ "a group naming a member": _aliased,
+ "a number line of generated numbers": lambda: m.NumberLine(
+ (0, 3, 1), numbers_to_include=(x for x in (0, 2))
+ ),
+ "3D axes of generated numbers": lambda: m.ThreeDAxes(
+ x_range=(0, 3, 1),
+ y_range=(0, 3, 1),
+ z_range=(0, 3, 1),
+ axis_config={"numbers_to_include": _numbers(), "font_size": 18},
+ ),
+ "a curve with generated breaks": lambda: m.ParametricFunction(
+ lambda t: np.array([t, t * t, 0.0]),
+ t_range=(-2, 2, 0.25),
+ discontinuities=(v for v in [-1.0, 0.5]),
+ use_smoothing=False,
+ ),
+ "a curve of a scene's method": lambda: m.ParametricFunction(
+ _Provider().point, t_range=(-2, 2, 0.25), use_smoothing=False
+ ),
+ "flowing stream lines": _flowing,
+ "an arrow field": lambda: m.ArrowVectorField(
+ lambda p: np.array([0.2, 0.3, 0.0]),
+ colors=[m.RED, m.BLUE],
+ x_range=[0, 0, 1],
+ y_range=[0, 0, 1],
+ ),
+ "a table with shared cells": _shared_cells,
+ "a matrix with shared entries": _shared_entries,
+ "a divided sample space": _divided,
+ "a plane": lambda: m.ComplexPlane(
+ x_range=(-3, 3, 1), y_range=(-2, 2, 1), faded_line_ratio=2
+ ),
+ "3D axes in a gradient": lambda: m.ThreeDAxes(
+ x_range=(-2, 2),
+ y_range=(-2, 2),
+ z_range=(-2, 2),
+ axis_config={"stroke_color": (m.RED, m.BLUE)},
+ ),
+ "a graph with opaque keys": lambda: m.Graph(
+ list(_KEYS), [_KEYS], layout={_KEYS[0]: m.LEFT, _KEYS[1]: m.RIGHT}
+ ),
+ "a graph whose key is its drawing": _key_and_drawing,
+ "a labeled digraph": lambda: m.DiGraph(
+ [0, 1, 2],
+ [(0, 1), (1, 2), (2, 0)],
+ layout={0: [-2, 0, 0], 1: [2, 0, 0], 2: [0, 2, 0]},
+ labels={v: m.Square(0.1) for v in range(3)},
+ ),
+ "a VDict with an opaque key": lambda: m.VDict({_KEYS[0]: m.Dot()}),
+ "a variable of a subclass": lambda: m.Variable(2, "x", var_type=_Decimal),
+ "a variable's number alone": lambda: m.Variable(2, "x", var_type=m.Integer).value,
+ "a number with unit, ellipsis and background": lambda: m.DecimalNumber(
+ 7.125, unit="m", include_background_rectangle=True, show_ellipsis=True
+ ),
+ "a formula with a color map": lambda: m.MathTex(
+ "x", "+", "y", tex_to_color_map={"x": m.RED}
+ ),
+ "a formula colored by an array": lambda: m.MathTex(
+ "x", tex_to_color_map={"x": np.array([1.0, 0.0, 0.0])}
+ ),
+ "a Tex": lambda: m.Tex("x", "+", "y"),
+ "a ligature in a gradient": lambda: m.Text(
+ "ffi", gradient=[m.RED, m.GREEN, m.BLUE]
+ ),
+ "a paragraph": lambda: m.Paragraph("", "office", "ffi", t2c={"f": m.RED}),
+ "code in a window": lambda: m.Code(
+ code_string="office é\nسلام", language="python", background="window"
+ ),
+ "an SVG with defaults": lambda: m.SVGMobject(
+ _SVG,
+ svg_default={"fill_color": m.RED},
+ path_string_config={"sheen_direction": [1.0, 2.0, 3.0]},
+ ),
+ "an SVG path": lambda: m.VMobjectFromSVGPath(se.Path("M0 0 Q1 2 3 4 L6 0 Z")),
+ "a brace": lambda: m.Brace(m.Rectangle(width=5, height=2), direction=m.UP),
+ "a line with tips": _tipped,
+ "an arrow with a recorded normal": lambda: (
+ m.Arrow((-1, 2, 0.5), (2, -0.5, 3))
+ .rotate(0.31, axis=[2.0, -1.0, 3.0])
+ .reset_normal_vector()
+ ),
+ "a dot with a saved state and a target": _with_history,
+ "a polyhedron": lambda: m.Polyhedron(
+ [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)],
+ [[0, 1, 2], [0, 1, 3]],
+ graph_config={"vertex_type": m.VectorizedPoint},
+ ),
+ "a checkered surface": lambda: m.Surface(
+ saddle,
+ resolution=(2, 3),
+ checkerboard_colors=[m.RED, m.BLUE],
+ ),
+ "a mobject with updaters": _updated,
+ "a kept construction that updates itself": _Kept,
+}
+CASES = {**{f"the class {k}": v for k, v in MOBJECTS.items()}, **STATES}
+
+
+def _target(mob: m.Mobject) -> m.Mobject:
+ target = mob.generate_target()
+ mob.target = None # (the original holds its target: let the two be compared)
+ return target
+
+
+def _saved(mob: m.Mobject) -> m.Mobject:
+ mob.save_state()
+ saved = mob.saved_state
+ assert saved is not None
+ mob.saved_state = None
+ return saved
+
+
+def _animated(mob: m.Mobject) -> m.Mobject:
+ target = mob.animate.shift(m.ORIGIN).target_mobject
+ assert target is not None
+ mob.target = None # (`.animate` keeps its target as the original's)
+ return target
+
+
+REPLICATIONS: dict[str, Callable[[m.Mobject], m.Mobject]] = {
+ "copy": lambda mob: mob.copy(),
+ "target": _target,
+ "saved": _saved,
+ "animated": _animated,
+}
+
+
+def evolve(mob: m.Mobject) -> None:
+ """Change a mobject by its own means: its trackers nudged, its updaters run."""
+ for part in list(reachable(mob).values()):
+ if isinstance(part, ValueTracker) and not isinstance(part.get_value(), complex):
+ part.set_value(part.get_value() + 1)
+ random.seed(7) # (flowing lines draw where they restart)
+ mob.update(0.03)
+
+
+def borrowed(mob: m.Mobject) -> set[int]:
+ """The members a mobject holds as dictionary keys: identities, borrowed by its copies."""
+ keys = (
+ k
+ for part in reachable(mob).values()
+ if isinstance(part, dict)
+ for k in part
+ if isinstance(k, m.Mobject)
+ )
+ return {id(k) for k in keys}
+
+
[email protected]("how", sorted(REPLICATIONS))
[email protected]("name", sorted(CASES))
+def test_a_replica_is_an_independent_isomorphic_copy(name: str, how: str) -> None:
+ original = CASES[name]()
+ keys = borrowed(original)
+ family = [x for x in original.get_family() if id(x) not in keys]
+ replica = REPLICATIONS[how](original)
+ assert look(replica) == look(original)
+ assert_replica(original, replica)
+ assert not reaches(replica, family), "the replica reaches its original"
+ before = look(original)
+ evolve(replica)
+ assert look(original) == before, "changing the replica changed the original"
+ evolve(original)
+ assert look(original) == look(replica), "the replica changes unlike its original"
+
+
[email protected]("name", sorted(CASES))
+def test_a_construction_made_again_is_an_independent_isomorphic_copy(name: str) -> None:
+ first, second, third = (CASES[name]() for _ in range(3))
+ for a, b in ((first, second), (second, third)):
+ assert look(a) == look(b)
+ assert_replica(a, b)
+ keys = borrowed(a)
+ assert not reaches(b, [x for x in a.get_family() if id(x) not in keys])
+
+
+# ── updaters ──────────────────────────────────────────────────────────────────────────────
+LOG: list[tuple[str, float | None]] = [] # what the updaters saw, in order
+
+
+class Owner: # an object whose methods are updaters
+ def __init__(self, label: str) -> None:
+ self.label = label
+
+ def per_frame(self, mob: m.Mobject) -> None:
+ LOG.append((self.label, None))
+
+ def timed(self, mob: m.Mobject, dt: float) -> None:
+ LOG.append((self.label, dt))
+
+
+class MobjectOwner(m.Mobject): # a mobject whose method is an updater of another
+ def __init__(self, label: str) -> None:
+ super().__init__()
+ self.label = label
+
+ def timed(self, mob: m.Mobject, dt: float) -> None:
+ LOG.append((self.label, dt))
+
+
+class Clocked: # a callable updater on a clock of its own
+ def __init__(self, label: str) -> None:
+ self.label = label
+ self.clock = clock.Clock()
+ self.clock.warp(0, 2, 4, linear)
+
+ def __call__(self, mob: m.Mobject, dt: float) -> None:
+ LOG.append((self.label, dt))
+
+
+def _labelled(label: str, timed: bool) -> Callable[..., None]:
+ if timed:
+
+ def time_based(mob: m.Mobject, dt: float) -> None:
+ LOG.append((label, dt))
+
+ return time_based
+
+ def per_frame(mob: m.Mobject) -> None:
+ LOG.append((label, None))
+
+ return per_frame
+
+
+def label_of(updater: object) -> str | None:
+ owner = getattr(updater, "__self__", updater)
+ label = getattr(owner, "label", None)
+ if isinstance(label, str):
+ return label
+ for cell in getattr(updater, "__closure__", None) or ():
+ if isinstance(cell.cell_contents, str):
+ return cell.cell_contents
+ return None
+
+
+@dataclass
+class Slot:
+ label: str
+ timed: bool
+ owner: object | None # what must be let go once the updater is gone
+ clocked: Clocked | None = None
+ stamp: Fraction = Fraction(0)
+
+
+@dataclass
+class Model:
+ slots: list[Slot] = field(default_factory=list)
+ suspended: bool = False
+
+
+FORMS = ["function", "method", "mobject method", "clocked"]
+
+
+class Updaters(RuleBasedStateMachine):
+ """A host and its part, their updaters added, removed, suspended, copied and run, beside a
+ model of each updater's clock."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ clock.reset()
+ LOG.clear()
+ self.host: m.Mobject = m.Group(m.Mobject())
+ self.models = {"host": Model(), "part": Model()}
+ self.removed: list[object] = []
+ self.count = 0
+
+ def mob(self, which: str) -> m.Mobject:
+ return self.host if which == "host" else self.host.submobjects[0]
+
+ @initialize()
+ def a_time_based_updater(self) -> None: # (something to watch from the start)
+ self.add("host", "function", timed=True)
+
+ def drop(self, which: str, label: str) -> None:
+ model = self.models[which]
+ for slot in [s for s in model.slots if s.label == label]:
+ model.slots.remove(slot)
+ if slot.owner is not None and all(s.label != label for s in model.slots):
+ self.removed.append(slot.owner)
+
+ @rule(
+ which=st.sampled_from(["host", "part"]),
+ form=st.sampled_from(FORMS),
+ timed=st.booleans(),
+ )
+ def add(self, which: str, form: str, timed: bool) -> None:
+ self.count += 1
+ label = f"u{self.count}"
+ owner: object | None = None
+ clocked = None
+ updater: Callable[..., object]
+ if form == "function":
+ updater = _labelled(label, timed)
+ elif form == "method":
+ plain = Owner(label)
+ owner, updater = plain, plain.timed if timed else plain.per_frame
+ elif form == "mobject method":
+ mobject = MobjectOwner(label)
+ owner, updater, timed = mobject, mobject.timed, True
+ else:
+ clocked = Clocked(label)
+ owner, updater, timed = clocked, clocked, True
+ self.mob(which).add_updater(updater)
+ self.models[which].slots.append(Slot(label, timed, owner, clocked, clock.now))
+
+ @precondition(lambda self: self.models["host"].slots)
+ @rule(data=st.data())
+ def add_again(self, data: st.DataObject) -> None:
+ # the same updater again, or an equal one (a method bound anew): one clock between them
+ slot = data.draw(st.sampled_from(self.models["host"].slots))
+ updater = next(u for u in self.host.updaters if label_of(u) == slot.label)
+ owner = getattr(updater, "__self__", None)
+ if isinstance(owner, Owner) and data.draw(st.booleans()):
+ updater = getattr(owner, getattr(updater, "__name__", ""))
+ self.host.add_updater(updater)
+ model = self.models["host"]
+ model.slots.append(
+ Slot(slot.label, slot.timed, slot.owner, slot.clocked, clock.now)
+ )
+ for s in model.slots:
+ if s.label == slot.label:
+ s.stamp = clock.now
+
+ @precondition(lambda self: self.models["host"].slots)
+ @rule(data=st.data())
+ def remove(self, data: st.DataObject) -> None:
+ slot = data.draw(st.sampled_from(self.models["host"].slots))
+ for updater in [u for u in self.host.updaters if label_of(u) == slot.label]:
+ self.host.remove_updater(updater)
+ self.drop("host", slot.label)
+
+ @rule(recursive=st.booleans(), how=st.sampled_from(["clear", "match"]))
+ def clear(self, recursive: bool, how: str) -> None:
+ if how == "clear":
+ self.host.clear_updaters(recursive)
+ else:
+ self.host.match_updaters(m.Mobject()) # takes none, and clears the parts'
+ recursive = True
+ for which in ("host", "part") if recursive else ("host",):
+ for slot in list(self.models[which].slots):
+ self.drop(which, slot.label)
+
+ @precondition(lambda self: not self.models["host"].suspended)
+ @rule(recursive=st.booleans())
+ def suspend(self, recursive: bool) -> None:
+ self.host.suspend_updating(recursive)
+ for which in ("host", "part") if recursive else ("host",):
+ self.models[which].suspended = True
+
+ @precondition(lambda self: any(model.suspended for model in self.models.values()))
+ @rule(recursive=st.booleans())
+ def resume(self, recursive: bool) -> None:
+ self.host.resume_updating(recursive)
+ for which in ("host", "part") if recursive else ("host",):
+ self.models[which].suspended = False
+ for slot in self.models[which].slots:
+ slot.stamp = clock.now
+
+ @precondition(lambda self: not self.models["host"].suspended)
+ @rule(dt=st.sampled_from([Fraction(1, 2), Fraction(1)]), recursive=st.booleans())
+ def play(self, dt: Fraction, recursive: bool) -> None:
+ # an animation suspends its mobject's updating while it plays and resumes it as it
+ # finishes, and the scene goes on: the time it played is not made up
+ self.suspend(recursive)
+ self.advance(dt, None)
+ self.resume(recursive)
+ self.advance(Fraction(1, 2), None)
+
+ @rule()
+ def copy(self) -> None:
+ self.host = self.host.copy() # the copy goes on as the original would have
+
+ def expected(
+ self, dt: float | None, t: Fraction, skipped: str | None
+ ) -> list[object]:
+ calls: list[object] = []
+ if self.models["host"].suspended: # a suspended host's subtree is not run
+ return calls
+ for which in ("host", "part"):
+ model = self.models[which]
+ if model.suspended:
+ continue
+ for slot in list(model.slots):
+ if which == "host" and slot.label == skipped:
+ continue
+ if not slot.timed:
+ calls.append((slot.label, None))
+ elif dt is not None: # update: the dt given
+ calls.append((slot.label, dt))
+ else: # advance: the time its clock ran since it last ran
+ on = slot.clocked.clock if slot.clocked else None
+ ran = (
+ on.at(float(t)) - on.at(float(slot.stamp))
+ if on
+ else float(t - slot.stamp)
+ )
+ calls.append((slot.label, ran))
+ for s in model.slots: # one stamp a callable
+ if s.label == slot.label:
+ s.stamp = t
+ return calls
+
+ @rule(
+ dt=st.sampled_from([Fraction(1, 2), Fraction(1), Fraction(3, 2)]),
+ victim=st.none() | st.integers(0, 3),
+ )
+ def advance(self, dt: Fraction, victim: int | None) -> None:
+ t = clock.now + dt
+ clock.now = t
+ LOG.clear()
+ model = self.models["host"]
+ doomed = None
+ if victim is not None and model.slots and not model.suspended:
+ # an updater that removes another while the pass runs: the other never runs
+ doomed = model.slots[victim % len(model.slots)].label
+
+ def remover(mob: m.Mobject, dt: float) -> None:
+ for u in list(mob.updaters):
+ if label_of(u) == doomed:
+ mob.remove_updater(u)
+
+ self.host.add_updater(remover, index=0)
+ self.host.advance(t)
+ expected = self.expected(None, t, doomed)
+ if doomed is not None:
+ self.host.remove_updater(remover)
+ self.drop("host", doomed)
+ assert expected == LOG
+
+ @rule(dt=st.sampled_from([0.25, 1.0]))
+ def update(self, dt: float) -> None:
+ LOG.clear()
+ self.host.update(dt)
+ assert self.expected(dt, clock.now, None) == LOG
+
+ @invariant()
+ def nothing_removed_is_held(self) -> None:
+ held = reaches(self.host, self.removed)
+ assert not held, f"the host keeps removed updaters' owners alive: {held}"
+
+
+TestUpdaters = Updaters.TestCase
+TestUpdaters.settings = settings(stateful_step_count=25, max_examples=100)
+
+
+# ── values ────────────────────────────────────────────────────────────────────────────────
+def scribble(value: object) -> None:
+ """Change a value in place, however it can be changed."""
+ if isinstance(value, np.ndarray):
+ if value.flags.writeable:
+ value[...] = 0.875 if value.dtype.kind == "f" else 1
+ elif isinstance(value, list):
+ if value and isinstance(value[0], list):
+ for row in value:
+ row.reverse()
+ else:
+ value[:] = [*(x + 1 for x in value), 1.0]
+ elif isinstance(value, dict):
+ for key in value:
+ value[key] = m.GREEN
+
+
+def _regenerated(mob: m.Mobject) -> list[object]:
+ mob.reset_points().generate_points()
+ return list(look(mob))
+
+
+def _meshed(mesh: m.Mobject) -> list[object]:
+ assert isinstance(mesh, m.MeshMobject)
+ mesh.reset_points().generate_points()
+ uvs = None if mesh.uvs is None else mesh.uvs.tobytes()
+ return [*look(mesh), mesh.triangles.tobytes(), uvs]
+
+
+def _labelled_line(line: m.Mobject) -> list[object]:
+ assert isinstance(line, m.NumberLine)
+ line.add_numbers()
+ line.add_ticks()
+ return list(look(line))
+
+
+def _faces(poly: m.Mobject) -> list[object]:
+ poly.update()
+ return list(look(poly))
+
+
+def _texture(mesh: m.Mobject) -> list[object]:
+ return [np.asarray(mesh.paint.texture).tobytes()]
+
+
+@dataclass
+class Given[T]:
+ """A mobject made of an input: `make` it of a fresh input `given()`; `later` is what it
+ makes of the input afterwards (regenerated, labelled, updated)."""
+
+ make: Callable[[T], m.Mobject]
+ given: Callable[[], T]
+ later: Callable[[m.Mobject], list[object]] = _regenerated
+
+
+TRIANGLE = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 1.0, 0.0]]
+DIRECTION = [0.5, -0.25, 0.125]
+RGBAS = [[0.1, 0.2, 0.3, 0.4], [0.7, 0.6, 0.5, 0.8]]
+FACES = [[0, 1, 2], [0, 1, 3]]
+TETRA = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
+
+
+def _array(rows: list[list[float]] | list[float]) -> Callable[[], np.ndarray]:
+ return lambda: np.array(rows, dtype=float)
+
+
+def _square_with(name: str) -> Callable[[np.ndarray], m.Mobject]:
+ def make(value: np.ndarray) -> m.Mobject:
+ square = m.Square()
+ setattr(square, name, value)
+ return square
+
+ return make
+
+
+def _mesh_with(name: str) -> Callable[[np.ndarray], m.Mobject]:
+ def make(value: np.ndarray) -> m.Mobject:
+ mesh = m.MeshMobject(np.array(TETRA), np.array(FACES), uvs=np.zeros((4, 2)))
+ setattr(mesh, name, value)
+ return mesh
+
+ return make
+
+
+def saddle(u: float, v: float) -> np.ndarray:
+ return np.array([u, v, u * v])
+
+
+def _surface(u_range: list[float]) -> m.Mobject:
+ return m.Surface(saddle, u_range=u_range, resolution=2)
+
+
+INPUTS: dict[str, Given] = {
+ "polygram vertices": Given(lambda v: m.Polygram(v), _array(TRIANGLE)),
+ "polygram vertex lists": Given(
+ lambda v: m.Polygram(v), lambda: [list(r) for r in TRIANGLE]
+ ),
+ "a sheen direction made with": Given(
+ lambda v: m.Square(sheen_direction=v), _array(DIRECTION)
+ ),
+ "a sheen direction set": Given(
+ lambda v: m.Square().set_sheen_direction(v), _array(DIRECTION)
+ ),
+ "a sheen set": Given(lambda v: m.Square().set_sheen(0.25, v), _array(DIRECTION)),
+ "a style set": Given(
+ lambda v: m.Square().set_style(sheen_factor=0.25, sheen_direction=v),
+ _array(DIRECTION),
+ ),
+ "a sheen direction assigned": Given(
+ _square_with("sheen_direction"), _array(DIRECTION)
+ ),
+ "fill rows": Given(_square_with("fill_rgbas"), _array(RGBAS)),
+ "stroke rows": Given(_square_with("stroke_rgbas"), _array(RGBAS)),
+ "background stroke rows": Given(
+ _square_with("background_stroke_rgbas"), _array(RGBAS)
+ ),
+ "a large strided brush": Given(
+ _square_with("fill_rgbas"),
+ lambda: np.linspace(0, 1, 4096 * 8).reshape(4096, 8)[:, ::2],
+ ),
+ "stroke colors and opacities": Given(
+ lambda v: m.Square().set_stroke(color=v, opacity=np.array([0.25, 0.75])),
+ _array([0.1, 0.2, 0.3]),
+ ),
+ "mesh triangles assigned": Given(
+ _mesh_with("triangles"), lambda: np.array([[0, 1, 2]])
+ ),
+ "mesh texture coordinates assigned": Given(
+ _mesh_with("uvs"), _array([[0.1, 0.2]] * 4)
+ ),
+ "a dictionary argument": Given(
+ lambda v: m.MathTex("x", "+", "y", tex_to_color_map=dict(v)),
+ lambda: {"x": m.RED},
+ ),
+ "mesh vertices made with": Given(
+ lambda v: m.MeshMobject(np.asarray(v), np.array(FACES)), _array(TETRA), _meshed
+ ),
+ "mesh triangles made with": Given(
+ lambda v: m.MeshMobject(np.array(TETRA), np.asarray(v)),
+ lambda: np.array(FACES),
+ _meshed,
+ ),
+ "a surface's range": Given(_surface, lambda: [-1.0, 1.0]),
+ "a curve's breaks": Given(
+ lambda v: m.ParametricFunction(
+ lambda t: np.array([t, t * t, 0.0]),
+ t_range=(-2, 2, 0.25),
+ discontinuities=v,
+ use_smoothing=False,
+ ),
+ lambda: [-1.0, 0.5],
+ ),
+ "a number line's exclusions": Given(
+ lambda v: m.NumberLine((0, 3, 1), include_ticks=False, numbers_to_exclude=v),
+ lambda: [0.0, 2.0],
+ _labelled_line,
+ ),
+ "a number line's elongated ticks": Given(
+ lambda v: m.NumberLine(
+ (0, 3, 1), include_ticks=False, numbers_with_elongated_ticks=v
+ ),
+ _array([0.0, 2.0]),
+ _labelled_line,
+ ),
+ "a polyhedron's faces": Given(
+ lambda v: m.Polyhedron(
+ TETRA, v, graph_config={"vertex_type": m.VectorizedPoint}
+ ),
+ lambda: [list(f) for f in FACES],
+ _faces,
+ ),
+ "a mesh's texture": Given(
+ lambda v: m.MeshMobject(
+ np.array(TETRA),
+ np.array(FACES),
+ uvs=np.zeros((4, 2)),
+ texture=np.asarray(v),
+ ),
+ lambda: np.full((2, 2, 4), 37, dtype=np.uint8),
+ _texture,
+ ),
+}
+
+
+class _Subclass(np.ndarray):
+ """An array of a subclass of ndarray: still a value."""
+
+
+def _kind(given: np.ndarray, kind: str) -> tuple[np.ndarray, np.ndarray]:
+ """An array input in one of the forms a caller may hold it in (`held`), and a writable
+ alias of it, which the caller may still change it through (`writer`)."""
+ owner = given.astype(np.float32) if kind == "float32" else given
+ if kind == "strided":
+ wide = np.zeros((*owner.shape[:-1], owner.shape[-1] * 2), dtype=owner.dtype)
+ wide[..., ::2] = owner
+ owner = wide[..., ::2]
+ writer = owner.view()
+ held = owner.view(_Subclass) if kind == "a subclass" else owner
+ if kind == "a read-only view":
+ held = owner.view()
+ held.flags.writeable = False
+ elif kind == "read-only":
+ held.flags.writeable = False
+ return held, writer
+
+
+KINDS = ["owned", "a read-only view", "read-only", "strided", "float32", "a subclass"]
+
+
[email protected]("name", sorted(INPUTS))
+def test_an_input_is_a_value(name: str) -> None:
+ case = INPUTS[name]
+ given, pristine = case.given(), case.given()
+ writeable = given.flags.writeable if isinstance(given, np.ndarray) else None
+ mob = case.make(given)
+ if isinstance(given, np.ndarray): # making it changes no input
+ np.testing.assert_array_equal(given, pristine)
+ assert given.flags.writeable == writeable
+ shown = look(mob)
+ scribble(given)
+ assert look(mob) == shown, "changing the input after changed the mobject"
+ assert case.later(mob) == case.later(case.make(pristine)), (
+ "changing the input after changed what the mobject makes of it"
+ )
+
+
+ARRAYS = [ # the array inputs a caller may hold in any form
+ n for n in sorted(INPUTS) if isinstance(INPUTS[n].given(), np.ndarray)
+]
+
+
[email protected]("kind", KINDS)
[email protected]("name", ARRAYS)
+def test_an_array_input_is_a_value_however_it_is_held(name: str, kind: str) -> None:
+ case = INPUTS[name]
+ given = case.given()
+ assert isinstance(given, np.ndarray)
+ held, writer = _kind(given, kind)
+ writeable = held.flags.writeable
+ mob = case.make(held)
+ copy = mob.copy()
+ assert held.flags.writeable == writeable
+ shown = look(mob)
+ writer[...] = 0.875 if writer.dtype.kind == "f" else 1
+ assert look(mob) == shown, "a writable alias of the input changed the mobject"
+ assert look(copy) == shown, "a writable alias of the input changed its copy"
+
+
+class Probe(dict[str, object]):
+ """A mapping a reachability check can find by its identity."""
+
+
+class Selection:
+ """A one-shot iterator of numbers, never to be copied."""
+
+ def __init__(self) -> None:
+ self.values = iter((1.0, 2.0))
+
+ def __iter__(self) -> "Selection":
+ return self
+
+ def __next__(self) -> float:
+ return next(self.values)
+
+ def __deepcopy__(self, memo: dict[int, object]) -> "Selection":
+ raise AssertionError("a consumed iterator is not drawing state")
+
+
+class Factory:
+ """A vertex factory: an object, kept or not by what it makes."""
+
+ def __call__(self, **kwargs: object) -> m.VectorizedPoint:
+ return m.VectorizedPoint()
+
+
+def _view_of_storage() -> np.ndarray:
+ storage = np.zeros((1 << 12, 3))
+ storage[:4] = TETRA
+ return storage[:4]
+
+
+def _laid_out(probe: list[object]) -> m.Mobject:
+ def layout(graph: object, **kwargs: object) -> dict[int, list[float]]:
+ probe.append(graph)
+ return {0: [0.0, 0.0], 1: [1.0, 0.0]}
+
+ return m.Graph([0, 1], [(0, 1)], layout=layout)
+
+
+@dataclass
+class Unshown[T]:
+ """A mobject made of an input it does not show: `make` it of a fresh `given()`."""
+
+ make: Callable[[T], m.Mobject]
+ given: Callable[[], T]
+
+
+UNSHOWN: dict[str, Unshown] = {
+ "a matrix's alignment corner": Unshown(
+ lambda v: m.MobjectMatrix(
+ [[m.Square(0.4)]], element_alignment_corner=np.asarray(v)
+ ),
+ lambda: np.array([1.0, -1.0, 0.0]),
+ ),
+ "a table's line options": Unshown(
+ lambda v: m.MobjectTable([[m.Square(0.3)]], line_config=cast(LineOptions, v)),
+ Probe,
+ ),
+ "a table's grid options": Unshown(
+ lambda v: m.MobjectTable(
+ [[m.Square(0.3)]], arrange_in_grid_config=cast(GridArrangement, v)
+ ),
+ Probe,
+ ),
+ "a plane's faded style": Unshown(
+ lambda v: m.NumberPlane(faded_line_style=cast(Style, v), faded_line_ratio=2),
+ lambda: Probe(stroke_color=m.RED),
+ ),
+ "a polar plane's background color": Unshown(
+ lambda v: m.PolarPlane(background_line_style={"stroke_color": np.asarray(v)}),
+ lambda: np.array([0.2, 0.4, 0.6]),
+ ),
+ "a number line's selection": Unshown(
+ lambda v: m.NumberLine((0, 3, 1), numbers_to_include=v), Selection
+ ),
+ "a number line's exclusion iterator": Unshown(
+ lambda v: m.NumberLine((0, 3, 1), include_ticks=False, numbers_to_exclude=v),
+ Selection,
+ ),
+ "3D axes' selection": Unshown(
+ lambda v: m.ThreeDAxes(
+ x_range=(0, 3, 1),
+ y_range=(0, 3, 1),
+ z_range=(0, 3, 1),
+ axis_config={"numbers_to_include": v, "font_size": 18},
+ ),
+ Selection,
+ ),
+ "a curve's break iterator": Unshown(
+ lambda v: m.ParametricFunction(
+ lambda t: np.array([t, t, 0.0]), t_range=(-2, 2, 0.5), discontinuities=v
+ ),
+ Selection,
+ ),
+ "a polyhedron's vertex views": Unshown(
+ lambda v: m.Polyhedron(
+ np.asarray(v), FACES, graph_config={"vertex_type": m.VectorizedPoint}
+ ),
+ _view_of_storage,
+ ),
+ "a polyhedron's vertex factory": Unshown(
+ lambda v: m.Polyhedron(TETRA, FACES, graph_config={"vertex_type": v}),
+ Factory,
+ ),
+ "a polygram's vertex view": Unshown(
+ lambda v: m.Polygram(np.asarray(v)[:3]), _view_of_storage
+ ),
+ "an arc's ignored normal": Unshown(
+ lambda v: m.Arc(normal_vector=np.asarray(v)), lambda: np.ones((1 << 12, 3))[3]
+ ),
+ "a surface's ignored piece options": Unshown(
+ lambda v: m.Surface(
+ lambda u, w: np.array([u, w, 0.0]),
+ resolution=2,
+ surface_piece_config=cast(Style, v),
+ ),
+ lambda: Probe(target=m.Group(*(m.Dot() for _ in range(8)))),
+ ),
+ "a rectangle's target": Unshown(
+ lambda v: m.SurroundingRectangle(v),
+ lambda: m.Circle().set_color(m.RED),
+ ),
+ "a parsed SVG path": Unshown(
+ lambda v: m.VMobjectFromSVGPath(v),
+ lambda: se.Path("M0 0 L2 0 L2 1 Z"),
+ ),
+ "a view assigned as a mesh's triangles": Unshown(
+ _mesh_with("triangles"), lambda: np.ones((4096, 3), dtype=np.int64)[:2]
+ ),
+ "a sheen direction made with": Unshown(
+ lambda v: m.Square(sheen_direction=np.asarray(v)), _array(DIRECTION)
+ ),
+ "fill rows assigned": Unshown(_square_with("fill_rgbas"), _array(RGBAS)),
+ "the graph a layout is handed": Unshown(_laid_out, list),
+}
+
+
[email protected]("name", sorted(UNSHOWN))
+def test_what_it_does_not_show_it_does_not_keep(name: str) -> None:
+ case = UNSHOWN[name]
+ given = case.given()
+ mob = case.make(given)
+ gone = (
+ [*given] if isinstance(given, list) else [given]
+ ) # (a layout's: what it was handed)
+ gone += [x.base for x in gone if isinstance(x, np.ndarray) and x.base is not None]
+ assert not reaches(mob, gone), "the mobject keeps an input it does not show"
+ mob.copy() # (an input it kept, a copy would copy)
+
+
+# what an edit replaces is not kept either: (a mobject, the edit, what the edit replaces)
+EDITS: dict[
+ str,
+ tuple[
+ Callable[[], m.Mobject],
+ Callable[[m.Mobject], object],
+ Callable[[m.Mobject], object],
+ ],
+] = {
+ "thinned": (
+ lambda: m.PMobject().add_points(np.zeros((1000, 3))),
+ lambda cloud: cloud.thin_out(100) if isinstance(cloud, m.PMobject) else None,
+ lambda cloud: cloud.paint.fill,
+ ),
+ "a target replaced": (
+ lambda: m.Mobject(target=m.Square()),
+ lambda mob: setattr(mob, "target", None),
+ lambda mob: mob.target,
+ ),
+ "a number's unit dropped": (
+ lambda: m.DecimalNumber(7, unit="m"),
+ lambda n: (
+ (setattr(n, "unit", None), n.set_value(7))
+ if isinstance(n, m.DecimalNumber)
+ else None
+ ),
+ lambda n: n.submobjects[-1],
+ ),
+ "a number's background dropped": (
+ lambda: m.DecimalNumber(7, include_background_rectangle=True),
+ lambda n: (
+ (setattr(n, "include_background_rectangle", False), n.set_value(7))
+ if isinstance(n, m.DecimalNumber)
+ else None
+ ),
+ lambda n: n.submobjects[0],
+ ),
+ "a number's added background, redrawn": (
+ lambda: m.DecimalNumber(7).add_background_rectangle(),
+ lambda n: n.set_value(8) if isinstance(n, m.DecimalNumber) else None,
+ lambda n: n.submobjects[0],
+ ),
+}
+
+
[email protected]("name", sorted(EDITS))
+def test_what_an_edit_replaces_is_not_kept(name: str) -> None:
+ make, edit, replaced = EDITS[name]
+ mob = make()
+ old = replaced(mob)
+ edit(mob)
+ assert not reaches(mob, [old]), "the mobject keeps what the edit replaced"
+
+
+def _numbers_of(line: m.Mobject) -> list[object]:
+ assert isinstance(line, m.NumberLine)
+ line.add_numbers()
+ return list(look(line))
+
+
+def _regenerate(mob: m.Mobject) -> list[object]:
+ return _regenerated(mob)
+
+
+def _bars(one_shot: bool) -> m.Mobject:
+ chart = m.BarChart([3, 0, -2], y_range=(-10, 10, 20))
+ for values in ([5, 1, -4], [4], [1, -2, 0]):
+ chart.change_bar_values(iter(values) if one_shot else values)
+ return chart
+
+
+def _line(name: str) -> Callable[[bool], m.Mobject]:
+ def make(one_shot: bool) -> m.Mobject:
+ values = [0.0, 2.0]
+ given = iter(values) if one_shot else values
+ if name == "numbers_to_include":
+ return m.NumberLine((0, 3, 1), numbers_to_include=given)
+ if name == "numbers_to_exclude":
+ return m.NumberLine(
+ (0, 3, 1), include_numbers=True, numbers_to_exclude=given
+ )
+ return m.NumberLine((0, 3, 1), numbers_with_elongated_ticks=given)
+
+ return make
+
+
+def _breaks(vectorized: bool) -> Callable[[bool], m.Mobject]:
+ def make(one_shot: bool) -> m.Mobject:
+ values = [-1.0, 0.5]
+ return m.ParametricFunction(
+ (lambda t: np.array([t, t * t, np.zeros_like(t)]))
+ if vectorized
+ else (lambda t: np.array([t, t * t, 0.0])),
+ t_range=(-2, 2, 0.25),
+ discontinuities=iter(values) if one_shot else values,
+ use_vectorized=vectorized,
+ )
+
+ return make
+
+
+def _axes(one_shot: bool) -> m.Mobject:
+ values = [1.0, 2.0]
+ return m.Axes(
+ x_range=(0, 3, 1),
+ y_range=(0, 3, 1),
+ axis_config={"numbers_to_include": iter(values) if one_shot else values},
+ )
+
+
+def _palette(one_shot: bool) -> m.Mobject:
+ colors = [m.RED, m.BLUE]
+ return m.Surface(
+ saddle,
+ resolution=2,
+ checkerboard_colors=iter(colors) if one_shot else colors,
+ )
+
+
+# what is made of an iterable: of its items once (one_shot) or of the list of them
+ITERABLES: dict[
+ str, tuple[Callable[[bool], m.Mobject], Callable[[m.Mobject], list[object]]]
+] = {
+ "a number line's numbers": (_line("numbers_to_include"), _numbers_of),
+ "a number line's exclusions": (_line("numbers_to_exclude"), _numbers_of),
+ "a number line's elongated ticks": (
+ _line("numbers_with_elongated_ticks"),
+ _numbers_of,
+ ),
+ "a curve's breaks": (_breaks(False), _regenerate),
+ "a vectorized curve's breaks": (_breaks(True), _regenerate),
+ "axes' numbers": (_axes, lambda mob: list(look(mob))),
+ "a surface's palette": (_palette, lambda mob: list(look(mob))),
+ "a chart's values, changed": (_bars, lambda mob: list(look(mob))),
+}
+
+
[email protected]("name", sorted(ITERABLES))
+def test_an_iterator_gives_what_the_list_of_its_items_gives(name: str) -> None:
+ make, later = ITERABLES[name]
+ once, listed = make(True), make(False)
+ assert look(once) == look(listed)
+ assert look(once.copy()) == look(listed.copy())
+ assert later(once) == later(listed)
+
+
+IGNORED: dict[str, tuple[Callable[[], m.Mobject], Callable[[], m.Mobject]]] = {
+ "an arc's normal": (lambda: m.Arc(normal_vector=[1.0, 2.0, 3.0]), lambda: m.Arc()),
+ "a tipped line's normal": (
+ lambda: (
+ m.Line((-1, 2, 0.5), (2, -0.5, 3), normal_vector=[2.0, -1.0, 5.0])
+ .add_tip()
+ .add_tip(at_start=True)
+ .rotate(0.37, axis=[1.0, 2.0, 3.0])
+ ),
+ lambda: (
+ m.Line((-1, 2, 0.5), (2, -0.5, 3))
+ .add_tip()
+ .add_tip(at_start=True)
+ .rotate(0.37, axis=[1.0, 2.0, 3.0])
+ ),
+ ),
+ "an SVG path's options": (
+ lambda: m.VMobjectFromSVGPath(
+ se.Path("M0 0 Q1 2 3 4 C4 4 5 2 6 0 L6 0 Z"),
+ long_lines=True,
+ should_subdivide_sharp_curves=True,
+ should_remove_null_curves=True,
+ ),
+ lambda: m.VMobjectFromSVGPath(se.Path("M0 0 Q1 2 3 4 C4 4 5 2 6 0 L6 0 Z")),
+ ),
+ "a surface's options": (
+ lambda: m.Surface(
+ saddle,
+ resolution=2,
+ should_make_jagged=True,
+ pre_function_handle_to_anchor_scale_factor=0.25,
+ surface_piece_config={"color": m.RED},
+ ),
+ lambda: m.Surface(saddle, resolution=2),
+ ),
+}
+
+
[email protected]("name", sorted(IGNORED))
+def test_an_ignored_option_is_ignored_and_not_kept(name: str) -> None:
+ given, plain = (make() for make in IGNORED[name])
+ assert_replica(
+ plain, given
+ ) # (the same parts, to the attribute: nothing kept of it)
+
+
+# what a query answers: (the query, its arguments)
+QUERIES: dict[str, tuple[object, ...]] = {
+ "get_center": (),
+ "get_critical_point": (m.UR,),
+ "get_start": (),
+ "get_end": (),
+ "get_all_points": (),
+ "get_points_defining_boundary": (),
+ "get_anchors": (),
+ "get_start_anchors": (),
+ "get_subpaths": (),
+ "get_cubic_bezier_tuples": (),
+ "get_nth_curve_length_pieces": (0,),
+ "reveal_pace": (),
+ "get_gradient_start_and_end_points": (),
+ "get_all_rgbas": (),
+ "get_stroke_rgbas": (),
+ "boundary_box": (),
+ "get_updaters": (),
+} # (get_family answers with the mobject's own list: Manim's API)
+
+
+def _ask(mob: m.Mobject, query: str) -> object:
+ method = getattr(mob, query, None)
+ if not callable(method):
+ return None
+ try:
+ return method(*QUERIES[query])
+ except Exception: # (a query this mobject cannot answer)
+ return None
+
+
+def _frozen(value: object) -> object:
+ if isinstance(value, np.ndarray):
+ return value.copy()
+ if isinstance(value, (tuple, list)):
+ return [_frozen(v) for v in value]
+ return value
+
+
+def _same(a: object, b: object) -> bool:
+ if isinstance(a, np.ndarray):
+ return isinstance(b, np.ndarray) and np.array_equal(a, b, equal_nan=True)
+ if isinstance(a, (tuple, list)) and isinstance(b, (tuple, list)):
+ return len(a) == len(b) and all(map(_same, a, b))
+ return a is b or a == b
+
+
+def _scribble_all(value: object) -> None:
+ if isinstance(value, np.ndarray) and value.flags.writeable:
+ value[...] = 50
+ elif isinstance(value, (tuple, list)):
+ for v in value:
+ _scribble_all(v)
+
+
[email protected]("name", sorted(MOBJECTS))
+def test_what_a_query_returns_is_a_value(name: str) -> None:
+ mob = MOBJECTS[name]()
+ for query in QUERIES:
+ if query == "boundary_box":
+ continue # (its own law, below)
+ answer = _ask(mob, query)
+ before, shown = _frozen(answer), look(mob)
+ _scribble_all(answer)
+ assert look(mob) == shown, f"changing what {query} returned changed the mobject"
+ assert _same(_ask(mob, query), before), (
+ f"changing {query}'s answer changed the next"
+ )
+
+
[email protected]("name", sorted(MOBJECTS))
+def test_the_box_returned_is_a_value(name: str) -> None:
+ mob = MOBJECTS[name]()
+ box = mob.boundary_box()
+ if box is None:
+ return
+ before, shown = box.copy(), look(mob)
+ if box.flags.writeable:
+ box[...] = 50
+ assert look(mob) == shown
+ assert _same(mob.boundary_box(), before)
+
+
+def _writable_constants() -> list[np.ndarray]:
+ import sys
+
+ return [
+ value
+ for name, module in list(sys.modules.items())
+ if name.startswith("manimgx") and module is not None
+ for value in vars(module).values()
+ if isinstance(value, np.ndarray) and value.flags.writeable
+ ]
+
+
[email protected]("name", sorted(MOBJECTS))
+def test_nothing_it_holds_is_a_constant(name: str) -> None:
+ held = reaches(MOBJECTS[name](), _writable_constants())
+ assert not held, "it holds one of manimgx's writable constants"
+
+
+# ── defaults and memories ─────────────────────────────────────────────────────────────────
+class Base(m.Mobject):
+ def __init__(self, tag: str = "base", value: int = 0) -> None:
+ super().__init__()
+ self.made: tuple[object, ...] = (tag, value)
+
+
+class Child(Base):
+ pass
+
+
+class Grand(Child):
+ def __init__(self, tag: str = "grand", value: int = 0) -> None:
+ super().__init__(tag=tag, value=value)
+
+
+class Left(Base):
+ pass
+
+
+class Right(Base):
+ def __init__(self, tag: str = "right", value: int = 0) -> None:
+ super().__init__(tag=tag, value=value)
+ self.made = (*self.made, "right") # (what tells that this constructor ran)
+
+
+class Diamond(Left, Right):
+ pass
+
+
+class Kept(Base):
+ @prototype
+ def __init__(self, tag: str = "kept", value: int = 0) -> None:
+ super().__init__(tag=tag, value=value)
+
+
+OWN: dict[type, dict[str, object]] = { # the classes with constructors of their own
+ Base: {"tag": "base", "value": 0},
+ Grand: {"tag": "grand", "value": 0},
+ Right: {"tag": "right", "value": 0},
+ Kept: {"tag": "kept", "value": 0},
+}
+HIERARCHIES: dict[str, list[type[Base]]] = {
+ "flat": [Base, Kept],
+ "chain": [Base, Child, Grand],
+ "diamond": [Base, Left, Right, Diamond],
+}
+
+
+def made_by(cls: type, configured: dict[type, dict[str, object]]) -> tuple[object, ...]:
+ """What `cls()` makes, by its MRO: the classes before the first constructor of its own lend
+ their defaults (the nearest's over the farther's) to that constructor, over its own."""
+ lent: dict[str, object] = {}
+ for klass in cls.__mro__:
+ if klass in OWN:
+ values = OWN[klass] | configured.get(klass, {}) | lent
+ ran = [k for k in cls.__mro__ if k in OWN] # the constructors that run
+ return (
+ values["tag"],
+ values["value"],
+ *(["right"] if Right in ran else []),
+ )
+ for key, value in configured.get(klass, {}).items():
+ lent.setdefault(key, value)
+ raise AssertionError(f"{cls.__name__} has no constructor")
+
+
+steps = st.lists(
+ st.tuples(
+ st.integers(0, 3),
+ st.none()
+ | st.fixed_dictionaries(
+ {"value": st.integers(1, 3)}, optional={"tag": st.sampled_from(["x", "y"])}
+ ),
+ ),
+ max_size=6,
+)
+
+
[email protected]("hierarchy", ["flat", "chain", "diamond"])
+@settings(max_examples=30)
+@given(steps=steps)
+@example(steps=[(1, {"value": 1}), (0, {"tag": "x"})]) # a child, then its parent
+@example(steps=[(1, {"tag": "left"})]) # a mixin
+def test_defaults_are_partial_application(
+ hierarchy: str, steps: list[tuple[int, dict[str, object] | None]]
+) -> None:
+ classes = HIERARCHIES[hierarchy]
+ configured: dict[type, dict[str, object]] = {}
+ try:
+ for index, given in steps:
+ cls = classes[index % len(classes)]
+ if given is None:
+ cls.set_default()
+ configured.pop(cls, None)
+ else:
+ cls.set_default(**given)
+ configured[cls] = given
+ for klass in classes:
+ assert klass().made == made_by(klass, configured), klass.__name__
+ finally:
+ for cls in classes:
+ cls.set_default()
+
+
+def test_an_unknown_default_is_an_error_when_it_is_used() -> None:
+ try:
+ Base.set_default(unknown=True)
+ with pytest.raises(TypeError, match="unknown"):
+ Base()
+ finally:
+ Base.set_default()
+ assert Base().made == ("base", 0)
+
+
+# constructions whose memories defaults must reach (and what they remember)
+CALLS: dict[str, Callable[[], m.Mobject]] = {
+ "a text": lambda: m.Text("HH"),
+ "a tabbed text": lambda: m.Text("a\tb", tab_width=4),
+ "a spaced text": lambda: m.Text("a b"),
+ "an aligned formula": lambda: m.SingleStringMathTex("x", tex_environment="align*"),
+ "an equation": lambda: m.SingleStringMathTex("x", tex_environment="equation*"),
+ # (numbers of the same digits, told apart by their class, their unit)
+ "a number in text": lambda: m.DecimalNumber(
+ 12, num_decimal_places=0, mob_class=m.Text
+ ),
+ "a number in math": lambda: m.DecimalNumber(
+ 12, num_decimal_places=0, mob_class=m.MathTex, color=m.RED
+ ),
+ "a number with a unit": lambda: m.DecimalNumber(7.125, unit="m"),
+ "a number without": lambda: m.DecimalNumber(7.125),
+ "code": lambda: m.Code(code_string="x\ny"),
+ "a paragraph": lambda: m.Paragraph("a", "b"),
+ "a division": lambda: m.SampleSpace().get_vertical_division(0.4),
+ "riemann rectangles": lambda: _riemann(),
+ "a red formula": lambda: m.MathTex("x+y", tex_to_color_map={"x": m.RED}),
+ "a blue formula": lambda: m.MathTex("x+y", tex_to_color_map={"x": m.BLUE}),
+ "a text colored ab then a": lambda: m.Text("ab", t2c={"ab": m.RED, "a": m.BLUE}),
+ "a text colored a then ab": lambda: m.Text("ab", t2c={"a": m.BLUE, "ab": m.RED}),
+ "a kept construction": lambda: Kept(),
+ "a subclass setting its input first": lambda: _Inputs("first"),
+ "the same subclass, another input": lambda: _Inputs("second"),
+ "a variable of a subclass": lambda: m.Variable(1.125, "x", var_type=_Integer),
+ "a checkered surface": lambda: m.Surface(lambda u, v: np.array([u, v, 0.0])),
+}
+
+
+class _Integer(m.Integer):
+ pass
+
+
+class _Marked(
+ m.Mobject
+): # a kept constructor that draws by an input set before it runs
+ @prototype
+ def __init__(self) -> None:
+ super().__init__()
+ self.add(m.Square(1 + len(str(vars(self)["marker"]))))
+
+
+class _Inputs(_Marked):
+ def __init__(self, marker: str) -> None:
+ self.marker = marker
+ super().__init__()
+
+
+def _riemann() -> m.Mobject:
+ axes = m.Axes(x_range=(0, 3), y_range=(0, 6), tips=False)
+ graph = axes.plot(lambda x: x + 2, x_range=(0, 2, 0.5))
+ return axes.get_riemann_rectangles(graph, x_range=(0, 1), dx=1)
+
+
+DEFAULTED: list[tuple[type[m.Mobject], dict[str, object]]] = [
+ (m.Text, {"weight": m.BOLD}),
+ (m.Typst, {"typst_preamble": "#set text(tracking: 8pt)"}),
+ (m.VGroup, {"color": m.RED}), # (VGroup is Group)
+ (m.Rectangle, {"width": 3.7, "height": 1.9, "grid_xstep": 0.4}),
+ (m.DecimalNumber, {"num_decimal_places": 3}),
+ (_Integer, {"num_decimal_places": 4}),
+ (m.Surface, {"checkerboard_colors": [m.RED, m.YELLOW], "resolution": 2}),
+ (Base, {"tag": "configured"}),
+]
+
+
[email protected]("call", sorted(CALLS))
+ "defaulted", range(len(DEFAULTED)), ids=[f"{c.__name__}" for c, _ in DEFAULTED]
+)
+def test_a_construction_follows_the_defaults_and_remembers_nothing_else(
+ call: str, defaulted: int
+) -> None:
+ cls, given = DEFAULTED[defaulted]
+ make = CALLS[call]
+ earlier = make() # (and so remembered)
+ seen = look(earlier)
+ earlier.copy().shift(m.UP).set_color(
+ m.PINK
+ ) # (a changed copy is no construction's)
+ try:
+ cls.set_default(**given)
+ warm = (make(), make())[1]
+ caches.clear()
+ cold = make()
+ assert look(warm) == look(cold), (
+ "a memory outlived the defaults it was made with"
+ )
+ assert look(earlier) == seen, (
+ "changing the defaults changed a mobject made before"
+ )
+ finally:
+ cls.set_default()
+ assert look(make()) == seen, "restoring the defaults left something behind"
+
+
+def test_font_defaults_reach_remembered_text(two_fonts: tuple[str, str]) -> None:
+ first, second = two_fonts
+ try:
+ m.Typst.set_default(font_paths=[first])
+ before = m.Text("HH")
+ explicit = m.Text("HH", font_paths=[])
+ m.Typst.set_default(font_paths=[second])
+ warm = m.Text("HH")
+ caches.clear()
+ cold = m.Text("HH")
+ assert look(warm) == look(cold)
+ assert (
+ warm.width != before.width
+ ) # (the fonts differ: the law has something to see)
+ assert look(m.Text("HH", font_paths=[])) == look(explicit)
+ finally:
+ m.Typst.set_default()
+
+
+ANY_ORDER = [*sorted(MOBJECTS), *sorted(CALLS)]
+
+
+def _call(name: str) -> m.Mobject:
+ return MOBJECTS[name]() if name in MOBJECTS else CALLS[name]()
+
+
+@settings(max_examples=3)
+@given(order=st.permutations(ANY_ORDER))
+def test_whatever_was_made_before_a_construction_is_as_if_made_from_nothing(
+ order: list[str],
+) -> None:
+ warm = [_call(name) for name in order]
+ for name, made in zip(order, warm, strict=True):
+ caches.clear()
+ cold = _call(name)
+ assert look(made) == look(cold), name
+ assert_replica(cold, made)
+ held: dict[int, str] = {} # and no two constructions share a mutable part
+ for name, made in zip(order, warm, strict=True):
+ for key in oracles.mutable_parts(made):
+ assert held.setdefault(key, name) == name, f"{name} and {held[key]} share"
+
+
+class TestPoints:
+ @given(points=arrays((9, 3)), others=arrays((9, 3)))
+ def test_others_are_taken(self, points: np.ndarray, others: np.ndarray) -> None:
+ assume(not np.array_equal(points, others))
+ mob = m.VMobject().set_points(points)
+ mob.points = others
+ np.testing.assert_array_equal(
+ mob.points, m.VMobject().set_points(others).points
+ )
+
+
+@given(
+ size=st.integers(1, 6),
+ addition=st.integers(-3, 12),
+ numpy=st.booleans(),
+ repeated=st.booleans(),
+)
+@example(size=128, addition=1, numpy=False, repeated=False)
+def test_a_grown_family_follows_each_part_with_invisible_copies(
+ size: int, addition: int, numpy: bool, repeated: bool
+) -> None:
+ marks = [m.Square(0.2, fill_opacity=0.4).shift(i * m.RIGHT) for i in range(size)]
+ parts = [
+ *marks,
+ *([marks[0]] if repeated else []),
+ ] # (one part held twice, by hand)
+ owner = m.VGroup()
+ owner.submobjects = list(parts)
+ assert (
+ owner.add_n_more_submobjects(
+ cast("int", np.int64(addition)) if numpy else addition
+ )
+ is owner
+ )
+ if addition <= 0:
+ assert owner.submobjects == parts
+ return
+ grown = owner.submobjects
+ assert len(grown) == len(parts) + addition
+ seen: set[int] = set()
+ for index, part in enumerate(grown):
+ source = index * len(parts) // len(grown) # spread as evenly as can be
+ if source not in seen: # each part first, itself
+ assert part is parts[source]
+ seen.add(source)
+ else: # then copies of it, which show nothing
+ assert part is not parts[source]
+ np.testing.assert_array_equal(part.points, parts[source].points)
+ assert part.get_fill_opacity() == part.get_stroke_opacity() == 0
+ assert len({id(part) for part in grown}) == len({id(p) for p in parts}) + addition
+
+
+unit = st.floats(0, 1)
+
+
+class TestLength:
+ @given(points=curves(max_curves=3), alpha=unit)
+ def test_a_proportion_is_by_length(self, points: np.ndarray, alpha: float) -> None:
+ mob = m.VMobject()
+ mob.points = points
+ lengths = oracles.arc_lengths(points)
+ assume(lengths.sum() > 1e-2)
+ u = mob._geometry.parameter_at(alpha) # where point_from_proportion goes
+ n = min(int(u), len(lengths) - 1)
+ part = oracles.arc_lengths(
+ partial_bezier_points(points[4 * n : 4 * n + 4], 0, u - n)
+ )
+ reached = (lengths[:n].sum() + part.sum()) / lengths.sum()
+ # measured by nine straight pieces a curve: right to within the piece it falls in
+ piece = mob._geometry.piece_lengths().max() / lengths.sum()
+ assert reached == pytest.approx(alpha, abs=piece + 1e-9)
+ np.testing.assert_allclose(
+ mob.point_from_proportion(alpha), bezier(points[4 * n : 4 * n + 4])(u - n)
+ )
+
+ @given(mob=paths(), alpha=unit)
+ def test_proportion_from_point_is_its_inverse(
+ self, mob: m.VMobject, alpha: float
+ ) -> None:
+ assume(mob.get_arc_length() > 1e-3)
+ point = mob.point_from_proportion(alpha)
+ back = mob.proportion_from_point(point)
+ # the first curve the point is on, to its tolerance (100 × 1e-6) counts
+ np.testing.assert_allclose(
+ mob.point_from_proportion(back),
+ point,
+ atol=1e-4 * (1 + np.abs(point).max()),
+ )
+
+ @given(mob=paths(), alpha=unit)
+ def test_a_reveal_has_drawn_to_the_point_at_its_proportion(
+ self, mob: m.VMobject, alpha: float
+ ) -> None:
+ paint = mob.paint.but(trim=np.array([0.0, alpha]), pace=mob.reveal_pace())
+ _, reached = paint.window(mob.get_num_curves())
+ n = min(int(reached), mob.get_num_curves() - 1)
+ np.testing.assert_allclose(
+ bezier(mob.get_nth_curve_points(n))(reached - n),
+ mob.point_from_proportion(alpha),
+ atol=1e-9,
+ )
+
+ @given(mob=paths())
+ def test_the_length_is_its_straight_pieces_and_no_more_than_the_arc(
+ self, mob: m.VMobject
+ ) -> None:
+ drawn = oracles.bezier_points(
+ mob.points, np.linspace(0, 1, 10)
+ ) # 9 pieces a curve
+ pieces = np.linalg.norm(np.diff(drawn, axis=1), axis=2).sum()
+ true = float(oracles.arc_lengths(mob.points).sum())
+ measured = mob.get_arc_length()
+ assert measured == pytest.approx(pieces, rel=1e-12, abs=1e-12)
+ assert (
+ measured <= true * (1 + 1e-9) + 1e-12
+ ) # chords are never longer than arcs
+ assert mob.get_arc_length(200) == pytest.approx(true, rel=1e-3, abs=1e-9)
+
+ @given(radius=st.floats(0.1, 10))
+ def test_a_circles_length_is_two_pi_r(self, radius: float) -> None:
+ assert m.Circle(radius=radius).get_arc_length() == pytest.approx(
+ 2 * np.pi * radius, rel=5e-4
+ )
+
+
+class TestBuilding:
+ @given(corners=st.integers(2, 8).flatmap(lambda n: arrays((n, 3), 10)))
+ def test_corners_are_joined_by_straight_curves(self, corners: np.ndarray) -> None:
+ mob = m.VMobject().set_points_as_corners(corners)
+ curves_ = mob.points.reshape(-1, 4, 3)
+ np.testing.assert_allclose(curves_[:, 0], corners[:-1], atol=1e-12)
+ np.testing.assert_allclose(curves_[:, 3], corners[1:], atol=1e-12)
+ for k in (1, 2):
+ np.testing.assert_allclose(
+ curves_[:, k],
+ corners[:-1] + k / 3 * (corners[1:] - corners[:-1]),
+ atol=1e-9,
+ )
+
+ @given(start=arrays(3, 10), handle=arrays(3, 10), end=arrays(3, 10), t=unit)
+ def test_a_quadratic_curve_is_its_cubic(
+ self, start: np.ndarray, handle: np.ndarray, end: np.ndarray, t: float
+ ) -> None:
+ mob = (
+ m.VMobject()
+ .start_new_path(start)
+ .add_quadratic_bezier_curve_to(handle, end)
+ )
+ quadratic = (1 - t) ** 2 * start + 2 * (1 - t) * t * handle + t**2 * end
+ np.testing.assert_allclose(bezier(mob.points)(t), quadratic, atol=1e-9)
+
+ @given(corners=st.integers(2, 6).flatmap(lambda n: arrays((n, 3), 10)))
+ def test_a_closed_path_ends_where_its_last_subpath_starts(
+ self, corners: np.ndarray
+ ) -> None:
+ mob = m.VMobject().set_points_as_corners(corners).close_path()
+ assert mob.is_closed()
+ # to the path's tolerance: a path already ending there gets no line
+ np.testing.assert_allclose(mob.points[-1], corners[0], rtol=1e-5, atol=1e-6)
+
+ @given(
+ parts=st.lists(curves(max_curves=3), min_size=1, max_size=4), gap=arrays(3, 5)
+ )
+ def test_subpaths_split_where_a_curve_does_not_start_at_the_last_end(
+ self, parts: list[np.ndarray], gap: np.ndarray
+ ) -> None:
+ assume(np.linalg.norm(gap) > 1e-3)
+ mob = m.VMobject()
+ placed = []
+ for part in parts: # each part starts away from where the last one ended
+ if placed:
+ part = part - part[0] + placed[-1][-1] + gap
+ placed.append(part)
+ mob.append_points(part)
+ subpaths = mob.get_subpaths()
+ assert len(subpaths) == len(placed)
+ for got, expected in zip(subpaths, placed, strict=True):
+ # (to a rounding: a path's points are kept relative to its first)
+ np.testing.assert_allclose(
+ got, expected, rtol=0, atol=1e-12 * (1 + np.abs(expected).max())
+ )
+
+
+class TestRefining:
+ @given(mob=paths(max_curves=4), n=st.integers(0, 12), t=unit)
+ def test_inserted_curves_are_parts_of_the_curves(
+ self, mob: m.VMobject, n: int, t: float
+ ) -> None:
+ old = mob.points.reshape(-1, 4, 3)
+ mob.insert_n_curves(n)
+ new = mob.points.reshape(-1, 4, 3)
+ assert len(new) == len(old) + n
+ # the split its docstring gives: new curve j to old curve j·m // n
+ shares = np.bincount(
+ np.arange(len(new)) * len(old) // len(new), minlength=len(old)
+ )
+ i = 0
+ for curve, share in zip(old, shares, strict=True):
+ for k in range(share):
+ np.testing.assert_allclose(
+ bezier(new[i])(t),
+ bezier(curve)((k + t) / share),
+ atol=1e-9 * (1 + np.abs(curve).max()),
+ )
+ i += 1
+
+ @given(a=paths(), b=paths())
+ def test_aligned_paths_keep_their_shapes(
+ self, a: m.VMobject, b: m.VMobject
+ ) -> None:
+ dense_a, dense_b = oracles.sample(a.points, 400), oracles.sample(b.points, 400)
+ a.align_points(b)
+ assert a.get_num_points() == b.get_num_points()
+ for mob, dense in ((a, dense_a), (b, dense_b)):
+ drawn = oracles.sample(mob.points, 20)
+ gaps = np.linalg.norm(drawn[:, None] - dense[None], axis=2).min(axis=1)
+ spacing = np.linalg.norm(np.diff(dense, axis=0), axis=1).max()
+ assert gaps.max() <= spacing + 1e-9
+
+ @given(mob=paths(), a=unit, b=unit, t=unit)
+ def test_a_part_is_the_path_between_its_proportions_by_curves(
+ self, mob: m.VMobject, a: float, b: float, t: float
+ ) -> None:
+ a, b = min(a, b), max(a, b)
+ part = mob.copy().pointwise_become_partial(mob, a, b)
+ n = mob.get_num_curves()
+
+ # by curves: proportion x is curve int(x·n) at parameter frac(x·n)
+ def at(x: float) -> np.ndarray:
+ k = min(int(x * n), n - 1)
+ return bezier(mob.get_nth_curve_points(k))(x * n - k)
+
+ np.testing.assert_allclose(
+ part.get_start(), at(a), atol=1e-9 * (1 + np.abs(mob.points).max())
+ )
+ np.testing.assert_allclose(
+ part.get_end(), at(b), atol=1e-9 * (1 + np.abs(mob.points).max())
+ )
+
+
+FUNCTIONS = {
+ "waves": lambda p: p + 0.5 * np.array([np.sin(p[1]), np.sin(p[0]), 0]),
+ "square": lambda p: np.array([p[0] * abs(p[0]) / 10, p[1], p[2]]),
+ "complex square": lambda p: np.array(
+ [(p[0] ** 2 - p[1] ** 2) / 10, p[0] * p[1] / 5, p[2]]
+ ),
+}
+
+
[email protected]("grouped", [False, True])
[email protected]("name", FUNCTIONS)
+@given(points=curves(max_curves=3))
+def test_an_image_is_within_its_tolerance_all_along(
+ name: str, grouped: bool, points: np.ndarray
+) -> None:
+ f = FUNCTIONS[name]
+ mob = m.VMobject()
+ mob.points = points
+ image = mob.copy()
+ (m.Group(image) if grouped else image).apply_function(f)
+ old = mob.points.reshape(-1, 4, 3)
+ new = image.points.reshape(
+ len(old), -1, 4, 3
+ ) # every curve cut into as many pieces
+ pieces = new.shape[1]
+ t = np.linspace(0, 1, 33)
+ for curve, cut in zip(old, new, strict=True):
+ for k, piece in enumerate(cut):
+ true = np.array(
+ [f(p) for p in oracles.bezier_points(curve, (k + t) / pieces)[0]]
+ )
+ got = oracles.bezier_points(np.asarray(piece), t)[0]
+ assert np.linalg.norm(got - true, axis=1).max() <= 1.5e-3
+
+
+class TestOrientation:
+ @given(
+ corners=st.integers(3, 8).flatmap(lambda n: arrays((n, 3), 10)),
+ shift=arrays(3, 50),
+ )
+ def test_it_does_not_depend_on_where_the_path_is(
+ self, corners: np.ndarray, shift: np.ndarray
+ ) -> None:
+ corners[:, 2] = 0
+ area = oracles.polygon_area(corners)
+ assume(abs(area) > 1e-3)
+ mob = m.VMobject().set_points_as_corners([*corners, corners[0]])
+ expected = "CCW" if area > 0 else "CW"
+ assert mob.get_direction() == expected
+ assert mob.shift(shift).get_direction() == expected
+ assert mob.reverse_direction().get_direction() != expected
+
+
+@given(lengths=st.tuples(*[st.integers(0, 20)] * 3), factor=st.integers(1, 25))
+@example(lengths=(5, 5, 5), factor=21)
+def test_thinning_keeps_every_kth_point_of_each_member_once(
+ lengths: tuple[int, int, int], factor: int
+) -> None:
+ clouds = [
+ m.PMobject().add_points(
+ np.arange(3.0 * n).reshape(n, 3),
+ rgbas=np.linspace(0, 1, 4 * n).reshape(n, 4),
+ )
+ for n in lengths
+ ]
+ root, a, b = clouds
+ root.add(a, m.Group(a, b)) # (a held twice in the family: thinned once)
+ original = [(c.points.copy(), c.paint.fill.copy()) for c in clouds]
+ assert root.thin_out(factor) is root
+ for cloud, (points, colors) in zip(clouds, original, strict=True):
+ np.testing.assert_array_equal(cloud.points, points[::factor])
+ np.testing.assert_array_equal(cloud.paint.fill, colors[::factor])
+
+
[email protected]("factor", [0, -1, -5])
+def test_thinning_requires_a_positive_factor_before_editing(factor: int) -> None:
+ cloud = m.PMobject().add_points([[1, 2, 3], [4, 5, 6]])
+ geometry, paint = cloud._geometry, cloud.paint
+ with pytest.raises(ValueError, match="factor must be positive"):
+ cloud.thin_out(factor)
+ assert cloud._geometry is geometry
+ assert cloud.paint is paint
+ with pytest.raises(ValueError, match="factor must be positive"):
+ m.PMobject().thin_out(factor)
+
+
+def _reached(a: float, b: float, n: int) -> list[int]:
+ """The steps k of n (each [k, k + 1) of them) that the stretch [na, nb] reaches into."""
+ return [k for k in range(n) if a * n < k + 1 and b * n > k]
+
+
+@given(a=st.floats(0, 1), b=st.floats(0, 1))
+def test_a_clouds_part_is_every_point_its_stretch_reaches_into(
+ a: float, b: float
+) -> None:
+ a, b = min(a, b), max(a, b)
+ points = np.array([[x, 0.0, 0.0] for x in range(10)])
+ source = m.PMobject().add_points(points, rgbas=np.linspace(0, 1, 40).reshape(10, 4))
+ part = m.PMobject().pointwise_become_partial(source, a, b)
+ shown = _reached(a, b, 10)
+ np.testing.assert_array_equal(part.points, points[shown].reshape(-1, 3))
+ np.testing.assert_array_equal(part.paint.fill, source.paint.fill[shown])
+
+
+def test_point_cloud_keeps_distinct_future_point_color_and_initial_width() -> None:
+ cloud = m.PMobject(color=m.RED, stroke_width=9).add_points([m.LEFT])
+ cloud.set_color(m.BLUE).set_stroke(width=2)
+ cloud.add_points([m.RIGHT])
+ np.testing.assert_array_equal(cloud.paint.fill, [m.BLUE.to_rgba(), m.RED.to_rgba()])
+ cloud.init_colors()
+ assert cloud.paint.stroke_width == 9
+ cloud.reset_points().add_points([m.ORIGIN])
+ np.testing.assert_array_equal(cloud.paint.fill, [m.RED.to_rgba()])
+ assert cloud.style["color"] == m.RED
+
+
+def test_a_lattices_triangles_are_derived_from_its_grid() -> None:
+ sphere = m.Sphere(resolution=(4, 6))
+ triangles = sphere.triangles
+ for same in (triangles, triangles.copy(), triangles.tolist()):
+ sphere.triangles = same
+ assert sphere.grid == (4, 6)
+ np.testing.assert_array_equal(sphere.triangles, triangles)
+ with pytest.raises(ValueError, match="derived triangles"):
+ sphere.triangles = triangles[::-1]
+
+
+@given(a=st.floats(0, 1), b=st.floats(0, 1))
+@example(a=0.0, b=1.0)
+@example(a=0.25, b=0.75)
+@example(a=0.5, b=0.5)
+def test_a_surfaces_part_is_a_surface_drawing_the_faces_its_stretch_reaches(
+ a: float, b: float
+) -> None:
+ a, b = min(a, b), max(a, b)
+ source = m.Sphere(resolution=(2, 3))
+ colors = source.paint.fill.copy()
+ colors[:, 3] = np.linspace(0.1, 0.9, len(colors)) # a color a cell
+ source.paint = source.paint.but(fill=colors)
+ part = m.MeshMobject(color=m.RED).pointwise_become_partial(source, a, b)
+ faces = _reached(a, b, 6)
+ assert part.grid == source.grid # its whole lattice, as painted
+ assert part.paint is source.paint
+ np.testing.assert_array_equal(part.points, source.points)
+ drawn = source.triangles.reshape(6, 2, 3)[faces].reshape(-1, 3)
+ np.testing.assert_array_equal(part.triangles, drawn)
+ box = part.boundary_box()
+ corners = source.points[np.unique(drawn)]
+ if faces:
+ assert box is not None
+ np.testing.assert_array_equal(box, [corners.min(axis=0), corners.max(axis=0)])
+ else:
+ assert box is None
+
+
+def test_a_surfaces_part_of_a_part_and_its_pieces_share_its_faces_out() -> None:
+ source = m.Torus(resolution=(4, 3)) # 12 faces
+ half = source.copy().pointwise_become_partial(source, 0.5, 1.0) # faces 6 to 12
+ quarter = half.copy().pointwise_become_partial(half, 0.0, 0.5) # 6 to 9
+ np.testing.assert_array_equal(quarter.triangles, source.triangles[12:18])
+ pieces = [p for p in source.get_pieces(4) if isinstance(p, m.MeshMobject)]
+ assert [p.grid for p in pieces] == [(4, 3)] * 4
+ np.testing.assert_array_equal(
+ np.concatenate([p.triangles for p in pieces]), source.triangles
+ )
+
+
+@given(a=st.floats(0, 1), b=st.floats(0, 1))
+@example(a=0.0, b=0.5)
+def test_a_meshs_part_is_the_triangles_its_stretch_reaches_with_their_corners_alone(
+ a: float, b: float
+) -> None:
+ a, b = min(a, b), max(a, b)
+ corners = np.array([[0.0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [2, 2, 0]])
+ rows = np.linspace(0, 1, 20).reshape(5, 4) # a color a corner
+ triangles = np.array([[0, 1, 2], [1, 3, 2], [3, 4, 2]])
+ source = m.MeshMobject(corners, triangles)
+ source.paint = source.paint.but(fill=rows)
+ part = m.MeshMobject().pointwise_become_partial(source, a, b)
+ reached = _reached(a, b, 3)
+ if reached == [0, 1, 2]: # the whole: the mesh itself
+ np.testing.assert_array_equal(part.points, corners)
+ return
+ own = triangles[reached].ravel()
+ np.testing.assert_array_equal(
+ part.points, corners[own]
+ ) # no corner it doesn't draw
+ np.testing.assert_array_equal(
+ part.points[part.triangles].reshape(-1, 3), corners[own]
+ )
+ np.testing.assert_array_equal(part.paint.fill, rows[own])
+ box = part.boundary_box()
+ if reached:
+ assert box is not None
+ drawn = corners[own]
+ np.testing.assert_array_equal(box, [drawn.min(axis=0), drawn.max(axis=0)])
+
+
+def test_shown_keys_label_their_values_however_added() -> None:
+ shown = m.VDict([("s", m.Square())], show_keys=True)
+ shown.add([("c", m.Circle())])
+ shown["r"] = m.Rectangle()
+ for key in ("s", "c", "r"):
+ value = shown[key]
+ (label,) = value.submobjects
+ assert isinstance(label, m.Tex)
+ assert label.tex_string == key
+ assert label.get_right()[0] < value.points[:, 0].min()
+ assert not m.VDict([("s", m.Square())])["s"].submobjects