Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add ArcPolygon to geometry.py (#707)

XorUnison3c347d7f158c
diff --git a/manim/mobject/geometry.py b/manim/mobject/geometry.py
index b77e2b136..3d43adc47 100644
--- a/manim/mobject/geometry.py
+++ b/manim/mobject/geometry.py
@@ -46,6 +46,8 @@ __all__ = [
"CubicBezier",
"Polygon",
"RegularPolygon",
+ "ArcPolygon",
+ "ArcPolygonFromArcs",
"Triangle",
"ArrowTip",
"Rectangle",
@@ -164,8 +166,7 @@ class TipableVMobject(VMobject):
def reset_endpoints_based_on_tip(self, tip, at_start):
if self.get_length() == 0:
- # Zero length, put_start_and_end_on wouldn't
- # work
+ # Zero length, put_start_and_end_on wouldn't work
return self
if at_start:
@@ -884,6 +885,244 @@ class RegularPolygon(Polygon):
Polygon.__init__(self, *vertices, **kwargs)
+class ArcPolygon(VMobject):
+ """A generalized polygon allowing for points to be connected with arcs.
+
+ This version tries to stick close to the way :class:`Polygon` is used. Points
+ can be passed to it directly which are used to generate the according arcs
+ (using :class:`ArcBetweenPoints`). An angle or radius can be passed to it to
+ use across all arcs, but to configure arcs individually an ``arc_config`` list
+ has to be passed with the syntax explained below.
+
+ .. tip::
+
+ Two instances of :class:`ArcPolygon` can be transformed properly into one
+ another as well. Be advised that any arc initialized with ``angle=0``
+ will actually be a straight line, so if a straight section should seamlessly
+ transform into an arced section or vice versa, initialize the straight section
+ with a negligible angle instead (such as ``angle=0.0001``).
+
+ There is an alternative version (:class:`ArcPolygonFromArcs`) that is instantiated
+ with pre-defined arcs.
+
+ See Also
+ --------
+ :class:`ArcPolygonFromArcs`
+
+ Parameters
+ ----------
+ vertices : Union[:class:`list`, :class:`np.array`]
+ A list of vertices, start and end points for the arc segments.
+ angle : :class:`float`
+ The angle used for constructing the arcs. If no other parameters
+ are set, this angle is used to construct all arcs.
+ radius : Optional[:class:`float`]
+ The circle radius used to construct the arcs. If specified,
+ overrides the specified ``angle``.
+ arc_config : Optional[Union[List[:class:`dict`]], :class:`dict`]
+ When passing a ``dict``, its content will be passed as keyword
+ arguments to :class:`~.ArcBetweenPoints`. Otherwise, a list
+ of dictionaries containing values that are passed as keyword
+ arguments for every individual arc can be passed.
+ kwargs
+ Further keyword arguments that are passed to the constructor of
+ :class:`~.VMobject`.
+
+ Attributes
+ ----------
+ arcs : :class:`list`
+ The arcs created from the input parameters::
+
+ >>> from manim import ArcPolygon
+ >>> ap = ArcPolygon([0, 0, 0], [2, 0, 0], [0, 2, 0])
+ >>> ap.arcs
+ [ArcBetweenPoints, ArcBetweenPoints, ArcBetweenPoints]
+
+ Examples
+ --------
+
+ .. manim:: SeveralArcPolygons
+
+ class SeveralArcPolygons(Scene):
+ def construct(self):
+ a = [0, 0, 0]
+ b = [2, 0, 0]
+ c = [0, 2, 0]
+ ap1 = ArcPolygon(a, b, c, radius=2)
+ ap2 = ArcPolygon(a, b, c, angle=45*DEGREES)
+ ap3 = ArcPolygon(a, b, c, arc_config={'radius': 1.7, 'color': RED})
+ ap4 = ArcPolygon(a, b, c, color=RED, fill_opacity=1,
+ arc_config=[{'radius': 1.7, 'color': RED},
+ {'angle': 20*DEGREES, 'color': BLUE},
+ {'radius': 1}])
+ ap_group = VGroup(ap1, ap2, ap3, ap4).arrange()
+ self.play(*[ShowCreation(ap) for ap in [ap1, ap2, ap3, ap4]])
+ self.wait()
+
+ For further examples see :class:`ArcPolygonFromArcs`.
+ """
+
+ def __init__(self, *vertices, angle=PI / 4, radius=None, arc_config=None, **kwargs):
+ n = len(vertices)
+ point_pairs = [(vertices[k], vertices[(k + 1) % n]) for k in range(n)]
+
+ if not arc_config:
+ if radius:
+ all_arc_configs = [{"radius": radius} for pair in point_pairs]
+ else:
+ all_arc_configs = [{"angle": angle} for pair in point_pairs]
+ elif isinstance(arc_config, dict):
+ all_arc_configs = [arc_config for pair in point_pairs]
+ else:
+ assert len(arc_config) == n
+ all_arc_configs = arc_config
+
+ arcs = [
+ ArcBetweenPoints(*pair, **conf)
+ for (pair, conf) in zip(point_pairs, all_arc_configs)
+ ]
+
+ super().__init__(**kwargs)
+ # Adding the arcs like this makes ArcPolygon double as a VGroup.
+ # Also makes changes to the ArcPolygon, such as scaling, affect
+ # the arcs, so that their new values are usable.
+ self.add(*arcs)
+ for arc in arcs:
+ self.append_points(arc.points)
+
+ # This enables the use of ArcPolygon.arcs as a convenience
+ # because ArcPolygon[0] returns itself, not the first Arc.
+ self.arcs = arcs
+
+
+class ArcPolygonFromArcs(VMobject):
+ """A generalized polygon allowing for points to be connected with arcs.
+
+ This version takes in pre-defined arcs to generate the arcpolygon and introduces
+ little new syntax. However unlike :class:`Polygon` it can't be created with points
+ directly.
+
+ For proper appearance the passed arcs should connect seamlessly:
+ ``[a,b][b,c][c,a]``
+
+ If there are any gaps between the arcs, those will be filled in
+ with straight lines, which can be used deliberately for any straight
+ sections. Arcs can also be passed as straight lines such as an arc
+ initialized with ``angle=0``.
+
+ .. tip::
+
+ Two instances of :class:`ArcPolygon` can be transformed properly into
+ one another as well. Be advised that any arc initialized with ``angle=0``
+ will actually be a straight line, so if a straight section should seamlessly
+ transform into an arced section or vice versa, initialize the straight
+ section with a negligible angle instead (such as ``angle=0.0001``).
+
+ There is an alternative version (:class:`ArcPolygon`) that can be instantiated
+ with points.
+
+ See Also
+ --------
+ :class:`ArcPolygon`
+
+ Parameters
+ ----------
+ arcs : Union[:class:`Arc`, :class:`ArcBetweenPoints`]
+ These are the arcs from which the arcpolygon is assembled.
+ kwargs
+ Keyword arguments that are passed to the constructor of
+ :class:`~.VMobject`. Affects how the ArcPolygon itself is drawn,
+ but doesn't affect passed arcs.
+
+ Attributes
+ ----------
+ arcs : :class:`list`
+ The arcs used to initialize the ArcPolygonFromArcs::
+
+ >>> from manim import ArcPolygonFromArcs, Arc, ArcBetweenPoints
+ >>> ap = ArcPolygonFromArcs(Arc(), ArcBetweenPoints([1,0,0], [0,1,0]), Arc())
+ >>> ap.arcs
+ [Arc, ArcBetweenPoints, Arc]
+
+ Examples
+ --------
+ One example of an arcpolygon is the Reuleaux triangle.
+ Instead of 3 straight lines connecting the outer points,
+ a Reuleaux triangle has 3 arcs connecting those points,
+ making a shape with constant width.
+
+ Passed arcs are stored as submobjects in the arcpolygon.
+ This means that the arcs are changed along with the arcpolygon,
+ for example when it's shifted, and these arcs can be manipulated
+ after the arcpolygon has been initialized.
+
+ Also both the arcs contained in an :class:`~.ArcPolygonFromArcs`, as well as the
+ arcpolygon itself are drawn, which affects draw time in :class:`~.ShowCreation`
+ for example. In most cases the arcs themselves don't
+ need to be drawn, in which case they can be passed as invisible.
+
+ .. manim:: ArcPolygonExample
+
+ class ArcPolygonExample(Scene):
+ def construct(self):
+ arc_conf = {"stroke_width": 0}
+ poly_conf = {"stroke_width": 10, "stroke_color": BLUE,
+ "fill_opacity": 1, "color": PURPLE}
+ a = [-1, 0, 0]
+ b = [1, 0, 0]
+ c = [0, np.sqrt(3), 0]
+ arc0 = ArcBetweenPoints(a, b, radius=2, **arc_conf)
+ arc1 = ArcBetweenPoints(b, c, radius=2, **arc_conf)
+ arc2 = ArcBetweenPoints(c, a, radius=2, **arc_conf)
+ reuleaux_tri = ArcPolygonFromArcs(arc0, arc1, arc2, **poly_conf)
+ self.play(FadeIn(reuleaux_tri))
+ self.wait(2)
+
+ The arcpolygon itself can also be hidden so that instead only the contained
+ arcs are drawn. This can be used to easily debug arcs or to highlight them.
+
+ .. manim:: ArcPolygonExample2
+
+ class ArcPolygonExample2(Scene):
+ def construct(self):
+ arc_conf = {"stroke_width": 3, "stroke_color": BLUE,
+ "fill_opacity": 0.5, "color": GREEN}
+ poly_conf = {"color": None}
+ a = [-1, 0, 0]
+ b = [1, 0, 0]
+ c = [0, np.sqrt(3), 0]
+ arc0 = ArcBetweenPoints(a, b, radius=2, **arc_conf)
+ arc1 = ArcBetweenPoints(b, c, radius=2, **arc_conf)
+ arc2 = ArcBetweenPoints(c, a, radius=2, stroke_color=RED)
+ reuleaux_tri = ArcPolygonFromArcs(arc0, arc1, arc2, **poly_conf)
+ self.play(FadeIn(reuleaux_tri))
+ self.wait(2)
+
+ """
+
+ def __init__(self, *arcs, **kwargs):
+ if not all(isinstance(m, (Arc, ArcBetweenPoints)) for m in arcs):
+ raise ValueError(
+ "All ArcPolygon submobjects must be of type Arc/ArcBetweenPoints"
+ )
+ super().__init__(**kwargs)
+ # Adding the arcs like this makes ArcPolygonFromArcs double as a VGroup.
+ # Also makes changes to the ArcPolygonFromArcs, such as scaling, affect
+ # the arcs, so that their new values are usable.
+ self.add(*arcs)
+ # This enables the use of ArcPolygonFromArcs.arcs as a convenience
+ # because ArcPolygonFromArcs[0] returns itself, not the first Arc.
+ self.arcs = [*arcs]
+ for arc1, arc2 in adjacent_pairs(arcs):
+ self.append_points(arc1.points)
+ line = Line(arc1.get_end(), arc2.get_start())
+ len_ratio = line.get_length() / arc1.get_arc_length()
+ if math.isnan(len_ratio) or math.isinf(len_ratio):
+ continue
+ line.insert_n_curves(int(arc1.get_num_curves() * len_ratio))
+ self.append_points(line.get_points())
+
+
class Triangle(RegularPolygon):
def __init__(self, **kwargs):
RegularPolygon.__init__(self, n=3, **kwargs)