Coverage for src/manimgx/mobjects/shapes.py: 95%
1012 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"Geometric figures: cubic paths, planar region operations, arrow tips and sampled point disks."
8from __future__ import annotations
10import itertools
11import warnings
12from collections.abc import Iterator, Sequence
13from functools import reduce
14from math import ceil
15from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpack
16from warnings import deprecated
18import numpy as np
20from manimgx.constants import (
21 DEFAULT_ARROW_TIP_LENGTH,
22 DEFAULT_DASH_LENGTH,
23 DEFAULT_DOT_RADIUS,
24 DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
25 DEFAULT_POINT_DENSITY_1D,
26 DEGREES,
27 DL,
28 DOWN,
29 DR,
30 LARGE_BUFF,
31 LEFT,
32 MED_SMALL_BUFF,
33 ORIGIN,
34 OUT,
35 PI,
36 RIGHT,
37 TAU,
38 UL,
39 UP,
40 UR,
41)
42from manimgx.drawing.geometry import (
43 Blend,
44 QuickHull,
45 _pathops,
46 _to_path,
47 angle_between_vectors,
48 angle_of_vector,
49 cartesian_to_spherical,
50 defined,
51 line_intersection,
52 normalize,
53 perpendicular_bisector,
54 regular_vertices,
55 rotation_matrix,
56 segment,
57 turn_between,
58)
59from manimgx.drawing.paint import (
60 BLUE,
61 PURE_YELLOW,
62 RED,
63 WHITE,
64 Colors,
65 Style,
66 StyleBase,
67 _Style,
68 _StyleBase,
69)
70from manimgx.mobject import (
71 Mobject,
72 Mobject1D,
73 Pivot,
74 VGroup,
75 VMobject,
76 _append_path,
77 prototype,
78 style_defaults,
79)
80from manimgx.settings import config
81from manimgx.typing import Point3DLike
83__all__ = [
84 "Angle",
85 "AnnotationDot",
86 "AnnularSector",
87 "Annulus",
88 "Arc",
89 "ArcBetweenPoints",
90 "ArcPolygon",
91 "ArcPolygonFromArcs",
92 "Arrow",
93 "ArrowCircleFilledTip",
94 "ArrowCircleTip",
95 "ArrowSquareFilledTip",
96 "ArrowSquareTip",
97 "ArrowTip",
98 "ArrowTriangleFilledTip",
99 "ArrowTriangleTip",
100 "Circle",
101 "ConvexHull",
102 "CubicBezier",
103 "CurvedArrow",
104 "CurvedDoubleArrow",
105 "CurvesAsSubmobjects",
106 "Cutout",
107 "DashedLine",
108 "DashedVMobject",
109 "Difference",
110 "Dot",
111 "DoubleArrow",
112 "Elbow",
113 "Ellipse",
114 "Exclusion",
115 "FullScreenRectangle",
116 "Intersection",
117 "Line",
118 "PointCloudDot",
119 "Polygon",
120 "Polygram",
121 "Rectangle",
122 "RegularPolygon",
123 "RegularPolygram",
124 "RightAngle",
125 "RoundedRectangle",
126 "ScreenRectangle",
127 "Sector",
128 "Square",
129 "Star",
130 "StealthTip",
131 "TangentLine",
132 "TipableVMobject",
133 "Triangle",
134 "Union",
135 "Vector",
136 "adjacent_n_tuples",
137 "adjacent_pairs",
138]
140if TYPE_CHECKING:
141 from collections.abc import Iterable
142 from typing import Self
144 import numpy.typing as npt
146 from manimgx.drawing.paint import ParsableManimColor
147 from manimgx.mobject import Mobject
148 from manimgx.mobjects.grid import Matrix, MatrixOptions
149 from manimgx.typing import (
150 MatrixMN,
151 Point3D,
152 Point3D_Array,
153 Point3DLike,
154 Point3DLike_Array,
155 Vector2DLike,
156 Vector3D,
157 Vector3DLike,
158 )
160 type AngleQuadrant = tuple[Literal[-1, 1], Literal[-1, 1]]
161 "Which way along each of two crossing lines a side of an angle goes from the\n crossing: a sign for each line, the first line's first; 1 along the line's\n direction (from its start toward its end), -1 back toward its start."
164class _TippedBase(_StyleBase, total=False):
165 """TippedBase's keys, open, for the keywords that add to them."""
167 tip_length: float
168 """The length of the tips [add_tip][manimgx.TipableVMobject.add_tip] makes, in
169 scene units (default 0.35; an [Arrow][manimgx.Arrow]'s may be shorter)."""
170 normal_vector: Vector3DLike
171 """The normal of the plane the path lies in (default OUT). Accepted for Manim
172 compatibility; ignored and not retained."""
173 tip_style: Style | None
174 """Style keywords for the tips the path makes (default None: none). A tip's
175 `fill_color` and `stroke_color` are the path's color unless given here."""
178class TippedBase(_TippedBase, total=False, closed=True):
179 """Every style keyword but `color`, and those of a path that can end in arrow tips
180 (see [TipableVMobject][manimgx.TipableVMobject]).
182 A class that takes `color` by position declares it itself, and the rest with this.
183 """
186class _Tipped(_TippedBase, total=False):
187 """Tipped's keys, open, for the keywords that add to them."""
189 color: Colors | None
190 """The color of both fill and stroke (default white; a [Circle][manimgx.Circle]'s is
191 red); None for the class's default."""
194class Tipped(_Tipped, total=False, closed=True):
195 """The style keywords, and those of a path that can end in arrow tips (see
196 [TipableVMobject][manimgx.TipableVMobject])."""
199class _ArcOptions(_Tipped, total=False):
200 """ArcOptions's keys, open, for the keywords that add to them."""
202 num_components: int
203 """How many anchor points the arc is drawn through: it is one fewer cubic Bézier
204 curves (default 9)."""
205 arc_center: Point3DLike
206 """Where the center of the arc's circle goes, in scene coordinates (default
207 ORIGIN)."""
210class ArcOptions(_ArcOptions, total=False, closed=True):
211 """An arc's keywords, for the classes that build one and pass them on: how finely
212 and where it is built, with the style and tip keywords."""
215class SectorOptions(_ArcOptions, total=False, closed=True):
216 """A [Sector][manimgx.Sector]'s keywords but its radius: its angles, with the arc
217 keywords."""
219 angle: float
220 """The angle the sector spans, in radians: counterclockwise from `start_angle`, or
221 clockwise if negative (default TAU / 4: a quarter turn)."""
222 start_angle: float
223 """The angle of its first edge, in radians, counterclockwise from the positive
224 x-axis (default 0)."""
227class ArcBetweenOptions(_Tipped, total=False, closed=True):
228 """An [ArcBetweenPoints][manimgx.ArcBetweenPoints]'s keywords but its ends: its
229 angle or its radius, with the style and tip keywords (for the classes that pass
230 them on)."""
232 angle: float
233 """The angle the arc turns through on its way, in radians: counterclockwise if
234 positive, bending it to the right of the straight way; clockwise if negative; a
235 straight segment if 0 (default TAU / 4)."""
236 radius: float | None
237 """The radius of the arc's circle, in scene units, in place of `angle`: the shorter
238 arc of that radius, bending right, or left if negative; at least half the distance
239 between the ends (default None: set by `angle`)."""
242def _similarity(
243 a: Point3D, b: Point3D, c: Point3D, d: Point3D
244) -> tuple[MatrixMN, MatrixMN]:
245 """(the 3×4 map, its rotation) taking segment a→b onto c→d, as CE's `put_start_and_end_on`:
246 scale and turn about a, then move."""
247 ab, cd = b - a, d - c
248 turn = rotation_matrix(*turn_between(ab, cd))
249 linear = turn * (np.linalg.norm(cd) / np.linalg.norm(ab))
250 return np.hstack([linear, (c - linear @ a)[:, None]]), turn
253class TipableVMobject(VMobject):
254 """A path that can end in arrow tips: what lines, arcs and arrows have in common.
256 A tip is a small shape (an [ArrowTip][manimgx.ArrowTip]) added to the path as a
257 submobject, at its end or its start, pointing along it. The tip's point goes where
258 the path ended, and the path is fitted to stop at the tip's base. With tips, the
259 path's [start][manimgx.TipableVMobject.get_start] and
260 [end][manimgx.TipableVMobject.get_end] are the tips' points.
262 Args:
263 tip_length: The length of the tips [add_tip][manimgx.TipableVMobject.add_tip]
264 makes, in scene units (default 0.35).
265 normal_vector: The normal of the plane the path lies in. Accepted for Manim
266 compatibility; ignored.
267 tip_style: Style keywords for the tips the path makes; a tip's `fill_color` and
268 `stroke_color` are the path's color unless given here.
269 """
271 _tip_positioned = False
273 tip: ArrowTip
274 """The tip at the path's end, once [add_tip][manimgx.TipableVMobject.add_tip] has
275 made one."""
276 start_tip: ArrowTip
277 """The tip at the path's start, once `add_tip(at_start=True)` has made one."""
279 def __init__(
280 self,
281 tip_length: float = DEFAULT_ARROW_TIP_LENGTH,
282 normal_vector: Vector3DLike = OUT,
283 tip_style: Style | None = None,
284 **kwargs: Unpack[Style],
285 ) -> None:
286 self.tip_length: float = tip_length
287 self.tip_style: Style = tip_style if tip_style is not None else {}
288 super().__init__(**kwargs)
290 def add_tip(
291 self,
292 tip: ArrowTip | None = None,
293 tip_shape: type[ArrowTip] | None = None,
294 tip_length: float | None = None,
295 tip_width: float | None = None,
296 at_start: bool = False,
297 ) -> Self:
298 """Add an arrow tip at the path's end, or its start, pointing along the path
299 there.
301 The tip's point goes where the path ended, and the path is scaled and turned
302 about its other end to stop at the tip's base. The tip is a submobject, named
303 [tip][manimgx.TipableVMobject.tip] (or `start_tip`), in the path's color unless
304 `tip_style` gives it another.
306 Args:
307 tip: A tip made beforehand, to turn and move into place; None to make one.
308 tip_shape: The class of the tip to make, an [ArrowTip][manimgx.ArrowTip]
309 subclass; None for
310 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
311 tip_length: The length of the tip to make, in scene units; None for the
312 path's `tip_length`.
313 tip_width: The width of the tip to make, if it is the default filled
314 triangle, in scene units; None for the default length. Other shapes take
315 no width: they are made at `tip_length` alone.
316 at_start: Whether the tip goes at the path's start, pointing back along it.
318 Examples:
319 ```python
320 import manimgx as m
323 class TipableVMobjectAddTipExample(m.Scene):
324 def construct(self) -> None:
325 line = m.Line(3 * m.LEFT, 3 * m.RIGHT, color=m.BLUE).add_tip()
326 both = m.Line(3 * m.LEFT, 3 * m.RIGHT, color=m.GREEN)
327 both.add_tip(tip_shape=m.StealthTip)
328 both.add_tip(tip_shape=m.ArrowCircleFilledTip, at_start=True)
329 arc = m.Arc(radius=2, angle=m.PI, color=m.YELLOW)
330 arc.add_tip(tip_length=0.5, tip_width=0.5)
331 self.add(m.VGroup(line, both, arc).arrange(m.DOWN, buff=1))
332 ```
333 """
334 if tip is None:
335 tip = self.create_tip(tip_shape, tip_length, tip_width, at_start)
336 else:
337 self.position_tip(tip, at_start)
338 self.reset_endpoints_based_on_tip(tip, at_start)
339 self.assign_tip_attr(tip, at_start)
340 self.add(tip)
341 return self
343 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
344 def create_tip(
345 self,
346 tip_shape: type[ArrowTip] | None = None,
347 tip_length: float | None = None,
348 tip_width: float | None = None,
349 at_start: bool = False,
350 ) -> ArrowTip:
351 """Make a tip for the path's end, or its start, pointing along the path there;
352 the tip is not added (see [add_tip][manimgx.TipableVMobject.add_tip]).
354 Args:
355 tip_shape: The class of the tip, an [ArrowTip][manimgx.ArrowTip] subclass;
356 None for [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
357 tip_length: Its length, in scene units; None for the path's
358 [default][manimgx.TipableVMobject.get_default_tip_length].
359 tip_width: Its width, if it is the default filled triangle, in scene units;
360 None for the default length.
361 at_start: Whether it is for the path's start, pointing back along it.
363 Returns:
364 A new tip, in place.
365 """
366 tip = self.get_unpositioned_tip(tip_shape, tip_length, tip_width)
367 self.position_tip(tip, at_start)
368 return tip
370 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
371 def get_unpositioned_tip(
372 self,
373 tip_shape: type[ArrowTip] | None = None,
374 tip_length: float | None = None,
375 tip_width: float | None = None,
376 ) -> ArrowTip:
377 """Make a tip in the path's style, not yet in place: what
378 [add_tip][manimgx.TipableVMobject.add_tip] makes before it turns and moves it to
379 an end.
381 The tip's `fill_color` and `stroke_color` are the path's color, with the path's
382 `tip_style` over them. The default filled triangle is made `tip_length` long and
383 `tip_width` wide; another shape is made at `tip_length`, as its class makes it.
385 Args:
386 tip_shape: The class of the tip; None for
387 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
388 tip_length: Its length, in scene units; None for the path's
389 [default][manimgx.TipableVMobject.get_default_tip_length].
390 tip_width: The width of the default filled triangle, in scene units; None
391 for the default length.
393 Returns:
394 A new tip.
395 """
396 # The default tip is given its width too (the default length unless given, as
397 # in CE), and a triangle scales with its two sides: it is the unit triangle of
398 # their ratio, scaled, one prototype per ratio whatever the size. Another
399 # class's shape need not scale with its length (ArrowTriangleTip's width does
400 # not), so its tip is made at its size.
402 default = self.get_default_tip_length()
403 length = default if tip_length is None else tip_length
404 color = self.get_color()
405 style: Style = {"fill_color": color, "stroke_color": color}
406 style.update(self.tip_style)
407 if tip_shape is not None and tip_shape is not ArrowTriangleFilledTip:
408 return tip_shape(length=length, **style)
409 width = default if tip_width is None else tip_width
410 if length <= 0:
411 return ArrowTriangleFilledTip(length=length, width=width, **style)
412 unit = ArrowTriangleFilledTip(length=1.0, width=width / length, **style)
413 return unit.scale(length)
415 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
416 def position_tip(self, tip: ArrowTip, at_start: bool = False) -> ArrowTip:
417 """Turn and move a tip onto the path's end, or its start: pointing along the
418 path there, its point on the end.
420 [add_tip][manimgx.TipableVMobject.add_tip] and
421 [create_tip][manimgx.TipableVMobject.create_tip] call it; the path does not
422 change.
424 Args:
425 tip: The tip to place.
426 at_start: Whether to place it at the path's start, pointing back along it.
428 Returns:
429 The tip, in place.
430 """
431 anchor = self.get_start() if at_start else self.get_end()
432 angles = cartesian_to_spherical(self._toward(at_start) - anchor)
433 turn = rotation_matrix(angles[1] - PI - tip.tip_angle, OUT)
434 if not self._tip_positioned:
435 axis = np.array([np.sin(angles[1]), -np.cos(angles[1]), 0])
436 turn = rotation_matrix(-angles[2] + PI / 2, axis) @ turn
437 self._tip_positioned = True
438 # one rigid map, x ↦ R(x − tip point) + anchor: the tip turns to point along the curve,
439 # and its tip point, a point of its own, lands on the curve's end (CE's turns about the
440 # center and its move are this map)
441 point = tip.tip_point
442 tip._geometry = tip._geometry.transformed(
443 np.hstack([turn, (anchor - turn @ point)[:, None]])
444 )
445 tip._rotate_direction_state(turn)
446 return tip
448 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
449 def reset_endpoints_based_on_tip(self, tip: ArrowTip, at_start: bool) -> Self:
450 """Fit the path to stop at a tip's base: scale and turn it about its other end,
451 which stays.
453 [add_tip][manimgx.TipableVMobject.add_tip] calls it once the tip is in place. A
454 path of no length stays as it is.
456 Args:
457 tip: The tip, in place at the path's end (or its start).
458 at_start: Whether the tip is at the path's start.
459 """
460 # `put_start_and_end_on`, one map — on the curve alone while no tip is on it yet
461 # (a class's own `scale` is not called: it is the curve that is fitted, not the
462 # object resized)
463 if self.get_length() == 0:
464 return self
465 start, end = (
466 (tip.base, self.get_end()) if at_start else (self.get_start(), tip.base)
467 )
468 if self.submobjects: # tips already on it move with it, as CE moves them
469 return self.put_start_and_end_on(start, end)
470 m, turn = _similarity(*self.get_start_and_end(), start, end)
471 self._geometry = self._geometry.transformed(m)
472 self._rotate_direction_state(turn)
473 return self
475 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
476 def assign_tip_attr(self, tip: ArrowTip, at_start: bool) -> Self:
477 """Name a tip as the path's [tip][manimgx.TipableVMobject.tip], or its
478 [start_tip][manimgx.TipableVMobject.start_tip]; the tip is not added.
480 [add_tip][manimgx.TipableVMobject.add_tip] calls it.
482 Args:
483 at_start: Whether it is the tip at the path's start.
484 """
485 if at_start:
486 self.start_tip = tip
487 else:
488 self.tip = tip
489 return self
491 def has_tip(self) -> bool:
492 """Whether the path has a tip at its end: its
493 [tip][manimgx.TipableVMobject.tip], among its submobjects.
494 """
495 tip = self.__dict__.get("tip")
496 return tip is not None and any(m is tip for m in self.submobjects)
498 def has_start_tip(self) -> bool:
499 """Whether the path has a tip at its start: its
500 [start_tip][manimgx.TipableVMobject.start_tip], among its submobjects.
501 """
502 tip = self.__dict__.get("start_tip")
503 return tip is not None and any(m is tip for m in self.submobjects)
505 def pop_tips(self) -> VGroup[ArrowTip]:
506 """Remove the path's tips, and fit the path back between its start and its end
507 as they were: the tips' points.
509 Returns:
510 The tips removed, the end tip first, in a new group (empty if there were
511 none).
512 """
514 start, end = self.get_start_and_end()
515 result = VGroup[ArrowTip]()
516 if self.has_tip():
517 result.add(self.tip)
518 self.remove(self.tip)
519 if self.has_start_tip():
520 result.add(self.start_tip)
521 self.remove(self.start_tip)
522 if result.submobjects:
523 self.put_start_and_end_on(start, end)
524 return result
526 def get_tips(self) -> VGroup[ArrowTip]:
527 """The tips the path has been given: its [tip][manimgx.TipableVMobject.tip] and
528 its [start_tip][manimgx.TipableVMobject.start_tip], those it has had.
530 A tip [pop_tips][manimgx.TipableVMobject.pop_tips] removed is still named, and
531 listed here; [has_tip][manimgx.TipableVMobject.has_tip] tells whether it is on
532 the path.
534 Returns:
535 The tips, the end tip first, in a new group.
536 """
538 result = VGroup[ArrowTip]()
539 if hasattr(self, "tip"):
540 result.add(self.tip)
541 if hasattr(self, "start_tip"):
542 result.add(self.start_tip)
543 return result
545 def get_tip(self) -> ArrowTip:
546 """The path's tip: the one at its end, or the one at its start if it has none
547 there.
549 It is the first of [get_tips][manimgx.TipableVMobject.get_tips]; a path never
550 given a tip raises an exception.
551 """
552 tips = self.get_tips()
553 if not tips.submobjects:
554 raise Exception("tip not found")
555 return tips[0]
557 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
558 def get_default_tip_length(self) -> float:
559 """The length of the tips the path makes unless given one: its `tip_length`.
561 Returns:
562 The length, in scene units.
563 """
564 return self.tip_length
566 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
567 def get_first_handle(self) -> Point3D:
568 """The path's first handle: the control point after its first point, toward
569 which it leaves its start.
571 Returns:
572 The point, in scene coordinates.
573 """
574 first_handle: Point3D = self.points[1]
575 return first_handle
577 def _toward(self, at_start: bool) -> Point3D:
578 """The point the path leaves its start toward, or comes into its end from: the
579 nearest of the end curve's control points apart from its end, so a tip points
580 along the path where a handle has no length (a curve arrives along P3 − P1 when
581 P2 = P3)."""
582 curve = self.points[:4] if at_start else self.points[-4:][::-1]
583 end = curve[0]
584 for point in curve[1:]:
585 if np.linalg.norm(point - end) > 1e-9 * (1 + np.abs(end).max()):
586 return point
587 return curve[1]
589 @deprecated("Manim CE's machinery: add_tip calls it", category=None)
590 def get_last_handle(self) -> Point3D:
591 """The path's last handle: the control point before its last point, from which
592 it comes into its end.
594 Returns:
595 The point, in scene coordinates.
596 """
597 last_handle: Point3D = self.points[-2]
598 return last_handle
600 def get_end(self) -> Point3D:
601 """Where the path ends: its end tip's point, if it has an end tip, and otherwise
602 its last point.
604 Returns:
605 The point, in scene coordinates.
606 """
607 if self.has_tip():
608 return np.array(self.tip.tip_point)
609 else:
610 return super().get_end()
612 def get_start(self) -> Point3D:
613 """Where the path starts: its start tip's point, if it has a start tip, and
614 otherwise its first point.
616 Returns:
617 The point, in scene coordinates.
618 """
619 if self.has_start_tip():
620 return np.array(self.start_tip.tip_point)
621 else:
622 return super().get_start()
624 def get_length(self) -> float:
625 """The distance from the path's start to its end, tips included: straight
626 across, so an arc's chord, not the length along it.
628 Returns:
629 The distance, in scene units.
630 """
631 start, end = self.get_start_and_end()
632 return float(np.linalg.norm(start - end))
635def _unit_arc(start: float, angle: float, n: int) -> np.ndarray:
636 """CE's arc on the unit circle: n anchors, handles along the tangents."""
637 a = np.linspace(start, start + angle, n)
638 anchors = np.stack([np.cos(a), np.sin(a), np.zeros(n)], axis=1)
639 tangents = np.stack([-anchors[:, 1], anchors[:, 0], np.zeros(n)], axis=1)
640 factor = 4 / 3 * np.tan(angle / (n - 1.0) / 4)
641 curves = np.empty((n - 1, 4, 3))
642 curves[:, 0], curves[:, 3] = anchors[:-1], anchors[1:]
643 curves[:, 1] = anchors[:-1] + factor * tangents[:-1]
644 curves[:, 2] = anchors[1:] - factor * tangents[1:]
645 return curves.reshape(-1, 3)
648class Arc(TipableVMobject):
649 r"""An arc of a circle: from the angle `start_angle` through `angle`,
650 counterclockwise if `angle` is positive; white unless styled.
652 Angles are in radians, about the arc's center, counterclockwise from the positive
653 x-axis. The arc is drawn through `num_components` points spaced evenly along it,
654 joined by cubic Bézier curves.
656 Args:
657 radius: The radius, in scene units; None for 1.
658 start_angle: The angle of the arc's first point.
659 angle: How far the arc goes: counterclockwise if positive, clockwise if
660 negative; TAU for a whole circle.
661 num_components: How many anchor points it is drawn through: the arc is one
662 fewer cubic Bézier curves.
663 arc_center: Where the center of its circle goes.
665 Examples:
666 ```python
667 import manimgx as m
670 class ArcExample(m.Scene):
671 def construct(self) -> None:
672 arcs = m.VGroup(
673 m.Arc(radius=1.5, angle=m.PI, color=m.BLUE),
674 m.Arc(radius=1.5, start_angle=m.PI / 2, angle=3 * m.PI / 2),
675 m.Arc(radius=1.5, angle=-m.PI / 2, color=m.YELLOW),
676 ).arrange(buff=1.5)
677 labels = ("angle=PI", "start_angle=PI/2\nangle=3*PI/2", "angle=-PI/2")
678 for arc, label in zip(arcs, labels):
679 self.add(m.Text(label, font_size=28).next_to(arc, m.DOWN))
680 self.play(m.Create(arcs, run_time=3))
681 ```
682 """
684 def __init__(
685 self,
686 radius: float | None = 1.0,
687 start_angle: float = 0,
688 angle: float = TAU / 4,
689 num_components: int = 9,
690 arc_center: Point3DLike = ORIGIN,
691 **kwargs: Unpack[Tipped],
692 ):
693 if radius is None:
694 radius = 1.0
695 self.radius = radius
696 self.num_components = num_components
697 self.arc_center: Point3D = np.asarray(arc_center)
698 self.start_angle = start_angle
699 self.angle = angle
700 self._failed_to_get_center: bool = False
701 super().__init__(**kwargs)
703 def generate_points(self) -> Self:
704 # the unit arc of this start, angle and number of pieces (a defined shape),
705 # placed by radius and center
706 start, angle, n = self.start_angle, self.angle, self.num_components
707 shape = defined(("arc", start, angle, n), lambda: _unit_arc(start, angle, n))
708 m = np.zeros((3, 4))
709 m[0, 0] = m[1, 1] = m[2, 2] = self.radius
710 m[:, 3] = self.arc_center
711 self._geometry = Blend(((m, shape),), len(shape.array))
712 return self
714 def get_arc_center(self, warning: bool = True) -> Point3D:
715 """The center of the arc's circle, where it is now, in whatever plane it lies:
716 the center of the circle through its first curve's ends and middle.
718 If there is none (a straight path), it is the origin, with a warning.
720 Args:
721 warning: Whether to warn when the center cannot be found.
723 Returns:
724 The point, in scene coordinates.
725 """
726 a1, h1, h2, a2 = self.points[:4]
727 if np.all(a1 == a2):
728 return np.copy(a1)
729 middle = (a1 + 3 * (h1 + h2) + a2) / 8 # on the circle, as an arc's curve is
730 u, v = a1 - middle, a2 - middle
731 normal = np.cross(u, v)
732 if np.linalg.norm(normal) <= 1e-12 * max(u @ u, v @ v):
733 if warning:
734 warnings.warn(
735 "Can't find Arc center, using ORIGIN instead", stacklevel=1
736 )
737 self._failed_to_get_center = True
738 return np.array(ORIGIN)
739 return middle + np.cross((u @ u) * v - (v @ v) * u, normal) / (
740 2 * normal @ normal
741 )
743 def move_arc_center_to(self, point: Point3DLike) -> Self:
744 """Move the arc so the center of its circle is at a point.
746 Args:
747 point: Where the center goes, in scene coordinates.
748 """
749 self.shift(point - self.get_arc_center())
750 return self
752 def stop_angle(self) -> float:
753 """The angle at which the arc ends: the angle of its last point about its
754 [center][manimgx.Arc.get_arc_center].
756 Returns:
757 The angle, in radians, counterclockwise from the positive x-axis, from 0 up
758 to TAU.
759 """
760 return angle_of_vector(self.points[-1] - self.get_arc_center()) % TAU
763class ArcBetweenPoints(Arc):
764 """An arc from one point to another, through an angle or of a radius; white unless
765 styled.
767 Going from `start` to `end`, a positive angle turns counterclockwise, bending the
768 arc to the right of the straight way; a negative angle bends it to the left, and 0
769 makes it a straight segment.
771 Args:
772 start: Where the arc starts.
773 end: Where it ends.
774 angle: The angle it turns through on its way, in radians.
775 radius: The radius of its circle, in scene units, in place of `angle`: the
776 shorter arc of that radius, bending right, or left if negative. It must be
777 at least half the distance between the ends. None to use `angle`.
778 **kwargs: [Arc keywords][manimgx.mobjects.shapes.ArcOptions]; `arc_center`
779 has no effect, as the ends place the arc.
781 Examples:
782 ```python
783 import manimgx as m
786 class ArcBetweenPointsExample(m.Scene):
787 def construct(self) -> None:
788 start, end = 3 * m.LEFT + m.DOWN, 3 * m.RIGHT + m.DOWN
789 arcs = m.VGroup(
790 m.ArcBetweenPoints(start, end, color=m.BLUE),
791 m.ArcBetweenPoints(start, end, radius=-4, color=m.GREEN),
792 m.ArcBetweenPoints(start, end, angle=-m.PI, color=m.YELLOW),
793 )
794 self.add(m.Dot(start, radius=0.12), m.Dot(end, radius=0.12))
795 self.play(m.Create(arcs, run_time=3))
796 ```
797 """
799 def __init__(
800 self,
801 start: Point3DLike,
802 end: Point3DLike,
803 angle: float = TAU / 4,
804 radius: float | None = None,
805 **kwargs: Unpack[ArcOptions],
806 ) -> None:
807 if radius is not None:
808 self.radius = radius
809 if radius < 0:
810 sign = -2
811 radius *= -1
812 else:
813 sign = 2
814 halfdist = np.linalg.norm(np.array(start) - np.array(end)) / 2
815 if radius < halfdist:
816 raise ValueError(
817 "ArcBetweenPoints called with a radius that is\n "
818 " smaller than half the distance between the points."
819 )
820 arc_height = radius - np.sqrt(radius**2 - halfdist**2)
821 angle = np.arccos((radius - arc_height) / radius) * sign
822 super().__init__(radius=radius, angle=angle, **kwargs)
823 if angle == 0:
824 self.set_points_as_corners(np.array([LEFT, RIGHT]))
825 self.put_start_and_end_on(start, end)
826 if radius is None:
827 center = self.get_arc_center(warning=False)
828 if not self._failed_to_get_center:
829 self.radius = float(np.linalg.norm(np.array(start) - np.array(center)))
830 else:
831 self.radius = np.inf
834class CurvedArrow(ArcBetweenPoints):
835 """An arrow along an arc: an [ArcBetweenPoints][manimgx.ArcBetweenPoints] with a tip
836 at its end, bending right on its way by default; white unless styled.
838 Args:
839 start_point: Where the arrow starts.
840 end_point: Where it points to: its tip's point.
841 tip_shape: The class of its tip; None for
842 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
843 **kwargs:
844 [ArcBetweenPoints keywords][manimgx.ArcBetweenPoints]:
845 its angle (a quarter turn unless given) or its radius, style and tips.
847 Examples:
848 ```python
849 import manimgx as m
852 class CurvedArrowExample(m.Scene):
853 def construct(self) -> None:
854 start, end = 3 * m.LEFT + 0.5 * m.UP, 3 * m.RIGHT + 0.5 * m.UP
855 arrows = m.VGroup(
856 m.CurvedArrow(start, end, color=m.BLUE),
857 m.CurvedArrow(start, end, angle=m.PI, color=m.YELLOW),
858 m.CurvedArrow(end, start, color=m.GREEN),
859 m.CurvedArrow(end, start, radius=3.2, tip_shape=m.StealthTip),
860 )
861 self.add(m.Dot(start, radius=0.12), m.Dot(end, radius=0.12))
862 self.play(m.Create(arrows, run_time=4))
863 ```
864 """
866 def __init__(
867 self,
868 start_point: Point3DLike,
869 end_point: Point3DLike,
870 *,
871 tip_shape: type[ArrowTip] | None = None,
872 **kwargs: Unpack[ArcBetweenOptions],
873 ) -> None:
875 super().__init__(start_point, end_point, **kwargs)
876 self.add_tip(tip_shape=tip_shape or ArrowTriangleFilledTip)
879class CurvedDoubleArrow(CurvedArrow):
880 """An arrow along an arc with a tip at each end: an
881 [ArcBetweenPoints][manimgx.ArcBetweenPoints] with two tips, bending right on its way
882 by default; white unless styled.
884 Args:
885 start_point: Where the arrow starts: its start tip's point.
886 end_point: Where it ends: its end tip's point.
887 tip_shape_start: The class of the tip at its start; None for
888 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
889 tip_shape_end: The class of the tip at its end; None for
890 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
891 **kwargs:
892 [ArcBetweenPoints keywords][manimgx.ArcBetweenPoints]:
893 its angle (a quarter turn unless given) or its radius, style and tips.
895 Examples:
896 ```python
897 import manimgx as m
900 class CurvedDoubleArrowExample(m.Scene):
901 def construct(self) -> None:
902 left = m.Circle(radius=1, color=m.BLUE).shift(4 * m.LEFT)
903 right = m.Square(side_length=2, color=m.GREEN).shift(4 * m.RIGHT)
904 top = left.get_top(), right.get_top()
905 arrows = m.VGroup(
906 m.CurvedDoubleArrow(*top, angle=-m.PI / 3),
907 m.CurvedDoubleArrow(
908 left.get_bottom(),
909 right.get_bottom(),
910 tip_shape_start=m.ArrowCircleFilledTip,
911 tip_shape_end=m.StealthTip,
912 color=m.YELLOW,
913 ),
914 )
915 self.add(left, right)
916 self.play(m.Create(arrows, run_time=2))
917 ```
918 """
920 def __init__(
921 self,
922 start_point: Point3DLike,
923 end_point: Point3DLike,
924 *,
925 tip_shape_start: type[ArrowTip] | None = None,
926 tip_shape_end: type[ArrowTip] | None = None,
927 **kwargs: Unpack[ArcBetweenOptions],
928 ) -> None:
930 super().__init__(start_point, end_point, tip_shape=tip_shape_end, **kwargs)
931 self.add_tip(at_start=True, tip_shape=tip_shape_start or ArrowTriangleFilledTip)
934class Circle(Arc):
935 """A circle: drawn counterclockwise from its rightmost point, red unless styled.
937 Args:
938 radius: The radius, in scene units; None for 1.
939 color: The color, which may be given by position (`Circle(1, BLUE)`); None for
940 red.
941 num_components: How many anchor points it is drawn through: the circle is one
942 fewer cubic Bézier arcs.
943 arc_center: Where its center goes.
944 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
946 Examples:
947 ```python
948 import manimgx as m
951 class CircleExample(m.Scene):
952 def construct(self) -> None:
953 circles = m.VGroup(
954 m.Circle(color=m.BLUE),
955 m.Circle(radius=1.5, color=m.GREEN, fill_opacity=0.5),
956 m.Circle(radius=2, color=m.YELLOW, stroke_width=12),
957 ).arrange(buff=1)
958 self.play(m.Create(circles))
959 ```
960 """
962 defaults: ClassVar[Style] = {"color": RED}
964 def __init__(
965 self,
966 radius: float | None = None,
967 color: Colors | None = None,
968 *,
969 num_components: int = 9,
970 arc_center: Point3DLike = ORIGIN,
971 **kwargs: Unpack[TippedBase],
972 ) -> None:
973 style = Tipped(**kwargs) if color is None else Tipped(**kwargs, color=color)
974 super().__init__(
975 radius=radius,
976 start_angle=0,
977 angle=TAU,
978 num_components=num_components,
979 arc_center=arc_center,
980 **style,
981 )
983 def surround(
984 self,
985 mobject: Mobject,
986 dim_to_match: int = 0,
987 stretch: bool = False,
988 buff: float = 0,
989 *,
990 buffer_factor: float = 1.2,
991 ) -> Self:
992 """Fit the circle around a mobject: through the corners of its bounding box, enlarged
993 by `buffer_factor`, then `buff` farther out.
995 Args:
996 mobject: The mobject to surround.
997 dim_to_match: The dimension (0, 1 or 2) of `mobject` the circle is first fitted
998 to, before it grows to the corners.
999 stretch: Whether that first fit stretches the circle into an ellipse matching the
1000 bounding box.
1001 buff: How much farther out the circle goes, in scene units.
1002 buffer_factor: How much larger than through the corners the circle is.
1004 Examples:
1005 ```python
1006 import manimgx as m
1009 class CircleSurroundExample(m.Scene):
1010 def construct(self) -> None:
1011 word = m.Text("manimgx", font_size=120)
1012 ring = m.Circle(color=m.YELLOW).surround(word)
1013 self.add(word)
1014 self.play(m.Create(ring))
1015 ```
1016 """
1017 self.replace(mobject, dim_to_match, stretch)
1018 self.width = np.sqrt(mobject.width**2 + mobject.height**2)
1019 self.scale(buffer_factor)
1020 return self.scale((self.width / 2 + buff) / (self.width / 2)) if buff else self
1022 def point_at_angle(self, angle: float) -> Point3D:
1023 """The point of the circle at an angle from its start, its rightmost point.
1025 Args:
1026 angle: The angle, in radians, counterclockwise; any angle wraps around.
1028 Returns:
1029 The point, in scene coordinates.
1030 """
1031 proportion = angle / TAU
1032 proportion -= np.floor(proportion)
1033 return self.point_from_proportion(proportion)
1035 @staticmethod
1036 def from_three_points(
1037 p1: Point3DLike, p2: Point3DLike, p3: Point3DLike, **kwargs: Unpack[Tipped]
1038 ) -> Circle:
1039 """The circle through three points.
1041 Args:
1042 p1: A point on the circle.
1043 p2: A second point on it.
1044 p3: A third point on it, not on the line through the other two.
1045 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
1047 Returns:
1048 A new circle.
1049 """
1050 center = line_intersection(
1051 perpendicular_bisector([np.asarray(p1), np.asarray(p2)]),
1052 perpendicular_bisector([np.asarray(p2), np.asarray(p3)]),
1053 )
1054 radius = float(np.linalg.norm(np.asarray(p1, dtype=float) - center))
1055 return Circle(radius=radius, **kwargs).shift(center)
1058class Dot(Circle):
1059 """A dot: a small filled disc, white and without an outline unless styled.
1061 Args:
1062 point: Where its center goes.
1063 radius: Its radius, in scene units (default 0.08).
1065 Examples:
1066 ```python
1067 import manimgx as m
1070 class DotExample(m.Scene):
1071 def construct(self) -> None:
1072 self.add(
1073 m.Dot([-5, 0, 0]),
1074 m.Dot([-3.5, 0, 0], radius=0.2, color=m.BLUE),
1075 m.Dot([-1, 0, 0], radius=0.6, color=m.YELLOW),
1076 m.Dot([3, 0, 0], radius=1.5, color=m.GREEN, fill_opacity=0.5),
1077 )
1078 ```
1079 """
1081 defaults: ClassVar[Style] = {"stroke_width": 0, "fill_opacity": 1.0, "color": WHITE}
1083 def __init__(
1084 self,
1085 point: Point3DLike = ORIGIN,
1086 radius: float = DEFAULT_DOT_RADIUS,
1087 **kwargs: Unpack[Tipped],
1088 ) -> None:
1089 super().__init__(radius=radius, arc_center=point, **kwargs)
1092class AnnotationDot(Dot):
1093 """A dot to mark a point with: a little larger than a [Dot][manimgx.Dot], blue with
1094 a thick white outline unless styled.
1096 Its colors are its `fill_color` and its `stroke_color`, which `color` does not
1097 change.
1099 Args:
1100 radius: Its radius, in scene units (default 0.104, 1.3 times a dot's).
1101 point: Where its center goes.
1103 Examples:
1104 ```python
1105 import manimgx as m
1108 class AnnotationDotExample(m.Scene):
1109 def construct(self) -> None:
1110 arc = m.Arc(radius=3, angle=m.PI, color=m.GREY).shift(1.5 * m.DOWN)
1111 start = m.AnnotationDot(point=arc.get_start())
1112 end = m.AnnotationDot(point=arc.get_end())
1113 top = m.AnnotationDot(
1114 0.25, point=arc.get_top(), fill_color=m.YELLOW, stroke_color=m.RED
1115 )
1116 self.add(arc, start, end, top)
1117 ```
1118 """
1120 defaults: ClassVar[Style] = {
1121 "stroke_width": 5,
1122 "stroke_color": WHITE,
1123 "fill_color": BLUE,
1124 }
1126 def __init__(
1127 self,
1128 radius: float = DEFAULT_DOT_RADIUS * 1.3,
1129 *,
1130 point: Point3DLike = ORIGIN,
1131 **kwargs: Unpack[Tipped],
1132 ) -> None:
1133 super().__init__(point=point, radius=radius, **kwargs)
1136class Ellipse(Circle):
1137 """An ellipse: a circle stretched to a width and a height, red unless styled.
1139 Like a circle, it is drawn counterclockwise from its rightmost point.
1141 Args:
1142 width: Its width, in scene units: its extent along x.
1143 height: Its height, in scene units: its extent along y.
1145 Examples:
1146 ```python
1147 import manimgx as m
1150 class EllipseExample(m.Scene):
1151 def construct(self) -> None:
1152 ellipses = m.VGroup(
1153 m.Ellipse(),
1154 m.Ellipse(width=2, height=4, color=m.BLUE),
1155 m.Ellipse(width=5, height=2, color=m.YELLOW, fill_opacity=0.5),
1156 ).arrange(buff=1)
1157 self.add(ellipses)
1158 ```
1159 """
1161 def __init__(
1162 self, width: float = 2, height: float = 1, **kwargs: Unpack[ArcOptions]
1163 ) -> None:
1164 super().__init__(**kwargs)
1165 self.stretch_to_fit_width(width)
1166 self.stretch_to_fit_height(height)
1169class AnnularSector(Arc):
1170 """A sector of a ring: the region between two arcs of one center, over one angle;
1171 white and filled, without an outline, unless styled.
1173 Args:
1174 inner_radius: The inner arc's radius, in scene units.
1175 outer_radius: The outer arc's radius, in scene units.
1176 angle: The angle it spans, in radians: counterclockwise from `start_angle`, or
1177 clockwise if negative.
1178 start_angle: The angle of its first edge, in radians, counterclockwise from the
1179 positive x-axis.
1180 **kwargs: [Arc keywords][manimgx.mobjects.shapes.ArcOptions];
1181 `num_components` has no effect.
1183 Examples:
1184 ```python
1185 import manimgx as m
1188 class AnnularSectorExample(m.Scene):
1189 def construct(self) -> None:
1190 sectors = m.VGroup(
1191 m.AnnularSector(),
1192 m.AnnularSector(1.5, 2, angle=m.PI, color=m.BLUE),
1193 m.AnnularSector(
1194 0.5, 2, angle=-3 * m.PI / 2, start_angle=m.PI, color=m.YELLOW
1195 ),
1196 ).arrange(buff=1)
1197 self.add(sectors)
1198 ```
1199 """
1201 defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0, "color": WHITE}
1203 def __init__(
1204 self,
1205 inner_radius: float = 1,
1206 outer_radius: float = 2,
1207 angle: float = TAU / 4,
1208 start_angle: float = 0,
1209 **kwargs: Unpack[ArcOptions],
1210 ) -> None:
1211 self.inner_radius = inner_radius
1212 self.outer_radius = outer_radius
1213 super().__init__(start_angle=start_angle, angle=angle, **kwargs)
1215 def generate_points(self) -> Self:
1216 arc = _unit_arc(self.start_angle, self.angle, 9)
1217 inner = arc * self.inner_radius + self.arc_center
1218 outer = arc[::-1] * self.outer_radius + self.arc_center
1219 self.append_points(inner)
1220 self.add_line_to(outer[0])
1221 self.append_points(outer)
1222 self.add_line_to(inner[0])
1223 return self
1226class Sector(AnnularSector):
1227 """A sector of a disc, a slice of pie: the region between two radii and the arc
1228 joining them; white and filled, without an outline, unless styled.
1230 Args:
1231 radius: Its radius, in scene units.
1232 **kwargs: [Sector keywords][manimgx.mobjects.shapes.SectorOptions]: its
1233 angles (a quarter turn from the positive x-axis unless given), style and
1234 center; `num_components` has no effect.
1236 Examples:
1237 ```python
1238 import manimgx as m
1241 class SectorExample(m.Scene):
1242 def construct(self) -> None:
1243 sectors = m.VGroup(
1244 m.Sector(radius=2),
1245 m.Sector(radius=2, angle=m.PI / 3, start_angle=m.PI, color=m.BLUE),
1246 m.Sector(radius=2, angle=-5 * m.PI / 3, color=m.YELLOW),
1247 ).arrange(buff=1)
1248 self.add(sectors)
1249 ```
1250 """
1252 def __init__(self, radius: float = 1, **kwargs: Unpack[SectorOptions]) -> None:
1253 super().__init__(inner_radius=0, outer_radius=radius, **kwargs)
1256class Annulus(Circle):
1257 """A ring: the region between two circles of one center; white and filled, without
1258 an outline, unless styled.
1260 The inner circle runs clockwise, the other way around from the outer one, so it is
1261 a hole in the fill.
1263 Args:
1264 inner_radius: The inner circle's radius, in scene units.
1265 outer_radius: The outer circle's radius, in scene units.
1266 mark_paths_closed: Accepted for Manim compatibility; ignored.
1267 **kwargs: [Arc keywords][manimgx.mobjects.shapes.ArcOptions];
1268 `num_components` has no effect.
1270 Examples:
1271 ```python
1272 import manimgx as m
1275 class AnnulusExample(m.Scene):
1276 def construct(self) -> None:
1277 rings = m.VGroup(
1278 m.Annulus(),
1279 m.Annulus(inner_radius=1.5, outer_radius=2, color=m.BLUE),
1280 m.Annulus(inner_radius=0.5, outer_radius=1.5, color=m.YELLOW),
1281 ).arrange(buff=1)
1282 self.add(rings)
1283 ```
1284 """
1286 defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0, "color": WHITE}
1288 def __init__(
1289 self,
1290 inner_radius: float = 1,
1291 outer_radius: float = 2,
1292 mark_paths_closed: bool = False,
1293 **kwargs: Unpack[ArcOptions],
1294 ) -> None:
1295 self.mark_paths_closed = mark_paths_closed
1296 self.inner_radius = inner_radius
1297 self.outer_radius = outer_radius
1298 super().__init__(**kwargs)
1300 def generate_points(self) -> Self:
1301 self.radius = self.outer_radius
1302 arc = _unit_arc(0, TAU, 9)
1303 self.append_points(arc * self.outer_radius)
1304 self.append_points(arc[::-1] * self.inner_radius)
1305 self.shift(self.arc_center)
1306 return self
1309class CubicBezier(VMobject):
1310 """A cubic Bézier curve: from one anchor to another, pulled toward two handles;
1311 white unless styled.
1313 The curve leaves its start heading toward `start_handle` and comes into its end
1314 from the direction of `end_handle`; the farther a handle, the longer the curve
1315 keeps to its direction. It passes through neither handle.
1317 Args:
1318 start_anchor: Where the curve starts.
1319 start_handle: The handle of its start.
1320 end_handle: The handle of its end.
1321 end_anchor: Where the curve ends.
1323 Examples:
1324 ```python
1325 import manimgx as m
1328 class CubicBezierExample(m.Scene):
1329 def construct(self) -> None:
1330 start, end = [-5, -2, 0], [5, -2, 0]
1331 handle1, handle2 = [-3, 3, 0], [6, 3, 0]
1332 curve = m.CubicBezier(start, handle1, handle2, end, color=m.YELLOW)
1333 levers = m.VGroup(m.Line(start, handle1), m.Line(end, handle2))
1334 levers.set_stroke(m.GREY, width=2)
1335 anchors = m.VGroup(m.Dot(start), m.Dot(end)).set_color(m.BLUE)
1336 handles = m.VGroup(m.Dot(handle1), m.Dot(handle2)).set_color(m.RED)
1337 self.add(levers, anchors, handles)
1338 self.play(m.Create(curve, run_time=2))
1339 ```
1340 """
1342 def __init__(
1343 self,
1344 start_anchor: Point3DLike,
1345 start_handle: Point3DLike,
1346 end_handle: Point3DLike,
1347 end_anchor: Point3DLike,
1348 **kwargs: Unpack[Style],
1349 ) -> None:
1350 super().__init__(**kwargs)
1351 self.add_cubic_bezier_curve(start_anchor, start_handle, end_handle, end_anchor)
1354class ArcPolygon(VMobject):
1355 """A polygon whose sides are arcs: an [ArcBetweenPoints][manimgx.ArcBetweenPoints]
1356 from each vertex to the next, and from the last back to the first; white unless
1357 styled.
1359 Going around the vertices counterclockwise, arcs of a positive angle bulge out, and
1360 arcs of a negative one bend in. Its outline runs along the arcs, and is filled and
1361 stroked in its style. The arcs are also its submobjects, its
1362 [arcs][manimgx.ArcPolygon.arcs], drawn over its outline in their own style (white
1363 unless `arc_config` styles them): to color the whole, style them too, as a family
1364 method such as [set_color][manimgx.Mobject.set_color] does.
1366 Args:
1367 *vertices: The vertices, in order around it.
1368 angle: The angle every arc turns through, in radians, unless `radius` or
1369 `arc_config` is given.
1370 radius: The radius of every arc, in scene units, in place of `angle`, unless
1371 `arc_config` is given; None (or 0) to use `angle`.
1372 arc_config: The arcs' [ArcBetweenPoints
1373 keywords][manimgx.ArcBetweenPoints], in place of
1374 `angle` and `radius`: one set for every arc, or a list of one per side, the
1375 first vertex's side first.
1377 Examples:
1378 ```python
1379 import manimgx as m
1382 class ArcPolygonExample(m.Scene):
1383 def construct(self) -> None:
1384 a, b, c = [0, 0, 0], [2.5, 0, 0], [0, 2.5, 0]
1385 sides = [{"radius": 2, "color": m.RED}, {"angle": 0}, {"angle": 1}]
1386 shapes = m.VGroup(
1387 m.ArcPolygon(a, b, c),
1388 m.ArcPolygon(a, b, c, radius=2, fill_opacity=0.5).set_color(m.BLUE),
1389 m.ArcPolygon(a, b, c, angle=-m.PI / 3).set_color(m.GREEN),
1390 m.ArcPolygon(a, b, c, arc_config=sides),
1391 ).arrange(buff=0.6)
1392 self.play(m.Create(shapes, run_time=4))
1393 ```
1394 """
1396 def __init__(
1397 self,
1398 *vertices: Point3DLike,
1399 angle: float = PI / 4,
1400 radius: float | None = None,
1401 arc_config: ArcBetweenOptions | list[ArcBetweenOptions] | None = None,
1402 **kwargs: Unpack[Style],
1403 ) -> None:
1404 n = len(vertices)
1405 point_pairs = [(vertices[k], vertices[(k + 1) % n]) for k in range(n)]
1406 all_arc_configs: Iterable[ArcBetweenOptions]
1407 if not arc_config:
1408 config_: ArcBetweenOptions = (
1409 {"radius": radius} if radius else {"angle": angle}
1410 )
1411 all_arc_configs = itertools.repeat(config_, len(point_pairs))
1412 elif isinstance(arc_config, list):
1413 assert len(arc_config) == n
1414 all_arc_configs = arc_config
1415 else:
1416 all_arc_configs = itertools.repeat(arc_config, len(point_pairs))
1417 arcs = [
1418 ArcBetweenPoints(*pair, **conf)
1419 for pair, conf in zip(point_pairs, all_arc_configs, strict=True)
1420 ]
1421 super().__init__(**kwargs)
1422 self.add(*arcs)
1423 for arc in arcs:
1424 self.append_points(arc.points)
1425 self.arcs = arcs
1426 """The arcs, one per side, the first vertex's side first; they are also its
1427 submobjects."""
1430class ArcPolygonFromArcs(VMobject):
1431 """A closed shape made of arcs: each arc in turn, joined to the next by a straight
1432 line where they do not meet, and the last to the first; white unless styled.
1434 Its outline is filled and stroked in its style. The arcs are also its submobjects,
1435 its [arcs][manimgx.ArcPolygonFromArcs.arcs], drawn over its outline in their own
1436 style: to color the whole, style them too, as a family method such as
1437 [set_color][manimgx.Mobject.set_color] does.
1439 Args:
1440 *arcs: The arcs, in order around it: [Arc][manimgx.Arc]s, or
1441 [ArcBetweenPoints][manimgx.ArcBetweenPoints].
1443 Examples:
1444 ```python
1445 import manimgx as m
1448 class ArcPolygonFromArcsExample(m.Scene):
1449 def construct(self) -> None:
1450 a, b, c = [-5.5, -1.3, 0], [-2.5, -1.3, 0], [-4, 1.3, 0]
1451 pairs = (a, b), (b, c), (c, a)
1452 sides = [m.ArcBetweenPoints(p, q, radius=3) for p, q in pairs]
1453 reuleaux = m.ArcPolygonFromArcs(*sides, fill_opacity=0.5)
1454 left = m.Arc(start_angle=m.PI / 2, angle=m.PI).shift(1.5 * m.RIGHT)
1455 right = m.Arc(start_angle=-m.PI / 2, angle=m.PI).shift(4.5 * m.RIGHT)
1456 stadium = m.ArcPolygonFromArcs(left, right, fill_opacity=0.5)
1457 reuleaux.set_color(m.BLUE)
1458 stadium.set_color(m.GREEN)
1459 self.play(m.Create(reuleaux), m.Create(stadium))
1460 ```
1461 """
1463 def __init__(self, *arcs: Arc | ArcBetweenPoints, **kwargs: Unpack[Style]) -> None:
1464 super().__init__(**kwargs)
1465 self.add(*arcs)
1466 self.arcs = [*arcs]
1467 """The arcs, in order; they are also its submobjects."""
1469 for arc1, arc2 in adjacent_pairs(arcs):
1470 self.append_points(arc1.points)
1471 # the joining line is divided into curves about as long as the arc's, so
1472 # the outline's points are spread evenly along it
1473 line = Line(arc1.get_end(), arc2.get_start())
1474 len_ratio = line.get_length() / arc1.get_arc_length()
1475 if np.isnan(len_ratio) or np.isinf(len_ratio):
1476 continue
1477 line.insert_n_curves(int(arc1.get_num_curves() * len_ratio))
1478 self.append_points(line.points)
1481class Polygram(VMobject):
1482 """A shape of straight sides through groups of vertices: each group a closed path,
1483 from vertex to vertex and back to its first; blue unless styled.
1485 The groups make one mobject, filled and stroked together. Where they overlap, the
1486 fill counts how many times its paths wind around each point: a group inside another
1487 that runs the other way around is a hole.
1489 The vertices are taken as they are given: changing their arrays afterwards changes
1490 no shape.
1492 Args:
1493 *vertex_groups: The groups of vertices, each in order around its path.
1495 Examples:
1496 ```python
1497 import numpy as np
1499 import manimgx as m
1502 class PolygramExample(m.Scene):
1503 def construct(self) -> None:
1504 r = np.sqrt(3)
1505 hexagram = m.Polygram(
1506 [[0, 2, 0], [-r, -1, 0], [r, -1, 0]],
1507 [[-r, 1, 0], [0, -2, 0], [r, 1, 0]],
1508 )
1509 framed = m.Polygram(
1510 [[-2, -2, 0], [2, -2, 0], [2, 2, 0], [-2, 2, 0]],
1511 [[-1, -1, 0], [-1, 1, 0], [1, 1, 0], [1, -1, 0]],
1512 color=m.YELLOW,
1513 fill_opacity=0.5,
1514 )
1515 self.play(m.Create(m.VGroup(hexagram, framed).arrange(buff=2)))
1516 ```
1517 """
1519 defaults: ClassVar[Style] = {"color": BLUE}
1521 def __init__(
1522 self, *vertex_groups: Point3DLike_Array, **kwargs: Unpack[Style]
1523 ) -> None:
1524 super().__init__(**kwargs)
1525 for vertices in vertex_groups:
1526 first_vertex, *vertices = vertices
1527 first_vertex = np.array(first_vertex)
1528 self.start_new_path(first_vertex)
1529 self.add_points_as_corners(np.array([*vertices, first_vertex]))
1531 def get_vertices(self) -> Point3D_Array:
1532 """The polygram's vertices, group after group: where each of its curves starts
1533 (the arcs and sides too, once its corners are rounded).
1535 Returns:
1536 An (n, 3) array of points, in scene coordinates.
1537 """
1538 return self.get_start_anchors()
1540 def get_vertex_groups(self) -> list[Point3D_Array]:
1541 """The polygram's vertices, grouped by the closed paths they are on.
1543 Returns:
1544 A list of (n, 3) arrays of points, one per closed path.
1545 """
1546 vertex_groups = []
1547 group = []
1548 for start, end in zip(
1549 self.get_start_anchors(), self.get_end_anchors(), strict=True
1550 ):
1551 group.append(start)
1552 if self.consider_points_equals(end, group[0]):
1553 vertex_groups.append(np.array(group))
1554 group = []
1555 return vertex_groups
1557 def round_corners(
1558 self,
1559 radius: float | list[float] = 0.5,
1560 evenly_distribute_anchors: bool = False,
1561 components_per_rounded_corner: int = 2,
1562 ) -> Self:
1563 """Round the polygram's corners: replace each with an arc of `radius` tangent to
1564 its two sides.
1566 An arc touches each side at most halfway along it: a radius too large for a
1567 corner is made smaller. A negative radius rounds a corner the other way,
1568 cutting a concave arc into it.
1570 Args:
1571 radius: The arcs' radius, in scene units; or a list of radii, one per
1572 corner of each group, from its second vertex's on (its first vertex's
1573 last), repeated over the corners: its length must divide their number.
1574 evenly_distribute_anchors: Whether to divide the straight sides into curves
1575 about as long as the arcs' curves, so the outline's points are spread
1576 evenly along it (a transform then moves them more evenly).
1577 components_per_rounded_corner: How many anchor points each arc is drawn
1578 through: 2 for one cubic Bézier curve.
1580 Examples:
1581 ```python
1582 import manimgx as m
1585 class PolygramRoundCornersExample(m.Scene):
1586 def construct(self) -> None:
1587 square = m.Square(2.8, color=m.YELLOW)
1588 shapes = m.VGroup(
1589 m.Star(outer_radius=1.5),
1590 m.Star(outer_radius=1.5).round_corners(0.25),
1591 square.round_corners([0.1, 0.4, 0.8, 1.2]),
1592 m.Triangle(radius=1.6, color=m.GREEN).round_corners(-0.5),
1593 ).arrange(buff=0.5)
1594 self.add(shapes)
1595 ```
1596 """
1597 if radius == 0:
1598 return self
1599 new_points: list[Point3D_Array] = []
1600 for vertex_group in self.get_vertex_groups():
1601 arcs = []
1602 if isinstance(radius, (int, float)):
1603 radius_list = [radius] * len(vertex_group)
1604 else:
1605 radius_list = radius * ceil(len(vertex_group) / len(radius))
1606 for current_radius, (v1, v2, v3) in zip(
1607 radius_list, adjacent_n_tuples(list(vertex_group), 3), strict=True
1608 ):
1609 vect1 = v2 - v1
1610 vect2 = v3 - v2
1611 unit_vect1 = normalize(vect1)
1612 unit_vect2 = normalize(vect2)
1613 angle = angle_between_vectors(vect1, vect2)
1614 angle *= np.sign(current_radius)
1615 cut_off_length = current_radius * np.tan(angle / 2)
1616 max_cut_off = min(np.linalg.norm(vect1), np.linalg.norm(vect2)) / 2
1617 cut_off_length = np.clip(cut_off_length, -max_cut_off, max_cut_off)
1618 sign = np.sign(np.cross(vect1, vect2)[2])
1619 arc = ArcBetweenPoints(
1620 v2 - unit_vect1 * cut_off_length,
1621 v2 + unit_vect2 * cut_off_length,
1622 angle=sign * angle,
1623 num_components=components_per_rounded_corner,
1624 )
1625 arcs.append(arc)
1626 average_arc_length = 1.0
1627 if evenly_distribute_anchors:
1628 nonzero_length_arcs = [arc for arc in arcs if len(arc.points) > 4]
1629 if len(nonzero_length_arcs) > 0:
1630 total_arc_length = sum(
1631 [arc.get_arc_length() for arc in nonzero_length_arcs]
1632 )
1633 num_curves = (
1634 sum([len(arc.points) for arc in nonzero_length_arcs]) / 4
1635 )
1636 average_arc_length = total_arc_length / num_curves
1637 arcs = [arcs[-1], *arcs[:-1]]
1639 for arc1, arc2 in adjacent_pairs(arcs):
1640 new_points.append(arc1.points)
1641 line = Line(arc1.get_end(), arc2.get_start())
1642 if evenly_distribute_anchors:
1643 line.insert_n_curves(ceil(line.get_length() / average_arc_length))
1644 new_points.append(line.points)
1645 self.set_points(np.concatenate(new_points) if new_points else np.array([]))
1646 return self
1649class Polygon(Polygram):
1650 """A polygon: straight sides from each vertex to the next, and from the last back to
1651 the first; blue unless styled.
1653 Args:
1654 *vertices: The vertices, in order around it.
1656 Examples:
1657 ```python
1658 import manimgx as m
1661 class PolygonExample(m.Scene):
1662 def construct(self) -> None:
1663 triangle = m.Polygon([-6, -2, 0], [-1.5, -2, 0], [-3.5, 2.5, 0])
1664 arrowhead = m.Polygon(
1665 [1, -2.5, 0],
1666 [6, 0, 0],
1667 [1, 2.5, 0],
1668 [2.5, 0, 0],
1669 color=m.YELLOW,
1670 fill_opacity=0.5,
1671 )
1672 self.play(m.Create(triangle), m.Create(arrowhead))
1673 ```
1674 """
1676 def __init__(self, *vertices: Point3DLike, **kwargs: Unpack[Style]) -> None:
1677 super().__init__(vertices, **kwargs)
1680class RegularPolygonOptions(_Style, total=False, closed=True):
1681 """A [RegularPolygon][manimgx.RegularPolygon]'s keywords but its number of vertices,
1682 for the classes that pass them on: its size and turn, with the style keywords."""
1684 radius: float
1685 """The radius of the circle its vertices are on, in scene units (default 1)."""
1686 start_angle: float | None
1687 """The angle of its first vertex, in radians, counterclockwise from the positive
1688 x-axis (default None: a vertex straight up if their number is odd, to the right if
1689 it is even)."""
1692class RegularPolygram(Polygram):
1693 """A regular star polygon: points evenly spaced on a circle, each joined to the one
1694 `density` steps on; blue unless styled.
1696 With a density of 1 it is a regular polygon; five points at density 2 make a
1697 pentagram. When the number of points and the density share a factor, the points
1698 make that many polygrams, each turned from the last: six points at density 2 make
1699 two triangles, a hexagram.
1701 Args:
1702 num_vertices: How many points there are on the circle.
1703 density: How many steps on each point is joined to: 1 for a polygon.
1704 radius: The radius of the circle, in scene units.
1705 start_angle: The angle of the first point, in radians, counterclockwise from
1706 the positive x-axis; None for a point straight up if each polygram has an
1707 odd number of points, to the right if even.
1709 Examples:
1710 ```python
1711 import manimgx as m
1714 class RegularPolygramExample(m.Scene):
1715 def construct(self) -> None:
1716 polygrams = m.VGroup(
1717 m.RegularPolygram(5, radius=2),
1718 m.RegularPolygram(7, density=3, radius=2, color=m.YELLOW),
1719 m.RegularPolygram(6, radius=2, color=m.GREEN),
1720 ).arrange(buff=1)
1721 self.play(m.Create(polygrams, run_time=3))
1722 ```
1723 """
1725 def __init__(
1726 self,
1727 num_vertices: int,
1728 *,
1729 density: int = 2,
1730 radius: float = 1,
1731 start_angle: float | None = None,
1732 **kwargs: Unpack[Style],
1733 ) -> None:
1734 num_gons = np.gcd(num_vertices, density)
1735 num_vertices //= num_gons
1736 density //= num_gons
1738 vertices, self.start_angle = regular_vertices(
1739 num_vertices, radius=radius, start_angle=start_angle
1740 )
1741 order = np.arange(num_vertices) * (density % num_vertices) % num_vertices
1742 vertex_groups = [vertices[order]]
1743 for i in range(1, num_gons):
1744 start_angle = self.start_angle + i / num_gons * TAU / num_vertices
1745 vertices, _ = regular_vertices(
1746 num_vertices, radius=radius, start_angle=start_angle
1747 )
1748 vertex_groups.append(vertices[order])
1749 super().__init__(*vertex_groups, **kwargs)
1752class RegularPolygon(RegularPolygram):
1753 """A regular polygon: `n` vertices evenly spaced on a circle, joined in turn; blue
1754 unless styled.
1756 Args:
1757 n: How many vertices, and sides, it has.
1758 **kwargs: [Regular polygon
1759 keywords][manimgx.mobjects.shapes.RegularPolygonOptions]: its
1760 radius (1 unless given), its turn and its style.
1762 Examples:
1763 ```python
1764 import manimgx as m
1767 class RegularPolygonExample(m.Scene):
1768 def construct(self) -> None:
1769 polygons = m.VGroup(
1770 m.RegularPolygon(radius=1.5),
1771 m.RegularPolygon(radius=1.5, start_angle=m.PI / 6, color=m.GREEN),
1772 m.RegularPolygon(5, radius=1.5, color=m.YELLOW),
1773 m.RegularPolygon(10, radius=1.5, color=m.RED),
1774 ).arrange(buff=0.5)
1775 self.add(polygons)
1776 ```
1777 """
1779 def __init__(self, n: int = 6, **kwargs: Unpack[RegularPolygonOptions]) -> None:
1780 super().__init__(n, density=1, **kwargs)
1783class Star(Polygon):
1784 """A star: `n` points on a circle, and between each two a vertex on a smaller
1785 circle; blue unless styled.
1787 Unless given, the inner radius is the one that makes the star the outline of the
1788 [RegularPolygram][manimgx.RegularPolygram] of its `n` points at `density`: its
1789 edges lie along the polygram's lines.
1791 Args:
1792 n: How many points it has.
1793 outer_radius: The radius of the circle its points are on, in scene units.
1794 inner_radius: The radius of the circle its inner vertices are on, in scene
1795 units; None to set it by `density`.
1796 density: Without `inner_radius`, the density of the polygram whose outline it
1797 is: the higher, the thinner its points. It must be above 0 and below
1798 `n / 2`.
1799 start_angle: The angle of its first point, in radians, counterclockwise from
1800 the positive x-axis (default a quarter turn: straight up); None for a
1801 point straight up if `n` is odd, to the right if even.
1803 Examples:
1804 ```python
1805 import manimgx as m
1808 class StarExample(m.Scene):
1809 def construct(self) -> None:
1810 stars = m.VGroup(
1811 m.Star(outer_radius=1.5),
1812 m.Star(7, outer_radius=1.5, color=m.YELLOW),
1813 m.Star(7, outer_radius=1.5, density=3, color=m.RED),
1814 m.Star(12, outer_radius=1.5, inner_radius=1, color=m.GREEN),
1815 ).arrange(buff=0.5)
1816 self.play(m.Create(stars, run_time=3))
1817 ```
1818 """
1820 def __init__(
1821 self,
1822 n: int = 5,
1823 *,
1824 outer_radius: float = 1,
1825 inner_radius: float | None = None,
1826 density: int = 2,
1827 start_angle: float | None = TAU / 4,
1828 **kwargs: Unpack[Style],
1829 ) -> None:
1830 inner_angle = TAU / (2 * n)
1831 if (
1832 inner_radius is None
1833 ): # the radius that makes the star's edges lines through `density` points
1834 if density <= 0 or density >= n / 2:
1835 raise ValueError(
1836 f"Incompatible density {density} for number of points {n}"
1837 )
1838 outer_angle = TAU * density / n
1839 inverse_x = 1 - np.tan(inner_angle) * (
1840 (np.cos(outer_angle) - 1) / np.sin(outer_angle)
1841 )
1842 inner_radius = float(outer_radius / (np.cos(inner_angle) * inverse_x))
1843 outer_vertices, self.start_angle = regular_vertices(
1844 n, radius=outer_radius, start_angle=start_angle
1845 )
1846 inner_vertices, _ = regular_vertices(
1847 n, radius=inner_radius, start_angle=self.start_angle + inner_angle
1848 )
1849 vertices: list[npt.NDArray] = []
1850 for pair in zip(outer_vertices, inner_vertices, strict=True):
1851 vertices.extend(pair)
1852 super().__init__(*vertices, **kwargs)
1855class Triangle(RegularPolygon):
1856 """An equilateral triangle, pointing up, its vertices on a circle of radius 1 unless
1857 given another; blue unless styled.
1859 Args:
1860 **kwargs: [Regular polygon
1861 keywords][manimgx.mobjects.shapes.RegularPolygonOptions]: its
1862 radius, its turn and its style.
1864 Examples:
1865 ```python
1866 import manimgx as m
1869 class TriangleExample(m.Scene):
1870 def construct(self) -> None:
1871 triangles = m.VGroup(
1872 m.Triangle(),
1873 m.Triangle(radius=2, color=m.YELLOW, fill_opacity=0.5),
1874 m.Triangle(radius=2, start_angle=-m.PI / 2, color=m.GREEN),
1875 ).arrange(buff=1)
1876 self.add(triangles)
1877 ```
1878 """
1880 def __init__(self, **kwargs: Unpack[RegularPolygonOptions]) -> None:
1881 super().__init__(n=3, **kwargs)
1884class _GridOptions(_Style, total=False):
1885 """GridOptions's keys, open, for the keywords that add to them."""
1887 grid_xstep: float | None
1888 """The distance between the vertical lines of its grid, from its left edge, in
1889 scene units (default None: no vertical lines)."""
1890 grid_ystep: float | None
1891 """The distance between the horizontal lines of its grid, from its top edge, in
1892 scene units (default None: no horizontal lines)."""
1893 mark_paths_closed: bool
1894 """Accepted for Manim compatibility; ignored."""
1897class GridOptions(_GridOptions, total=False, closed=True):
1898 """A [Rectangle][manimgx.Rectangle]'s grid, with the style keywords (for the classes
1899 that pass them on)."""
1902class RectangleOptions(_GridOptions, total=False, closed=True):
1903 """A [Rectangle][manimgx.Rectangle]'s keywords, for the classes that pass them on:
1904 its size and its grid, with the style keywords."""
1906 height: float
1907 """Its height, in scene units (default 2)."""
1908 width: float
1909 """Its width, in scene units (default 4)."""
1912class Rectangle(Polygon):
1913 """A rectangle, 4 wide and 2 tall unless sized, centered at the origin; white unless
1914 styled.
1916 Its vertices run counterclockwise from its top right corner. With `grid_xstep` or
1917 `grid_ystep` it is ruled into a grid: lines across it, its
1918 [grid_lines][manimgx.Rectangle.grid_lines], in its `color`.
1920 Args:
1921 color: Its color, which may be given by position (`Rectangle(BLUE)`); None for
1922 white.
1923 height: Its height, in scene units.
1924 width: Its width, in scene units.
1925 grid_xstep: The distance between the vertical lines of its grid, from its left
1926 edge, in scene units; None for none.
1927 grid_ystep: The distance between the horizontal lines of its grid, from its top
1928 edge, in scene units; None for none.
1929 mark_paths_closed: Accepted for Manim compatibility; ignored.
1930 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
1932 Examples:
1933 ```python
1934 import manimgx as m
1937 class RectangleExample(m.Scene):
1938 def construct(self) -> None:
1939 grid = m.Rectangle(
1940 m.YELLOW, height=3, width=4, grid_xstep=1, grid_ystep=0.5
1941 )
1942 rectangles = m.VGroup(
1943 m.Rectangle(),
1944 m.Rectangle(m.BLUE, height=4, width=1.5, fill_opacity=0.5),
1945 grid,
1946 ).arrange(buff=1)
1947 self.add(rectangles)
1948 ```
1949 """
1951 defaults: ClassVar[Style] = {"color": WHITE}
1953 def __init__(
1954 self,
1955 color: Colors | None = None,
1956 height: float = 2.0,
1957 width: float = 4.0,
1958 grid_xstep: float | None = None,
1959 grid_ystep: float | None = None,
1960 mark_paths_closed: bool = False,
1961 **kwargs: Unpack[StyleBase],
1962 ) -> None:
1963 style = Style(**kwargs) if color is None else Style(**kwargs, color=color)
1964 color = (style_defaults(type(self)) | style).get("color", WHITE)
1965 super().__init__(UR, UL, DL, DR, **style)
1966 self.stretch_to_fit_width(width)
1967 self.stretch_to_fit_height(height)
1969 v = self.get_vertices()
1970 line_color = color or WHITE
1971 self.grid_lines = VGroup()
1972 """The lines of its grid: a group of the vertical lines, then one of the
1973 horizontal lines, those it has; a submobject, unless it is empty (without a
1974 grid)."""
1975 if grid_xstep:
1976 grid_xstep = abs(grid_xstep)
1977 count = int(width / grid_xstep)
1978 grid = VGroup(
1979 *(
1980 Line(
1981 v[1] + i * grid_xstep * RIGHT,
1982 v[1] + i * grid_xstep * RIGHT + height * DOWN,
1983 color=line_color,
1984 )
1985 for i in range(1, count)
1986 )
1987 )
1988 self.grid_lines.add(grid)
1989 if grid_ystep:
1990 grid_ystep = abs(grid_ystep)
1991 count = int(height / grid_ystep)
1992 grid = VGroup(
1993 *(
1994 Line(
1995 v[1] + i * grid_ystep * DOWN,
1996 v[1] + i * grid_ystep * DOWN + width * RIGHT,
1997 color=line_color,
1998 )
1999 for i in range(1, count)
2000 )
2001 )
2002 self.grid_lines.add(grid)
2003 if self.grid_lines:
2004 self.add(self.grid_lines)
2007class ScreenOptions(_Style, total=False, closed=True):
2008 """A [ScreenRectangle][manimgx.ScreenRectangle]'s keywords, for the rectangles that
2009 pass them on: its proportions and its height, with the style keywords."""
2011 aspect_ratio: float
2012 """Its width over its height (default 16 / 9)."""
2013 height: float
2014 """Its height, in scene units (default 4)."""
2017class ScreenRectangle(Rectangle):
2018 """A rectangle with a screen's proportions, 16:9 and 4 tall unless given others,
2019 centered at the origin; white unless styled.
2021 Args:
2022 aspect_ratio: Its width over its height.
2023 height: Its height, in scene units.
2025 Examples:
2026 ```python
2027 import manimgx as m
2030 class ScreenRectangleExample(m.Scene):
2031 def construct(self) -> None:
2032 screens = m.VGroup(
2033 m.ScreenRectangle(),
2034 m.ScreenRectangle(aspect_ratio=4 / 3, height=3, color=m.BLUE),
2035 ).arrange(buff=1)
2036 self.add(screens)
2037 ```
2038 """
2040 def __init__(
2041 self,
2042 aspect_ratio: float = 16.0 / 9.0,
2043 height: float = 4,
2044 **kwargs: Unpack[Style],
2045 ) -> None:
2046 super().__init__(width=aspect_ratio * height, height=height, **kwargs)
2048 @property
2049 def aspect_ratio(self) -> float:
2050 """The rectangle's width over its height. Set it to stretch the rectangle's
2051 width to that proportion, about its center; its height stays."""
2052 return self.width / self.height
2054 @aspect_ratio.setter
2055 def aspect_ratio(self, value: float) -> None:
2056 self.stretch_to_fit_width(value * self.height)
2059class FullScreenRectangle(ScreenRectangle):
2060 """A screen rectangle as tall as the frame, centered at the origin: with the 16:9
2061 proportions it has unless given others, the frame's own outline; white unless
2062 styled.
2064 Its height is the frame's (8 units unless configured otherwise), whatever `height`
2065 is given.
2067 Args:
2068 **kwargs: [Screen rectangle keywords][manimgx.mobjects.shapes.ScreenOptions];
2069 `height` has no effect.
2071 Examples:
2072 ```python
2073 import manimgx as m
2076 class FullScreenRectangleExample(m.Scene):
2077 def construct(self) -> None:
2078 backdrop = m.FullScreenRectangle(
2079 fill_color=m.DARK_BLUE, fill_opacity=1, stroke_color=m.YELLOW
2080 )
2081 self.add(backdrop, m.Text("A backdrop", font_size=96))
2082 ```
2083 """
2085 def __init__(self, **kwargs: Unpack[ScreenOptions]) -> None:
2086 super().__init__(**kwargs)
2087 self.height = config.frame_height
2090class Square(Rectangle):
2091 """A square, 2 on a side unless sized, centered at the origin; white unless styled.
2093 Args:
2094 side_length: The length of its sides, in scene units.
2096 Examples:
2097 ```python
2098 import manimgx as m
2101 class SquareExample(m.Scene):
2102 def construct(self) -> None:
2103 squares = m.VGroup(
2104 m.Square(),
2105 m.Square(3, color=m.BLUE, fill_opacity=0.5),
2106 m.Square(4, color=m.YELLOW, grid_xstep=1, grid_ystep=1),
2107 ).arrange(buff=1)
2108 self.add(squares)
2109 ```
2110 """
2112 def __init__(self, side_length: float = 2.0, **kwargs: Unpack[GridOptions]) -> None:
2113 super().__init__(height=side_length, width=side_length, **kwargs)
2115 @property
2116 def side_length(self) -> float:
2117 """The length of the square's sides, in scene units: the distance between its
2118 first two vertices. Set it to scale the square to that side, about its
2119 center."""
2120 return float(np.linalg.norm(self.get_vertices()[0] - self.get_vertices()[1]))
2122 @side_length.setter
2123 def side_length(self, value: float) -> None:
2124 self.scale(value / self.side_length)
2127class RoundedRectangle(Rectangle):
2128 """A rectangle with rounded corners, 4 wide and 2 tall unless sized; white unless
2129 styled.
2131 Args:
2132 corner_radius: The radius of its corners, in scene units; or a list of radii
2133 for its top left, bottom left, bottom right and top right corners, in that
2134 order, repeated if there are one or two (see
2135 [round_corners][manimgx.Polygram.round_corners]).
2136 **kwargs: [Rectangle
2137 keywords][manimgx.mobjects.shapes.RectangleOptions]: its size,
2138 its grid and its style.
2140 Examples:
2141 ```python
2142 import manimgx as m
2145 class RoundedRectangleExample(m.Scene):
2146 def construct(self) -> None:
2147 leaf = m.RoundedRectangle([0, 1.2, 0, 1.2], height=3, width=3)
2148 rectangles = m.VGroup(
2149 m.RoundedRectangle(),
2150 m.RoundedRectangle(1.5, height=4, width=4, color=m.BLUE),
2151 leaf.set_color(m.YELLOW),
2152 ).arrange(buff=1)
2153 self.add(rectangles)
2154 ```
2155 """
2157 def __init__(
2158 self,
2159 corner_radius: float | list[float] = 0.5,
2160 **kwargs: Unpack[RectangleOptions],
2161 ) -> None:
2162 super().__init__(**kwargs)
2163 self.corner_radius = corner_radius
2164 self.round_corners(self.corner_radius)
2167class Cutout(VMobject):
2168 """A shape with holes cut out of it: the main shape's outline, with the other
2169 shapes' outlines as holes; white unless styled.
2171 Each hole's path runs the other way around from the main shape's, so the fill
2172 leaves it out: the shapes given as holes are turned to run that way, in place. Only
2173 the shapes' own paths are used, not their submobjects', and the cutout has a style
2174 of its own.
2176 Args:
2177 main_shape: The shape to cut the holes out of.
2178 *mobjects: The shapes of the holes, inside it.
2180 Examples:
2181 ```python
2182 import manimgx as m
2185 class CutoutExample(m.Scene):
2186 def construct(self) -> None:
2187 holes = [
2188 m.Circle(0.7).shift(1.3 * m.UL),
2189 m.Square(1.4).shift(1.3 * m.UR),
2190 m.Triangle(radius=0.8).shift(1.3 * m.DL),
2191 m.Star(outer_radius=0.8).shift(1.3 * m.DR),
2192 ]
2193 card = m.Cutout(m.Square(5), *holes, color=m.BLUE, fill_opacity=1)
2194 behind = m.Circle(radius=2.2, color=m.YELLOW, fill_opacity=1)
2195 self.add(behind, card)
2196 ```
2197 """
2199 def __init__(
2200 self, main_shape: VMobject, *mobjects: VMobject, **kwargs: Unpack[Style]
2201 ) -> None:
2202 super().__init__(**kwargs)
2203 self.append_points(main_shape.points)
2204 sub_direction: Literal["CCW", "CW"] = (
2205 "CCW" if main_shape.get_direction() == "CW" else "CW"
2206 )
2207 for mobject in mobjects:
2208 self.append_points(mobject.force_direction(sub_direction).points)
2211class ConvexHull(Polygram):
2212 """The convex hull of points: the smallest convex polygon around them all, its
2213 vertices among them; blue unless styled.
2215 It is found in the plane of the screen: the points' z coordinates are ignored.
2217 Args:
2218 *points: The points: at least three, not all on one line.
2219 tolerance: How far outside the hull a point may be and still not be made a
2220 vertex of it, in scene units.
2222 Examples:
2223 ```python
2224 import numpy as np
2226 import manimgx as m
2229 class ConvexHullExample(m.Scene):
2230 def construct(self) -> None:
2231 points = np.random.default_rng(7).uniform(-3, 3, (20, 3)) * [1.5, 1, 0]
2232 hull = m.ConvexHull(*points, color=m.YELLOW, fill_opacity=0.3)
2233 self.add(hull, *(m.Dot(point, radius=0.1) for point in points))
2234 ```
2235 """
2237 def __init__(
2238 self, *points: Point3DLike, tolerance: float = 1e-05, **kwargs: Unpack[Style]
2239 ) -> None:
2240 array = np.array(points)[:, :2]
2241 hull = QuickHull(tolerance)
2242 hull.build(array)
2243 facets = set(hull.facets) - hull.removed
2244 facet = facets.pop()
2245 subfacets = list(facet.subfacets)
2246 while len(subfacets) <= len(facets):
2247 sf = subfacets[-1]
2248 (facet,) = hull.neighbors[sf] - {facet}
2249 (sf,) = facet.subfacets - {sf}
2250 subfacets.append(sf)
2251 coordinates = np.vstack([sf.coordinates for sf in subfacets])
2252 vertices = np.hstack((coordinates, np.zeros((len(coordinates), 1))))
2253 super().__init__(vertices, **kwargs)
2256class ArrowTip(VMobject):
2257 """The base of arrow tips: a small shape with two points of its own, its
2258 [tip_point][manimgx.ArrowTip.tip_point], where the path it ends points to, and its
2259 [base][manimgx.ArrowTip.base], where the path stops.
2261 A path makes its tip as `tip_shape(length=…, **style)` (see
2262 [add_tip][manimgx.TipableVMobject.add_tip]), then turns and moves it into place: the
2263 tip is what its class makes at that length. It is not made itself: its subclasses
2264 are the tips. To make a tip of your own, subclass it and a shape, made at the length
2265 given: the shape's first point is the tip point, and the point halfway around its
2266 outline is the base. Both are read from its points, so they move with it; a
2267 subclass that names other points of its shape does so as properties, never stored.
2269 Args:
2270 length: The tip's length, in scene units.
2271 """
2273 @prototype
2274 def __init__(
2275 self, length: float = DEFAULT_ARROW_TIP_LENGTH, **kwargs: Unpack[Style]
2276 ) -> None:
2277 raise NotImplementedError("Has to be implemented in inheriting subclasses.")
2279 @property
2280 def base(self) -> Point3D:
2281 """The point where the path meets the tip, and stops: halfway around the tip's
2282 outline from its tip point."""
2283 return self.point_from_proportion(0.5)
2285 @property
2286 def tip_point(self) -> Point3D:
2287 """The tip's point, where the path points to: the first point of its
2288 outline."""
2289 tip_point: Point3D = self.points[0]
2290 return tip_point
2292 @property
2293 def vector(self) -> Vector3D:
2294 """The vector from the tip's base to its tip point: the way it points."""
2295 return self.tip_point - self.base
2297 @property
2298 def tip_angle(self) -> float:
2299 """The direction the tip points in: the angle of its
2300 [vector][manimgx.ArrowTip.vector], in radians, counterclockwise from the
2301 positive x-axis."""
2302 return angle_of_vector(self.vector)
2304 @property
2305 def length(self) -> float:
2306 """The tip's length, in scene units: the distance from its base to its tip
2307 point."""
2308 return float(np.linalg.norm(self.vector))
2311class StealthTip(ArrowTip):
2312 """A dart-shaped tip: a sharp point with two barbs swept back from it and a notch
2313 between them, where the path stops; filled, with a stroke 3 wide.
2315 Its length runs from its barbs to its point; the notch is 5/8 of the way back from
2316 the point. It is half as long as the other tips unless given a length.
2318 Args:
2319 length: Its length, from its barbs to its point, in scene units (default
2320 0.175).
2321 start_angle: Accepted for Manim compatibility; ignored.
2323 Examples:
2324 ```python
2325 import manimgx as m
2328 class StealthTipExample(m.Scene):
2329 def construct(self) -> None:
2330 tip = m.StealthTip
2331 a, b = 3 * m.LEFT, 3 * m.RIGHT
2332 arrows = m.VGroup(
2333 m.Arrow(a, b, tip_shape=tip),
2334 m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
2335 m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
2336 m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
2337 ).arrange(m.DOWN, buff=0.8)
2338 self.add(arrows)
2339 ```
2340 """
2342 defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 3}
2344 @prototype
2345 def __init__(
2346 self,
2347 length: float = DEFAULT_ARROW_TIP_LENGTH / 2,
2348 start_angle: float = PI,
2349 **kwargs: Unpack[Style],
2350 ):
2351 self.start_angle = start_angle
2352 VMobject.__init__(self, **kwargs)
2353 self.set_points_as_corners(
2354 np.array([[2, 0, 0], [-1.2, 1.6, 0], [0, 0, 0], [-1.2, -1.6, 0], [2, 0, 0]])
2355 )
2356 self.scale(length / self.length)
2358 @property
2359 def length(self) -> float:
2360 """The tip's whole length, in scene units: from its barbs to its point, 1.6
2361 times the distance from its notch to its point."""
2362 return float(np.linalg.norm(self.vector) * 1.6)
2365class ArrowTriangleTip(ArrowTip, Triangle):
2366 """A triangular tip, outlined: an isosceles triangle `length` long and `width` wide,
2367 its outline 3 wide and not filled.
2369 Args:
2370 length: Its length, from its base to its point, in scene units.
2371 width: Its width, across its base, in scene units.
2372 start_angle: The direction its point faces as made, in radians (default PI:
2373 left); a path turns the tip to point along itself.
2375 Examples:
2376 ```python
2377 import manimgx as m
2380 class ArrowTriangleTipExample(m.Scene):
2381 def construct(self) -> None:
2382 tip = m.ArrowTriangleTip
2383 a, b = 3 * m.LEFT, 3 * m.RIGHT
2384 arrows = m.VGroup(
2385 m.Arrow(a, b, tip_shape=tip),
2386 m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
2387 m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
2388 m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
2389 ).arrange(m.DOWN, buff=0.8)
2390 self.add(arrows)
2391 ```
2392 """
2394 defaults: ClassVar[Style] = {"fill_opacity": 0.0, "stroke_width": 3}
2396 @prototype
2397 def __init__(
2398 self,
2399 length: float = DEFAULT_ARROW_TIP_LENGTH,
2400 width: float = DEFAULT_ARROW_TIP_LENGTH,
2401 start_angle: float = PI,
2402 **kwargs: Unpack[Style],
2403 ) -> None:
2404 Triangle.__init__(self, start_angle=start_angle, **kwargs)
2405 self.width = width
2406 self.stretch_to_fit_width(length)
2407 self.stretch_to_fit_height(width)
2410class ArrowTriangleFilledTip(ArrowTriangleTip):
2411 """A triangular tip, filled and without an outline: the default tip of lines, arcs
2412 and arrows.
2414 Args:
2415 length: Its length, from its base to its point, in scene units.
2416 width: Its width, across its base, in scene units.
2417 start_angle: The direction its point faces as made, in radians (default PI:
2418 left); a path turns the tip to point along itself.
2419 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
2421 Examples:
2422 ```python
2423 import manimgx as m
2426 class ArrowTriangleFilledTipExample(m.Scene):
2427 def construct(self) -> None:
2428 tip = m.ArrowTriangleFilledTip
2429 a, b = 3 * m.LEFT, 3 * m.RIGHT
2430 arrows = m.VGroup(
2431 m.Arrow(a, b, tip_shape=tip),
2432 m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
2433 m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
2434 m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
2435 ).arrange(m.DOWN, buff=0.8)
2436 self.add(arrows)
2437 ```
2438 """
2440 defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0}
2443class ArrowCircleTip(ArrowTip, Circle):
2444 """A round tip, outlined: a circle `length` across, from where the path stops to
2445 where it ended; its outline 3 wide and not filled.
2447 Args:
2448 length: Its diameter, in scene units.
2449 start_angle: Accepted for Manim compatibility; ignored.
2451 Examples:
2452 ```python
2453 import manimgx as m
2456 class ArrowCircleTipExample(m.Scene):
2457 def construct(self) -> None:
2458 tip = m.ArrowCircleTip
2459 a, b = 3 * m.LEFT, 3 * m.RIGHT
2460 arrows = m.VGroup(
2461 m.Arrow(a, b, tip_shape=tip),
2462 m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
2463 m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
2464 m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
2465 ).arrange(m.DOWN, buff=0.8)
2466 self.add(arrows)
2467 ```
2468 """
2470 defaults: ClassVar[Style] = {"fill_opacity": 0.0, "stroke_width": 3}
2472 @prototype
2473 def __init__(
2474 self,
2475 length: float = DEFAULT_ARROW_TIP_LENGTH,
2476 start_angle: float = PI,
2477 **kwargs: Unpack[Style],
2478 ) -> None:
2479 self.start_angle = start_angle
2480 Circle.__init__(self, **kwargs)
2481 self.width = length
2482 self.stretch_to_fit_height(length)
2485class ArrowCircleFilledTip(ArrowCircleTip):
2486 """A round tip, filled and without an outline: a disc `length` across, from where
2487 the path stops to where it ended.
2489 Args:
2490 length: Its diameter, in scene units.
2491 start_angle: Accepted for Manim compatibility; ignored.
2492 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
2494 Examples:
2495 ```python
2496 import manimgx as m
2499 class ArrowCircleFilledTipExample(m.Scene):
2500 def construct(self) -> None:
2501 tip = m.ArrowCircleFilledTip
2502 a, b = 3 * m.LEFT, 3 * m.RIGHT
2503 arrows = m.VGroup(
2504 m.Arrow(a, b, tip_shape=tip),
2505 m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
2506 m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
2507 m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
2508 ).arrange(m.DOWN, buff=0.8)
2509 self.add(arrows)
2510 ```
2511 """
2513 defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0}
2516class ArrowSquareTip(ArrowTip, Square):
2517 """A square tip, outlined: a square `length` on a side, set on a corner, its
2518 diagonal along the path from where the path stops to where it ended; its outline 3
2519 wide and not filled.
2521 Its [length][manimgx.ArrowTip.length] is that diagonal's.
2523 Args:
2524 length: The length of its sides, in scene units.
2525 start_angle: Accepted for Manim compatibility; ignored.
2527 Examples:
2528 ```python
2529 import manimgx as m
2532 class ArrowSquareTipExample(m.Scene):
2533 def construct(self) -> None:
2534 tip = m.ArrowSquareTip
2535 a, b = 3 * m.LEFT, 3 * m.RIGHT
2536 arrows = m.VGroup(
2537 m.Arrow(a, b, tip_shape=tip),
2538 m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
2539 m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
2540 m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
2541 ).arrange(m.DOWN, buff=0.8)
2542 self.add(arrows)
2543 ```
2544 """
2546 defaults: ClassVar[Style] = {"fill_opacity": 0.0, "stroke_width": 3}
2548 @prototype
2549 def __init__(
2550 self,
2551 length: float = DEFAULT_ARROW_TIP_LENGTH,
2552 start_angle: float = PI,
2553 **kwargs: Unpack[Style],
2554 ) -> None:
2555 self.start_angle = start_angle
2556 Square.__init__(self, side_length=length, **kwargs)
2557 self.width = length
2558 self.stretch_to_fit_height(length)
2561class ArrowSquareFilledTip(ArrowSquareTip):
2562 """A square tip, filled and without an outline: a square `length` on a side, set on
2563 a corner, its diagonal along the path from where the path stops to where it ended.
2565 Its [length][manimgx.ArrowTip.length] is that diagonal's.
2567 Args:
2568 length: The length of its sides, in scene units.
2569 start_angle: Accepted for Manim compatibility; ignored.
2570 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
2572 Examples:
2573 ```python
2574 import manimgx as m
2577 class ArrowSquareFilledTipExample(m.Scene):
2578 def construct(self) -> None:
2579 tip = m.ArrowSquareFilledTip
2580 a, b = 3 * m.LEFT, 3 * m.RIGHT
2581 arrows = m.VGroup(
2582 m.Arrow(a, b, tip_shape=tip),
2583 m.Arrow(a / 3, b / 3, tip_shape=tip, color=m.BLUE),
2584 m.CurvedArrow(a, b, angle=-m.PI / 3, tip_shape=tip, color=m.GREEN),
2585 m.Line(a, b, color=m.YELLOW).add_tip(tip_shape=tip, tip_length=0.6),
2586 ).arrange(m.DOWN, buff=0.8)
2587 self.add(arrows)
2588 ```
2589 """
2591 defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0}
2594class ArcedBase(_TippedBase, total=False):
2595 """A line's bend, with the tip keywords and every style keyword but `color`."""
2597 path_arc: float
2598 """The angle the line bends through, in radians: 0 for straight; otherwise it is an
2599 arc from its start to its end, turning counterclockwise if positive (bending right
2600 on its way), clockwise if negative (default 0)."""
2603class _Arced(ArcedBase, _Tipped, total=False):
2604 """Arced's keys, open, for the keywords that add to them."""
2606 pass
2609class Arced(_Arced, total=False, closed=True):
2610 """A line's bend, with the style and tip keywords (for the lines that set the buffer
2611 themselves)."""
2614class _LineOptions(_Arced, total=False):
2615 """LineOptions's keys, open, for the keywords that add to them."""
2617 buff: float
2618 """How far the line stops short of each end, in scene units; a line shorter than
2619 twice it keeps its ends (default 0)."""
2622class LineOptions(_LineOptions, total=False, closed=True):
2623 """A [Line][manimgx.Line]'s keywords but its ends, for the classes that pass them
2624 on: its buffer and its bend, with the style and tip keywords."""
2627class DashedLineOptions(_LineOptions, total=False):
2628 """A [DashedLine][manimgx.DashedLine]'s keywords but its ends: its dashes, with the
2629 line keywords."""
2631 dash_length: float
2632 """The length of each dash, in scene units: about it, as a whole number of dashes
2633 spans the line (default 0.05)."""
2634 dashed_ratio: float
2635 """The fraction of the line the dashes cover, from 0 to 1; the rest is gaps
2636 (default 0.5: dashes and gaps as long)."""
2639class _ArrowTipsBase(ArcedBase, total=False):
2640 """ArrowTipsBase's keys, open, for the keywords that add to them."""
2642 max_tip_length_to_length_ratio: float
2643 """The longest its tip may be, as a fraction of its length: a short arrow's tip is
2644 shorter (default 0.25)."""
2645 max_stroke_width_to_length_ratio: float
2646 """The widest its stroke may be, in hundredths of a scene unit, per scene unit of
2647 its length: a short arrow is thinner (default 5)."""
2648 tip_shape: type[ArrowTip]
2649 """The class of its tip (default
2650 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip])."""
2653class ArrowTipsBase(_ArrowTipsBase, total=False, closed=True):
2654 """An [Arrow][manimgx.Arrow]'s keywords but its ends, its buffer and its color (for
2655 the methods that set those): its tip, how it shrinks when short, and its bend."""
2658class _ArrowTips(_ArrowTipsBase, _Tipped, total=False):
2659 """ArrowTips's keys, open, for the keywords that add to them."""
2661 pass
2664class ArrowTips(_ArrowTips, total=False, closed=True):
2665 """An [Arrow][manimgx.Arrow]'s keywords but its ends and its buffer (for the arrows
2666 that set it: vectors)."""
2669class ArrowOptions(_ArrowTips, total=False, closed=True):
2670 """An [Arrow][manimgx.Arrow]'s keywords but its ends, for the classes that pass them
2671 on."""
2673 buff: float
2674 """How far the arrow stops short of each end, in scene units (default 0.25)."""
2677class Line(TipableVMobject):
2678 """A straight line from one point to another, white unless styled; or an arc
2679 between them, bent through `path_arc`.
2681 An end may be a mobject: the line then starts (or ends) at its point farthest
2682 toward the other end (see [get_boundary_point][manimgx.Mobject.get_boundary_point]),
2683 so a line between two shapes runs from outline to outline. The line is placed when
2684 it is made, and does not follow the mobjects afterwards.
2686 Args:
2687 start: Where the line starts: a point, or a mobject.
2688 end: Where it ends: a point, or a mobject.
2689 buff: How far it stops short of each end, in scene units (along it, if bent);
2690 a line shorter than twice it keeps its ends.
2691 path_arc: The angle it bends through, in radians: 0 for straight; otherwise it
2692 is an arc, turning counterclockwise if positive, bending right on its way
2693 (see [ArcBetweenPoints][manimgx.ArcBetweenPoints]).
2695 Examples:
2696 ```python
2697 import manimgx as m
2700 class LineExample(m.Scene):
2701 def construct(self) -> None:
2702 straight = m.Line(4 * m.LEFT, 4 * m.RIGHT, color=m.BLUE)
2703 bent = m.Line(4 * m.LEFT, 4 * m.RIGHT, path_arc=-m.PI / 3)
2704 m.VGroup(straight, bent).arrange(m.DOWN, buff=1).shift(m.UP)
2705 left = m.Circle(radius=1, color=m.GREEN).move_to([-4.5, -2, 0])
2706 right = m.Circle(radius=0.5, color=m.RED).move_to([4.5, -2.5, 0])
2707 link = m.Line(left, right, buff=0.2, color=m.YELLOW)
2708 self.add(straight, bent, left, right, link)
2709 ```
2710 """
2712 def __init__(
2713 self,
2714 start: Point3DLike | Mobject = LEFT,
2715 end: Point3DLike | Mobject = RIGHT,
2716 buff: float = 0,
2717 path_arc: float = 0,
2718 **kwargs: Unpack[Tipped],
2719 ) -> None:
2720 self.dim = 3
2721 self.buff = buff
2722 self.path_arc = path_arc
2723 self._set_start_and_end_attrs(start, end)
2724 super().__init__(**kwargs)
2726 def generate_points(self) -> Self:
2727 self.set_points_by_ends(
2728 start=self.start, end=self.end, buff=self.buff, path_arc=self.path_arc
2729 )
2730 return self
2732 @deprecated("use put_start_and_end_on", category=None)
2733 def set_points_by_ends(
2734 self,
2735 start: Point3DLike | Mobject,
2736 end: Point3DLike | Mobject,
2737 buff: float = 0,
2738 path_arc: float = 0,
2739 ) -> Self:
2740 """Rebuild the line between two ends, straight or bent.
2742 Its tips, if it has any, stay where they are.
2744 Args:
2745 start: Where it starts: a point, or a mobject (see [Line][manimgx.Line]).
2746 end: Where it ends: a point, or a mobject.
2747 buff: How far it stops short of each end, in scene units.
2748 path_arc: 0 for straight; otherwise the line is bent through its own
2749 `path_arc` (see [set_path_arc][manimgx.Line.set_path_arc]).
2750 """
2751 self._set_start_and_end_attrs(start, end)
2752 if path_arc:
2753 arc = ArcBetweenPoints(self.start, self.end, angle=self.path_arc)
2754 self.set_points(arc.points)
2755 else:
2756 self._geometry = segment(self.start, self.end)
2757 self._account_for_buff(buff)
2758 return self
2760 def _account_for_buff(self, buff: float) -> None:
2761 if buff <= 0:
2762 return
2763 length = self.get_length() if self.path_arc == 0 else self.get_arc_length()
2764 if length < 2 * buff:
2765 return
2766 if self.path_arc == 0: # straight: the segment between the ends brought in
2767 start, end = self.get_start_and_end()
2768 inward = (end - start) * (buff / length)
2769 self._geometry = segment(start + inward, end - inward)
2770 return
2771 buff_proportion = buff / length
2772 self.pointwise_become_partial(self, buff_proportion, 1 - buff_proportion)
2774 def _set_start_and_end_attrs(
2775 self, start: Point3DLike | Mobject, end: Point3DLike | Mobject
2776 ) -> None:
2777 rough_start = self._pointify(start)
2778 rough_end = self._pointify(end)
2779 vect = normalize(rough_end - rough_start)
2780 self.start = self._pointify(start, vect)
2781 self.end = self._pointify(end, -vect)
2783 def _pointify(
2784 self, mob_or_point: Mobject | Point3DLike, direction: Vector3DLike | None = None
2785 ) -> Point3D:
2786 if isinstance(mob_or_point, Mobject):
2787 mob = mob_or_point
2788 if direction is None:
2789 return mob.get_center()
2790 else:
2791 return mob.get_boundary_point(direction)
2792 return np.array(mob_or_point)
2794 def set_path_arc(self, new_value: float) -> Self:
2795 """Bend the line through a new angle: rebuild it, straight or as an arc, between
2796 the ends it was made with.
2798 It is rebuilt where it was made (or last rebuilt), wherever it has moved since,
2799 and keeps its buffer.
2801 Args:
2802 new_value: The angle, in radians: 0 for straight; otherwise an arc, turning
2803 counterclockwise if positive.
2804 """
2805 self.path_arc = new_value
2806 self.init_points()
2807 return self
2809 def put_start_and_end_on(self, start: Point3DLike, end: Point3DLike) -> Self:
2810 """Move, turn and scale the line so it runs from `start` to `end`, tips
2811 included; its shape stays, scaled in proportion (an arrow's tips keep their
2812 size).
2814 A line whose ends coincide is rebuilt between the new ends.
2816 Args:
2817 start: Where its start goes: its start tip's point, if it has one.
2818 end: Where its end goes: its end tip's point, if it has one.
2820 Examples:
2821 ```python
2822 import manimgx as m
2825 class LinePutStartAndEndOnExample(m.Scene):
2826 def construct(self) -> None:
2827 a, b, c = [-4, -2, 0], [0, 2.5, 0], [4, -2, 0]
2828 dots = m.VGroup(*(m.Dot(p, radius=0.12) for p in (a, b, c)))
2829 line = m.Line(a, b, color=m.BLUE)
2830 self.add(dots, line)
2831 self.play(line.animate.put_start_and_end_on(b, c))
2832 self.play(line.animate.put_start_and_end_on(c, a))
2833 ```
2834 """
2835 curr_start, curr_end = self.get_start_and_end()
2836 if np.all(curr_start == curr_end):
2837 self.start = np.asarray(start)
2838 self.end = np.asarray(end)
2839 self.generate_points()
2840 return super().put_start_and_end_on(start, end)
2842 def get_vector(self) -> Vector3D:
2843 """The vector from the line's start to its end, tips included.
2845 Returns:
2846 The vector, in scene units.
2847 """
2848 return self.get_end() - self.get_start()
2850 def get_unit_vector(self) -> Vector3D:
2851 """The line's direction: the unit vector from its start toward its end.
2853 Returns:
2854 A vector of length 1; zero for a line of no length.
2855 """
2856 return normalize(self.get_vector())
2858 def get_angle(self) -> float:
2859 """The line's angle: the direction from its start to its end, counterclockwise
2860 from the positive x-axis.
2862 Returns:
2863 The angle, in radians, from -PI to PI.
2864 """
2865 return angle_of_vector(self.get_vector())
2867 def get_projection(self, point: Point3DLike) -> Point3D:
2868 """The point of the line nearest a point: the point's orthogonal projection onto
2869 the line, extended past its ends.
2871 Args:
2872 point: The point to project.
2874 Returns:
2875 The point on the line, in scene coordinates.
2876 """
2877 start = self.get_start()
2878 end = self.get_end()
2879 unit_vect = normalize(end - start)
2880 return start + float(np.dot(point - start, unit_vect)) * unit_vect
2882 def get_slope(self) -> float:
2883 """The line's slope: how far it rises for each unit it runs to the right, the
2884 tangent of its [angle][manimgx.Line.get_angle].
2886 Returns:
2887 The slope; very large for a line nearly upright.
2888 """
2889 return float(np.tan(self.get_angle()))
2891 def set_angle(self, angle: float, about_point: Point3DLike | None = None) -> Self:
2892 """Turn the line so its [angle][manimgx.Line.get_angle] is `angle`: about its
2893 start, unless given another point.
2895 Args:
2896 angle: The new angle, in radians, counterclockwise from the positive x-axis.
2897 about_point: The point it turns about; None for its start.
2898 """
2899 if about_point is None:
2900 about_point = self.get_start()
2901 self.rotate(angle - self.get_angle(), about_point=about_point)
2902 return self
2904 def set_length(self, length: float) -> Self:
2905 """Scale the line about its center to a length, tips included (an arrow's tips
2906 keep their size).
2908 Args:
2909 length: The new length, from its start to its end, in scene units.
2911 Examples:
2912 ```python
2913 import manimgx as m
2916 class LineSetLengthExample(m.Scene):
2917 def construct(self) -> None:
2918 line = m.Line(m.LEFT, m.RIGHT, color=m.BLUE).shift(m.UP)
2919 arrow = m.Arrow(m.LEFT, m.RIGHT, color=m.YELLOW).shift(m.DOWN)
2920 self.add(line, arrow)
2921 self.play(line.animate.set_length(10), arrow.animate.set_length(10))
2922 self.play(line.animate.set_length(4), arrow.animate.set_length(4))
2923 ```
2924 """
2925 scale_factor: float = length / self.get_length()
2926 return self.scale(scale_factor)
2929class CurvesAsSubmobjects(VGroup[VMobject]):
2930 """A path split into its curves: a group of one path per curve, each styled as the
2931 path is.
2933 Each part can then be styled or animated on its own: a gradient across the parts
2934 colors the path along its length. Only the path's own curves are taken, not its
2935 submobjects'.
2937 Args:
2938 vmobject: The path to split.
2939 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself: as it
2940 has no points, they do not restyle its parts, which take the path's style.
2942 Examples:
2943 ```python
2944 import numpy as np
2946 import manimgx as m
2949 class CurvesAsSubmobjectsExample(m.Scene):
2950 def construct(self) -> None:
2951 curve = m.ParametricFunction(
2952 lambda t: [2 * t, 2 * np.sin(t), 0], t_range=(-3, 3, 0.1)
2953 )
2954 parts = m.CurvesAsSubmobjects(curve.set_stroke(width=12))
2955 parts.set_color_by_gradient(m.BLUE, m.YELLOW, m.RED)
2956 self.play(m.Create(parts, run_time=2))
2957 ```
2958 """
2960 def __init__(self, vmobject: VMobject, **kwargs: Unpack[Style]) -> None:
2961 super().__init__(**kwargs)
2962 for tup in vmobject.get_cubic_bezier_tuples():
2963 part = VMobject()
2964 part.set_points(tup)
2965 part.match_style(vmobject)
2966 self.add(part)
2969def dash_pattern(
2970 n: int, ratio: float, offset: float, closed: bool
2971) -> tuple[float, float, float]:
2972 """CE's dashes as a periodic window over the path (period, duty, phase — fractions of it): an
2973 open path starts and ends with a dash; a closed one repeats every 1/n."""
2974 dash = ratio / n
2975 void = (
2976 (1 - ratio) / n if closed else (1 - ratio if n == 1 else (1 - ratio) / (n - 1))
2977 )
2978 period = dash + void
2979 return period, dash / period, offset % 1 * period
2982def _even(vmobject: VMobject) -> bool:
2983 """Whether a path's curves are all one length (so its parameter measures its length: a
2984 dash window over it has equal dashes)."""
2985 lengths = vmobject._geometry.curve_lengths()
2986 return len(lengths) > 0 and float(np.ptp(lengths)) <= 1e-3 * float(lengths.max())
2989class DashedVMobject(VMobject):
2990 """A path drawn in dashes: evenly spaced dashes along another path, in its style.
2992 An open path starts and ends with a dash; a closed one has as many gaps as dashes,
2993 all the way around. Each dash ends as the path's `cap_style` says, and an arrow's
2994 tips are drawn whole.
2996 Args:
2997 vmobject: The path to draw in dashes.
2998 num_dashes: How many dashes; 0 draws none.
2999 dashed_ratio: The fraction of the path the dashes cover, from 0 to 1; the gaps
3000 take the rest.
3001 dash_offset: How far the dashes are moved along the path, toward its end, as a
3002 fraction of a dash and the gap after it.
3003 equal_lengths: Whether the dashes are equally long; if False they are equal
3004 stretches of the path's parameter, longer where the path runs faster.
3005 **kwargs: [Style keywords][manimgx.drawing.paint.Style]; the dashes take the path's
3006 paint over them.
3008 Examples:
3009 ```python
3010 import manimgx as m
3013 class DashedVMobjectExample(m.Scene):
3014 def construct(self) -> None:
3015 circle = m.Circle(radius=1.5, color=m.BLUE, stroke_width=6)
3016 square = m.Square(side_length=3, color=m.GREEN, stroke_width=6)
3017 arc = m.Arc(radius=2, angle=m.PI, color=m.YELLOW, stroke_width=6)
3018 shapes = m.VGroup(
3019 m.DashedVMobject(circle, num_dashes=12),
3020 m.DashedVMobject(square, num_dashes=16, dashed_ratio=0.7),
3021 m.DashedVMobject(arc, num_dashes=7, dashed_ratio=0.3),
3022 ).arrange(buff=1)
3023 self.play(m.Create(shapes, run_time=2))
3024 ```
3025 """
3027 defaults: ClassVar[Style] = {"color": WHITE}
3029 def __init__(
3030 self,
3031 vmobject: VMobject,
3032 num_dashes: int = 15,
3033 dashed_ratio: float = 0.5,
3034 dash_offset: float = 0,
3035 equal_lengths: bool = True,
3036 **kwargs: Unpack[Style],
3037 ) -> None:
3038 self.dashed_ratio = dashed_ratio
3039 self.num_dashes = num_dashes
3040 super().__init__(**kwargs)
3041 base = vmobject
3043 tips = base.get_tips().submobjects if isinstance(base, TipableVMobject) else []
3044 whole = all(any(m is t for t in tips) for m in base.submobjects)
3045 # the path itself, drawn in dashes (a window over it; its tips drawn whole)
3046 if (
3047 num_dashes > 0
3048 and whole
3049 and base.has_points()
3050 and (not equal_lengths or _even(base))
3051 ):
3052 self._geometry = base._geometry
3053 self.match_style(base, family=False)
3054 self.paint = self.paint.but(
3055 dash=dash_pattern(
3056 num_dashes, dashed_ratio, dash_offset, base.is_closed()
3057 )
3058 )
3059 self.add(*(tip.copy() for tip in tips))
3060 return
3061 vmobject = base.copy()
3063 tips = vmobject.pop_tips() if isinstance(vmobject, TipableVMobject) else None
3064 r, n = dashed_ratio, num_dashes
3065 if n > 0:
3066 closed = vmobject.is_closed()
3067 dash_len = r / n
3068 void_len = (
3069 (1 - r) / n if closed else (1 - r if n == 1 else (1 - r) / (n - 1))
3070 )
3071 period = dash_len + void_len
3072 phase = dash_offset % 1 * period
3073 pattern_len = 1 if closed else 1 + void_len
3074 starts = [(i * period + phase) % pattern_len for i in range(n)]
3075 ends = [(i * period + dash_len + phase) % pattern_len for i in range(n)]
3076 if not closed:
3077 if ends[-1] > 1 and starts[-1] > 1:
3078 ends.pop()
3079 starts.pop()
3080 elif ends[-1] < dash_len:
3081 if starts[-1] < 1:
3082 starts.append(0)
3083 ends.append(ends[-1])
3084 ends[-2] = 1
3085 else:
3086 starts[-1] = 0
3087 elif starts[-1] > 1 - dash_len:
3088 ends[-1] = 1
3089 if equal_lengths:
3090 lengths = np.cumsum(
3091 np.r_[0.0, vmobject._geometry.piece_lengths().ravel()]
3092 )
3093 refs = np.linspace(0, 1, lengths.size)
3094 total = lengths[-1]
3095 self.add(
3096 *(
3097 vmobject.get_subcurve(
3098 np.interp(s * total, lengths, refs),
3099 np.interp(e * total, lengths, refs),
3100 )
3101 for s, e in zip(starts, ends, strict=True)
3102 )
3103 )
3104 else:
3105 self.add(
3106 *(
3107 vmobject.get_subcurve(s, e)
3108 for s, e in zip(starts, ends, strict=True)
3109 )
3110 )
3111 self.match_style(base, family=False)
3112 if tips is not None and tips.submobjects:
3113 self.add(*tips.submobjects)
3116class DashedLine(Line):
3117 """A line drawn in dashes, white unless styled.
3119 The dashes are the line's stroke drawn in pieces: a whole number of them, at least
3120 two, spread evenly from end to end, each about `dash_length` long, each ended as
3121 the line's `cap_style` says. It stays one path, placed, bent and tipped as a
3122 [Line][manimgx.Line] is, and starts and ends where the line does; its handles are
3123 its dashes', the first dash's and the last's. Its dashes are counted when it is
3124 made, and scale with it.
3126 Args:
3127 start: Where the line starts: a point, or a mobject (see [Line][manimgx.Line]).
3128 end: Where it ends: a point, or a mobject.
3129 buff: How far it stops short of each end, in scene units.
3130 path_arc: The angle it bends through, in radians: 0 for straight.
3131 dash_length: The length of each dash, in scene units (default 0.05): about it,
3132 as a whole number of dashes spans the line.
3133 dashed_ratio: The fraction of the line the dashes cover, from 0 to 1; the rest
3134 is gaps.
3136 Examples:
3137 ```python
3138 import manimgx as m
3141 class DashedLineExample(m.Scene):
3142 def construct(self) -> None:
3143 start, end = 5 * m.LEFT, 5 * m.RIGHT
3144 lines = m.VGroup(
3145 m.DashedLine(start, end),
3146 m.DashedLine(start, end, dash_length=0.4, color=m.BLUE),
3147 m.DashedLine(start, end, dash_length=0.4, dashed_ratio=0.2),
3148 m.DashedLine(start, end, path_arc=m.PI / 4, color=m.YELLOW),
3149 ).arrange(m.DOWN, buff=1)
3150 lines[2].set_color(m.GREEN)
3151 self.add(lines)
3152 ```
3153 """
3155 def __init__(
3156 self,
3157 start: Point3DLike | Mobject = LEFT,
3158 end: Point3DLike | Mobject = RIGHT,
3159 buff: float = 0,
3160 path_arc: float = 0,
3161 *,
3162 dash_length: float = DEFAULT_DASH_LENGTH,
3163 dashed_ratio: float = 0.5,
3164 **kwargs: Unpack[Tipped],
3165 ) -> None:
3166 self.dash_length = dash_length
3167 self.dashed_ratio = dashed_ratio
3168 super().__init__(start, end, buff, path_arc, **kwargs)
3169 self.paint = self.paint.but( # a line drawn in dashes: one path, a dash window
3170 dash=dash_pattern(self._calculate_num_dashes(), dashed_ratio, 0, False)
3171 )
3173 def _calculate_num_dashes(self) -> int:
3174 return max(
3175 2, int(np.ceil(self.get_length() / self.dash_length * self.dashed_ratio))
3176 )
3178 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3179 def get_first_handle(self) -> Point3D:
3180 """The line's first handle: its first dash's, the control point after the
3181 line's start toward which that dash leaves it (a third of the way into the
3182 dash, on a straight line).
3184 Returns:
3185 The point, in scene coordinates.
3186 """
3187 start, handle = self.points[:2]
3188 return start + self._dash_cut() * (handle - start)
3190 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3191 def get_last_handle(self) -> Point3D:
3192 """The line's last handle: its last dash's, the control point before the
3193 line's end from which that dash comes into it (a third of the way back into
3194 the dash, on a straight line).
3196 Returns:
3197 The point, in scene coordinates.
3198 """
3199 handle, end = self.points[-2:]
3200 return end + self._dash_cut() * (handle - end)
3202 def _dash_cut(self) -> float:
3203 """How far into the curve at each end of the line the dash there reaches, in
3204 that curve's parameter from the end: the dash is the curve cut there, which
3205 keeps the end and brings its handle in by as much (de Casteljau). The first
3206 dash starts the line and the last ends it, each period × duty of its parameter;
3207 drawn solid, the line is one piece, each end curve whole."""
3208 if self.paint.dash is None:
3209 return 1.0
3210 period, duty, _ = self.paint.dash
3211 return min(1.0, period * duty * self.get_num_curves())
3214class TangentLine(Line):
3215 """A line tangent to a path at a point along it, `length` long and centered on the
3216 point; white unless styled.
3218 Its direction is that of the chord between the points `d_alpha` before and after
3219 the point.
3221 Args:
3222 vmob: The path.
3223 alpha: Where along the path, as a proportion of its length: 0 at its start, 1
3224 at its end.
3225 length: The line's length, in scene units.
3226 d_alpha: The proportion of the path's length before and after the point whose
3227 chord sets the direction.
3229 Examples:
3230 ```python
3231 import manimgx as m
3234 class TangentLineExample(m.Scene):
3235 def construct(self) -> None:
3236 circle = m.Circle(radius=2.5, color=m.BLUE)
3237 self.add(circle)
3238 for alpha in (0, 0.2, 0.45, 0.7):
3239 self.add(m.TangentLine(circle, alpha, length=4, color=m.YELLOW))
3240 self.add(m.Dot(circle.point_from_proportion(alpha)))
3241 ```
3242 """
3244 def __init__(
3245 self,
3246 vmob: VMobject,
3247 alpha: float,
3248 length: float = 1,
3249 d_alpha: float = 1e-06,
3250 **kwargs: Unpack[LineOptions],
3251 ) -> None:
3252 self.length = length
3253 self.d_alpha = d_alpha
3254 da = self.d_alpha
3255 a1 = np.clip(alpha - da, 0, 1)
3256 a2 = np.clip(alpha + da, 0, 1)
3257 super().__init__(
3258 vmob.point_from_proportion(a1), vmob.point_from_proportion(a2), **kwargs
3259 )
3260 self.scale(self.length / self.get_length())
3263class Elbow(VMobject):
3264 """The mark of a right angle: two segments `width` long meeting at a square corner;
3265 white unless styled.
3267 Made at the origin, it marks the right angle between the positive x and y axes:
3268 from (0, `width`) across to its corner at (`width`, `width`), and down to
3269 (`width`, 0); `angle` turns it about the origin. To mark the angle between two
3270 lines, see [RightAngle][manimgx.RightAngle].
3272 Args:
3273 width: The length of each segment, in scene units.
3274 angle: The angle it is turned through about the origin, in radians,
3275 counterclockwise.
3277 Examples:
3278 ```python
3279 import manimgx as m
3282 class ElbowExample(m.Scene):
3283 def construct(self) -> None:
3284 elbows = m.VGroup(
3285 m.Elbow(),
3286 m.Elbow(width=1.5, color=m.BLUE),
3287 m.Elbow(width=2, angle=5 * m.PI / 4, color=m.YELLOW),
3288 ).arrange(buff=1.5)
3289 self.add(elbows)
3290 ```
3291 """
3293 def __init__(
3294 self, width: float = 0.2, angle: float = 0, **kwargs: Unpack[Style]
3295 ) -> None:
3296 self.angle = angle
3297 super().__init__(**kwargs)
3298 self.set_points_as_corners(np.array([UP, UP + RIGHT, RIGHT]))
3299 self.scale_to_fit_width(width, about_point=ORIGIN)
3300 self.rotate(self.angle, about_point=ORIGIN)
3303class Arrow(Line):
3304 """An arrow: a line with a tip at its end, stopping `buff` short of the two points
3305 it joins; white, with a stroke 6 wide, unless styled.
3307 A short arrow is drawn in proportion: its tip is at most
3308 `max_tip_length_to_length_ratio` of its length, and its stroke at most
3309 `max_stroke_width_to_length_ratio` wide per unit of its length. Scaled, it keeps
3310 its tip's size (see [scale][manimgx.Arrow.scale]).
3312 Args:
3313 start: Where the arrow starts: a point, or a mobject (see [Line][manimgx.Line]).
3314 end: Where it points to: a point, or a mobject.
3315 buff: How far it stops short of each end, in scene units (default 0.25): an
3316 arrow between two mobjects leaves a gap at each.
3317 max_tip_length_to_length_ratio: The longest its tip may be, as a fraction of
3318 its length.
3319 max_stroke_width_to_length_ratio: The widest its stroke may be, in hundredths
3320 of a scene unit, per scene unit of its length.
3321 tip_shape: The class of its tip.
3322 **kwargs: [Style, tip and bend keywords][manimgx.mobjects.shapes.Arced]:
3323 its `path_arc` bends it.
3325 Examples:
3326 ```python
3327 import manimgx as m
3330 class ArrowExample(m.Scene):
3331 def construct(self) -> None:
3332 a, b = 2.5 * m.LEFT, 2.5 * m.RIGHT
3333 arrows = m.VGroup(
3334 m.Arrow(a, b),
3335 m.Arrow(a, b, buff=0, color=m.BLUE),
3336 m.Arrow(a, b, path_arc=-m.PI / 3, color=m.GREEN),
3337 m.Arrow(a, b, tip_shape=m.StealthTip, color=m.YELLOW),
3338 ).arrange(m.DOWN, buff=0.8, aligned_edge=m.LEFT)
3339 shorts = m.VGroup()
3340 for length in (0.5, 1, 2, 4, 6):
3341 shorts.add(m.Arrow(m.ORIGIN, length * m.UP, buff=0, color=m.RED))
3342 shorts.arrange(aligned_edge=m.DOWN)
3343 self.add(m.VGroup(arrows, shorts).arrange(buff=1.5))
3344 ```
3345 """
3347 defaults: ClassVar[Style] = {"stroke_width": 6}
3349 def __init__(
3350 self,
3351 start: Point3DLike | Mobject = LEFT,
3352 end: Point3DLike | Mobject = RIGHT,
3353 *,
3354 buff: float = MED_SMALL_BUFF,
3355 max_tip_length_to_length_ratio: float = 0.25,
3356 max_stroke_width_to_length_ratio: float = 5,
3357 tip_shape: type[ArrowTip] = ArrowTriangleFilledTip,
3358 **kwargs: Unpack[Arced],
3359 ) -> None:
3360 self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio
3361 self.max_stroke_width_to_length_ratio = max_stroke_width_to_length_ratio
3362 super().__init__(start, end, buff=buff, **kwargs)
3363 self.initial_stroke_width = self.stroke_width
3364 self.add_tip(tip_shape=tip_shape)
3365 self._set_stroke_width_from_length()
3367 def scale(
3368 self,
3369 scale_factor: float | Vector3DLike,
3370 scale_stroke: bool = False,
3371 scale_tips: bool = False,
3372 **kwargs: Unpack[Pivot],
3373 ) -> Self:
3374 """Scale the arrow, keeping its tips' size unless `scale_tips`.
3376 The shaft is scaled, and the tips are put back on its ends. Then the shaft's
3377 stroke width is set from its new length, as when the arrow was made: the smaller
3378 of the width it was made with and `max_stroke_width_to_length_ratio` times its
3379 length. An arrow of no length stays as it is.
3381 Args:
3382 scale_factor: The factor: one, or one per axis (see
3383 [Mobject.scale][manimgx.Mobject.scale]).
3384 scale_stroke: Whether stroke widths scale too; the shaft's is then set from
3385 its length all the same.
3386 scale_tips: Whether the tips scale with the shaft.
3387 **kwargs: [Pivot keywords][manimgx.mobject.Pivot]: the point that stays
3388 fixed (default: its center).
3390 Examples:
3391 ```python
3392 import manimgx as m
3395 class ArrowScaleExample(m.Scene):
3396 def construct(self) -> None:
3397 kept = m.Arrow(m.LEFT, m.RIGHT, color=m.BLUE).shift(1.5 * m.UP)
3398 scaled = m.Arrow(m.LEFT, m.RIGHT, color=m.YELLOW).shift(m.DOWN)
3399 top = m.Text("scale(3)").move_to(2.8 * m.UP)
3400 bottom = m.Text("scale(3, scale_tips=True)").move_to(2.5 * m.DOWN)
3401 self.add(top, bottom, kept, scaled)
3402 self.play(
3403 kept.animate.scale(3), scaled.animate.scale(3, scale_tips=True)
3404 )
3405 ```
3406 """
3407 if self.get_length() == 0:
3408 return self
3409 if scale_tips:
3410 super().scale(scale_factor, scale_stroke, **kwargs)
3411 self._set_stroke_width_from_length()
3412 return self
3413 has_tip = self.has_tip()
3414 order = list(self.submobjects) # the tips come back to their places among them
3415 old_tips = self.pop_tips()
3416 super().scale(scale_factor, scale_stroke, **kwargs)
3417 self._set_stroke_width_from_length()
3418 for tip, at_start in zip(
3419 old_tips, (False, True) if has_tip else (True,), strict=False
3420 ):
3421 self.add_tip(tip=tip, at_start=at_start)
3422 place = {id(m): i for i, m in enumerate(order)}
3423 self.submobjects.sort(key=lambda m: place.get(id(m), len(order)))
3424 return self
3426 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3427 def get_normal_vector(self) -> Vector3D:
3428 """The normal of the plane the arrow's tip lies in, from its first three
3429 anchors.
3431 Returns:
3432 A unit vector: IN for an arrow in the plane of the screen.
3433 """
3434 p0, p1, p2 = self.tip.get_start_anchors()[:3]
3435 return normalize(np.cross(p2 - p1, p1 - p0))
3437 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3438 def reset_normal_vector(self) -> Self:
3439 """Set the arrow's `normal_vector` to its
3440 [tip's normal][manimgx.Arrow.get_normal_vector].
3442 Kept for Manim compatibility: nothing reads `normal_vector`.
3443 """
3444 self.normal_vector = self.get_normal_vector()
3445 return self
3447 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3448 def get_default_tip_length(self) -> float:
3449 """The length of the tips the arrow makes unless given one: its `tip_length`,
3450 or `max_tip_length_to_length_ratio` times its length if that is shorter.
3452 Returns:
3453 The length, in scene units.
3454 """
3455 max_ratio = self.max_tip_length_to_length_ratio
3456 return min(self.tip_length, max_ratio * self.get_length())
3458 def _set_stroke_width_from_length(self) -> Self:
3459 max_ratio = self.max_stroke_width_to_length_ratio
3460 self.set_stroke(
3461 width=min(self.initial_stroke_width, max_ratio * self.get_length()),
3462 family=False,
3463 )
3464 return self
3467class Vector(Arrow):
3468 """A vector: an arrow from the origin to a point; white unless styled.
3470 Args:
3471 direction: Where it points to, from the origin: two coordinates, or three.
3472 buff: How far it stops short of the origin and of its end, in scene units.
3474 Examples:
3475 ```python
3476 import manimgx as m
3479 class VectorExample(m.Scene):
3480 def construct(self) -> None:
3481 vectors = m.VGroup(
3482 m.Vector([2, 1], color=m.YELLOW),
3483 m.Vector([-3, 2], color=m.BLUE),
3484 m.Vector([1, -3, 0], color=m.GREEN),
3485 )
3486 self.add(m.NumberPlane(), vectors)
3487 ```
3488 """
3490 def __init__(
3491 self,
3492 direction: Vector2DLike | Vector3DLike = RIGHT,
3493 buff: float = 0,
3494 **kwargs: Unpack[ArrowTips],
3495 ) -> None:
3496 self.buff = buff
3497 end = np.asarray(direction, dtype=float)
3498 if len(end) == 2:
3499 end = np.hstack([end, 0])
3500 super().__init__(ORIGIN, end, buff=buff, **kwargs)
3502 def coordinate_label(
3503 self,
3504 integer_labels: bool = True,
3505 n_dim: int = 2,
3506 **kwargs: Unpack[MatrixOptions],
3507 ) -> Matrix:
3508 """Make a label of the vector's coordinates: a column matrix beside its tip.
3510 The label, at 0.8 of a matrix's size, is placed 0.25 beyond the vector's end,
3511 centered on it vertically: to its right if the vector points right (or straight
3512 up or down), to its left otherwise. It is not added to the vector.
3514 Args:
3515 integer_labels: Whether to round the coordinates to integers.
3516 n_dim: How many coordinates to show: 2 for x and y, 3 for z too.
3517 **kwargs: [Matrix keywords][manimgx.mobjects.grid.MatrixOptions]; `color`
3518 colors the whole label.
3520 Returns:
3521 A new matrix.
3523 Examples:
3524 ```python
3525 import manimgx as m
3528 class VectorCoordinateLabelExample(m.Scene):
3529 def construct(self) -> None:
3530 right = m.Vector([3, 2], color=m.YELLOW)
3531 left = m.Vector([-4, -2], color=m.BLUE)
3532 self.add(m.NumberPlane(), right, left)
3533 self.add(right.coordinate_label())
3534 self.add(left.coordinate_label(color=m.BLUE))
3535 ```
3536 """
3537 from manimgx.mobjects.grid import Matrix
3539 vect = np.array(self.get_end())
3540 if integer_labels:
3541 vect = np.round(vect).astype(int)
3542 vect = vect[:n_dim]
3543 vect = vect.reshape((n_dim, 1))
3544 color = kwargs.pop("color", None)
3545 label = Matrix(vect, **kwargs)
3546 label.scale(LARGE_BUFF - 0.2)
3547 shift_dir = np.array(self.get_end())
3548 if shift_dir[0] >= 0:
3549 shift_dir -= label.get_left() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * LEFT
3550 else:
3551 shift_dir -= label.get_right() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * RIGHT
3552 label.shift(shift_dir)
3553 if color is not None:
3554 label.set_color(color)
3555 return label
3558class DoubleArrow(Arrow):
3559 """An arrow with a tip at each end; white, with a stroke 6 wide, unless styled.
3561 Its tips and its stroke are sized from its length, tip to tip, as an
3562 [Arrow][manimgx.Arrow]'s are.
3564 Args:
3565 start: Where it starts: a point, or a mobject (see [Line][manimgx.Line]).
3566 end: Where it ends: a point, or a mobject.
3567 tip_shape_start: The class of the tip at its start.
3568 tip_shape_end: The class of the tip at its end; None for the `tip_shape`
3569 keyword's, or else [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
3571 Examples:
3572 ```python
3573 import manimgx as m
3576 class DoubleArrowExample(m.Scene):
3577 def construct(self) -> None:
3578 circle = m.Circle(radius=2, color=m.BLUE).shift(3 * m.LEFT)
3579 diameter = m.DoubleArrow(circle.get_left(), circle.get_right(), buff=0)
3580 mixed = m.DoubleArrow(
3581 m.RIGHT,
3582 6 * m.RIGHT,
3583 tip_shape_start=m.ArrowCircleFilledTip,
3584 tip_shape_end=m.StealthTip,
3585 color=m.YELLOW,
3586 )
3587 self.add(circle, diameter, mixed)
3588 ```
3589 """
3591 def __init__(
3592 self,
3593 start: Point3DLike | Mobject = LEFT,
3594 end: Point3DLike | Mobject = RIGHT,
3595 *,
3596 tip_shape_start: type[ArrowTip] = ArrowTriangleFilledTip,
3597 tip_shape_end: type[ArrowTip] | None = None,
3598 **kwargs: Unpack[ArrowOptions],
3599 ) -> None:
3600 if tip_shape_end is not None:
3601 kwargs["tip_shape"] = tip_shape_end
3602 super().__init__(start, end, **kwargs)
3603 self.add_tip(at_start=True, tip_shape=tip_shape_start)
3604 self._set_stroke_width_from_length() # as an arrow's: by its length, tip to tip
3607class _AngleShape(_Style, total=False):
3608 """AngleShape's keys, open, for the keywords that add to them."""
3610 quadrant: AngleQuadrant
3611 """Which way each side of the angle goes from the crossing: a sign for each line,
3612 the first line's first; 1 along the line's direction (from its start toward its
3613 end), -1 back toward its start (default (1, 1))."""
3614 other_angle: bool
3615 """Whether the arc runs clockwise from the first side to the second, instead of
3616 counterclockwise: it then marks the rest of the full turn (default False)."""
3617 dot: bool
3618 """Whether to put a dot inside the arc, as a right angle is sometimes marked
3619 (default False; an elbow has none)."""
3620 dot_radius: float | None
3621 """The dot's radius, in scene units (default None: a tenth of the arc's radius)."""
3622 dot_distance: float
3623 """How far the dot is from the crossing, as a fraction of the arc's radius (default
3624 0.55)."""
3625 dot_color: ParsableManimColor
3626 """The dot's color (default white)."""
3629class AngleShape(_AngleShape, total=False, closed=True):
3630 """An [Angle][manimgx.Angle]'s keywords but its radius and its elbow (for right
3631 angles, which set them): which angle it marks, and its dot, with the style
3632 keywords."""
3635class AngleOptions(_AngleShape, total=False, closed=True):
3636 """An [Angle][manimgx.Angle]'s keywords but its lines (for the methods that make
3637 one)."""
3639 radius: float | None
3640 """The arc's radius, or the elbow's side, in scene units (default None: 0.4, or
3641 for short lines two thirds of the distance from the crossing to the nearer of the
3642 line ends the sides point to, when that is less than 0.6)."""
3643 elbow: bool
3644 """Whether to mark the angle with an elbow, two segments making a corner between
3645 its sides, instead of an arc (default False)."""
3648class Angle(VMobject):
3649 """The mark of an angle between two lines: an arc about the point where they cross,
3650 counterclockwise from a side along the first line to a side along the second; white
3651 unless styled.
3653 The lines are taken as infinite, so they need not reach the point where they cross.
3654 From there, `quadrant` picks the way each side goes along its line, and
3655 `other_angle` turns the arc clockwise instead, marking the rest of the full turn:
3656 together they pick the angle marked, which may be more than half a turn. With
3657 `elbow`, the mark is two segments instead, making a corner between the two sides,
3658 as a right angle is marked. Parallel lines in the plane of the screen make an empty
3659 mark, of value 0.
3661 Args:
3662 line1: The line the angle is measured from.
3663 line2: The line it is measured to.
3664 radius: The arc's radius, or the elbow's side, in scene units; None for 0.4, or
3665 for short lines two thirds of the distance from the crossing to the nearer
3666 of the line ends the sides point to, when that is less than 0.6.
3667 quadrant: Which way each side goes from the crossing: a sign for each line,
3668 `line1`'s first; 1 along the line's direction (from its start toward its
3669 end), -1 back toward its start.
3670 other_angle: Whether the arc runs clockwise from the first side to the second
3671 instead, marking the rest of the full turn.
3672 dot: Whether to put a dot inside the arc (an elbow has none).
3673 dot_radius: The dot's radius, in scene units; None for a tenth of the arc's
3674 radius.
3675 dot_distance: How far the dot is from the crossing, as a fraction of the arc's
3676 radius.
3677 dot_color: The dot's color.
3678 elbow: Whether to mark the angle with an elbow instead of an arc.
3680 Examples:
3681 ```python
3682 import manimgx as m
3685 class AngleExample(m.Scene):
3686 def construct(self) -> None:
3687 line1 = m.Line(1.2 * m.LEFT, 1.2 * m.RIGHT)
3688 line2 = m.Line(1.2 * m.DOWN, 1.2 * m.UP).rotate(-30 * m.DEGREES)
3689 angles = [
3690 m.Angle(line1, line2, color=m.YELLOW),
3691 m.Angle(line1, line2, quadrant=(-1, 1), color=m.BLUE),
3692 m.Angle(line1, line2, other_angle=True, color=m.GREEN),
3693 m.Angle(line1, line2, dot=True, color=m.RED),
3694 ]
3695 labels = ["default", "quadrant=(-1, 1)", "other_angle=True", "dot=True"]
3696 panels = m.VGroup()
3697 for angle in angles:
3698 panels.add(m.VGroup(line1.copy(), line2.copy(), angle))
3699 panels.arrange(buff=1)
3700 for panel, label in zip(panels, labels):
3701 text = m.Text(label, font_size=24).next_to(panel, m.DOWN)
3702 self.add(panel, text)
3703 ```
3704 """
3706 def __init__(
3707 self,
3708 line1: Line,
3709 line2: Line,
3710 radius: float | None = None,
3711 quadrant: AngleQuadrant = (1, 1),
3712 other_angle: bool = False,
3713 dot: bool = False,
3714 dot_radius: float | None = None,
3715 dot_distance: float = 0.55,
3716 dot_color: ParsableManimColor = WHITE,
3717 elbow: bool = False,
3718 **kwargs: Unpack[Style],
3719 ) -> None:
3720 super().__init__(**kwargs)
3721 self.lines = (line1, line2)
3722 self.quadrant = quadrant
3723 self.dot_distance = dot_distance
3724 self.elbow = elbow
3725 try:
3726 inter = line_intersection(
3727 [line1.get_start(), line1.get_end()],
3728 [line2.get_start(), line2.get_end()],
3729 )
3730 except ValueError:
3731 lines_are_in_xy_plane = all(
3732 point[2] == 0
3733 for line in (line1, line2)
3734 for point in (line.get_start(), line.get_end())
3735 )
3736 directions_are_parallel = (
3737 np.cross(line1.get_vector(), line2.get_vector())[2] == 0
3738 )
3739 if not (lines_are_in_xy_plane and directions_are_parallel):
3740 raise
3741 self.angle_value = 0.0
3742 return
3743 if radius is None:
3744 if quadrant[0] == 1:
3745 dist_1 = np.linalg.norm(line1.get_end() - inter)
3746 else:
3747 dist_1 = np.linalg.norm(line1.get_start() - inter)
3748 if quadrant[1] == 1:
3749 dist_2 = np.linalg.norm(line2.get_end() - inter)
3750 else:
3751 dist_2 = np.linalg.norm(line2.get_start() - inter)
3752 radius = (
3753 float(2 / 3 * min(dist_1, dist_2)) if min(dist_1, dist_2) < 0.6 else 0.4
3754 )
3755 else:
3756 self.radius = radius
3757 anchor_angle_1 = inter + quadrant[0] * radius * line1.get_unit_vector()
3758 anchor_angle_2 = inter + quadrant[1] * radius * line2.get_unit_vector()
3759 if elbow:
3760 anchor_middle = (
3761 inter
3762 + quadrant[0] * radius * line1.get_unit_vector()
3763 + quadrant[1] * radius * line2.get_unit_vector()
3764 )
3765 angle_mobject: VMobject = Elbow(**kwargs)
3766 angle_mobject.set_points_as_corners(
3767 np.array([anchor_angle_1, anchor_middle, anchor_angle_2])
3768 )
3769 else:
3770 angle_1 = angle_of_vector(anchor_angle_1 - inter)
3771 angle_2 = angle_of_vector(anchor_angle_2 - inter)
3772 if not other_angle:
3773 start_angle = angle_1
3774 if angle_2 > angle_1:
3775 angle_fin = angle_2 - angle_1
3776 else:
3777 angle_fin = 2 * np.pi - (angle_1 - angle_2)
3778 else:
3779 start_angle = angle_1
3780 if angle_2 < angle_1:
3781 angle_fin = -angle_1 + angle_2
3782 else:
3783 angle_fin = -2 * np.pi + (angle_2 - angle_1)
3784 self.angle_value = angle_fin
3785 angle_mobject = Arc(
3786 radius=radius,
3787 angle=self.angle_value,
3788 start_angle=start_angle,
3789 arc_center=inter,
3790 **kwargs,
3791 )
3792 if dot:
3793 if dot_radius is None:
3794 dot_radius = radius / 10
3795 else:
3796 self.dot_radius = dot_radius
3797 right_dot = Dot(ORIGIN, radius=dot_radius, color=dot_color)
3798 dot_anchor = (
3799 inter
3800 + (angle_mobject.get_center() - inter)
3801 / np.linalg.norm(angle_mobject.get_center() - inter)
3802 * radius
3803 * dot_distance
3804 )
3805 right_dot.move_to(dot_anchor)
3806 self.add(right_dot)
3807 self.set_points(angle_mobject.points)
3809 def get_lines(self) -> VGroup:
3810 """The two lines the angle is between.
3812 Returns:
3813 A new group of the two lines, `line1` first.
3814 """
3815 return VGroup(*self.lines)
3817 def get_value(self, degrees: bool = False) -> float:
3818 """The size of the angle marked: counterclockwise from its first side to its
3819 second, or clockwise, and negative, with `other_angle`.
3821 An angle marked with an elbow has no value: asking for it raises an exception.
3823 Args:
3824 degrees: Whether to give it in degrees instead of radians.
3826 Returns:
3827 The angle, in radians (or degrees), from -TAU to TAU.
3828 """
3829 return self.angle_value / DEGREES if degrees else self.angle_value
3831 @staticmethod
3832 def from_three_points(
3833 A: Point3DLike, B: Point3DLike, C: Point3DLike, **kwargs: Unpack[AngleOptions]
3834 ) -> Angle:
3835 """The mark of the angle ABC: at `B`, from the line toward `A` counterclockwise
3836 to the line toward `C`.
3838 Args:
3839 A: A point on the first side.
3840 B: The vertex.
3841 C: A point on the second side.
3842 **kwargs: [Angle keywords][manimgx.mobjects.shapes.AngleOptions].
3844 Returns:
3845 A new angle.
3847 Examples:
3848 ```python
3849 import manimgx as m
3852 class AngleFromThreePointsExample(m.Scene):
3853 def construct(self) -> None:
3854 a, b, c = [-4, -2, 0], [3, -2, 0], [-1, 2.5, 0]
3855 angles = m.VGroup(
3856 m.Angle.from_three_points(b, a, c, radius=0.8, color=m.YELLOW),
3857 m.Angle.from_three_points(c, b, a, radius=0.8, color=m.BLUE),
3858 m.Angle.from_three_points(a, c, b, radius=0.8, color=m.GREEN),
3859 )
3860 self.add(m.Polygon(a, b, c, color=m.WHITE), angles)
3861 ```
3862 """
3863 return Angle(Line(B, A), Line(B, C), **kwargs)
3866class RightAngle(Angle):
3867 """The mark of a right angle between two lines: an [Angle][manimgx.Angle] marked
3868 with an elbow; white unless styled.
3870 The lines need not be perpendicular: the elbow is then a corner of a
3871 parallelogram.
3873 Args:
3874 line1: The first line.
3875 line2: The second line.
3876 length: The length of the elbow's sides, in scene units; None for 0.4, or less
3877 for short lines (see [Angle][manimgx.Angle]).
3878 **kwargs: [Angle keywords][manimgx.mobjects.shapes.AngleShape]; the dot
3879 keywords have no effect.
3881 Examples:
3882 ```python
3883 import manimgx as m
3886 class RightAngleExample(m.Scene):
3887 def construct(self) -> None:
3888 a, b, c = [-6, -2, 0], [-1, -2, 0], [-6, 2, 0]
3889 triangle = m.Polygon(a, b, c, color=m.BLUE)
3890 corner = m.RightAngle(m.Line(a, b), m.Line(a, c), color=m.YELLOW)
3891 line1 = m.Line([1, -2, 0], [6, 3, 0])
3892 line2 = m.Line([1, 3, 0], [6, -2, 0])
3893 marks = m.VGroup(
3894 m.RightAngle(line1, line2),
3895 m.RightAngle(line1, line2, length=0.7, quadrant=(-1, -1)),
3896 ).set_color(m.GREEN)
3897 self.add(triangle, corner, line1, line2, marks)
3898 ```
3899 """
3901 def __init__(
3902 self,
3903 line1: Line,
3904 line2: Line,
3905 length: float | None = None,
3906 **kwargs: Unpack[AngleShape],
3907 ) -> None:
3908 super().__init__(line1, line2, radius=length, elbow=True, **kwargs)
3911@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3912def adjacent_n_tuples[T](objects: Sequence[T], n: int) -> Iterator[tuple[T, ...]]:
3913 """Each run of `n` items in a row, wrapping around at the end: for `[a, b, c]` and
3914 2, `(a, b)`, `(b, c)` and `(c, a)`.
3916 Args:
3917 objects: The items.
3918 n: How many items each run has.
3920 Returns:
3921 The runs, as tuples, one starting at each item.
3922 """
3923 return zip(*(list(objects[k:]) + list(objects[:k]) for k in range(n)), strict=True)
3926@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)
3927def adjacent_pairs[T](objects: Sequence[T]) -> Iterator[tuple[T, ...]]:
3928 """Each item with the next, wrapping around at the end (see
3929 [adjacent_n_tuples][manimgx.adjacent_n_tuples]).
3931 Args:
3932 objects: The items.
3934 Returns:
3935 The pairs, as tuples, one starting at each item.
3936 """
3937 return adjacent_n_tuples(objects, 2)
3940if TYPE_CHECKING:
3941 from pathops import Path as SkiaPath
3942 from pathops import PathOp
3944 from manimgx.typing import Point3D_Array
3947def _combine(operation: PathOp, *vmobjects: VMobject) -> SkiaPath:
3948 """Fold an operation over the operands' own outlines, left to right."""
3949 paths = [_to_path(m.points, m.tolerance_for_point_equality) for m in vmobjects]
3950 return reduce(lambda a, b: _pathops().op(a, b, operation), paths)
3953class Union(VMobject):
3954 """The union of shapes: the region any of them covers, as a new path; white unless
3955 styled.
3957 It is found from the shapes' own paths (not their submobjects'), each the region
3958 its fill covers, in the plane of the screen: their z coordinates are dropped. The
3959 shapes stay as they are.
3961 Args:
3962 *vmobjects: The shapes: at least two.
3964 Examples:
3965 ```python
3966 import manimgx as m
3969 class UnionExample(m.Scene):
3970 def construct(self) -> None:
3971 square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
3972 circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
3973 circle.shift(3 * m.LEFT + m.UP)
3974 union = m.Union(square, circle, color=m.GREEN, fill_opacity=0.8)
3975 self.add(square, circle, union.shift(7 * m.RIGHT))
3976 ```
3977 """
3979 def __init__(self, *vmobjects: VMobject, **kwargs: Unpack[Style]) -> None:
3980 if len(vmobjects) < 2:
3981 raise ValueError("At least 2 mobjects needed for Union.")
3982 super().__init__(**kwargs)
3983 outpen = _pathops().Path()
3984 _pathops().union(
3985 [
3986 _to_path(vmobject.points, vmobject.tolerance_for_point_equality)
3987 for vmobject in vmobjects
3988 ],
3989 outpen.getPen(),
3990 )
3991 _append_path(self, outpen)
3994class Difference(VMobject):
3995 """The difference of two shapes: the region the first covers and the second does
3996 not, as a new path; white unless styled.
3998 It is found from the shapes' own paths (not their submobjects'), each the region
3999 its fill covers, in the plane of the screen: their z coordinates are dropped. The
4000 shapes stay as they are.
4002 Args:
4003 subject: The shape to take a part of.
4004 clip: The shape whose region is left out of it.
4006 Examples:
4007 ```python
4008 import manimgx as m
4011 class DifferenceExample(m.Scene):
4012 def construct(self) -> None:
4013 square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
4014 circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
4015 circle.shift(3 * m.LEFT + m.UP)
4016 cut = m.Difference(square, circle, color=m.GREEN, fill_opacity=0.8)
4017 self.add(square, circle, cut.shift(7 * m.RIGHT))
4018 ```
4019 """
4021 def __init__(
4022 self, subject: VMobject, clip: VMobject, **kwargs: Unpack[Style]
4023 ) -> None:
4024 super().__init__(**kwargs)
4025 _append_path(self, _combine(_pathops().PathOp.DIFFERENCE, subject, clip))
4028class Intersection(VMobject):
4029 """The intersection of shapes: the region all of them cover, as a new path; white
4030 unless styled.
4032 It is found from the shapes' own paths (not their submobjects'), each the region
4033 its fill covers, in the plane of the screen: their z coordinates are dropped. The
4034 shapes stay as they are.
4036 Args:
4037 *vmobjects: The shapes: at least two.
4039 Examples:
4040 ```python
4041 import manimgx as m
4044 class IntersectionExample(m.Scene):
4045 def construct(self) -> None:
4046 square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
4047 circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
4048 circle.shift(3 * m.LEFT + m.UP)
4049 common = m.Intersection(square, circle, color=m.GREEN, fill_opacity=0.8)
4050 self.add(square, circle, common.shift(7 * m.RIGHT))
4051 ```
4052 """
4054 def __init__(self, *vmobjects: VMobject, **kwargs: Unpack[Style]) -> None:
4055 if len(vmobjects) < 2:
4056 raise ValueError("At least 2 mobjects needed for Intersection.")
4057 super().__init__(**kwargs)
4058 _append_path(self, _combine(_pathops().PathOp.INTERSECTION, *vmobjects))
4061class Exclusion(VMobject):
4062 """The exclusive or of two shapes: the region one of them covers but not both, as a
4063 new path; white unless styled.
4065 It is found from the shapes' own paths (not their submobjects'), each the region
4066 its fill covers, in the plane of the screen: their z coordinates are dropped. The
4067 shapes stay as they are.
4069 Args:
4070 subject: The first shape.
4071 clip: The second shape.
4073 Examples:
4074 ```python
4075 import manimgx as m
4078 class ExclusionExample(m.Scene):
4079 def construct(self) -> None:
4080 square = m.Square(3, color=m.RED, fill_opacity=0.5).shift(4.5 * m.LEFT)
4081 circle = m.Circle(1.5, color=m.BLUE, fill_opacity=0.5)
4082 circle.shift(3 * m.LEFT + m.UP)
4083 either = m.Exclusion(square, circle, color=m.GREEN, fill_opacity=0.8)
4084 self.add(square, circle, either.shift(7 * m.RIGHT))
4085 ```
4086 """
4088 def __init__(
4089 self, subject: VMobject, clip: VMobject, **kwargs: Unpack[Style]
4090 ) -> None:
4091 super().__init__(**kwargs)
4092 _append_path(self, _combine(_pathops().PathOp.XOR, subject, clip))
4095class PointCloudDot(Mobject1D):
4096 """A disk of points: rings of points around a center, pure yellow unless styled.
4098 The rings are 1/`density` scene units apart, from that far from the center out to
4099 just inside `radius`, and the points along each ring about as far apart. Its points
4100 are small: `stroke_width` 2.
4102 Args:
4103 center: Where its center is, in scene coordinates.
4104 radius: How far out its points reach, in scene units.
4105 density: How many rings, and points along a ring, per scene unit.
4106 **kwargs: [Style keywords][manimgx.drawing.paint.Style]: `color` colors its points,
4107 and `stroke_width` sizes them.
4109 Examples:
4110 ```python
4111 import manimgx as m
4114 class PointCloudDotExample(m.Scene):
4115 def construct(self) -> None:
4116 clouds = m.Group(
4117 m.PointCloudDot(),
4118 m.PointCloudDot(density=5, stroke_width=8, color=m.BLUE),
4119 m.PointCloudDot(density=15, stroke_width=4, color=m.RED),
4120 ).arrange(buff=0.6)
4121 self.add(clouds)
4122 ```
4123 """
4125 defaults: ClassVar[Style] = {"stroke_width": 2, "color": PURE_YELLOW}
4127 def __init__(
4128 self,
4129 center: Point3DLike = ORIGIN,
4130 radius: float = 2.0,
4131 *,
4132 density: int = DEFAULT_POINT_DENSITY_1D,
4133 **kwargs: Unpack[Style],
4134 ) -> None:
4135 self.radius = radius
4136 self.epsilon = 1.0 / density
4137 super().__init__(density=density, **kwargs)
4138 self.shift(center)
4140 def generate_points(self) -> Self:
4141 rings = []
4142 for r in np.arange(self.epsilon, self.radius, self.epsilon):
4143 theta = np.linspace(
4144 0,
4145 2 * np.pi,
4146 num=int(2 * np.pi * (r + self.epsilon) / self.epsilon),
4147 )[:, None]
4148 rings.append(r * (np.cos(theta) * RIGHT + np.sin(theta) * UP))
4149 return self.add_points(np.concatenate(rings) if rings else np.empty((0, 3)))