Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add 3D Mobjects - Cone, Cylinder, Line3D, Arrow3D and Torus. (#1026)

Darylgolden9006441c4fe8
diff --git a/manim/mobject/three_dimensions.py b/manim/mobject/three_dimensions.py
index f4c52dd56..d703e8544 100644
--- a/manim/mobject/three_dimensions.py
+++ b/manim/mobject/three_dimensions.py
@@ -1,16 +1,26 @@
"""Three-dimensional mobjects."""
-__all__ = ["ThreeDVMobject", "ParametricSurface", "Sphere", "Cube", "Prism"]
+__all__ = [
+ "ThreeDVMobject",
+ "ParametricSurface",
+ "Sphere",
+ "Cube",
+ "Prism",
+ "Cone",
+ "Arrow3D",
+ "Cylinder",
+ "Line3D",
+ "Torus",
+]
from ..constants import *
-from ..mobject.geometry import Square
+from ..mobject.geometry import Square, Circle, Line
+from ..mobject.mobject import *
from ..mobject.types.vectorized_mobject import VGroup
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.iterables import tuplify
-from ..utils.space_ops import z_to_vector
-from ..utils.color import BLUE_D, BLUE, BLUE_E, LIGHT_GREY
-
-##############
+from ..utils.space_ops import z_to_vector, normalize, get_norm
+from ..utils.color import *
class ThreeDVMobject(VMobject):
@@ -139,7 +149,7 @@ class Sphere(ParametricSurface):
u_max=u_max,
v_min=v_min,
v_max=v_max,
- **kwargs
+ **kwargs,
)
self.radius = radius
self.scale(self.radius)
@@ -164,7 +174,7 @@ class Cube(VGroup):
fill_color=fill_color,
fill_opacity=fill_opacity,
stroke_width=stroke_width,
- **kwargs
+ **kwargs,
)
def generate_points(self):
@@ -189,3 +199,454 @@ class Prism(Cube):
Cube.generate_points(self)
for dim, value in enumerate(self.dimensions):
self.rescale_to_fit(value, dim, stretch=True)
+
+
+class Cone(ParametricSurface):
+ """A circular cone.
+ Can be defined using 2 parameters: its height, and its base radius.
+ The polar angle, theta, can be calculated using arctan(base_radius /
+ height) The spherical radius, r, is calculated using the pythagorean
+ theorem.
+
+ Examples
+ --------
+ .. manim:: ExampleCone
+ :save_last_frame:
+
+ class ExampleCone(ThreeDScene):
+ def construct(self):
+ axes = ThreeDAxes()
+ cone = Cone(direction=X_AXIS+Y_AXIS+2*Z_AXIS)
+ self.set_camera_orientation(phi=5*PI/11, theta=PI/9)
+ self.add(axes, cone)
+
+ Parameters
+ --------
+ base_radius : :class:`float`
+ The base radius from which the cone tapers.
+ height : :class:`float`
+ The height measured from the plane formed by the base_radius to the apex of the cone.
+ direction : :class:`numpy.array`
+ The direction of the apex.
+ show_base : :class:`bool`
+ Whether to show the base plane or not.
+ v_min : :class:`float`
+ The azimuthal angle to start at.
+ v_max : :class:`float`
+ The azimuthal angle to end at.
+ u_min : :class:`float`
+ The radius at the apex.
+ checkerboard_colors : :class:`bool`
+ Show checkerboard grid texture on the cone.
+ """
+
+ def __init__(
+ self,
+ base_radius=1,
+ height=1,
+ direction=Z_AXIS,
+ show_base=False,
+ v_min=0,
+ v_max=TAU,
+ u_min=0,
+ checkerboard_colors=False,
+ **kwargs
+ ):
+ self.direction = direction
+ self.theta = PI - np.arctan(base_radius / height)
+
+ ParametricSurface.__init__(
+ self,
+ self.func,
+ v_min=v_min,
+ v_max=v_max,
+ u_min=u_min,
+ u_max=np.sqrt(base_radius ** 2 + height ** 2),
+ checkerboard_colors=checkerboard_colors,
+ **kwargs,
+ )
+ # used for rotations
+ self._current_theta = 0
+ self._current_phi = 0
+
+ if show_base:
+ self.base_circle = Circle(
+ radius=base_radius,
+ color=self.fill_color,
+ fill_opacity=self.fill_opacity,
+ stroke_width=0,
+ )
+ self.base_circle.shift(height * IN)
+ self.add(self.base_circle)
+
+ self._rotate_to_direction()
+
+ def func(self, u, v):
+ """Converts from spherical coordinates to cartesian.
+ Parameters
+ ---------
+ u : :class:`float`
+ The radius.
+ v : :class:`float`
+ The azimuthal angle.
+ """
+ r = u
+ phi = v
+ return np.array(
+ [
+ r * np.sin(self.theta) * np.cos(phi),
+ r * np.sin(self.theta) * np.sin(phi),
+ r * np.cos(self.theta),
+ ]
+ )
+
+ def _rotate_to_direction(self):
+ x, y, z = self.direction
+
+ r = np.sqrt(x ** 2 + y ** 2 + z ** 2)
+ theta = np.arccos(z / r)
+
+ if x == 0:
+ if y == 0: # along the z axis
+ phi = 0
+ else:
+ phi = np.arctan(np.inf)
+ if y < 0:
+ phi += PI
+ else:
+ phi = np.arctan(y / x)
+ if x < 0:
+ phi += PI
+
+ # Undo old rotation (in reverse order)
+ self.rotate(-self._current_phi, Z_AXIS, about_point=ORIGIN)
+ self.rotate(-self._current_theta, Y_AXIS, about_point=ORIGIN)
+
+ # Do new rotation
+ self.rotate(theta, Y_AXIS, about_point=ORIGIN)
+ self.rotate(phi, Z_AXIS, about_point=ORIGIN)
+
+ # Store values
+ self._current_theta = theta
+ self._current_phi = phi
+
+ def set_direction(self, direction):
+ self.direction = direction
+ self._rotate_to_direction()
+
+ def get_direction(self):
+ return self.direction
+
+
+class Cylinder(ParametricSurface):
+ """A cylinder, defined by its height, radius and direction,
+
+ Examples
+ ---------
+ .. manim:: ExampleCylinder
+ :save_last_frame:
+
+ class ExampleCylinder(ThreeDScene):
+ def construct(self):
+ axes = ThreeDAxes()
+ cylinder = Cylinder(radius=2, height=3)
+ self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES)
+ self.add(axes, cylinder)
+
+ Parameters
+ ---------
+ radius : :class:`float`
+ The radius of the cylinder.
+ height : :class:`float`
+ The height of the cylinder.
+ direction : :class:`numpy.array`
+ The direction of the central axis of the cylinder.
+ v_min : :class:`float`
+ The height along the height axis (given by direction) to start on.
+ v_max : :class:`float`
+ The height along the height axis (given by direction) to end on.
+ show_ends : :class:`bool`
+ Whether to show the end caps or not.
+ """
+
+ def __init__(
+ self,
+ radius=1,
+ height=2,
+ direction=Z_AXIS,
+ v_min=0,
+ v_max=TAU,
+ show_ends=True,
+ resolution=24,
+ **kwargs
+ ):
+ self._height = height
+ self.radius = radius
+ ParametricSurface.__init__(
+ self,
+ self.func,
+ resolution=resolution,
+ u_min=-self._height / 2,
+ u_max=self._height / 2,
+ v_min=v_min,
+ v_max=v_max,
+ **kwargs,
+ )
+ if show_ends:
+ self.add_bases()
+ self._current_phi = 0
+ self._current_theta = 0
+ self.set_direction(direction)
+
+ def func(self, u, v):
+ """Converts from cylindrical coordinates to cartesian.
+ Parameters
+ ---------
+ u : :class:`float`
+ The height.
+ v : :class:`float`
+ The azimuthal angle.
+ """
+ height = u
+ phi = v
+ r = self.radius
+ return np.array([r * np.cos(phi), r * np.sin(phi), height])
+
+ def add_bases(self):
+ """Adds the end caps of the cylinder."""
+ self.base_top = Circle(
+ radius=self.radius,
+ color=self.fill_color,
+ fill_opacity=self.fill_opacity,
+ shade_in_3d=True,
+ stroke_width=0,
+ )
+ self.base_top.shift(self.u_max * IN)
+ self.base_bottom = Circle(
+ radius=self.radius,
+ color=self.fill_color,
+ fill_opacity=self.fill_opacity,
+ shade_in_3d=True,
+ stroke_width=0,
+ )
+ self.base_bottom.shift(self.u_min * IN)
+ self.add(self.base_top, self.base_bottom)
+
+ def _rotate_to_direction(self):
+ x, y, z = self.direction
+
+ r = np.sqrt(x ** 2 + y ** 2 + z ** 2)
+ theta = np.arccos(z / r)
+
+ if x == 0:
+ if y == 0: # along the z axis
+ phi = 0
+ else: # along the x axis
+ phi = np.arctan(np.inf)
+ if y < 0:
+ phi += PI
+ else:
+ phi = np.arctan(y / x)
+ if x < 0:
+ phi += PI
+
+ # undo old rotation (in reverse direction)
+ self.rotate(-self._current_phi, Z_AXIS, about_point=ORIGIN)
+ self.rotate(-self._current_theta, Y_AXIS, about_point=ORIGIN)
+
+ # do new rotation
+ self.rotate(theta, Y_AXIS, about_point=ORIGIN)
+ self.rotate(phi, Z_AXIS, about_point=ORIGIN)
+
+ # store new values
+ self._current_theta = theta
+ self._current_phi = phi
+
+ def set_direction(self, direction):
+ # if get_norm(direction) is get_norm(self.direction):
+ # pass
+ self.direction = direction
+ self._rotate_to_direction()
+
+ def get_direction(self):
+ return self.direction
+
+
+class Line3D(Cylinder):
+ """A cylindrical line, for use in ThreeDScene.
+
+ Examples
+ ---------
+ .. manim:: ExampleLine3D
+ :save_last_frame:
+
+ class ExampleLine3D(ThreeDScene):
+ def construct(self):
+ axes = ThreeDAxes()
+ line = Line3D(start=np.array([0, 0, 0]), end=np.array([2, 2, 2]))
+ self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES)
+ self.add(axes, line)
+
+ Parameters
+ ---------
+ start : :class:`numpy.array`
+ The start position of the line.
+ end : :class:`numpy.array`
+ The end position of the line.
+ thickness : :class:`float`
+ The thickness of the line.
+ """
+
+ def __init__(self, start=LEFT, end=RIGHT, thickness=0.02, color=None, **kwargs):
+ self.thickness = thickness
+ self.set_start_and_end_attrs(start, end, **kwargs)
+ if color is not None:
+ self.set_color(color)
+
+ def set_start_and_end_attrs(self, start, end, **kwargs):
+ """Sets the start and end points of the line.
+
+ If either ``start`` or ``end`` are :class:`~.Mobject`s, this gives their centers.
+ """
+ rough_start = self.pointify(start)
+ rough_end = self.pointify(end)
+ self.vect = rough_end - rough_start
+ self.length = get_norm(self.vect)
+ self.direction = normalize(self.vect)
+ # Now that we know the direction between them,
+ # we can the appropriate boundary point from
+ # start and end, if they're mobjects
+ self.start = self.pointify(start, self.direction)
+ self.end = self.pointify(end, -self.direction)
+ Cylinder.__init__(
+ self,
+ height=get_norm(self.vect),
+ radius=self.thickness,
+ direction=self.direction,
+ **kwargs,
+ )
+ self.shift((self.start + self.end) / 2)
+
+ def pointify(self, mob_or_point, direction=None):
+ if isinstance(mob_or_point, Mobject):
+ mob = mob_or_point
+ if direction is None:
+ return mob.get_center()
+ else:
+ return mob.get_boundary_point(direction)
+ return np.array(mob_or_point)
+
+ def get_start(self):
+ return self.start
+
+ def get_end(self):
+ return self.end
+
+
+class Arrow3D(Line3D):
+ """An arrow made out of a cylindrical line and a conical tip.
+
+ Examples
+ ---------
+ .. manim:: ExampleArrow3D
+ :save_last_frame:
+
+ class ExampleArrow3D(ThreeDScene):
+ def construct(self):
+ axes = ThreeDAxes()
+ arrow = Arrow3D(start=np.array([0, 0, 0]), end=np.array([2, 2, 2]))
+ self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES)
+ self.add(axes, arrow)
+
+ Parameters
+ ---------
+ start : :class:`numpy.array`
+ The start position of the arrow.
+ end : :class:`numpy.array`
+ The end position of the arrow.
+ thickness : :class:`float`
+ The thickness of the arrow.
+ height : :class:`float`
+ The height of the conical tip.
+ base_radius: :class:`float`
+ The base radius of the conical tip.
+ """
+
+ def __init__(
+ self,
+ start=LEFT,
+ end=RIGHT,
+ thickness=0.02,
+ height=0.5,
+ base_radius=0.25,
+ color=WHITE,
+ **kwargs
+ ):
+ Line3D.__init__(self, start=start, end=end, **kwargs)
+
+ self.length = get_norm(self.vect)
+ self.set_start_and_end_attrs(
+ self.start,
+ self.end - height * self.direction,
+ thickness=thickness,
+ **kwargs,
+ )
+
+ self.cone = Cone(
+ direction=self.direction, base_radius=base_radius, height=height, **kwargs
+ )
+ self.cone.shift(end)
+ self.add(self.cone)
+ self.set_color(color)
+
+
+class Torus(ParametricSurface):
+ """A torus.
+
+ Examples
+ ---------
+ .. manim :: ExampleTorus
+ :save_last_frame:
+
+ class ExampleTorus(ThreeDScene):
+ def construct(self):
+ axes = ThreeDAxes()
+ torus = Torus()
+ self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES)
+ self.add(axes, torus)
+
+ Parameters
+ ---------
+ major_radius : :class:`float`
+ Distance from the center of the tube to the center of the torus.
+ minor_radius : :class:`float`
+ Radius of the tube.
+ """
+
+ def __init__(
+ self,
+ major_radius=3,
+ minor_radius=1,
+ u_min=0,
+ u_max=TAU,
+ v_min=0,
+ v_max=TAU,
+ resolution=24,
+ **kwargs
+ ):
+ self.R = major_radius
+ self.r = minor_radius
+ ParametricSurface.__init__(
+ self,
+ self.func,
+ u_min=u_min,
+ u_max=u_max,
+ v_min=v_min,
+ v_max=v_max,
+ resolution=resolution,
+ **kwargs,
+ )
+
+ def func(self, u, v):
+ P = np.array([np.cos(u), np.sin(u), 0])
+ return (self.R - self.r * np.cos(v)) * P - np.sin(v) * OUT
diff --git a/tests/control_data/graphical_units_data/threed/Arrow3DTest.npz b/tests/control_data/graphical_units_data/threed/Arrow3DTest.npz
new file mode 100644
index 000000000..f1e0721a9
Binary files /dev/null and b/tests/control_data/graphical_units_data/threed/Arrow3DTest.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/ConeTest.npz b/tests/control_data/graphical_units_data/threed/ConeTest.npz
new file mode 100644
index 000000000..64fd64381
Binary files /dev/null and b/tests/control_data/graphical_units_data/threed/ConeTest.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/CylinderTest.npz b/tests/control_data/graphical_units_data/threed/CylinderTest.npz
new file mode 100644
index 000000000..7898966cb
Binary files /dev/null and b/tests/control_data/graphical_units_data/threed/CylinderTest.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/Line3DTest.npz b/tests/control_data/graphical_units_data/threed/Line3DTest.npz
new file mode 100644
index 000000000..275fad16a
Binary files /dev/null and b/tests/control_data/graphical_units_data/threed/Line3DTest.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/TorusTest.npz b/tests/control_data/graphical_units_data/threed/TorusTest.npz
new file mode 100644
index 000000000..f9c4673af
Binary files /dev/null and b/tests/control_data/graphical_units_data/threed/TorusTest.npz differ
diff --git a/tests/test_graphical_units/test_threed.py b/tests/test_graphical_units/test_threed.py
index 8068a7323..b48b4d401 100644
--- a/tests/test_graphical_units/test_threed.py
+++ b/tests/test_graphical_units/test_threed.py
@@ -15,6 +15,31 @@ class SphereTest(ThreeDScene):
self.play(Animation(Sphere()))
+class ConeTest(ThreeDScene):
+ def construct(self):
+ self.play(Animation(Cone()))
+
+
+class CylinderTest(ThreeDScene):
+ def construct(self):
+ self.play(Animation(Cylinder()))
+
+
+class Line3DTest(ThreeDScene):
+ def construct(self):
+ self.play(Animation(Line3D()))
+
+
+class Arrow3DTest(ThreeDScene):
+ def construct(self):
+ self.play(Animation(Arrow3D()))
+
+
+class TorusTest(ThreeDScene):
+ def construct(self):
+ self.play(Animation(Torus()))
+
+
class AxesTest(ThreeDScene):
def construct(self):
self.play(Animation(ThreeDAxes()))