Skip to content

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

Python

Make mutable authoring and configuration contracts explicit

Sina Atalay11dbadb0e5fd
diff --git a/src/manimgx/config.py b/src/manimgx/config.py
index 6073eb14..c7b32efc 100644
--- a/src/manimgx/config.py
+++ b/src/manimgx/config.py
@@ -124,7 +124,9 @@ class Config:
# CE's dict-style access (`config["frame_width"]`), typed by key
@overload
- def __getitem__(self, key: Literal["pixel_width", "pixel_height"]) -> int: ...
+ def __getitem__(
+ self, key: Literal["pixel_width", "pixel_height", "simulation_rate"]
+ ) -> int: ...
@overload
def __getitem__(
self,
@@ -151,7 +153,9 @@ class Config:
@overload
def __setitem__(
- self, key: Literal["pixel_width", "pixel_height"], value: int
+ self,
+ key: Literal["pixel_width", "pixel_height", "simulation_rate"],
+ value: int,
) -> None: ...
@overload
def __setitem__(
diff --git a/src/manimgx/constants.py b/src/manimgx/constants.py
index 8b77e858..599b27d6 100644
--- a/src/manimgx/constants.py
+++ b/src/manimgx/constants.py
@@ -182,7 +182,7 @@ class LineJointType(Enum):
"""Corners cut straight across."""
MITER = 3
"""Pointed corners, where the stroke's edges meet; cut straight across where the
- point would be more than ten stroke widths long."""
+ point would lie more than five stroke widths from the path's corner."""
class CapStyleType(Enum):
diff --git a/src/manimgx/drawing/paint.py b/src/manimgx/drawing/paint.py
index 79a41b85..539bd708 100644
--- a/src/manimgx/drawing/paint.py
+++ b/src/manimgx/drawing/paint.py
@@ -16,11 +16,12 @@ from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from enum import Enum
from pathlib import PurePath
-from typing import TYPE_CHECKING, Final, Self, TypedDict, TypeIs, cast, overload
+from typing import TYPE_CHECKING, Final, Self, TypeIs, cast, overload
from warnings import deprecated
import numpy as np
import numpy.typing as npt
+from typing_extensions import TypedDict
from manimgx.caches import Memo, unchanged
from manimgx.constants import UL, CapStyleType, LineJointType
@@ -1169,12 +1170,8 @@ class Material:
# `StyleBase` for the rest.
-class Look(TypedDict, total=False):
- """The style keywords that are not paint.
-
- A mobject whose paint comes from its source (an SVG file, typeset text) takes these,
- with [`Repaint`][manimgx.drawing.paint.Repaint] to paint over its source's colors.
- """
+class _Look(TypedDict, total=False):
+ """Look's keys, open, for the keywords that add to them."""
background_stroke_color: Colors | None
"""The color of an outline drawn behind the fill (default black)."""
@@ -1209,6 +1206,14 @@ class Look(TypedDict, total=False):
"""The state [`MoveToTarget`][manimgx.MoveToTarget] moves the mobject to."""
+class Look(_Look, total=False, closed=True):
+ """The style keywords that are not paint.
+
+ A mobject whose paint comes from its source (an SVG file, typeset text) takes these,
+ with [`Repaint`][manimgx.drawing.paint.Repaint] to paint over its source's colors.
+ """
+
+
class Repaint(TypedDict, total=False):
"""Paint over the paint a mobject's source gives its parts.
@@ -1232,11 +1237,8 @@ class Repaint(TypedDict, total=False):
"""The stroke's width, in hundredths of a scene unit."""
-class StyleBase(Look, total=False):
- """Every style keyword but `color`.
-
- A class that takes `color` by position declares it itself, and the rest with this.
- """
+class _StyleBase(_Look, total=False):
+ """StyleBase's keys, open, for the keywords that add to them."""
fill_color: Colors | None
"""The fill's color; `color` if not given. Several colors make a gradient along
@@ -1251,7 +1253,21 @@ class StyleBase(Look, total=False):
"""The stroke's width, in hundredths of a scene unit (default 4; 0: no stroke)."""
-class Style(StyleBase, total=False):
+class StyleBase(_StyleBase, total=False, closed=True):
+ """Every style keyword but `color`.
+
+ A class that takes `color` by position declares it itself, and the rest with this.
+ """
+
+
+class _Style(_StyleBase, total=False):
+ """Style's keys, open, for the keywords that add to them."""
+
+ color: Colors | None
+ """The color of both fill and stroke (default white); None for the class's default."""
+
+
+class Style(_Style, total=False, closed=True):
"""The style keywords: one vocabulary for every mobject and every group.
Every mobject takes these keywords, and each class sets its own defaults for them
@@ -1260,9 +1276,6 @@ class Style(StyleBase, total=False):
a hex string, or RGB values.
"""
- color: Colors | None
- """The color of both fill and stroke (default white); None for the class's default."""
-
class Fill(TypedDict):
"""A fill's color and opacity: an image's style (`ImageMobject.get_style()`)."""
diff --git a/src/manimgx/mobject.py b/src/manimgx/mobject.py
index c1f7d391..e9dd8512 100644
--- a/src/manimgx/mobject.py
+++ b/src/manimgx/mobject.py
@@ -25,7 +25,6 @@ from typing import (
Literal,
Never,
Self,
- TypedDict,
TypeIs,
Unpack,
cast,
@@ -35,6 +34,7 @@ from warnings import deprecated
import numpy as np
import numpy.typing as npt
+from typing_extensions import TypedDict
from manimgx import caches
from manimgx.animation import clock
@@ -85,7 +85,6 @@ from manimgx.drawing.paint import (
BLACK,
WHITE,
Colors,
- Look,
ManimColor,
Material,
Paint,
@@ -95,6 +94,7 @@ from manimgx.drawing.paint import (
Style,
StyleBase,
StyleSnapshot,
+ _Look,
color_gradient,
frozen,
interpolate_color,
@@ -527,10 +527,8 @@ class GridArrangement(TypedDict, total=False):
fills columns top to bottom, from the left)."""
-class Beside(TypedDict, total=False):
- """How [next_to][manimgx.Mobject.next_to] aligns a mobject beside another: its
- keywords but the direction and the gap, for the methods that pass them on
- ([arrange][manimgx.Mobject.arrange])."""
+class _Beside(TypedDict, total=False):
+ """Beside's keys, open, for the keywords that add to them."""
aligned_edge: Vector3DLike
"""The edge, as a direction, along which the two line up besides the side they meet
@@ -547,7 +545,13 @@ class Beside(TypedDict, total=False):
it keeps (default (1, 1, 1))."""
-class Placement(Beside, total=False):
+class Beside(_Beside, total=False, closed=True):
+ """How [next_to][manimgx.Mobject.next_to] aligns a mobject beside another: its
+ keywords but the direction and the gap, for the methods that pass them on
+ ([arrange][manimgx.Mobject.arrange])."""
+
+
+class Placement(_Beside, total=False, closed=True):
"""How [next_to][manimgx.Mobject.next_to] places a mobject beside another: its
keywords but the direction, for the methods that pass them on."""
@@ -555,7 +559,7 @@ class Placement(Beside, total=False):
"""The gap between the two, in scene units (default 0.25)."""
-class BackgroundOptions(Look, total=False):
+class BackgroundOptions(_Look, total=False, closed=True):
"""A background rectangle's keywords but its color and opacity: those of
[add_background_rectangle][manimgx.Mobject.add_background_rectangle] and its
variants."""
@@ -575,7 +579,7 @@ class BackgroundOptions(Look, total=False):
"""The outline's color (default: the rectangle's color)."""
-class Pivot(TypedDict, total=False):
+class Pivot(TypedDict, total=False, closed=True):
"""The point a transformation keeps fixed: given, or a point of the mobject's
bounding box.
@@ -4259,7 +4263,9 @@ class Mobject:
animation's [Transform options][manimgx.animation.transform.TransformOptions]; a
`path_arc` or a `path_func` among them replaces the motion. Call it with a
function — `square.animate(lambda s: s.shift(UP))` — to record that function as
- a call.
+ a call. Call a method of your own class so: through `animate`, a type checker
+ knows only manimgx's methods, but it checks a function against the mobject's
+ class.
Examples:
```python
@@ -4544,7 +4550,8 @@ class ValueTracker[V: (float, complex) = float](Mobject):
change the number at once.
Args:
- value: The number it starts with.
+ value: The real number it starts with; use
+ [ComplexValueTracker][manimgx.ComplexValueTracker] for complex numbers.
**kwargs: [Style keywords][manimgx.drawing.paint.Style], as any mobject takes (a
tracker is not drawn).
@@ -4569,6 +4576,14 @@ class ValueTracker[V: (float, complex) = float](Mobject):
```
"""
+ @overload
+ def __init__(
+ self: "ValueTracker[float]", value: float = 0, **kwargs: Unpack[Style]
+ ) -> None: ...
+ @overload
+ def __init__(
+ self: "ComplexValueTracker", value: complex = 0, **kwargs: Unpack[Style]
+ ) -> None: ...
def __init__(self, value: V = 0, **kwargs: Unpack[Style]) -> None:
super().__init__(**kwargs)
self.points = np.zeros((1, 3))
@@ -6095,25 +6110,25 @@ class VDict[T: Mobject = Mobject](Mobject):
"""
@overload # `VDict({...})`: members of any kinds
- def __init__(
+ def __init__[Key: Hashable](
self: "VDict[Mobject]",
mapping_or_iterable: (
- Mapping[Hashable, Mobject] | Iterable[tuple[Hashable, Mobject]]
+ Mapping[Key, Mobject] | Iterable[tuple[Key, Mobject]]
) = {},
show_keys: bool = False,
**kwargs: Unpack[Style],
) -> None: ...
@overload # `VDict[Circle]({...})`: declared
- def __init__(
+ def __init__[Key: Hashable](
self,
- mapping_or_iterable: Mapping[Hashable, T] | Iterable[tuple[Hashable, T]] = {},
+ mapping_or_iterable: Mapping[Key, T] | Iterable[tuple[Key, T]] = {},
show_keys: bool = False,
**kwargs: Unpack[Style],
) -> None: ...
- def __init__(
+ def __init__[Key: Hashable](
self,
mapping_or_iterable: (
- Mapping[Hashable, Mobject] | Iterable[tuple[Hashable, Mobject]]
+ Mapping[Key, Mobject] | Iterable[tuple[Key, Mobject]]
) = {},
show_keys: bool = False,
**kwargs: Unpack[Style],
@@ -6126,8 +6141,8 @@ class VDict[T: Mobject = Mobject](Mobject):
mapping_or_iterable # ty: ignore[invalid-argument-type] # a VDict[T] is given T
)
- def add( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: by key
- self, mapping_or_iterable: Mapping[Hashable, T] | Iterable[tuple[Hashable, T]]
+ def add[Key: Hashable]( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: by key
+ self, mapping_or_iterable: Mapping[Key, T] | Iterable[tuple[Key, T]]
) -> Self:
"""Add members by key, after the group's.
diff --git a/src/manimgx/mobjects/annotations.py b/src/manimgx/mobjects/annotations.py
index 6502ba87..89479576 100644
--- a/src/manimgx/mobjects/annotations.py
+++ b/src/manimgx/mobjects/annotations.py
@@ -49,6 +49,7 @@ from manimgx.drawing.paint import (
Look,
ParsableManimColor,
Style,
+ _Style,
)
from manimgx.mobject import Mobject, Placement, VGroup, VMobject, _family, _family_box
from manimgx.mobjects.shapes import (
@@ -85,7 +86,7 @@ if TYPE_CHECKING:
)
-class FrameOptions(Style, total=False):
+class FrameOptions(_Style, total=False, closed=True):
"""The keywords of a rectangle made around a mobject, as a
[SurroundingRectangle][manimgx.SurroundingRectangle] or a
[BackgroundRectangle][manimgx.BackgroundRectangle] is: its margin and its corners,
@@ -175,6 +176,8 @@ class BackgroundRectangle(SurroundingRectangle):
*mobjects: The mobjects to go behind.
buff: The margin around them, in scene units: one for all sides, or
(horizontal, vertical).
+ corner_radius: The radius of its corners, in scene units: 0 for square
+ corners.
Examples:
```python
@@ -200,11 +203,12 @@ class BackgroundRectangle(SurroundingRectangle):
self,
*mobjects: Mobject,
buff: float | tuple[float, float] = 0,
+ corner_radius: float = 0.0,
**kwargs: Unpack[Style],
) -> None:
if kwargs.get("color") is None: # not given (None too): the scene's, when made
kwargs["color"] = config.background_color
- super().__init__(*mobjects, buff=buff, **kwargs)
+ super().__init__(*mobjects, buff=buff, corner_radius=corner_radius, **kwargs)
self.original_fill_opacity: float = self.fill_opacity
@@ -541,7 +545,7 @@ class LabeledPolygram(Polygram):
self.add(self.label)
-class BraceOptions(Style, total=False):
+class BraceOptions(_Style, total=False, closed=True):
"""A [brace][manimgx.Brace]'s keywords but its direction, for the classes that pass
them on.
@@ -738,7 +742,7 @@ type LabelMaker = Callable[
] # strings (MathTex takes several) to a label
-class BraceLabelOptions(Style, total=False):
+class BraceLabelOptions(_Style, total=False, closed=True):
"""A [brace label][manimgx.BraceLabel]'s keywords but its label's class, for the
classes that choose it.
diff --git a/src/manimgx/mobjects/shapes.py b/src/manimgx/mobjects/shapes.py
index 3656ad71..4e0ac872 100644
--- a/src/manimgx/mobjects/shapes.py
+++ b/src/manimgx/mobjects/shapes.py
@@ -65,6 +65,8 @@ from manimgx.drawing.paint import (
Colors,
Style,
StyleBase,
+ _Style,
+ _StyleBase,
)
from manimgx.mobject import (
Mobject,
@@ -159,12 +161,8 @@ if TYPE_CHECKING:
"Which way along each of two crossing lines a side of an angle goes from the\n crossing: a sign for each line, the first line's first; 1 along the line's\n direction (from its start toward its end), -1 back toward its start."
-class TippedBase(StyleBase, total=False):
- """Every style keyword but `color`, and those of a path that can end in arrow tips
- (see [TipableVMobject][manimgx.TipableVMobject]).
-
- A class that takes `color` by position declares it itself, and the rest with this.
- """
+class _TippedBase(_StyleBase, total=False):
+ """TippedBase's keys, open, for the keywords that add to them."""
tip_length: float
"""The length of the tips [add_tip][manimgx.TipableVMobject.add_tip] makes, in
@@ -177,18 +175,29 @@ class TippedBase(StyleBase, total=False):
`fill_color` and `stroke_color` are the path's color unless given here."""
-class Tipped(TippedBase, total=False):
- """The style keywords, and those of a path that can end in arrow tips (see
- [TipableVMobject][manimgx.TipableVMobject])."""
+class TippedBase(_TippedBase, total=False, closed=True):
+ """Every style keyword but `color`, and those of a path that can end in arrow tips
+ (see [TipableVMobject][manimgx.TipableVMobject]).
+
+ A class that takes `color` by position declares it itself, and the rest with this.
+ """
+
+
+class _Tipped(_TippedBase, total=False):
+ """Tipped's keys, open, for the keywords that add to them."""
color: Colors | None
"""The color of both fill and stroke (default white; a [Circle][manimgx.Circle]'s is
red); None for the class's default."""
-class ArcOptions(Tipped, total=False):
- """An arc's keywords, for the classes that build one and pass them on: how finely
- and where it is built, with the style and tip keywords."""
+class Tipped(_Tipped, total=False, closed=True):
+ """The style keywords, and those of a path that can end in arrow tips (see
+ [TipableVMobject][manimgx.TipableVMobject])."""
+
+
+class _ArcOptions(_Tipped, total=False):
+ """ArcOptions's keys, open, for the keywords that add to them."""
num_components: int
"""How many anchor points the arc is drawn through: it is one fewer cubic Bézier
@@ -198,7 +207,12 @@ class ArcOptions(Tipped, total=False):
ORIGIN)."""
-class SectorOptions(ArcOptions, total=False):
+class ArcOptions(_ArcOptions, total=False, closed=True):
+ """An arc's keywords, for the classes that build one and pass them on: how finely
+ and where it is built, with the style and tip keywords."""
+
+
+class SectorOptions(_ArcOptions, total=False, closed=True):
"""A [Sector][manimgx.Sector]'s keywords but its radius: its angles, with the arc
keywords."""
@@ -210,7 +224,7 @@ class SectorOptions(ArcOptions, total=False):
x-axis (default 0)."""
-class ArcBetweenOptions(Tipped, total=False):
+class ArcBetweenOptions(_Tipped, total=False, closed=True):
"""An [ArcBetweenPoints][manimgx.ArcBetweenPoints]'s keywords but its ends: its
angle or its radius, with the style and tip keywords (for the classes that pass
them on)."""
@@ -1669,7 +1683,7 @@ class Polygon(Polygram):
super().__init__(vertices, **kwargs)
-class RegularPolygonOptions(Style, total=False):
+class RegularPolygonOptions(_Style, total=False, closed=True):
"""A [RegularPolygon][manimgx.RegularPolygon]'s keywords but its number of vertices,
for the classes that pass them on: its size and turn, with the style keywords."""
@@ -1873,9 +1887,8 @@ class Triangle(RegularPolygon):
super().__init__(n=3, **kwargs)
-class GridOptions(Style, total=False):
- """A [Rectangle][manimgx.Rectangle]'s grid, with the style keywords (for the classes
- that pass them on)."""
+class _GridOptions(_Style, total=False):
+ """GridOptions's keys, open, for the keywords that add to them."""
grid_xstep: float | None
"""The distance between the vertical lines of its grid, from its left edge, in
@@ -1887,7 +1900,12 @@ class GridOptions(Style, total=False):
"""Accepted for Manim compatibility; ignored."""
-class RectangleOptions(GridOptions, total=False):
+class GridOptions(_GridOptions, total=False, closed=True):
+ """A [Rectangle][manimgx.Rectangle]'s grid, with the style keywords (for the classes
+ that pass them on)."""
+
+
+class RectangleOptions(_GridOptions, total=False, closed=True):
"""A [Rectangle][manimgx.Rectangle]'s keywords, for the classes that pass them on:
its size and its grid, with the style keywords."""
@@ -1914,6 +1932,7 @@ class Rectangle(Polygon):
edge, in scene units; None for none.
grid_ystep: The distance between the horizontal lines of its grid, from its top
edge, in scene units; None for none.
+ mark_paths_closed: Accepted for Manim compatibility; ignored.
**kwargs: [Style keywords][manimgx.drawing.paint.Style].
Examples:
@@ -1944,6 +1963,7 @@ class Rectangle(Polygon):
width: float = 4.0,
grid_xstep: float | None = None,
grid_ystep: float | None = None,
+ mark_paths_closed: bool = False,
**kwargs: Unpack[StyleBase],
) -> None:
style = Style(**kwargs) if color is None else Style(**kwargs, color=color)
@@ -1990,7 +2010,7 @@ class Rectangle(Polygon):
self.add(self.grid_lines)
-class ScreenOptions(Style, total=False):
+class ScreenOptions(_Style, total=False, closed=True):
"""A [ScreenRectangle][manimgx.ScreenRectangle]'s keywords, for the rectangles that
pass them on: its proportions and its height, with the style keywords."""
@@ -2577,7 +2597,7 @@ class ArrowSquareFilledTip(ArrowSquareTip):
defaults: ClassVar[Style] = {"fill_opacity": 1.0, "stroke_width": 0}
-class ArcedBase(TippedBase, total=False):
+class ArcedBase(_TippedBase, total=False):
"""A line's bend, with the tip keywords and every style keyword but `color`."""
path_arc: float
@@ -2586,21 +2606,31 @@ class ArcedBase(TippedBase, total=False):
on its way), clockwise if negative (default 0)."""
-class Arced(ArcedBase, Tipped, total=False):
+class _Arced(ArcedBase, _Tipped, total=False):
+ """Arced's keys, open, for the keywords that add to them."""
+
+ pass
+
+
+class Arced(_Arced, total=False, closed=True):
"""A line's bend, with the style and tip keywords (for the lines that set the buffer
themselves)."""
-class LineOptions(Arced, total=False):
- """A [Line][manimgx.Line]'s keywords but its ends, for the classes that pass them
- on: its buffer and its bend, with the style and tip keywords."""
+class _LineOptions(_Arced, total=False):
+ """LineOptions's keys, open, for the keywords that add to them."""
buff: float
"""How far the line stops short of each end, in scene units; a line shorter than
twice it keeps its ends (default 0)."""
-class DashedLineOptions(LineOptions, total=False):
+class LineOptions(_LineOptions, total=False, closed=True):
+ """A [Line][manimgx.Line]'s keywords but its ends, for the classes that pass them
+ on: its buffer and its bend, with the style and tip keywords."""
+
+
+class DashedLineOptions(_LineOptions, total=False):
"""A [DashedLine][manimgx.DashedLine]'s keywords but its ends: its dashes, with the
line keywords."""
@@ -2612,9 +2642,8 @@ class DashedLineOptions(LineOptions, total=False):
(default 0.5: dashes and gaps as long)."""
-class ArrowTipsBase(ArcedBase, total=False):
- """An [Arrow][manimgx.Arrow]'s keywords but its ends, its buffer and its color (for
- the methods that set those): its tip, how it shrinks when short, and its bend."""
+class _ArrowTipsBase(ArcedBase, total=False):
+ """ArrowTipsBase's keys, open, for the keywords that add to them."""
max_tip_length_to_length_ratio: float
"""The longest its tip may be, as a fraction of its length: a short arrow's tip is
@@ -2627,12 +2656,23 @@ class ArrowTipsBase(ArcedBase, total=False):
[ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip])."""
-class ArrowTips(ArrowTipsBase, Tipped, total=False):
+class ArrowTipsBase(_ArrowTipsBase, total=False, closed=True):
+ """An [Arrow][manimgx.Arrow]'s keywords but its ends, its buffer and its color (for
+ the methods that set those): its tip, how it shrinks when short, and its bend."""
+
+
+class _ArrowTips(_ArrowTipsBase, _Tipped, total=False):
+ """ArrowTips's keys, open, for the keywords that add to them."""
+
+ pass
+
+
+class ArrowTips(_ArrowTips, total=False, closed=True):
"""An [Arrow][manimgx.Arrow]'s keywords but its ends and its buffer (for the arrows
that set it: vectors)."""
-class ArrowOptions(ArrowTips, total=False):
+class ArrowOptions(_ArrowTips, total=False, closed=True):
"""An [Arrow][manimgx.Arrow]'s keywords but its ends, for the classes that pass them
on."""
@@ -3570,10 +3610,8 @@ class DoubleArrow(Arrow):
self._set_stroke_width_from_length() # as an arrow's: by its length, tip to tip
-class AngleShape(Style, total=False):
- """An [Angle][manimgx.Angle]'s keywords but its radius and its elbow (for right
- angles, which set them): which angle it marks, and its dot, with the style
- keywords."""
+class _AngleShape(_Style, total=False):
+ """AngleShape's keys, open, for the keywords that add to them."""
quadrant: AngleQuadrant
"""Which way each side of the angle goes from the crossing: a sign for each line,
@@ -3594,7 +3632,13 @@ class AngleShape(Style, total=False):
"""The dot's color (default white)."""
-class AngleOptions(AngleShape, total=False):
+class AngleShape(_AngleShape, total=False, closed=True):
+ """An [Angle][manimgx.Angle]'s keywords but its radius and its elbow (for right
+ angles, which set them): which angle it marks, and its dot, with the style
+ keywords."""
+
+
+class AngleOptions(_AngleShape, total=False, closed=True):
"""An [Angle][manimgx.Angle]'s keywords but its lines (for the methods that make
one)."""
diff --git a/src/manimgx/mobjects/svg.py b/src/manimgx/mobjects/svg.py
index 8d1df343..f9258090 100644
--- a/src/manimgx/mobjects/svg.py
+++ b/src/manimgx/mobjects/svg.py
@@ -22,7 +22,7 @@ import numpy as np
from manimgx.caches import Memo
from manimgx.constants import RIGHT
from manimgx.drawing.geometry import Blend
-from manimgx.drawing.paint import BLACK, Colors, Look, Repaint, Style, key_of
+from manimgx.drawing.paint import BLACK, Colors, Look, Repaint, Style, _Style, key_of
from manimgx.mobject import VGroup, VMobject, copied
from manimgx.mobjects.shapes import Circle, Line, Polygon, Rectangle, RoundedRectangle
@@ -44,7 +44,7 @@ def _point(point: se.Point | None) -> np.ndarray:
return np.array([point.x, point.y, 0.0])
-class PathOptions(Style, total=False):
+class PathOptions(_Style, total=False):
"""How an SVG path becomes curves: an [SVGMobject][manimgx.SVGMobject]'s
`path_string_config`, the keywords of each path it reads.
diff --git a/src/manimgx/mobjects/three_d.py b/src/manimgx/mobjects/three_d.py
index 7721752d..f31817ff 100644
--- a/src/manimgx/mobjects/three_d.py
+++ b/src/manimgx/mobjects/three_d.py
@@ -31,9 +31,10 @@ __all__ = [
"Torus",
]
from collections.abc import Callable, Hashable, Iterable, Sequence
-from typing import TYPE_CHECKING, ClassVar, Literal, Self, TypedDict, Unpack, cast
+from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpack, cast
import numpy as np
+from typing_extensions import TypedDict
from manimgx.caches import forgets
from manimgx.constants import (
@@ -71,6 +72,7 @@ from manimgx.drawing.paint import (
ManimColor,
ParsableManimColor,
Style,
+ _Style,
rgbas_by_value,
)
from manimgx.mobject import MeshMobject, Mobject, VectorizedPoint, VGroup, VMobject
@@ -111,10 +113,8 @@ class ThreeDVMobject(VMobject):
v2: float
-class SurfaceLook(Style, total=False):
- """A [Surface][manimgx.Surface]'s keywords but its function, ranges and resolution,
- for the shapes that set those (spheres, cylinders, …): its checkerboard, with the
- style keywords."""
+class _SurfaceLook(_Style, total=False):
+ """SurfaceLook's keys, open, for the keywords that add to them."""
surface_piece_config: Style | None
"""Accepted for Manim compatibility; ignored."""
@@ -127,7 +127,13 @@ class SurfaceLook(Style, total=False):
"""Accepted for Manim compatibility; ignored."""
-class SurfaceOptions(SurfaceLook, total=False):
+class SurfaceLook(_SurfaceLook, total=False, closed=True):
+ """A [Surface][manimgx.Surface]'s keywords but its function, ranges and resolution,
+ for the shapes that set those (spheres, cylinders, …): its checkerboard, with the
+ style keywords."""
+
+
+class SurfaceOptions(_SurfaceLook, total=False, closed=True):
"""A [Surface][manimgx.Surface]'s keywords but its function and ranges, for the
shapes that pass them on ([Cone][manimgx.Cone]): its resolution and checkerboard,
with the style keywords."""
@@ -886,7 +892,7 @@ class Cylinder(_DirectedSurface):
return self
-class Line3DOptions(SurfaceLook, total=False):
+class Line3DOptions(_SurfaceLook, total=False, closed=True):
"""A [Line3D][manimgx.Line3D]'s keywords but its ends, for the methods that pass
them on ([parallel_to][manimgx.Line3D.parallel_to],
[perpendicular_to][manimgx.Line3D.perpendicular_to]): its thickness and resolution,
@@ -1230,7 +1236,7 @@ class Torus(Surface):
return _revolve(self.R - self.r * np.cos(v), -self.r * np.sin(v), u)
-class PolyhedronOptions(TypedDict, total=False):
+class PolyhedronOptions(TypedDict, total=False, closed=True):
"""How a [Polyhedron][manimgx.Polyhedron]'s faces and its graph of vertices and
edges look, for the solids that set their own vertices and faces
([Tetrahedron][manimgx.Tetrahedron], [ConvexHull3D][manimgx.ConvexHull3D], …)."""
diff --git a/tests/unit/mobjects/test_svg.py b/tests/unit/mobjects/test_svg.py
index 98ba5640..6fe3be82 100644
--- a/tests/unit/mobjects/test_svg.py
+++ b/tests/unit/mobjects/test_svg.py
@@ -7,6 +7,8 @@ equal to the last ones up to their repr — the drawing the cache gives is the o
the file anew gives: the same parts, points and paint, and the same named groups of them.
"""
+from __future__ import annotations
+
import os
from collections.abc import Callable
from pathlib import Path
diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py
index a11c515d..be6b4456 100644
--- a/tests/unit/test_config.py
+++ b/tests/unit/test_config.py
@@ -5,9 +5,14 @@
proportions. A scene laid out in the central 8 × 8 square fits both, at the same size.
- A height that is set is the frame's height, whatever the video's proportions; the CLI's
reset before a scene file forgets it, as it forgets every field.
+- Nothing reads the configuration when manimgx is imported: a scene's file sets the video's
+ size after its import, so a default read then would be a wide video's in a tall one.
"""
+import ast
import dataclasses
+from pathlib import Path
+from typing import assert_type
import pytest
from hypothesis import given
@@ -19,6 +24,12 @@ from manimgx.config import Config
pixels = st.integers(16, 4096)
+def test_simulation_rate_has_the_same_typed_dictionary_access_as_other_fields() -> None:
+ config = Config()
+ config["simulation_rate"] = 120
+ assert assert_type(config["simulation_rate"], int) == config.simulation_rate == 120
+
+
@given(width=pixels, height=pixels)
def test_the_frames_short_side_is_8_units_in_the_videos_proportions(
width: int, height: int
@@ -52,3 +63,37 @@ def test_the_defaults_forget_a_height_set() -> None:
setattr(m.config, field.name, getattr(Config(), field.name))
m.config.pixel_width, m.config.pixel_height = 1080, 1920
assert m.config.frame_width == pytest.approx(8)
+
+
+class _AtImport(ast.NodeVisitor):
+ """The lines of a module that read `config` when the module is imported."""
+
+ def __init__(self) -> None:
+ self.lines: list[int] = []
+
+ def visit_Name(self, node: ast.Name) -> None:
+ if node.id == "config" and isinstance(node.ctx, ast.Load):
+ self.lines.append(node.lineno)
+
+ def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
+ # its decorators and defaults run now; its body, when it is called
+ for expr in [*node.decorator_list, *node.args.defaults, *node.args.kw_defaults]:
+ if expr is not None:
+ self.visit(expr)
+
+ visit_AsyncFunctionDef = visit_FunctionDef
+
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ for expr in [*node.args.defaults, *node.args.kw_defaults]:
+ if expr is not None:
+ self.visit(expr)
+
+
+def test_nothing_reads_the_configuration_when_manimgx_is_imported() -> None:
+ package = Path(m.__file__).parent
+ reads = []
+ for path in sorted(package.rglob("*.py")):
+ found = _AtImport()
+ found.visit(ast.parse(path.read_text(encoding="utf-8")))
+ reads += [f"{path.relative_to(package)}:{line}" for line in found.lines]
+ assert not reads, f"read before a scene's file can set the video: {reads}"
diff --git a/tests/unit/test_typing.py b/tests/unit/test_typing.py
new file mode 100644
index 00000000..59ef9973
--- /dev/null
+++ b/tests/unit/test_typing.py
@@ -0,0 +1,234 @@
+"""A type checker knows each keyword a mobject or an animation takes, and each method
+`.animate` and `.always` call, and nothing else.
+
+- Every TypedDict that a signature unpacks (`**kwargs: Unpack[Style]`) is closed (PEP 728):
+ a keyword it doesn't name is an error to a type checker, not a key of type `object`.
+- So ty reports a misspelled keyword (`m.Circle(colour=…)`), where manimgx would ignore it,
+ and a misspelled method through `.animate` or `.always` (`.animate.shfit(…)`), or in a
+ function given to `.animate`, which manimgx reports only when the scene runs; it takes the
+ methods there as the mobject's.
+- Mutable mappings and numbers retain their key and value types through construction,
+ updates, and animation proxies.
+"""
+
+import importlib
+import re
+from pathlib import Path
+
+from tests.typecheck import check
+from typing_extensions import is_typeddict
+
+PACKAGE = Path(__file__).parents[2] / "src" / "manimgx"
+
+
+def unpacked() -> dict[str, set[str]]:
+ """The TypedDicts that the package's signatures unpack, by module: their names."""
+ found: dict[str, set[str]] = {}
+ for path in PACKAGE.rglob("*.py"):
+ names = set(re.findall(r"Unpack\[(\w+)", path.read_text(encoding="utf-8")))
+ if names:
+ module = ".".join(path.relative_to(PACKAGE.parent).with_suffix("").parts)
+ found[module.removesuffix(".__init__")] = names
+ return found
+
+
+def test_every_typeddict_a_signature_unpacks_is_closed() -> None:
+ seen = 0
+ for module, names in unpacked().items():
+ namespace = vars(importlib.import_module(module))
+ for name in names:
+ kind = namespace.get(name)
+ # imported for the type checker only: checked where it is defined
+ if kind is None:
+ continue
+ assert is_typeddict(kind), f"{module}.{name}"
+ assert getattr(kind, "__closed__", False), f"{module}.{name} is open"
+ seen += 1
+ assert seen > 50
+
+
+def _ty(scene: Path) -> dict[int, str]:
+ """The rule ty breaks on each line of a scene, by line."""
+ return {
+ line: message.split("[", 1)[1].split("]", 1)[0]
+ for _, line, _, message in check([scene])
+ }
+
+
+def test_ty_reports_a_misspelling(tmp_path: Path) -> None:
+ scene = tmp_path / "scene.py"
+ scene.write_text(
+ "import manimgx as m\n"
+ "\n"
+ "m.Circle(colour=m.BLUE)\n"
+ 'm.Text("x", font_szie=20)\n'
+ "m.FadeIn(m.Dot(), run_tme=2)\n"
+ "m.Square().set_style(fill_opactiy=1)\n"
+ "m.Square().animate.shfit(m.RIGHT)\n"
+ "m.Square().animate.shift(m.RIGHT).scael(2)\n"
+ "m.Dot().always.nxt_to(m.ORIGIN)\n"
+ "m.Square().animate(lambda s: s.shfit(m.RIGHT))\n",
+ encoding="utf-8",
+ )
+ assert _ty(scene) == {
+ 3: "unknown-argument",
+ 4: "unknown-argument",
+ 5: "unknown-argument",
+ 6: "unknown-argument",
+ 7: "unresolved-attribute",
+ 8: "unresolved-attribute",
+ 9: "unresolved-attribute",
+ 10: "unresolved-attribute",
+ }
+
+
+def test_ty_takes_the_methods_through_animate_as_the_mobjects(tmp_path: Path) -> None:
+ # a kind's own parameters, where they are its own
+ scene = tmp_path / "scene.py"
+ scene.write_text(
+ "import manimgx as m\n"
+ "\n"
+ "m.Axes().animate.add_coordinates([1, 2])\n"
+ "m.DecimalNumber(1).animate.increment_value(2)\n"
+ 'm.Text("x").animate.scale(2, about_edge=m.UP)\n'
+ "m.Cone().animate.set_direction(m.UP)\n"
+ "m.Square().animate.close_path().make_jagged()\n"
+ "m.Dot().always.next_to(m.ORIGIN, m.UP)\n"
+ "m.Square().animate(lambda s: s.shift(m.UP).set_color(m.RED))\n",
+ encoding="utf-8",
+ )
+ assert _ty(scene) == {}
+
+
+def test_matching_accepts_a_typed_mapping_of_hashable_keys(tmp_path: Path) -> None:
+ scene = tmp_path / "scene.py"
+ scene.write_text(
+ "import manimgx as m\n"
+ 'keys: dict[str, str] = {"a": "b"}\n'
+ 'm.TransformMatchingTex(m.MathTex("a"), m.MathTex("b"), key_map=keys)\n',
+ encoding="utf-8",
+ )
+ assert _ty(scene) == {}
+
+
+def test_vdict_accepts_assigned_mappings_without_widening_their_members(
+ tmp_path: Path,
+) -> None:
+ source = tmp_path / "vdict.py"
+ source.write_text(
+ "from typing import assert_type\n"
+ "import manimgx as m\n"
+ "circles = {'circle': m.Circle()}\n"
+ "numbered = {1: m.Circle()}\n"
+ "shapes = m.VDict(circles)\n"
+ "assert_type(shapes, m.VDict[m.Mobject])\n"
+ "shapes.add(numbered)\n"
+ "shapes['square'] = m.Square()\n"
+ "typed = m.VDict[m.Circle](circles)\n"
+ "assert_type(typed['circle'], m.Circle)\n"
+ "typed.add(circles).add(numbered)\n"
+ "pairs = [('circle', m.Circle())]\n"
+ "typed.add(pairs)\n"
+ "assert_type(m.VDict[m.Circle](pairs)['circle'], m.Circle)\n",
+ encoding="utf-8",
+ )
+ assert check([source]) == []
+
+
+def test_vdict_rejects_wrong_members_and_unhashable_keys(tmp_path: Path) -> None:
+ source = tmp_path / "vdict.py"
+ source.write_text(
+ "import manimgx as m\n"
+ "squares = {'square': m.Square()}\n"
+ "m.VDict[m.Circle](squares)\n"
+ "typed = m.VDict[m.Circle]()\n"
+ "typed.add(squares)\n"
+ "typed.add([([], m.Circle())])\n",
+ encoding="utf-8",
+ )
+ assert [
+ (line, message.split("]")[0]) for _, line, _, message in check([source])
+ ] == [
+ (3, "error[no-matching-overload"),
+ (5, "error[invalid-argument-type"),
+ (6, "error[invalid-argument-type"),
+ ]
+
+
+def test_decimal_number_retains_real_and_complex_value_types(tmp_path: Path) -> None:
+ source = tmp_path / "numbers.py"
+ source.write_text(
+ "from typing import assert_type\n"
+ "import manimgx as m\n"
+ "real = m.DecimalNumber(1)\n"
+ "assert_type(real.get_value(), float)\n"
+ "assert_type(m.DecimalNumber().get_value(), float)\n"
+ "assert_type(m.Integer(2).get_value(), int)\n"
+ "real.set_value(1.5).increment_value(.25)\n"
+ "z = m.DecimalNumber(1 + 2j)\n"
+ "assert_type(z.get_value(), complex)\n"
+ "z.set_value(3 + 4j).increment_value(2j)\n"
+ "z.set_value(2)\n"
+ "z.animate.set_value(2 + 3j).increment_value(1j)\n"
+ "z.always.set_value(2 + 3j)\n"
+ "m.ChangingDecimal(z, lambda t: 1 + 2j*t)\n"
+ "m.ChangeDecimalToValue(z, 3j)\n"
+ "declared = m.DecimalNumber[complex]()\n"
+ "declared.set_value(1j)\n"
+ "assert_type(declared.get_value(), complex)\n",
+ encoding="utf-8",
+ )
+ assert check([source]) == []
+
+
+def test_real_numbers_cannot_be_changed_into_complex_values(tmp_path: Path) -> None:
+ source = tmp_path / "numbers.py"
+ source.write_text(
+ "import manimgx as m\n"
+ "def complex_update(alpha: float) -> complex:\n"
+ " return 2j*alpha\n"
+ "real = m.DecimalNumber(1)\n"
+ "real.set_value(2j)\n"
+ "real.increment_value(2j)\n"
+ "real.animate.set_value(2j)\n"
+ "real.always.increment_value(2j)\n"
+ "m.Integer(2j)\n"
+ "m.ChangeDecimalToValue(real, 2j)\n"
+ "m.ChangingDecimal(real, complex_update)\n",
+ encoding="utf-8",
+ )
+ assert [
+ (line, message.split("]")[0]) for _, line, _, message in check([source])
+ ] == [(line, "error[invalid-argument-type") for line in range(5, 12)]
+
+
+def test_tracker_constructors_preserve_real_and_complex_value_types(
+ tmp_path: Path,
+) -> None:
+ source = tmp_path / "trackers.py"
+ source.write_text(
+ "from typing import assert_type\n"
+ "import manimgx as m\n"
+ "class Real(m.ValueTracker): pass\n"
+ "class Complex(m.ComplexValueTracker): pass\n"
+ "assert_type(m.ValueTracker().get_value(), float)\n"
+ "assert_type(Real(2).get_value(), float)\n"
+ "assert_type(m.ComplexValueTracker(0).get_value(), complex)\n"
+ "assert_type(Complex(1j).get_value(), complex)\n"
+ "Complex().animate.increment_value(1j).set_value(2j)\n",
+ encoding="utf-8",
+ )
+ assert check([source]) == []
+
+
+def test_real_tracker_construction_cannot_claim_complex_storage(tmp_path: Path) -> None:
+ source = tmp_path / "trackers.py"
+ source.write_text(
+ "import manimgx as m\n"
+ "m.ValueTracker(1j)\n"
+ "m.ValueTracker[complex](0)\n"
+ "class Real(m.ValueTracker): pass\n"
+ "Real(1j)\n",
+ encoding="utf-8",
+ )
+ assert [line for _, line, _, _ in check([source])] == [2, 3, 5]