Coverage for src/manimgx/animation/motion.py: 98%
562 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"""Animation presets built from the shared lifecycle and transform primitives.
8A reveal is paint, so drawing, passing flashes and border reveals use the same
9Transform as movement and morphing; whole-object procedures use Animation. Showing a
10group's parts in turn is visibility, not paint: the scene leaves the parts not shown yet
11out of the picture (`Animation.hidden`)."""
13from __future__ import annotations
15import inspect
16import itertools as it
17import math
18from collections.abc import Callable, Iterable, Sequence
19from typing import TYPE_CHECKING, ClassVar, Unpack, cast
20from warnings import deprecated
22import numpy as np
23import numpy.typing as npt
25from manimgx.animation.easing import (
26 double_smooth,
27 linear,
28 smooth,
29 there_and_back,
30 wiggle,
31)
32from manimgx.animation.timeline import (
33 Animation,
34 AnimationGroup,
35 AnimationOptions,
36 Key,
37 LaggedStart,
38 Succession,
39 _gathered,
40)
41from manimgx.constants import (
42 DEFAULT_POINTWISE_FUNCTION_RUN_TIME,
43 DEFAULT_STROKE_WIDTH,
44 DEGREES,
45 ORIGIN,
46 OUT,
47 PI,
48 RIGHT,
49 SMALL_BUFF,
50 TAU,
51 UP,
52)
53from manimgx.drawing.geometry import (
54 Path,
55 interpolate,
56 inverse_interpolate,
57 normalize,
58 path_along_circles,
59 spiral_path,
60)
61from manimgx.drawing.paint import GREY, PURE_YELLOW, ParsableManimColor
62from manimgx.mobject import Group, Mobject, Pivot, VGroup, VMobject
63from manimgx.settings import config
64from manimgx.typing import Point3D, Point3DLike, Vector3DLike
66if TYPE_CHECKING:
67 from manimgx.drawing.paint import Paint
68 from manimgx.mobjects.numbers import DecimalNumber
69 from manimgx.scene import Scene
70from manimgx.animation.transform import Transform, TransformOptions, _Call
72__all__ = [
73 "AddTextLetterByLetter",
74 "AddTextWordByWord",
75 "ApplyComplexFunction",
76 "ApplyFunction",
77 "ApplyMatrix",
78 "ApplyMethod",
79 "ApplyPointwiseFunction",
80 "ApplyWave",
81 "Blink",
82 "Broadcast",
83 "ChangeDecimalToValue",
84 "ChangingDecimal",
85 "Circumscribe",
86 "ClockwiseTransform",
87 "ComplexHomotopy",
88 "CounterclockwiseTransform",
89 "Create",
90 "CyclicReplace",
91 "DrawBorderThenFill",
92 "FadeIn",
93 "FadeOut",
94 "FadeToColor",
95 "FadeTransform",
96 "FadeTransformPieces",
97 "Flash",
98 "FocusOn",
99 "GrowArrow",
100 "GrowFromCenter",
101 "GrowFromEdge",
102 "GrowFromPoint",
103 "Homotopy",
104 "Indicate",
105 "MaintainPositionRelativeTo",
106 "MoveAlongPath",
107 "MoveToTarget",
108 "PhaseFlow",
109 "RemoveTextLetterByLetter",
110 "ReplacementTransform",
111 "Restore",
112 "Rotate",
113 "Rotating",
114 "ScaleInPlace",
115 "ShowIncreasingSubsets",
116 "ShowPassingFlash",
117 "ShowPassingFlashWithThinningStrokeWidth",
118 "ShowSubmobjectsOneByOne",
119 "ShrinkToCenter",
120 "SpinInFromNothing",
121 "SpiralIn",
122 "Swap",
123 "TransformFromCopy",
124 "TypeWithCursor",
125 "Uncreate",
126 "UntypeWithCursor",
127 "Unwrite",
128 "UpdateFromAlphaFunc",
129 "UpdateFromFunc",
130 "Wiggle",
131 "Write",
132]
135def trimmed(mob: Mobject, a: float, b: float) -> Mobject:
136 """Set which stretch of each path of a mobject is drawn.
138 The stretch is paint state, which each frame applies when it draws: the points are
139 not changed.
141 Args:
142 mob: The mobject whose parts with points are trimmed.
143 a: Where the drawn stretch begins, as a fraction of each path's length.
144 b: Where it ends; (0, 0) draws nothing, (0, 1) the whole path.
146 Returns:
147 The mobject, for chaining.
148 """
149 for leaf in mob.family_members_with_points():
150 leaf.paint = leaf.paint.but(trim=np.array([a, b]), pace=leaf.reveal_pace())
151 return mob
154class Create(Transform):
155 """Draw a mobject into view along its paths, one part after another.
157 The mobject joins the scene when the animation begins. Each part is revealed from its
158 start to its end; with the default `lag_ratio` of 1, a part begins when the one before
159 it is drawn.
161 Args:
162 mobject: The mobject to draw.
164 Examples:
165 ```python
166 import manimgx as m
169 class CreateExample(m.Scene):
170 def construct(self) -> None:
171 square = m.Square(side_length=4, color=m.BLUE, fill_opacity=0.5)
172 self.play(m.Create(square, run_time=2))
173 ```
174 """
176 defaults: ClassVar[AnimationOptions] = {"lag_ratio": 1.0, "introducer": True}
178 def __init__(self, mobject: Mobject, **kwargs: Unpack[AnimationOptions]) -> None:
179 super().__init__(mobject, keys=(lambda m: trimmed(m, 0, 0), None), **kwargs)
182class Uncreate(Create):
183 """Undraw a mobject along its paths, and take it out of the scene.
185 Each part is erased from its end back to its start, one part after another in the
186 order [`Create`][manimgx.Create] draws them. The mobject leaves the scene when the
187 animation finishes.
189 Args:
190 mobject: The mobject to undraw.
191 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions].
193 Examples:
194 ```python
195 import manimgx as m
198 class UncreateExample(m.Scene):
199 def construct(self) -> None:
200 formula = m.MathTex("a^2 + b^2 = c^2", font_size=120)
201 box = m.SurroundingRectangle(formula, buff=0.4, color=m.YELLOW)
202 self.add(formula, box)
203 self.play(m.Uncreate(box, run_time=2))
204 ```
205 """
207 defaults: ClassVar[AnimationOptions] = {
208 "reverse_rate_function": True,
209 "remover": True,
210 "introducer": False,
211 }
214class ShowPassingFlash(Transform):
215 """Flash a stretch of a mobject's path along it, from its start to past its end.
217 A window, `time_width` of the path's length, travels along the mobject, which shows
218 only what lies inside it. The mobject joins the scene for the flash and leaves
219 it at the end, even if it was there before (flash a copy to keep the original); its
220 paths are whole again afterward.
222 Args:
223 mobject: The mobject whose paths the window travels along.
224 time_width: The window's length, as a fraction of the path's length.
226 Examples:
227 ```python
228 import manimgx as m
231 class ShowPassingFlashExample(m.Scene):
232 def construct(self) -> None:
233 pentagon = m.RegularPolygon(5, color=m.GREY, stroke_width=8).scale(3)
234 flash = pentagon.copy().set_color(m.YELLOW)
235 self.add(pentagon)
236 self.play(m.ShowPassingFlash(flash, time_width=0.5, run_time=2))
237 ```
238 """
240 defaults: ClassVar[AnimationOptions] = {"remover": True, "introducer": True}
242 def __init__(
243 self,
244 mobject: Mobject,
245 time_width: float = 0.1,
246 **kwargs: Unpack[AnimationOptions],
247 ) -> None:
248 self.time_width = time_width
249 super().__init__(
250 mobject,
251 keys=(
252 lambda m: trimmed(m, -time_width, 0),
253 lambda m: trimmed(m, 1, 1 + time_width),
254 ),
255 **kwargs,
256 )
259class DrawBorderThenFill(Transform):
260 """Draw a mobject's outline, then fill it in.
262 In the first half, each part's border is drawn along its path, `stroke_width` wide,
263 in the paint the part is seen in: its own stroke, if it draws one, or else its fill
264 (a gradient stays one), unless `stroke_color` is given. In the second, the fill
265 comes in while the border turns into the part's own stroke; where the part draws no
266 stroke, the border thins away in the same paint. The parts end as they were. The
267 mobject joins the scene when the animation begins. It runs 2 seconds, eased by
268 [`double_smooth`][manimgx.double_smooth]: smoothly in each half.
270 Args:
271 vmobject: The mobject to draw.
272 stroke_width: The border's width, in hundredths of a scene unit.
273 stroke_color: The border's color; None for the paint each part is seen in.
275 Examples:
276 ```python
277 import manimgx as m
280 class DrawBorderThenFillExample(m.Scene):
281 def construct(self) -> None:
282 shapes = m.VGroup(
283 m.Square(side_length=3, color=m.ORANGE, fill_opacity=1),
284 m.Star(outer_radius=2, color=m.BLUE, fill_opacity=1),
285 ).arrange(buff=1.5)
286 self.play(m.DrawBorderThenFill(shapes, stroke_color=m.YELLOW))
287 ```
288 """
290 defaults: ClassVar[AnimationOptions] = {
291 "run_time": 2.0,
292 "rate_func": double_smooth,
293 "introducer": True,
294 }
296 def __init__(
297 self,
298 vmobject: Mobject,
299 stroke_width: float = 2,
300 stroke_color: ParsableManimColor | None = None,
301 **kwargs: Unpack[AnimationOptions],
302 ) -> None:
303 super().__init__(
304 vmobject,
305 keys=(self._undrawn, self._outline, self._filled),
306 **kwargs,
307 )
308 self.stroke_width, self.stroke_color = stroke_width, stroke_color
310 def _undrawn(self, mobject: Mobject) -> Mobject:
311 """Its outline, none of it drawn yet: where it starts."""
312 return trimmed(self._outline(mobject), 0, 0)
314 def _border(self, part: Mobject) -> None:
315 """A part's stroke as its border: its own stroke if it draws one, else its fill (every
316 row, so a gradient stays one; at its opacity); in `stroke_color`, if given."""
317 p = part.paint
318 if not _draws_stroke(p):
319 part.paint = p.but(stroke=p.fill)
320 if self.stroke_color is not None:
321 part.set_stroke(self.stroke_color, family=False)
323 def _outline(self, m: Mobject) -> Mobject:
324 for part in m.family_members_with_points():
325 self._border(part)
326 part.paint = part.paint.but(stroke_width=self.stroke_width)
327 return m.set_fill(opacity=0)
329 def _filled(self, m: Mobject) -> Mobject:
330 """The object, but a part that draws no stroke has its unseen stroke in its border's
331 paint: its border thins away in it, not in a color it never shows."""
332 for part in m.family_members_with_points():
333 if not _draws_stroke(part.paint):
334 self._border(part)
335 return m
337 def _ends_as_given(self) -> bool:
338 # drawn and filled, it is itself: its unseen strokes its own
339 steps = len(self.keys) - 1
340 return self._resting_at(steps) == steps or super()._ends_as_given()
343def _draws_stroke(paint: Paint) -> bool:
344 return paint.stroke_width > 0 and bool(paint.stroke[:, 3].any())
347class Write(DrawBorderThenFill):
348 r"""Write a mobject as if by hand: each part's outline drawn, then filled in.
350 The drawing of [`DrawBorderThenFill`][manimgx.DrawBorderThenFill], at an even pace
351 (`linear`), its parts staggered: `lag_ratio` is 4 divided by the number of parts, at
352 most 0.2, and it runs 1 second for fewer than 15 parts, 2 seconds otherwise. The
353 mobject joins the scene when the animation begins. [`Unwrite`][manimgx.Unwrite]
354 erases it.
356 Args:
357 vmobject: The mobject to write, as a text or a formula.
358 reverse: Whether to write the parts from the last to the first (they keep their
359 order, so the later ones stay drawn over the earlier ones); the mobject then
360 leaves the scene when the animation finishes (unless given `remover=False`).
362 Examples:
363 ```python
364 import manimgx as m
367 class WriteExample(m.Scene):
368 def construct(self) -> None:
369 formula = m.MathTex(r"e^{i\pi} + 1 = 0", font_size=144)
370 self.play(m.Write(formula))
371 ```
372 """
374 defaults: ClassVar[AnimationOptions] = {"rate_func": linear}
376 def __init__(
377 self,
378 vmobject: Mobject,
379 reverse: bool = False,
380 **kwargs: Unpack[AnimationOptions],
381 ) -> None:
382 n = len(vmobject.family_members_with_points())
383 kwargs.setdefault("run_time", 1 if n < 15 else 2)
384 kwargs.setdefault("lag_ratio", min(4.0 / max(1.0, n), 0.2))
385 kwargs.setdefault("remover", reverse)
386 kwargs.setdefault("introducer", not reverse)
387 self.reverse = reverse
388 super().__init__(vmobject, **kwargs)
390 def get_sub_alpha(self, alpha: float, index: int, num_submobjects: int) -> float:
391 # reversed, the last part goes first; the parts keep their order, so their
392 # stacking
393 if self.reverse:
394 index = num_submobjects - 1 - index
395 return super().get_sub_alpha(alpha, index, num_submobjects)
398class Unwrite(Write):
399 """Erase a mobject as if writing it backward, and take it out of the scene.
401 The reverse of [`Write`][manimgx.Write]: each part's fill fades into its outline,
402 and the outline is undrawn, one part shortly after another, by default the last
403 part first. The parts keep their order while it plays, so the later ones stay drawn
404 over the earlier ones. The mobject leaves the scene when the animation finishes.
406 Args:
407 vmobject: The mobject to erase.
408 reverse: Whether to erase the parts from the last to the first; False erases
409 from the first.
411 Examples:
412 ```python
413 import manimgx as m
416 class UnwriteExample(m.Scene):
417 def construct(self) -> None:
418 alice = m.Text("Alice", font_size=96)
419 rest = m.Text("and Bob", font_size=96)
420 m.VGroup(alice, rest).arrange(buff=0.4)
421 self.add(alice, rest)
422 self.play(m.Unwrite(rest))
423 ```
424 """
426 defaults: ClassVar[AnimationOptions] = {"reverse_rate_function": True}
428 def __init__(
429 self,
430 vmobject: Mobject,
431 reverse: bool = True,
432 **kwargs: Unpack[AnimationOptions],
433 ) -> None:
434 super().__init__(vmobject, reverse=reverse, **kwargs)
437class _Fade(Transform):
438 fading_in: ClassVar[bool] = False
440 def __init__(
441 self,
442 *mobjects: Mobject,
443 shift: Vector3DLike | None = None,
444 target_position: Point3DLike | Mobject | None = None,
445 scale: float = 1,
446 **kwargs: Unpack[TransformOptions],
447 ) -> None:
448 if not mobjects:
449 raise ValueError("At least one mobject must be passed.")
450 mobject = mobjects[0] if len(mobjects) == 1 else _gathered(*mobjects)
451 self.point_target = shift is None and target_position is not None
452 if self.point_target:
453 center = (
454 target_position.get_center()
455 if isinstance(target_position, Mobject)
456 else np.asarray(target_position, dtype=float)
457 )
458 shift = center - mobject.get_center()
459 self.shift_vector = ORIGIN if shift is None else np.asarray(shift, dtype=float)
460 self.scale_factor = scale
461 super().__init__(
462 mobject,
463 keys=(self._faded, None) if self.fading_in else (None, self._faded),
464 **kwargs,
465 )
467 def _faded(self, m: Mobject) -> Mobject:
468 m.fade(1)
469 m.shift(
470 self.shift_vector * (-1 if self.fading_in and not self.point_target else 1)
471 )
472 return m.scale(self.scale_factor)
475class FadeIn(_Fade):
476 """Fade mobjects into view.
478 They start transparent (moved back by `shift`, or at `target_position`, and `scale`
479 times their size) and arrive as they are. They join the scene when the animation
480 begins.
482 Args:
483 *mobjects: The mobjects to fade in, together; at least one.
484 shift: The direction and distance they move while fading in: they start this far
485 behind their places.
486 target_position: Where they start from, when no `shift` is given: a point, or a
487 mobject's center.
488 scale: Their size at the start, relative to their own.
489 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions].
491 Examples:
492 ```python
493 import manimgx as m
496 class FadeInExample(m.Scene):
497 def construct(self) -> None:
498 dot = m.Dot(2 * m.UP + 4 * m.LEFT, radius=0.2, color=m.YELLOW)
499 names = ("plain", "shift", "target", "scale")
500 words = m.VGroup(*(m.Text(name, font_size=60) for name in names))
501 words.arrange(buff=0.8)
502 self.add(dot)
503 self.play(
504 m.LaggedStart(
505 m.FadeIn(words[0]),
506 m.FadeIn(words[1], shift=m.DOWN),
507 m.FadeIn(words[2], target_position=dot),
508 m.FadeIn(words[3], scale=1.5),
509 lag_ratio=0.5,
510 )
511 )
512 ```
513 """
515 defaults: ClassVar[AnimationOptions] = {"introducer": True}
516 fading_in = True
519class FadeOut(_Fade):
520 """Fade mobjects out of view, and take them out of the scene.
522 They end transparent (moved along `shift`, or to `target_position`, and `scale`
523 times their size). They leave the scene when the animation finishes, and are then as
524 they were before it: adding them again shows them.
526 Args:
527 *mobjects: The mobjects to fade out, together; at least one.
528 shift: The direction and distance they move while fading out.
529 target_position: Where they go, when no `shift` is given: a point, or a
530 mobject's center.
531 scale: Their size at the end, relative to their own.
532 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions].
534 Examples:
535 ```python
536 import manimgx as m
539 class FadeOutExample(m.Scene):
540 def construct(self) -> None:
541 dot = m.Dot(2 * m.UP + 4 * m.LEFT, radius=0.2, color=m.YELLOW)
542 names = ("plain", "shift", "target", "scale")
543 words = m.VGroup(*(m.Text(name, font_size=60) for name in names))
544 words.arrange(buff=0.8)
545 self.add(dot, words)
546 self.play(
547 m.LaggedStart(
548 m.FadeOut(words[0]),
549 m.FadeOut(words[1], shift=m.DOWN),
550 m.FadeOut(words[2], target_position=dot),
551 m.FadeOut(words[3], scale=0.5),
552 lag_ratio=0.5,
553 )
554 )
555 ```
556 """
558 defaults: ClassVar[AnimationOptions] = {"remover": True}
561class GrowFromPoint(Transform):
562 """Grow a mobject from a point.
564 It starts shrunk to nothing at `point`, in `point_color` if given, and grows to its
565 size and place. The mobject joins the scene when the animation begins.
567 Args:
568 mobject: The mobject to grow.
569 point: The point it grows from, or a mobject whose center it grows from (taken
570 when the animation is made).
571 point_color: The color it starts in; None for its own.
573 Examples:
574 ```python
575 import manimgx as m
578 class GrowFromPointExample(m.Scene):
579 def construct(self) -> None:
580 dot = m.Dot(3 * m.UP + 5 * m.LEFT, radius=0.2, color=m.YELLOW)
581 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
582 self.add(dot)
583 self.play(m.GrowFromPoint(square, dot, point_color=m.YELLOW))
584 ```
585 """
587 defaults: ClassVar[AnimationOptions] = {"introducer": True}
589 def __init__(
590 self,
591 mobject: Mobject,
592 point: Point3DLike | Mobject,
593 point_color: ParsableManimColor | None = None,
594 **kwargs: Unpack[TransformOptions],
595 ) -> None:
596 self.point = (
597 point.get_center()
598 if isinstance(point, Mobject)
599 else np.asarray(point, dtype=float)
600 )
601 self.point_color = point_color
602 super().__init__(mobject, keys=(self._shrunk, None), **kwargs)
604 def _shrunk(self, m: Mobject) -> Mobject:
605 m.scale(0).move_to(self.point)
606 return m.set_color(self.point_color) if self.point_color else m
609class GrowFromCenter(GrowFromPoint):
610 """Grow a mobject from its center.
612 It starts shrunk to nothing at its center, in `point_color` if given. The mobject
613 joins the scene when the animation begins.
615 Args:
616 mobject: The mobject to grow.
617 point_color: The color it starts in; None for its own.
619 Examples:
620 ```python
621 import manimgx as m
624 class GrowFromCenterExample(m.Scene):
625 def construct(self) -> None:
626 left = m.Circle(radius=1.5, color=m.BLUE, fill_opacity=0.5)
627 right = m.Circle(radius=1.5, color=m.GREEN, fill_opacity=0.5)
628 m.VGroup(left, right).arrange(buff=2)
629 self.play(
630 m.GrowFromCenter(left), m.GrowFromCenter(right, point_color=m.RED)
631 )
632 ```
633 """
635 def __init__(
636 self,
637 mobject: Mobject,
638 point_color: ParsableManimColor | None = None,
639 **kwargs: Unpack[TransformOptions],
640 ) -> None:
641 super().__init__(
642 mobject, mobject.get_center(), point_color=point_color, **kwargs
643 )
646class GrowFromEdge(GrowFromPoint):
647 """Grow a mobject from an edge or a corner of its bounding box.
649 It starts shrunk to nothing there, in `point_color` if given. The mobject joins the
650 scene when the animation begins.
652 Args:
653 mobject: The mobject to grow.
654 edge: The direction of the edge (as [`DOWN`][manimgx.DOWN], its bottom) or the
655 corner (as [`UR`][manimgx.UR], its top right) it grows from.
656 point_color: The color it starts in; None for its own.
658 Examples:
659 ```python
660 import manimgx as m
663 class GrowFromEdgeExample(m.Scene):
664 def construct(self) -> None:
665 squares = m.VGroup(
666 *(m.Square(side_length=2.5, fill_opacity=0.5) for _ in range(3))
667 ).arrange(buff=1.5)
668 squares.set_color_by_gradient(m.BLUE, m.GREEN)
669 self.play(
670 m.GrowFromEdge(squares[0], m.DOWN),
671 m.GrowFromEdge(squares[1], m.RIGHT),
672 m.GrowFromEdge(squares[2], m.UR),
673 )
674 ```
675 """
677 def __init__(
678 self,
679 mobject: Mobject,
680 edge: Vector3DLike,
681 point_color: ParsableManimColor | None = None,
682 **kwargs: Unpack[TransformOptions],
683 ) -> None:
684 super().__init__(
685 mobject, mobject.get_critical_point(edge), point_color=point_color, **kwargs
686 )
689class GrowArrow(GrowFromPoint):
690 """Grow an arrow from its start; its tip grows with it.
692 The arrow joins the scene when the animation begins.
694 Args:
695 arrow: The arrow to grow.
696 point_color: The color it starts in; None for its own.
698 Examples:
699 ```python
700 import manimgx as m
703 class GrowArrowExample(m.Scene):
704 def construct(self) -> None:
705 right = m.Arrow(3 * m.LEFT, 3 * m.RIGHT, color=m.BLUE).shift(1.5 * m.UP)
706 up = m.Arrow(3 * m.LEFT, 3 * m.RIGHT + 1.5 * m.UP, color=m.YELLOW)
707 up.shift(1.5 * m.DOWN)
708 self.play(m.GrowArrow(right), m.GrowArrow(up, point_color=m.RED))
709 ```
710 """
712 def __init__(
713 self,
714 arrow: Mobject,
715 point_color: ParsableManimColor | None = None,
716 **kwargs: Unpack[TransformOptions],
717 ) -> None:
718 super().__init__(arrow, arrow.get_start(), point_color=point_color, **kwargs)
720 def _shrunk(self, m: Mobject) -> Mobject:
721 from manimgx.mobjects.shapes import Arrow
723 if isinstance(m, Arrow):
724 m.scale(0, scale_tips=True, about_point=self.point)
725 else:
726 m.scale(0, about_point=self.point)
727 return m.set_color(self.point_color) if self.point_color else m
730class SpinInFromNothing(GrowFromCenter):
731 """Grow a mobject from its center while spinning it into place.
733 It turns through `angle` as it grows (counterclockwise, for a positive angle). The
734 mobject joins the scene when the animation begins.
736 Args:
737 mobject: The mobject to spin in.
738 angle: How far it turns on its way, in radians.
739 point_color: The color it starts in; None for its own.
741 Examples:
742 ```python
743 import manimgx as m
746 class SpinInFromNothingExample(m.Scene):
747 def construct(self) -> None:
748 left = m.Square(side_length=2.5, color=m.BLUE, fill_opacity=0.5)
749 right = m.Star(outer_radius=1.5, color=m.YELLOW, fill_opacity=0.5)
750 m.VGroup(left, right).arrange(buff=3)
751 self.play(
752 m.SpinInFromNothing(left),
753 m.SpinInFromNothing(right, angle=m.TAU, point_color=m.RED),
754 run_time=2,
755 )
756 ```
757 """
759 def __init__(
760 self,
761 mobject: Mobject,
762 angle: float = PI / 2,
763 point_color: ParsableManimColor | None = None,
764 **kwargs: Unpack[AnimationOptions],
765 ) -> None:
766 self.angle = angle
767 super().__init__(
768 mobject, path_func=spiral_path(angle), point_color=point_color, **kwargs
769 )
772class Indicate(Transform):
773 """Draw attention to a mobject: enlarge and color it for a moment.
775 It grows to `scale_factor` times its size in `color`, and comes back as it was
776 (eased by [`there_and_back`][manimgx.there_and_back]).
778 Args:
779 mobject: The mobject to indicate.
780 scale_factor: How many times its size it grows to.
781 color: The color it turns.
783 Examples:
784 ```python
785 import manimgx as m
788 class IndicateExample(m.Scene):
789 def construct(self) -> None:
790 formula = m.MathTex("a^2", "+", "b^2", "=", "c^2", font_size=144)
791 self.add(formula)
792 self.play(m.Indicate(formula[4]))
793 ```
794 """
796 defaults: ClassVar[AnimationOptions] = {"rate_func": there_and_back}
798 def __init__(
799 self,
800 mobject: Mobject,
801 scale_factor: float = 1.2,
802 color: ParsableManimColor = PURE_YELLOW,
803 **kwargs: Unpack[TransformOptions],
804 ) -> None:
805 self.color, self.scale_factor = color, scale_factor
806 super().__init__(
807 mobject,
808 keys=(None, lambda m: m.scale(scale_factor).set_color(color)),
809 **kwargs,
810 )
813class Rotate(Transform):
814 """Rotate a mobject rigidly about a point.
816 It turns by `angle` about `axis` around one pivot: `about_point`, or the point of
817 its bounding box at `about_edge`, or its center, taken from the mobject as it is
818 when the rotation begins. Every point travels along a circle about the pivot, so the
819 mobject keeps its shape on the way, and an angle of [`TAU`][manimgx.TAU] is a full
820 turn.
822 Args:
823 mobject: The mobject to rotate.
824 angle: The angle, in radians, counterclockwise about `axis`.
825 axis: The axis it turns about; the default, [`OUT`][manimgx.OUT], turns it in
826 the plane of the screen.
827 about_point: The pivot; None to take it from `about_edge`, or the center.
828 about_edge: The direction of the point of its bounding box it turns about, when
829 no `about_point` is given.
830 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions]; a
831 `path_func` or `path_arc_centers` of its own replaces the turn on the way.
833 Examples:
834 ```python
835 import manimgx as m
838 class RotateExample(m.Scene):
839 def construct(self) -> None:
840 pivot = m.Dot(radius=0.1)
841 left = m.Rectangle(m.BLUE, width=2.5, height=1.2, fill_opacity=0.5)
842 right = left.copy().set_color(m.YELLOW)
843 left.shift(4 * m.LEFT)
844 right.shift(2 * m.RIGHT)
845 self.add(pivot, left, right)
846 self.play(
847 m.Rotate(left, m.PI / 2),
848 m.Rotate(right, m.PI / 2, about_point=pivot.get_center()),
849 run_time=2,
850 )
851 ```
852 """
854 def __init__(
855 self,
856 mobject: Mobject,
857 angle: float = PI,
858 axis: Vector3DLike = OUT,
859 about_point: Point3DLike | None = None,
860 about_edge: Vector3DLike | None = None,
861 **kwargs: Unpack[TransformOptions],
862 ) -> None:
863 self.angle, self.axis, self.about_edge = angle, axis, about_edge
864 self._point = None if about_point is None else np.asarray(about_point, float)
865 self.about_point = self._pivot(mobject)
866 self._own_path = "path_func" in kwargs or "path_arc_centers" in kwargs
867 kwargs.setdefault("path_arc", angle)
868 kwargs.setdefault("path_arc_axis", axis)
869 kwargs.setdefault("path_arc_centers", self.about_point)
870 super().__init__(
871 mobject,
872 keys=(None, self._turned),
873 **kwargs,
874 )
876 def _turned(self, mob: Mobject) -> Mobject:
877 """Where it ends: turned through the whole angle about its pivot (a method, so
878 that a copy of the animation turns about its own)."""
879 return mob.rotate(self.angle, self.axis, about_point=self.about_point)
881 def _pivot(self, mob: Mobject) -> Point3D:
882 if self._point is not None:
883 return self._point
884 if self.about_edge is not None:
885 return mob.get_critical_point(self.about_edge)
886 return mob.get_center()
888 def derive(self, source: Mobject) -> None:
889 self._about(source)
890 super().derive(source)
892 def rederive(self) -> None:
893 if self.model is not None:
894 self._about(self.model)
895 super().rederive()
897 def _about(self, source: Mobject) -> None:
898 # the pivot, unless given, is a point of the object: read from it as it is now (as
899 # its updaters have it, while they run beneath), and the path turns about it
900 self.about_point = self._pivot(source)
901 if not self._own_path:
902 self._path_func = path_along_circles(
903 self.path_arc, self.about_point, self.path_arc_axis
904 )
907class ReplacementTransform(Transform):
908 """Transform a mobject into another, which then takes its place in the scene.
910 It plays as [`Transform`][manimgx.Transform] does; when it finishes,
911 `target_mobject` is in the scene where the mobject was, and the mobject is not: go
912 on animating the target.
914 Args:
915 mobject: The mobject to transform; it leaves the scene.
916 target_mobject: The mobject it turns into, which takes its place.
918 Examples:
919 ```python
920 import manimgx as m
923 class ReplacementTransformExample(m.Scene):
924 def construct(self) -> None:
925 numbers = m.VGroup(*(m.MathTex(n, font_size=144) for n in "123"))
926 numbers.arrange(buff=3)
927 self.add(numbers[0])
928 self.play(m.ReplacementTransform(numbers[0], numbers[1]))
929 self.play(m.ReplacementTransform(numbers[1], numbers[2]))
930 ```
931 """
933 def __init__(
934 self,
935 mobject: Mobject,
936 target_mobject: Mobject,
937 **kwargs: Unpack[TransformOptions],
938 ) -> None:
939 kwargs.setdefault("replace_mobject_with_target_in_scene", True)
940 super().__init__(mobject, target_mobject, **kwargs)
943class TransformFromCopy(Transform):
944 """Transform a copy of a mobject into another, leaving the mobject where it is.
946 `target_mobject` joins the scene, starting as a copy of the mobject as it is when the
947 animation begins, and turns into itself as any transform turns one mobject into
948 another: eased, staggered and along `path_arc` from the copy to it. It ends exactly as
949 it was; the mobject stays as it is.
951 Args:
952 mobject: The mobject the copy is made from.
953 target_mobject: The mobject the copy turns into; it joins the scene.
955 Examples:
956 ```python
957 import manimgx as m
960 class TransformFromCopyExample(m.Scene):
961 def construct(self) -> None:
962 square = m.Square(side_length=2.5, color=m.BLUE, fill_opacity=0.5)
963 circle = m.Circle(radius=1.25, color=m.YELLOW, fill_opacity=0.5)
964 square.shift(3 * m.LEFT)
965 circle.shift(3 * m.RIGHT)
966 self.add(square)
967 self.play(m.TransformFromCopy(square, circle, run_time=2))
968 ```
969 """
971 def __init__(
972 self,
973 mobject: Mobject,
974 target_mobject: Mobject,
975 **kwargs: Unpack[TransformOptions],
976 ) -> None:
977 super().__init__(target_mobject, keys=(mobject, None), **kwargs)
980class ClockwiseTransform(Transform):
981 """Transform a mobject into another along clockwise half circles.
983 Each point travels from its start to its end clockwise along a half circle: a
984 [`Transform`][manimgx.Transform] whose `path_arc` is −π, unless given another.
986 Args:
987 mobject: The mobject to transform.
988 target_mobject: The mobject whose shape and style it takes.
990 Examples:
991 ```python
992 import manimgx as m
995 class ClockwiseTransformExample(m.Scene):
996 def construct(self) -> None:
997 dot = m.Dot(2.5 * m.LEFT, radius=0.3, color=m.YELLOW)
998 square = m.Square(side_length=1.5, color=m.BLUE, fill_opacity=0.5)
999 square.shift(2.5 * m.RIGHT)
1000 self.add(dot)
1001 self.play(m.ClockwiseTransform(dot, square, run_time=2))
1002 ```
1003 """
1005 def __init__(
1006 self,
1007 mobject: Mobject,
1008 target_mobject: Mobject,
1009 **kwargs: Unpack[TransformOptions],
1010 ) -> None:
1011 kwargs.setdefault("path_arc", -PI)
1012 super().__init__(mobject, target_mobject, **kwargs)
1015class CounterclockwiseTransform(Transform):
1016 """Transform a mobject into another along counterclockwise half circles.
1018 Each point travels from its start to its end counterclockwise along a half circle: a
1019 [`Transform`][manimgx.Transform] whose `path_arc` is π, unless given another.
1021 Args:
1022 mobject: The mobject to transform.
1023 target_mobject: The mobject whose shape and style it takes.
1025 Examples:
1026 ```python
1027 import manimgx as m
1030 class CounterclockwiseTransformExample(m.Scene):
1031 def construct(self) -> None:
1032 square = m.Square(side_length=1.5, color=m.BLUE, fill_opacity=0.5)
1033 circle = m.Circle(radius=0.75, color=m.YELLOW, fill_opacity=0.5)
1034 square.shift(2.5 * m.RIGHT)
1035 circle.shift(2.5 * m.LEFT)
1036 self.add(square)
1037 self.play(m.CounterclockwiseTransform(square, circle, run_time=2))
1038 ```
1039 """
1041 def __init__(
1042 self,
1043 mobject: Mobject,
1044 target_mobject: Mobject,
1045 **kwargs: Unpack[TransformOptions],
1046 ) -> None:
1047 kwargs.setdefault("path_arc", PI)
1048 super().__init__(mobject, target_mobject, **kwargs)
1051class MoveToTarget[M: Mobject = Mobject](Transform[M]):
1052 """Transform a mobject into its `target`.
1054 Make the target first with [`generate_target`][manimgx.Mobject.generate_target], a
1055 copy of the mobject, and change it as you like; the animation transforms the mobject
1056 into it. A mobject without a target raises a ValueError.
1058 Args:
1059 mobject: The mobject to transform; its `target` is what it becomes.
1061 Examples:
1062 ```python
1063 import manimgx as m
1066 class MoveToTargetExample(m.Scene):
1067 def construct(self) -> None:
1068 circle = m.Circle(radius=2, color=m.BLUE).shift(3 * m.LEFT)
1069 target = circle.generate_target()
1070 target.set_fill(m.GREEN, opacity=0.5).scale(0.5).shift(6 * m.RIGHT)
1071 self.add(circle)
1072 self.play(m.MoveToTarget(circle))
1073 ```
1074 """
1076 def __init__(self, mobject: M, **kwargs: Unpack[TransformOptions]) -> None:
1077 if mobject.target is None:
1078 raise ValueError(
1079 "MoveToTarget called on a mobject without a target (see"
1080 " generate_target)"
1081 )
1082 super().__init__(mobject, mobject.target, **kwargs)
1085class _ApplyMethod(Transform):
1086 """Transform a mobject into what a call of one of its methods makes of it: what
1087 `ApplyMethod` and the animations that apply one method (`Restore`, …) are made of.
1089 The call is carried out when the animation begins, on the mobject as it is then. Its
1090 arguments are taken as written, when the animation is made: a mobject among them
1091 that is not part of this one is a copy of it as it was then. The method's keywords
1092 go in a dict after its positional arguments (the animation's own keywords are its
1093 options): `_ApplyMethod(square.scale, 2, {"about_edge": DL})`.
1095 Args:
1096 method: A method of a mobject, not called: `square.scale`.
1097 *args: The method's arguments; a dict at the end holds its keywords.
1098 """
1100 def __init__(
1101 self,
1102 method: Callable[..., object],
1103 *args: object,
1104 **kwargs: Unpack[TransformOptions],
1105 ) -> None:
1106 if not inspect.ismethod(method) or not isinstance(method.__self__, Mobject):
1107 raise ValueError(
1108 "Whoops, looks like you accidentally invoked the method you want to"
1109 " animate"
1110 )
1111 keywords: dict[str, object] = {}
1112 if args and isinstance(args[-1], dict):
1113 args, keywords = args[:-1], cast("dict[str, object]", args[-1])
1114 call = _Call(
1115 method.__func__,
1116 args,
1117 keywords,
1118 {id(m) for m in method.__self__.get_family()},
1119 )
1120 super().__init__(method.__self__, keys=(None, call), **kwargs)
1123@deprecated(
1124 "ApplyMethod(mobject.method, *args) is mobject.animate.method(*args): use .animate",
1125 category=None,
1126)
1127class ApplyMethod(_ApplyMethod):
1128 """Transform a mobject into what a call of one of its methods makes of it: Manim
1129 CE's older way to write [`.animate`][manimgx.Mobject.animate].
1130 `ApplyMethod(square.scale, 2)` is `square.animate.scale(2)`.
1132 Args:
1133 method: A method of a mobject, not called: `square.scale`.
1134 *args: The method's arguments; a dict at the end holds its keywords.
1135 """
1138class ApplyPointwiseFunction(_ApplyMethod):
1139 """Transform a mobject into its image under a function of a point.
1141 Each point p travels in a straight line to `function(p)`, and a path's curves are
1142 mapped as [apply_function][manimgx.Mobject.apply_function] maps them, cut into more
1143 curves where the function bends them. It runs 3 seconds.
1145 Args:
1146 function: A function from a point to where it goes, in scene coordinates.
1147 mobject: The mobject to move.
1149 Examples:
1150 ```python
1151 import numpy as np
1153 import manimgx as m
1156 class ApplyPointwiseFunctionExample(m.Scene):
1157 def construct(self) -> None:
1158 square = m.Square(side_length=2, color=m.BLUE, fill_opacity=0.5)
1159 self.add(square)
1160 self.play(
1161 m.ApplyPointwiseFunction(
1162 lambda p: m.complex_to_R3(np.exp(m.R3_to_complex(p))), square
1163 )
1164 )
1165 ```
1166 """
1168 defaults: ClassVar[AnimationOptions] = {
1169 "run_time": DEFAULT_POINTWISE_FUNCTION_RUN_TIME
1170 }
1172 def __init__(
1173 self,
1174 function: Callable[[Point3D], Point3D],
1175 mobject: Mobject,
1176 **kwargs: Unpack[TransformOptions],
1177 ) -> None:
1178 super().__init__(mobject.apply_function, function, **kwargs)
1181@deprecated(
1182 "FadeToColor(mobject, color) is mobject.animate.set_color(color): use .animate",
1183 category=None,
1184)
1185class FadeToColor(_ApplyMethod):
1186 """Change a mobject's color, gradually: `mobject.animate.set_color(color)`.
1188 Args:
1189 mobject: The mobject to recolor.
1190 color: The color it turns.
1191 """
1193 def __init__(
1194 self,
1195 mobject: Mobject,
1196 color: ParsableManimColor,
1197 **kwargs: Unpack[TransformOptions],
1198 ) -> None:
1199 super().__init__(mobject.set_color, color, **kwargs)
1202@deprecated(
1203 "ScaleInPlace(mobject, k) is mobject.animate.scale(k): use .animate",
1204 category=None,
1205)
1206class ScaleInPlace(_ApplyMethod):
1207 """Scale a mobject about its center: `mobject.animate.scale(scale_factor)`.
1209 Args:
1210 mobject: The mobject to scale.
1211 scale_factor: The factor it is scaled by: 2 doubles its size.
1212 """
1214 def __init__(
1215 self, mobject: Mobject, scale_factor: float, **kwargs: Unpack[TransformOptions]
1216 ) -> None:
1217 super().__init__(mobject.scale, scale_factor, **kwargs)
1220class ShrinkToCenter(_ApplyMethod):
1221 """Shrink a mobject to nothing at its center.
1223 It stays in the scene, shrunk to a point: pass `remover=True` to take it out when
1224 the animation finishes.
1226 Args:
1227 mobject: The mobject to shrink.
1229 Examples:
1230 ```python
1231 import manimgx as m
1234 class ShrinkToCenterExample(m.Scene):
1235 def construct(self) -> None:
1236 circles = m.VGroup(
1237 *(
1238 m.Circle(radius=1.2, color=color, fill_opacity=0.5)
1239 for color in (m.BLUE, m.YELLOW, m.GREEN)
1240 )
1241 ).arrange(buff=1)
1242 self.add(circles)
1243 self.play(m.ShrinkToCenter(circles[1]))
1244 ```
1245 """
1247 def __init__(self, mobject: Mobject, **kwargs: Unpack[TransformOptions]) -> None:
1248 super().__init__(mobject.scale, 0, **kwargs)
1251class Restore(_ApplyMethod):
1252 """Transform a mobject back into the state it saved.
1254 Save the state first with [`save_state`][manimgx.Mobject.save_state]; the animation
1255 transforms the mobject into it.
1257 Args:
1258 mobject: The mobject to restore.
1260 Examples:
1261 ```python
1262 import manimgx as m
1265 class RestoreExample(m.Scene):
1266 def construct(self) -> None:
1267 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
1268 square.save_state()
1269 square.scale(0.5).rotate(m.PI / 4).shift(4 * m.LEFT)
1270 square.set_color(m.YELLOW)
1271 self.add(square)
1272 self.play(m.Restore(square, run_time=2))
1273 ```
1274 """
1276 def __init__(self, mobject: Mobject, **kwargs: Unpack[TransformOptions]) -> None:
1277 super().__init__(mobject.restore, **kwargs)
1280class ApplyFunction(Transform):
1281 """Transform a mobject into what a function makes of it.
1283 The function gets a copy of the mobject when the animation begins, and returns the
1284 state to transform into: the copy, changed, or a new mobject (anything else raises a
1285 TypeError).
1287 Args:
1288 function: A function from a copy of the mobject to its end state.
1289 mobject: The mobject to transform.
1291 Examples:
1292 ```python
1293 import manimgx as m
1296 class ApplyFunctionExample(m.Scene):
1297 def construct(self) -> None:
1298 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5)
1299 self.add(square)
1301 def to_red_circle(mob: m.Mobject) -> m.Mobject:
1302 circle = m.Circle(radius=2, color=m.RED, fill_opacity=0.5)
1303 return circle.move_to(mob)
1305 self.play(m.ApplyFunction(to_red_circle, square))
1306 ```
1307 """
1309 def __init__(
1310 self,
1311 function: Callable[[Mobject], Mobject],
1312 mobject: Mobject,
1313 **kwargs: Unpack[TransformOptions],
1314 ) -> None:
1315 self.function = function
1316 super().__init__(mobject, keys=(None, self._apply), **kwargs)
1318 def _apply(self, copy: Mobject) -> Mobject:
1319 return self.function(copy)
1322class ApplyMatrix(ApplyPointwiseFunction):
1323 """Transform a mobject by a matrix: each point p goes to M·p.
1325 A 2 × 2 matrix acts on x and y, keeping z; a 3 × 3 one on all three (any other shape
1326 raises a ValueError). The points travel in straight lines. It runs 3 seconds.
1328 Args:
1329 matrix: The matrix, 2 × 2 or 3 × 3, as nested lists or an array.
1330 mobject: The mobject to transform.
1331 about_point: The point that stays where it is.
1333 Examples:
1334 ```python
1335 import manimgx as m
1338 class ApplyMatrixExample(m.Scene):
1339 def construct(self) -> None:
1340 matrix = [[1, 1], [0, 2 / 3]]
1341 plane = m.NumberPlane()
1342 text = m.Text("Hello World!", font_size=72)
1343 self.add(plane, text)
1344 self.play(m.ApplyMatrix(matrix, plane), m.ApplyMatrix(matrix, text))
1345 ```
1346 """
1348 def __init__(
1349 self,
1350 matrix: npt.ArrayLike,
1351 mobject: Mobject,
1352 about_point: Point3DLike = ORIGIN,
1353 **kwargs: Unpack[TransformOptions],
1354 ) -> None:
1355 matrix = np.array(matrix)
1356 if matrix.shape == (2, 2):
1357 matrix = np.block(
1358 [[matrix, np.zeros((2, 1))], [np.zeros((1, 2)), np.ones((1, 1))]]
1359 )
1360 elif matrix.shape != (3, 3):
1361 raise ValueError("Matrix has bad dimensions")
1362 center = np.asarray(about_point, dtype=float)
1363 super().__init__(
1364 lambda p: np.dot(p - center, matrix.T) + center, mobject, **kwargs
1365 )
1368class ApplyComplexFunction(_ApplyMethod):
1369 """Transform a mobject into its image under a function of a complex number.
1371 Each point (x, y, z) is taken as x + iy and travels in a straight line to its image
1372 under the function, keeping z, and a path's curves are mapped as
1373 [apply_function][manimgx.Mobject.apply_function] maps them.
1375 Args:
1376 function: A function from a complex number to a complex number.
1377 mobject: The mobject to move.
1379 Examples:
1380 ```python
1381 import manimgx as m
1384 class ApplyComplexFunctionExample(m.Scene):
1385 def construct(self) -> None:
1386 plane = m.NumberPlane(x_range=(-3, 3, 0.5), y_range=(-3, 3, 0.5))
1387 plane.prepare_for_nonlinear_transform()
1388 self.add(plane)
1389 self.play(m.ApplyComplexFunction(lambda z: z**2 / 4, plane), run_time=2)
1390 ```
1391 """
1393 def __init__(
1394 self,
1395 function: Callable[[complex], complex],
1396 mobject: Mobject,
1397 **kwargs: Unpack[TransformOptions],
1398 ) -> None:
1399 self.function = function
1400 super().__init__(mobject.apply_complex_function, function, **kwargs)
1403class CyclicReplace(Transform):
1404 """Move each mobject to the place of the next one, and the last to the first's.
1406 Each travels along an arc, of 90° by default (`path_arc`). A group given alone is
1407 taken as the mobjects.
1409 Args:
1410 *mobjects: The mobjects, in the order of the cycle.
1412 Examples:
1413 ```python
1414 import manimgx as m
1417 class CyclicReplaceExample(m.Scene):
1418 def construct(self) -> None:
1419 shapes = m.VGroup(
1420 m.Square(color=m.BLUE),
1421 m.Circle(color=m.YELLOW),
1422 m.Triangle(color=m.GREEN),
1423 m.Star(color=m.RED),
1424 ).arrange(buff=1)
1425 self.add(shapes)
1426 self.play(m.CyclicReplace(*shapes))
1427 self.play(m.CyclicReplace(*shapes))
1428 ```
1429 """
1431 def __init__(self, *mobjects: Mobject, **kwargs: Unpack[TransformOptions]) -> None:
1432 self.group = (
1433 mobjects[0]
1434 if len(mobjects) == 1 and isinstance(mobjects[0], Group)
1435 else _gathered(*mobjects)
1436 )
1437 kwargs.setdefault("path_arc", 90 * DEGREES)
1438 super().__init__(self.group, keys=(None, self._cycled), **kwargs)
1440 def _cycled(self, target: Mobject) -> Mobject:
1441 for m1, m2 in zip([target[-1], *target[:-1]], self.group, strict=True):
1442 m1.move_to(m2)
1443 return target
1446class Swap(CyclicReplace):
1447 """Swap the places of two mobjects, each along an arc.
1449 The same as [`CyclicReplace`][manimgx.CyclicReplace], which with two mobjects moves
1450 each to the other's place.
1452 Args:
1453 *mobjects: The two mobjects.
1454 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions].
1456 Examples:
1457 ```python
1458 import manimgx as m
1461 class SwapExample(m.Scene):
1462 def construct(self) -> None:
1463 square = m.Square(side_length=2, color=m.BLUE, fill_opacity=1)
1464 circle = m.Circle(color=m.RED, fill_opacity=1)
1465 square.shift(2 * m.LEFT)
1466 circle.shift(2 * m.RIGHT)
1467 self.add(square, circle)
1468 self.play(m.Swap(square, circle))
1469 ```
1470 """
1473class FadeTransform(Transform):
1474 """Cross-fade a mobject into another, each moving onto the other's place and size.
1476 The mobject fades out as it moves and stretches onto `target_mobject`, and the
1477 target fades in from the mobject's place and size. When it finishes, the target is
1478 in the scene and the mobject is not (it is back as it was when the animation
1479 began).
1481 Args:
1482 mobject: The mobject to fade out.
1483 target_mobject: The mobject to fade in; it joins the scene.
1484 stretch: Whether each is stretched to the other's width and height; if not, it
1485 is scaled evenly to match the dimension `dim_to_match`.
1486 dim_to_match: The dimension matched when not stretching: 0 the width, 1 the
1487 height.
1489 Examples:
1490 ```python
1491 import manimgx as m
1494 class FadeTransformExample(m.Scene):
1495 def construct(self) -> None:
1496 rectangle = m.Rectangle(
1497 width=4, height=1.5, color=m.BLUE, fill_opacity=0.5
1498 ).shift(3 * m.LEFT)
1499 circle = m.Circle(radius=1.5, color=m.YELLOW, fill_opacity=0.5)
1500 circle.shift(3 * m.RIGHT)
1501 self.add(rectangle)
1502 self.play(m.FadeTransform(rectangle, circle, run_time=2))
1503 ```
1504 """
1506 def __init__(
1507 self,
1508 mobject: Mobject,
1509 target_mobject: Mobject,
1510 stretch: bool = True,
1511 dim_to_match: int = 1,
1512 **kwargs: Unpack[TransformOptions],
1513 ) -> None:
1514 self.to_add_on_completion, self.stretch, self.dim_to_match = (
1515 target_mobject,
1516 stretch,
1517 dim_to_match,
1518 )
1519 super().__init__(
1520 Group(mobject, target_mobject.copy()),
1521 keys=(self._fading_in, self._faded_out),
1522 **kwargs,
1523 )
1525 def _fading_in(self, group: Mobject) -> Mobject:
1526 """Where it starts: the target ghosted onto the mobject."""
1527 return self._ghosted(group, 1, 0)
1529 def _faded_out(self, group: Mobject) -> Mobject:
1530 """Where it ends: the mobject ghosted onto the target."""
1531 return self._ghosted(group, 0, 1)
1533 def _ghosted(self, group: Mobject, i: int, j: int) -> Mobject:
1534 """The group with its part i ghosted onto its part j."""
1535 self.ghost_to(group[i], group[j])
1536 return group
1538 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1539 def ghost_to(self, source: Mobject, target: Mobject) -> None:
1540 """Fit a mobject onto another and make it transparent.
1542 It is stretched, or scaled to match (`stretch`, `dim_to_match`): the state one
1543 side of the cross-fade fades from or to. `begin` calls it for both sides.
1545 Args:
1546 source: The mobject to fit and make transparent.
1547 target: The mobject it is fitted onto; if it is empty, `source` stays in
1548 place.
1549 """
1550 if target.get_num_points() or target.submobjects:
1551 source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match)
1552 source.set_opacity(0)
1554 def _ends_as_given(self) -> bool:
1555 return True # the mobject leaves as it was, and the target comes in as it is
1557 def clean_up_from_scene(self, scene: Scene) -> None:
1558 Animation.clean_up_from_scene(self, scene)
1559 scene.remove(self.mobject)
1560 scene.add(self.to_add_on_completion)
1563class FadeTransformPieces(FadeTransform):
1564 """Cross-fade a mobject into another, part by part.
1566 The parts of the two are matched up, and each part cross-fades onto its match as
1567 [`FadeTransform`][manimgx.FadeTransform] does for a whole.
1569 Args:
1570 mobject: The mobject to fade out.
1571 target_mobject: The mobject to fade in; it joins the scene.
1572 stretch: Whether each part is stretched to its match's width and height; if not,
1573 it is scaled evenly to match the dimension `dim_to_match`.
1574 dim_to_match: The dimension matched when not stretching: 0 the width, 1 the
1575 height.
1576 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions].
1578 Examples:
1579 ```python
1580 import manimgx as m
1583 class FadeTransformPiecesExample(m.Scene):
1584 def construct(self) -> None:
1585 source = m.VGroup(m.Square(), m.Circle().shift(m.LEFT + m.UP))
1586 target = m.VGroup(m.Circle(), m.Triangle().shift(m.RIGHT + m.DOWN))
1587 source.set_color(m.BLUE).shift(3 * m.LEFT)
1588 target.set_color(m.YELLOW).shift(3 * m.RIGHT)
1589 self.add(source)
1590 self.play(m.FadeTransformPieces(source, target, run_time=2))
1591 ```
1592 """
1594 def _ghosted(self, group: Mobject, i: int, j: int) -> Mobject:
1595 group[0].align_submobjects(group[1]) # the pieces matched up
1596 return super()._ghosted(group, i, j)
1598 def ghost_to(self, source: Mobject, target: Mobject) -> None:
1599 for sm0, sm1 in zip(source.get_family(), target.get_family(), strict=True):
1600 super().ghost_to(sm0, sm1)
1603class FocusOn(Transform):
1604 """Close a spotlight in on a point.
1606 A transparent disc covering the frame shrinks onto `focus_point`, turning `color` at
1607 `opacity` as it closes, and is gone when the animation finishes; it follows a
1608 mobject that moves. It runs 2 seconds.
1610 Args:
1611 focus_point: The point to focus on, or a mobject whose center to focus on.
1612 opacity: The disc's opacity at the end.
1613 color: The disc's color.
1615 Examples:
1616 ```python
1617 import manimgx as m
1620 class FocusOnExample(m.Scene):
1621 def construct(self) -> None:
1622 dot = m.Dot(2 * m.DOWN, radius=0.2, color=m.YELLOW)
1623 self.add(m.Text("Focus on the dot below", font_size=60), dot)
1624 self.play(m.FocusOn(dot))
1625 ```
1626 """
1628 defaults: ClassVar[AnimationOptions] = {"run_time": 2.0, "remover": True}
1630 def __init__(
1631 self,
1632 focus_point: Point3DLike | Mobject,
1633 opacity: float = 0.2,
1634 color: ParsableManimColor = GREY,
1635 **kwargs: Unpack[AnimationOptions],
1636 ) -> None:
1637 from manimgx.mobjects.shapes import Dot
1639 self.focus_point, self.color, self.opacity = focus_point, color, opacity
1640 start = Dot(
1641 radius=config.frame_x_radius + config.frame_y_radius,
1642 stroke_width=0,
1643 fill_color=color,
1644 fill_opacity=0,
1645 )
1646 target = Dot(radius=0).set_fill(color, opacity=opacity)
1647 target.add_updater(
1648 lambda d: d.move_to(focus_point)
1649 ) # its own object, following the point
1650 super().__init__(start, target, **kwargs)
1653class UpdateFromFunc[M: Mobject = Mobject](Animation[M]):
1654 """Call a function on a mobject at every frame, for the animation's run time.
1656 The function gets the mobject, not the progress: use it to keep a mobject up to date
1657 while other animations play. The mobject's own updaters act on it directly
1658 (`suspend_mobject_updating` is False).
1660 Args:
1661 mobject: The mobject to update.
1662 update_function: A function of the mobject, called at every frame.
1664 Examples:
1665 ```python
1666 import manimgx as m
1669 class UpdateFromFuncExample(m.Scene):
1670 def construct(self) -> None:
1671 dot = m.Dot(4 * m.LEFT, radius=0.2, color=m.YELLOW)
1672 label = m.Text("dot", font_size=60)
1673 self.add(dot, label)
1674 self.play(
1675 dot.animate.shift(8 * m.RIGHT),
1676 m.UpdateFromFunc(label, lambda mob: mob.next_to(dot, m.UP)),
1677 run_time=2,
1678 )
1679 ```
1680 """
1682 keys: Sequence[Key] = ()
1684 defaults: ClassVar[AnimationOptions] = {"suspend_mobject_updating": False}
1686 def __init__(
1687 self,
1688 mobject: M,
1689 update_function: Callable[[M], object],
1690 **kwargs: Unpack[AnimationOptions],
1691 ) -> None:
1692 self.update_function = update_function
1693 super().__init__(mobject, **kwargs)
1695 def interpolate_mobject(self, alpha: float) -> None:
1696 self.update_function(self.mobject)
1699class UpdateFromAlphaFunc[M: Mobject = Mobject](Animation[M]):
1700 """Call a function on a mobject at every frame, with the animation's progress.
1702 The function gets the mobject and the progress, eased by the rate function, and sets
1703 the mobject as it is at that progress. The mobject's own updaters act on it directly
1704 (`suspend_mobject_updating` is False).
1706 Args:
1707 mobject: The mobject to update.
1708 update_function: A function of the mobject and the eased progress, from 0 to 1.
1710 Examples:
1711 ```python
1712 import manimgx as m
1715 class UpdateFromAlphaFuncExample(m.Scene):
1716 def construct(self) -> None:
1717 square = m.Square(side_length=2, color=m.BLUE, fill_opacity=0.5)
1719 def slide(mob: m.Square, alpha: float) -> None:
1720 mob.move_to((8 * alpha - 4) * m.RIGHT)
1721 mob.set_color(m.interpolate_color(m.BLUE, m.YELLOW, alpha))
1723 self.play(m.UpdateFromAlphaFunc(square, slide, run_time=2))
1724 ```
1725 """
1727 keys: Sequence[Key] = ()
1729 defaults: ClassVar[AnimationOptions] = {"suspend_mobject_updating": False}
1731 def __init__(
1732 self,
1733 mobject: M,
1734 update_function: Callable[[M, float], object],
1735 **kwargs: Unpack[AnimationOptions],
1736 ) -> None:
1737 self.update_function = update_function
1738 super().__init__(mobject, **kwargs)
1740 def interpolate_mobject(self, alpha: float) -> None:
1741 self.update_function(self.mobject, self.rate_func(alpha))
1744class MaintainPositionRelativeTo(Animation):
1745 """Keep a mobject at the same offset from another's center, at every frame.
1747 The offset is the one between their centers when the animation is made; play it
1748 together with the animations that move `tracked_mobject`.
1750 Args:
1751 mobject: The mobject to keep in place.
1752 tracked_mobject: The mobject it follows.
1754 Examples:
1755 ```python
1756 import manimgx as m
1759 class MaintainPositionRelativeToExample(m.Scene):
1760 def construct(self) -> None:
1761 leader = m.Square(side_length=2, color=m.BLUE, fill_opacity=0.5)
1762 follower = m.Circle(color=m.YELLOW).next_to(leader, m.RIGHT, buff=0.5)
1763 m.VGroup(leader, follower).shift(4 * m.LEFT + 1.5 * m.DOWN)
1764 self.add(leader, follower)
1765 self.play(
1766 leader.animate.shift(5 * m.RIGHT + 3 * m.UP),
1767 m.MaintainPositionRelativeTo(follower, leader),
1768 run_time=2,
1769 )
1770 ```
1771 """
1773 keys: Sequence[Key] = ()
1775 def __init__(
1776 self,
1777 mobject: Mobject,
1778 tracked_mobject: Mobject,
1779 **kwargs: Unpack[AnimationOptions],
1780 ) -> None:
1781 self.tracked_mobject = tracked_mobject
1782 self.diff = mobject.get_center() - tracked_mobject.get_center()
1783 super().__init__(mobject, **kwargs)
1785 def interpolate_mobject(self, alpha: float) -> None:
1786 self.mobject.shift(
1787 self.tracked_mobject.get_center() - self.mobject.get_center() + self.diff
1788 )
1791class Rotating(Rotate):
1792 """Rotate a mobject at a steady pace: by default, a full turn in 5 seconds.
1794 A [`Rotate`][manimgx.Rotate] whose angle is [`TAU`][manimgx.TAU] unless given
1795 another, at an even pace (`linear`), over 5 seconds.
1797 Args:
1798 mobject: The mobject to rotate.
1799 angle: The angle, in radians, counterclockwise about `axis`.
1800 axis: The axis it turns about; the default, [`OUT`][manimgx.OUT], turns it in
1801 the plane of the screen.
1802 about_point: The pivot; None to take it from `about_edge`, or the center.
1803 about_edge: The direction of the point of its bounding box it turns about, when
1804 no `about_point` is given.
1806 Examples:
1807 ```python
1808 import manimgx as m
1811 class RotatingExample(m.Scene):
1812 def construct(self) -> None:
1813 hand = m.Arrow(m.ORIGIN, 2.5 * m.UP, buff=0, color=m.YELLOW)
1814 self.add(m.Circle(radius=3, color=m.GREY), hand)
1815 self.play(m.Rotating(hand, -m.TAU, about_point=m.ORIGIN, run_time=4))
1816 ```
1817 """
1819 # timed as CE's Rotating (5 s, linear, a full turn): a tween along circles, not a
1820 # procedure (perth-e9's)
1821 defaults: ClassVar[AnimationOptions] = {"run_time": 5.0, "rate_func": linear}
1823 def __init__(
1824 self,
1825 mobject: Mobject,
1826 angle: float = TAU,
1827 axis: Vector3DLike = OUT,
1828 about_point: Point3DLike | None = None,
1829 about_edge: Vector3DLike | None = None,
1830 **kwargs: Unpack[TransformOptions],
1831 ) -> None:
1832 super().__init__(mobject, angle, axis, about_point, about_edge, **kwargs)
1835class MoveAlongPath(Transform):
1836 """Move a mobject along a path.
1838 Its center travels along `path` from the path's start to its end, at an even speed
1839 along its length (as eased by the rate function), and the mobject keeps its shape.
1840 It starts at the path's start, wherever it was. Its own updaters act on it directly
1841 while it moves (`suspend_mobject_updating` is False).
1843 Args:
1844 mobject: The mobject to move.
1845 path: The curve it travels along.
1847 Examples:
1848 ```python
1849 import numpy as np
1851 import manimgx as m
1854 class MoveAlongPathExample(m.Scene):
1855 def construct(self) -> None:
1856 path = m.FunctionGraph(lambda x: 2 * np.sin(x), x_range=(-6, 6))
1857 dot = m.Dot(radius=0.2, color=m.ORANGE)
1858 self.add(path.set_color(m.GREY), dot)
1859 self.play(m.MoveAlongPath(dot, path, run_time=3))
1860 ```
1861 """
1863 # a tween whose path is the curve itself, not a procedure (perth-e9's)
1864 defaults: ClassVar[AnimationOptions] = {"suspend_mobject_updating": False}
1866 def __init__(
1867 self, mobject: Mobject, path: VMobject, **kwargs: Unpack[TransformOptions]
1868 ) -> None:
1869 self.path = path
1870 kwargs["path_func"] = Path(steps=(path.point_from_proportion,))
1871 super().__init__(
1872 mobject,
1873 keys=tuple(
1874 (
1875 lambda m, end=end: m.move_to(path.point_from_proportion(end))
1876 for end in (0, 1)
1877 )
1878 ),
1879 **kwargs,
1880 )
1883class Homotopy(Animation):
1884 """Deform a mobject by a homotopy: a function of each point and the progress.
1886 At progress t, from 0 to 1 (eased by the rate function), the mobject is the image of
1887 the mobject as it began: each point (x, y, z) goes to `homotopy(x, y, z, t)`, and a
1888 path's curves are mapped as [apply_function][manimgx.Mobject.apply_function] maps
1889 them. It runs 3 seconds.
1891 Args:
1892 homotopy: A function of x, y, z and t, returning where the point is at t.
1893 mobject: The mobject to deform.
1894 apply_function_kwargs: Where the coordinates are measured from:
1895 `{"about_point": ...}` or `{"about_edge": ...}`; None for the origin.
1897 Examples:
1898 ```python
1899 import numpy as np
1901 import manimgx as m
1904 class HomotopyExample(m.Scene):
1905 def construct(self) -> None:
1906 line = m.FunctionGraph(lambda x: 0, x_range=(-6, 6), color=m.BLUE)
1908 def wave(x: float, y: float, z: float, t: float) -> tuple[float, ...]:
1909 return (x, y + 1.5 * t * np.sin(2 * x - 6 * t), z)
1911 self.add(line)
1912 self.play(m.Homotopy(wave, line))
1913 ```
1914 """
1916 defaults: ClassVar[AnimationOptions] = {"run_time": 3.0}
1918 def __init__(
1919 self,
1920 homotopy: Callable[[float, float, float, float], Point3DLike],
1921 mobject: Mobject,
1922 apply_function_kwargs: Pivot | None = None,
1923 **kwargs: Unpack[AnimationOptions],
1924 ) -> None:
1925 self.homotopy = homotopy
1926 self.apply_function_kwargs: Pivot = apply_function_kwargs or {}
1927 super().__init__(mobject, **kwargs)
1929 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
1930 def function_at_time_t(self, t: float) -> Callable[[Point3D], Point3D]:
1931 """Return the homotopy at one progress, as a function of a point.
1933 Args:
1934 t: The progress, from 0 to 1.
1936 Returns:
1937 A function from a point to where it is at `t`.
1938 """
1939 return lambda p: np.array(self.homotopy(p[0], p[1], p[2], t))
1941 def interpolate_submobject(
1942 self, submobject: Mobject, starting_submobject: Mobject, alpha: float
1943 ) -> None:
1944 submobject.points = starting_submobject.points
1945 submobject.apply_function(
1946 self.function_at_time_t(alpha), **self.apply_function_kwargs
1947 )
1950class ComplexHomotopy(Homotopy):
1951 """Deform a mobject by a complex homotopy: a function of x + iy and the progress.
1953 At progress t, from 0 to 1 (eased by the rate function), the mobject is the image of
1954 the mobject as it began: each point (x, y, z) goes to `complex_homotopy(x + iy, t)`,
1955 keeping z, and a path's curves are mapped as
1956 [apply_function][manimgx.Mobject.apply_function] maps them. It runs 3 seconds.
1958 Args:
1959 complex_homotopy: A function of z and t, returning where the point is at t, as a
1960 complex number.
1961 mobject: The mobject to deform.
1963 Examples:
1964 ```python
1965 import numpy as np
1967 import manimgx as m
1970 class ComplexHomotopyExample(m.Scene):
1971 def construct(self) -> None:
1972 plane = m.NumberPlane(x_range=(-3, 3), y_range=(-3, 3))
1973 plane.prepare_for_nonlinear_transform()
1974 self.add(plane)
1975 self.play(
1976 m.ComplexHomotopy(lambda z, t: z * np.exp(0.5j * t * abs(z)), plane)
1977 )
1978 ```
1979 """
1981 def __init__(
1982 self,
1983 complex_homotopy: Callable[[complex, float], complex],
1984 mobject: Mobject,
1985 **kwargs: Unpack[AnimationOptions],
1986 ) -> None:
1987 def homotopy(
1988 x: float, y: float, z: float, t: float
1989 ) -> tuple[float, float, float]:
1990 c = complex_homotopy(complex(x, y), t)
1991 return (c.real, c.imag, z)
1993 super().__init__(homotopy, mobject, **kwargs)
1996class ApplyWave(Homotopy):
1997 """Send a wave through a mobject, from left to right.
1999 Its points are displaced along `direction`, by up to `amplitude`, as the wave passes
2000 them, and are back in place once it has passed. It runs 2 seconds.
2002 Args:
2003 mobject: The mobject to wave.
2004 direction: The direction the points are displaced in.
2005 amplitude: How far they are displaced at most, in scene units.
2006 wave_func: The shape of each ripple's rise: a rate function.
2007 time_width: The wave's width, as a fraction of the mobject's width.
2008 ripples: How many ripples the wave has.
2010 Examples:
2011 ```python
2012 import manimgx as m
2015 class ApplyWaveExample(m.Scene):
2016 def construct(self) -> None:
2017 text = m.Text("WaveWaveWave", font_size=120)
2018 self.add(text)
2019 self.play(m.ApplyWave(text))
2020 self.play(m.ApplyWave(text, ripples=3, amplitude=0.4))
2021 ```
2022 """
2024 defaults: ClassVar[AnimationOptions] = {"run_time": 2.0}
2026 def __init__(
2027 self,
2028 mobject: Mobject,
2029 direction: Vector3DLike = UP,
2030 amplitude: float = 0.2,
2031 wave_func: Callable[[float], float] = smooth,
2032 time_width: float = 1,
2033 ripples: int = 1,
2034 **kwargs: Unpack[AnimationOptions],
2035 ) -> None:
2036 x_min, x_max = mobject.get_left()[0], mobject.get_right()[0]
2037 vect = amplitude * normalize(direction)
2039 def wave(t: float) -> float:
2040 t = 1 - t
2041 if t >= 1 or t <= 0:
2042 return 0
2043 phases = ripples * 2
2044 phase = int(t * phases)
2045 if phase == 0:
2046 return wave_func(t * phases)
2047 if phase == phases - 1:
2048 t -= phase / phases
2049 return (1 - wave_func(t * phases)) * (2 * (ripples % 2) - 1)
2050 phase = int((phase - 1) / 2)
2051 t -= (2 * phase + 1) / phases
2052 return (1 - 2 * wave_func(t * ripples)) * (1 - 2 * (phase % 2))
2054 def homotopy(x: float, y: float, z: float, t: float) -> np.ndarray:
2055 upper = interpolate(0, 1 + time_width, t)
2056 relative_x = inverse_interpolate(x_min, x_max, x)
2057 return (
2058 np.array([x, y, z])
2059 + wave(inverse_interpolate(upper - time_width, upper, relative_x))
2060 * vect
2061 )
2063 super().__init__(homotopy, mobject, **kwargs)
2066class PhaseFlow(Animation):
2067 """Carry a mobject's points along a vector field.
2069 Each point moves with the velocity `function` gives it where it is, for
2070 `virtual_time` units of the field's time over the animation, from where it is when
2071 the animation begins. The flow is integrated in steps of the field's time,
2072 `config.simulation_rate` a second of the animation, by the classical Runge–Kutta
2073 method, so it is the same at every frame rate; a frame between steps shows the flow
2074 carried on from the step before it. A path's curves are mapped as
2075 [apply_function][manimgx.Mobject.apply_function] maps them. It runs at an even pace
2076 (`linear`), and the mobject's own updaters act on it directly
2077 (`suspend_mobject_updating` is False).
2079 Args:
2080 function: The vector field: a function from a point to its velocity.
2081 mobject: The mobject to carry.
2082 virtual_time: How long the points flow, in the field's units of time.
2084 Examples:
2085 ```python
2086 import numpy as np
2088 import manimgx as m
2091 class PhaseFlowExample(m.Scene):
2092 def construct(self) -> None:
2093 square = m.Square(side_length=2, color=m.BLUE, fill_opacity=0.5)
2094 square.shift(3 * m.RIGHT)
2095 self.add(m.Dot(), square)
2097 def spiral(p: np.ndarray) -> np.ndarray:
2098 return np.array([-p[1] - 0.3 * p[0], p[0] - 0.3 * p[1], 0.0])
2100 self.play(m.PhaseFlow(spiral, square, virtual_time=m.PI, run_time=3))
2101 ```
2102 """
2104 keys: Sequence[Key] = ()
2106 defaults: ClassVar[AnimationOptions] = {
2107 "suspend_mobject_updating": False,
2108 "rate_func": linear,
2109 }
2111 def __init__(
2112 self,
2113 function: Callable[[Point3D], Point3D],
2114 mobject: Mobject,
2115 virtual_time: float = 1,
2116 **kwargs: Unpack[AnimationOptions],
2117 ) -> None:
2118 self.virtual_time, self.function = virtual_time, function
2119 super().__init__(mobject, **kwargs)
2121 def begin(self) -> None:
2122 super().begin()
2123 # the flow's steps, whenever the frames fall: those taken, and where they left it
2124 self._grid = max(1, round(config.simulation_rate * self.run_time))
2125 self._taken = 0
2126 self._left = [(m, m._geometry) for m in self.mobject.get_family()]
2128 def interpolate_mobject(self, alpha: float) -> None:
2129 at = self.rate_func(alpha) * self._grid # where the flow is, in steps
2130 step = self.virtual_time / self._grid
2131 for mob, geometry in self._left:
2132 mob._geometry = geometry
2133 while self._taken != (whole := math.floor(at)):
2134 forward = self._taken < whole
2135 self._flow(step if forward else -step)
2136 self._taken += 1 if forward else -1
2137 self._left = [(m, m._geometry) for m in self.mobject.get_family()]
2138 if at > whole:
2139 self._flow((at - whole) * step)
2141 def _flow(self, dt: float) -> None:
2142 """Carry the points on by `dt` of the field's time: a Runge–Kutta step."""
2143 field = self.function
2145 def carried(p: Point3D) -> Point3D:
2146 k1 = field(p)
2147 k2 = field(p + dt / 2 * k1)
2148 k3 = field(p + dt / 2 * k2)
2149 return p + dt / 6 * (k1 + 2 * k2 + 2 * k3 + field(p + dt * k3))
2151 self.mobject.apply_function(carried)
2154class Wiggle(Animation):
2155 """Wiggle a mobject: rock it back and forth while it swells and shrinks back.
2157 It grows to `scale_value` times its size and back, while turning back and forth by
2158 up to `rotation_angle`, `n_wiggles` swings in all, about its center or the given
2159 points. It runs 2 seconds.
2161 Args:
2162 mobject: The mobject to wiggle.
2163 scale_value: How many times its size it grows to, halfway through.
2164 rotation_angle: How far it turns each way at most, in radians.
2165 n_wiggles: How many swings it makes.
2166 scale_about_point: The point it grows about; None for its center.
2167 rotate_about_point: The point it turns about; None for its center.
2169 Examples:
2170 ```python
2171 import manimgx as m
2174 class WiggleExample(m.Scene):
2175 def construct(self) -> None:
2176 text = m.Text("Wiggle", font_size=144)
2177 self.add(text)
2178 self.play(m.Wiggle(text))
2179 ```
2180 """
2182 defaults: ClassVar[AnimationOptions] = {"run_time": 2.0}
2184 def __init__(
2185 self,
2186 mobject: Mobject,
2187 scale_value: float = 1.1,
2188 rotation_angle: float = 0.01 * TAU,
2189 n_wiggles: int = 6,
2190 scale_about_point: Point3DLike | None = None,
2191 rotate_about_point: Point3DLike | None = None,
2192 **kwargs: Unpack[AnimationOptions],
2193 ) -> None:
2194 self.scale_value, self.rotation_angle, self.n_wiggles = (
2195 scale_value,
2196 rotation_angle,
2197 n_wiggles,
2198 )
2199 self.scale_about_point = (
2200 None if scale_about_point is None else np.array(scale_about_point)
2201 )
2202 self.rotate_about_point = (
2203 None if rotate_about_point is None else np.array(rotate_about_point)
2204 )
2205 super().__init__(mobject, **kwargs)
2207 def interpolate_mobject(self, alpha: float) -> None:
2208 # the pivot: the whole's center as it began, once a frame (not the center of a
2209 # mobject half of whose parts this frame has wiggled already)
2210 self._center = self.frames[0].get_center()
2211 super().interpolate_mobject(alpha)
2213 def interpolate_submobject(
2214 self, submobject: Mobject, starting_submobject: Mobject, alpha: float
2215 ) -> None:
2216 submobject._geometry = starting_submobject._geometry
2217 submobject.scale(
2218 interpolate(1, self.scale_value, there_and_back(alpha)),
2219 about_point=(
2220 self._center
2221 if self.scale_about_point is None
2222 else self.scale_about_point
2223 ),
2224 )
2225 submobject.rotate(
2226 wiggle(alpha, self.n_wiggles) * self.rotation_angle,
2227 about_point=(
2228 self._center
2229 if self.rotate_about_point is None
2230 else self.rotate_about_point
2231 ),
2232 )
2235class ChangingDecimal[V: (float, complex) = float](Animation["DecimalNumber[V]"]):
2236 """Change the value a number shows with the animation's progress.
2238 At every frame, the number shows `number_update_func` of the progress, from 0 to 1,
2239 eased by the rate function.
2241 Args:
2242 decimal_mob: The number to change.
2243 number_update_func: A function from the progress to the value to show.
2245 Examples:
2246 ```python
2247 import manimgx as m
2250 class ChangingDecimalExample(m.Scene):
2251 def construct(self) -> None:
2252 number = m.DecimalNumber(0, font_size=144)
2253 self.add(number)
2254 self.play(m.ChangingDecimal(number, lambda a: 100 * a, run_time=3))
2255 ```
2256 """
2258 keys: Sequence[Key] = ()
2260 defaults: ClassVar[AnimationOptions] = {"suspend_mobject_updating": False}
2262 def __init__(
2263 self,
2264 decimal_mob: DecimalNumber[V],
2265 number_update_func: Callable[[float], V],
2266 **kwargs: Unpack[AnimationOptions],
2267 ) -> None:
2268 self.number_update_func = number_update_func
2269 super().__init__(decimal_mob, **kwargs)
2271 def interpolate_mobject(self, alpha: float) -> None:
2272 self.mobject.set_value(self.number_update_func(self.rate_func(alpha)))
2275class ChangeDecimalToValue[V: (float, complex) = float](ChangingDecimal[V]):
2276 """Count a number to a value.
2278 It goes from the value it has when the animation is made to `target_number`, eased
2279 by the rate function.
2281 Args:
2282 decimal_mob: The number to change.
2283 target_number: The value it ends at.
2285 Examples:
2286 ```python
2287 import manimgx as m
2290 class ChangeDecimalToValueExample(m.Scene):
2291 def construct(self) -> None:
2292 number = m.DecimalNumber(0, font_size=144)
2293 self.add(number)
2294 self.play(m.ChangeDecimalToValue(number, 3.14, run_time=2))
2295 ```
2296 """
2298 def __init__(
2299 self,
2300 decimal_mob: DecimalNumber[V],
2301 target_number: V,
2302 **kwargs: Unpack[AnimationOptions],
2303 ) -> None:
2304 start = decimal_mob.number
2305 super().__init__(
2306 decimal_mob, lambda a: interpolate(start, target_number, a), **kwargs
2307 )
2310class ShowIncreasingSubsets(Animation):
2311 """Show the submobjects of a group one more at a time.
2313 At progress p, eased by the rate function, the first ⌊p·n⌋ of its n submobjects are
2314 shown and the rest are hidden: left out of the picture, not changed, so each part
2315 shows as it is, whatever else plays on it. The group joins the scene when the
2316 animation begins. A part still hidden when the animation ends stays unseen, left
2317 transparent; a remover's group leaves the scene as it is. Pass `rate_func=linear` for
2318 an even pace.
2320 Args:
2321 group: The group whose submobjects are shown.
2322 int_func: How many are shown: a function of p·n (the default rounds down).
2324 Examples:
2325 ```python
2326 import manimgx as m
2329 class ShowIncreasingSubsetsExample(m.Scene):
2330 def construct(self) -> None:
2331 dots = m.VGroup(*(m.Dot(radius=0.4) for _ in range(8)))
2332 dots.arrange(buff=0.6).set_color_by_gradient(m.BLUE, m.YELLOW)
2333 self.play(m.ShowIncreasingSubsets(dots, rate_func=m.linear, run_time=2))
2334 ```
2335 """
2337 keys: Sequence[Key] = ()
2339 defaults: ClassVar[AnimationOptions] = {
2340 "suspend_mobject_updating": False,
2341 "introducer": True,
2342 }
2344 def __init__(
2345 self,
2346 group: Mobject,
2347 int_func: Callable[[float], float] = np.floor,
2348 **kwargs: Unpack[AnimationOptions],
2349 ) -> None:
2350 self.all_submobs, self.int_func = list(group.submobjects), int_func
2351 self._hidden: list[Mobject] = []
2352 super().__init__(group, **kwargs)
2354 @property
2355 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
2356 def hidden(self) -> Sequence[Mobject]:
2357 """The submobjects it has not shown yet, or no longer shows."""
2358 return self._hidden
2360 def interpolate_mobject(self, alpha: float) -> None:
2361 value = (
2362 1 - self.rate_func(alpha)
2363 if self.reverse_rate_function
2364 else self.rate_func(alpha)
2365 )
2366 self.update_submobject_list(int(self.int_func(value * len(self.all_submobs))))
2368 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
2369 def update_submobject_list(self, index: int) -> None:
2370 """Show the first `index` submobjects and hide the rest.
2372 `interpolate_mobject` calls it at every frame.
2374 Args:
2375 index: How many submobjects are shown.
2376 """
2377 self._hidden = self.all_submobs[max(index, 0) :]
2379 def _release(self) -> None:
2380 super()._release()
2381 # ended, what it hides stays unseen: transparent, the one way the scene holds a
2382 # part unseen (a remover's group leaves the scene as it is)
2383 if not self.is_remover():
2384 for part in self._hidden:
2385 part.set_opacity(0)
2386 self._hidden = []
2389class ShowSubmobjectsOneByOne(ShowIncreasingSubsets):
2390 """Show mobjects one at a time, each in place of the one before.
2392 At progress p, eased by the rate function, only the ⌈p·n⌉-th of the n mobjects is
2393 shown, as it is, and the others are hidden; when the animation ends, those it hides
2394 stay unseen, left transparent. Pass `rate_func=linear` for an even pace.
2396 Args:
2397 group: The mobjects to show in turn.
2398 int_func: Which one is shown: a function of p·n (the default rounds up).
2400 Examples:
2401 ```python
2402 import manimgx as m
2405 class ShowSubmobjectsOneByOneExample(m.Scene):
2406 def construct(self) -> None:
2407 polygons = (
2408 m.VGroup(
2409 *(m.RegularPolygon(n, fill_opacity=1) for n in range(3, 9))
2410 )
2411 .set_color(m.YELLOW)
2412 .scale(2.5)
2413 )
2414 self.play(
2415 m.ShowSubmobjectsOneByOne(polygons, rate_func=m.linear, run_time=3)
2416 )
2417 ```
2418 """
2420 def __init__(
2421 self,
2422 group: Iterable[Mobject],
2423 int_func: Callable[[float], float] = np.ceil,
2424 **kwargs: Unpack[AnimationOptions],
2425 ) -> None:
2426 super().__init__(_gathered(*group), int_func=int_func, **kwargs)
2428 def update_submobject_list(self, index: int) -> None:
2429 self._hidden = [m for i, m in enumerate(self.all_submobs) if i != index - 1]
2432class AddTextLetterByLetter(ShowIncreasingSubsets):
2433 """Type a text in, one letter at a time.
2435 The letters appear one after another at an even pace (`linear`), `time_per_char`
2436 seconds each unless a `run_time` is given. The text joins the scene when the
2437 animation begins.
2439 Args:
2440 text: The text to type, whose submobjects are its letters; a text without any
2441 raises a ValueError.
2442 int_func: How many letters are shown: a function of the progress times the
2443 number of letters (the default rounds up, so the first shows at once).
2444 time_per_char: How long each letter takes, in seconds.
2446 Examples:
2447 ```python
2448 import manimgx as m
2451 class AddTextLetterByLetterExample(m.Scene):
2452 def construct(self) -> None:
2453 text = m.Text("Hello, world!", font_size=96)
2454 self.play(m.AddTextLetterByLetter(text, time_per_char=0.15))
2455 ```
2456 """
2458 defaults: ClassVar[AnimationOptions] = {"rate_func": linear}
2460 def __init__(
2461 self,
2462 text: Mobject,
2463 int_func: Callable[[float], float] = np.ceil,
2464 time_per_char: float = 0.1,
2465 **kwargs: Unpack[AnimationOptions],
2466 ) -> None:
2467 self.time_per_char = time_per_char
2468 if not text.family_members_with_points():
2469 raise ValueError(
2470 f"The text mobject {text} does not seem to contain any characters."
2471 )
2472 kwargs.setdefault(
2473 "run_time", max(1 / config.frame_rate, time_per_char) * len(text)
2474 )
2475 super().__init__(text, int_func=int_func, **kwargs)
2478class RemoveTextLetterByLetter(AddTextLetterByLetter):
2479 """Remove a text one letter at a time, from the last, and take it out of the scene.
2481 The reverse of [`AddTextLetterByLetter`][manimgx.AddTextLetterByLetter]: the letters
2482 disappear from the last to the first, `time_per_char` seconds each unless a
2483 `run_time` is given. The text leaves the scene when the animation finishes, as it
2484 was before it: adding it again shows it.
2486 Args:
2487 text: The text to remove, whose submobjects are its letters; a text without any
2488 raises a ValueError.
2489 int_func: How many letters are still shown: a function of what is left of the
2490 progress times the number of letters (the default rounds up).
2491 time_per_char: How long each letter takes, in seconds.
2492 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions].
2494 Examples:
2495 ```python
2496 import manimgx as m
2499 class RemoveTextLetterByLetterExample(m.Scene):
2500 def construct(self) -> None:
2501 text = m.Text("Hello, world!", font_size=96)
2502 self.add(text)
2503 self.play(m.RemoveTextLetterByLetter(text, time_per_char=0.15))
2504 ```
2505 """
2507 defaults: ClassVar[AnimationOptions] = {
2508 "reverse_rate_function": True,
2509 "introducer": False,
2510 "remover": True,
2511 }
2514class TypeWithCursor(AddTextLetterByLetter):
2515 """Type a text in letter by letter, with a cursor after the last letter typed.
2517 The letters appear as with [`AddTextLetterByLetter`][manimgx.AddTextLetterByLetter],
2518 and the cursor, shown as it is, moves along after them. The cursor becomes part of
2519 the text, at its end, and stays there when the animation finishes unless
2520 `leave_cursor_on` is False. The text joins the scene when the animation begins.
2522 Args:
2523 text: The text to type, whose submobjects are its letters.
2524 cursor: The cursor: any mobject, such as a thin rectangle.
2525 buff: The gap between the last letter and the cursor, in scene units.
2526 keep_cursor_y: Whether the cursor keeps its own height as it moves; if not, it
2527 moves at the text's middle height.
2528 leave_cursor_on: Whether the cursor stays at the end of the text when the
2529 animation finishes.
2530 time_per_char: How long each letter takes, in seconds.
2532 Examples:
2533 ```python
2534 import manimgx as m
2537 class TypeWithCursorExample(m.Scene):
2538 def construct(self) -> None:
2539 text = m.Text("Typing...", font_size=96, color=m.PURPLE)
2540 cursor = m.Rectangle(m.GREY_A, height=1.1, width=0.4, fill_opacity=1)
2541 cursor.move_to(text[0])
2542 self.play(m.TypeWithCursor(text, cursor))
2543 ```
2544 """
2546 def __init__(
2547 self,
2548 text: Mobject,
2549 cursor: Mobject,
2550 buff: float = 0.1,
2551 keep_cursor_y: bool = True,
2552 leave_cursor_on: bool = True,
2553 time_per_char: float = 0.1,
2554 **kwargs: Unpack[AnimationOptions],
2555 ) -> None:
2556 self.cursor, self.buff, self.keep_cursor_y, self.leave_cursor_on = (
2557 cursor,
2558 buff,
2559 keep_cursor_y,
2560 leave_cursor_on,
2561 )
2562 super().__init__(text, time_per_char=time_per_char, **kwargs)
2564 def begin(self) -> None:
2565 self.y_cursor = self.cursor.get_y()
2566 self.cursor_start = self.mobject.get_center()
2567 if self.keep_cursor_y:
2568 self.cursor.set_y(self.y_cursor)
2569 self.mobject.add(self.cursor)
2570 super().begin()
2572 def finish(self) -> None:
2573 if not self.leave_cursor_on:
2574 self.mobject.remove(self.cursor)
2575 super().finish()
2577 def clean_up_from_scene(self, scene: Scene) -> None:
2578 if not self.leave_cursor_on:
2579 scene.remove(self.cursor)
2580 super().clean_up_from_scene(scene)
2582 def update_submobject_list(self, index: int) -> None:
2583 super().update_submobject_list(index)
2584 anchor = self.all_submobs[index - 1] if index else self.all_submobs[0]
2585 (
2586 self.cursor.next_to(anchor, RIGHT, buff=self.buff)
2587 if index
2588 else self.cursor.move_to(anchor)
2589 ).set_y(self.cursor_start[1])
2590 if self.keep_cursor_y:
2591 self.cursor.set_y(self.y_cursor)
2594class UntypeWithCursor(TypeWithCursor):
2595 """Delete a text letter by letter, with a cursor after the last letter left.
2597 The reverse of [`TypeWithCursor`][manimgx.TypeWithCursor]: the letters disappear
2598 from the last to the first. The text leaves the scene when the animation finishes,
2599 as it was before it (adding it again shows it); the cursor becomes part of the
2600 text, and leaves with it.
2602 Args:
2603 text: The text to delete, whose submobjects are its letters.
2604 cursor: The cursor: any mobject, such as a thin rectangle.
2605 buff: The gap between the last letter and the cursor, in scene units.
2606 keep_cursor_y: Whether the cursor keeps its own height as it moves; if not, it
2607 moves at the text's middle height.
2608 leave_cursor_on: Whether the cursor stays part of the text when the animation
2609 finishes.
2610 time_per_char: How long each letter takes, in seconds.
2611 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions].
2613 Examples:
2614 ```python
2615 import manimgx as m
2618 class UntypeWithCursorExample(m.Scene):
2619 def construct(self) -> None:
2620 text = m.Text("Deleting...", font_size=96, color=m.PURPLE)
2621 cursor = m.Rectangle(m.GREY_A, height=1.1, width=0.4, fill_opacity=1)
2622 cursor.move_to(text[0])
2623 self.add(text)
2624 self.play(m.UntypeWithCursor(text, cursor))
2625 ```
2626 """
2628 defaults: ClassVar[AnimationOptions] = {
2629 "reverse_rate_function": True,
2630 "introducer": False,
2631 "remover": True,
2632 }
2635class SpiralIn(Animation):
2636 """Fly the submobjects of a mobject in from far away, spiralling into place.
2638 Each comes home to where it is when the animation begins, from `scale_factor` + 1
2639 times as far from the mobject's center: on the way it turns once around that center
2640 (and back once about its own, so it keeps its orientation), and it fades in over the
2641 first `fade_in_fraction` of the way. The mobject joins the scene when the animation
2642 begins; making the animation changes nothing.
2644 Args:
2645 shapes: The mobject whose submobjects spiral in.
2646 scale_factor: How far out they start: `scale_factor` + 1 times as far from the
2647 center as their places.
2648 fade_in_fraction: The fraction of the way over which they fade in, from 0 to 1.
2650 Examples:
2651 ```python
2652 import manimgx as m
2655 class SpiralInExample(m.Scene):
2656 def construct(self) -> None:
2657 shapes = m.VGroup(
2658 m.Circle(color=m.GREEN, fill_opacity=1),
2659 m.Square(color=m.BLUE, fill_opacity=1),
2660 m.Triangle(color=m.YELLOW, fill_opacity=1),
2661 m.Star(color=m.RED, fill_opacity=1),
2662 ).arrange(buff=1)
2663 self.play(m.SpiralIn(shapes, run_time=2))
2664 ```
2665 """
2667 defaults: ClassVar[AnimationOptions] = {"introducer": True}
2669 def __init__(
2670 self,
2671 shapes: Mobject,
2672 scale_factor: float = 8,
2673 fade_in_fraction: float = 0.3,
2674 **kwargs: Unpack[AnimationOptions],
2675 ) -> None:
2676 self.scale_factor, self.fade_in_fraction = scale_factor, fade_in_fraction
2677 super().__init__(shapes, **kwargs)
2679 def interpolate_mobject(self, alpha: float) -> None:
2680 alpha = self.rate_func(alpha)
2681 homes = self.frames[0] # the first keyframe: the shapes as the animation began
2682 center = homes.get_center()
2683 for shape, home in zip(self.mobject, homes, strict=True):
2684 travel = (center - home.get_center()) * self.scale_factor
2685 fill, stroke = home.get_fill_opacity(), home.get_stroke_opacity()
2686 shape.become(home).shift(-travel * (1 - alpha))
2687 shape.rotate(TAU * alpha, about_point=center)
2688 shape.rotate(-TAU * alpha, about_point=shape.get_center_of_mass())
2689 shape.set_fill(opacity=min(fill, alpha * fill / self.fade_in_fraction))
2690 shape.set_stroke(
2691 opacity=min(stroke, alpha * stroke / self.fade_in_fraction)
2692 )
2695class AddTextWordByWord(Succession):
2696 """Type words in, letter by letter, pausing briefly after each word.
2698 Each submobject of `text_mobject` is a word, and the words come in turn: a word's own
2699 submobjects, its letters, appear one after another, `time_per_char` seconds each;
2700 then the word holds for 0.005 × (its number of letters)^1.5 seconds. Give it a group
2701 of words, such as a [`VGroup`][manimgx.VGroup] of [`Text`][manimgx.Text]s: the
2702 submobjects of a single `Text` are its letters, which have no parts of their own to
2703 type, so each appears whole in its turn.
2705 Args:
2706 text_mobject: The words: a group whose submobjects are words made of letters.
2707 time_per_char: How long each letter takes, in seconds.
2708 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions] for
2709 the whole.
2711 Examples:
2712 ```python
2713 import manimgx as m
2716 class AddTextWordByWordExample(m.Scene):
2717 def construct(self) -> None:
2718 words = m.VGroup(
2719 *(m.Text(word, font_size=120) for word in ("Word", "by", "word"))
2720 ).arrange(buff=0.5)
2721 self.play(m.AddTextWordByWord(words, time_per_char=0.12))
2722 ```
2723 """
2725 def __init__(
2726 self,
2727 text_mobject: Mobject,
2728 time_per_char: float = 0.06,
2729 **kwargs: Unpack[AnimationOptions],
2730 ) -> None:
2731 self.time_per_char = time_per_char
2732 anims = it.chain(
2733 *(
2734 [
2735 ShowIncreasingSubsets(w, run_time=time_per_char * len(w)),
2736 Animation(w, run_time=0.005 * len(w) ** 1.5),
2737 ]
2738 for w in text_mobject
2739 )
2740 )
2741 super().__init__(*anims, **kwargs)
2744class Flash(AnimationGroup):
2745 """Flash lines out from a point, like a burst of light.
2747 `num_lines` lines, `line_length` long and starting `flash_radius` from the point,
2748 shoot outward as passing flashes ([`ShowPassingFlash`][manimgx.ShowPassingFlash]),
2749 and are gone when the animation finishes. The animation options go to each line's
2750 flash.
2752 Args:
2753 point: The point to flash from, or a mobject whose center to flash from.
2754 line_length: Each line's length, in scene units.
2755 num_lines: How many lines.
2756 flash_radius: How far from the point the lines start, in scene units.
2757 line_stroke_width: The lines' width, in hundredths of a scene unit.
2758 color: The lines' color.
2759 time_width: Each line's flash window, as a fraction of its length.
2760 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions] for
2761 each line's flash.
2763 Examples:
2764 ```python
2765 import manimgx as m
2768 class FlashExample(m.Scene):
2769 def construct(self) -> None:
2770 circle = m.Circle(radius=2, color=m.BLUE, fill_opacity=0.5)
2771 self.add(circle)
2772 self.play(
2773 m.Flash(
2774 circle,
2775 line_length=1,
2776 num_lines=24,
2777 flash_radius=2.2,
2778 time_width=0.3,
2779 run_time=2,
2780 )
2781 )
2782 ```
2783 """
2785 def __init__(
2786 self,
2787 point: Point3DLike | Mobject,
2788 line_length: float = 0.2,
2789 num_lines: int = 12,
2790 flash_radius: float = 0.1,
2791 line_stroke_width: int = 3,
2792 color: ParsableManimColor = PURE_YELLOW,
2793 time_width: float = 1,
2794 **kwargs: Unpack[AnimationOptions],
2795 ) -> None:
2796 from manimgx.mobjects.shapes import Line
2798 self.point = (
2799 point.get_center()
2800 if isinstance(point, Mobject)
2801 else np.asarray(point, dtype=float)
2802 )
2803 self.color, self.time_width = color, time_width
2804 self.lines = VGroup()
2805 for angle in np.arange(0, TAU, TAU / num_lines):
2806 line = Line(self.point, self.point + line_length * RIGHT).shift(
2807 flash_radius * RIGHT
2808 )
2809 self.lines.add(line.rotate(angle, about_point=self.point))
2810 self.lines.set_color(color).set_stroke(width=line_stroke_width)
2811 super().__init__(
2812 *(
2813 ShowPassingFlash(line, time_width=time_width, **kwargs)
2814 for line in self.lines
2815 ),
2816 group=self.lines,
2817 )
2820class ShowPassingFlashWithThinningStrokeWidth(AnimationGroup):
2821 """Flash a stretch of a mobject's path along it, with a tail that thins behind it.
2823 `n_segments` passing flashes ([`ShowPassingFlash`][manimgx.ShowPassingFlash]) of
2824 copies of the mobject play together: their widths rise from none to the mobject's
2825 stroke width as their windows shrink from `time_width` to none, so the flash is
2826 widest at its head. The copies are gone when the animation finishes, and the mobject
2827 itself is left as it is. The animation options go to each flash.
2829 Args:
2830 vmobject: The mobject whose paths the flash travels along.
2831 n_segments: How many flashes make it up.
2832 time_width: The tail's length, as a fraction of the path's length.
2833 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions] for
2834 each flash.
2836 Examples:
2837 ```python
2838 import manimgx as m
2841 class ShowPassingFlashWithThinningStrokeWidthExample(m.Scene):
2842 def construct(self) -> None:
2843 circle = m.Circle(radius=2.5, color=m.YELLOW, stroke_width=16)
2844 self.add(circle.copy().set_stroke(m.GREY, width=4))
2845 self.play(
2846 m.ShowPassingFlashWithThinningStrokeWidth(
2847 circle, time_width=0.5, run_time=2
2848 )
2849 )
2850 ```
2851 """
2853 defaults: ClassVar[AnimationOptions] = {"remover": True}
2855 def __init__(
2856 self,
2857 vmobject: Mobject,
2858 n_segments: int = 10,
2859 time_width: float = 0.1,
2860 **kwargs: Unpack[AnimationOptions],
2861 ) -> None:
2862 self.n_segments, self.time_width = n_segments, time_width
2863 widths = np.linspace(0, vmobject.get_stroke_width(), n_segments)
2864 time_widths = np.linspace(time_width, 0, n_segments)
2865 super().__init__(
2866 *(
2867 ShowPassingFlash(
2868 vmobject.copy().set_stroke(width=w), time_width=tw, **kwargs
2869 )
2870 for w, tw in zip(widths, time_widths, strict=True)
2871 )
2872 )
2875class Circumscribe(Succession):
2876 """Draw attention to a mobject with a frame drawn around it.
2878 The frame, a rectangle or a circle `buff` away from the mobject, flashes around it
2879 ([`ShowPassingFlash`][manimgx.ShowPassingFlash]); with `fade_in` it fades in and is
2880 then undrawn, with `fade_out` it is drawn and then fades out, and with both it fades
2881 in and out. It is gone when the animation finishes. `run_time` times the frame (1
2882 second by default); the other options apply to the whole.
2884 Args:
2885 mobject: The mobject to frame.
2886 shape: The frame's kind: [`Rectangle`][manimgx.Rectangle] (None, the default) or
2887 [`Circle`][manimgx.Circle]; any other raises a ValueError.
2888 fade_in: Whether the frame fades in.
2889 fade_out: Whether the frame fades out.
2890 time_width: The flashing stretch's length, as a fraction of the frame's, when it
2891 neither fades in nor out.
2892 buff: The gap between the mobject and the frame, in scene units.
2893 color: The frame's color.
2894 stroke_width: The frame's width, in hundredths of a scene unit.
2895 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]:
2896 `run_time` for the frame, the others for the whole.
2898 Examples:
2899 ```python
2900 import manimgx as m
2903 class CircumscribeExample(m.Scene):
2904 def construct(self) -> None:
2905 text = m.Text("Circumscribe", font_size=96)
2906 self.add(text)
2907 self.play(m.Circumscribe(text))
2908 self.play(m.Circumscribe(text, m.Circle, fade_out=True))
2909 ```
2910 """
2912 def __init__(
2913 self,
2914 mobject: Mobject,
2915 shape: type[VMobject] | None = None,
2916 fade_in: bool = False,
2917 fade_out: bool = False,
2918 time_width: float = 0.3,
2919 buff: float = SMALL_BUFF,
2920 color: ParsableManimColor = PURE_YELLOW,
2921 stroke_width: float = DEFAULT_STROKE_WIDTH,
2922 **kwargs: Unpack[AnimationOptions],
2923 ) -> None:
2924 from manimgx.mobjects.annotations import SurroundingRectangle
2925 from manimgx.mobjects.shapes import Circle, Rectangle
2927 shape = shape or Rectangle
2928 if shape is Rectangle:
2929 frame = SurroundingRectangle(
2930 mobject, color=color, buff=buff, stroke_width=stroke_width
2931 )
2932 elif shape is Circle:
2933 frame = Circle(color=color, stroke_width=stroke_width).surround(
2934 mobject, buffer_factor=1
2935 )
2936 frame.scale((frame.width / 2 + buff) / (frame.width / 2))
2937 else:
2938 raise ValueError("shape should be either Rectangle or Circle.")
2939 run_time = kwargs.pop("run_time", 1.0)
2940 half = run_time / 2
2941 if fade_in and fade_out:
2942 anims = [FadeIn(frame, run_time=half), FadeOut(frame, run_time=half)]
2943 elif fade_in:
2944 frame.reverse_direction()
2945 anims = [FadeIn(frame, run_time=half), Uncreate(frame, run_time=half)]
2946 elif fade_out:
2947 anims = [Create(frame, run_time=half), FadeOut(frame, run_time=half)]
2948 else:
2949 anims = [ShowPassingFlash(frame, time_width, run_time=run_time)]
2950 super().__init__(*anims, **kwargs)
2953class Blink(Succession):
2954 """Blink a mobject: hide it and show it again, a number of times.
2956 It shows for `time_on` seconds and hides for `time_off`, `blinks` times, then shows
2957 again for `time_on` (or stays hidden, with `hide_at_end`). It is made fully opaque
2958 to show it, and fully transparent to hide it.
2960 Args:
2961 mobject: The mobject to blink.
2962 time_on: How long it shows each time, in seconds.
2963 time_off: How long it hides each time, in seconds.
2964 blinks: How many times it blinks.
2965 hide_at_end: Whether it stays hidden at the end.
2966 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions] for
2967 the whole.
2969 Examples:
2970 ```python
2971 import manimgx as m
2974 class BlinkExample(m.Scene):
2975 def construct(self) -> None:
2976 text = m.Text("Blinking", font_size=120)
2977 self.add(text)
2978 self.play(m.Blink(text, blinks=3))
2979 ```
2980 """
2982 def __init__(
2983 self,
2984 mobject: Mobject,
2985 time_on: float = 0.5,
2986 time_off: float = 0.5,
2987 blinks: int = 1,
2988 hide_at_end: bool = False,
2989 **kwargs: Unpack[AnimationOptions],
2990 ) -> None:
2991 def show(opacity: float, run_time: float) -> UpdateFromFunc:
2992 return UpdateFromFunc(
2993 mobject,
2994 update_function=lambda m: m.set_opacity(opacity),
2995 run_time=run_time,
2996 )
2998 anims = [show(1.0, time_on), show(0.0, time_off)] * blinks
2999 super().__init__(
3000 *anims, *([] if hide_at_end else [show(1.0, time_on)]), **kwargs
3001 )
3004class Broadcast(LaggedStart):
3005 """Send copies of a mobject spreading out from a point, one after another.
3007 Each of `n_mobs` copies starts at `focal_point`, `initial_width` wide and at
3008 `initial_opacity`, and grows like a ripple to the mobject's size, centered on
3009 `focal_point`, as its opacity goes to `final_opacity`. They begin one after another
3010 (`lag_ratio` 0.2, over 3 seconds), and leave the scene when the animation finishes,
3011 unless given `remover=False`. The copies of a filled mobject fade as a whole, those
3012 of an outline in their stroke. The mobject itself is not shown.
3014 Args:
3015 mobject: The ripples' shape, at its largest.
3016 focal_point: Where the ripples spread from.
3017 n_mobs: How many copies.
3018 initial_opacity: The copies' opacity at the start.
3019 final_opacity: The copies' opacity at the end.
3020 initial_width: The copies' width at the start, in scene units.
3021 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]:
3022 `remover` for each copy, the others for the whole.
3024 Examples:
3025 ```python
3026 import manimgx as m
3029 class BroadcastExample(m.Scene):
3030 def construct(self) -> None:
3031 self.add(m.Dot(radius=0.2, color=m.TEAL))
3032 self.play(m.Broadcast(m.Circle(radius=3.5, color=m.TEAL)))
3033 ```
3034 """
3036 defaults: ClassVar[AnimationOptions] = {"lag_ratio": 0.2, "run_time": 3.0}
3038 def __init__(
3039 self,
3040 mobject: Mobject,
3041 focal_point: Point3DLike = ORIGIN,
3042 n_mobs: int = 5,
3043 initial_opacity: float = 1,
3044 final_opacity: float = 0,
3045 initial_width: float = 0.0,
3046 **kwargs: Unpack[AnimationOptions],
3047 ) -> None:
3048 remover = kwargs.pop("remover", True)
3049 self.focal_point, self.n_mobs = focal_point, n_mobs
3050 filled = bool(mobject.fill_opacity)
3051 opacity = (
3052 (lambda m, o: m.set_opacity(o))
3053 if filled
3054 else (lambda m, o: m.set_stroke(opacity=o))
3055 )
3056 anims = []
3057 for _ in range(n_mobs):
3058 mob = mobject.copy()
3059 opacity(mob, final_opacity)
3060 mob.move_to(focal_point).save_state()
3061 mob.set(width=initial_width)
3062 opacity(mob, initial_opacity)
3063 anims.append(Restore(mob, remover=remover))
3064 super().__init__(*anims, **kwargs)