Coverage for src/manimgx/mobject.py: 94%
1951 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
1# SPDX-FileCopyrightText: 2026 Academa, Inc.
2# SPDX-FileCopyrightText: 2024 the Manim Community Developers
3# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
4# SPDX-License-Identifier: MIT
6"Mutable scene objects: one family graph, shared geometry and paint, and path, point and mesh leaf rules."
8import copy
9import functools
10import inspect
11import itertools as it
12import math
13import pathlib
14import random
15import types
16import weakref
17from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping, Sequence
18from fractions import Fraction
19from functools import reduce
20from typing import (
21 TYPE_CHECKING,
22 ClassVar,
23 Concatenate,
24 Final,
25 Literal,
26 Never,
27 Self,
28 TypeIs,
29 Unpack,
30 cast,
31 overload,
32)
33from warnings import deprecated
35import numpy as np
36import numpy.typing as npt
37from typing_extensions import TypedDict
39from manimgx import caches
40from manimgx.animation import clock
41from manimgx.caches import Memo, unchanged
42from manimgx.constants import (
43 DEFAULT_MOBJECT_TO_EDGE_BUFFER,
44 DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
45 DEFAULT_POINT_DENSITY_1D,
46 DEFAULT_STROKE_WIDTH,
47 DL,
48 DOWN,
49 IN,
50 LEFT,
51 MED_SMALL_BUFF,
52 ORIGIN,
53 OUT,
54 RIGHT,
55 TAU,
56 UL,
57 UP,
58 CapStyleType,
59 LineJointType,
60)
61from manimgx.drawing.geometry import (
62 _NPPCC,
63 EMPTY,
64 Blend,
65 Lattice,
66 Path,
67 _pathops,
68 bezier,
69 bezier_remap,
70 get_smooth_cubic_bezier_handle_points,
71 integer_interpolate,
72 interpolate,
73 linear_about,
74 normalize,
75 partial_bezier_points,
76 rotation_matrix,
77 segment,
78 shoelace_direction,
79 straight_path,
80 subpath_ranges,
81 turn_between,
82)
83from manimgx.drawing.paint import (
84 BLACK,
85 WHITE,
86 Colors,
87 ManimColor,
88 Material,
89 Paint,
90 PaintArray,
91 PaintAttribute,
92 ParsableManimColor,
93 SimpleStyle,
94 Style,
95 StyleBase,
96 StyleSnapshot,
97 _Look,
98 color_gradient,
99 frozen,
100 interpolate_color,
101 key_of,
102 parse_colors,
103 stretch_array,
104)
105from manimgx.settings import config
106from manimgx.typing import (
107 MatrixMN,
108 PathFunc,
109 Point3D,
110 Point3D_Array,
111 Point3DLike,
112 Point3DLike_Array,
113 PointsFunc,
114 RGBA_Array,
115 Vector3D,
116 Vector3DLike,
117)
119__all__ = [
120 "ComplexValueTracker",
121 "Group",
122 "MeshMobject",
123 "Mobject",
124 "Mobject1D",
125 "PGroup",
126 "PMobject",
127 "Point",
128 "VDict",
129 "VGroup",
130 "VMobject",
131 "ValueTracker",
132 "VectorizedPoint",
133 "override_animate",
134 "override_animation",
135 "remove_list_redundancies",
136]
138if TYPE_CHECKING:
139 from manimgx.animation.timeline import Animation
140 from manimgx.animation.transform import Always, Animate
142type Updater[M] = Callable[[M], object] | Callable[[M, float], object]
143"""A function that keeps a mobject updated: called with the mobject once a frame, or, if
144it has a parameter named `dt`, with the mobject and the seconds since it last ran. What
145it returns is ignored; see [add_updater][manimgx.Mobject.add_updater]."""
147type _Recorder = tuple[
148 "Mobject", Callable[..., object], Sequence[Callable[..., object]]
149]
152def axis_factors(factor: float | Vector3DLike) -> np.ndarray:
153 """A scale's factors along x, y and z.
155 Args:
156 factor: One factor for every axis, or one per axis.
158 Returns:
159 The three factors.
160 """
161 return np.broadcast_to(np.asarray(factor, dtype=float), 3)
164def length_factor(factor: float | Vector3DLike) -> float:
165 """How a scale changes a length that has no direction, such as a stroke's width or a
166 font's size.
168 Args:
169 factor: The scale's factor, or its factors along x, y and z.
171 Returns:
172 The factor itself; for one factor per axis, the geometric mean of the sizes of
173 x's and y's.
174 """
175 x, y, _ = np.abs(axis_factors(factor))
176 return float(np.sqrt(x * y))
179# CE's override decorators, as data: a mobject method → the animation class it plays instead
180# (`override_animation`), and a mobject method → the method whose animation its `.animate`
181# call plays (`override_animate`)
182_plays_instead: dict[Callable[..., object], type["Animation"]] = {}
183_animate_plays: dict[Callable[..., object], Callable[..., "Animation"]] = {}
185# What an updater is, known per function (a method's is its function's) and held weakly:
186# a function outlives no scene for being an updater, nor a method's object
187_TIME_BASED: "weakref.WeakKeyDictionary[Callable[..., object], bool]" = (
188 weakref.WeakKeyDictionary()
189)
190_FLOWS: "weakref.WeakSet[Callable[..., object]]" = weakref.WeakSet()
193def _has_updater(
194 updaters: Iterable[Callable[..., object]], updater: Callable[..., object]
195) -> bool:
196 """Whether this exact callable remains in the active updater list."""
197 return any(active is updater for active in updaters)
200def _function(updater: Callable[..., object]) -> Callable[..., object]:
201 """The function an updater runs: a method's function, else the updater itself."""
202 return getattr(updater, "__func__", updater)
205def _per_frame[M](updater: Updater[M]) -> TypeIs[Callable[[M], object]]:
206 """Does the updater take the mobject alone (no `dt`)? CE inspects the signature on every
207 call; the answer is kept per function."""
208 function = _function(updater)
209 try:
210 known = _TIME_BASED.get(function)
211 except TypeError: # held by no weak reference (a builtin): asked each time
212 return "dt" not in inspect.signature(updater).parameters
213 if known is None:
214 known = _TIME_BASED[function] = "dt" in inspect.signature(updater).parameters
215 return not known
218def _flows(updater: Callable[..., object]) -> bool:
219 """Is the updater a [flow][manimgx.mobject.flow] (or a method whose function is)?"""
220 return _function(updater) in _FLOWS
223def flow[U: Callable[..., object]](updater: U) -> U:
224 """Declare a time-based updater a flow: one that does the same over some time
225 however that time is split into steps.
227 A time-based updater is handed `dt`, the seconds since it last ran. Most compose:
228 one that moves the mobject at a rate (`mob.shift(dt * velocity)`), or sets it by a
229 function of the time it has run, does the same in one step of `dt` as in two of
230 `dt / 2`. A flow runs at every instant the scene computes — each frame, and the end
231 of each play and wait — handed exactly the time since, so every frame shows it at
232 that frame's instant.
234 Any other time-based updater is simulated, since what it does may depend on its
235 steps (an integrator, a ball that bounces): it steps on a clock of its own,
236 `config.simulation_rate` ticks a second (60) and the end of each play and wait, so
237 it takes the same steps at any frame rate, and a frame shows it as its last tick
238 left it. While one is in the scene, the scene computes every tick, between frames
239 too. Declare an updater that composes a flow to make it exact at every frame and to
240 spare those ticks; [always_shift][manimgx.always_shift] and
241 [always_rotate][manimgx.always_rotate] add flows. An updater that only reads the
242 world, as a traced path's does, is a [recorder][manimgx.mobject.record].
244 Args:
245 updater: A time-based updater: a function of the mobject and `dt`.
247 Returns:
248 The same updater, declared a flow, to add with
249 [add_updater][manimgx.Mobject.add_updater].
251 Examples:
252 ```python
253 import manimgx as m
254 from manimgx.mobject import flow
257 @flow
258 def orbit(dot: m.Mobject, dt: float) -> None:
259 dot.rotate(dt * m.PI / 2, about_point=m.ORIGIN) # a quarter turn a second
262 class FlowExample(m.Scene):
263 def construct(self) -> None:
264 dot = m.Dot(3 * m.RIGHT, radius=0.25, color=m.YELLOW)
265 dot.add_updater(orbit)
266 self.add(m.Circle(radius=3, color=m.BLUE), dot)
267 self.wait(3)
268 ```
269 """
270 _FLOWS.add(_function(updater))
271 return updater
274_RECORDERS: "weakref.WeakSet[Callable[..., object]]" = weakref.WeakSet()
277def record[U: Callable[..., object]](updater: U) -> U:
278 """Declare a time-based updater a recorder: one that reads the world and changes
279 only its own mobject, as a [TracedPath][manimgx.TracedPath]'s does.
281 The scene runs a recorder at every instant it computes — each tick of the
282 simulation clock, each frame, and the end of each play and wait — once everything
283 else is there: the animations playing, the mobjects' updaters and the scene's. At a
284 frame or at the end of a play or wait, it runs twice: first on the world as time
285 alone brought it there, as a tick sees it, then once the per-frame updaters have
286 run, so it can tell their change apart (a traced path spreads it over the frame
287 that ends there). A recorder is simulated (see [flow][manimgx.mobject.flow]):
288 while one is in the scene, the scene computes the simulation clock's ticks.
290 Args:
291 updater: A time-based updater: a function of the mobject and `dt`, or such a
292 method, decorated where its class defines it.
294 Returns:
295 The same updater, declared a recorder, to add with
296 [add_updater][manimgx.Mobject.add_updater].
297 """
298 # the scene computes a frame or an event in two passes (`Scene._instant`) only while
299 # a recorder is in it; the second pass is `clock.framing`
300 _RECORDERS.add(_function(updater))
301 return updater
304def records(updater: Callable[..., object]) -> bool:
305 """Whether an updater is a [recorder][manimgx.mobject.record].
307 The scene asks, to know whether it must compute each frame in two passes.
309 Args:
310 updater: An updater; a method is a recorder if its function is.
311 """
312 return _function(updater) in _RECORDERS
315def simulated(updater: Updater[Never]) -> bool:
316 """Whether an updater steps on the simulation clock: it is time-based and not a
317 [flow][manimgx.mobject.flow].
319 The scene asks, to know whether it must compute the ticks of its simulation clock.
321 Args:
322 updater: An updater, of a mobject or of a scene.
323 """
324 return not _per_frame(updater) and not _flows(updater)
327_SHARED: frozenset[type] = frozenset(
328 {
329 int,
330 float,
331 bool,
332 str,
333 bytes,
334 Blend,
335 Paint,
336 ManimColor,
337 np.float64,
338 np.int64,
339 np.bool_,
340 types.FunctionType, # a function (not a bound method: that is rebound to the copy)
341 pathlib.PosixPath,
342 pathlib.WindowsPath,
343 }
344)
347def copied[T](value: T) -> T:
348 """A deep copy of a value that holds mobjects.
350 Lists, tuples and dicts are rebuilt, each mobject is copied once (so two references
351 to one mobject refer to one copy), and plain values are shared.
353 Args:
354 value: A mobject, or a container of mobjects and plain values.
355 """
356 # see `_copied`
357 return cast("T", _copied(value, {}))
360def _copied(value: object, memo: dict[int, object]) -> object:
361 """A deep copy that knows the common shapes: values shared, containers rebuilt, mobjects
362 copied through the memo (aliases stay aliases)."""
363 kind = type(value)
364 if value is None or kind in _SHARED:
365 return value
366 if kind is list:
367 return [_copied(v, memo) for v in cast("list[object]", value)]
368 if kind is dict:
369 return {
370 k: _copied(v, memo) for k, v in cast("dict[object, object]", value).items()
371 }
372 if kind is tuple:
373 return tuple(_copied(v, memo) for v in cast("tuple[object, ...]", value))
374 if isinstance(value, Mobject):
375 known = memo.get(id(value))
376 return known if known is not None else value.__deepcopy__(memo)
377 if kind is np.ndarray: # read-only, an array is a value: shared
378 array = cast("np.ndarray", value)
379 return array.copy() if array.flags.writeable else array
380 return copy.deepcopy(value, memo)
383_CASCADES: Memo[type, Style] = Memo(1 << 12)
384_UNPAINTED: Final = Paint() # every mobject's paint until its style is applied
385_PAINT_STYLE: Final = (
386 "color",
387 "fill_color",
388 "fill_opacity",
389 "stroke_color",
390 "stroke_width",
391 "stroke_opacity",
392 "background_stroke_color",
393 "background_stroke_width",
394 "background_stroke_opacity",
395 "sheen_factor",
396 "sheen_direction",
397 "joint_type",
398 "cap_style",
399 "shade_in_3d",
400 "material",
401)
402# a style's paint, as the first `init_colors` makes it: (the mobject's, a fresh member's)
403_STYLED: Memo[tuple[object, ...], tuple[Paint, Paint | None]] = Memo(1 << 12)
404_PROTOTYPES: Memo[tuple[object, ...], "Mobject"] = Memo(1 << 12)
407def _copy_state(source: "Mobject", target: "Mobject", memo: dict[int, object]) -> None:
408 """Copy fields in order, with active clock stamps owned by the copied updaters."""
409 shared = type(source).shared
410 copied = target.__dict__
411 for name, value in source.__dict__.items():
412 if value is None or type(value) in _SHARED or name in shared:
413 copied[name] = value
414 elif name == "_since_":
415 stamps = cast("dict[object, Fraction]", value)
416 copied[name] = {
417 (updater if "updaters" in shared else _copied(updater, memo)): stamps[
418 updater
419 ]
420 for updater in source.updaters
421 if updater in stamps
422 }
423 else:
424 copied[name] = _copied(value, memo)
427@functools.cache
428def _kind(cls: type["Mobject"]) -> type["Mobject"]:
429 """How a class of mobject is drawn: as a path, as points, as a mesh, or not at all."""
430 kinds = (VMobject, PMobject, MeshMobject)
431 return next((kind for kind in kinds if issubclass(cls, kind)), Mobject)
434def _fresh(mob: "Mobject", alone: bool = False) -> "Mobject":
435 """A member `become` gains: a copy of the other's (alone: without its members), with
436 no updaters."""
437 made = mob.copy()
438 if alone:
439 made.submobjects = []
440 for part in made.get_family():
441 part.clear_updaters()
442 return made
445def prototype[S: "Mobject", **P](
446 init: Callable[Concatenate[S, P], None],
447) -> Callable[Concatenate[S, P], None]:
448 """Make a mobject class's construction run once per distinct call: a decorator for
449 its `__init__`.
451 Construction is a value: an `__init__` given the same arguments (and the same
452 configuration) makes the same mobject. So it runs once per distinct call, and every
453 later construction takes a copy of what it made; an expensive mobject (typeset text,
454 an arrow tip) is made once. A call with an argument that is not a plain value (a
455 mobject, a function) constructs as usual.
457 Args:
458 init: The class's `__init__`.
460 Returns:
461 The `__init__`, remembering what it makes.
462 """
464 # a later construction adopts the made mobject's attributes: whatever named the made
465 # mobject names the new one
467 @functools.wraps(init)
468 def construct(self: S, *args: P.args, **kwargs: P.kwargs) -> None:
469 if self.__dict__:
470 init(self, *args, **kwargs)
471 return
472 try:
473 key = (
474 init,
475 type(self),
476 key_of(args),
477 key_of(sorted(kwargs.items())),
478 key_of(tuple(vars(config).values())),
479 )
480 except TypeError:
481 init(self, *args, **kwargs)
482 return
483 made = _PROTOTYPES.get(key)
484 if made is None:
485 init(self, *args, **kwargs)
486 _PROTOTYPES.keep(key, self.copy())
487 return
488 _copy_state(made, self, {id(made): self})
490 return construct
493def _anchors(points: Point3D_Array) -> Point3D_Array:
494 """A path's anchors: the first and last point of every cubic curve."""
495 if len(points) < 4:
496 return points
497 return points[np.r_[0 : len(points) : 4, 3 : len(points) : 4]]
500def _style_key(style: Style) -> tuple[object, ...] | None:
501 try:
502 key = tuple(key_of(style.get(name)) for name in _PAINT_STYLE)
503 except TypeError:
504 return None
505 return key
508_STRAIGHT = straight_path() # a default (paths are immutable)
511class GridArrangement(TypedDict, total=False):
512 """How [arrange_in_grid][manimgx.Mobject.arrange_in_grid] lays mobjects out: its
513 keywords, for the classes that pass them on (tables)."""
515 rows: int | None
516 """How many rows (default None: as many as `row_alignments` or `row_heights` lists,
517 else as many as the mobjects need; with neither `rows` nor `cols`, a grid as square
518 as it can be)."""
519 cols: int | None
520 """How many columns (default None: as many as `col_alignments` or `col_widths`
521 lists, else as many as the mobjects need; with neither `rows` nor `cols`, a grid as
522 square as it can be)."""
523 buff: float | tuple[float, float]
524 """The gap between cells, in scene units: one for both directions, or (horizontal,
525 vertical) (default 0.25)."""
526 cell_alignment: Vector3DLike
527 """Where each mobject sits in its cell, as a direction: UL for its top left corner
528 (default ORIGIN: centered)."""
529 row_alignments: str | None
530 """Each row's vertical alignment, top to bottom: a letter per row, "u" (up), "c"
531 (center) or "d" (down) (default None: as `cell_alignment`'s vertical part says)."""
532 col_alignments: str | None
533 """Each column's horizontal alignment, left to right: a letter per column, "l"
534 (left), "c" (center) or "r" (right) (default None: as `cell_alignment`'s horizontal
535 part says)."""
536 row_heights: Iterable[float | None] | None
537 """Each row's height, top to bottom, in scene units; None for the height of its
538 tallest mobject (default None: all measured)."""
539 col_widths: Iterable[float | None] | None
540 """Each column's width, left to right, in scene units; None for the width of its
541 widest mobject (default None: all measured)."""
542 flow_order: str
543 """The order the cells are filled in: two letters, the direction a line of cells
544 fills and then the direction the lines follow each other — "r" (right), "l" (left),
545 "u" (up) or "d" (down) (default "rd": rows left to right, from the top down; "dr"
546 fills columns top to bottom, from the left)."""
549class _Beside(TypedDict, total=False):
550 """Beside's keys, open, for the keywords that add to them."""
552 aligned_edge: Vector3DLike
553 """The edge, as a direction, along which the two line up besides the side they meet
554 at: with the direction RIGHT and UP here, their tops line up (default ORIGIN:
555 centered)."""
556 submobject_to_align: "Mobject | None"
557 """A part of the mobject to put beside the other in its place; the rest moves with
558 it (default None: the whole mobject)."""
559 index_of_submobject_to_align: int | None
560 """The index of the part of each mobject to line up: this one's part goes beside the
561 other's (default None: the whole of each)."""
562 coor_mask: Vector3DLike
563 """Which coordinates may change: 1 for each axis the mobject moves along, 0 for one
564 it keeps (default (1, 1, 1))."""
567class Beside(_Beside, total=False, closed=True):
568 """How [next_to][manimgx.Mobject.next_to] aligns a mobject beside another: its
569 keywords but the direction and the gap, for the methods that pass them on
570 ([arrange][manimgx.Mobject.arrange])."""
573class Placement(_Beside, total=False, closed=True):
574 """How [next_to][manimgx.Mobject.next_to] places a mobject beside another: its
575 keywords but the direction, for the methods that pass them on."""
577 buff: float
578 """The gap between the two, in scene units (default 0.25)."""
581class BackgroundOptions(_Look, total=False, closed=True):
582 """A background rectangle's keywords but its color and opacity: those of
583 [add_background_rectangle][manimgx.Mobject.add_background_rectangle] and its
584 variants."""
586 buff: float | tuple[float, float]
587 """The margin around the mobject, in scene units: one for both directions, or
588 (horizontal, vertical) (default 0)."""
589 corner_radius: float
590 """The radius of the rectangle's corners, in scene units (default 0: square
591 corners)."""
592 stroke_width: float
593 """The width of the rectangle's outline, in hundredths of a scene unit (default 0:
594 none)."""
595 stroke_opacity: float
596 """The outline's opacity, from 0 to 1 (default 0)."""
597 stroke_color: Colors | None
598 """The outline's color (default: the rectangle's color)."""
601class Pivot(TypedDict, total=False, closed=True):
602 """The point a transformation keeps fixed: given, or a point of the mobject's
603 bounding box.
605 With neither keyword, a scale, a rotation or a stretch keeps the mobject's center
606 fixed, and a function or a matrix is applied about the origin.
607 """
609 about_point: Point3DLike | None
610 """The point that stays fixed, in scene coordinates; it takes precedence over
611 `about_edge`."""
612 about_edge: Vector3DLike | None
613 """The point of the mobject's bounding box that stays fixed, named by a direction:
614 UP for the middle of its top edge, UR for its top right corner, ORIGIN for its
615 center."""
618def style_defaults(cls: "type[Mobject]") -> Style:
619 """A mobject class's style defaults: the [defaults][manimgx.Mobject.defaults] of
620 every class in its hierarchy, each class's over its parents'.
622 Args:
623 cls: A mobject class.
625 Returns:
626 The defaults of its style keywords.
627 """
628 # each class in the hierarchy adds only what it changes; cached per class
629 cached = _CASCADES.get(cls)
630 if cached is None:
631 cached = Style()
632 for klass in reversed(cls.__mro__):
633 if issubclass(klass, Mobject) and "defaults" in vars(klass):
634 cached = cached | klass.defaults
635 _CASCADES.keep(cls, cached)
636 return cached
639@deprecated("use list(dict.fromkeys(items))", category=None)
640def remove_list_redundancies[T](items: Sequence[T]) -> list[T]:
641 """The items without repeats: each one once, where it last occurs.
643 Items are the same when they are the same object.
645 Args:
646 items: The items, in order.
648 Returns:
649 A new list.
650 """
651 # the last occurrence of each is kept (CE semantics)
652 seen: set[int] = set()
653 out: list[T] = []
654 for x in reversed(items):
655 if id(x) not in seen:
656 seen.add(id(x))
657 out.append(x)
658 out.reverse()
659 return out
662def _family(roots: Iterable["Mobject"]) -> list["Mobject"]:
663 """Preorder from these roots, each member once at its last occurrence."""
664 # Members held once (most families) are the preorder itself, made in one pass; a member
665 # met again sends the work to the walk that keeps last occurrences.
666 roots = list(roots)
667 preorder: list[Mobject] = []
668 met: set[int] = set()
669 pending = roots[::-1]
670 while pending:
671 item = pending.pop()
672 if id(item) in met:
673 return _family_of_repeats(roots)
674 met.add(id(item))
675 preorder.append(item)
676 if item.submobjects:
677 pending.extend(item.submobjects[::-1])
678 return preorder
681def _family_of_repeats(roots: list["Mobject"]) -> list["Mobject"]:
682 """`_family` of roots whose families share members, or repeat them."""
683 # Right-to-left postorder is reversed preorder. Keep its first occurrences,
684 # skipping already visited subtrees, then reverse to keep preorder's last ones.
685 family: list[Mobject] = []
686 seen: set[int] = set()
687 pending: list[Mobject | tuple[Mobject]] = list(roots)
688 while pending:
689 item = pending.pop()
690 if isinstance(item, tuple):
691 family.append(item[0])
692 elif id(item) not in seen:
693 seen.add(id(item))
694 if item.submobjects:
695 pending.append((item,))
696 pending.extend(item.submobjects)
697 else:
698 family.append(item)
699 family.reverse()
700 return family
703def _family_box(family: Iterable["Mobject"]) -> np.ndarray | None:
704 """Combine the selected family's own geometry boxes without constructing a group."""
705 # A member's box is what it draws (`_box`); paths use their curves' tight bounds.
706 boxes = [b for m in family if m._geometry.n and (b := m._box()) is not None]
707 if len(boxes) < 2:
708 return boxes[0] if boxes else None
709 stacked = np.array(boxes)
710 return np.array([stacked[:, 0].min(axis=0), stacked[:, 1].max(axis=0)])
713class Mobject:
714 """The object everything in a scene is made of: shapes, text, groups, trackers.
716 A mobject has points in scene coordinates (x to the right, y up, z out of the
717 screen; the frame is 8 units on its short side, about 14.2 × 8 at 16:9, centered
718 on the origin);
719 submobjects, a tree drawn and moved with it; a style: its fill, its stroke and their
720 colors; updaters, which change it as time passes; and a z-index, its place in the
721 drawing order. You make one through its subclasses — [`Circle`][manimgx.Circle],
722 [`Text`][manimgx.Text], [`VGroup`][manimgx.VGroup] and the rest — and they all share
723 the methods here: to transform it ([`shift`][manimgx.Mobject.shift],
724 [`scale`][manimgx.Mobject.scale], [`rotate`][manimgx.Mobject.rotate]), lay it out
725 ([`next_to`][manimgx.Mobject.next_to], [`arrange`][manimgx.Mobject.arrange]), style
726 it ([`set_color`][manimgx.Mobject.set_color]), keep it updated
727 ([`add_updater`][manimgx.Mobject.add_updater]), and animate any of that
728 ([`animate`][manimgx.Mobject.animate]).
730 A transformation or a style acts on the mobject's whole family — the mobject, its
731 submobjects, theirs, and so on — and returns the mobject, so calls chain:
732 `Square().scale(2).set_color(BLUE)`. Size and layout go by the mobject's
733 [bounding box][manimgx.Mobject.boundary_box]: the smallest box, aligned with the
734 axes, around what it draws.
735 """
737 animation_overrides: ClassVar[
738 dict[type["Animation"], Callable[..., "Animation"]]
739 ] = {}
740 # The animations the class plays another in place of: each animation class, with the
741 # function that makes the one played instead (see `override_animation`).
742 defaults: ClassVar[Style] = {}
743 """The style keywords whose defaults the class changes: a subclass lists only what
744 it changes (`defaults = {"color": BLUE}`), and takes the rest from its parents (see
745 [style_defaults][manimgx.mobject.style_defaults])."""
746 shared: ClassVar[frozenset[str]] = frozenset(
747 {"style", "__orig_class__", "_film_record"}
748 )
749 """The attributes a copy shares with its original instead of copying them: values
750 that are never changed in place."""
752 # CE's style attributes, kept in the paint: each reads and sets the mobject's own,
753 # not its family's
754 joint_type = PaintAttribute[LineJointType]("joint")
755 """How the mobject's own stroke is joined where its path turns: round, beveled or
756 mitered (see [LineJointType][manimgx.LineJointType])."""
757 cap_style = PaintAttribute[CapStyleType]("cap")
758 """How the mobject's own stroke ends, at each end it shows: round, butt or square
759 (see [CapStyleType][manimgx.CapStyleType])."""
760 shade_in_3d = PaintAttribute[bool]("shade_in_3d")
761 """Whether a three-dimensional scene's light shades the mobject's own paint."""
762 material = PaintAttribute[Material | None]("material")
763 """How the mobject's own surface reflects the scene's lights (see
764 [Material][manimgx.Material]); None: Manim's shading."""
765 sheen_factor = PaintAttribute[float]("sheen_factor")
766 """How much the mobject's own colors lighten toward its `sheen_direction`, from -1
767 to 1 (0: none; negative: they darken); see
768 [set_sheen][manimgx.Mobject.set_sheen]."""
769 sheen_direction = PaintArray[Vector3D, Vector3DLike]("sheen_direction")
770 """The direction the mobject's own colors lighten toward, which its color gradients
771 run along too."""
772 fill_rgbas = PaintArray[RGBA_Array]("fill")
773 """The mobject's own fill colors, as rows of red, green, blue and opacity, from 0 to
774 1: one row per gradient stop."""
775 stroke_rgbas = PaintArray[RGBA_Array]("stroke")
776 """The mobject's own stroke colors, as rows of red, green, blue and opacity, from 0
777 to 1."""
778 background_stroke_rgbas = PaintArray[RGBA_Array]("background")
779 """The colors of the mobject's own background stroke (an outline drawn behind its
780 fill), as rows of red, green, blue and opacity, from 0 to 1."""
781 background_stroke_width = PaintAttribute[float]("background_width")
782 """The width of the mobject's own background stroke, in hundredths of a scene
783 unit."""
784 z_index_group: "Mobject | None" = None
785 """The group the mobject is ordered with in a three-dimensional scene, if any: set
786 by `set_shade_in_3d(z_index_as_group=True)`. Kept for Manim compatibility: the
787 renderer draws a three-dimensional scene by depth."""
789 def __init_subclass__(cls, **kwargs: object) -> None:
790 super().__init_subclass__(**kwargs)
791 own = {
792 _plays_instead[f]: f
793 for f in vars(cls).values()
794 if inspect.isfunction(f) and f in _plays_instead
795 }
796 if own: # a class's overrides are its bases' and its own
797 cls.animation_overrides = cls.animation_overrides | own
799 def __init__(self, **kwargs: Unpack[Style]) -> None:
800 if (
801 "color" in kwargs and kwargs["color"] is None
802 ): # not given: the class's default
803 del kwargs["color"]
804 self.style = style_defaults(type(self)) | kwargs
805 """Pending constructor style, including the class's defaults. Base color
806 initialization consumes this instance entry; current appearance is kept in
807 [paint][manimgx.Mobject.paint]. Point clouds retain their defaults for later points."""
808 name = self.style.get("name")
809 self.name = type(self).__name__ if name is None else name
810 """The mobject's name: its class's name, unless it was made with one."""
811 self.dim = 3
812 """How many coordinates each of its points has: 3."""
813 self.target: Mobject | None = self.style.get("target")
814 """The state [MoveToTarget][manimgx.MoveToTarget] moves the mobject to: made by
815 [generate_target][manimgx.Mobject.generate_target], or given when the mobject
816 was made; None if neither."""
817 self.z_index = self.style.get("z_index", 0.0)
818 """The mobject's place in the drawing order: a higher index is drawn over a
819 lower one (default 0); see [set_z_index][manimgx.Mobject.set_z_index]."""
820 self.submobjects: list[Mobject] = []
821 """The mobject's children, in drawing order: each is drawn over those before it,
822 at an equal z-index."""
823 self.updaters: list[Updater[Self]] = []
824 """The mobject's own updaters, in the order they run; see
825 [add_updater][manimgx.Mobject.add_updater]."""
826 self.updating_suspended = False
827 """Whether the mobject's updaters are suspended; see
828 [suspend_updating][manimgx.Mobject.suspend_updating]."""
829 self.paint = _UNPAINTED
830 """The mobject's own style as it is now, as one value: its colors, opacities,
831 stroke widths and sheen. The style methods replace it; it is never changed in
832 place."""
833 self.reset_points()
834 self.generate_points()
835 self.init_colors()
837 # ── kind hooks ─────────────────────────────────────────────────────────
838 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
839 def generate_points(self) -> Self:
840 """Build the mobject's points: its shape.
842 The constructor calls it. A class with a shape of its own overrides it; a plain
843 mobject has no points.
844 """
845 return self
847 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
848 def init_points(self) -> Self:
849 """Build the mobject's points: the same as
850 [generate_points][manimgx.Mobject.generate_points], by another name.
851 """
852 # CE's other name for `generate_points`
853 self.generate_points()
854 return self
856 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
857 def init_colors(self, propagate_colors: bool = True) -> Self:
858 """Paint the mobject with its style.
860 The constructor calls it once its points are built: the first call paints the
861 style keywords the mobject was made with, then consumes those inputs. A later
862 call paints its present style again — its first fill and stroke colors, their
863 opacities, its stroke widths and its sheen. A subclass can read its instance's
864 pending `style` before delegating; successful initialization removes that entry.
866 Args:
867 propagate_colors: Whether its whole family is painted (so the parts
868 [generate_points][manimgx.Mobject.generate_points] made), or the mobject
869 alone.
870 """
871 # CE semantics: the first call paints the constructor style onto the family,
872 # later calls re-apply the current style to it
873 family = propagate_colors
874 p = self.paint
875 s: Style | None = self.__dict__.get("style")
876 if s is None:
877 self.set_fill(self.get_fill_color(), p.fill[0, 3], family)
878 self.set_stroke(
879 self.get_stroke_color(), p.stroke_width, p.stroke[0, 3], family=family
880 )
881 self.set_stroke(
882 self.get_stroke_color(background=True),
883 p.background_width,
884 p.background[0, 3],
885 background=True,
886 family=family,
887 )
888 return self.set_sheen(p.sheen_factor, p.sheen_direction, family)
889 members = self._each(family)
890 key = _style_key(s)
891 if key is not None and any(m.paint is not _UNPAINTED for m in members):
892 key = None # a family painted already is painted over, not looked up
893 if key is not None: # the paint a style makes is a value: made once, shared
894 styled = _STYLED.get(key)
895 if styled is not None and (len(members) == 1 or styled[1] is not None):
896 self.paint, rest = styled
897 if rest is not None:
898 for m in members[1:]:
899 m.paint = rest
900 del self.style
901 return self
902 color = s.get("color", WHITE)
903 fill, stroke, joint = (
904 s.get("fill_color"),
905 s.get("stroke_color"),
906 s.get("joint_type"),
907 )
908 self.paint = p.but(
909 joint=LineJointType.AUTO if joint is None else joint,
910 cap=s.get("cap_style", CapStyleType.AUTO),
911 shade_in_3d=s.get("shade_in_3d", False),
912 material=s.get("material"),
913 )
914 self.set_fill(
915 color if fill is None else fill, s.get("fill_opacity", 0.0), family
916 )
917 self.set_stroke(
918 color if stroke is None else stroke,
919 s.get("stroke_width", DEFAULT_STROKE_WIDTH),
920 s.get("stroke_opacity", 1.0),
921 family=family,
922 )
923 self.set_stroke(
924 s.get("background_stroke_color", BLACK),
925 s.get("background_stroke_width", 0.0),
926 s.get("background_stroke_opacity", 1.0),
927 background=True,
928 family=family,
929 )
930 self.set_sheen(s.get("sheen_factor", 0.0), s.get("sheen_direction", UL), family)
931 del self.style
932 if key is not None:
933 _STYLED.keep(
934 key, (self.paint, members[1].paint if len(members) > 1 else None)
935 )
936 return self
938 # its points are cubic curves' control points (a path): its box is its curves' tight box
939 _curves: ClassVar[bool] = False
941 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
942 def get_points_defining_boundary(self) -> Point3D_Array:
943 """The points [get_boundary_point][manimgx.Mobject.get_boundary_point] chooses
944 among: every point of the mobject's family — or, for a path, its members'
945 anchors, the ends of its curves (a path's handles need not lie on it).
947 The mobject's bounding box is not made from them: it is
948 [boundary_box][manimgx.Mobject.boundary_box], around what the family draws.
950 Returns:
951 The points, as an (n, 3) array.
952 """
953 if not self._curves:
954 return self.get_all_points()
955 arrays = [
956 _anchors(m.points)
957 for m in self.get_family()
958 if m._curves and m.has_points()
959 ]
960 return np.concatenate(arrays) if arrays else np.zeros((0, 3))
962 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
963 def align_points_with_larger(self, larger: "Mobject") -> Self:
964 """Give the mobject as many points as `larger`, its shape unchanged, so the two
965 can be blended point by point.
967 [align_points][manimgx.Mobject.align_points] calls it on the one of two mobjects
968 with fewer points. Each kind implements it (a path divides its curves); a
969 mobject of no kind cannot.
971 Args:
972 larger: The mobject with more points.
973 """
974 raise NotImplementedError(f"{type(self).__name__} cannot align points")
976 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
977 def get_point_mobject(self, center: Point3DLike | None = None) -> "Mobject":
978 """The mobject shrunk to a point: what it grows from, or shrinks to, when a
979 transform makes it appear or disappear.
981 A kind returns a point of its own kind and style; a mobject of no kind, the
982 group of its members' points.
984 Args:
985 center: Where the point is; None for the mobject's center.
987 Returns:
988 A new mobject.
989 """
990 c = self.get_center() if center is None else center
991 return Group(*(m.get_point_mobject(c) for m in self.submobjects))
993 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
994 def pointwise_become_partial(self, mobject: "Mobject", a: float, b: float) -> Self:
995 """Become a part of another mobject: its points from proportion `a` of the way
996 along it to proportion `b`, as a reveal over that stretch shows it: a path's
997 curves, cut where `a` and `b` fall; a cloud's points, a mesh's triangles and a
998 surface's faces whole, every one the stretch reaches into.
1000 [get_pieces][manimgx.Mobject.get_pieces] calls it. Each kind implements it; a
1001 mobject of no kind stays as it is.
1003 Args:
1004 mobject: The mobject to take a part of (this one, or one of its kind).
1005 a: Where the part starts, from 0 to 1.
1006 b: Where the part ends, from `a` to 1.
1007 """
1008 return self
1010 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1011 def reveal_pace(self) -> tuple[np.ndarray, np.ndarray] | None:
1012 """How a reveal ([Create][manimgx.Create], [Write][manimgx.Write], …) moves
1013 through the mobject: evenly by its parts, or, for a path, by arc length, so it
1014 is drawn at a steady speed.
1016 The reveal animations read it for each drawn member.
1018 Returns:
1019 None for evenly by step (points, triangles, or a surface's faces, in order,
1020 each whole with all it draws); for a path, fractions of its length and the
1021 curve parameters where they are reached.
1022 """
1023 return None
1025 # ── points ────────────────────────────────────────────────────────────
1026 @property
1027 def points(self) -> Point3D_Array:
1028 """The mobject's own points, in scene coordinates: an (n, 3) array, read-only.
1030 A path's are the control points of its cubic Bézier curves, four per curve.
1031 Assign an array to reshape the mobject; its submobjects keep theirs. Assigning the
1032 points it has changes nothing (it keeps its geometry, and all that was derived from
1033 it), unless they are a blend of shapes, as mid-morph, which become one; assigning
1034 them with more after them grows it.
1035 """
1036 # the geometry blend, materialized (cached, hence read-only)
1037 return self._geometry.points()
1039 @points.setter
1040 def points(self, value: Point3DLike_Array) -> None:
1041 array = np.asarray(value, dtype=float).reshape(-1, self.dim)
1042 g = self.__dict__.get("_geometry", EMPTY) # (none yet, while constructing)
1043 # one shape: the points it was given again, or more after them, compared as the
1044 # geometry holds them (their last point first: points that changed are told at once),
1045 # are unchanged, or grown; so are the points it was read as (never read for this: a
1046 # change would pay for it). A blend of more shapes becomes one again, which the
1047 # player draws directly.
1048 if 0 < g.n <= len(array) and len(g.terms) == 1:
1049 m, shape = g.terms[0]
1050 if (
1051 np.array_equal(m[:, :3], np.eye(3))
1052 and np.array_equal(array[g.n - 1] - m[:, 3], shape.array[-1])
1053 and np.array_equal(array[: g.n] - m[:, 3], shape.array)
1054 ):
1055 if len(array) > g.n:
1056 self._geometry = Blend(
1057 ((m, shape.extended(array[g.n :] - m[:, 3])),), len(array)
1058 )
1059 return
1060 if g.n == len(array) and unchanged(array, g.cached):
1061 return
1062 self._geometry = Blend.of(array, self.dim)
1064 def reset_points(self) -> Self:
1065 """Remove the mobject's own points; its submobjects keep theirs."""
1066 self._geometry: Blend = EMPTY
1067 return self
1069 def set_points(self, points: Point3DLike_Array) -> Self:
1070 """Give the mobject new points of its own, in place of its present ones.
1072 Args:
1073 points: The points, in scene coordinates: an (n, 3) array.
1074 """
1075 self.points = np.array(points, dtype=float)
1076 return self
1078 @deprecated("get_points() is points: use it", category=None)
1079 def get_points(self) -> Point3D_Array:
1080 """The mobject's own [points][manimgx.Mobject.points].
1082 Returns:
1083 An (n, 3) array, read-only.
1084 """
1085 return self.points
1087 def has_points(self) -> bool:
1088 """Whether the mobject has points of its own (a group has none: its members do)."""
1089 return self._geometry.n > 0
1091 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1092 def has_no_points(self) -> bool:
1093 """Whether the mobject has no points of its own."""
1094 return self._geometry.n == 0
1096 @deprecated("use len(mobject.points)", category=None)
1097 def get_num_points(self) -> int:
1098 """How many points of its own the mobject has.
1100 Returns:
1101 The number of points.
1102 """
1103 return self._geometry.n
1105 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1106 def get_all_points(self) -> Point3D_Array:
1107 """Every point of the mobject's family, member after member.
1109 Returns:
1110 An (n, 3) array.
1111 """
1112 arrays = [m.points for m in self.get_family()]
1113 return np.concatenate(arrays) if arrays else np.zeros((0, 3))
1115 def get_start(self) -> Point3D:
1116 """The mobject's first point: where a path starts.
1118 Raises an exception if the mobject has no points of its own.
1120 Returns:
1121 The point, in scene coordinates.
1122 """
1123 self._require_points()
1124 return np.array(self.points[0])
1126 def get_end(self) -> Point3D:
1127 """The mobject's last point: where a path ends.
1129 Raises an exception if the mobject has no points of its own.
1131 Returns:
1132 The point, in scene coordinates.
1133 """
1134 self._require_points()
1135 return np.array(self.points[-1])
1137 @deprecated("use get_start() and get_end()", category=None)
1138 def get_start_and_end(self) -> tuple[Point3D, Point3D]:
1139 """The mobject's first and last points.
1141 Returns:
1142 Its [start][manimgx.Mobject.get_start] and its
1143 [end][manimgx.Mobject.get_end], in scene coordinates.
1144 """
1145 return self.get_start(), self.get_end()
1147 def _require_points(self) -> None:
1148 if self.has_no_points():
1149 raise Exception(
1150 f"Cannot call this method on a {type(self).__name__} with no points"
1151 )
1153 # ── family ────────────────────────────────────────────────────────────
1154 def add(self, *mobjects: "Mobject") -> Self:
1155 """Add submobjects after the ones the mobject has: they move with it, and are
1156 drawn over those before them (at an equal z-index).
1158 A mobject that is a submobject already moves to the end. Adding anything but a
1159 mobject, or the mobject itself or one that holds it, raises an exception (a
1160 mobject cannot hold itself).
1162 Args:
1163 *mobjects: The mobjects to add, in order.
1164 """
1165 return self._place(None, mobjects)
1167 def add_to_back(self, *mobjects: "Mobject") -> Self:
1168 """Add submobjects before the ones the mobject has: they are drawn under them
1169 (at an equal z-index).
1171 A mobject that is a submobject already moves to the front; what `add` refuses,
1172 this refuses too.
1174 Args:
1175 *mobjects: The mobjects to add, in order.
1176 """
1177 return self._place(0, mobjects)
1179 def insert(self, index: int, mobject: "Mobject") -> Self:
1180 """Insert a submobject at a place among the mobject's other submobjects.
1182 A mobject that is a submobject already moves there; what `add` refuses, this
1183 refuses too.
1185 Args:
1186 index: Its place in the list of the other submobjects, as `list.insert`
1187 takes it.
1188 mobject: The mobject to insert.
1189 """
1190 return self._place(index, (mobject,))
1192 def _place(self, index: int | None, mobjects: Sequence["Mobject"]) -> Self:
1193 """The one way submobjects join: each a mobject that neither is this one nor holds
1194 it, once (where it last occurs), at `index` among the others (None: last)."""
1195 for m in mobjects:
1196 if m is self or (
1197 m.submobjects and any(member is self for member in m.get_family())
1198 ):
1199 raise ValueError(
1200 f"Cannot add {type(m).__name__} to {type(self).__name__}: a"
1201 " mobject cannot hold itself"
1202 )
1203 new = remove_list_redundancies(list(mobjects))
1204 joining = {id(m) for m in new}
1205 others = [m for m in self.submobjects if id(m) not in joining]
1206 at = len(others) if index is None else index
1207 self.submobjects = others[:at] + new + others[at:]
1208 return self
1210 def remove(self, *mobjects: "Mobject") -> Self:
1211 """Remove submobjects: those given that are among the mobject's own submobjects
1212 (not its submobjects' submobjects); the rest are ignored.
1214 Args:
1215 *mobjects: The mobjects to remove.
1216 """
1217 for m in mobjects:
1218 if m in self.submobjects:
1219 self.submobjects.remove(m)
1220 return self
1222 def get_family(self) -> list["Mobject"]:
1223 """The mobject and all its descendants: itself, then each submobject's family in
1224 turn, each member once (where it last occurs, if the tree holds it twice).
1226 Returns:
1227 A new list.
1228 """
1229 if not self.submobjects:
1230 return [self]
1231 return _family((self,))
1233 def family_members_with_points(self) -> list["Mobject"]:
1234 """The members of the mobject's family that have points of their own: the ones
1235 that are drawn.
1237 Returns:
1238 A new list, in family order.
1239 """
1240 return [m for m in self.get_family() if m.has_points()]
1242 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1243 def split(self) -> list["Mobject"]:
1244 """The mobject's parts: itself, if it has points of its own, then its
1245 submobjects.
1247 Indexing the mobject (`mobject[0]`), slicing it, iterating over it and its `len`
1248 go through the same parts.
1250 Returns:
1251 A new list.
1252 """
1253 return list(self)
1255 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1256 def get_group_class(self) -> type["Group"]:
1257 """The class of the groups the mobject's parts are gathered in: slicing it
1258 (`mobject[1:3]`) makes one.
1260 Returns:
1261 [Group][manimgx.Group].
1262 """
1263 return Group
1265 def __iter__(self) -> Iterator["Mobject"]:
1266 return it.chain([self] if self.has_points() else [], self.submobjects)
1268 def __len__(self) -> int:
1269 return len(self.submobjects) + (1 if self.has_points() else 0)
1271 @overload
1272 def __getitem__(self, value: int) -> "Mobject": ...
1273 @overload
1274 def __getitem__(self, value: slice) -> "Mobject": ...
1275 def __getitem__(self, value: int | slice) -> "Mobject":
1276 items = list(self)
1277 if isinstance(value, slice):
1278 return self.get_group_class()(*items[value])
1279 return items[value]
1281 # ── copying ───────────────────────────────────────────────────────────
1282 def __deepcopy__(self, memo: dict[int, object]) -> Self:
1283 """A copy shares what cannot change (geometry and paint are values, and what the class
1284 names in `shared`) and deep-copies the rest."""
1285 cls = type(self)
1286 result = cls.__new__(cls)
1287 memo[id(self)] = result
1288 _copy_state(self, result, memo)
1289 return result
1291 def copy(self) -> Self:
1292 """A copy of the mobject, with its whole family.
1294 Every mobject its attributes refer to is copied once, so an attribute that
1295 refers to one of its members refers to the copy's member. The copy runs the same
1296 updater functions, on itself, and is not in the scene. Copying is cheap: the
1297 copy shares the original's points and style until either one changes them.
1298 """
1299 return copy.deepcopy(self)
1301 def generate_target(self) -> Self:
1302 """Make the mobject's [target][manimgx.Mobject.target]: a copy of it, which you
1303 change into the state [MoveToTarget][manimgx.MoveToTarget] then animates the
1304 mobject to.
1306 Using [animate][manimgx.Mobject.animate] makes a new target too, in place of
1307 this one.
1309 Returns:
1310 The target.
1312 Examples:
1313 ```python
1314 import manimgx as m
1317 class MobjectGenerateTargetExample(m.Scene):
1318 def construct(self) -> None:
1319 circle = m.Circle(radius=1.5, color=m.BLUE).shift(3 * m.LEFT)
1320 target = circle.generate_target()
1321 target.set_fill(m.GREEN, opacity=0.5).shift(6 * m.RIGHT + m.UP)
1322 target.scale(0.5)
1323 self.add(circle)
1324 self.play(m.MoveToTarget(circle))
1325 ```
1326 """
1327 self.target = None # not copied into the new target
1328 self.target = self.copy()
1329 return self.target
1331 def save_state(self) -> Self:
1332 """Keep a copy of the mobject as it is now, to return to with
1333 [restore][manimgx.Mobject.restore] or the [Restore][manimgx.Restore] animation.
1335 The copy is the mobject's `saved_state`; saving again replaces it.
1337 Examples:
1338 ```python
1339 import manimgx as m
1342 class MobjectSaveStateExample(m.Scene):
1343 def construct(self) -> None:
1344 square = m.Square(color=m.BLUE, fill_opacity=0.5)
1345 square.save_state()
1346 self.add(square)
1347 self.play(square.animate.set_color(m.YELLOW).shift(3 * m.LEFT))
1348 self.play(square.animate.rotate(m.PI / 4).scale(2))
1349 self.play(m.Restore(square))
1350 ```
1351 """
1352 self.saved_state = None # not copied into the new saved state
1353 self.saved_state = self.copy()
1354 return self
1356 def restore(self) -> Self:
1357 """Make the mobject what it was when [save_state][manimgx.Mobject.save_state]
1358 last kept it: its points and its style, member by member (see
1359 [become][manimgx.Mobject.become]).
1361 Raises an exception if its state was never saved.
1362 """
1363 saved = getattr(self, "saved_state", None)
1364 if saved is None:
1365 raise Exception("Trying to restore without having saved")
1366 self.become(saved)
1367 return self
1369 # ── updaters ──────────────────────────────────────────────────────────
1370 # A time-based updater integrates the time it is live: `advance(t)` hands it the time since
1371 # it was last brought forward — or attached, joined the scene, or resumed — on its clock:
1372 # scene time, unless the updater carries a `clock` (ChangeSpeed's do).
1373 def update(self, dt: float = 0, recursive: bool = True) -> Self:
1374 """Run each of the mobject's updaters once, now; nothing runs while its updating
1375 is suspended.
1377 The scene runs updaters itself, at every frame: this runs them by hand, now.
1379 Args:
1380 dt: The seconds handed to its time-based updaters.
1381 recursive: Whether its submobjects' updaters run too, after its own.
1382 """
1383 # CE's; the scene uses `advance`
1384 if self.updating_suspended:
1385 return self
1386 updaters = self.updaters
1387 for updater in updaters:
1388 if updaters is not self.updaters and not _has_updater(
1389 self.updaters, updater
1390 ):
1391 continue
1392 if _per_frame(updater):
1393 updater(self)
1394 else:
1395 updater(self, dt)
1396 if recursive:
1397 for sub in self.submobjects:
1398 sub.update(dt, recursive)
1399 return self
1401 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1402 def advance(
1403 self,
1404 t: Fraction,
1405 recursive: bool = True,
1406 recorders: "list[_Recorder] | None" = None,
1407 ) -> Self:
1408 """Bring the mobject's updaters to scene time `t`.
1410 An engine hook: the scene calls it on each of its mobjects at every instant it
1411 computes, and an animation on the copy of its mobject that the updaters run on
1412 while it plays. Each time-based updater is handed the time since it last ran —
1413 on its own clock, if it has one (as [ChangeSpeed][manimgx.ChangeSpeed]'s
1414 updaters do). A simulated one (time-based, not a
1415 [flow][manimgx.mobject.flow]) runs only at the ticks of the simulation
1416 clock and at the ends of plays and waits; a per-frame one only at frames and
1417 those ends. Nothing runs while the mobject's updating is suspended.
1419 Args:
1420 t: The scene time, in seconds, exact.
1421 recursive: Whether its submobjects' updaters are brought there too, after
1422 its own.
1423 recorders: Where the scene collects the
1424 [recorders][manimgx.mobject.record], each with its mobject
1425 and the updater list it came from, to run them once everything
1426 else is at `t`; None: they run here, as the
1427 simulated updaters they are.
1428 """
1429 # a simulated updater runs only where it steps (`clock.stepping`: between the
1430 # simulation clock's ticks it stays where it was); a per-frame one only at a
1431 # frame or an event (`clock.framing`)
1432 if self.updating_suspended:
1433 return self
1434 updaters = self.updaters
1435 for updater in updaters:
1436 if updaters is not self.updaters and not _has_updater(
1437 self.updaters, updater
1438 ):
1439 continue
1440 if _per_frame(updater):
1441 if clock.framing:
1442 updater(self)
1443 elif recorders is not None and records(updater):
1444 recorders.append((self, updater, updaters))
1445 elif clock.stepping or _flows(updater):
1446 self._bring(updater, t)
1447 if recursive:
1448 for sub in self.submobjects:
1449 sub.advance(t, recursive, recorders)
1450 return self
1452 def _bring(self, updater: Callable[..., object], t: Fraction) -> None:
1453 """Run a time-based updater with the time its clock ran since it was last brought
1454 forward."""
1455 since = self._since
1456 start = since.get(updater, t)
1457 since[updater] = t
1458 on: clock.Clock | None = getattr(updater, "clock", None)
1459 dt = float(t - start) if on is None else on.at(float(t)) - on.at(float(start))
1460 updater(self, dt)
1462 @property
1463 def _since(self) -> dict[object, Fraction]:
1464 """When each time-based updater was last brought forward (made on first use)."""
1465 since = self.__dict__.get("_since_")
1466 if since is None:
1467 since = self.__dict__["_since_"] = {}
1468 return since
1470 def _stamp(self, t: Fraction, recursive: bool = True) -> None:
1471 """The time-based updaters start (again) from `t`: they joined the scene, or resumed."""
1472 for updater in self.updaters:
1473 if not _per_frame(updater):
1474 self._since[updater] = t
1475 if recursive:
1476 for sub in self.submobjects:
1477 sub._stamp(t, recursive)
1479 @overload
1480 def add_updater(
1481 self,
1482 update_function: Callable[[Self], object],
1483 index: int | None = None,
1484 call_updater: bool = False,
1485 ) -> Self: ...
1486 @overload
1487 def add_updater(
1488 self,
1489 update_function: Callable[[Self, float], object],
1490 index: int | None = None,
1491 call_updater: bool = False,
1492 ) -> Self: ...
1493 def add_updater(
1494 self,
1495 update_function: Updater[Self],
1496 index: int | None = None,
1497 call_updater: bool = False,
1498 ) -> Self:
1499 """Add an updater: a function that keeps the mobject updated as time passes.
1501 An updater is a function of the mobject, run once a frame — to keep a relation,
1502 such as a label beside a dot — or, if it has a parameter named `dt`, of the
1503 mobject and `dt`: the seconds of scene time since it last ran, or since it was
1504 added, the mobject joined the scene, or its updating resumed. A time-based
1505 updater moves the mobject by the time that passed:
1506 `lambda mob, dt: mob.rotate(dt * PI)` turns it half a turn a second, at any
1507 frame rate. What an updater returns is ignored.
1509 The scene runs the updaters of the mobjects in it at every frame, after the
1510 animations playing have moved them to the frame's instant, and at the end of
1511 each play and wait: mobject by mobject in the order they were added to the
1512 scene, a mobject's own before its submobjects', and a
1513 [recorder][manimgx.mobject.record] after all the rest. So add a mobject
1514 that follows another after it, or it sees where the other's updaters left it at
1515 the instant before. Updaters keep running while an animation plays the mobject,
1516 beneath the animation (see `suspend_mobject_updating` among the
1517 [animation options][manimgx.animation.timeline.AnimationOptions]). A time-based
1518 updater steps on the scene's simulation clock, `config.simulation_rate` ticks a
1519 second, so it takes the same steps at any frame rate; declare one that does the
1520 same however its time is split a [flow][manimgx.mobject.flow], and it runs
1521 exactly at every frame instead.
1523 Args:
1524 update_function: The updater: a function of the mobject, or of the mobject
1525 and `dt`.
1526 index: Where it goes among the mobject's updaters, which run in order; None
1527 for last.
1528 call_updater: Whether to run it once right away; a time-based one is handed
1529 a `dt` of 0.
1531 Examples:
1532 ```python
1533 import manimgx as m
1536 class MobjectAddUpdaterExample(m.Scene):
1537 def construct(self) -> None:
1538 hand = m.Line(m.ORIGIN, 3 * m.RIGHT, color=m.BLUE)
1539 # time-based: a quarter turn about the origin every second
1540 hand.add_updater(
1541 lambda mob, dt: mob.rotate(dt * m.PI / 2, about_point=m.ORIGIN)
1542 )
1543 dot = m.Dot(radius=0.2, color=m.YELLOW)
1544 # per frame: at the hand's end, wherever it is
1545 dot.add_updater(lambda mob: mob.move_to(hand.get_end()))
1546 self.add(hand, dot)
1547 self.wait(3)
1548 ```
1549 """
1550 if index is None:
1551 self.updaters.append(update_function)
1552 else:
1553 self.updaters.insert(index, update_function)
1554 if not _per_frame(update_function):
1555 self._since[update_function] = clock.now # it integrates from now
1556 if call_updater:
1557 if _per_frame(update_function):
1558 update_function(self)
1559 else:
1560 update_function(self, 0)
1561 return self
1563 def remove_updater(self, update_function: Updater[Never]) -> Self:
1564 """Remove an updater from the mobject, every time it was added.
1566 This also cancels calls that have not yet run in the current update,
1567 including a recorder waiting for the other updaters to finish.
1569 Args:
1570 update_function: The updater to remove.
1571 """
1572 self.updaters = [u for u in self.updaters if u is not update_function]
1573 since = self.__dict__.get("_since_")
1574 if since is not None and update_function not in self.updaters:
1575 since.pop(update_function, None)
1576 return self
1578 def clear_updaters(self, recursive: bool = True) -> Self:
1579 """Remove every updater of the mobject, including calls still waiting
1580 to run in the current update.
1582 Args:
1583 recursive: Whether its whole family's updaters are removed too.
1584 """
1585 self.updaters = []
1586 self.__dict__.pop("_since_", None)
1587 if recursive:
1588 for sub in self.submobjects:
1589 sub.clear_updaters()
1590 return self
1592 def get_updaters(self) -> tuple[Updater[Self], ...]:
1593 """The mobject's own updaters, in the order they run.
1595 Change them with [add_updater][manimgx.Mobject.add_updater],
1596 [remove_updater][manimgx.Mobject.remove_updater] and
1597 [clear_updaters][manimgx.Mobject.clear_updaters], which keep their clocks with
1598 them.
1600 Returns:
1601 A snapshot of them.
1602 """
1603 return tuple(self.updaters)
1605 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1606 def get_family_updaters(self) -> list[Updater[Never]]: # each of its own kind
1607 """Every updater of the mobject's family: its own, then its descendants', in
1608 family order.
1610 Returns:
1611 A new list.
1612 """
1613 return [u for m in self.get_family() for u in m.updaters]
1615 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1616 def has_time_based_updater(self) -> bool:
1617 """Whether any of the mobject's own updaters is time-based: it takes `dt`."""
1618 return not all(_per_frame(u) for u in self.updaters)
1620 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1621 def get_time_based_updaters(self) -> list[Updater[Self]]:
1622 """The mobject's own time-based updaters: those that take `dt`.
1624 Returns:
1625 A new list, in the order they run.
1626 """
1627 return [u for u in self.updaters if not _per_frame(u)]
1629 @property
1630 def always(self) -> "Always[Self]":
1631 """A proxy that turns each method call made on it into an updater: the call is
1632 made again every frame.
1634 `label.always.next_to(dot, UP)` keeps the label above the dot, wherever the dot
1635 goes. Each call is also made right away, and adds one per-frame updater (see
1636 [add_updater][manimgx.Mobject.add_updater]); the proxy returns itself, so calls
1637 chain. The arguments are taken once, as written: pass the mobject to follow
1638 (`dot`), not its position (`dot.get_center()`), which stays where it was.
1640 Examples:
1641 ```python
1642 import manimgx as m
1645 class MobjectAlwaysExample(m.Scene):
1646 def construct(self) -> None:
1647 square = m.Square(color=m.BLUE, fill_opacity=0.5).shift(4 * m.LEFT)
1648 label = m.Text("always above")
1649 label.always.next_to(square, m.UP)
1650 self.add(square, label)
1651 self.play(square.animate.shift(8 * m.RIGHT), run_time=2)
1652 ```
1653 """
1654 # CE's
1655 from manimgx.animation.transform import Always
1657 return Always(self)
1659 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1660 def match_updaters(self, mobject: "Mobject") -> Self:
1661 """Give the mobject another's updaters in place of its own, and clear its
1662 submobjects'.
1664 They are the same functions, now run on this mobject too; the time-based ones
1665 start from now.
1667 Args:
1668 mobject: The mobject whose updaters to take (its own, not its family's).
1669 """
1670 self.clear_updaters()
1671 self.updaters.extend(mobject.updaters)
1672 self._stamp(clock.now, recursive=False)
1673 return self
1675 def suspend_updating(self, recursive: bool = True) -> Self:
1676 """Stop the mobject's updaters from running, and its family's beneath it, until
1677 [resume_updating][manimgx.Mobject.resume_updating]: nothing updated through a
1678 suspended mobject runs.
1680 An animation suspends the updating of the mobject it plays while it plays, and
1681 runs the updaters beneath it instead (see
1682 [add_updater][manimgx.Mobject.add_updater]).
1684 Args:
1685 recursive: Whether each member of its family is suspended too, so that it stays
1686 stopped where it is updated apart from the mobject (a member the scene
1687 also holds by itself), and when the mobject alone resumes.
1688 """
1689 self.updating_suspended = True
1690 if recursive:
1691 for sub in self.submobjects:
1692 sub.suspend_updating(recursive)
1693 return self
1695 def resume_updating(self, recursive: bool = True) -> Self:
1696 """Let the mobject's updaters run again, from now: the time they were suspended
1697 is not made up.
1699 They are not run here: the scene runs them where it next brings the world — at
1700 the instant it is computing, when an animation resumes them as it finishes,
1701 else at the next one, such as the next frame.
1703 Args:
1704 recursive: Whether its whole family's updaters resume too: resumed alone, the
1705 mobject runs again, and the members beneath it that are not suspended
1706 themselves.
1707 """
1708 # not run here as well: the instant's own pass runs them, and a per-frame
1709 # updater would run twice at one instant
1710 self.updating_suspended = False
1711 if recursive:
1712 for sub in self.submobjects:
1713 sub.resume_updating(recursive)
1714 self._stamp(clock.now, recursive)
1715 return self
1717 # ── the one transform primitive ────────────────────────────────────────
1718 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1719 def apply_points_function_about_point(
1720 self,
1721 func: PointsFunc,
1722 about_point: Point3DLike | None = None,
1723 about_edge: Vector3DLike | None = None,
1724 ) -> Self:
1725 """Apply a function to the points of the mobject's whole family, about a point:
1726 each drawn member's points become `func(points - about_point) + about_point`.
1728 It moves the points alone, and a path's curves follow its control points: they
1729 are exactly their image under an affine map (a move, a scale, a rotation, a
1730 matrix), but stray from it under a function that bends them.
1731 [apply_function][manimgx.Mobject.apply_function] maps a path's curves
1732 themselves, cutting them where a function bends them.
1734 Args:
1735 func: A function of an (n, 3) array of points, relative to the point, that
1736 returns their new places.
1737 about_point: The point the function is applied about; None: see
1738 `about_edge`.
1739 about_edge: The point of the mobject's bounding box it is applied about,
1740 named by a direction (UL for its top left corner); None for its center.
1741 """
1742 if about_point is None:
1743 about_point = self.get_critical_point(
1744 ORIGIN if about_edge is None else about_edge
1745 )
1746 about = np.array(about_point, dtype=float)
1747 for mob in self.family_members_with_points():
1748 mob.points = func(mob.points - about) + about
1749 return self
1751 def shift(self, *vectors: Vector3DLike) -> Self:
1752 """Move the mobject and its whole family by a vector.
1754 Args:
1755 *vectors: The vector, in scene units (`2 * RIGHT` moves it two units right);
1756 several are added into one.
1758 Examples:
1759 ```python
1760 import manimgx as m
1763 class MobjectShiftExample(m.Scene):
1764 def construct(self) -> None:
1765 square = m.Square(color=m.BLUE, fill_opacity=0.5)
1766 self.add(square)
1767 self.play(square.animate.shift(4 * m.LEFT))
1768 self.play(square.animate.shift(2 * m.UP, 8 * m.RIGHT))
1769 ```
1770 """
1771 # one vector (a (1, 3) array too, as CE takes it)
1772 vector = vectors[0] if len(vectors) == 1 else reduce(np.add, vectors)
1773 total = np.asarray(vector, dtype=float).reshape(-1)
1774 for mob in self.family_members_with_points():
1775 mob._geometry = mob._geometry.translated(total)
1776 return self
1778 def _apply_linear(
1779 self,
1780 linear: MatrixMN,
1781 about_point: Point3DLike | None = None,
1782 about_edge: Vector3DLike | None = None,
1783 ) -> Self:
1784 """x ↦ L(x − about) + about on every member: a matrix composed into the geometry."""
1785 if about_point is None:
1786 about_point = self.get_critical_point(
1787 ORIGIN if about_edge is None else about_edge
1788 )
1789 m = linear_about(
1790 np.asarray(linear, dtype=float), np.array(about_point, dtype=float)
1791 )
1792 for mob in self.family_members_with_points():
1793 mob._geometry = mob._geometry.transformed(m)
1794 return self
1796 def scale(
1797 self,
1798 scale_factor: float | Vector3DLike,
1799 scale_stroke: bool = False,
1800 *,
1801 about_point: Point3DLike | None = None,
1802 about_edge: Vector3DLike | None = None,
1803 ) -> Self:
1804 """Scale the mobject and its whole family about a point: by one factor, or by
1805 one per axis.
1807 Stroke widths stay as they are, unless `scale_stroke`.
1809 Args:
1810 scale_factor: The factor: 2 doubles the mobject's size, 0.5 halves it, and a
1811 negative factor also reflects it through the point; or its factors along
1812 x, y and z.
1813 scale_stroke: Whether stroke widths scale too, by the factor (for factors
1814 per axis, the geometric mean of the sizes of x's and y's).
1815 about_point: The point that stays fixed; None: see `about_edge`.
1816 about_edge: The point of the mobject's bounding box that stays fixed, named
1817 by a direction (DL for its bottom left corner); None for its center.
1819 Examples:
1820 ```python
1821 import manimgx as m
1824 class MobjectScaleExample(m.Scene):
1825 def construct(self) -> None:
1826 a = m.Square(color=m.BLUE, fill_opacity=0.5)
1827 b, c = a.copy(), a.copy()
1828 m.VGroup(a, b, c).arrange(buff=2.5)
1829 for square, text in zip(
1830 (a, b, c), ("scale(2)", "about_edge=DL", "[0.5, 1.5, 1]")
1831 ):
1832 self.add(m.Text(text, font_size=32).next_to(square, m.DOWN, 2))
1833 self.add(a, b, c)
1834 self.play(
1835 a.animate.scale(2),
1836 b.animate.scale(2, about_edge=m.DL),
1837 c.animate.scale([0.5, 1.5, 1]),
1838 )
1839 ```
1840 """
1841 if scale_stroke:
1842 length = length_factor(scale_factor)
1843 for mob in self.get_family():
1844 mob.paint = mob.paint.but(
1845 stroke_width=length * mob.get_stroke_width(),
1846 background_width=length * mob.get_stroke_width(background=True),
1847 )
1848 if isinstance(scale_factor, (int, float)): # one factor: a scale about a point
1849 if about_point is None:
1850 edge = ORIGIN if about_edge is None else about_edge
1851 about_point = self.get_critical_point(edge)
1852 about = np.array(about_point, dtype=float)
1853 for mob in self.family_members_with_points():
1854 mob._geometry = mob._geometry.scaled(float(scale_factor), about)
1855 return self
1856 return self._apply_linear(
1857 np.diag(axis_factors(scale_factor)), about_point, about_edge
1858 )
1860 def rotate(
1861 self,
1862 angle: float,
1863 axis: Vector3DLike = OUT,
1864 *,
1865 about_point: Point3DLike | None = None,
1866 about_edge: Vector3DLike | None = None,
1867 ) -> Self:
1868 """Rotate the mobject and its whole family by an angle, about an axis through a
1869 point.
1871 Its sheen direction turns with it. Through [animate][manimgx.Mobject.animate],
1872 the mobject turns rigidly through the whole angle.
1874 Args:
1875 angle: The angle, in radians: counterclockwise as seen from where `axis`
1876 points (on the screen, for the default axis).
1877 axis: The axis's direction (default OUT, out of the screen: a turn in the
1878 plane).
1879 about_point: The point the axis goes through; None: see `about_edge`.
1880 about_edge: The point of the mobject's bounding box the axis goes through,
1881 named by a direction (DL for its bottom left corner); None for its
1882 center.
1884 Examples:
1885 ```python
1886 import manimgx as m
1889 class MobjectRotateExample(m.Scene):
1890 def construct(self) -> None:
1891 a = m.Square(side_length=2.5, color=m.BLUE, fill_opacity=0.5)
1892 b = m.Square(side_length=2.5, color=m.YELLOW, fill_opacity=0.5)
1893 m.VGroup(a, b).arrange(buff=4)
1894 pivot = m.Dot(b.get_corner(m.DL), radius=0.12, color=m.RED)
1895 self.add(a, b, pivot)
1896 self.play(
1897 a.animate.rotate(m.PI / 4),
1898 b.animate.rotate(m.PI / 2, about_edge=m.DL),
1899 )
1900 ```
1901 """
1902 rot = rotation_matrix(angle, axis)
1903 self._rotate_direction_state(rot)
1904 return self._apply_linear(rot, about_point, about_edge)
1906 def _rotate_direction_state(self, rot: MatrixMN) -> None:
1907 for mob in self.get_family():
1908 mob.paint = mob.paint.but(sheen_direction=rot @ mob.paint.sheen_direction)
1910 @deprecated(
1911 "rotate_about_origin(angle, axis) is rotate(angle, axis, about_point=ORIGIN)",
1912 category=None,
1913 )
1914 def rotate_about_origin(self, angle: float, axis: Vector3DLike = OUT) -> Self:
1915 """Rotate the mobject and its whole family by an angle, about an axis through
1916 the origin: `rotate(angle, axis, about_point=ORIGIN)`.
1918 Args:
1919 angle: The angle, in radians: counterclockwise as seen from where `axis`
1920 points.
1921 axis: The axis's direction (default OUT: a turn in the plane of the screen).
1922 """
1923 return self.rotate(angle, axis, about_point=ORIGIN)
1925 def flip(
1926 self,
1927 axis: Vector3DLike = UP,
1928 *,
1929 about_point: Point3DLike | None = None,
1930 about_edge: Vector3DLike | None = None,
1931 ) -> Self:
1932 """Flip the mobject and its whole family over: turn it half around an axis
1933 through a point, which mirrors it across that axis.
1935 About the default UP axis, it is mirrored left to right; about RIGHT, upside
1936 down. Through [animate][manimgx.Mobject.animate], it turns over, through space.
1938 Args:
1939 axis: The axis's direction (default UP).
1940 about_point: The point the axis goes through; None: see `about_edge`.
1941 about_edge: The point of the mobject's bounding box the axis goes through,
1942 named by a direction; None for its center.
1944 Examples:
1945 ```python
1946 import manimgx as m
1949 class MobjectFlipExample(m.Scene):
1950 def construct(self) -> None:
1951 word = m.Text("flip", font_size=160, color=m.YELLOW)
1952 self.add(word)
1953 self.play(word.animate.flip())
1954 self.play(word.animate.flip(m.RIGHT))
1955 ```
1956 """
1957 return self.rotate(
1958 TAU / 2, axis, about_point=about_point, about_edge=about_edge
1959 )
1961 @deprecated(
1962 "stretch_about_point(factor, dim, point) is stretch(factor, dim, about_point=point): use it",
1963 category=None,
1964 )
1965 def stretch_about_point(self, factor: float, dim: int, point: Point3DLike) -> Self:
1966 """Stretch the mobject and its whole family along one axis, keeping a point
1967 fixed (see [stretch][manimgx.Mobject.stretch]).
1969 Args:
1970 factor: The factor along the axis.
1971 dim: The axis: 0 for x, 1 for y, 2 for z.
1972 point: The point that stays fixed.
1973 """
1974 return self.stretch(factor, dim, about_point=point)
1976 def stretch(
1977 self,
1978 factor: float,
1979 dim: int,
1980 *,
1981 about_point: Point3DLike | None = None,
1982 about_edge: Vector3DLike | None = None,
1983 ) -> Self:
1984 """Stretch the mobject and its whole family along one axis: scale that
1985 coordinate of every point, about a point, and keep the others.
1987 Stroke widths stay as they are.
1989 Args:
1990 factor: The factor: 2 makes the mobject twice as long along the axis.
1991 dim: The axis: 0 for x (its width), 1 for y (its height), 2 for z.
1992 about_point: The point that stays fixed; None: see `about_edge`.
1993 about_edge: The point of the mobject's bounding box that stays fixed, named
1994 by a direction (DOWN for the middle of its bottom edge); None for its
1995 center.
1997 Examples:
1998 ```python
1999 import manimgx as m
2002 class MobjectStretchExample(m.Scene):
2003 def construct(self) -> None:
2004 circle = m.Circle(radius=1.5, color=m.BLUE, fill_opacity=0.5)
2005 self.add(circle)
2006 self.play(circle.animate.stretch(3, 0))
2007 self.play(circle.animate.stretch(0.5, 1, about_edge=m.DOWN))
2008 ```
2009 """
2010 linear = np.eye(3)
2011 linear[dim, dim] = factor
2012 return self._apply_linear(linear, about_point, about_edge)
2014 def apply_matrix(
2015 self,
2016 matrix: MatrixMN,
2017 *,
2018 about_point: Point3DLike | None = None,
2019 about_edge: Vector3DLike | None = None,
2020 ) -> Self:
2021 """Transform the mobject and its whole family by a matrix: each point, taken
2022 relative to a fixed point, is multiplied by it.
2024 Args:
2025 matrix: A 3 × 3 matrix, or a smaller one (2 × 2) that acts on the first
2026 coordinates and keeps the rest.
2027 about_point: The point that stays fixed; with neither this nor `about_edge`,
2028 the origin.
2029 about_edge: The point of the mobject's bounding box that stays fixed, named
2030 by a direction.
2032 Examples:
2033 ```python
2034 import manimgx as m
2037 class MobjectApplyMatrixExample(m.Scene):
2038 def construct(self) -> None:
2039 grid = m.NumberPlane()
2040 square = m.Square(color=m.YELLOW, fill_opacity=0.5).shift(m.UR)
2041 shear = [[1, 1], [0, 1]]
2042 self.add(grid, square)
2043 self.play(
2044 grid.animate.apply_matrix(shear),
2045 square.animate.apply_matrix(shear),
2046 run_time=2,
2047 )
2048 ```
2049 """
2050 if about_point is None and about_edge is None:
2051 about_point = ORIGIN
2052 full = np.identity(self.dim)
2053 m = np.array(matrix)
2054 full[: m.shape[0], : m.shape[1]] = m
2055 return self._apply_linear(full, about_point, about_edge)
2057 def apply_function(
2058 self,
2059 function: Callable[[Point3D], Point3D],
2060 *,
2061 about_point: Point3DLike | None = None,
2062 about_edge: Vector3DLike | None = None,
2063 ) -> Self:
2064 """Move the mobject's whole family through a function, about a point: each
2065 drawn member becomes its image under the function.
2067 A path's curves are mapped to the curves of their image. Each curve is mapped to
2068 the curve through the images of its ends, along the images of its directions
2069 there; where one strays from the true image halfway along it by more than 0.001
2070 scene units (a quarter of a pixel at 4K), every curve of the path is cut into 2,
2071 4, 8, … equal pieces (at most 256 each), and the pieces are mapped instead. Any
2072 other kind maps its points. Through [animate][manimgx.Mobject.animate], each
2073 point of the path, cut the same way, moves straight to its image.
2075 Args:
2076 function: A function of a point, relative to the fixed point, that returns
2077 its new place.
2078 about_point: The point the function is applied about; with neither this nor
2079 `about_edge`, the origin, so the function sees scene coordinates.
2080 about_edge: The point of the mobject's bounding box it is applied about,
2081 named by a direction.
2083 Examples:
2084 ```python
2085 import numpy as np
2087 import manimgx as m
2090 def wave(p: np.ndarray) -> np.ndarray:
2091 return p + 0.5 * np.array([np.sin(p[1]), np.sin(p[0]), 0])
2094 class MobjectApplyFunctionExample(m.Scene):
2095 def construct(self) -> None:
2096 grid = m.NumberPlane()
2097 grid.prepare_for_nonlinear_transform()
2098 self.add(grid)
2099 self.play(grid.animate.apply_function(wave), run_time=2)
2100 ```
2101 """
2102 # each leaf becomes its image its own way (`_map_points`): a mobject's points
2103 # map; a path's curves become the curves of their image (`VMobject._map_points`)
2104 if about_point is None:
2105 about_point = (
2106 ORIGIN if about_edge is None else self.get_critical_point(about_edge)
2107 )
2108 about = np.array(about_point, dtype=float)
2109 for mob in self.family_members_with_points():
2110 mob._map_points(function, about)
2111 return self
2113 def _map_points(
2114 self, function: Callable[[Point3D], Point3D], about: np.ndarray
2115 ) -> None:
2116 """This leaf's image under `function`, about `about`: each point mapped."""
2117 self.points = np.apply_along_axis(function, 1, self.points - about) + about
2119 def apply_complex_function(
2120 self, function: Callable[[complex], complex], **kwargs: Unpack[Pivot]
2121 ) -> Self:
2122 """Move the mobject's whole family through a function of a complex number: the
2123 point (x, y, z) is x + iy, and goes where `function` sends it, keeping its z.
2125 A path's curves are mapped as [apply_function][manimgx.Mobject.apply_function]
2126 maps them.
2128 Args:
2129 function: A function of a complex number, returning one.
2130 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point the
2131 function is applied about (default: the origin).
2133 Examples:
2134 ```python
2135 import manimgx as m
2138 class MobjectApplyComplexFunctionExample(m.Scene):
2139 def construct(self) -> None:
2140 grid = m.ComplexPlane(x_range=(-4, 4, 0.5), y_range=(-4, 4, 0.5))
2141 grid.prepare_for_nonlinear_transform()
2142 self.add(grid)
2143 self.play(
2144 grid.animate.apply_complex_function(lambda z: z**2 / 4),
2145 run_time=2,
2146 )
2147 ```
2148 """
2150 def r3(point: Point3D) -> Point3D:
2151 z = function(complex(point[0], point[1]))
2152 return np.array([z.real, z.imag, point[2]])
2154 return self.apply_function(r3, **kwargs)
2156 @deprecated("use move_to(function(mobject.get_center()))", category=None)
2157 def apply_function_to_position(
2158 self, function: Callable[[Point3D], Point3D]
2159 ) -> Self:
2160 """Move the mobject so its center goes where a function sends it; its shape
2161 stays.
2163 Args:
2164 function: A function of a point, in scene coordinates, that returns its new
2165 place.
2166 """
2167 return self.move_to(function(self.get_center()))
2169 @deprecated("use move_to(function(mobject.get_center()))", category=None)
2170 def apply_function_to_submobject_positions(
2171 self, function: Callable[[Point3D], Point3D]
2172 ) -> Self:
2173 """Move each submobject so its center goes where a function sends it; their
2174 shapes stay.
2176 Args:
2177 function: A function of a point, in scene coordinates, that returns its new
2178 place.
2179 """
2180 for sub in self.submobjects:
2181 sub.apply_function_to_position(function)
2182 return self
2184 @deprecated("use reverse_direction", category=None)
2185 def reverse_points(self) -> Self:
2186 """Reverse the order of the points of each drawn member of the family: a path
2187 then runs the other way, from its end to its start.
2188 """
2189 for mob in self.family_members_with_points():
2190 mob.points = mob.points[::-1].copy()
2191 return self
2193 # ── bounds: one box, what the family draws ───────────────────────────────
2194 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
2195 def length_over_dim(self, dim: int) -> float:
2196 """The mobject's extent along one axis, in scene units: its
2197 [bounding box][manimgx.Mobject.boundary_box]'s, from its lowest coordinate to
2198 its highest.
2200 Args:
2201 dim: The axis: 0 for x (its width), 1 for y (its height), 2 for z (its
2202 depth).
2204 Returns:
2205 The extent; 0 if it has no points.
2206 """
2207 box = self.boundary_box()
2208 return 0 if box is None else float(box[1, dim] - box[0, dim])
2210 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
2211 def get_extremum_along_dim(
2212 self, points: Point3D_Array | None = None, dim: int = 0, key: float = 0
2213 ) -> float:
2214 """The lowest, the middle or the highest coordinate along one axis, of some
2215 points or of the mobject's [bounding box][manimgx.Mobject.boundary_box].
2217 Args:
2218 points: The points, as an (n, 3) array; None for the mobject's bounding box.
2219 dim: The axis: 0 for x, 1 for y, 2 for z.
2220 key: Which: negative for the lowest, 0 for the middle of the range, positive
2221 for the highest.
2223 Returns:
2224 The coordinate; 0 for the box of a mobject with no points.
2225 """
2226 if points is None:
2227 box = self.boundary_box()
2228 lo, hi = (0.0, 0.0) if box is None else (box[0, dim], box[1, dim])
2229 else:
2230 lo, hi = np.min(points[:, dim]), np.max(points[:, dim])
2231 return float(lo if key < 0 else hi if key > 0 else (lo + hi) / 2)
2233 def _box(self) -> np.ndarray | None:
2234 """The (2, 3) box of what this member draws, alone: its geometry's (a path's,
2235 its curves' tight box); None when it draws nothing."""
2236 return self._geometry.box(self._curves)
2238 def boundary_box(self) -> np.ndarray | None:
2239 """The mobject's bounding box: the smallest box, aligned with the axes, around
2240 what its family draws.
2242 A path is measured by its curves themselves, not by their control points (a
2243 curve bulges past its anchors where it turns, and its handles reach past the
2244 curve); any other kind by its points. A stroke's width is not counted. It is
2245 the one box every measure reads: [width][manimgx.Mobject.width] and
2246 [height][manimgx.Mobject.height], the corners, edges and center
2247 ([get_critical_point][manimgx.Mobject.get_critical_point]), `get_x` and `get_y`,
2248 alignment and layout, and the extent of a color gradient. It joins the boxes of
2249 the family's members, so a member spans the same in whatever group holds it.
2251 Returns:
2252 A 2 × 3 array, the lowest (x, y, z) then the highest; None if the family has
2253 no points.
2254 """
2255 return _family_box(self.get_family())
2257 def get_critical_point(self, direction: Vector3DLike) -> Point3D:
2258 """A point of the mobject's bounding box, named by a direction: its center, the
2259 middle of an edge, or a corner.
2261 Each coordinate is the box's lowest where the direction's is negative, its
2262 highest where it is positive, and its middle where it is 0: UR names the top
2263 right corner, UP the middle of the top edge, ORIGIN the center. The box is
2264 [boundary_box][manimgx.Mobject.boundary_box], around what the mobject draws: a
2265 path's curves themselves, not their control points.
2267 Args:
2268 direction: The direction, such as UP, UR or ORIGIN.
2270 Returns:
2271 The point, in scene coordinates; the origin if the mobject has no points.
2272 """
2273 box = self.boundary_box()
2274 if box is None:
2275 return np.zeros(self.dim)
2276 lo, hi = box.tolist()
2277 return np.array(
2278 [
2279 lo[k] if d < 0 else hi[k] if d > 0 else (lo[k] + hi[k]) / 2
2280 for k, d in enumerate(np.asarray(direction).tolist()[: self.dim])
2281 ]
2282 )
2284 @deprecated(
2285 "get_edge_center is get_critical_point: use it, or get_top, get_bottom,"
2286 " get_left and get_right",
2287 category=None,
2288 )
2289 def get_edge_center(self, direction: Vector3DLike) -> Point3D:
2290 """The middle of an edge of the mobject's bounding box, named by a direction:
2291 [get_critical_point][manimgx.Mobject.get_critical_point], by another name."""
2292 return self.get_critical_point(direction)
2294 get_corner = get_critical_point
2295 """A corner of the mobject's bounding box, named by a direction (`get_corner(UR)`):
2296 another name for [get_critical_point][manimgx.Mobject.get_critical_point]."""
2298 def get_center(self) -> Point3D:
2299 """The center of the mobject's bounding box.
2301 Returns:
2302 The point, in scene coordinates.
2303 """
2304 return self.get_critical_point(np.zeros(self.dim))
2306 @deprecated("use get_center", category=None)
2307 def get_center_of_mass(self) -> Point3D:
2308 """The mean of all the points of the mobject's family: every control point of a
2309 path, its handles too.
2311 Returns:
2312 The point, in scene coordinates.
2313 """
2314 return np.mean(self.get_all_points(), axis=0)
2316 def get_boundary_point(self, direction: Vector3DLike) -> Point3D:
2317 """The point of the mobject farthest in a direction: of the points it is drawn
2318 through, the one farthest along `direction`.
2320 Unlike [get_critical_point][manimgx.Mobject.get_critical_point], it is one of
2321 those points (for a path, an end of one of its curves), not a point of the
2322 mobject's bounding box.
2324 Returns:
2325 The point, in scene coordinates.
2326 """
2327 points = self.get_points_defining_boundary()
2328 return points[np.argmax(points @ np.asarray(direction))]
2330 def get_top(self) -> Point3D:
2331 """The middle of the top edge of the mobject's bounding box.
2333 Returns:
2334 The point, in scene coordinates.
2335 """
2336 return self.get_critical_point(UP)
2338 def get_bottom(self) -> Point3D:
2339 """The middle of the bottom edge of the mobject's bounding box.
2341 Returns:
2342 The point, in scene coordinates.
2343 """
2344 return self.get_critical_point(DOWN)
2346 def get_right(self) -> Point3D:
2347 """The middle of the right edge of the mobject's bounding box.
2349 Returns:
2350 The point, in scene coordinates.
2351 """
2352 return self.get_critical_point(RIGHT)
2354 def get_left(self) -> Point3D:
2355 """The middle of the left edge of the mobject's bounding box.
2357 Returns:
2358 The point, in scene coordinates.
2359 """
2360 return self.get_critical_point(LEFT)
2362 @deprecated("use get_critical_point(OUT), or get_critical_point(IN)", category=None)
2363 def get_zenith(self) -> Point3D:
2364 """The middle of the face of the mobject's bounding box farthest out of the
2365 screen (toward OUT: its highest z).
2367 Returns:
2368 The point, in scene coordinates.
2369 """
2370 return self.get_critical_point(OUT)
2372 @deprecated("use get_critical_point(OUT), or get_critical_point(IN)", category=None)
2373 def get_nadir(self) -> Point3D:
2374 """The middle of the face of the mobject's bounding box farthest into the screen
2375 (toward IN: its lowest z).
2377 Returns:
2378 The point, in scene coordinates.
2379 """
2380 return self.get_critical_point(IN)
2382 @deprecated("use get_x, get_y or get_z", category=None)
2383 def get_coord(self, dim: int, direction: Vector3DLike = ORIGIN) -> float:
2384 """One coordinate of a point of the mobject's bounding box: along axis `dim`,
2385 its lowest, middle or highest, as `direction`'s coordinate there is negative, 0
2386 or positive.
2388 Args:
2389 dim: The axis: 0 for x, 1 for y, 2 for z.
2390 direction: A direction such as LEFT, ORIGIN or RIGHT (default ORIGIN: the
2391 middle).
2392 """
2393 return self.get_extremum_along_dim(dim=dim, key=np.asarray(direction)[dim])
2395 def get_x(self, direction: Vector3DLike = ORIGIN) -> float:
2396 """The x coordinate of the mobject's center, or of an edge of its bounding box.
2398 Args:
2399 direction: LEFT for its left edge, RIGHT for its right edge; ORIGIN
2400 (default) for its center.
2401 """
2402 return self.get_coord(0, direction)
2404 def get_y(self, direction: Vector3DLike = ORIGIN) -> float:
2405 """The y coordinate of the mobject's center, or of an edge of its bounding box.
2407 Args:
2408 direction: DOWN for its bottom edge, UP for its top edge; ORIGIN (default)
2409 for its center.
2410 """
2411 return self.get_coord(1, direction)
2413 def get_z(self, direction: Vector3DLike = ORIGIN) -> float:
2414 """The z coordinate of the mobject's center, or of a face of its bounding box.
2416 Args:
2417 direction: IN for its lowest z, OUT for its highest; ORIGIN (default) for
2418 its center.
2419 """
2420 return self.get_coord(2, direction)
2422 def get_midpoint(self) -> Point3D:
2423 """The point halfway along the mobject: for a path, half its length from its
2424 start.
2426 Returns:
2427 The point, in scene coordinates.
2428 """
2429 return self.point_from_proportion(0.5)
2431 def point_from_proportion(self, alpha: float) -> Point3D:
2432 """The point a proportion of the way along the mobject, from its start (0) to
2433 its end (1): for a path, by its length.
2435 Each kind implements it; a mobject of no kind has no way along it, and raises an
2436 exception.
2438 Args:
2439 alpha: The proportion, from 0 to 1.
2441 Returns:
2442 The point, in scene coordinates.
2443 """
2444 raise NotImplementedError(f"{type(self).__name__} has no parametrization")
2446 @property
2447 def width(self) -> float:
2448 """The mobject's width, in scene units: its
2449 [bounding box][manimgx.Mobject.boundary_box]'s extent along x, from the leftmost
2450 of what it draws to the rightmost. Set it to scale the mobject to that width, in
2451 proportion, about its center."""
2452 return self.length_over_dim(0)
2454 @width.setter
2455 def width(self, value: float) -> None:
2456 self.scale_to_fit_width(value)
2458 @property
2459 def height(self) -> float:
2460 """The mobject's height, in scene units: its
2461 [bounding box][manimgx.Mobject.boundary_box]'s extent along y, from the lowest
2462 of what it draws to the highest. Set it to scale the mobject to that height, in
2463 proportion, about its center."""
2464 return self.length_over_dim(1)
2466 @height.setter
2467 def height(self, value: float) -> None:
2468 self.scale_to_fit_height(value)
2470 @deprecated("get_width() is width: use it", category=None)
2471 def get_width(self) -> float:
2472 """The mobject's [width][manimgx.Mobject.width].
2474 Returns:
2475 The width, in scene units.
2476 """
2477 return self.width
2479 @deprecated("get_height() is height: use it", category=None)
2480 def get_height(self) -> float:
2481 """The mobject's [height][manimgx.Mobject.height].
2483 Returns:
2484 The height, in scene units.
2485 """
2486 return self.height
2488 # ── layout ────────────────────────────────────────────────────────────
2489 def center(self) -> Self:
2490 """Move the mobject so the center of its bounding box is at the origin."""
2491 return self.shift(-self.get_center())
2493 def move_to(
2494 self,
2495 point_or_mobject: "Point3DLike | Mobject",
2496 aligned_edge: Vector3DLike = ORIGIN,
2497 coor_mask: Vector3DLike = (1, 1, 1),
2498 ) -> Self:
2499 """Move the mobject to a point, or onto another mobject: its center, or the
2500 point of its bounding box `aligned_edge` names, goes there.
2502 Args:
2503 point_or_mobject: A point, in scene coordinates, or a mobject: then the
2504 point of its bounding box `aligned_edge` names (its center, by default).
2505 aligned_edge: The point of the mobject that goes there, named by a
2506 direction: ORIGIN (default) for its center, DL for its bottom left
2507 corner.
2508 coor_mask: Which coordinates change: 1 for each axis the mobject moves
2509 along, 0 for one it keeps (`(1, 0, 0)` moves it horizontally only).
2511 Examples:
2512 ```python
2513 import manimgx as m
2516 class MobjectMoveToExample(m.Scene):
2517 def construct(self) -> None:
2518 dot = m.Dot([3, 1.5, 0], radius=0.15, color=m.YELLOW)
2519 origin = m.Dot(radius=0.15, color=m.RED)
2520 square = m.Square(color=m.BLUE, fill_opacity=0.5).shift(4 * m.LEFT)
2521 self.add(dot, origin, square)
2522 self.play(square.animate.move_to(dot))
2523 self.play(square.animate.move_to(m.ORIGIN, aligned_edge=m.DL))
2524 ```
2525 """
2526 if isinstance(point_or_mobject, Mobject):
2527 target = point_or_mobject.get_critical_point(aligned_edge)
2528 else:
2529 target = np.asarray(point_or_mobject, dtype=float)
2530 return self.shift(
2531 (target - self.get_critical_point(aligned_edge)) * np.asarray(coor_mask)
2532 )
2534 def next_to(
2535 self,
2536 mobject_or_point: "Mobject | Point3DLike",
2537 direction: Vector3DLike = RIGHT,
2538 buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
2539 aligned_edge: Vector3DLike = ORIGIN,
2540 submobject_to_align: "Mobject | None" = None,
2541 index_of_submobject_to_align: int | None = None,
2542 coor_mask: Vector3DLike = (1, 1, 1),
2543 ) -> Self:
2544 """Put the mobject beside another, or beside a point, `buff` away in a
2545 direction.
2547 The side of the mobject facing back along `direction` goes to the other's side
2548 facing along it, `buff` farther on: with RIGHT, the middle of its left edge goes
2549 `buff` to the right of the middle of the other's right edge. A diagonal
2550 direction (UR) puts corner to corner.
2552 Args:
2553 mobject_or_point: The mobject (its bounding box) or the point to put it
2554 beside.
2555 direction: The side: RIGHT (default), UP, DL, …
2556 buff: The gap, in scene units, along `direction` (default 0.25).
2557 aligned_edge: The edge along which the two line up besides the side they
2558 meet at, named by a direction: with the direction RIGHT and UP here,
2559 their tops line up (default ORIGIN: centered).
2560 submobject_to_align: A part of the mobject to put beside the other in its
2561 place; the rest moves with it.
2562 index_of_submobject_to_align: The index of the part of each mobject to line
2563 up: this one's part goes beside the other's.
2564 coor_mask: Which coordinates change: 1 for each axis the mobject moves
2565 along, 0 for one it keeps.
2567 Examples:
2568 ```python
2569 import manimgx as m
2572 class MobjectNextToExample(m.Scene):
2573 def construct(self) -> None:
2574 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
2575 right = m.Text("RIGHT").next_to(square, m.RIGHT)
2576 up = m.Text("UP, aligned LEFT").next_to(
2577 square, m.UP, aligned_edge=m.LEFT
2578 )
2579 down = m.Text("DOWN, buff=1").next_to(square, m.DOWN, buff=1)
2580 dot = m.Dot(radius=0.2, color=m.YELLOW)
2581 dot.next_to(square, m.UL, buff=0)
2582 self.add(square, right, up, down, dot)
2583 ```
2584 """
2585 d, edge = (
2586 np.asarray(direction, dtype=float),
2587 np.asarray(aligned_edge, dtype=float),
2588 )
2589 if isinstance(mobject_or_point, Mobject):
2590 target_aligner = (
2591 mobject_or_point
2592 if index_of_submobject_to_align is None
2593 else mobject_or_point[index_of_submobject_to_align]
2594 )
2595 target = target_aligner.get_critical_point(edge + d)
2596 else:
2597 target = np.asarray(mobject_or_point, dtype=float)
2598 if submobject_to_align is not None:
2599 aligner: Mobject = submobject_to_align
2600 elif index_of_submobject_to_align is not None:
2601 aligner = self[index_of_submobject_to_align]
2602 else:
2603 aligner = self
2604 point_to_align = aligner.get_critical_point(edge - d)
2605 return self.shift((target - point_to_align + buff * d) * np.asarray(coor_mask))
2607 @deprecated("use to_edge or to_corner", category=None)
2608 def align_on_border(
2609 self, direction: Vector3DLike, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER
2610 ) -> Self:
2611 """Move the mobject to an edge or a corner of the frame, `buff` in from it.
2613 Only the coordinates along which `direction` points change: sent to the top
2614 edge, the mobject moves up or down only. The frame is the configured one,
2615 centered on the origin, wherever the camera looks.
2617 Args:
2618 direction: The edge (UP, LEFT, …) or the corner (UR, DL, …) of the frame.
2619 buff: The margin between the mobject and the frame's edge, in scene units
2620 (default 0.5).
2621 """
2622 d = np.asarray(direction, dtype=float)
2623 target = np.sign(d) * (config.frame_x_radius, config.frame_y_radius, 0)
2624 shift = (target - self.get_critical_point(d) - buff * d) * np.abs(np.sign(d))
2625 return self.shift(shift)
2627 def to_corner(
2628 self, corner: Vector3DLike = DL, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER
2629 ) -> Self:
2630 """Move the mobject into a corner of the frame, `buff` in from both its edges.
2632 The frame is the configured one, centered on the origin, wherever the camera
2633 looks.
2635 Args:
2636 corner: The corner: UL, UR, DL (default) or DR.
2637 buff: The margin between the mobject and each edge of the frame, in scene
2638 units (default 0.5).
2640 Examples:
2641 ```python
2642 import manimgx as m
2645 class MobjectToCornerExample(m.Scene):
2646 def construct(self) -> None:
2647 self.add(m.Text("UL").to_corner(m.UL))
2648 self.add(m.Text("UR, buff=0").to_corner(m.UR, buff=0))
2649 self.add(m.Circle(color=m.BLUE).to_corner(m.DL))
2650 self.add(m.Square(color=m.YELLOW).to_corner(m.DR, buff=1))
2651 ```
2652 """
2653 return self.align_on_border(corner, buff)
2655 def to_edge(
2656 self, edge: Vector3DLike = LEFT, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER
2657 ) -> Self:
2658 """Move the mobject to an edge of the frame, `buff` in from it; along the edge,
2659 it stays where it is.
2661 The frame is the configured one, centered on the origin, wherever the camera
2662 looks.
2664 Args:
2665 edge: The edge: UP, DOWN, LEFT (default) or RIGHT.
2666 buff: The margin between the mobject and the edge, in scene units (default
2667 0.5).
2669 Examples:
2670 ```python
2671 import manimgx as m
2674 class MobjectToEdgeExample(m.Scene):
2675 def construct(self) -> None:
2676 top = m.Text("to_edge(UP)").to_edge(m.UP)
2677 left = m.Text("to_edge(LEFT)").to_edge(m.LEFT)
2678 circle = m.Circle(color=m.BLUE).shift(2 * m.DOWN)
2679 circle.to_edge(m.RIGHT, buff=0)
2680 self.add(top, left, circle)
2681 ```
2682 """
2683 return self.align_on_border(edge, buff)
2685 def is_off_screen(self) -> bool:
2686 """Whether the mobject is wholly outside the frame: the configured one, centered
2687 on the origin.
2689 Returns:
2690 True if its bounding box lies wholly past an edge of the frame.
2691 """
2692 x, y = config.frame_x_radius, config.frame_y_radius
2693 return bool(
2694 self.get_left()[0] > x
2695 or self.get_right()[0] < -x
2696 or self.get_bottom()[1] > y
2697 or self.get_top()[1] < -y
2698 )
2700 def shift_onto_screen(self, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER) -> Self:
2701 """Move the mobject back into the frame where it reaches past an edge, or nearer
2702 to it than `buff`: to that edge, `buff` in (see
2703 [to_edge][manimgx.Mobject.to_edge]).
2705 Args:
2706 buff: The margin to keep from the frame's edges, in scene units (default
2707 0.5).
2708 """
2709 radii = (config.frame_x_radius, config.frame_y_radius)
2710 for vect in (UP, DOWN, LEFT, RIGHT):
2711 dim = int(np.argmax(np.abs(vect)))
2712 if np.dot(self.get_critical_point(vect), vect) > radii[dim] - buff:
2713 self.to_edge(vect, buff=buff)
2714 return self
2716 background_rectangle: "Mobject | None" = None
2717 """The rectangle last put behind the mobject (see
2718 [add_background_rectangle][manimgx.Mobject.add_background_rectangle]); None if
2719 none."""
2721 def add_background_rectangle(
2722 self,
2723 color: ParsableManimColor | None = None,
2724 opacity: float = 0.75,
2725 **kwargs: Unpack[BackgroundOptions],
2726 ) -> Self:
2727 """Put a rectangle behind the mobject, to set it off from whatever is behind it:
2728 a [BackgroundRectangle][manimgx.BackgroundRectangle] around it, added as its
2729 first submobject.
2731 The rectangle moves with the mobject; it is the mobject's
2732 [background_rectangle][manimgx.Mobject.background_rectangle].
2734 Args:
2735 color: The rectangle's color; None for the scene's background color.
2736 opacity: The rectangle's opacity, from 0 to 1 (default 0.75).
2737 **kwargs: [Background keywords][manimgx.mobject.BackgroundOptions]: its
2738 margin, corners and outline.
2740 Examples:
2741 ```python
2742 import manimgx as m
2745 class MobjectAddBackgroundRectangleExample(m.Scene):
2746 def construct(self) -> None:
2747 label = m.Text("set off from the grid", font_size=64)
2748 label.add_background_rectangle(color=m.BLACK, opacity=0.9, buff=0.2)
2749 self.add(m.NumberPlane(), label)
2750 ```
2751 """
2752 from manimgx.mobjects.annotations import BackgroundRectangle
2754 self.background_rectangle = BackgroundRectangle(
2755 self, color=color, fill_opacity=opacity, **kwargs
2756 )
2757 return self.add_to_back(self.background_rectangle)
2759 def align_to(
2760 self,
2761 mobject_or_point: "Mobject | Point3DLike",
2762 direction: Vector3DLike = ORIGIN,
2763 ) -> Self:
2764 """Move the mobject so a side of it lines up with another's: along each axis on
2765 which `direction` is not 0, the side of its bounding box in that direction goes
2766 where the other's is.
2768 `align_to(other, UP)` puts its top at the height of the other's top, moving it
2769 up or down only; `align_to(other, UL)` lines up both tops and both left sides.
2770 With the default ORIGIN, nothing moves.
2772 Args:
2773 mobject_or_point: The mobject to line up with (the side of its bounding box
2774 `direction` names), or a point.
2775 direction: The side, named by a direction: UP, DL, …
2777 Examples:
2778 ```python
2779 import manimgx as m
2782 class MobjectAlignToExample(m.Scene):
2783 def construct(self) -> None:
2784 floor = m.Line(6 * m.LEFT, 6 * m.RIGHT).shift(3 * m.DOWN)
2785 shapes = m.VGroup(
2786 m.Circle(color=m.BLUE),
2787 m.Square(side_length=3, color=m.GREEN),
2788 m.Triangle(color=m.YELLOW),
2789 m.Star(color=m.RED),
2790 ).arrange(buff=1)
2791 self.add(floor, shapes)
2792 self.play(*(s.animate.align_to(floor, m.DOWN) for s in shapes))
2793 ```
2794 """
2795 point = (
2796 mobject_or_point.get_critical_point(direction)
2797 if isinstance(mobject_or_point, Mobject)
2798 else np.asarray(mobject_or_point)
2799 )
2800 for dim in range(self.dim):
2801 if direction[dim] != 0:
2802 self.set_coord(point[dim], dim, direction)
2803 return self
2805 @deprecated("use set_x, set_y or set_z", category=None)
2806 def set_coord(
2807 self, value: float, dim: int, direction: Vector3DLike = ORIGIN
2808 ) -> Self:
2809 """Move the mobject along one axis so a coordinate of its bounding box is
2810 `value`: its lowest, middle or highest, as `direction`'s coordinate there is
2811 negative, 0 or positive.
2813 Args:
2814 value: The coordinate, in scene units.
2815 dim: The axis: 0 for x, 1 for y, 2 for z.
2816 direction: A direction such as LEFT, ORIGIN or RIGHT (default ORIGIN: the
2817 center).
2818 """
2819 shift = np.zeros(self.dim)
2820 shift[dim] = value - self.get_coord(dim, direction)
2821 return self.shift(shift)
2823 def set_x(self, x: float, direction: Vector3DLike = ORIGIN) -> Self:
2824 """Move the mobject left or right so its center, or an edge of its bounding box,
2825 is at `x`.
2827 Args:
2828 x: The x coordinate, in scene units.
2829 direction: LEFT to place its left edge, RIGHT its right edge; ORIGIN
2830 (default) its center.
2831 """
2832 return self.set_coord(x, 0, direction)
2834 def set_y(self, y: float, direction: Vector3DLike = ORIGIN) -> Self:
2835 """Move the mobject up or down so its center, or an edge of its bounding box, is
2836 at `y`.
2838 Args:
2839 y: The y coordinate, in scene units.
2840 direction: DOWN to place its bottom edge, UP its top edge; ORIGIN (default)
2841 its center.
2842 """
2843 return self.set_coord(y, 1, direction)
2845 def set_z(self, z: float, direction: Vector3DLike = ORIGIN) -> Self:
2846 """Move the mobject in or out so its center, or a face of its bounding box, is
2847 at `z`.
2849 Args:
2850 z: The z coordinate, in scene units.
2851 direction: IN to place its lowest z, OUT its highest; ORIGIN (default) its
2852 center.
2853 """
2854 return self.set_coord(z, 2, direction)
2856 @deprecated("use scale_to_fit_width or scale_to_fit_height", category=None)
2857 def rescale_to_fit(
2858 self, length: float, dim: int, stretch: bool = False, **kwargs: Unpack[Pivot]
2859 ) -> Self:
2860 """Scale the mobject so its extent along one axis is `length`: in proportion, or
2861 along that axis only.
2863 A mobject with no extent along the axis stays as it is.
2865 Args:
2866 length: The extent, in scene units.
2867 dim: The axis: 0 for x (its width), 1 for y (its height), 2 for z (its
2868 depth).
2869 stretch: Whether to stretch it along that axis only, instead of scaling it
2870 in proportion.
2871 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2872 fixed (default: its center).
2873 """
2874 old = self.length_over_dim(dim)
2875 if old == 0:
2876 return self
2877 return (
2878 self.stretch(length / old, dim, **kwargs)
2879 if stretch
2880 else self.scale(length / old, **kwargs)
2881 )
2883 def scale_to_fit_width(self, width: float, **kwargs: Unpack[Pivot]) -> Self:
2884 """Scale the mobject in proportion to a width.
2886 Args:
2887 width: The width, in scene units.
2888 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2889 fixed (default: its center).
2890 """
2891 return self.rescale_to_fit(width, 0, stretch=False, **kwargs)
2893 def stretch_to_fit_width(self, width: float, **kwargs: Unpack[Pivot]) -> Self:
2894 """Stretch the mobject horizontally to a width; its height stays.
2896 Args:
2897 width: The width, in scene units.
2898 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2899 fixed (default: its center).
2900 """
2901 return self.rescale_to_fit(width, 0, stretch=True, **kwargs)
2903 def scale_to_fit_height(self, height: float, **kwargs: Unpack[Pivot]) -> Self:
2904 """Scale the mobject in proportion to a height.
2906 Args:
2907 height: The height, in scene units.
2908 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2909 fixed (default: its center).
2910 """
2911 return self.rescale_to_fit(height, 1, stretch=False, **kwargs)
2913 def stretch_to_fit_height(self, height: float, **kwargs: Unpack[Pivot]) -> Self:
2914 """Stretch the mobject vertically to a height; its width stays.
2916 Args:
2917 height: The height, in scene units.
2918 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2919 fixed (default: its center).
2920 """
2921 return self.rescale_to_fit(height, 1, stretch=True, **kwargs)
2923 @deprecated("use match_width or match_height", category=None)
2924 def match_dim_size(
2925 self, mobject: "Mobject", dim: int, **kwargs: Unpack[Pivot]
2926 ) -> Self:
2927 """Scale the mobject in proportion so its extent along one axis is another's.
2929 Args:
2930 mobject: The mobject to match.
2931 dim: The axis: 0 for x (width), 1 for y (height), 2 for z (depth).
2932 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2933 fixed (default: its center).
2934 """
2935 return self.rescale_to_fit(mobject.length_over_dim(dim), dim, **kwargs)
2937 def match_width(self, mobject: "Mobject", **kwargs: Unpack[Pivot]) -> Self:
2938 """Scale the mobject in proportion to another's width.
2940 Args:
2941 mobject: The mobject to match.
2942 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2943 fixed (default: its center).
2944 """
2945 return self.match_dim_size(mobject, 0, **kwargs)
2947 def match_height(self, mobject: "Mobject", **kwargs: Unpack[Pivot]) -> Self:
2948 """Scale the mobject in proportion to another's height.
2950 Args:
2951 mobject: The mobject to match.
2952 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2953 fixed (default: its center).
2954 """
2955 return self.match_dim_size(mobject, 1, **kwargs)
2957 @deprecated("use scale", category=None)
2958 def match_depth(self, mobject: "Mobject", **kwargs: Unpack[Pivot]) -> Self:
2959 """Scale the mobject in proportion to another's depth, its extent along z.
2961 Args:
2962 mobject: The mobject to match.
2963 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
2964 fixed (default: its center).
2965 """
2966 return self.match_dim_size(mobject, 2, **kwargs)
2968 @deprecated("use match_x, match_y or match_z", category=None)
2969 def match_coord(
2970 self, mobject: "Mobject", dim: int, direction: Vector3DLike = ORIGIN
2971 ) -> Self:
2972 """Move the mobject along one axis to another's coordinate there: the same point
2973 of each one's bounding box, as `direction` names it, gets the same coordinate.
2975 Args:
2976 mobject: The mobject to match.
2977 dim: The axis: 0 for x, 1 for y, 2 for z.
2978 direction: Which point along the axis: the lowest, the middle (ORIGIN,
2979 default) or the highest, as its coordinate there is negative, 0 or
2980 positive.
2981 """
2982 return self.set_coord(mobject.get_coord(dim, direction), dim, direction)
2984 def match_x(self, mobject: "Mobject", direction: Vector3DLike = ORIGIN) -> Self:
2985 """Move the mobject left or right to another's x: centers, or left or right
2986 edges, lined up.
2988 Args:
2989 mobject: The mobject to match.
2990 direction: LEFT to line up the left edges, RIGHT the right ones; ORIGIN
2991 (default) the centers.
2992 """
2993 return self.match_coord(mobject, 0, direction)
2995 def match_y(self, mobject: "Mobject", direction: Vector3DLike = ORIGIN) -> Self:
2996 """Move the mobject up or down to another's y: centers, or top or bottom edges,
2997 lined up.
2999 Args:
3000 mobject: The mobject to match.
3001 direction: DOWN to line up the bottom edges, UP the top ones; ORIGIN
3002 (default) the centers.
3003 """
3004 return self.match_coord(mobject, 1, direction)
3006 def match_z(self, mobject: "Mobject", direction: Vector3DLike = ORIGIN) -> Self:
3007 """Move the mobject in or out to another's z: centers, or faces, lined up.
3009 Args:
3010 mobject: The mobject to match.
3011 direction: IN to line up the lowest z, OUT the highest; ORIGIN (default) the
3012 centers.
3013 """
3014 return self.match_coord(mobject, 2, direction)
3016 def replace(
3017 self, mobject: "Mobject", dim_to_match: int = 0, stretch: bool = False
3018 ) -> Self:
3019 """Put the mobject in another's place: scaled to its extent along one axis (or
3020 stretched to its width and height), and centered on it.
3022 The other mobject stays where it is.
3024 Args:
3025 mobject: The mobject whose place it takes.
3026 dim_to_match: The axis whose extent it takes, in proportion: 0 for x (the
3027 width), 1 for y (the height), 2 for z.
3028 stretch: Whether to stretch it to the other's width and height instead.
3029 """
3030 if stretch:
3031 self.stretch_to_fit_width(mobject.width)
3032 self.stretch_to_fit_height(mobject.height)
3033 else:
3034 self.rescale_to_fit(mobject.length_over_dim(dim_to_match), dim_to_match)
3035 return self.shift(mobject.get_center() - self.get_center())
3037 def put_start_and_end_on(self, start: Point3DLike, end: Point3DLike) -> Self:
3038 """Move, turn and scale the mobject so its first point is at `start` and its
3039 last at `end`; its shape stays, scaled in proportion.
3041 A mobject whose first and last points coincide is only moved.
3043 Args:
3044 start: Where its first point goes.
3045 end: Where its last point goes.
3046 """
3047 cur_start, cur_end = self.get_start_and_end()
3048 cur_vec = cur_end - cur_start
3049 if np.all(cur_vec == 0):
3050 return self.shift(np.asarray(start) - cur_start)
3051 target_vec = np.asarray(end) - np.asarray(start)
3052 angle, axis = turn_between(cur_vec, target_vec)
3053 self.scale(
3054 np.linalg.norm(target_vec) / np.linalg.norm(cur_vec), about_point=cur_start
3055 )
3056 self.rotate(angle, about_point=cur_start, axis=axis)
3057 return self.shift(np.asarray(start) - cur_start)
3059 def arrange(
3060 self,
3061 direction: Vector3DLike = RIGHT,
3062 buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
3063 center: bool = True,
3064 **kwargs: Unpack[Beside],
3065 ) -> Self:
3066 """Lay the submobjects out in a row: each one beside the one before it (see
3067 [next_to][manimgx.Mobject.next_to]), `buff` apart; then center the whole at the
3068 origin.
3070 Args:
3071 direction: The way the row goes: RIGHT (default), DOWN for a column, …
3072 buff: The gap between neighbours, in scene units (default 0.25).
3073 center: Whether to center the mobject at the origin afterwards; if not, the
3074 first submobject stays where it was.
3075 **kwargs: [Beside keywords][manimgx.mobject.Beside]: how neighbours
3076 line up (`aligned_edge=DOWN` puts their bottoms on one line).
3078 Examples:
3079 ```python
3080 import manimgx as m
3083 class MobjectArrangeExample(m.Scene):
3084 def construct(self) -> None:
3085 sizes = (0.5, 1, 2)
3086 squares = m.VGroup(*(m.Square(s, color=m.BLUE) for s in sizes))
3087 squares.arrange(buff=0.5, aligned_edge=m.DOWN)
3088 words = m.VGroup(m.Text("one"), m.Text("three"), m.Text("eleven"))
3089 words.arrange(m.DOWN, aligned_edge=m.LEFT)
3090 self.add(m.VGroup(squares, words).arrange(buff=1.5))
3091 ```
3092 """
3093 for m1, m2 in zip(self.submobjects[:-1], self.submobjects[1:], strict=True):
3094 m2.next_to(m1, direction, buff, **kwargs)
3095 return self.center() if center else self
3097 @deprecated("arrange_submobjects is arrange: use it", category=None)
3098 def arrange_submobjects(
3099 self,
3100 direction: Vector3DLike = RIGHT,
3101 buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
3102 center: bool = True,
3103 **kwargs: Unpack[Beside],
3104 ) -> Self:
3105 """[arrange][manimgx.Mobject.arrange], by another name."""
3106 return self.arrange(direction, buff, center, **kwargs)
3108 def arrange_in_grid(
3109 self,
3110 rows: int | None = None,
3111 cols: int | None = None,
3112 buff: float | tuple[float, float] = MED_SMALL_BUFF,
3113 cell_alignment: Vector3DLike = ORIGIN,
3114 row_alignments: str | None = None,
3115 col_alignments: str | None = None,
3116 row_heights: Iterable[float | None] | None = None,
3117 col_widths: Iterable[float | None] | None = None,
3118 flow_order: str = "rd",
3119 ) -> Self:
3120 """Lay the submobjects out in a grid of rows and columns, centered where the
3121 mobject was.
3123 Each row is as tall as its tallest mobject and each column as wide as its
3124 widest, unless given. Each mobject sits in its cell as `cell_alignment` says,
3125 but vertically as `row_alignments` says for its row and horizontally as
3126 `col_alignments` says for its column, where they are given. Too few rows and
3127 columns for the submobjects raise an exception.
3129 Args:
3130 rows: How many rows; None for as many as `row_alignments` or `row_heights`
3131 lists, else as many as the submobjects need. With neither `rows` nor
3132 `cols`, the grid is as square as it can be.
3133 cols: How many columns; None for as many as `col_alignments` or `col_widths`
3134 lists, else as many as the submobjects need.
3135 buff: The gap between cells, in scene units: one for both directions, or
3136 (horizontal, vertical) (default 0.25).
3137 cell_alignment: Where each mobject sits in its cell, named by a direction:
3138 UL for its top left corner (default ORIGIN: centered).
3139 row_alignments: Each row's vertical alignment, top to bottom: a letter per
3140 row, "u" (up), "c" (center) or "d" (down); None: as the vertical part of
3141 `cell_alignment` says (UL: up).
3142 col_alignments: Each column's horizontal alignment, left to right: a letter
3143 per column, "l" (left), "c" (center) or "r" (right); None: as the
3144 horizontal part of `cell_alignment` says (UL: left).
3145 row_heights: Each row's height, top to bottom, in scene units; None (for the
3146 grid or a row) for the height of the row's tallest mobject.
3147 col_widths: Each column's width, left to right, in scene units; None (for
3148 the grid or a column) for the width of the column's widest mobject.
3149 flow_order: The order the cells are filled in: two letters, the direction a
3150 line of cells fills and then the direction the lines follow each other,
3151 "r" (right), "l" (left), "u" (up) or "d" (down). The default "rd" fills
3152 rows left to right, from the top down; "dr" fills columns top to bottom,
3153 from the left.
3155 Examples:
3156 ```python
3157 import manimgx as m
3160 def cells() -> m.VGroup:
3161 return m.VGroup(
3162 *(
3163 m.Square(0.9, color=m.BLUE).add(m.Text(str(i), font_size=36))
3164 for i in range(1, 11)
3165 )
3166 )
3169 class MobjectArrangeInGridExample(m.Scene):
3170 def construct(self) -> None:
3171 by_rows = cells().arrange_in_grid(rows=3, buff=0.2)
3172 by_cols = cells().arrange_in_grid(rows=3, buff=0.2, flow_order="dr")
3173 self.add(m.VGroup(by_rows, by_cols).arrange(buff=1.5))
3174 ```
3175 """
3176 mobs = list(self.submobjects)
3177 start_pos = self.get_center()
3178 heights_in = list(row_heights) if row_heights is not None else None
3179 widths_in = list(col_widths) if col_widths is not None else None
3180 cols = cols or (
3181 len(col_alignments)
3182 if col_alignments
3183 else len(widths_in)
3184 if widths_in
3185 else None
3186 )
3187 rows = rows or (
3188 len(row_alignments)
3189 if row_alignments
3190 else len(heights_in)
3191 if heights_in
3192 else None
3193 )
3194 if rows is None:
3195 cols = math.ceil(math.sqrt(len(mobs))) if cols is None else cols
3196 rows = math.ceil(len(mobs) / cols)
3197 elif cols is None:
3198 cols = math.ceil(len(mobs) / rows)
3199 if rows * cols < len(mobs):
3200 raise ValueError("Too few rows and columns to fit all submobjetcs.")
3201 bx, by = buff if isinstance(buff, tuple) else (buff, buff)
3202 cell = np.asarray(cell_alignment, dtype=float)
3203 rdirs = ( # a row aligns its cells vertically, a column horizontally
3204 [cell * UP] * rows
3205 if row_alignments is None
3206 else [{"u": UP, "c": ORIGIN, "d": DOWN}[c] for c in row_alignments]
3207 )
3208 cdirs = (
3209 [cell * RIGHT] * cols
3210 if col_alignments is None
3211 else [{"l": LEFT, "c": ORIGIN, "r": RIGHT}[c] for c in col_alignments]
3212 )
3213 index = {
3214 "dr": lambda r, c: rows - r - 1 + c * rows,
3215 "dl": lambda r, c: rows - r - 1 + (cols - c - 1) * rows,
3216 "ur": lambda r, c: r + c * rows,
3217 "ul": lambda r, c: r + (cols - c - 1) * rows,
3218 "rd": lambda r, c: (rows - r - 1) * cols + c,
3219 "ld": lambda r, c: (rows - r - 1) * cols + (cols - c - 1),
3220 "ru": lambda r, c: r * cols + c,
3221 "lu": lambda r, c: r * cols + (cols - c - 1),
3222 }[flow_order]
3223 rdirs.reverse()
3224 heights_given = list(reversed(heights_in)) if heights_in else [None] * rows
3225 placeholder = Mobject()
3226 mobs.extend([placeholder] * (rows * cols - len(mobs)))
3227 grid = [[mobs[index(r, c)] for c in range(cols)] for r in range(rows)]
3228 heights = [
3229 h if h is not None else max(grid[r][c].height for c in range(cols))
3230 for r, h in enumerate(heights_given)
3231 ]
3232 widths = [
3233 w if w is not None else max(grid[r][c].width for r in range(rows))
3234 for c, w in enumerate(widths_in or [None] * cols)
3235 ]
3236 y = 0.0
3237 for r in range(rows):
3238 x = 0.0
3239 for c in range(cols):
3240 if grid[r][c] is not placeholder:
3241 lo, hi = (
3242 np.array([x, y, 0.0]),
3243 np.array([x + widths[c], y + heights[r], 0.0]),
3244 )
3245 align = rdirs[r] + cdirs[c]
3246 corner = np.where(
3247 align < 0, lo, np.where(align > 0, hi, (lo + hi) / 2)
3248 )
3249 grid[r][c].move_to(corner, align)
3250 x += widths[c] + bx
3251 y += heights[r] + by
3252 return self.move_to(start_pos)
3254 def sort(
3255 self,
3256 point_to_num_func: Callable[[Point3D], float] = lambda p: p[0],
3257 submob_func: Callable[["Mobject"], float] | None = None,
3258 ) -> Self:
3259 """Sort the submobjects by a number: one computed from each one's center (by
3260 default its x coordinate, so left to right), or from each one itself.
3262 Their order is the order they are drawn in (at an equal z-index), and the order
3263 a `lag_ratio` staggers their animation in.
3265 Args:
3266 point_to_num_func: A function of a submobject's center, giving the number to
3267 sort it by.
3268 submob_func: A function of a submobject, giving the number to sort it by, in
3269 place of `point_to_num_func`.
3270 """
3271 key = submob_func or (lambda m: point_to_num_func(m.get_center()))
3272 self.submobjects.sort(key=key)
3273 return self
3275 def shuffle(self, recursive: bool = False) -> Self:
3276 """Put the submobjects in a random order, drawn from Python's `random`.
3278 Args:
3279 recursive: Whether each submobject's submobjects are shuffled too, and
3280 theirs.
3281 """
3282 if recursive:
3283 for sub in self.submobjects:
3284 sub.shuffle(recursive=True)
3285 random.shuffle(self.submobjects)
3286 return self
3288 def invert(self, recursive: bool = False) -> Self:
3289 """Reverse the order of the submobjects.
3291 Args:
3292 recursive: Whether each submobject's submobjects are reversed too, and
3293 theirs.
3294 """
3295 if recursive:
3296 for sub in self.submobjects:
3297 sub.invert(recursive=True)
3298 self.submobjects.reverse()
3299 return self
3301 @deprecated("use arrange, with buff", category=None)
3302 def space_out_submobjects(
3303 self, factor: float = 1.5, **kwargs: Unpack[Pivot]
3304 ) -> Self:
3305 """Spread the submobjects apart, each keeping its size: the mobject is scaled by
3306 `factor`, then each submobject back by 1 / `factor`, about its own center.
3308 Args:
3309 factor: How much farther apart their centers go (1.5: half as far again).
3310 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point they
3311 spread out from (default: the mobject's center).
3312 """
3313 self.scale(factor, **kwargs)
3314 for sub in self.submobjects:
3315 sub.scale(1.0 / factor)
3316 return self
3318 def set_z_index(self, z_index_value: float, family: bool = True) -> Self:
3319 """Set the mobject's place in the drawing order: a higher z-index is drawn over
3320 a lower one, anywhere in the scene.
3322 Mobjects of an equal z-index are drawn in the scene's order: the ones added
3323 later over the ones added earlier, and a mobject's submobjects each over those
3324 before it. Every mobject's z-index is 0 unless set.
3326 Args:
3327 z_index_value: The z-index.
3328 family: Whether its whole family gets it, or the mobject alone (which orders
3329 only its own points).
3331 Examples:
3332 ```python
3333 import manimgx as m
3336 class MobjectSetZIndexExample(m.Scene):
3337 def construct(self) -> None:
3338 red = m.Square(3, color=m.RED, fill_opacity=1).shift(m.LEFT + m.UP)
3339 blue = m.Square(3, color=m.BLUE, fill_opacity=1)
3340 green = m.Square(3, color=m.GREEN, fill_opacity=1)
3341 green.shift(m.RIGHT + m.DOWN)
3342 red.set_z_index(1) # added first, drawn on top
3343 self.add(red, blue, green)
3344 ```
3345 """
3346 if family:
3347 for sub in self.submobjects:
3348 sub.set_z_index(z_index_value, family)
3349 self.z_index = z_index_value
3350 return self
3352 # ── style: written once for every kind, through Paint ──────────────────
3353 def _each(self, family: bool) -> list["Mobject"]:
3354 return self.get_family() if family else [self]
3356 def set_fill(
3357 self,
3358 color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
3359 opacity: float | Iterable[float] | None = None,
3360 family: bool = True,
3361 ) -> Self:
3362 """Set the mobject's fill: its color, its opacity, or both.
3364 Args:
3365 color: The color; several make a gradient across the mobject, from the first
3366 to the last toward its sheen direction (UL unless set). None keeps the
3367 present one.
3368 opacity: The opacity, from 0 (no fill) to 1 (opaque); several make a
3369 gradient of opacities. None keeps the present one.
3370 family: Whether its whole family is filled, or the mobject alone.
3372 Examples:
3373 ```python
3374 import manimgx as m
3377 class MobjectSetFillExample(m.Scene):
3378 def construct(self) -> None:
3379 a, b, c = (m.Square(side_length=2.5) for _ in range(3))
3380 m.VGroup(a, b, c).arrange(buff=1)
3381 a.set_fill(m.BLUE, opacity=1)
3382 b.set_fill(m.GREEN, opacity=0.4)
3383 c.set_fill([m.YELLOW, m.RED], opacity=1)
3384 self.add(a, b, c)
3385 ```
3386 """
3387 for mob in reversed(self._each(family)):
3388 mob.paint = mob.paint.updated("fill", color, opacity)
3389 return self
3391 def set_stroke(
3392 self,
3393 color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
3394 width: float | None = None,
3395 opacity: float | Iterable[float] | None = None,
3396 background: bool = False,
3397 family: bool = True,
3398 ) -> Self:
3399 """Set the mobject's stroke, its outline: its color, width and opacity, any of
3400 them.
3402 Args:
3403 color: The color; several make a gradient, from the first to the last toward
3404 the mobject's sheen direction (UL unless set). None keeps the present
3405 one.
3406 width: The width, in hundredths of a scene unit (4 unless styled; 0: no
3407 stroke); None keeps the present one.
3408 opacity: The opacity, from 0 to 1; several make a gradient of opacities.
3409 None keeps the present one.
3410 background: Whether to set the background stroke instead: an outline drawn
3411 behind the fill.
3412 family: Whether its whole family is stroked, or the mobject alone.
3414 Examples:
3415 ```python
3416 import manimgx as m
3419 class MobjectSetStrokeExample(m.Scene):
3420 def construct(self) -> None:
3421 a = m.Circle(radius=1.5, color=m.BLUE, fill_opacity=0.3)
3422 b, c = a.copy(), a.copy()
3423 m.VGroup(a, b, c).arrange(buff=1)
3424 a.set_stroke(m.YELLOW, width=2)
3425 b.set_stroke(m.YELLOW, width=16)
3426 c.set_stroke(m.YELLOW, width=16, opacity=0.3)
3427 self.add(a, b, c)
3428 ```
3429 """
3430 channel = "background" if background else "stroke"
3431 for mob in reversed(self._each(family)):
3432 paint = mob.paint.updated(channel, color, opacity)
3433 if width is not None:
3434 paint = (
3435 paint.but(background_width=width)
3436 if background
3437 else paint.but(stroke_width=width)
3438 )
3439 mob.paint = paint
3440 return self
3442 def set_style(
3443 self,
3444 fill_color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
3445 fill_opacity: float | Iterable[float] | None = None,
3446 stroke_color: ParsableManimColor | Iterable[ParsableManimColor] | None = None,
3447 stroke_width: float | None = None,
3448 stroke_opacity: float | Iterable[float] | None = None,
3449 background_stroke_color: (
3450 ParsableManimColor | Iterable[ParsableManimColor] | None
3451 ) = None,
3452 background_stroke_width: float | None = None,
3453 background_stroke_opacity: float | Iterable[float] | None = None,
3454 sheen_factor: float | None = None,
3455 sheen_direction: Vector3DLike | None = None,
3456 family: bool = True,
3457 ) -> Self:
3458 """Set any of the mobject's style at once: what is None stays as it is.
3460 See [set_fill][manimgx.Mobject.set_fill],
3461 [set_stroke][manimgx.Mobject.set_stroke] and
3462 [set_sheen][manimgx.Mobject.set_sheen]; the sheen changes only with a nonzero
3463 `sheen_factor`.
3465 Args:
3466 fill_color: The fill's color; several make a gradient.
3467 fill_opacity: The fill's opacity, from 0 to 1.
3468 stroke_color: The stroke's color; several make a gradient.
3469 stroke_width: The stroke's width, in hundredths of a scene unit.
3470 stroke_opacity: The stroke's opacity, from 0 to 1.
3471 background_stroke_color: The color of the outline drawn behind the fill.
3472 background_stroke_width: That outline's width, in hundredths of a scene
3473 unit.
3474 background_stroke_opacity: That outline's opacity, from 0 to 1.
3475 sheen_factor: How much the colors lighten toward `sheen_direction`, from -1
3476 to 1; None or 0 leaves the sheen as it is.
3477 sheen_direction: The direction they lighten toward, set with `sheen_factor`.
3478 family: Whether its whole family is styled, or the mobject alone.
3479 """
3480 self.set_fill(fill_color, fill_opacity, family)
3481 self.set_stroke(stroke_color, stroke_width, stroke_opacity, family=family)
3482 self.set_stroke(
3483 background_stroke_color,
3484 background_stroke_width,
3485 background_stroke_opacity,
3486 background=True,
3487 family=family,
3488 )
3489 if sheen_factor:
3490 self.set_sheen(sheen_factor, sheen_direction, family)
3491 return self
3493 def set_material(self, material: Material | None, family: bool = True) -> Self:
3494 """Give the mobject a surface the scene's lights reflect from, in a three-dimensional
3495 scene: its fill color is the surface's base color.
3497 Args:
3498 material: How the surface reflects light (see [Material][manimgx.Material]); None
3499 for Manim's shading.
3500 family: Whether its whole family takes the material, or the mobject alone.
3502 Returns:
3503 This mobject, for chaining.
3505 Examples:
3506 ```python
3507 import manimgx as m
3510 class MobjectSetMaterialExample(m.ThreeDScene):
3511 def construct(self) -> None:
3512 self.set_camera_orientation(
3513 phi=65 * m.DEGREES, theta=-50 * m.DEGREES
3514 )
3515 self.add(
3516 m.SunLight(4 * m.LEFT + 6 * m.OUT),
3517 m.AmbientLight(intensity=0.15),
3518 )
3519 torus = m.Torus(resolution=(48, 24)).set_color(m.TEAL)
3520 self.add(torus.set_material(m.Material(roughness=0.25)))
3521 self.play(
3522 torus.animate.set_material(
3523 m.Material(metallic=1, roughness=0.6)
3524 )
3525 )
3526 ```
3527 """
3528 for mob in self.get_family() if family else [self]:
3529 mob.paint = mob.paint.but(material=material)
3530 return self
3532 def set_color(
3533 self,
3534 color: ParsableManimColor | Iterable[ParsableManimColor],
3535 family: bool = True,
3536 ) -> Self:
3537 """Color the mobject: its fill and its stroke, which keep their opacities (an
3538 unfilled shape stays unfilled).
3540 Args:
3541 color: The color; several make a gradient across the mobject, from the first
3542 to the last toward its sheen direction (UL unless set).
3543 family: Whether its whole family is colored, or the mobject alone.
3545 Examples:
3546 ```python
3547 import manimgx as m
3550 class MobjectSetColorExample(m.Scene):
3551 def construct(self) -> None:
3552 circle = m.Circle(radius=1.5)
3553 square = m.Square(side_length=3, fill_opacity=0.5)
3554 shapes = m.VGroup(circle, square).arrange(buff=2)
3555 self.add(shapes)
3556 self.play(shapes.animate.set_color(m.YELLOW))
3557 self.play(square.animate.set_color([m.BLUE, m.GREEN]))
3558 ```
3559 """
3560 self.set_fill(color, family=family)
3561 return self.set_stroke(color, family=family)
3563 def set_opacity(self, opacity: float, family: bool = True) -> Self:
3564 """Set the opacity of the mobject's fill, stroke and background stroke alike —
3565 so an unfilled shape gets a fill of that opacity.
3567 Args:
3568 opacity: The opacity, from 0 (invisible) to 1 (opaque).
3569 family: Whether its whole family gets it, or the mobject alone.
3571 Examples:
3572 ```python
3573 import manimgx as m
3576 class MobjectSetOpacityExample(m.Scene):
3577 def construct(self) -> None:
3578 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=1)
3579 circle = m.Circle(radius=1.5, color=m.YELLOW, fill_opacity=1)
3580 square.shift(m.LEFT)
3581 circle.shift(m.RIGHT)
3582 self.add(square, circle)
3583 self.play(circle.animate.set_opacity(0.3))
3584 ```
3585 """
3586 self.set_fill(opacity=opacity, family=family)
3587 self.set_stroke(opacity=opacity, family=family)
3588 return self.set_stroke(opacity=opacity, background=True, family=family)
3590 def fade(self, darkness: float = 0.5, family: bool = True) -> Self:
3591 """Make the mobject fainter: its fill's, stroke's and background stroke's
3592 opacities each times 1 − `darkness`.
3594 Args:
3595 darkness: How much fainter, from 0 (as it is) to 1 (invisible).
3596 family: Whether its whole family fades, or the mobject alone.
3597 """
3598 factor = 1.0 - darkness
3599 if factor == 1.0:
3600 return self
3601 for mob in self._each(family):
3602 p, faded = mob.paint, {}
3603 for name in ("fill", "stroke", "background"): # every row: stops, points
3604 rows = getattr(p, name)
3605 if len(rows):
3606 faded[name] = rows * [1.0, 1.0, 1.0, factor]
3607 mob.paint = p.but(**faded)
3608 return self
3610 def set_sheen(
3611 self, factor: float, direction: Vector3DLike | None = None, family: bool = True
3612 ) -> Self:
3613 """Give the mobject a sheen: its colors lighten across it, toward a direction.
3615 With a nonzero factor, its fill and its stroke each become a gradient from their
3616 color to that color lightened by the factor.
3618 Args:
3619 factor: How much the colors lighten, from -1 to 1: 0 for no sheen, a
3620 negative factor darkens.
3621 direction: The direction they lighten toward, copied as a value; None
3622 keeps the present one (UL unless styled). The caller's array is
3623 unchanged.
3624 family: Whether its whole family gets it, or the mobject alone.
3625 """
3626 if direction is not None:
3627 direction = frozen(np.array(direction, dtype=float, copy=True))
3628 for mob in self._each(family):
3629 mob.paint = (
3630 mob.paint.but(sheen_factor=factor)
3631 if direction is None
3632 else mob.paint.but(sheen_factor=factor, sheen_direction=direction)
3633 )
3634 if factor != 0:
3635 mob.paint = mob.paint.updated("stroke", mob.get_stroke_color(), None)
3636 mob.paint = mob.paint.updated("fill", mob.get_fill_color(), None)
3637 return self
3639 def set_sheen_direction(self, direction: Vector3DLike, family: bool = True) -> Self:
3640 """Set the direction the mobject's colors lighten toward, which its gradients
3641 run along too.
3643 Args:
3644 direction: The direction, copied as a value without changing the
3645 caller's array.
3646 family: Whether its whole family gets it, or the mobject alone.
3647 """
3648 direction = frozen(np.array(direction, dtype=float, copy=True))
3649 for mob in self._each(family):
3650 mob.paint = mob.paint.but(sheen_direction=direction)
3651 return self
3653 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3654 def get_stroke_rgbas(self, background: bool = False) -> np.ndarray:
3655 """The mobject's own stroke colors, one row per gradient stop.
3657 Args:
3658 background: Whether to read the background stroke's instead.
3660 Returns:
3661 An (n, 4) array of red, green, blue and opacity, from 0 to 1.
3662 """
3663 return self.paint.background if background else self.paint.stroke
3665 @deprecated("get_fill_color() is fill_color: use it", category=None)
3666 def get_fill_color(self) -> ManimColor:
3667 """The mobject's own fill color (for a gradient, its first)."""
3668 return ManimColor(self.paint.fill[0, :3])
3670 @deprecated("get_fill_opacity() is fill_opacity: use it", category=None)
3671 def get_fill_opacity(self) -> float:
3672 """The opacity of the mobject's own fill (for a gradient, its first color's).
3674 Returns:
3675 The opacity, from 0 to 1.
3676 """
3677 return float(self.paint.fill[0, 3])
3679 @deprecated("get_stroke_color() is stroke_color: use it", category=None)
3680 def get_stroke_color(self, background: bool = False) -> ManimColor:
3681 """The mobject's own stroke color (for a gradient, its first).
3683 Args:
3684 background: Whether to read the background stroke's instead.
3685 """
3686 return ManimColor(self.get_stroke_rgbas(background)[0, :3])
3688 @deprecated("get_stroke_width() is stroke_width: use it", category=None)
3689 def get_stroke_width(self, background: bool = False) -> float:
3690 """The width of the mobject's own stroke.
3692 Args:
3693 background: Whether to read the background stroke's instead.
3695 Returns:
3696 The width, in hundredths of a scene unit.
3697 """
3698 return max(
3699 0.0, self.paint.background_width if background else self.paint.stroke_width
3700 )
3702 @deprecated("get_stroke_opacity() is stroke_opacity: use it", category=None)
3703 def get_stroke_opacity(self, background: bool = False) -> float:
3704 """The opacity of the mobject's own stroke (for a gradient, its first color's).
3706 Args:
3707 background: Whether to read the background stroke's instead.
3709 Returns:
3710 The opacity, from 0 to 1.
3711 """
3712 return float(self.get_stroke_rgbas(background)[0, 3])
3714 @deprecated("get_color() is color: use it", category=None)
3715 def get_color(self) -> ManimColor:
3716 """The mobject's own color: its fill's, or its stroke's if it has no fill (its
3717 fill wholly transparent).
3718 """
3719 if np.all(self.paint.fill[:, 3] == 0):
3720 return self.get_stroke_color()
3721 return self.get_fill_color()
3723 @property
3724 def color(self) -> ManimColor:
3725 """The mobject's own color: its fill's, or its stroke's if it has no fill. Set
3726 it to color the whole family (see [set_color][manimgx.Mobject.set_color])."""
3727 return self.get_color()
3729 @color.setter
3730 def color(self, value: ParsableManimColor) -> None:
3731 self.set_color(value)
3733 fill_color = property(get_fill_color, lambda self, c: self.set_fill(c))
3734 """The mobject's own fill color (for a gradient, its first). Set it to fill the
3735 whole family with a color (see [set_fill][manimgx.Mobject.set_fill])."""
3736 stroke_color = property(get_stroke_color, lambda self, c: self.set_stroke(c))
3737 """The mobject's own stroke color (for a gradient, its first). Set it to stroke the
3738 whole family with a color (see [set_stroke][manimgx.Mobject.set_stroke])."""
3739 fill_opacity = property(get_fill_opacity, lambda self, o: self.set_fill(opacity=o))
3740 """The opacity of the mobject's own fill, from 0 to 1. Set it to set the whole
3741 family's."""
3742 stroke_opacity = property(
3743 get_stroke_opacity, lambda self, o: self.set_stroke(opacity=o)
3744 )
3745 """The opacity of the mobject's own stroke, from 0 to 1. Set it to set the whole
3746 family's."""
3747 stroke_width = property(get_stroke_width, lambda self, w: self.set_stroke(width=w))
3748 """The width of the mobject's own stroke, in hundredths of a scene unit. Set it to
3749 set the whole family's."""
3751 def match_style(self, mobject: "Mobject", family: bool = True) -> Self:
3752 """Give the mobject another's style: its colors, opacities, stroke widths, sheen
3753 and the rest of its look, all but how much of it a reveal shows.
3755 Args:
3756 mobject: The mobject whose style to take.
3757 family: Whether the submobjects take the style of the other's too, in order:
3758 paired evenly when their numbers differ, and each taking the other
3759 mobject's own if it has none.
3760 """
3761 self.paint = mobject.paint.but(trim=self.paint.trim)
3762 if family:
3763 subs1, subs2 = self.submobjects, mobject.submobjects
3764 if subs1:
3765 subs2 = subs2 or [mobject]
3766 n = max(len(subs1), len(subs2))
3767 for i in range(n):
3768 subs1[i * len(subs1) // n].match_style(subs2[i * len(subs2) // n])
3769 return self
3771 def match_color(self, mobject: "Mobject") -> Self:
3772 """Color the mobject and its whole family with another's
3773 [color][manimgx.Mobject.color].
3775 Args:
3776 mobject: The mobject whose color to take.
3777 """
3778 return self.set_color(mobject.get_color())
3780 def set_color_by_gradient(self, *colors: ParsableManimColor) -> Self:
3781 """Color the drawn members of the family along a gradient: in family order, each
3782 one solid, from the first color to the last.
3784 One color colors them all; none raises an exception.
3786 Args:
3787 *colors: The colors the gradient runs through, evenly.
3789 Examples:
3790 ```python
3791 import manimgx as m
3794 class MobjectSetColorByGradientExample(m.Scene):
3795 def construct(self) -> None:
3796 dots = m.VGroup(*(m.Dot(radius=0.35) for _ in range(9)))
3797 dots.arrange(buff=0.5)
3798 dots.set_color_by_gradient(m.BLUE, m.GREEN, m.YELLOW)
3799 word = m.Text("gradient", font_size=120)
3800 word.set_color_by_gradient(m.RED, m.YELLOW)
3801 self.add(m.VGroup(dots, word).arrange(m.DOWN, buff=1))
3802 ```
3803 """
3804 return self.set_submobject_colors_by_gradient(*colors)
3806 def set_submobject_colors_by_radial_gradient(
3807 self,
3808 center: Point3DLike | None = None,
3809 radius: float = 1,
3810 inner_color: ParsableManimColor = WHITE,
3811 outer_color: ParsableManimColor = "#000000",
3812 ) -> Self:
3813 """Color the drawn members of the family by how far their centers are from a
3814 point: `inner_color` there, blending to `outer_color` at `radius` and beyond;
3815 each member one solid color.
3817 Args:
3818 center: The point; None for the mobject's center.
3819 radius: The distance at which the color is `outer_color`, in scene units.
3820 inner_color: The color at the point.
3821 outer_color: The color at `radius` and beyond.
3822 """
3823 c = self.get_center() if center is None else np.asarray(center)
3824 for mob in self.family_members_with_points():
3825 t = min(float(np.linalg.norm(mob.get_center() - c)) / radius, 1.0)
3826 mob.set_color(
3827 interpolate_color(ManimColor(inner_color), ManimColor(outer_color), t),
3828 family=False,
3829 )
3830 return self
3832 @deprecated("sort_submobjects is sort: use it", category=None)
3833 def sort_submobjects(
3834 self,
3835 point_to_num_func: Callable[[Point3D], float] = lambda p: p[0],
3836 submob_func: "Callable[[Mobject], float] | None" = None,
3837 ) -> Self:
3838 """Sort the submobjects by a number: the same as [sort][manimgx.Mobject.sort].
3840 Args:
3841 point_to_num_func: A function of a submobject's center, giving the number to
3842 sort it by (default: its x coordinate).
3843 submob_func: A function of a submobject, giving the number to sort it by, in
3844 place of `point_to_num_func`.
3845 """
3846 return self.sort(point_to_num_func, submob_func)
3848 @deprecated("use set_color(mobject.color)", category=None)
3849 def to_original_color(self) -> Self:
3850 """Color the whole family with the mobject's own [color][manimgx.Mobject.color]."""
3851 return self.set_color(self.color)
3853 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3854 def apply_to_family(self, func: Callable[["Mobject"], object]) -> None:
3855 """Call a function on each drawn member of the family, in family order.
3857 Args:
3858 func: A function of a mobject; what it returns is ignored.
3859 """
3860 for mob in self.family_members_with_points():
3861 func(mob)
3863 @deprecated(
3864 "set_submobject_colors_by_gradient is set_color_by_gradient: use it",
3865 category=None,
3866 )
3867 def set_submobject_colors_by_gradient(self, *colors: ParsableManimColor) -> Self:
3868 """Color the drawn members of the family along a gradient: the same as
3869 [set_color_by_gradient][manimgx.Mobject.set_color_by_gradient].
3871 Args:
3872 *colors: The colors the gradient runs through, evenly.
3873 """
3874 if len(colors) == 0:
3875 raise ValueError("Need at least one color")
3876 if len(colors) == 1:
3877 return self.set_color(colors[0])
3878 mobs = self.family_members_with_points()
3879 for mob, color in zip(mobs, color_gradient(colors, len(mobs)), strict=True):
3880 mob.set_color(color, family=False)
3881 return self
3883 def set_colors_by_radial_gradient(
3884 self,
3885 center: Point3DLike | None = None,
3886 radius: float = 1,
3887 inner_color: ParsableManimColor = WHITE,
3888 outer_color: ParsableManimColor = "#000000",
3889 ) -> Self:
3890 """Color the mobject by distance from a point: `inner_color` there, blending to
3891 `outer_color` at `radius` and beyond.
3893 Each drawn member of the family is one solid color, by its center's distance.
3895 Args:
3896 center: The point; None for the mobject's center.
3897 radius: The distance at which the color is `outer_color`, in scene units.
3898 inner_color: The color at the point.
3899 outer_color: The color at `radius` and beyond.
3900 """
3901 c = self.get_center() if center is None else np.asarray(center)
3902 for mob in self.family_members_with_points():
3903 t = min(float(np.linalg.norm(mob.get_center() - c)) / radius, 1)
3904 mob.set_color(
3905 interpolate_color(ManimColor(inner_color), ManimColor(outer_color), t),
3906 family=False,
3907 )
3908 return self
3910 def fade_to(
3911 self, color: ParsableManimColor, alpha: float, family: bool = True
3912 ) -> Self:
3913 """Blend the mobject's color toward another: each drawn member's own color,
3914 mixed `alpha` of the way to `color`.
3916 Args:
3917 color: The color to blend toward.
3918 alpha: How far, from 0 (as it is) to 1 (`color`).
3919 family: Whether its whole family blends, or the mobject alone.
3920 """
3921 if self.has_points():
3922 self.set_color(
3923 interpolate_color(self.get_color(), ManimColor(color), alpha),
3924 family=False,
3925 )
3926 if family:
3927 for sub in self.submobjects:
3928 sub.fade_to(color, alpha)
3929 return self
3931 # ── structural alignment + interpolation (the Transform engine) ─────────
3932 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3933 def align_data(
3934 self, mobject: "Mobject", skip_point_alignment: bool = False
3935 ) -> Self:
3936 """Give this mobject's family and another's the same structure, so the two can
3937 be blended member by member: the same number of members, level by level, and,
3938 unless skipped, the same number of points in each pair.
3940 A transform calls it on its keyframes; both mobjects change, but neither's look
3941 does.
3943 Args:
3944 mobject: The other mobject.
3945 skip_point_alignment: Whether to leave the numbers of points as they are
3946 ([become][manimgx.Mobject.become] does: it takes the other's points as
3947 they are).
3948 """
3949 self.null_point_align(mobject)
3950 self.align_submobjects(mobject)
3951 if not skip_point_alignment:
3952 self.align_points(mobject)
3953 for m1, m2 in zip(self.submobjects, mobject.submobjects, strict=True):
3954 m1.align_data(m2, skip_point_alignment)
3955 return self
3957 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3958 def align_points(self, mobject: "Mobject") -> Self:
3959 """Give this mobject and another the same number of points of their own, and of
3960 color rows: the one with fewer is refined, its shape and look unchanged (see
3961 [align_points_with_larger][manimgx.Mobject.align_points_with_larger]).
3963 Args:
3964 mobject: The other mobject.
3965 """
3966 self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
3967 n1, n2 = self.get_num_points(), mobject.get_num_points()
3968 if n1 < n2:
3969 self.align_points_with_larger(mobject)
3970 elif n2 < n1:
3971 mobject.align_points_with_larger(self)
3972 return self
3974 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3975 def align_submobjects(self, mobject: "Mobject") -> Self:
3976 """Give this mobject and another the same number of submobjects.
3978 The one with fewer repeats its own (see
3979 [add_n_more_submobjects][manimgx.Mobject.add_n_more_submobjects]); one with none
3980 grows, at its center, the point of each of the other's — of that one's kind and
3981 style, so what appears from nothing appears as itself.
3983 Args:
3984 mobject: The other mobject.
3985 """
3986 # (CE's VGroup lent a grown point the group's own, never-drawn style)
3987 for a, b in ((self, mobject), (mobject, self)):
3988 if not a.submobjects and b.submobjects:
3989 center = a.get_center()
3990 a.submobjects = [m.get_point_mobject(center) for m in b.submobjects]
3991 else:
3992 a.add_n_more_submobjects(
3993 max(0, len(b.submobjects) - len(a.submobjects))
3994 )
3995 return self
3997 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3998 def null_point_align(self, mobject: "Mobject") -> Self:
3999 """If one of this mobject and another has no points of its own and the other
4000 has, move the other's points into a submobject of its own, so the two families
4001 line up (see
4002 [push_self_into_submobjects][manimgx.Mobject.push_self_into_submobjects]).
4004 Args:
4005 mobject: The other mobject.
4006 """
4007 for m1, m2 in ((self, mobject), (mobject, self)):
4008 if m1.has_no_points() and m2.has_points():
4009 m2.push_self_into_submobjects()
4010 return self
4012 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4013 def push_self_into_submobjects(self) -> Self:
4014 """Move the mobject's own points into a new submobject, added last: a copy of it
4015 without submobjects or updaters (a part of the mobject, which keeps its updaters,
4016 not a replica that would run them too). The mobject keeps its submobjects, and has
4017 no points of its own.
4018 """
4019 clone = self.copy()
4020 clone.submobjects = []
4021 clone.clear_updaters()
4022 self.reset_points()
4023 return self.add(clone)
4025 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4026 def add_n_more_submobjects(self, n: int) -> Self:
4027 """Add `n` submobjects, for a transform that splits parts: a mobject with none
4028 gets `n` points of itself, at its center (see
4029 [get_point_mobject][manimgx.Mobject.get_point_mobject]); otherwise each
4030 submobject is followed by invisible copies of itself, spread as evenly as can
4031 be.
4033 Args:
4034 n: How many to add.
4035 """
4036 if n == 0:
4037 return self
4038 cur = len(self.submobjects)
4039 if cur == 0:
4040 self.submobjects = [self.get_point_mobject() for _ in range(n)]
4041 return self
4042 target = cur + n
4043 # Count the integer indices in each child's interval.
4044 split = [
4045 int(((i + 1) * target + cur - 1) // cur - (i * target + cur - 1) // cur)
4046 for i in range(cur)
4047 ]
4048 new: list[Mobject] = []
4049 for sub, sf in zip(self.submobjects, split, strict=True):
4050 new.append(sub)
4051 new.extend(sub.copy().fade(1) for _ in range(1, sf))
4052 self.submobjects = new
4053 return self
4055 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4056 def interpolate(
4057 self,
4058 mobject1: "Mobject",
4059 mobject2: "Mobject",
4060 alpha: float,
4061 path_func: PathFunc = _STRAIGHT,
4062 ) -> Self:
4063 """Make the mobject a blend of two others: `mobject1` at 0, `mobject2` at 1.
4065 Its own points go from the first's to the second's along `path_func`, and its
4066 style blends from the first's to the second's; its submobjects are left as they
4067 are. A transform calls it on each drawn member, with its aligned keyframes (see
4068 [align_data][manimgx.Mobject.align_data]), which have as many points as each
4069 other.
4071 Args:
4072 mobject1: The mobject it is at 0.
4073 mobject2: The mobject it is at 1.
4074 alpha: How far from the first to the second, from 0 to 1.
4075 path_func: The path each point takes (default: straight).
4076 """
4077 g1, g2 = mobject1._geometry, mobject2._geometry
4078 if (
4079 isinstance(path_func, Path) and g1.n == g2.n
4080 ): # a linear path moves shapes, not points
4081 self._geometry = Blend.mix(g1, g2, path_func.coefficients(alpha))
4082 else:
4083 self.points = path_func(mobject1.points, mobject2.points, alpha)
4084 self.paint = self.paint.mixed(mobject1.paint, mobject2.paint, alpha)
4085 return self
4087 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4088 def interpolate_color(
4089 self, mobject1: "Mobject", mobject2: "Mobject", alpha: float
4090 ) -> Self:
4091 """Make the mobject's own style a blend of two others': `mobject1`'s at 0,
4092 `mobject2`'s at 1; its points stay.
4094 Args:
4095 mobject1: The mobject whose style it has at 0.
4096 mobject2: The mobject whose style it has at 1.
4097 alpha: How far from the first to the second, from 0 to 1.
4098 """
4099 self.paint = self.paint.mixed(mobject1.paint, mobject2.paint, alpha)
4100 return self
4102 def become(
4103 self,
4104 mobject: "Mobject",
4105 match_height: bool = False,
4106 match_width: bool = False,
4107 match_depth: bool = False,
4108 match_center: bool = False,
4109 stretch: bool = False,
4110 ) -> Self:
4111 """Make the mobject another's value, at once, while staying itself: the same
4112 object in the scene, with its updaters.
4114 It takes the other's points, shape and style, and its members', position by
4115 position: a member stays itself where the other has one of its kind in its place,
4116 and takes that one's value; the other's further members come as copies, without
4117 updaters; its own further members go. The other is left as it is. With a
4118 `match_*` flag or `stretch`, a copy of `mobject` is first fitted to this mobject.
4120 Args:
4121 mobject: The mobject to look like.
4122 match_height: Whether the copy is first scaled, in proportion, to this
4123 mobject's height.
4124 match_width: Whether it is first scaled to this mobject's width.
4125 match_depth: Whether it is first scaled to this mobject's depth.
4126 match_center: Whether it is first moved to this mobject's center.
4127 stretch: Whether it is first stretched to this mobject's width, height and
4128 depth, in place of the `match_*` scalings.
4130 Examples:
4131 ```python
4132 import manimgx as m
4135 class MobjectBecomeExample(m.Scene):
4136 def construct(self) -> None:
4137 shape = m.Circle(radius=2, color=m.RED, fill_opacity=0.8)
4138 shape.add_updater(lambda mob, dt: mob.rotate(dt))
4139 self.add(shape)
4140 self.wait()
4141 square = m.Square(side_length=4, color=m.BLUE, fill_opacity=0.8)
4142 shape.become(square)
4143 self.wait(2) # the same mobject: its updater still turns it
4144 ```
4145 """
4146 if stretch or match_height or match_width or match_depth or match_center:
4147 mobject = mobject.copy()
4148 for dim, match in ((1, match_height), (0, match_width), (2, match_depth)):
4149 if stretch or match:
4150 mobject.rescale_to_fit(self.length_over_dim(dim), dim, stretch)
4151 if match_center:
4152 mobject.move_to(self.get_center())
4153 elif not {id(m) for m in self.get_family()}.isdisjoint(
4154 id(m) for m in mobject.get_family()
4155 ): # sharing members (becoming its own member, say): it takes a copy's value
4156 mobject = mobject.copy()
4157 self._take(mobject)
4158 return self
4160 def _take(self, other: "Mobject") -> None:
4161 """Take another mobject's value (see [become][manimgx.Mobject.become])."""
4162 theirs = other.submobjects
4163 if other.has_points() and _kind(type(self)) is not _kind(type(other)):
4164 # its kind can't hold the other's own shape: it holds it in a first member
4165 self.reset_points()
4166 theirs = [_fresh(other, alone=True), *theirs]
4167 else:
4168 self._geometry = other._geometry # immutable values: shared, not copied
4169 self._take_shape(other)
4170 self.paint = other.paint
4171 members: list[Mobject] = []
4172 for i, sub in enumerate(theirs):
4173 mine = self.submobjects[i] if i < len(self.submobjects) else None
4174 if mine is not None and _kind(type(mine)) is _kind(type(sub)):
4175 mine._take(sub)
4176 else:
4177 mine = _fresh(sub)
4178 members.append(mine)
4179 self.submobjects = members
4181 def match_points(self, mobject: "Mobject") -> Self:
4182 """Take another mobject's shape: its points, member by member in family order;
4183 this mobject's style stays its own.
4185 Members past the end of the shorter family stay as they are.
4187 Args:
4188 mobject: The mobject whose shape to take.
4189 """
4190 for sm1, sm2 in zip(self.get_family(), mobject.get_family(), strict=False):
4191 sm1._geometry = sm2._geometry
4192 sm1._take_shape(sm2)
4193 return self
4195 def _take_shape(self, mobject: "Mobject") -> None:
4196 """What goes with another mobject's points when this one takes them (a kind whose
4197 shape is more than points — a mesh's triangles — takes that too)."""
4199 @classmethod
4200 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4201 def add_animation_override(
4202 cls,
4203 animation_class: type["Animation"],
4204 override_func: Callable[..., "Animation"],
4205 ) -> None:
4206 """Make the class play another animation in place of one: playing
4207 `animation_class(mobject, …)` on a mobject of the class plays what
4208 `override_func` returns instead.
4210 [override_animation][manimgx.override_animation] does this for a method of the
4211 class. Overriding one animation twice raises an exception.
4213 Args:
4214 animation_class: The animation to play another in place of.
4215 override_func: A function of the mobject, then the animation's other
4216 arguments and keywords, that returns the animation to play.
4217 """
4218 if animation_class in cls.animation_overrides:
4219 raise Exception(
4220 f"The animation {animation_class.__name__} for {cls.__name__} is"
4221 " overridden by more than one method"
4222 )
4223 cls.animation_overrides = cls.animation_overrides | {
4224 animation_class: override_func
4225 }
4227 @classmethod
4228 def set_default(cls, **kwargs: object) -> None:
4229 """Change the defaults of the class's constructor keywords, for every mobject of
4230 the class made from then on; with none given, restore them.
4232 After `Text.set_default(font_size=100)`, a `Text` is 100 points unless it is
4233 made with another size. The keywords are checked when a mobject is made.
4235 Changing or restoring defaults discards remembered constructions. Existing
4236 mobjects keep their state; later construction reads the current defaults.
4238 Repeated calls replace this class's keyword defaults. Reset restores its
4239 original constructor, or normal inheritance if it had no constructor of its own.
4240 The defaults are applied when a mobject is made, to the constructor then in
4241 force: the class's own, or the next one in the made mobject's class's order (so a
4242 parent's later defaults reach a configured child, and a configured mixin calls the
4243 class after it in a subclass's order).
4245 Args:
4246 **kwargs: Keywords of the class's constructor, with their new defaults.
4247 """
4248 if kwargs:
4249 original = cls.__dict__.get(
4250 "_original__init__", cls.__dict__.get("__init__")
4251 )
4252 defaults = dict(kwargs)
4254 # The constructor checks the keywords when it runs: defaults applied to a
4255 # signature have no static type
4256 def init(self: Mobject, *args: object, **given: object) -> None:
4257 merged = defaults | given
4258 if original is not None:
4259 original(self, *args, **merged)
4260 else:
4261 super(cls, self).__init__(*args, **merged)
4263 setattr(cls, "_original__init__", original) # noqa: B010
4264 setattr(cls, "__init__", init) # noqa: B010
4265 elif "_original__init__" in cls.__dict__:
4266 original = cls.__dict__["_original__init__"]
4267 delattr(cls, "_original__init__")
4268 if original is None:
4269 delattr(cls, "__init__")
4270 else:
4271 setattr(cls, "__init__", original) # noqa: B010
4272 caches.clear()
4274 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4275 def get_pieces(self, n_pieces: int) -> "Group":
4276 """Split the mobject into pieces: copies of it, each an equal part of it in
4277 turn, from its start to its end (a path's, by its curves).
4279 Only the mobject's own points are split; its submobjects are left out.
4281 Args:
4282 n_pieces: How many pieces.
4284 Returns:
4285 A new group of the pieces, in order.
4286 """
4287 template = self.copy()
4288 template.submobjects = []
4289 alphas = np.linspace(0, 1, n_pieces + 1)
4290 return Group(
4291 *(
4292 template.copy().pointwise_become_partial(self, a1, a2)
4293 for a1, a2 in it.pairwise(alphas)
4294 )
4295 )
4297 # ── animation hooks ───────────────────────────────────────────────────
4298 @property
4299 def animate(self) -> "Animate[Self]":
4300 """An animation of the mobject, built from the method calls made on it.
4302 `square.animate.shift(RIGHT).scale(2)` is an animation that moves the square
4303 right and doubles its size: pass it to [Scene.play][manimgx.Scene.play]. Each
4304 call is recorded — and tried at once on a copy, so a wrong call fails where it
4305 is written — and returns the animation, so calls chain. The calls are carried
4306 out on the mobject as it is when the animation begins, and the animation tweens
4307 it from that state to the result: in
4308 `Succession(square.animate.shift(RIGHT), square.animate.rotate(PI / 2))`, the
4309 square turns about its center where the shift left it. When the animation
4310 finishes, the calls are carried out on the mobject itself.
4312 The motion follows the calls: a turn among them (`rotate`, `flip`) turns the
4313 mobject rigidly about its pivot, through its whole angle (`rotate(TAU)` is a full turn); every other call moves its center
4314 straight; and the rest of the change (a size, a color, a new shape) blends along
4315 the way. Call `animate` with options before any method —
4316 `square.animate(run_time=2, rate_func=linear).shift(UP)` — to set the
4317 animation's [Transform options][manimgx.animation.transform.TransformOptions]; a
4318 `path_arc` or a `path_func` among them replaces the motion. Call it with a
4319 function — `square.animate(lambda s: s.shift(UP))` — to record that function as
4320 a call. Call a method of your own class so: through `animate`, a type checker
4321 knows only ManimGX's methods, but it checks a function against the mobject's
4322 class.
4324 Examples:
4325 ```python
4326 import manimgx as m
4329 class MobjectAnimateExample(m.Scene):
4330 def construct(self) -> None:
4331 triangle = m.Triangle(color=m.BLUE, fill_opacity=0.5)
4332 self.add(triangle)
4333 self.play(triangle.animate.shift(3 * m.LEFT).scale(1.5))
4334 self.play(triangle.animate.rotate(m.PI).set_color(m.YELLOW))
4335 self.play(triangle.animate(path_arc=m.PI).move_to(3 * m.RIGHT))
4336 ```
4337 """
4338 from manimgx.animation.transform import Animate
4340 return Animate(self)
4342 @classmethod
4343 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4344 def animation_override_for(
4345 cls, animation_class: type["Animation"]
4346 ) -> Callable[..., "Animation"] | None:
4347 """The function that makes the animation the class plays in place of
4348 `animation_class` (see [override_animation][manimgx.override_animation]).
4350 An animation asks, when it is played.
4352 Returns:
4353 The function; None if the class plays `animation_class` itself.
4354 """
4355 return cls.animation_overrides.get(animation_class)
4357 def set(self, **kwargs: object) -> Self:
4358 """Set attributes of the mobject by name: its properties, such as `width`,
4359 `height` or `color` (or a text's `font_size`), or any other attribute.
4361 Through [animate][manimgx.Mobject.animate] it animates the change:
4362 `mobject.animate.set(width=4)`.
4364 Args:
4365 **kwargs: The attributes' names, with their values.
4366 """
4367 # CE's
4368 for attr, value in kwargs.items():
4369 setattr(self, attr, value)
4370 return self
4372 def __repr__(self) -> str:
4373 return str(self.name)
4376def _members(items: Iterable[Mobject | Iterable[Mobject]]) -> list[Mobject]:
4377 """Mobjects and iterables of mobjects, flattened one level."""
4378 flat: list[Mobject] = []
4379 for m in items:
4380 if isinstance(m, Mobject):
4381 flat.append(m)
4382 else:
4383 flat.extend(m)
4384 return flat
4387class Group[T: Mobject = Mobject](Mobject):
4388 """Mobjects together, of any kinds: paths, text, images, point clouds, other groups.
4390 A group has no points of its own: its members are its submobjects, and whatever is
4391 done to the group — moving, scaling, styling, animating — is done to them all.
4392 [VGroup][manimgx.VGroup] is another name for it. A group can be indexed (`group[0]`), sliced (`group[1:3]` is a new group of those
4393 members) and iterated over, and `group + mobject`, `group - mobject`, `+=` and `-=`
4394 add and remove members.
4396 Its member type is inferred from what it is made with; a group meant to hold several
4397 kinds says so once, as `Group[Mobject](…)`, and `Group[Integer](…)` holds integers
4398 only, so `group[0]` is an [Integer][manimgx.Integer] to a type checker.
4400 Args:
4401 *mobjects: The members, in drawing order: mobjects, or iterables of mobjects
4402 (each of their mobjects a member).
4403 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself: as it
4404 has no points, they do not restyle its members (the style methods do).
4406 Examples:
4407 ```python
4408 import manimgx as m
4411 class GroupExample(m.Scene):
4412 def construct(self) -> None:
4413 shapes = m.Group(
4414 m.Circle(color=m.BLUE), m.Square(color=m.GREEN), m.Triangle()
4415 ).arrange(buff=1)
4416 self.play(m.Create(shapes))
4417 self.play(shapes.animate.scale(1.5).set_fill(opacity=0.5))
4418 self.play(shapes[1].animate.shift(m.UP))
4419 ```
4420 """
4422 # a kind (path, points, mesh) belongs to a leaf, never to a container — so CE's
4423 # Group, VGroup and PGroup are this one class
4425 # a Group[T] only ever adds T
4426 submobjects: list[T]
4427 """The group's members, in drawing order."""
4429 @overload # `Group(a, b)`: members of any kinds
4430 def __init__(
4431 self: "Group[Mobject]",
4432 *mobjects: Mobject | Iterable[Mobject],
4433 **kwargs: Unpack[Style],
4434 ) -> None: ...
4435 @overload # `Group[Integer](a, b)`: declared, so checked on the way in and precise on the way out
4436 def __init__(self, *mobjects: T | Iterable[T], **kwargs: Unpack[Style]) -> None: ...
4437 def __init__(
4438 self, *mobjects: Mobject | Iterable[Mobject], **kwargs: Unpack[Style]
4439 ) -> None:
4440 super().__init__(**kwargs)
4441 Mobject.add(self, *_members(mobjects))
4443 def add( # ty: ignore[invalid-method-override] # a Group[T] adds T
4444 self, *mobjects: T | Iterable[T]
4445 ) -> Self:
4446 """Add members after the ones the group has: mobjects, or iterables of mobjects
4447 (each of their mobjects a member).
4449 A member already in the group moves to the end. Adding anything but mobjects, or
4450 the group to itself, raises an exception.
4452 Args:
4453 *mobjects: The members to add, in order.
4454 """
4455 return super().add(*_members(mobjects))
4457 def __iter__(self) -> Iterator[T]:
4458 return iter(self.submobjects)
4460 @overload
4461 def __getitem__(self, value: int) -> T: ...
4462 @overload
4463 def __getitem__(self, value: slice) -> "Group[T]": ...
4464 def __getitem__(self, value: int | slice) -> "T | Group[T]":
4465 if isinstance(value, slice):
4466 return self._group(self.submobjects[value])
4467 return self.submobjects[value]
4469 def __add__(self, mobject: T) -> "Group[T]":
4470 return self._group([*self.submobjects, mobject])
4472 def __iadd__(self, mobject: T) -> Self:
4473 return self.add(mobject)
4475 def __sub__(self, mobject: T) -> "Group[T]":
4476 rest = self._group(self.submobjects)
4477 rest.remove(mobject)
4478 return rest
4480 def __isub__(self, mobject: T) -> Self:
4481 return self.remove(mobject)
4483 def _group(self, members: Iterable[T]) -> "Group[T]":
4484 """A plain group of members of this group's type (`Group(…)` alone would say Mobject)."""
4485 return cast("Group[T]", Group(*members))
4488@deprecated(
4489 "Manim CE's way to change the animation a class plays: ManimGX doesn't document it",
4490 category=None,
4491)
4492def override_animate[F: Callable[..., "Animation"]](
4493 method: Callable[..., object],
4494) -> Callable[[F], F]:
4495 """Decorate a mobject class's method that makes the animation to play when another
4496 method is called through [animate][manimgx.Mobject.animate].
4498 Then `mobject.animate.method(*args, **kwargs)` is the animation the decorated method
4499 returns, called with the mobject, the same arguments, and `anim_args`: the options
4500 given to `animate(...)` (an empty dict if none). It is made when the call is
4501 written, and cannot be chained with other calls.
4503 Args:
4504 method: The method whose `animate` call plays the decorated method's animation.
4506 Returns:
4507 The decorator, which returns the decorated method as it is.
4509 Examples:
4510 ```python
4511 import manimgx as m
4512 from manimgx.animation.motion import TransformOptions
4515 class Tally(m.VGroup):
4516 def add_mark(self) -> "Tally":
4517 mark = m.Line(1.5 * m.UP, 1.5 * m.DOWN, stroke_width=12)
4518 return self.add(mark.shift(0.7 * (len(self) - 2) * m.RIGHT))
4520 @m.override_animate(add_mark)
4521 def _add_mark_animation(self, anim_args: TransformOptions) -> m.Animation:
4522 self.add_mark()
4523 return m.GrowFromCenter(self[-1], **anim_args)
4526 class OverrideAnimateExample(m.Scene):
4527 def construct(self) -> None:
4528 tally = Tally().add_mark()
4529 self.add(tally)
4530 for _ in range(4):
4531 self.play(tally.animate(run_time=0.5).add_mark())
4532 ```
4533 """
4534 # CE's decorator
4536 def decorator(animation_method: F) -> F:
4537 _animate_plays[method] = animation_method
4538 return animation_method
4540 return decorator
4543@deprecated(
4544 "Manim CE's way to change the animation a class plays: ManimGX doesn't document it",
4545 category=None,
4546)
4547def override_animation[F: Callable[..., "Animation"]](
4548 animation_class: type["Animation"],
4549) -> Callable[[F], F]:
4550 """Decorate a mobject class's method that makes the animation to play in place of
4551 `animation_class`.
4553 Then playing `animation_class(mobject, *args, **kwargs)` on a mobject of the class,
4554 or of a subclass, plays what the decorated method returns, called with the mobject
4555 and the same arguments. An animation made with `use_override=False` plays itself.
4557 Args:
4558 animation_class: The animation to play another in place of.
4560 Returns:
4561 The decorator, which returns the decorated method as it is.
4563 Examples:
4564 ```python
4565 from typing import Unpack
4567 import manimgx as m
4568 from manimgx.animation.timeline import AnimationOptions
4571 class DrawnSquare(m.Square):
4572 @m.override_animation(m.FadeIn)
4573 def _fade_in(self, **kwargs: Unpack[AnimationOptions]) -> m.Animation:
4574 return m.Create(self, **kwargs)
4577 class OverrideAnimationExample(m.Scene):
4578 def construct(self) -> None:
4579 square = DrawnSquare(side_length=4, color=m.BLUE, fill_opacity=0.5)
4580 self.play(m.FadeIn(square, run_time=2)) # drawn, not faded in
4581 ```
4582 """
4583 # CE's decorator
4585 def decorator(func: F) -> F:
4586 _plays_instead[func] = animation_class
4587 return func
4589 return decorator
4592class ValueTracker[V: (float, complex) = float](Mobject):
4593 """A number that animations can change and updaters can read.
4595 The number is kept as the x coordinate of the tracker's one point, so whatever moves
4596 a mobject changes it: `tracker.animate.set_value(5)` takes it to 5 at the pace of
4597 the animation's rate function, and the updaters of other mobjects read it with
4598 [`get_value`][manimgx.ValueTracker.get_value]. A tracker is never drawn; add it to
4599 the scene only if it has updaters of its own. `tracker += 1` and `tracker -= 1`
4600 change the number at once.
4602 Args:
4603 value: The real number it starts with; use
4604 [ComplexValueTracker][manimgx.ComplexValueTracker] for complex numbers.
4605 **kwargs: [Style keywords][manimgx.drawing.paint.Style], as any mobject takes (a
4606 tracker is not drawn).
4608 Examples:
4609 ```python
4610 import manimgx as m
4613 class ValueTrackerExample(m.Scene):
4614 def construct(self) -> None:
4615 x = m.ValueTracker(-4)
4616 line = m.NumberLine(x_range=(-6, 6, 1), length=12).add_numbers()
4617 pointer = m.Vector(1.5 * m.DOWN, color=m.YELLOW)
4618 pointer.add_updater(lambda p: p.next_to(line.n2p(x.get_value()), m.UP))
4619 label = m.MathTex("x", font_size=72, color=m.YELLOW)
4620 label.add_updater(lambda t: t.next_to(pointer, m.UP))
4621 self.add(line, pointer, label)
4622 self.play(x.animate.set_value(5), run_time=2)
4623 x -= 3
4624 self.wait(0.5)
4625 self.play(x.animate.increment_value(-5))
4626 ```
4627 """
4629 @overload
4630 def __init__(
4631 self: "ValueTracker[float]", value: float = 0, **kwargs: Unpack[Style]
4632 ) -> None: ...
4633 @overload
4634 def __init__(
4635 self: "ComplexValueTracker", value: complex = 0, **kwargs: Unpack[Style]
4636 ) -> None: ...
4637 def __init__(self, value: V = 0, **kwargs: Unpack[Style]) -> None:
4638 super().__init__(**kwargs)
4639 self.points = np.zeros((1, 3))
4640 self.set_value(value)
4642 def get_value(self) -> V:
4643 """The number the tracker holds."""
4644 return float(self.points[0, 0])
4646 def set_value(self, value: V) -> Self:
4647 """Set the number the tracker holds; through
4648 [`animate`][manimgx.Mobject.animate], animate it there.
4650 Args:
4651 value: The new number.
4652 """
4653 points = np.array(self.points)
4654 points[0, 0] = value
4655 self.points = points
4656 return self
4658 def increment_value(self, d_value: V) -> Self:
4659 """Add to the number the tracker holds; through
4660 [`animate`][manimgx.Mobject.animate], animate the change.
4662 Args:
4663 d_value: The amount to add; a negative one subtracts.
4664 """
4665 return self.set_value(self.get_value() + d_value)
4667 def __iadd__(self, d_value: V) -> Self:
4668 return self.increment_value(d_value)
4670 def __isub__(self, d_value: V) -> Self:
4671 return self.increment_value(-d_value)
4674class ComplexValueTracker(ValueTracker[complex]):
4675 """A complex number that animations can change and updaters can read.
4677 The number is kept as the tracker's one point, its real part as x and its imaginary
4678 part as y, so an animation takes it along a straight line of the complex plane:
4679 `tracker.animate.set_value(3 + 2j)`. `+=` and `-=` change it at once, in complex
4680 arithmetic.
4682 Args:
4683 value: The number it starts with.
4684 **kwargs: [Style keywords][manimgx.drawing.paint.Style], as any mobject takes (a
4685 tracker is not drawn).
4687 Examples:
4688 ```python
4689 import manimgx as m
4692 class ComplexValueTrackerExample(m.Scene):
4693 def construct(self) -> None:
4694 plane = m.ComplexPlane().add_coordinates()
4695 z = m.ComplexValueTracker(2 + 1j)
4696 dot = m.Dot(radius=0.15, color=m.YELLOW)
4697 dot.add_updater(lambda d: d.move_to(plane.n2p(z.get_value())))
4698 self.add(plane, dot)
4699 self.play(z.animate.set_value(-3 + 2j))
4700 self.play(z.animate.set_value(z.get_value() * 1j))
4701 self.play(z.animate.set_value(z.get_value() / (1 + 1j)))
4702 ```
4703 """
4705 def get_value(self) -> complex:
4706 """The complex number the tracker holds."""
4707 return complex(*self.points[0, :2])
4709 def set_value(self, value: complex) -> Self:
4710 """Set the complex number the tracker holds; through
4711 [`animate`][manimgx.Mobject.animate], animate it there, in a straight line.
4713 Args:
4714 value: The new number; a real one is taken as complex.
4715 """
4716 z = complex(value)
4717 points = np.array(self.points)
4718 points[0, :2] = (z.real, z.imag)
4719 self.points = points
4720 return self
4723_T_VALUES = np.linspace(0, 1, _NPPCC)
4724_IMAGE_TOLERANCE = 1e-3
4725"""How far a curve's image may stray from the true image of the curve at a third and two
4726thirds of each piece (scene units): a quarter of a pixel at 4K."""
4727_IMAGE_MAX_DEPTH = 8
4728"""At most 2**8 pieces per curve for an image (a map that blows up somewhere stops there)."""
4729_CHECKS = np.array([1 / 3, 2 / 3])[:, None]
4730# where an image is checked, in each piece: the middle alone passes an image that strays both
4731# ways about it (a wave, a curve of no handles); with its ends, two points inside pin a cubic
4732_AT_CHECKS = np.hstack(
4733 [
4734 (1 - _CHECKS) ** 3,
4735 3 * (1 - _CHECKS) ** 2 * _CHECKS,
4736 3 * (1 - _CHECKS) * _CHECKS**2,
4737 _CHECKS**3,
4738 ]
4739)
4742def _checked(curves: np.ndarray) -> np.ndarray:
4743 """Each cubic's points at a third and two thirds of its parameter: (curves, 2, dim)."""
4744 return np.einsum("tk,ckd->ctd", _AT_CHECKS, curves)
4747class VMobject(Mobject):
4748 """A path: cubic Bézier curves, stroked in white and unfilled unless styled.
4750 Each curve has four control points: it starts at an anchor, bends toward two handles
4751 and ends at the next anchor. The path's [points][manimgx.Mobject.points] are its
4752 curves' control points, four by four, and a new subpath starts wherever a curve does
4753 not begin where the one before it ends. The stroke follows the curves; the fill
4754 closes each subpath with a straight line back to its start, and where subpaths
4755 overlap, a point is filled unless their windings around it cancel: a subpath inside
4756 another that runs the other way cuts a hole.
4758 Circles, polygons, text and graphs are all paths. A plain `VMobject` has no points
4759 until it is given a shape: set its points as corners, or start it at a point and add
4760 lines and curves.
4762 Args:
4763 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
4765 Examples:
4766 ```python
4767 import manimgx as m
4770 class VMobjectExample(m.Scene):
4771 def construct(self) -> None:
4772 path = m.VMobject(color=m.BLUE, fill_opacity=0.5, stroke_width=8)
4773 path.set_points_as_corners([[-3, -2, 0], [-3, 2, 0], [0, 2, 0]])
4774 path.add_cubic_bezier_curve_to([3, 2, 0], [3, -2, 0], [0, -2, 0])
4775 path.close_path()
4776 self.play(m.Create(path, run_time=2))
4777 ```
4778 """
4780 _curves = True # a path: its box is its curves' tight box
4781 # CE's per-instance options, which no scene sets: constants a subclass may override.
4782 pre_function_handle_to_anchor_scale_factor: float = 0.01
4783 """Where along each handle [apply_function][manimgx.Mobject.apply_function] samples
4784 the function, as a fraction of the handle's length (default 0.01): the handle then
4785 follows how the function stretches the path at its anchor, so the curves stay
4786 smooth."""
4787 make_smooth_after_applying_functions: bool = False
4788 """Whether [apply_function][manimgx.Mobject.apply_function] makes the path smooth
4789 after mapping its curves (default False; see
4790 [make_smooth][manimgx.VMobject.make_smooth])."""
4791 tolerance_for_point_equality: float = 1e-6
4792 """How far apart, in scene units, two points of the path may be and still count as
4793 one, where a subpath ends and whether the path is closed (default 1e-6, plus 1e-5 of
4794 their coordinates)."""
4796 @property
4797 def n_points_per_curve(self) -> int:
4798 """The number of control points of each of the path's curves: 4."""
4799 return _NPPCC
4801 def set_cap_style(self, cap_style: CapStyleType) -> Self:
4802 """Set how the strokes of the path and its family end, at each end they show:
4803 an open path's ends, a reveal's moving end, each dash's ends.
4805 A two-dimensional scene draws the caps; a three-dimensional scene ends every
4806 stroke flat (see [CapStyleType][manimgx.CapStyleType]).
4808 Args:
4809 cap_style: The cap: round, butt or square.
4810 """
4811 for mob in self.get_family():
4812 mob.paint = mob.paint.but(cap=cap_style)
4813 return self
4815 def set_shade_in_3d(
4816 self, value: bool = True, z_index_as_group: bool = False
4817 ) -> Self:
4818 """Set whether a three-dimensional scene's light shades the path and its family.
4820 Args:
4821 value: Whether the light shades them.
4822 z_index_as_group: Whether each member of the family also takes the path as
4823 its z-index group, which is kept for
4824 Manim compatibility (the renderer draws a three-dimensional scene by
4825 depth).
4826 """
4827 for mob in self.get_family():
4828 mob.paint = mob.paint.but(shade_in_3d=value)
4829 if z_index_as_group:
4830 mob.z_index_group = self
4831 return self
4833 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4834 def get_sheen_direction(self) -> np.ndarray:
4835 """The direction the path's own colors lighten toward, which its gradients run
4836 along too (see [set_sheen][manimgx.Mobject.set_sheen]).
4838 Returns:
4839 A copy of the direction.
4840 """
4841 return np.array(self.paint.sheen_direction)
4843 gradient_frame: Mobject | None = None
4844 """The mobject whose bounding box the path's color gradients span; None for the
4845 path's own. Parts that share one show a single gradient across them all."""
4847 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
4848 def get_gradient_start_and_end_points(self) -> tuple[Point3D, Point3D]:
4849 """Where the path's color gradients start and end: a gradient spans its
4850 [bounding box][manimgx.Mobject.boundary_box], along its sheen direction.
4852 They are the box's center, less and plus the sheen direction scaled by half the
4853 box's size along each axis: with the default direction, [UL][manimgx.UL], the
4854 box's lower right and upper left corners. The box is the
4855 [gradient_frame][manimgx.VMobject.gradient_frame]'s, if the path has one. The
4856 renderer reads them for a path whose fill or stroke has several colors.
4858 Returns:
4859 The start and the end, in scene coordinates; the origin twice if the box has
4860 no points.
4861 """
4862 box = (self.gradient_frame or self).boundary_box()
4863 if box is None:
4864 return np.zeros(3), np.zeros(3)
4865 lo, hi = box
4866 center, offset = (lo + hi) / 2, (hi - lo) / 2 * self.get_sheen_direction()
4867 return center - offset, center + offset
4869 # ── path building ─────────────────────────────────────────────────────
4870 @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
4871 def set_anchors_and_handles(
4872 self,
4873 anchors1: Point3D_Array,
4874 handles1: Point3D_Array,
4875 handles2: Point3D_Array,
4876 anchors2: Point3D_Array,
4877 ) -> Self:
4878 """Give the path new curves, in place of its points, from their control points
4879 listed kind by kind.
4881 Curve `i` runs from `anchors1[i]` to `anchors2[i]`, bending toward `handles1[i]`
4882 and then `handles2[i]`: the four arrays have one row per curve.
4884 Args:
4885 anchors1: Where each curve starts, in scene coordinates.
4886 handles1: Each curve's first handle.
4887 handles2: Each curve's second handle.
4888 anchors2: Where each curve ends.
4889 """
4890 n = _NPPCC * len(anchors1)
4891 points = np.empty((n, self.dim))
4892 for i, array in enumerate((anchors1, handles1, handles2, anchors2)):
4893 points[i::_NPPCC] = array
4894 self.points = points
4895 return self
4897 @deprecated("clear_points is reset_points: use it", category=None)
4898 def clear_points(self) -> Self:
4899 """Remove the path's own points: the same as
4900 [reset_points][manimgx.Mobject.reset_points].
4901 """
4902 return self.reset_points()
4904 def append_points(self, new_points: Point3DLike_Array) -> Self:
4905 """Add control points after the path's own: taken four by four, the path's
4906 points are its curves.
4908 Args:
4909 new_points: The points, in scene coordinates: an (n, 3) array.
4910 """
4911 # the path grows in place (its shape is a prefix of an append-only log), so a
4912 # traced path grows by what it gains, not by a copy of all it has
4913 rows = np.asarray(new_points, dtype=float).reshape(-1, self.dim)
4914 g = self._geometry
4915 if len(g.terms) == 1 and np.array_equal(g.terms[0][0][:, :3], np.eye(3)):
4916 m, shape = g.terms[0]
4917 self._geometry = Blend(
4918 ((m, shape.extended(rows - m[:, 3])),), g.n + len(rows)
4919 )
4920 return self
4921 self.points = np.concatenate([self.points, rows])
4922 return self
4924 def start_new_path(self, point: Point3DLike) -> Self:
4925 """Start a new subpath at a point: the next curve added begins there, not where
4926 the path ends.
4928 A curve left unfinished (a subpath started and given no curve yet) is completed
4929 with copies of its first point, as a curve of no length. Started where the path
4930 ends, the subpath just goes on.
4932 Args:
4933 point: Where the new subpath starts, in scene coordinates.
4934 """
4935 n = self._geometry.n
4936 if n % _NPPCC != 0:
4937 last = self._geometry.point(n // _NPPCC * _NPPCC)
4938 self.append_points([last] * (_NPPCC - n % _NPPCC) + [point])
4939 else:
4940 self.append_points([point])
4941 return self
4943 def add_cubic_bezier_curve(
4944 self,
4945 anchor1: Point3DLike,
4946 handle1: Point3DLike,
4947 handle2: Point3DLike,
4948 anchor2: Point3DLike,
4949 ) -> Self:
4950 """Add a curve from `anchor1` to `anchor2`, bending toward two handles: a new
4951 subpath, unless `anchor1` is where the path ends.
4953 Its four points are appended as they are, so the path's curves must all be
4954 whole: after [start_new_path][manimgx.VMobject.start_new_path], use
4955 [add_cubic_bezier_curve_to][manimgx.VMobject.add_cubic_bezier_curve_to].
4957 Args:
4958 anchor1: Where the curve starts, in scene coordinates.
4959 handle1: The handle it leaves `anchor1` heading toward.
4960 handle2: The handle it arrives at `anchor2` heading away from.
4961 anchor2: Where it ends.
4962 """
4963 return self.append_points([anchor1, handle1, handle2, anchor2])
4965 def add_cubic_bezier_curve_to(
4966 self, handle1: Point3DLike, handle2: Point3DLike, anchor: Point3DLike
4967 ) -> Self:
4968 """Add a curve from where the path ends to `anchor`, bending toward two handles.
4970 The curve leaves the path's last point heading toward `handle1`, and arrives at
4971 `anchor` heading away from `handle2`. The path must have a point to start from.
4973 Args:
4974 handle1: The first handle, in scene coordinates.
4975 handle2: The second handle.
4976 anchor: Where the curve ends.
4978 Examples:
4979 ```python
4980 import manimgx as m
4983 class VMobjectAddCubicBezierCurveToExample(m.Scene):
4984 def construct(self) -> None:
4985 start, h1, h2, end = [-4, -2, 0], [-2, 3, 0], [2, 3, 0], [4, -2, 0]
4986 path = m.VMobject(color=m.YELLOW, stroke_width=8)
4987 path.start_new_path(start).add_cubic_bezier_curve_to(h1, h2, end)
4988 handles = m.VGroup(m.Line(start, h1), m.Line(h2, end))
4989 dots = [m.Dot(p, radius=0.12) for p in (start, h1, h2, end)]
4990 self.add(handles.set_color(m.GREY), *dots)
4991 self.play(m.Create(path, run_time=2))
4992 ```
4993 """
4994 self._require_points()
4995 new = [handle1, handle2, anchor]
4996 return self.append_points(
4997 new if self.has_new_path_started() else [self.get_last_point(), *new]
4998 )
5000 def add_cubic_bezier_curves(self, curves: Point3DLike_Array) -> Self:
5001 """Add curves after the path's own, given by their control points, four per
5002 curve: anchor, handle, handle, anchor.
5004 Args:
5005 curves: The curves' control points, in scene coordinates: an (n, 4, 3)
5006 array, or the points one after another.
5007 """
5008 return self.append_points(np.asarray(curves).reshape(-1, 3))
5010 def add_quadratic_bezier_curve_to(
5011 self, handle: Point3DLike, anchor: Point3DLike
5012 ) -> Self:
5013 """Add a quadratic Bézier curve from where the path ends to `anchor`, bending
5014 toward one handle.
5016 It is added as the cubic curve of the same shape. The path must have a point to
5017 start from.
5019 Args:
5020 handle: The handle, in scene coordinates: the curve leaves the path's last
5021 point heading toward it, and arrives at `anchor` heading away from it.
5022 anchor: Where the curve ends.
5024 Examples:
5025 ```python
5026 import manimgx as m
5029 class VMobjectAddQuadraticBezierCurveToExample(m.Scene):
5030 def construct(self) -> None:
5031 start, handle, end = [-4, -2, 0], [0, 3, 0], [4, -2, 0]
5032 path = m.VMobject(color=m.TEAL, stroke_width=8)
5033 path.start_new_path(start)
5034 path.add_quadratic_bezier_curve_to(handle, end)
5035 handles = m.VGroup(m.Line(start, handle), m.Line(handle, end))
5036 dots = [m.Dot(p, radius=0.12) for p in (start, handle, end)]
5037 self.add(handles.set_color(m.GREY), *dots)
5038 self.play(m.Create(path, run_time=2))
5039 ```
5040 """
5041 h, a, last = np.asarray(handle), np.asarray(anchor), self.get_last_point()
5042 return self.add_cubic_bezier_curve_to(
5043 2 / 3 * h + 1 / 3 * last, 2 / 3 * h + 1 / 3 * a, a
5044 )
5046 def add_line_to(self, point: Point3DLike) -> Self:
5047 """Add a straight line from where the path ends to a point.
5049 The path must have a point to start from.
5051 Args:
5052 point: Where the line ends, in scene coordinates.
5054 Examples:
5055 ```python
5056 import manimgx as m
5059 class VMobjectAddLineToExample(m.Scene):
5060 def construct(self) -> None:
5061 stairs = m.VMobject(color=m.BLUE, stroke_width=8)
5062 stairs.start_new_path([-5, -3, 0])
5063 for _ in range(5):
5064 stairs.add_line_to(stairs.get_end() + 1.2 * m.UP)
5065 stairs.add_line_to(stairs.get_end() + 2 * m.RIGHT)
5066 self.play(m.Create(stairs, run_time=3))
5067 ```
5068 """
5069 last = self.get_last_point()
5070 p = np.asarray(point, dtype=float)
5071 return self.add_cubic_bezier_curve_to(
5072 *(interpolate(last, p, t) for t in _T_VALUES[1:])
5073 )
5075 def add_smooth_curve_to(self, *points: Point3DLike) -> Self:
5076 """Add a curve that continues the path smoothly: it leaves where the path ends
5077 in the direction the path arrives there.
5079 Its first handle is the path's last handle mirrored through the path's end.
5080 Given only the anchor, the curve arrives there as the mirror image of how it
5081 leaves (mirrored across the perpendicular bisector of the line between its
5082 ends); given a second handle first, it arrives heading away from that. With no
5083 curve to continue, after [start_new_path][manimgx.VMobject.start_new_path], it
5084 is a straight line to the anchor.
5086 Args:
5087 *points: The anchor where the curve ends, or the second handle and then the
5088 anchor, in scene coordinates.
5090 Examples:
5091 ```python
5092 import manimgx as m
5095 class VMobjectAddSmoothCurveToExample(m.Scene):
5096 def construct(self) -> None:
5097 wave = m.VMobject(color=m.YELLOW, stroke_width=8)
5098 wave.start_new_path([-6, 0, 0])
5099 wave.add_cubic_bezier_curve_to([-6, 2, 0], [-4, 2, 0], [-4, 0, 0])
5100 for x in (-2, 0, 2, 4, 6):
5101 wave.add_smooth_curve_to([x, 0, 0])
5102 self.play(m.Create(wave, run_time=3))
5103 ```
5104 """
5105 if len(points) == 1:
5106 handle2, new_anchor = None, np.asarray(points[0])
5107 elif len(points) == 2:
5108 handle2, new_anchor = np.asarray(points[0]), np.asarray(points[1])
5109 else:
5110 raise ValueError("Only call add_smooth_curve_to with 1 or 2 points")
5111 if self.has_new_path_started():
5112 return self.add_line_to(new_anchor)
5113 last_h2, last_a2 = self.points[-2:]
5114 tangent = last_a2 - last_h2
5115 handle1 = last_a2 + tangent
5116 if handle2 is None: # the tangent mirrored across the ends' bisector
5117 chord = normalize(new_anchor - last_a2)
5118 handle2 = new_anchor + tangent - 2 * (tangent @ chord) * chord
5119 return self.append_points([last_a2, handle1, handle2, new_anchor])
5121 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5122 def has_new_path_started(self) -> bool:
5123 """Whether the path ends in a subpath just started: a point that begins no curve
5124 yet, where the next curve added starts.
5126 Returns:
5127 True after [start_new_path][manimgx.VMobject.start_new_path], until a curve
5128 is added.
5129 """
5130 return self._geometry.n % _NPPCC == 1
5132 @deprecated("use get_end", category=None)
5133 def get_last_point(self) -> Point3D:
5134 """The path's last point: where it ends, and where the next curve added begins.
5136 Returns:
5137 The point, in scene coordinates.
5138 """
5139 return self._geometry.point(-1)
5141 def is_closed(self) -> bool:
5142 """Whether the path ends where it starts: its first and last points coincide,
5143 within a millionth of a unit."""
5144 return self.consider_points_equals(
5145 self._geometry.point(0), self._geometry.point(-1)
5146 )
5148 def close_path(self) -> Self:
5149 """Close the path: add a straight line from where it ends back to where its last
5150 subpath starts, unless it ends where it starts.
5152 The fill closes every subpath anyway; closing one makes its stroke go all the
5153 way around.
5155 Examples:
5156 ```python
5157 import manimgx as m
5160 class VMobjectClosePathExample(m.Scene):
5161 def construct(self) -> None:
5162 corners = [[-2, -1.5, 0], [0, 1.5, 0], [2, -1.5, 0]]
5163 style = {"fill_opacity": 0.5, "stroke_width": 8}
5164 open_path = m.VMobject(color=m.GREEN, **style)
5165 closed_path = m.VMobject(color=m.YELLOW, **style)
5166 open_path.set_points_as_corners(corners)
5167 closed_path.set_points_as_corners(corners).close_path()
5168 self.add(m.VGroup(open_path, closed_path).arrange(buff=2))
5169 ```
5170 """
5171 if not self.is_closed():
5172 self.add_line_to(self.get_subpaths()[-1][0])
5173 return self
5175 def add_subpath(self, points: Point3DLike_Array) -> Self:
5176 """Add curves after the path's own, by their control points, four per curve: a
5177 new subpath, unless they start where the path ends.
5179 Args:
5180 points: The curves' control points, in scene coordinates.
5181 """
5182 return self.append_points(points)
5184 def append_vectorized_mobject(self, vmobject: "VMobject") -> Self:
5185 """Add another path's curves after this path's own: its points, not its
5186 submobjects.
5188 A subpath just started and given no curve yet (see
5189 [start_new_path][manimgx.VMobject.start_new_path]) is dropped for them.
5191 Args:
5192 vmobject: The path whose points to add.
5193 """
5194 if self.has_new_path_started(): # its start begins the path that was begun
5195 self.points = self.points[:-1]
5196 return self.append_points(vmobject.points)
5198 def add_points_as_corners(self, points: Point3DLike_Array) -> Self:
5199 """Add straight lines from where the path ends through each point in turn.
5201 The path must have a point to start from.
5203 Args:
5204 points: The corners, in scene coordinates, in order: the path then ends at
5205 the last.
5206 """
5207 self._require_points()
5208 pts = np.asarray(points, dtype=float).reshape(-1, self.dim)
5209 if len(pts) == 0:
5210 return self
5211 starts = np.vstack([self.points[-1:], pts[:-1]])
5212 if self.has_new_path_started():
5213 self.points = self.points[:-1]
5214 new = np.empty((_NPPCC * len(starts), self.dim))
5215 for i, t in enumerate(_T_VALUES):
5216 new[i::_NPPCC] = interpolate(starts, pts, t)
5217 return self.append_points(new)
5219 def set_points_as_corners(self, points: Point3DLike_Array) -> Self:
5220 """Give the path new points, in place of its own: straight lines through the
5221 given points in turn.
5223 The path is open: to close it, end with its first point again.
5225 Args:
5226 points: The corners, in scene coordinates, in order.
5228 Examples:
5229 ```python
5230 import manimgx as m
5233 class VMobjectSetPointsAsCornersExample(m.Scene):
5234 def construct(self) -> None:
5235 zigzag = m.VMobject(color=m.YELLOW, stroke_width=8)
5236 zigzag.set_points_as_corners(
5237 [[-3, -1.5, 0], [-1.5, 1.5, 0], [0, -1.5, 0], [1.5, 1.5, 0]]
5238 )
5239 triangle = m.VMobject(color=m.BLUE, fill_opacity=0.5)
5240 triangle.set_points_as_corners(
5241 [[-2, -1.5, 0], [0, 2, 0], [2, -1.5, 0], [-2, -1.5, 0]]
5242 )
5243 self.add(m.VGroup(zigzag, triangle).arrange(buff=2))
5244 ```
5245 """
5246 pts = np.asarray(points, dtype=float)
5247 if len(pts) == 2: # a segment: the one segment, placed
5248 self._geometry = segment(pts[0], pts[1])
5249 return self
5250 return self.set_anchors_and_handles(
5251 *(interpolate(pts[:-1], pts[1:], t) for t in _T_VALUES)
5252 )
5254 def set_points_smoothly(self, points: Point3DLike_Array) -> Self:
5255 """Give the path new points, in place of its own: a smooth curve through the
5256 given points in turn.
5258 The curve passes through each point, bending smoothly there, with no change of
5259 curvature (a cubic spline); if the last point is the first, it closes smoothly.
5261 Args:
5262 points: The points it passes through, in scene coordinates, in order.
5264 Examples:
5265 ```python
5266 import manimgx as m
5269 class VMobjectSetPointsSmoothlyExample(m.Scene):
5270 def construct(self) -> None:
5271 points = [[-5, -1, 0], [-3, 2, 0], [-1, -2, 0], [1, 2, 0]]
5272 points += [[3, -1, 0], [5, 1, 0]]
5273 corners = m.VMobject(color=m.GREY).set_points_as_corners(points)
5274 curve = m.VMobject(color=m.YELLOW, stroke_width=8)
5275 curve.set_points_smoothly(points)
5276 self.add(corners, *(m.Dot(p, radius=0.12) for p in points))
5277 self.play(m.Create(curve, run_time=2))
5278 ```
5279 """
5280 self.set_points_as_corners(points)
5281 return self.make_smooth()
5283 @deprecated("use make_smooth or make_jagged", category=None)
5284 def change_anchor_mode(self, mode: Literal["jagged", "smooth"]) -> Self:
5285 """Set anew the handles of every subpath in the family, for a smooth curve
5286 through its anchors or straight lines between them; the anchors stay.
5288 Args:
5289 mode: "smooth" for a smooth curve (see
5290 [make_smooth][manimgx.VMobject.make_smooth]); "jagged" for straight
5291 lines ([make_jagged][manimgx.VMobject.make_jagged]).
5292 """
5293 for sub in self.family_members_with_points():
5294 assert isinstance(sub, VMobject)
5295 subpaths = sub.get_subpaths()
5296 sub.clear_points()
5297 for subpath in subpaths:
5298 anchors = np.append(subpath[::_NPPCC], subpath[-1:], 0)
5299 if mode == "smooth":
5300 h1, h2 = get_smooth_cubic_bezier_handle_points(anchors)
5301 else:
5302 h1, h2 = (
5303 interpolate(anchors[:-1], anchors[1:], 1 / 3),
5304 interpolate(anchors[:-1], anchors[1:], 2 / 3),
5305 )
5306 new = np.array(subpath)
5307 new[1::_NPPCC], new[2::_NPPCC] = h1, h2
5308 sub.append_points(new)
5309 return self
5311 def make_smooth(self) -> Self:
5312 """Make every subpath in the family a smooth curve through its anchors, with no
5313 change of curvature at any (a cubic spline); a closed subpath closes smoothly.
5315 The anchors stay and the handles move: a polygon becomes a rounded loop through
5316 its corners.
5318 Examples:
5319 ```python
5320 import manimgx as m
5323 class VMobjectMakeSmoothExample(m.Scene):
5324 def construct(self) -> None:
5325 square = m.Square(side_length=4, color=m.BLUE, stroke_width=8)
5326 self.add(square.copy().set_stroke(m.GREY, 3))
5327 self.play(square.animate.make_smooth(), run_time=2)
5328 ```
5329 """
5330 return self.change_anchor_mode("smooth")
5332 def make_jagged(self) -> Self:
5333 """Make every subpath in the family straight lines between its anchors: a curve
5334 through points becomes the polygon through them.
5335 """
5336 return self.change_anchor_mode("jagged")
5338 def _map_points(
5339 self, function: Callable[[Point3D], Point3D], about: np.ndarray
5340 ) -> None:
5341 """This leaf's image under `function` (about `about`): each curve its image, to within
5342 `_IMAGE_TOLERANCE`. A cubic's image is the cubic through the images of its ends along
5343 the images of its tangents (its handles shrunk by
5344 `pre_function_handle_to_anchor_scale_factor`, mapped, and grown back); where that is
5345 not within the tolerance of the true image a third and two thirds of the way along
5346 it, every cubic of the leaf is cut into 2, 4, … equal pieces first: the same number
5347 for all, so a tween from the leaf as it was (cut to match by `align_points`) moves
5348 each point straight to its image."""
5350 def image(points: np.ndarray) -> np.ndarray:
5351 return np.apply_along_axis(function, 1, points - about) + about
5353 n = len(self.points) // _NPPCC * _NPPCC
5354 if n == 0:
5355 super()._map_points(function, about)
5356 return
5357 factor = self.pre_function_handle_to_anchor_scale_factor
5358 curves = self.points[:n].reshape(-1, _NPPCC, 3)
5359 for depth in range(_IMAGE_MAX_DEPTH + 1):
5360 pieces = (
5361 curves if depth == 0 else bezier_remap(curves, len(curves) << depth)
5362 )
5363 k = len(pieces)
5364 a1, h1, h2, a2 = (pieces[:, i] for i in range(_NPPCC))
5365 # where the path runs on, a piece's end is the next one's start: mapped once
5366 loose = np.ones(k, dtype=bool)
5367 loose[:-1] = np.any(a2[:-1] != a1[1:], axis=1)
5368 mapped = image(
5369 np.concatenate(
5370 (
5371 a1,
5372 a1 + factor * (h1 - a1),
5373 a2 + factor * (h2 - a2),
5374 a2[loose],
5375 _checked(pieces).reshape(-1, 3),
5376 )
5377 )
5378 )
5379 b1 = mapped[:k]
5380 b2 = np.empty_like(b1)
5381 b2[:-1] = b1[1:]
5382 b2[loose] = mapped[3 * k : -2 * k]
5383 result = np.stack(
5384 (
5385 b1,
5386 b1 + (1.0 / factor) * (mapped[k : 2 * k] - b1),
5387 b2 + (1.0 / factor) * (mapped[2 * k : 3 * k] - b2),
5388 b2,
5389 ),
5390 axis=1,
5391 )
5392 with np.errstate(invalid="ignore"): # a map that blows up: nan, refined on
5393 true = mapped[-2 * k :].reshape(k, 2, 3)
5394 stray = np.linalg.norm(true - _checked(result), axis=2).max()
5395 if depth == _IMAGE_MAX_DEPTH or stray <= _IMAGE_TOLERANCE:
5396 break
5397 tail = self.points[n:] # a path just started: its point
5398 self.points = np.concatenate(
5399 (result.reshape(-1, 3), image(tail) if len(tail) else tail)
5400 )
5401 if self.make_smooth_after_applying_functions:
5402 self.make_smooth()
5404 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5405 def scale_handle_to_anchor_distances(self, factor: float) -> Self:
5406 """Move the handles of every path in the family toward their anchors, or away
5407 from them, scaling their distances by a factor.
5409 The curves flatten toward straight lines (below 1) or bulge (above 1); the
5410 anchors stay.
5412 Args:
5413 factor: The factor: 0 makes each curve a straight line between its anchors,
5414 1 leaves it as it is.
5415 """
5416 for sub in self.family_members_with_points():
5417 if len(sub.points) < _NPPCC or not isinstance(sub, VMobject):
5418 continue
5419 a1, h1, h2, a2 = sub.get_anchors_and_handles()
5420 sub.set_anchors_and_handles(
5421 a1, a1 + factor * (h1 - a1), a2 + factor * (h2 - a2), a2
5422 )
5423 return self
5425 # ── curves and subpaths ───────────────────────────────────────────────
5426 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5427 def consider_points_equals(self, p0: Point3DLike, p1: Point3DLike) -> bool:
5428 """Whether two points count as one: equal within
5429 [tolerance_for_point_equality][manimgx.VMobject.tolerance_for_point_equality].
5431 Args:
5432 p0: A point.
5433 p1: Another point.
5434 """
5435 return bool(np.allclose(p0, p1, atol=self.tolerance_for_point_equality))
5437 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5438 def get_cubic_bezier_tuples_from_points(self, points: Point3D_Array) -> np.ndarray:
5439 """Split control points into curves, four points each; an unfinished last curve
5440 is left out.
5442 Args:
5443 points: The control points: an (n, 3) array.
5445 Returns:
5446 The curves, as an array of shape (curves, 4, 3).
5447 """
5448 n = len(points) - len(points) % _NPPCC
5449 return np.asarray(points[:n]).reshape(
5450 -1, _NPPCC, points.shape[1] if len(points) else 3
5451 )
5453 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5454 def get_cubic_bezier_tuples(self) -> np.ndarray:
5455 """The path's curves, by their control points.
5457 Returns:
5458 An array of shape (curves, 4, 3), each curve's anchor, two handles and
5459 anchor.
5460 """
5461 return self.get_cubic_bezier_tuples_from_points(self.points)
5463 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5464 def get_subpaths_from_points(self, points: Point3D_Array) -> list[Point3D_Array]:
5465 """Split control points into subpaths: a subpath starts wherever a curve does
5466 not begin where the one before it ends.
5468 Args:
5469 points: The control points, four per curve: an (n, 3) array.
5471 Returns:
5472 The subpaths, each an array of its control points.
5473 """
5474 return [
5475 points[a:b]
5476 for a, b, _ in subpath_ranges(points, self.tolerance_for_point_equality)
5477 ]
5479 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5480 def consider_points_equals_2d(self, p0: Point3DLike, p1: Point3DLike) -> bool:
5481 """Whether two points count as one seen along the z axis: their x and y
5482 coordinates equal within
5483 [tolerance_for_point_equality][manimgx.VMobject.tolerance_for_point_equality].
5485 Args:
5486 p0: A point.
5487 p1: Another point.
5488 """
5489 return bool(
5490 np.allclose(
5491 np.asarray(p0)[:2],
5492 np.asarray(p1)[:2],
5493 atol=self.tolerance_for_point_equality,
5494 )
5495 )
5497 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5498 def gen_cubic_bezier_tuples_from_points(
5499 self, points: Point3D_Array
5500 ) -> tuple[Point3D_Array, ...]:
5501 """Split control points into curves, four points each; an unfinished last curve
5502 is left out.
5504 Args:
5505 points: The control points: an (n, 3) array.
5507 Returns:
5508 The curves, each a (4, 3) array.
5509 """
5510 n = len(points) - len(points) % _NPPCC
5511 return tuple(points[i : i + _NPPCC] for i in range(0, n, _NPPCC))
5513 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5514 def gen_subpaths_from_points_2d(
5515 self, points: Point3D_Array
5516 ) -> Iterator[Point3D_Array]:
5517 """Split control points into subpaths, comparing points by their x and y only: a
5518 subpath starts wherever a curve does not begin where the one before it ends.
5520 Args:
5521 points: The control points, four per curve: an (n, 3) array.
5523 Returns:
5524 The subpaths, one after another, each an array of its control points.
5525 """
5526 return (
5527 points[a:b]
5528 for a, b, _ in subpath_ranges(
5529 points, self.tolerance_for_point_equality, dims=2
5530 )
5531 )
5533 def get_subpaths(self) -> list[Point3D_Array]:
5534 """The path's subpaths: a subpath starts wherever a curve does not begin where
5535 the one before it ends.
5537 Returns:
5538 The subpaths, each an array of its control points, four per curve.
5539 """
5540 return self.get_subpaths_from_points(self.points)
5542 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5543 def get_nth_curve_points(self, n: int) -> Point3D_Array:
5544 """The control points of one of the path's curves.
5546 Args:
5547 n: Which curve, counting from 0.
5549 Returns:
5550 Its anchor, two handles and anchor, as a (4, 3) array.
5551 """
5552 return self.points[_NPPCC * n : _NPPCC * (n + 1)]
5554 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5555 def get_nth_curve_function(self, n: int) -> Callable[[float], Point3D]:
5556 """One of the path's curves, as a function from 0, its start, to 1, its end.
5558 Args:
5559 n: Which curve, counting from 0.
5561 Returns:
5562 A function of the curve's parameter, from 0 to 1, giving its point there.
5563 """
5564 return bezier(self.get_nth_curve_points(n))
5566 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5567 def get_nth_curve_length_pieces(
5568 self, n: int, sample_points: int | None = None
5569 ) -> np.ndarray:
5570 """The lengths of the straight pieces between points along one of the path's
5571 curves, taken at evenly spaced values of its parameter.
5573 Args:
5574 n: Which curve, counting from 0.
5575 sample_points: How many points to take, its ends included; None for 10,
5576 the path's own measure (the one its reveals and proportions go by).
5578 Returns:
5579 The pieces' lengths, in scene units, one fewer than the points.
5580 """
5581 if sample_points in (None, 10): # the path's own, measured once
5582 return self._geometry.piece_lengths()[n].copy()
5583 curve = self.get_nth_curve_function(n)
5584 pts = np.array([curve(a) for a in np.linspace(0, 1, sample_points)])
5585 return np.linalg.norm(np.diff(pts, axis=0), axis=1)
5587 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5588 def get_nth_curve_length(self, n: int, sample_points: int | None = None) -> float:
5589 """The length of one of the path's curves, measured along straight pieces
5590 between points on it.
5592 Args:
5593 n: Which curve, counting from 0.
5594 sample_points: How many points to measure through, its ends included (evenly
5595 spaced in its parameter); None for 10.
5597 Returns:
5598 The length, in scene units.
5599 """
5600 return float(np.sum(self.get_nth_curve_length_pieces(n, sample_points)))
5602 def get_num_curves(self) -> int:
5603 """How many curves the path has: its points, four per curve.
5605 Returns:
5606 The number of curves.
5607 """
5608 return self._geometry.n // _NPPCC
5610 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5611 def get_curve_functions_with_lengths(
5612 self, sample_points: int | None = None
5613 ) -> Iterator[tuple[Callable[[float], Point3D], float]]:
5614 """Each of the path's curves, as a function, with its length.
5616 Args:
5617 sample_points: How many points each curve's length is measured through (see
5618 [get_nth_curve_length][manimgx.VMobject.get_nth_curve_length]); None for
5619 10.
5621 Yields:
5622 Each curve's function of its parameter, from 0 to 1, and its length in scene
5623 units.
5624 """
5625 for n in range(self.get_num_curves()):
5626 yield (
5627 self.get_nth_curve_function(n),
5628 self.get_nth_curve_length(n, sample_points),
5629 )
5631 def point_from_proportion(self, alpha: float) -> Point3D:
5632 """The point a proportion of the way along the path, by length: 0 is its start,
5633 1 its end.
5635 The length is the path's own measure, the one a reveal draws by (nine straight
5636 pieces per curve), so it is where a [Create][manimgx.Create] at that proportion
5637 has drawn to, and a [MoveAlongPath][manimgx.MoveAlongPath] moves at a steady
5638 speed. Raises an exception if `alpha` is outside [0, 1] or the path has no
5639 points.
5641 Args:
5642 alpha: The proportion, from 0 to 1.
5644 Returns:
5645 The point, in scene coordinates.
5647 Examples:
5648 ```python
5649 import manimgx as m
5652 class VMobjectPointFromProportionExample(m.Scene):
5653 def construct(self) -> None:
5654 points = [[-5, -2, 0], [-2, 2, 0], [1, -1, 0], [5, 2, 0]]
5655 curve = m.VMobject(color=m.BLUE, stroke_width=6)
5656 curve.set_points_smoothly(points)
5657 self.add(curve)
5658 for alpha in (0, 0.25, 0.5, 0.75, 1):
5659 point = curve.point_from_proportion(alpha)
5660 dot = m.Dot(point, radius=0.15, color=m.YELLOW)
5661 label = m.Text(str(alpha), font_size=32).next_to(dot, m.DOWN)
5662 self.add(dot, label)
5663 ```
5664 """
5665 if alpha < 0 or alpha > 1:
5666 raise ValueError(f"Alpha {alpha} not between 0 and 1.")
5667 self._require_points()
5668 curves = self.get_num_curves()
5669 if curves == 0: # a point, or a subpath just started
5670 return self.points[-1]
5671 at = self._geometry.parameter_at(alpha)
5672 n = min(int(at), curves - 1)
5673 return self.get_nth_curve_function(n)(at - n)
5675 def get_arc_length(self, sample_points_per_curve: int | None = None) -> float:
5676 """The path's length: the sum of its curves' lengths, each measured along
5677 straight pieces between points on it.
5679 Args:
5680 sample_points_per_curve: How many points each curve is measured through, its
5681 ends included; None for 10, the path's own measure.
5683 Returns:
5684 The length, in scene units.
5685 """
5686 if sample_points_per_curve in (None, 10):
5687 return float(self._geometry.curve_lengths().sum())
5688 return sum(
5689 length
5690 for _, length in self.get_curve_functions_with_lengths(
5691 sample_points_per_curve
5692 )
5693 )
5695 @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
5696 def get_anchors_and_handles(self) -> list[Point3D_Array]:
5697 """The path's control points, kind by kind: its curves' first anchors, first
5698 handles, second handles and second anchors.
5700 Returns:
5701 Four arrays, one row per curve, in the order
5702 [set_anchors_and_handles][manimgx.VMobject.set_anchors_and_handles] takes
5703 them.
5704 """
5705 return [self.points[i::_NPPCC] for i in range(_NPPCC)]
5707 @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
5708 def get_start_anchors(self) -> Point3D_Array:
5709 """Where each of the path's curves starts.
5711 Returns:
5712 An array of one point per curve, in scene coordinates.
5713 """
5714 return self.points[::_NPPCC]
5716 @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
5717 def get_end_anchors(self) -> Point3D_Array:
5718 """Where each of the path's curves ends.
5720 Returns:
5721 An array of one point per curve, in scene coordinates.
5722 """
5723 return self.points[_NPPCC - 1 :: _NPPCC]
5725 def get_anchors(self) -> Point3D_Array:
5726 """The path's anchors, curve by curve: each curve's start, then its end, so an
5727 anchor two curves share is listed twice.
5729 Returns:
5730 An array of points, in scene coordinates; for a path of one point, that
5731 point.
5732 """
5733 if self.points.shape[0] == 1:
5734 return self.points
5735 s, e = self.get_start_anchors(), self.get_end_anchors()
5736 out = np.empty((len(s) + len(e), self.dim))
5737 out[0::2], out[1::2] = s, e
5738 return out
5740 # ── the Path kind's alignment and partial rules ────────────────────────
5741 def align_points(self, mobject: Mobject) -> Self:
5742 self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
5743 if (
5744 not isinstance(mobject, VMobject)
5745 or self.get_num_points() == mobject.get_num_points()
5746 ):
5747 return self
5748 vmobject = mobject
5749 for mob in (self, vmobject):
5750 if mob.has_no_points():
5751 mob.start_new_path(mob.get_center())
5752 if mob.has_new_path_started():
5753 mob.add_line_to(mob.get_last_point())
5754 subpaths1, subpaths2 = self.get_subpaths(), vmobject.get_subpaths()
5755 new1, new2 = [], []
5757 def nth(paths: list[Point3D_Array], n: int) -> Point3D_Array:
5758 """Subpath n without its trailing null curves (a curve all at the point before it)
5759 — but its first — or its last point, held, when it has no subpath n."""
5760 if n >= len(paths):
5761 return np.tile(paths[-1][-1] if paths else np.zeros(3), (_NPPCC, 1))
5762 path = paths[n]
5763 k = len(path) // _NPPCC
5764 if k > 1:
5765 curves = path[: k * _NPPCC].reshape(k, _NPPCC, -1)[1:]
5766 before = path[_NPPCC - 1 : (k - 1) * _NPPCC : _NPPCC][:, None]
5767 null = np.all( # np.allclose, curve by curve
5768 np.abs(curves - before)
5769 <= self.tolerance_for_point_equality + 1e-5 * np.abs(before),
5770 axis=(1, 2),
5771 )
5772 kept = len(null) - int(np.argmin(null[::-1])) if not null.all() else 0
5773 path = path[: (kept + 1) * _NPPCC]
5774 return path
5776 for n in range(max(len(subpaths1), len(subpaths2))):
5777 sp1, sp2 = nth(subpaths1, n), nth(subpaths2, n)
5778 new1.append(
5779 self.insert_n_curves_to_point_list(
5780 max(0, (len(sp2) - len(sp1)) // _NPPCC), sp1
5781 )
5782 )
5783 new2.append(
5784 self.insert_n_curves_to_point_list(
5785 max(0, (len(sp1) - len(sp2)) // _NPPCC), sp2
5786 )
5787 )
5788 self.set_points(np.concatenate(new1))
5789 vmobject.set_points(np.concatenate(new2))
5790 return self
5792 def align_points_with_larger(self, larger: Mobject) -> Self:
5793 return self.align_points(larger)
5795 def insert_n_curves(self, n: int) -> Self:
5796 """Divide the path's curves into more curves, its shape unchanged.
5798 Each curve is split into equal stretches of its parameter, the new curves
5799 spread among the curves as evenly as can be (curve i of m gets the new curves j
5800 of n with j·m // n = i): the way a transform gives two paths as many curves as
5801 each other.
5803 Args:
5804 n: How many curves to add.
5805 """
5806 new_path_point = self.get_last_point() if self.has_new_path_started() else None
5807 self.set_points(self.insert_n_curves_to_point_list(n, self.points))
5808 if new_path_point is not None:
5809 self.append_points([new_path_point])
5810 return self
5812 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5813 def insert_n_curves_to_point_list(
5814 self, n: int, points: Point3D_Array
5815 ) -> Point3D_Array:
5816 """Divide the curves of a list of control points into more curves, their shape
5817 unchanged (see [insert_n_curves][manimgx.VMobject.insert_n_curves]).
5819 Args:
5820 n: How many curves to add.
5821 points: The control points, four per curve; a single point gives `n` curves
5822 of no length at it.
5824 Returns:
5825 The new control points.
5826 """
5827 if len(points) == 1:
5828 return np.repeat(points, _NPPCC * n, 0)
5829 tuples = self.get_cubic_bezier_tuples_from_points(points)
5830 return bezier_remap(tuples, len(tuples) + n).reshape(-1, 3)
5832 def reveal_pace(self) -> tuple[np.ndarray, np.ndarray]:
5833 return self._geometry.pace()
5835 def get_point_mobject(self, center: Point3DLike | None = None) -> "VectorizedPoint":
5836 point = VectorizedPoint(self.get_center() if center is None else center)
5837 point.match_style(self)
5838 return point
5840 def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
5841 vmobject = mobject
5842 if a <= 0 and b >= 1:
5843 return self.set_points(vmobject.points)
5844 num_curves = len(vmobject.points) // _NPPCC
5845 if num_curves == 0:
5846 return self
5847 lo, lo_res = integer_interpolate(0, num_curves, a)
5848 hi, hi_res = integer_interpolate(0, num_curves, b)
5849 src = vmobject.points.copy() if self is vmobject else vmobject.points
5850 n = _NPPCC
5851 if lo == hi:
5852 self.points = partial_bezier_points(
5853 src[n * lo : n * (lo + 1)], lo_res, hi_res
5854 )
5855 else:
5856 pts = np.empty((n * (hi - lo + 1), self.dim))
5857 pts[:n] = partial_bezier_points(src[n * lo : n * (lo + 1)], lo_res, 1)
5858 pts[n:-n] = src[n * (lo + 1) : n * hi]
5859 pts[-n:] = partial_bezier_points(src[n * hi : n * (hi + 1)], 0, hi_res)
5860 self.points = pts
5861 return self
5863 def get_subcurve(self, a: float, b: float) -> Self:
5864 """A copy of the path cut down to its part from proportion `a` of the way along
5865 it to proportion `b`.
5867 The proportions go by the path's curves, each an equal share whatever its
5868 length, and along each curve by its parameter
5869 ([point_from_proportion][manimgx.VMobject.point_from_proportion] goes by
5870 length). The copy's submobjects are copied whole.
5872 Args:
5873 a: Where the part starts, from 0 to 1.
5874 b: Where it ends, from `a` to 1.
5876 Returns:
5877 A new path.
5879 Examples:
5880 ```python
5881 import manimgx as m
5884 class VMobjectGetSubcurveExample(m.Scene):
5885 def construct(self) -> None:
5886 circle = m.Circle(radius=2.5, color=m.GREY)
5887 half = circle.get_subcurve(0.25, 0.75).set_stroke(m.YELLOW, 12)
5888 self.add(circle)
5889 self.play(m.Create(half))
5890 ```
5891 """
5892 return self.copy().pointwise_become_partial(self, a, b)
5894 def get_direction(self) -> str:
5895 """Which way the path turns: "CW" (clockwise) or "CCW" (counterclockwise), by
5896 the sign of the area its curves' start anchors enclose.
5898 Returns:
5899 "CW" or "CCW".
5900 """
5901 return shoelace_direction(self.get_start_anchors())
5903 def reverse_direction(self) -> Self:
5904 """Reverse the order of the path's own points, so it runs the other way: from
5905 its end to its start.
5907 Its submobjects stay as they are. A drawing animation then draws it the other
5908 way, and a subpath inside another cuts
5909 a hole in the fill only if the two run opposite ways.
5911 Examples:
5912 ```python
5913 import manimgx as m
5916 class VMobjectReverseDirectionExample(m.Scene):
5917 def construct(self) -> None:
5918 outer, inner = m.Square(side_length=4), m.Square(side_length=2)
5919 same = m.VMobject(color=m.BLUE, fill_opacity=0.8)
5920 same.append_vectorized_mobject(outer)
5921 same.append_vectorized_mobject(inner)
5922 opposite = m.VMobject(color=m.YELLOW, fill_opacity=0.8)
5923 opposite.append_vectorized_mobject(outer)
5924 opposite.append_vectorized_mobject(inner.reverse_direction())
5925 self.add(m.VGroup(same, opposite).arrange(buff=2))
5926 ```
5927 """
5928 self.points = self.points[::-1].copy()
5929 return self
5931 def force_direction(self, target_direction: Literal["CW", "CCW"]) -> Self:
5932 """Make the path run clockwise or counterclockwise: reverse it if it runs the
5933 other way (see [get_direction][manimgx.VMobject.get_direction]).
5935 Args:
5936 target_direction: "CW" for clockwise, "CCW" for counterclockwise.
5937 """
5938 if self.get_direction() != target_direction:
5939 self.reverse_direction()
5940 return self
5942 @overload
5943 def get_style(self, simple: Literal[True]) -> SimpleStyle: ...
5944 @overload
5945 def get_style(self, simple: Literal[False] = False) -> StyleSnapshot: ...
5946 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5947 def get_style(self, simple: bool = False) -> SimpleStyle | StyleSnapshot:
5948 """The path's own style, as keywords: `set_style(**style)` gives it back.
5950 Args:
5951 simple: Whether to give only the first color and opacity of the fill and
5952 the stroke, and the stroke's width, in place of every color (each stop
5953 of a gradient) of the fill, stroke and background stroke, their widths
5954 and the sheen.
5956 Returns:
5957 A dictionary of [set_style][manimgx.Mobject.set_style]'s keywords.
5958 """
5959 if simple:
5960 return SimpleStyle(
5961 fill_color=self.get_fill_color(),
5962 fill_opacity=self.get_fill_opacity(),
5963 stroke_color=self.get_stroke_color(),
5964 stroke_opacity=self.get_stroke_opacity(),
5965 stroke_width=self.get_stroke_width(),
5966 )
5967 p = self.paint
5968 return StyleSnapshot(
5969 fill_color=[ManimColor(c[:3]) for c in p.fill],
5970 fill_opacity=[float(c[3]) for c in p.fill],
5971 stroke_color=[ManimColor(c[:3]) for c in p.stroke],
5972 stroke_opacity=[float(c[3]) for c in p.stroke],
5973 stroke_width=self.get_stroke_width(),
5974 background_stroke_color=[ManimColor(c[:3]) for c in p.background],
5975 background_stroke_opacity=[float(c[3]) for c in p.background],
5976 background_stroke_width=self.get_stroke_width(background=True),
5977 sheen_factor=self.paint.sheen_factor,
5978 sheen_direction=self.get_sheen_direction(),
5979 )
5981 @staticmethod
5982 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
5983 def get_mobject_type_class() -> type[Mobject]:
5984 """The class of the paths' kind: `VMobject`, whatever a path's own class.
5986 Returns:
5987 [VMobject][manimgx.VMobject].
5988 """
5989 return VMobject
5991 def proportion_from_point(
5992 self, point: Point3DLike, tolerance: float = 1e-6
5993 ) -> float:
5994 """How far along the path a point on it lies, by length: the inverse of
5995 [point_from_proportion][manimgx.VMobject.point_from_proportion].
5997 The first curve the point lies on counts. Raises an exception if the point is
5998 not on the path.
6000 Args:
6001 point: The point, in scene coordinates.
6002 tolerance: How near the path the point must be: within 100 times this, in
6003 scene units, along each axis.
6005 Returns:
6006 The proportion, from 0 (the path's start) to 1 (its end).
6007 """
6008 p = np.asarray(point, dtype=float)
6009 for n in range(self.get_num_curves()):
6010 curve = self.get_nth_curve_points(n)
6011 dim = int(
6012 np.argmax(np.ptp(curve, axis=0))
6013 ) # solve along the curve's widest coordinate, then check all
6014 c = [
6015 curve[0],
6016 3 * (curve[1] - curve[0]),
6017 3 * (curve[2] - 2 * curve[1] + curve[0]),
6018 curve[3] - 3 * curve[2] + 3 * curve[1] - curve[0],
6019 ]
6020 coeffs = np.array([ci[dim] for ci in c])
6021 coeffs[0] -= p[dim]
6022 roots = [
6023 r.real
6024 for r in (
6025 np.polynomial.Polynomial(coeffs).roots()
6026 if coeffs[1:].any()
6027 else [0.0] # constant along its widest coordinate: a point
6028 )
6029 # candidates, each checked below: a double root (a stationary end) comes
6030 # back as a complex pair with parts near √ε
6031 if abs(r.imag) < 1e-4 and -1e-4 <= r.real <= 1 + 1e-4
6032 ]
6033 hits = [
6034 t
6035 for t in roots
6036 if np.allclose(
6037 bezier(curve)(min(max(t, 0), 1)), p, atol=tolerance * 100
6038 )
6039 ]
6040 if hits: # by the path's own measure: the inverse of point_from_proportion
6041 return self._geometry.fraction_at(n + min(max(max(hits), 0.0), 1.0))
6042 raise ValueError(f"Point {point} does not lie on this curve.")
6045VGroup = Group # a group is a group: kinds belong to leaves
6046"""Another name for [Group][manimgx.Group], which holds mobjects of any kind."""
6049class VectorizedPoint(VMobject):
6050 """A path of one point: unseen, a place to put things by, or to grow them from.
6052 It is black, with no stroke and no fill. Its width and height are numbers of its
6053 own, not measured from its point.
6055 Args:
6056 location: Where the point is, in scene coordinates.
6057 artificial_width: The width it reports, in scene units.
6058 artificial_height: The height it reports, in scene units.
6060 Examples:
6061 ```python
6062 import manimgx as m
6065 class VectorizedPointExample(m.Scene):
6066 def construct(self) -> None:
6067 point = m.VectorizedPoint(4 * m.LEFT)
6068 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
6069 self.play(m.ReplacementTransform(point, square.shift(2 * m.RIGHT)))
6070 ```
6071 """
6073 defaults: ClassVar[Style] = {"color": BLACK, "fill_opacity": 0.0, "stroke_width": 0}
6075 def __init__(
6076 self,
6077 location: Point3DLike = ORIGIN,
6078 artificial_width: float = 0.01,
6079 artificial_height: float = 0.01,
6080 **kwargs: Unpack[Style],
6081 ) -> None:
6082 self.artificial_width = artificial_width
6083 self.artificial_height = artificial_height
6084 super().__init__(**kwargs)
6085 self.set_points(np.array([location], dtype=float))
6087 @property
6088 def width(self) -> float:
6089 """The point's width, in scene units: its `artificial_width`, not measured.
6090 Setting it changes that number and nothing else."""
6091 return self.artificial_width
6093 @width.setter
6094 def width(self, value: float) -> None:
6095 self.artificial_width = value
6097 @property
6098 def height(self) -> float:
6099 """The point's height, in scene units: its `artificial_height`, not measured.
6100 Setting it changes that number and nothing else."""
6101 return self.artificial_height
6103 @height.setter
6104 def height(self, value: float) -> None:
6105 self.artificial_height = value
6107 @deprecated("use get_center", category=None)
6108 def get_location(self) -> Point3D:
6109 """Where the point is.
6111 Returns:
6112 A copy of the point, in scene coordinates.
6113 """
6114 return np.array(self.points[0])
6116 @deprecated("use move_to", category=None)
6117 def set_location(self, new_loc: Point3DLike) -> Self:
6118 """Move the point.
6120 Args:
6121 new_loc: Where it goes, in scene coordinates.
6122 """
6123 return self.set_points(np.array([new_loc], dtype=float))
6126class VDict[T: Mobject = Mobject](Mobject):
6127 """A group whose members have keys, as a dictionary has: `vdict[key]` is a member.
6129 Members of any kind are added, replaced (`vdict[key] = mobject`) and removed by key;
6130 like any group, it draws, moves and styles them together, in the order they were
6131 added. With `show_keys`, each member is labeled with its key.
6133 Args:
6134 mapping_or_iterable: The first members: a dictionary of keys and mobjects, or
6135 (key, mobject) pairs.
6136 show_keys: Whether each member, added now or later, is labeled with its key: a
6137 [Tex][manimgx.Tex] of `str(key)` at its left, added to the member itself,
6138 so the label moves, animates and leaves with it, and counts in its size.
6139 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself: as it
6140 has no points, they do not restyle its members (the style methods do).
6142 Examples:
6143 ```python
6144 import manimgx as m
6147 class VDictExample(m.Scene):
6148 def construct(self) -> None:
6149 shapes = m.VDict(
6150 {
6151 "circle": m.Circle(radius=0.9, color=m.RED),
6152 "square": m.Square(side_length=1.8, color=m.GREEN),
6153 },
6154 show_keys=True,
6155 )
6156 shapes["triangle"] = m.Triangle(color=m.BLUE)
6157 self.add(shapes.arrange(buff=1))
6158 self.play(shapes["square"].animate.set_color(m.YELLOW))
6159 ```
6160 """
6162 @overload # `VDict({...})`: members of any kinds
6163 def __init__[Key: Hashable](
6164 self: "VDict[Mobject]",
6165 mapping_or_iterable: (
6166 Mapping[Key, Mobject] | Iterable[tuple[Key, Mobject]]
6167 ) = {},
6168 show_keys: bool = False,
6169 **kwargs: Unpack[Style],
6170 ) -> None: ...
6171 @overload # `VDict[Circle]({...})`: declared
6172 def __init__[Key: Hashable](
6173 self,
6174 mapping_or_iterable: Mapping[Key, T] | Iterable[tuple[Key, T]] = {},
6175 show_keys: bool = False,
6176 **kwargs: Unpack[Style],
6177 ) -> None: ...
6178 def __init__[Key: Hashable](
6179 self,
6180 mapping_or_iterable: Mapping[Key, T] | Iterable[tuple[Key, T]] = {},
6181 show_keys: bool = False,
6182 **kwargs: Unpack[Style],
6183 ) -> None:
6184 super().__init__(**kwargs)
6185 self.show_keys = show_keys
6186 self.submob_dict: dict[Hashable, T] = {}
6187 """The members, by key."""
6188 self.add(mapping_or_iterable)
6190 def add[Key: Hashable]( # ty: ignore[invalid-method-override] # CE's: by key
6191 self, mapping_or_iterable: Mapping[Key, T] | Iterable[tuple[Key, T]]
6192 ) -> Self:
6193 """Add members by key, after the group's.
6195 Each is labeled with its key if the group shows its keys. A key the group has already
6196 is given the new mobject, but the old one stays in the group: to replace a
6197 member, set it (`vdict[key] = mobject`).
6199 Args:
6200 mapping_or_iterable: A dictionary of keys and mobjects, or (key, mobject)
6201 pairs.
6202 """
6203 for key, value in dict(mapping_or_iterable).items():
6204 self.add_key_value_pair(key, value)
6205 return self
6207 def remove( # ty: ignore[invalid-method-override] # CE's: by key
6208 self, key: Hashable
6209 ) -> Self:
6210 """Remove the member with a key from the group.
6212 Raises an exception if the group has no such key.
6214 Args:
6215 key: The member's key.
6216 """
6217 super().remove(self.submob_dict.pop(key))
6218 return self
6220 def __getitem__(self, key: Hashable) -> T: # ty: ignore[invalid-method-override] # CE's: by key
6221 return self.submob_dict[key]
6223 def __setitem__(self, key: Hashable, value: T) -> None:
6224 if key in self.submob_dict:
6225 self.remove(key)
6226 self.add([(key, value)])
6228 @deprecated("use add({key: value})", category=None)
6229 def add_key_value_pair(self, key: Hashable, value: T) -> Self:
6230 """Add a member with a key, after the group's.
6232 The constructor, [add][manimgx.VDict.add] and `vdict[key] = mobject` all add
6233 members this way. If the group shows its keys (`show_keys`), the member is
6234 labeled first: a [Tex][manimgx.Tex] of `str(key)`, at its left, is added to the
6235 member itself, so the label moves, animates and leaves with it.
6237 Args:
6238 key: Its key.
6239 value: The mobject.
6240 """
6241 if self.show_keys:
6242 from manimgx.mobjects.text import Tex
6244 value.add(Tex(str(key)).next_to(value, LEFT))
6245 self.submob_dict[key] = value
6246 Mobject.add(self, value)
6247 return self
6249 @deprecated("use the group's submobjects", category=None)
6250 def get_all_submobjects(self) -> list[T]:
6251 """The members, in the order of their keys.
6253 Returns:
6254 A list of the mobjects.
6255 """
6256 return list(self.submob_dict.values())
6259class PMobject(Mobject):
6260 """A point cloud: a mobject drawn as points, each a dot of its own color.
6262 Points are added with [add_points][manimgx.PMobject.add_points], each with a color;
6263 the style methods color them all. Each point is a disk as wide as a stroke of its
6264 `stroke_width`, a hundredth of a scene unit for each unit of width: at the default
6265 width, 4, about 4 pixels of a 720p frame.
6267 Args:
6268 **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `color` colors the points
6269 added without a color (white unless given), and `stroke_width` sizes them;
6270 the other paint keywords are not used.
6272 Examples:
6273 ```python
6274 import numpy as np
6276 import manimgx as m
6279 class PMobjectExample(m.Scene):
6280 def construct(self) -> None:
6281 t = np.linspace(0, 1, 300)
6282 spiral = np.column_stack(
6283 [3.5 * t * np.cos(20 * t), 3.5 * t * np.sin(20 * t), 0 * t]
6284 )
6285 colors = m.color_gradient([m.BLUE, m.GREEN, m.YELLOW], len(t))
6286 rgbas = np.array([color.to_rgba() for color in colors])
6287 cloud = m.PMobject(stroke_width=15).add_points(spiral, rgbas=rgbas)
6288 self.add(cloud)
6289 ```
6290 """
6292 def init_colors(self, propagate_colors: bool = True) -> Self:
6293 # a point's color is its row in `rgbas`, set as points are added; style gives
6294 # its size
6295 self.paint = self.paint.but(
6296 stroke_width=self.style.get("stroke_width", DEFAULT_STROKE_WIDTH)
6297 )
6298 return self
6300 def _color(self) -> ManimColor:
6301 return parse_colors(self.style.get("color", WHITE))[0]
6303 def reset_points(self) -> Self:
6304 self.points = np.zeros((0, 3))
6305 self.paint = self.paint.but(fill=np.zeros((0, 4)))
6306 return self
6308 def add_points(
6309 self,
6310 points: Point3DLike_Array,
6311 rgbas: np.ndarray | None = None,
6312 color: ParsableManimColor | None = None,
6313 alpha: float = 1.0,
6314 ) -> Self:
6315 """Add points to the cloud, after its own, with their colors.
6317 Args:
6318 points: The points, in scene coordinates: an (n, 3) array.
6319 rgbas: Their colors, one row of red, green, blue and opacity (from 0 to 1)
6320 per point; None to give them all `color`.
6321 color: Their color, when `rgbas` is None; None for the cloud's (its `color`
6322 style keyword, white unless given).
6323 alpha: Their opacity, from 0 to 1, when `rgbas` is None.
6324 """
6325 points = np.asarray(points, dtype=float).reshape(-1, 3)
6326 if rgbas is None:
6327 c = ManimColor(color) if color else self._color()
6328 rgbas = np.repeat([c.to_rgba_with_alpha(alpha)], len(points), axis=0)
6329 elif len(rgbas) != len(points):
6330 raise ValueError("points and rgbas must have same length")
6331 self.points = np.append(self.points, points, axis=0)
6332 self.paint = self.paint.but(fill=np.append(self.paint.fill, rgbas, axis=0))
6333 return self
6335 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
6336 def get_all_rgbas(self) -> RGBA_Array:
6337 """The colors of every point of the cloud's family, member after member.
6339 Returns:
6340 An (n, 4) array of red, green, blue and opacity, from 0 to 1.
6341 """
6342 return np.concatenate(
6343 [m.paint.fill for m in self.family_members_with_points()]
6344 or [np.zeros((0, 4))]
6345 )
6347 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
6348 def match_colors(self, mobject: Mobject) -> Self:
6349 """Give the cloud another cloud's colors, point for point.
6351 The two are first aligned as a transform aligns them: the one with fewer points
6352 is given more, repeating its points, so `mobject` may change too.
6354 Args:
6355 mobject: The cloud whose colors to take.
6356 """
6357 Mobject.align_data(self, mobject)
6358 self.paint = self.paint.but(fill=mobject.paint.fill)
6359 return self
6361 def thin_out(self, factor: int = 5) -> Self:
6362 """Keep one point in every `factor` of each cloud in the family, from its first.
6364 Args:
6365 factor: One point is kept in this many; must be positive.
6366 """
6367 if factor < 1:
6368 raise ValueError("factor must be positive")
6369 for mob in self.family_members_with_points():
6370 mob.points, mob.paint = (
6371 mob.points[::factor],
6372 mob.paint.but(fill=mob.paint.fill[::factor].copy()),
6373 )
6374 return self
6376 # ── the Points kind's alignment and partial rules ──────────────────────
6377 def align_points_with_larger(self, larger: Mobject) -> Self:
6378 n = larger.get_num_points()
6379 self.points = stretch_array(self.points, n)
6380 self.paint = self.paint.but(fill=stretch_array(self.paint.fill, n))
6381 return self
6383 def get_point_mobject(self, center: Point3DLike | None = None) -> "Point":
6384 return Point(self.get_center() if center is None else center)
6386 def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
6387 # every point the stretch reaches into, as a reveal over it shows them
6388 n = mobject.get_num_points()
6389 lo = min(max(math.floor(a * n), 0), n)
6390 hi = min(max(math.ceil(b * n), lo), n)
6391 fill = mobject.paint.fill
6392 self.points = mobject.points[lo:hi]
6393 self.paint = self.paint.but(fill=fill[lo:hi] if len(fill) == n else fill)
6394 return self
6397@deprecated("Manim CE's base of point clouds along lines: use PMobject", category=None)
6398class Mobject1D(PMobject):
6399 """A point cloud of lines: points evenly spaced along each, `density` to a unit.
6401 Lines are added with [add_line][manimgx.Mobject1D.add_line].
6403 Args:
6404 density: How many points a line gets per scene unit of its length.
6405 **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `color` colors the points
6406 added without a color (white unless given), and `stroke_width` sizes them.
6408 Examples:
6409 ```python
6410 import manimgx as m
6413 class Mobject1DExample(m.Scene):
6414 def construct(self) -> None:
6415 cloud = m.Mobject1D(density=6, stroke_width=12)
6416 cloud.add_line([-4, -2, 0], [4, -2, 0], color=m.BLUE)
6417 cloud.add_line([4, -2, 0], [0, 2.5, 0], color=m.YELLOW)
6418 cloud.add_line([0, 2.5, 0], [-4, -2, 0], color=m.RED)
6419 self.add(cloud)
6420 ```
6421 """
6423 def __init__(
6424 self, density: int = DEFAULT_POINT_DENSITY_1D, **kwargs: Unpack[Style]
6425 ) -> None:
6426 self.density = density
6427 self.epsilon = 1.0 / density
6428 super().__init__(**kwargs)
6430 def add_line(
6431 self,
6432 start: Point3DLike,
6433 end: Point3DLike,
6434 color: ParsableManimColor | None = None,
6435 ) -> Self:
6436 """Add a line of points from `start` toward `end`, 1/`density` scene units
6437 apart.
6439 The line stops short of `end`, where another may start; a line of no length is
6440 one point.
6442 Args:
6443 start: Where the line starts, in scene coordinates.
6444 end: Where it ends.
6445 color: The points' color; None for the cloud's.
6446 """
6447 s, e = np.asarray(start, dtype=float), np.asarray(end, dtype=float)
6448 length = np.linalg.norm(e - s)
6449 points = (
6450 np.array([s])
6451 if length == 0
6452 else interpolate(s, e, np.arange(0, 1, self.epsilon / length)[:, None])
6453 )
6454 return self.add_points(points, color=color)
6457if TYPE_CHECKING:
6459 @deprecated("PGroup is Group: use Group, or VGroup", category=None)
6460 class PGroup[T: Mobject = Mobject](Group[T]):
6461 """Manim CE's group of point clouds: [Group][manimgx.Group], which holds
6462 mobjects of any kind."""
6464else:
6465 PGroup = Group # a group is a group: kinds belong to leaves
6468@deprecated("Manim CE's one-point cloud: use VectorizedPoint, or Dot", category=None)
6469class Point(PMobject):
6470 """A point cloud of one point, black unless colored: unseen on the default black
6471 background.
6473 Args:
6474 location: Where the point is, in scene coordinates.
6475 color: Its color, which may be given by position (`Point(ORIGIN, RED)`); None
6476 for black.
6477 **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `stroke_width` sizes the
6478 point.
6480 Examples:
6481 ```python
6482 import manimgx as m
6485 class PointExample(m.Scene):
6486 def construct(self) -> None:
6487 colors = [m.RED, m.YELLOW, m.GREEN, m.BLUE, m.PURPLE]
6488 for i, color in enumerate(colors):
6489 self.add(m.Point([2.5 * i - 5, 0, 0], color, stroke_width=60))
6490 ```
6491 """
6493 defaults: ClassVar[Style] = {"color": BLACK}
6495 def __init__(
6496 self,
6497 location: Point3DLike = ORIGIN,
6498 color: Colors | None = None,
6499 **kwargs: Unpack[StyleBase],
6500 ) -> None:
6501 self.location = np.array(location, dtype=float) # its own, as it was given
6502 super().__init__(
6503 **(Style(**kwargs) if color is None else Style(**kwargs, color=color))
6504 )
6506 def generate_points(self) -> Self:
6507 return self.reset_points().add_points(np.array([self.location]))
6510if TYPE_CHECKING:
6511 from manimgx.scene import Camera
6514_MESH_STRAIGHT = straight_path() # a default (paths are immutable)
6517def _value(array: np.ndarray, held: np.ndarray | None = None) -> np.ndarray:
6518 """An owned read-only snapshot; an equal value keeps the array already held."""
6519 if held is not None and unchanged(array, held):
6520 return held
6521 array = array.copy()
6522 array.flags.writeable = False
6523 return array
6526class MeshMobject(Mobject):
6527 """A mesh: triangles between vertices, filled with one color, a color per vertex, or
6528 a picture; white and opaque unless styled.
6530 Any two meshes can morph into each other, whatever their triangles: the one with
6531 fewer gains some, collapsed to points. Drawn in ([Create][manimgx.Create]), a mesh
6532 appears triangle by triangle, in their order. A three-dimensional scene's light
6533 shades it only with `shade_in_3d=True`.
6535 Args:
6536 vertices: The vertices, in scene coordinates: an (n, 3) array; None for an empty
6537 mesh.
6538 triangles: The triangles: an (m, 3) array of indices into `vertices`.
6539 vertex_colors: A color for each vertex, blended across each triangle: an (n, 4)
6540 array of red, green, blue and opacity, from 0 to 1; None for the style's
6541 color.
6542 uvs: Where each vertex is in the picture: an (n, 2) array of coordinates from 0
6543 to 1, (0, 0) the picture's top left.
6544 texture: The picture: an (h, w, 4) array of RGBA values from 0 to 255, or a
6545 [Camera][manimgx.Camera], whose view is drawn anew every frame.
6547 Examples:
6548 ```python
6549 import numpy as np
6551 import manimgx as m
6554 class MeshMobjectExample(m.Scene):
6555 def construct(self) -> None:
6556 vertices = np.array([[-3, -2.5, 0], [3, -2.5, 0], [0, 3, 0]])
6557 colors = np.array([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]])
6558 triangle = m.MeshMobject(
6559 vertices, np.array([[0, 1, 2]]), vertex_colors=colors
6560 )
6561 self.play(m.FadeIn(triangle))
6562 ```
6563 """
6565 defaults: ClassVar[Style] = {
6566 "fill_opacity": 1.0,
6567 "stroke_opacity": 0.0,
6568 "stroke_width": 0.0,
6569 }
6571 def __init__(
6572 self,
6573 vertices: Point3D_Array | None = None,
6574 triangles: np.ndarray | None = None,
6575 *,
6576 vertex_colors: np.ndarray | None = None,
6577 uvs: np.ndarray | None = None,
6578 texture: "np.ndarray | Camera | None" = None,
6579 **kwargs: Unpack[Style],
6580 ) -> None:
6581 # values, as they are given: regenerated, the mesh is what it was made of
6582 self._init_mesh = (
6583 None if vertices is None else np.array(vertices),
6584 None if triangles is None else np.array(triangles),
6585 None if uvs is None else np.array(uvs),
6586 )
6587 self._vertex_colors = None if vertex_colors is None else np.array(vertex_colors)
6588 self._texture = _value(texture) if isinstance(texture, np.ndarray) else texture
6589 super().__init__(**kwargs)
6591 @property
6592 def triangles(self) -> np.ndarray:
6593 """The mesh's readonly (m, 3) triangle indices; for a lattice these are the
6594 coarse triangles of the faces it draws, two each.
6596 Equal assignment is a no-op. Ordinary meshes snapshot replacement indices;
6597 a sampled lattice requires constructing an explicit MeshMobject instead.
6598 """
6599 topology = self._topology
6600 return topology.triangles() if isinstance(topology, Lattice) else topology
6602 @triangles.setter
6603 def triangles(self, value: npt.ArrayLike) -> None:
6604 array = np.asarray(value, dtype=np.int64)
6605 array = array if array.shape[1:] == (3,) else array.reshape(-1, 3)
6606 held = self.__dict__.get("_topology")
6607 if isinstance(held, Lattice):
6608 if np.array_equal(array, self.triangles):
6609 return
6610 raise ValueError(
6611 "A lattice's derived triangles cannot be replaced; construct "
6612 "MeshMobject(vertices, triangles, vertex_colors=...) explicitly"
6613 )
6614 self._topology = _value(array, held)
6616 @property
6617 def uvs(self) -> np.ndarray | None:
6618 """Where each vertex is in the mesh's picture: an (n, 2) array of coordinates
6619 from 0 to 1, read-only; None for a mesh without them. Assignments snapshot
6620 the supplied coordinates; equal values keep the current array."""
6621 return self._uvs
6623 @uvs.setter
6624 def uvs(self, value: npt.ArrayLike | None) -> None:
6625 self._uvs = (
6626 None
6627 if value is None
6628 else _value(np.asarray(value, dtype=float), self.__dict__.get("_uvs"))
6629 )
6631 @property
6632 def grid(self) -> tuple[int, int] | None:
6633 """The numbers of lattice cells along u and v, or None for explicit triangles.
6635 A (u, v) lattice has (u + 1) * (v + 1) samples. Its fill rows belong to cells
6636 and UVs to samples; ordinary mesh fill rows belong to vertices. match_points
6637 adopts this domain while retaining its recipient's style. A part of a surface
6638 has its whole lattice, and draws some of its faces.
6639 """
6640 topology = self._topology
6641 return (topology.u, topology.v) if isinstance(topology, Lattice) else None
6643 def generate_points(self) -> Self:
6644 vertices, triangles, uvs = self._init_mesh
6645 if vertices is not None:
6646 self.points = np.asarray(vertices, dtype=float)
6647 self._topology = _value(
6648 np.asarray(triangles, dtype=np.int64).reshape(-1, 3), self.triangles
6649 )
6650 self.uvs = uvs
6651 return self
6653 def reset_points(self) -> Self:
6654 super().reset_points()
6655 self._topology = _value(np.zeros((0, 3), dtype=np.int64))
6656 self.uvs = None
6657 return self
6659 def init_colors(self, propagate_colors: bool = True) -> Self:
6660 super().init_colors(propagate_colors)
6661 if self._vertex_colors is not None:
6662 self.paint = self.paint.but(fill=np.array(self._vertex_colors, dtype=float))
6663 self.paint = self.paint.but(texture=self._texture)
6664 return self
6666 # ── the Mesh kind's alignment and partial rules ────────────────────────
6667 def _as_soup(self) -> None:
6668 """Convert to explicit triangles, giving each corner its own point and paint row."""
6669 index = self.triangles.ravel()
6670 if len(self.points) == len(index) and np.array_equal(
6671 index, np.arange(len(index))
6672 ):
6673 return
6674 topology = self._topology
6675 if isinstance(topology, Lattice):
6676 if len(self.paint.fill) > 1: # its faces' rows, one per corner of each
6677 cells = stretch_array(self.paint.fill, topology.u * topology.v)
6678 drawn = cells[topology.first : topology.end]
6679 self.paint = self.paint.but(fill=np.repeat(drawn, 6, axis=0))
6680 elif len(self.paint.fill) == len(self.points) > 1:
6681 self.paint = self.paint.but(fill=self.paint.fill[index])
6682 self.points = self.points[index]
6683 if self.uvs is not None:
6684 self.uvs = self.uvs[index]
6685 self._topology = _value(np.arange(len(index)).reshape(-1, 3))
6687 def align_points(self, mobject: Mobject) -> Self:
6688 # Equal topology shares the existing domain. Different topology becomes explicit
6689 # triangle soup; the smaller mesh gains copies collapsed to their centers.
6690 if not isinstance(mobject, MeshMobject):
6691 self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
6692 return self
6693 if len(self.points) != len(mobject.points) or not np.array_equal(
6694 self._topology, mobject._topology
6695 ):
6696 for mesh in (self, mobject):
6697 mesh._as_soup()
6698 small, large = sorted((self, mobject), key=lambda m: len(m.points))
6699 n = len(large.points) // 3
6700 if len(small.points) == 0:
6701 small.points = np.repeat(small.get_center()[None], n * 3, axis=0)
6702 else:
6703 pieces = small.points.reshape(-1, 3, 3)
6704 index = np.arange(n) * len(pieces) // n
6705 first = np.r_[True, index[1:] != index[:-1]]
6706 padded = pieces[index].copy()
6707 padded[~first] = padded[~first].mean(axis=1, keepdims=True)
6708 if len(small.paint.fill) == len(small.points) > 1:
6709 colors = small.paint.fill.reshape(-1, 3, 4)[index].reshape(-1, 4)
6710 small.paint = small.paint.but(fill=colors)
6711 if small.uvs is not None:
6712 small.uvs = small.uvs.reshape(-1, 3, 2)[index].reshape(-1, 2)
6713 small.points = padded.reshape(-1, 3)
6714 small._topology = large._topology
6715 for a, b in ((self, mobject), (mobject, self)):
6716 if len(a.paint.fill) == len(a.points) > 1 and len(b.paint.fill) == 1:
6717 b.paint = b.paint.but(
6718 fill=np.repeat(b.paint.fill, len(b.points), axis=0)
6719 )
6720 self.paint, mobject.paint = Paint.aligned(self.paint, mobject.paint)
6721 return self
6723 def _take_shape(self, mobject: Mobject) -> None:
6724 if isinstance(mobject, MeshMobject):
6725 self._topology, self._uvs = mobject._topology, mobject.uvs
6727 def get_point_mobject(self, center: Point3DLike | None = None) -> "MeshMobject":
6728 c = self.get_center() if center is None else np.asarray(center, dtype=float)
6729 point = MeshMobject(np.repeat(c[None], 3, axis=0), np.array([[0, 1, 2]]))
6730 point.paint = self.paint
6731 return point
6733 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
6734 def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
6735 """Take a source's geometry and paint, then keep the steps a reveal over the
6736 stretch shows, whole: a surface's faces, or a mesh's triangles.
6738 A surface's part is a surface: its whole lattice, drawing those faces, as smooth
6739 and with the edges they have in it. A mesh's part is its triangles alone, each
6740 corner with its paint and UV. Repeated calls restart from source.
6741 """
6742 if isinstance(mobject, MeshMobject):
6743 self._geometry = mobject._geometry
6744 self._take_shape(mobject)
6745 self.paint = mobject.paint
6746 topology = self._topology
6747 lattice = isinstance(topology, Lattice)
6748 n = topology.end - topology.first if lattice else len(topology)
6749 lo = min(max(math.floor(a * n), 0), n)
6750 hi = min(max(math.ceil(b * n), lo), n)
6751 if (lo, hi) == (0, n):
6752 return self
6753 if isinstance(topology, Lattice):
6754 first = topology.first
6755 self._topology = topology._replace(first=first + lo, end=first + hi)
6756 return self
6757 self._as_soup() # three corners a triangle, in order: keep the part's own
6758 self.points = self.points[3 * lo : 3 * hi]
6759 if len(self.paint.fill) == 3 * n > 1:
6760 self.paint = self.paint.but(fill=self.paint.fill[3 * lo : 3 * hi])
6761 if self.uvs is not None:
6762 self.uvs = self.uvs[3 * lo : 3 * hi]
6763 self._topology = _value(np.arange(3 * (hi - lo)).reshape(-1, 3))
6764 return self
6766 def _box(self) -> np.ndarray | None:
6767 # a part of a surface keeps its whole lattice: its box is its drawn faces'
6768 topology = self._topology
6769 if not isinstance(topology, Lattice) or topology.end - topology.first == (
6770 topology.u * topology.v
6771 ):
6772 return super()._box()
6773 drawn = self.points[np.unique(topology.triangles())]
6774 return np.array([drawn.min(axis=0), drawn.max(axis=0)]) if len(drawn) else None
6776 def interpolate(
6777 self,
6778 mobject1: Mobject,
6779 mobject2: Mobject,
6780 alpha: float,
6781 path_func: PathFunc = _MESH_STRAIGHT,
6782 ) -> Self:
6783 super().interpolate(mobject1, mobject2, alpha, path_func)
6784 if isinstance(mobject1, MeshMobject) and isinstance(mobject2, MeshMobject):
6785 self._topology = mobject2._topology if alpha >= 1 else mobject1._topology
6786 return self
6789if TYPE_CHECKING:
6790 from pathops import Path as SkiaPath
6793def _append_path(target: "VMobject", path: "SkiaPath") -> "None":
6794 """Append a planar path through the existing cubic builder, preserving its arithmetic."""
6795 start = np.zeros(3)
6796 verb = _pathops().PathVerb
6797 for kind, points in path:
6798 parts = np.array([(*point, 0.0) for point in points], dtype=float)
6799 if kind == verb.MOVE:
6800 for part in parts:
6801 start = part
6802 target.start_new_path(part)
6803 elif kind == verb.CUBIC:
6804 first, second, end = parts
6805 target.add_cubic_bezier_curve_to(first, second, end)
6806 elif kind == verb.LINE:
6807 target.add_line_to(parts[0])
6808 elif kind == verb.CLOSE:
6809 target.add_line_to(start)
6810 elif kind == verb.QUAD:
6811 control, end = parts
6812 target.add_quadratic_bezier_curve_to(control, end)
6813 else:
6814 raise Exception(f"Unsupported: {kind}")