Coverage for src/manimgx/mobjects/three_d.py: 98%

368 statements  

« 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 

5 

6"""Ported from Manim CE 0.21 (MIT).""" 

7 

8from __future__ import annotations 

9 

10import functools 

11import warnings 

12from warnings import deprecated 

13 

14__all__ = [ 

15 "Arrow3D", 

16 "Cone", 

17 "ConvexHull3D", 

18 "Cube", 

19 "Cylinder", 

20 "Dodecahedron", 

21 "Dot3D", 

22 "Icosahedron", 

23 "Line3D", 

24 "Octahedron", 

25 "Polyhedron", 

26 "Prism", 

27 "Sphere", 

28 "Surface", 

29 "Tetrahedron", 

30 "ThreeDVMobject", 

31 "Torus", 

32] 

33from collections.abc import Callable, Hashable, Iterable, Sequence 

34from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpack 

35 

36import numpy as np 

37from typing_extensions import TypedDict 

38 

39from manimgx.caches import forgets 

40from manimgx.constants import ( 

41 DEFAULT_DOT_RADIUS, 

42 DOWN, 

43 IN, 

44 LEFT, 

45 ORIGIN, 

46 OUT, 

47 PI, 

48 RIGHT, 

49 TAU, 

50 UP, 

51 Y_AXIS, 

52 Z_AXIS, 

53 LineJointType, 

54) 

55from manimgx.drawing.geometry import ( 

56 Lattice, 

57 QuickHull, 

58 normalize, 

59 perpendicular_bisector, 

60 rotation_about_z, 

61 rotation_matrix, 

62 sample, 

63 z_to_vector, 

64) 

65from manimgx.drawing.paint import ( 

66 BLUE, 

67 BLUE_D, 

68 BLUE_E, 

69 LIGHT_GREY, 

70 WHITE, 

71 Colorscale, 

72 ManimColor, 

73 ParsableManimColor, 

74 Style, 

75 _paired, 

76 _Style, 

77 rgbas_by_value, 

78) 

79from manimgx.mobject import MeshMobject, Mobject, VectorizedPoint, VGroup, VMobject 

80from manimgx.mobjects.graph import Graph, GraphOptions 

81from manimgx.mobjects.shapes import Circle, Polygon, Square 

82 

83if TYPE_CHECKING: 

84 from manimgx.mobjects.plotting import ThreeDAxes 

85 from manimgx.typing import ( 

86 Point3D, 

87 Point3DLike, 

88 Point3DLike_Array, 

89 Vector3D, 

90 Vector3DLike, 

91 ) 

92 

93 

94@deprecated( 

95 "ThreeDVMobject(...) is VMobject(..., shade_in_3d=True): use it", category=None 

96) 

97class ThreeDVMobject(VMobject): 

98 """A path shaded by a three-dimensional scene's light: a 

99 [VMobject][manimgx.VMobject] with `shade_in_3d` on. 

100 

101 It takes a VMobject's arguments. Give it points in three dimensions (with 

102 `set_points_as_corners`, `set_points_smoothly`, …) to draw a curve through space 

103 that the light shades as it does the other three-dimensional objects. 

104 """ 

105 

106 # u_index … v2: a surface face's place in its (u, v) grid; nothing sets them (a 

107 # Surface is one mesh, not faces of this class) 

108 defaults: ClassVar[Style] = {"shade_in_3d": True} 

109 u_index: int 

110 v_index: int 

111 u1: float 

112 u2: float 

113 v1: float 

114 v2: float 

115 

116 

117class _SurfaceLook(_Style, total=False): 

118 """SurfaceLook's keys, open, for the keywords that add to them.""" 

119 

120 surface_piece_config: Style | None 

121 """Accepted for Manim compatibility; ignored.""" 

122 checkerboard_colors: Iterable[ParsableManimColor] | Literal[False] 

123 """The colors the faces are checkered with, in turn along both u and v (default 

124 `BLUE_D` and `BLUE_E`, a cone's False; False: the fill color alone).""" 

125 should_make_jagged: bool 

126 """Accepted for Manim compatibility; ignored.""" 

127 pre_function_handle_to_anchor_scale_factor: float 

128 """Accepted for Manim compatibility; ignored.""" 

129 

130 

131class SurfaceLook(_SurfaceLook, total=False, closed=True): 

132 """A [Surface][manimgx.Surface]'s keywords but its function, ranges and resolution, 

133 for the shapes that set those (spheres, cylinders, …): its checkerboard, with the 

134 style keywords.""" 

135 

136 

137class SurfaceOptions(_SurfaceLook, total=False, closed=True): 

138 """A [Surface][manimgx.Surface]'s keywords but its function and ranges, for the 

139 shapes that pass them on ([Cone][manimgx.Cone]): its resolution and checkerboard, 

140 with the style keywords.""" 

141 

142 resolution: int | Sequence[int] 

143 """How many faces the surface has along u and along v: one positive integer for 

144 both, or a pair of positive integers `(u, v)` (default 32).""" 

145 

146 

147_COLORMAP_TEXELS = 256 # a colorscale's samples along the value, as a texture 

148 

149 

150@forgets 

151@functools.cache 

152def _checkerboard( 

153 palette: tuple[tuple[float, float, float, float], ...], 

154 u_count: int, 

155 v_count: int, 

156 opacity: float, 

157) -> np.ndarray: 

158 """A checkerboard's rows — one color per cell: a value of its palette, 

159 grid and opacity.""" 

160 k = np.arange(u_count * v_count) 

161 rows = np.array(palette)[(k // v_count + k % v_count) % len(palette)] 

162 rows[:, 3] = opacity 

163 rows.flags.writeable = False 

164 return rows 

165 

166 

167class Surface(MeshMobject): 

168 """A parametric surface: the points `func(u, v)` for u and v over their ranges, 

169 drawn as the smooth surface through them; checkered in two blues, with thin light 

170 grey edges, and shaded by a three-dimensional scene's light, unless styled. 

171 

172 The ranges are divided into `resolution` steps, along u and along v, and the 

173 function is sampled at the corners of the grid's cells, the surface's faces. What is 

174 drawn is the smooth surface through those samples, not flat faces: `resolution` sets 

175 how closely it follows the function, and the light shades it smoothly, across the 

176 seam too where the surface closes on itself (a sphere, a torus, a cylinder). Each 

177 face keeps its own colors, so a checkerboard keeps sharp cells, and the stroke draws 

178 the faces' edges, curved with the surface. The faces are one mesh (a 

179 [MeshMobject][manimgx.MeshMobject]): it morphs into other meshes (drawn as flat 

180 faces while it morphs into one of another grid), and [Create][manimgx.Create] draws 

181 it in face by face, each face with its edges. 

182 [set_fill_by_checkerboard][manimgx.Surface.set_fill_by_checkerboard] and 

183 [set_fill_by_value][manimgx.Surface.set_fill_by_value] color it. 

184 

185 The checkerboard palette supplies the initial paint; use 

186 [set_fill_by_checkerboard][manimgx.Surface.set_fill_by_checkerboard] to recolor 

187 the surface later. The initial palette and ignored compatibility options are 

188 not retained as instance attributes. 

189 

190 Args: 

191 func: The function, from (u, v) to a point in scene coordinates (on axes, their 

192 [c2p][manimgx.Axes.coords_to_point] of coordinates). 

193 u_range: The range of u, `(u_min, u_max)`. 

194 v_range: The range of v, `(v_min, v_max)`. 

195 resolution: How many faces the surface has along u and along v: one positive 

196 integer for both, or a pair of positive integers `(u, v)`. 

197 surface_piece_config: Accepted for Manim compatibility; ignored. 

198 checkerboard_colors: The initial checkerboard colors, in turn; False for the 

199 fill color alone. 

200 should_make_jagged: Accepted for Manim compatibility; ignored. 

201 pre_function_handle_to_anchor_scale_factor: Accepted for Manim compatibility; 

202 ignored. 

203 

204 Examples: 

205 ```python 

206 import numpy as np 

207 

208 import manimgx as m 

209 

210 

211 class SurfaceExample(m.ThreeDScene): 

212 def construct(self) -> None: 

213 self.set_camera_orientation(phi=60 * m.DEGREES, theta=-60 * m.DEGREES) 

214 

215 def mobius(u: float, v: float) -> np.ndarray: 

216 r = 2.5 + v * np.cos(u / 2) 

217 return np.array([r * np.cos(u), r * np.sin(u), v * np.sin(u / 2)]) 

218 

219 strip = m.Surface( 

220 mobius, u_range=(0, m.TAU), v_range=(-1, 1), resolution=(48, 6) 

221 ) 

222 self.add(strip) 

223 ``` 

224 """ 

225 

226 # one mesh, func(u, v) sampled over a grid of faces, drawn as the C² cubic spline 

227 # through its samples (see `feed.refine_surface`: periodic along a direction whose 

228 # ends meet, not-a-knot otherwise). Paint belongs to lattice cells; the renderer 

229 # derives their independently colored blocks and edge loops. Unequal lattices 

230 # align as explicit triangle soup. 

231 defaults: ClassVar[Style] = { 

232 "fill_color": BLUE_D, 

233 "fill_opacity": 1.0, 

234 "stroke_color": LIGHT_GREY, 

235 "stroke_width": 0.5, 

236 "stroke_opacity": 1.0, 

237 "shade_in_3d": True, 

238 } 

239 

240 def __init__( 

241 self, 

242 func: Callable[[float, float], np.ndarray], 

243 u_range: Sequence[float] = (0, 1), 

244 v_range: Sequence[float] = (0, 1), 

245 resolution: int | Sequence[int] = 32, 

246 surface_piece_config: Style | None = None, 

247 checkerboard_colors: Iterable[ParsableManimColor] | Literal[False] = ( 

248 BLUE_D, 

249 BLUE_E, 

250 ), 

251 should_make_jagged: bool = False, 

252 pre_function_handle_to_anchor_scale_factor: float = 1e-05, 

253 **kwargs: Unpack[Style], 

254 ) -> None: 

255 self.u_range = list(u_range) # values, as they are given 

256 self.v_range = list(v_range) 

257 self.resolution = resolution 

258 colors: list[ManimColor] | Literal[False] = ( 

259 False 

260 if checkerboard_colors is False 

261 else [ManimColor(c) for c in checkerboard_colors] 

262 ) 

263 self._func = func 

264 super().__init__(**kwargs) 

265 if colors: 

266 self.set_fill_by_checkerboard(*colors) 

267 

268 def func(self, u: float, v: float) -> np.ndarray: 

269 """The surface's point at (u, v): its function's value. 

270 

271 Args: 

272 u: The first parameter. 

273 v: The second parameter. 

274 

275 Returns: 

276 The point, in scene coordinates, as the surface was made (before it was 

277 moved). 

278 """ 

279 return self._func(u, v) 

280 

281 def generate_points(self) -> Self: 

282 u_res, v_res = ( 

283 (self.resolution, self.resolution) 

284 if isinstance(self.resolution, int) 

285 else self.resolution 

286 ) 

287 if u_res <= 0 or v_res <= 0: 

288 raise ValueError("Surface resolution must be positive in both directions") 

289 u = np.linspace(self.u_range[0], self.u_range[1], u_res + 1) 

290 v = np.linspace(self.v_range[0], self.v_range[1], v_res + 1) 

291 grid = sample(self.func, *np.meshgrid(u, v, indexing="ij")) 

292 self.points = grid.reshape(-1, 3) 

293 self._topology = Lattice.of(len(u) - 1, len(v) - 1) 

294 self.uvs = None 

295 return self 

296 

297 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

298 def face_indices(self) -> tuple[np.ndarray, np.ndarray]: 

299 """The place of every face in the surface's grid: its index along u and its 

300 index along v, in the mesh's order. 

301 

302 Returns: 

303 Two arrays, the faces' indices along u and along v. 

304 """ 

305 grid = self.grid 

306 if grid is None: 

307 raise ValueError("Checkerboard cells require lattice topology") 

308 u, v = grid 

309 k = np.arange(u * v) 

310 return k // v, k % v 

311 

312 def _paint_faces(self, colors: np.ndarray, opacity: float | None) -> Self: 

313 """One color per cell — (cells, 4) RGBA; opacity as given, else 

314 as it was.""" 

315 rows = colors.copy() 

316 rows[:, 3] = self._opacity(opacity, len(rows)) 

317 return self._fill_rows(rows) 

318 

319 def _fill_rows(self, rows: np.ndarray) -> Self: 

320 """Colors as the surface's fill, in place of a colormap.""" 

321 self.paint = self.paint.but(fill=rows, texture=None, colormap=False) 

322 return self 

323 

324 def _opacity(self, opacity: float | None, count: int) -> float | np.ndarray: 

325 """The opacity faces are painted with: as given, else as it was (per cell, or one).""" 

326 current = self.paint.fill 

327 if opacity is not None: 

328 return opacity 

329 return current[:, 3] if len(current) == count else float(current[0, 3]) 

330 

331 def set_fill_by_checkerboard( 

332 self, *colors: ParsableManimColor, opacity: float | None = None 

333 ) -> Self: 

334 """Color the faces like a checkerboard: the colors in turn, along u and along v. 

335 

336 The face at place (i, j) of the grid takes the color i + j places along 

337 `colors`, cycling: two colors make a checkerboard, more make diagonal stripes. 

338 It replaces the colors [set_fill_by_value][manimgx.Surface.set_fill_by_value] 

339 gave. 

340 

341 Args: 

342 *colors: The colors, in turn. 

343 opacity: The faces' opacity, from 0 to 1; None to keep theirs. 

344 """ 

345 palette = tuple(tuple(ManimColor(c).to_rgba()) for c in colors) 

346 grid = self.grid 

347 if grid is None: 

348 raise ValueError("Checkerboard cells require lattice topology") 

349 alpha = self._opacity(opacity, grid[0] * grid[1]) 

350 # one opacity: the checkerboard is a value, made once 

351 if isinstance(alpha, float): 

352 return self._fill_rows(_checkerboard(palette, *grid, alpha)) 

353 i, j = self.face_indices() 

354 return self._paint_faces(np.array(palette)[(i + j) % len(palette)], opacity) 

355 

356 def set_fill_by_value( 

357 self, 

358 axes: ThreeDAxes, 

359 colorscale: Colorscale | None = None, 

360 axis: int = 2, 

361 colors: Colorscale | None = None, 

362 ) -> Self: 

363 """Color the surface point by point by a coordinate on axes: its height, z, by 

364 default, on a colorscale. 

365 

366 Each sample of the surface has its coordinate along `axis`, and the values are 

367 blended across the surface before the colorscale maps them: the colors follow 

368 the surface smoothly, and a face whose corners straddle a color of the scale 

369 shows it. The colors are the fill's, lit as a fill color is, at the fill's 

370 opacity: a fill color set later ([set_fill][manimgx.Mobject.set_fill], 

371 [set_color][manimgx.Mobject.set_color]) replaces them, as 

372 [set_fill_by_checkerboard][manimgx.Surface.set_fill_by_checkerboard] does. 

373 Without a colorscale, it warns and leaves the colors as they are. 

374 

375 Args: 

376 axes: The axes whose coordinates color the surface. 

377 colorscale: The colors: spread evenly over the axes' range along `axis`, or 

378 `(color, value)` pairs, which span their own values; blended between, 

379 and held beyond the ends. 

380 axis: The coordinate: 0 for x, 1 for y, 2 for z. 

381 colors: The colorscale by its older name, accepted for Manim compatibility: 

382 used when `colorscale` is None. 

383 

384 Examples: 

385 ```python 

386 import numpy as np 

387 

388 import manimgx as m 

389 

390 

391 class SurfaceSetFillByValueExample(m.ThreeDScene): 

392 def construct(self) -> None: 

393 self.set_camera_orientation( 

394 phi=65 * m.DEGREES, theta=-130 * m.DEGREES 

395 ) 

396 axes = m.ThreeDAxes( 

397 x_range=(0, 5), 

398 y_range=(0, 5), 

399 z_range=(-1, 1, 0.5), 

400 x_length=7, 

401 y_length=7, 

402 z_length=3, 

403 ) 

404 surface = m.Surface( 

405 lambda u, v: axes.c2p(u, v, np.sin(u) * np.cos(v)), 

406 u_range=(0, 5), 

407 v_range=(0, 5), 

408 resolution=8, 

409 ) 

410 surface.set_fill_by_value( 

411 axes, colorscale=[(m.RED, -0.5), (m.YELLOW, 0), (m.GREEN, 0.5)] 

412 ) 

413 self.add(axes, surface) 

414 ``` 

415 """ 

416 # the colorscale is a texture along the value (a colormap) and each sample's 

417 # value its coordinate: values are interpolated over the surface before they are 

418 # mapped 

419 colorscale = colorscale if colorscale is not None else colors 

420 if colorscale is None: 

421 warnings.warn( 

422 "The value passed to the colorscale keyword argument was None, the" 

423 " surface fill color has not been changed", 

424 stacklevel=2, 

425 ) 

426 return self 

427 low, high = (axes.x_range, axes.y_range, axes.z_range or (0, 0))[axis][:2] 

428 if _paired(colorscale): 

429 pivots = [p for _, p in colorscale] 

430 low, high = min(pivots), max(pivots) 

431 values = np.asarray(axes.point_to_coords(self.points), dtype=float)[:, axis] 

432 span = high - low if high > low else 1.0 

433 n = _COLORMAP_TEXELS 

434 ramp = rgbas_by_value(colorscale, np.linspace(low, high, n), low, high) 

435 colormap = (ramp[None] * 255).round().astype(np.uint8) 

436 colormap[..., 3] = 255 

437 colormap.flags.writeable = False 

438 # texel centers: the ends hold beyond them 

439 u = (0.5 + np.clip((values - low) / span, 0.0, 1.0) * (n - 1)) / n 

440 self.uvs = np.stack([u, np.full_like(u, 0.5)], axis=1) 

441 grid = self.grid 

442 count = len(self.points) if grid is None else grid[0] * grid[1] 

443 alpha = self._opacity(None, count) 

444 fill = np.ones((1 if isinstance(alpha, float) else count, 4)) 

445 fill[:, 3] = alpha 

446 self.paint = self.paint.but(fill=fill, texture=colormap, colormap=True) 

447 return self 

448 

449 

450def _revolve( 

451 radius: float | np.ndarray, 

452 height: float | np.ndarray, 

453 angle: float | np.ndarray, 

454) -> np.ndarray: 

455 """Turn a radial profile about z, at one angle or a grid of angles.""" 

456 return np.array([radius * np.cos(angle), radius * np.sin(angle), height]) 

457 

458 

459class Sphere(Surface): 

460 """A sphere: checkered in two blues and shaded by a three-dimensional scene's light, 

461 unless styled. 

462 

463 It is a [Surface][manimgx.Surface] of u, the longitude, and v, the angle from the 

464 south pole (the bottom, along z): their ranges may cut out a part of it. 

465 

466 Args: 

467 center: Where its center goes. 

468 radius: Its radius, in scene units. 

469 resolution: How many faces it has around and from pole to pole: one number for 

470 both, or `(u, v)`; None for (24, 12). 

471 u_range: The range of the longitude, in radians: (0, τ) goes all the way 

472 around. 

473 v_range: The range of the angle from the south pole, in radians: (0, π) goes 

474 from pole to pole. 

475 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceLook]: 

476 `checkerboard_colors`, and the style keywords. 

477 

478 Examples: 

479 ```python 

480 import manimgx as m 

481 

482 

483 class SphereExample(m.ThreeDScene): 

484 def construct(self) -> None: 

485 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-90 * m.DEGREES) 

486 self.add( 

487 m.Sphere(center=(-4, 0, 0), radius=1.5), 

488 m.Sphere(radius=1.5, resolution=(12, 6)).set_color(m.GREEN), 

489 m.Sphere( 

490 center=(4, 0, 0), 

491 radius=1.5, 

492 v_range=(0, m.PI / 2), 

493 checkerboard_colors=[m.RED, m.YELLOW], 

494 ), 

495 ) 

496 ``` 

497 """ 

498 

499 def __init__( 

500 self, 

501 center: Point3DLike = ORIGIN, 

502 radius: float = 1, 

503 resolution: int | Sequence[int] | None = None, 

504 u_range: Sequence[float] = (0, TAU), 

505 v_range: Sequence[float] = (0, PI), 

506 **kwargs: Unpack[SurfaceLook], 

507 ) -> None: 

508 self.radius = radius 

509 super().__init__( 

510 self.func, 

511 resolution=resolution if resolution is not None else (24, 12), 

512 u_range=u_range, 

513 v_range=v_range, 

514 **kwargs, 

515 ) 

516 self.shift(center) 

517 

518 def func(self, u: float, v: float) -> Point3D: 

519 """The sphere's point at a longitude and an angle from its south pole, as it is 

520 made around the origin. 

521 

522 Args: 

523 u: The longitude, in radians, counterclockwise from the x-axis. 

524 v: The angle from the south pole, in radians: 0 at the bottom, π at the 

525 top. 

526 

527 Returns: 

528 The point, relative to the sphere's center. 

529 """ 

530 return self.radius * _revolve(np.sin(v), -np.cos(v), u) 

531 

532 

533class Dot3D(Sphere): 

534 """A dot in three dimensions: a small sphere, white unless given a color. 

535 

536 Args: 

537 point: Where its center goes. 

538 radius: Its radius, in scene units. 

539 resolution: How many faces it has around and from pole to pole: one number for 

540 both, or `(u, v)`; None for (24, 12). 

541 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceLook]: 

542 `color` paints it all in one color; the style keywords. 

543 

544 Examples: 

545 ```python 

546 import manimgx as m 

547 

548 

549 class Dot3DExample(m.ThreeDScene): 

550 def construct(self) -> None: 

551 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-45 * m.DEGREES) 

552 axes = m.ThreeDAxes(x_range=(-3, 3), y_range=(-3, 3), z_range=(-2, 2)) 

553 self.add( 

554 axes, 

555 m.Dot3D(axes.c2p(0, 0, 1.5), radius=0.2, color=m.RED), 

556 m.Dot3D(axes.c2p(2, 0, 0), radius=0.2, color=m.BLUE), 

557 m.Dot3D(axes.c2p(0, 2, 0), radius=0.2, color=m.YELLOW), 

558 ) 

559 ``` 

560 """ 

561 

562 def __init__( 

563 self, 

564 point: Point3DLike = ORIGIN, 

565 radius: float = DEFAULT_DOT_RADIUS, 

566 resolution: int | tuple[int, int] | None = (8, 8), 

567 **kwargs: Unpack[SurfaceLook], 

568 ) -> None: 

569 color = kwargs.pop("color", None) or WHITE # one color, over the checkerboard 

570 super().__init__(center=point, radius=radius, resolution=resolution, **kwargs) 

571 self.set_color(color) 

572 

573 

574class Cube(VGroup): 

575 """A cube: six square faces, centered at the origin with its edges along the axes; 

576 blue, three-quarters opaque, without edges and shaded by a three-dimensional 

577 scene's light, unless styled. 

578 

579 Args: 

580 side_length: The length of its edges, in scene units. 

581 **kwargs: [Style keywords][manimgx.drawing.paint.Style] for its faces. 

582 

583 Examples: 

584 ```python 

585 import manimgx as m 

586 

587 

588 class CubeExample(m.ThreeDScene): 

589 def construct(self) -> None: 

590 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-45 * m.DEGREES) 

591 cubes = m.Group( 

592 m.Cube(), 

593 m.Cube(side_length=3, fill_color=m.TEAL, fill_opacity=1), 

594 m.Cube(fill_opacity=0.3, stroke_width=2, stroke_color=m.YELLOW), 

595 ).arrange(buff=1.5) 

596 self.add(cubes) 

597 ``` 

598 """ 

599 

600 defaults: ClassVar[Style] = { 

601 "fill_opacity": 0.75, 

602 "fill_color": BLUE, 

603 "stroke_width": 0, 

604 } 

605 

606 def __init__(self, side_length: float = 2, **kwargs: Unpack[Style]) -> None: 

607 self.side_length = side_length 

608 super().__init__(**kwargs) 

609 

610 def generate_points(self) -> Self: 

611 for vect in (IN, OUT, LEFT, RIGHT, UP, DOWN): 

612 face = Square( 

613 side_length=self.side_length, 

614 shade_in_3d=True, 

615 joint_type=LineJointType.BEVEL, 

616 ) 

617 face.flip() 

618 face.shift(self.side_length * OUT / 2.0) 

619 face.apply_matrix(z_to_vector(vect)) 

620 self.add(face) 

621 return self 

622 

623 

624class Prism(Cube): 

625 """A box: a [Cube][manimgx.Cube] stretched to its width, height and depth; blue, 

626 three-quarters opaque, without edges and shaded by a three-dimensional scene's 

627 light, unless styled. 

628 

629 Args: 

630 dimensions: Its size along x, y and z, in scene units; None for (3, 2, 1). 

631 **kwargs: [Style keywords][manimgx.drawing.paint.Style] for its faces. 

632 

633 Examples: 

634 ```python 

635 import manimgx as m 

636 

637 

638 class PrismExample(m.ThreeDScene): 

639 def construct(self) -> None: 

640 self.set_camera_orientation(phi=60 * m.DEGREES, theta=-60 * m.DEGREES) 

641 prisms = m.Group( 

642 m.Prism(), 

643 m.Prism(dimensions=[1, 2, 3], fill_color=m.GREEN), 

644 ).arrange(buff=1.5) 

645 self.add(prisms) 

646 ``` 

647 """ 

648 

649 def __init__( 

650 self, dimensions: Vector3DLike | None = None, **kwargs: Unpack[Style] 

651 ) -> None: 

652 self.dimensions = ( 

653 [3.0, 2.0, 1.0] if dimensions is None else [float(d) for d in dimensions] 

654 ) 

655 super().__init__(**kwargs) 

656 

657 def generate_points(self) -> Self: 

658 super().generate_points() 

659 for dim, value in enumerate(self.dimensions): 

660 self.rescale_to_fit(value, dim, stretch=True) 

661 return self 

662 

663 

664class _DirectedSurface(Surface): 

665 direction: Vector3D 

666 _current_theta: float 

667 _current_phi: float 

668 

669 def set_direction(self, direction: Vector3DLike) -> Self: 

670 """Turn the surface's axis to a direction, undoing its previous direction. 

671 

672 Both turns are about the origin, preserving other changes to the surface. 

673 

674 Args: 

675 direction: The direction of the axis, from a cone's base to its apex. 

676 """ 

677 self.direction = np.array(direction, dtype=float) 

678 x, y, z = self.direction 

679 r = np.sqrt(x**2 + y**2 + z**2) 

680 theta = float(np.arccos(z / r)) if r > 0 else 0.0 

681 if x == 0: 

682 phi = 0.0 if y == 0 else float(np.arctan(np.inf)) + (PI if y < 0 else 0) 

683 else: 

684 phi = float(np.arctan(y / x)) 

685 if x < 0: 

686 phi += PI 

687 turn = ( 

688 rotation_about_z(phi) 

689 @ rotation_matrix(theta - self._current_theta, Y_AXIS) 

690 @ rotation_about_z(-self._current_phi) 

691 ) 

692 self._rotate_direction_state(turn) 

693 self._apply_linear(turn, ORIGIN) 

694 self._current_theta, self._current_phi = theta, phi 

695 return self 

696 

697 

698class Cone(_DirectedSurface): 

699 """A cone, its apex at the origin, pointing along `direction` from its base; blue, 

700 shaded by a three-dimensional scene's light, and open at the base, unless styled. 

701 

702 It is a [Surface][manimgx.Surface] of u, the distance from the apex along its side, 

703 and v, the angle around its axis: `v_range` may cut out a slice, and `u_min` its 

704 tip. It is one color, not checkered, unless given `checkerboard_colors`. 

705 

706 Args: 

707 base_radius: The radius of its base, in scene units. 

708 height: Its height, from its base to its apex, in scene units. 

709 direction: The direction it points in, from its base to its apex. 

710 show_base: Whether a disc closes its base. 

711 v_range: The range of the angle around its axis, in radians: (0, τ) goes all 

712 the way around. 

713 u_min: Where its side begins, as a distance from the apex along it, in scene 

714 units: above 0, the tip is cut off. 

715 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceOptions]: 

716 `resolution`, `checkerboard_colors`, and the style keywords. 

717 

718 Examples: 

719 ```python 

720 import manimgx as m 

721 

722 

723 class ConeExample(m.ThreeDScene): 

724 def construct(self) -> None: 

725 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-60 * m.DEGREES) 

726 frustum = m.Cone(base_radius=1.5, height=3, u_min=1.5, fill_color=m.RED) 

727 self.add( 

728 m.Cone(base_radius=1.5, height=3).shift(4 * m.LEFT + 1.5 * m.OUT), 

729 m.Cone(direction=m.X_AXIS + m.Z_AXIS, show_base=True), 

730 frustum.shift(4 * m.RIGHT + 1.5 * m.OUT), 

731 ) 

732 ``` 

733 """ 

734 

735 def __init__( 

736 self, 

737 base_radius: float = 1, 

738 height: float = 1, 

739 direction: Vector3DLike = Z_AXIS, 

740 show_base: bool = False, 

741 v_range: Sequence[float] = (0, TAU), 

742 u_min: float = 0, 

743 **kwargs: Unpack[SurfaceOptions], 

744 ) -> None: 

745 self.direction = np.array(direction, dtype=float) 

746 self.theta = PI - np.arctan(base_radius / height) 

747 kwargs.setdefault("checkerboard_colors", False) 

748 super().__init__( 

749 self.func, 

750 v_range=v_range, 

751 u_range=(u_min, np.sqrt(base_radius**2 + height**2)), 

752 **kwargs, 

753 ) 

754 self.new_height = height 

755 self._current_theta = 0.0 

756 self._current_phi = 0.0 

757 self.base_circle = Circle( 

758 radius=base_radius, 

759 color=self.fill_color, 

760 fill_opacity=self.fill_opacity, 

761 stroke_width=0, 

762 ) 

763 """The disc of its base, in its fill color: part of the cone with 

764 `show_base`.""" 

765 self.base_circle.shift(height * IN) 

766 self._set_start_and_end_attributes(self.direction) 

767 if show_base: 

768 self.add(self.base_circle) 

769 self.set_direction(direction) 

770 

771 def func(self, u: float, v: float) -> Point3D: 

772 """The cone's point, as it is made pointing up (along z) with its apex at the 

773 origin, at a distance from the apex along its side and an angle around its axis. 

774 

775 Args: 

776 u: The distance from the apex, along the side, in scene units. 

777 v: The angle around the axis, in radians. 

778 

779 Returns: 

780 The point, in scene coordinates. 

781 """ 

782 return _revolve(u * np.sin(self.theta), u * np.cos(self.theta), v) 

783 

784 def _set_start_and_end_attributes(self, direction: Vector3D) -> None: 

785 normalized_direction = direction * np.linalg.norm(direction) 

786 start = self.base_circle.get_center() 

787 end = start + normalized_direction * self.new_height 

788 self.start_point = VectorizedPoint(start) 

789 self.end_point = VectorizedPoint(end) 

790 self.add(self.start_point, self.end_point) 

791 

792 

793class Cylinder(_DirectedSurface): 

794 """A cylinder, centered at the origin, its axis along `direction`: checkered in two 

795 blues, closed at both ends by discs, and shaded by a three-dimensional scene's 

796 light, unless styled. 

797 

798 It is a [Surface][manimgx.Surface] of u, the height along its axis, and v, the 

799 angle around it: `v_range` may cut out a slice. 

800 

801 Args: 

802 radius: Its radius, in scene units. 

803 height: Its height, along its axis, in scene units. 

804 direction: The direction of its axis. 

805 v_range: The range of the angle around its axis, in radians: (0, τ) goes all 

806 the way around. 

807 show_ends: Whether discs close its ends. 

808 resolution: How many faces it has along its axis and around it: one number for 

809 both, or `(u, v)`. 

810 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceLook]: 

811 `checkerboard_colors`, and the style keywords. 

812 

813 Examples: 

814 ```python 

815 import manimgx as m 

816 

817 

818 class CylinderExample(m.ThreeDScene): 

819 def construct(self) -> None: 

820 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-60 * m.DEGREES) 

821 self.add( 

822 m.Cylinder(radius=1.5, height=3).shift(4.5 * m.LEFT), 

823 m.Cylinder(radius=0.5, height=4, direction=m.X_AXIS + m.Z_AXIS), 

824 m.Cylinder(show_ends=False, v_range=(0, m.PI)).shift(4 * m.RIGHT), 

825 ) 

826 ``` 

827 """ 

828 

829 def __init__( 

830 self, 

831 radius: float = 1, 

832 height: float = 2, 

833 direction: Vector3DLike = Z_AXIS, 

834 v_range: Sequence[float] = (0, TAU), 

835 show_ends: bool = True, 

836 resolution: int | Sequence[int] = (24, 24), 

837 **kwargs: Unpack[SurfaceLook], 

838 ) -> None: 

839 self._height = height 

840 self.radius = radius 

841 super().__init__( 

842 self.func, 

843 resolution=resolution, 

844 u_range=(-self._height / 2, self._height / 2), 

845 v_range=v_range, 

846 **kwargs, 

847 ) 

848 if show_ends: 

849 self.add_bases() 

850 self._current_phi = 0.0 

851 self._current_theta = 0.0 

852 self.set_direction(direction) 

853 

854 def func(self, u: float, v: float) -> np.ndarray: 

855 """The cylinder's point, as it is made along z and centered on the origin, at a 

856 height along its axis and an angle around it. 

857 

858 Args: 

859 u: The height along the axis, in scene units, from the middle. 

860 v: The angle around the axis, in radians. 

861 

862 Returns: 

863 The point, in scene coordinates. 

864 """ 

865 return _revolve(self.radius, u, v) 

866 

867 @deprecated("Manim CE's machinery: the constructor calls it", category=None) 

868 def add_bases(self) -> Self: 

869 """Add the discs that close the cylinder's ends: `base_top` and `base_bottom`, 

870 in its fill color. 

871 

872 They are placed at the ends of a cylinder along z, centered on the origin, as 

873 it is made: the constructor adds them (with `show_ends`) before turning the 

874 cylinder to its direction. 

875 """ 

876 bases = [ 

877 Circle( 

878 radius=self.radius, 

879 color=self.fill_color, 

880 fill_opacity=self.fill_opacity, 

881 shade_in_3d=True, 

882 stroke_width=0, 

883 ) 

884 for _ in range(2) 

885 ] 

886 self.base_top, self.base_bottom = bases 

887 self.base_top.shift(self.u_range[1] * IN) 

888 self.base_bottom.shift(self.u_range[0] * IN) 

889 self.add(self.base_top, self.base_bottom) 

890 return self 

891 

892 

893class Line3DOptions(_SurfaceLook, total=False, closed=True): 

894 """A [Line3D][manimgx.Line3D]'s keywords but its ends, for the methods that pass 

895 them on ([parallel_to][manimgx.Line3D.parallel_to], 

896 [perpendicular_to][manimgx.Line3D.perpendicular_to]): its thickness and resolution, 

897 with the surface keywords.""" 

898 

899 thickness: float 

900 """The line's radius, in scene units (default 0.02).""" 

901 resolution: int | tuple[int, int] 

902 """How many faces the line has around it (2 along it), or `(along, around)` 

903 (default 24).""" 

904 

905 

906class Line3D(Cylinder): 

907 """A line in three dimensions: a thin cylinder from one point to another; checkered 

908 in two blues, and shaded by a three-dimensional scene's light, unless styled. 

909 

910 An end may be a mobject: the line then starts (or ends) at its point farthest 

911 toward the other end (see [get_boundary_point][manimgx.Mobject.get_boundary_point]). 

912 

913 Args: 

914 start: Where the line starts: a point, or a mobject. 

915 end: Where it ends: a point, or a mobject. 

916 thickness: Its radius, in scene units. 

917 resolution: How many faces it has around it (2 along it), or 

918 `(along, around)`. 

919 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceLook]: 

920 `color` paints it all in one color; the style keywords. 

921 

922 Examples: 

923 ```python 

924 import manimgx as m 

925 

926 

927 class Line3DExample(m.ThreeDScene): 

928 def construct(self) -> None: 

929 self.set_camera_orientation(phi=65 * m.DEGREES, theta=-45 * m.DEGREES) 

930 axes = m.ThreeDAxes(x_range=(-3, 3), y_range=(-3, 3), z_range=(-2, 2)) 

931 line = m.Line3D(axes.c2p(-2, 0, 0), axes.c2p(1, 2, 1.5), thickness=0.05) 

932 self.add(axes, line.set_color(m.YELLOW)) 

933 ``` 

934 """ 

935 

936 def __init__( 

937 self, 

938 start: Point3DLike | Mobject = LEFT, 

939 end: Point3DLike | Mobject = RIGHT, 

940 thickness: float = 0.02, 

941 resolution: int | Sequence[int] = 24, 

942 **kwargs: Unpack[SurfaceLook], 

943 ): 

944 color = kwargs.pop("color", None) 

945 self.thickness = thickness 

946 self.resolution = (2, resolution) if isinstance(resolution, int) else resolution 

947 self.set_start_and_end_attrs(start, end, **kwargs) 

948 if color is not None: 

949 self.set_color(color) 

950 

951 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

952 def set_start_and_end_attrs( 

953 self, 

954 start: Point3DLike | Mobject, 

955 end: Point3DLike | Mobject, 

956 **kwargs: Unpack[SurfaceLook], 

957 ) -> Self: 

958 """Make the line run from one point (or mobject) to another: the constructor 

959 calls it. 

960 

961 It makes the line anew, as a cylinder of the line's thickness and resolution 

962 from `start` to `end`, styled by the keywords. 

963 

964 Args: 

965 start: Where the line starts: a point, or a mobject. 

966 end: Where it ends: a point, or a mobject. 

967 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceLook]. 

968 """ 

969 rough_start = self.pointify(start) 

970 rough_end = self.pointify(end) 

971 self.vect = rough_end - rough_start 

972 self.length = float(np.linalg.norm(self.vect)) 

973 self.direction: Vector3D = normalize(self.vect) 

974 self.start = self.pointify(start, self.direction) 

975 self.end = self.pointify(end, -self.direction) 

976 super().__init__( 

977 height=self.length, 

978 radius=self.thickness, 

979 direction=self.direction, 

980 resolution=self.resolution, 

981 **kwargs, 

982 ) 

983 self.shift((self.start + self.end) / 2) 

984 return self 

985 

986 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

987 def pointify( 

988 self, mob_or_point: Mobject | Point3DLike, direction: Vector3DLike | None = None 

989 ) -> Point3D: 

990 """Turn a point or a mobject into a point: a point as it is; a mobject's center, 

991 or its boundary point in a direction. 

992 

993 Args: 

994 mob_or_point: The point, or the mobject. 

995 direction: The direction of the mobject's boundary point (see 

996 [get_boundary_point][manimgx.Mobject.get_boundary_point]); None for its 

997 center. 

998 

999 Returns: 

1000 The point, in scene coordinates. 

1001 """ 

1002 if isinstance(mob_or_point, Mobject): 

1003 return ( 

1004 mob_or_point.get_center() 

1005 if direction is None 

1006 else mob_or_point.get_boundary_point(direction) 

1007 ) 

1008 return np.array(mob_or_point, dtype=float) 

1009 

1010 @classmethod 

1011 def parallel_to( 

1012 cls, 

1013 line: Line3D, 

1014 point: Point3DLike = ORIGIN, 

1015 length: float = 5, 

1016 **kwargs: Unpack[Line3DOptions], 

1017 ) -> Line3D: 

1018 """Make a line parallel to another, through a point: `length` long, centered on 

1019 the point. 

1020 

1021 Args: 

1022 line: The line to be parallel to. 

1023 point: The point the new line is centered on. 

1024 length: The new line's length, in scene units. 

1025 **kwargs: [Line keywords][manimgx.mobjects.three_d.Line3DOptions]: 

1026 `thickness`, `color`, …. 

1027 

1028 Returns: 

1029 A new line. 

1030 

1031 Examples: 

1032 ```python 

1033 import manimgx as m 

1034 

1035 

1036 class Line3DParallelToExample(m.ThreeDScene): 

1037 def construct(self) -> None: 

1038 self.set_camera_orientation( 

1039 phi=60 * m.DEGREES, theta=-45 * m.DEGREES 

1040 ) 

1041 line = m.Line3D(2 * m.RIGHT, m.UP + m.OUT, color=m.RED) 

1042 parallel = m.Line3D.parallel_to(line, color=m.YELLOW) 

1043 self.add(m.ThreeDAxes(), line, parallel) 

1044 ``` 

1045 """ 

1046 np_point = np.asarray(point, dtype=float) 

1047 vect = normalize(line.vect) 

1048 return cls(np_point + vect * length / 2, np_point - vect * length / 2, **kwargs) 

1049 

1050 @classmethod 

1051 def perpendicular_to( 

1052 cls, 

1053 line: Line3D, 

1054 point: Point3DLike = ORIGIN, 

1055 length: float = 5, 

1056 **kwargs: Unpack[Line3DOptions], 

1057 ) -> Line3D: 

1058 """Make a line perpendicular to another, through a point: in the plane of the 

1059 line and the point, `length` long, centered on the point. 

1060 

1061 A point on the line (which makes no plane with it) raises a ValueError. 

1062 

1063 Args: 

1064 line: The line to be perpendicular to. 

1065 point: The point the new line is centered on, off the line. 

1066 length: The new line's length, in scene units. 

1067 **kwargs: [Line keywords][manimgx.mobjects.three_d.Line3DOptions]: 

1068 `thickness`, `color`, …. 

1069 

1070 Returns: 

1071 A new line. 

1072 

1073 Examples: 

1074 ```python 

1075 import manimgx as m 

1076 

1077 

1078 class Line3DPerpendicularToExample(m.ThreeDScene): 

1079 def construct(self) -> None: 

1080 self.set_camera_orientation( 

1081 phi=60 * m.DEGREES, theta=-45 * m.DEGREES 

1082 ) 

1083 line = m.Line3D(2 * m.RIGHT, m.UP + m.OUT, color=m.RED) 

1084 perpendicular = m.Line3D.perpendicular_to(line, color=m.BLUE) 

1085 self.add(m.ThreeDAxes(), line, perpendicular) 

1086 ``` 

1087 """ 

1088 np_point = np.asarray(point, dtype=float) 

1089 norm = np.cross(line.vect, np_point - line.start) 

1090 if np.linalg.norm(norm) == 0: 

1091 raise ValueError("Could not find the perpendicular.") 

1092 start, end = perpendicular_bisector([line.start, line.end], norm) 

1093 vect = normalize(end - start) 

1094 return cls(np_point + vect * length / 2, np_point - vect * length / 2, **kwargs) 

1095 

1096 

1097class Arrow3D(Line3D): 

1098 """An arrow in three dimensions: a thin cylinder from `start`, ending in a cone 

1099 whose apex is at `end`; white unless given a color, shaded by a three-dimensional 

1100 scene's light. 

1101 

1102 Args: 

1103 start: Where the arrow starts. 

1104 end: Where its tip's apex is. 

1105 thickness: The radius of its shaft, in scene units. 

1106 height: The length of its tip, a [Cone][manimgx.Cone], in scene units. 

1107 base_radius: The radius of its tip's base, in scene units. 

1108 resolution: How many faces its shaft has around it (2 along it), or 

1109 `(along, around)`. 

1110 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceLook] 

1111 for the shaft and the tip: `color`, and the style keywords. 

1112 

1113 Examples: 

1114 ```python 

1115 import manimgx as m 

1116 

1117 

1118 class Arrow3DExample(m.ThreeDScene): 

1119 def construct(self) -> None: 

1120 self.set_camera_orientation(phi=65 * m.DEGREES, theta=-45 * m.DEGREES) 

1121 axes = m.ThreeDAxes(x_range=(-3, 3), y_range=(-3, 3), z_range=(-2, 2)) 

1122 arrows = [ 

1123 m.Arrow3D(axes.c2p(0, 0, 0), axes.c2p(*end), color=color) 

1124 for end, color in ( 

1125 ((2, 0, 0), m.RED), 

1126 ((0, 2, 0), m.GREEN), 

1127 ((0, 0, 2), m.BLUE), 

1128 ((1.5, 1.5, 1.5), m.YELLOW), 

1129 ) 

1130 ] 

1131 self.add(axes, *arrows) 

1132 ``` 

1133 """ 

1134 

1135 def __init__( 

1136 self, 

1137 start: Point3DLike = LEFT, 

1138 end: Point3DLike = RIGHT, 

1139 thickness: float = 0.02, 

1140 height: float = 0.3, 

1141 base_radius: float = 0.08, 

1142 resolution: int | tuple[int, int] = 24, 

1143 **kwargs: Unpack[SurfaceLook], 

1144 ) -> None: 

1145 color = kwargs.pop("color", None) or WHITE 

1146 start, end = np.asarray(start, dtype=float), np.asarray(end, dtype=float) 

1147 super().__init__( 

1148 start=start, 

1149 end=end - height * normalize(end - start), 

1150 thickness=thickness, 

1151 resolution=resolution, 

1152 **kwargs, 

1153 ) 

1154 self.cone = Cone( 

1155 direction=self.direction, base_radius=base_radius, height=height, **kwargs 

1156 ) 

1157 """Its tip: a [Cone][manimgx.Cone], its apex at the arrow's end.""" 

1158 self.cone.shift(end) 

1159 self.end_point = VectorizedPoint(end) 

1160 self.add(self.end_point, self.cone) 

1161 self.set_color(color) 

1162 

1163 

1164class Torus(Surface): 

1165 """A torus: a tube around a circle in the xy-plane, centered at the origin; 

1166 checkered in two blues and shaded by a three-dimensional scene's light, unless 

1167 styled. 

1168 

1169 It is a [Surface][manimgx.Surface] of u, the angle around its axis (z), and v, the 

1170 angle around its tube: their ranges may cut out a part of it. 

1171 

1172 Args: 

1173 major_radius: The radius of the circle the tube runs around: from the torus's 

1174 center to the middle of its tube, in scene units. 

1175 minor_radius: The tube's radius, in scene units. 

1176 u_range: The range of the angle around its axis, in radians: (0, τ) goes all 

1177 the way around. 

1178 v_range: The range of the angle around its tube, in radians. 

1179 resolution: How many faces it has around its axis and around its tube: one 

1180 number for both, or `(u, v)`; None for (24, 24). 

1181 **kwargs: [Surface keywords][manimgx.mobjects.three_d.SurfaceLook]: 

1182 `checkerboard_colors`, and the style keywords. 

1183 

1184 Examples: 

1185 ```python 

1186 import manimgx as m 

1187 

1188 

1189 class TorusExample(m.ThreeDScene): 

1190 def construct(self) -> None: 

1191 self.set_camera_orientation(phi=65 * m.DEGREES, theta=-60 * m.DEGREES) 

1192 self.add( 

1193 m.Torus(major_radius=2, minor_radius=0.7).shift(3 * m.LEFT), 

1194 m.Torus( 

1195 major_radius=2, 

1196 minor_radius=0.7, 

1197 u_range=(0, 1.5 * m.PI), 

1198 checkerboard_colors=[m.ORANGE, m.YELLOW], 

1199 ).shift(3 * m.RIGHT), 

1200 ) 

1201 ``` 

1202 """ 

1203 

1204 def __init__( 

1205 self, 

1206 major_radius: float = 3, 

1207 minor_radius: float = 1, 

1208 u_range: Sequence[float] = (0, TAU), 

1209 v_range: Sequence[float] = (0, TAU), 

1210 resolution: int | tuple[int, int] | None = None, 

1211 **kwargs: Unpack[SurfaceLook], 

1212 ) -> None: 

1213 self.R = major_radius 

1214 self.r = minor_radius 

1215 super().__init__( 

1216 self.func, 

1217 u_range=u_range, 

1218 v_range=v_range, 

1219 resolution=resolution if resolution is not None else (24, 24), 

1220 **kwargs, 

1221 ) 

1222 

1223 def func(self, u: float, v: float) -> Point3D: 

1224 """The torus's point, as it is made around the origin, at an angle around its 

1225 axis and an angle around its tube. 

1226 

1227 Args: 

1228 u: The angle around the axis, in radians, counterclockwise from the x-axis. 

1229 v: The angle around the tube, in radians: 0 on its inner side. 

1230 

1231 Returns: 

1232 The point, in scene coordinates. 

1233 """ 

1234 return _revolve(self.R - self.r * np.cos(v), -self.r * np.sin(v), u) 

1235 

1236 

1237class PolyhedronOptions(TypedDict, total=False, closed=True): 

1238 """How a [Polyhedron][manimgx.Polyhedron]'s faces and its graph of vertices and 

1239 edges look, for the solids that set their own vertices and faces 

1240 ([Tetrahedron][manimgx.Tetrahedron], [ConvexHull3D][manimgx.ConvexHull3D], …).""" 

1241 

1242 faces_config: Style | None 

1243 """[Style keywords][manimgx.drawing.paint.Style] for the faces, over their defaults: 

1244 half opaque, shaded by a three-dimensional scene's light (default None: none).""" 

1245 graph_config: GraphOptions | None 

1246 """[Graph keywords][manimgx.Graph] for the vertices and edges, 

1247 over their defaults: [Dot3D][manimgx.Dot3D] vertices, invisible edges (default None: 

1248 none).""" 

1249 

1250 

1251class Polyhedron(VGroup): 

1252 """A polyhedron: its faces, polygons through its vertices, and the graph of its 

1253 vertices and edges; blue half-opaque faces with white dots at the vertices, shaded 

1254 by a three-dimensional scene's light, unless styled. 

1255 

1256 The faces are its [faces][manimgx.Polyhedron.faces], a group of 

1257 [Polygon][manimgx.Polygon]s, whose outlines draw the edges; its 

1258 [graph][manimgx.Polyhedron.graph] is a [Graph][manimgx.Graph] whose vertices are 

1259 [Dot3D][manimgx.Dot3D]s, `graph[i]` the vertex of index i, and whose own edges are 

1260 invisible unless configured. The faces follow the vertices: move a vertex, and an 

1261 updater keeps the faces through it. Initial coordinates and graph options are 

1262 construction inputs; later positions belong to the graph, and `faces_list` 

1263 defines the faces. 

1264 

1265 Args: 

1266 vertex_coords: The vertices' points, in scene coordinates. 

1267 faces_list: The faces, each a list of the indices of its vertices, in order 

1268 around it. 

1269 faces_config: [Style keywords][manimgx.drawing.paint.Style] for the faces, over 

1270 their defaults (half opaque, shaded in 3D); None for none. 

1271 graph_config: [Graph keywords][manimgx.Graph] for the 

1272 vertices and edges, over their defaults ([Dot3D][manimgx.Dot3D] vertices, 

1273 invisible edges); None for none. 

1274 

1275 Examples: 

1276 ```python 

1277 import manimgx as m 

1278 

1279 

1280 class PolyhedronExample(m.ThreeDScene): 

1281 def construct(self) -> None: 

1282 self.set_camera_orientation(phi=70 * m.DEGREES, theta=30 * m.DEGREES) 

1283 corners = [[1, 1, 0], [1, -1, 0], [-1, -1, 0], [-1, 1, 0], [0, 0, 2]] 

1284 faces = [[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4], [0, 1, 2, 3]] 

1285 pyramid = m.Polyhedron(corners, faces).scale(1.5).shift(m.IN) 

1286 self.add(pyramid) 

1287 self.play(pyramid.graph[4].animate.move_to([1, 1, 2]), run_time=2) 

1288 ``` 

1289 """ 

1290 

1291 def __init__( 

1292 self, 

1293 vertex_coords: Point3DLike_Array, 

1294 faces_list: list[list[int]], 

1295 faces_config: Style | None = None, 

1296 graph_config: GraphOptions | None = None, 

1297 ): 

1298 super().__init__() 

1299 self.faces_config = Style(fill_opacity=0.5, shade_in_3d=True) | ( 

1300 faces_config or Style() 

1301 ) 

1302 graph_config = GraphOptions( 

1303 vertex_type=Dot3D, edge_config={"stroke_opacity": 0} 

1304 ) | (graph_config or GraphOptions()) 

1305 vertex_indices = list(range(len(vertex_coords))) 

1306 layout: dict[Hashable, Point3D] = { 

1307 i: np.asarray(p, dtype=float) for i, p in enumerate(vertex_coords) 

1308 } 

1309 self.faces_list = [list(face) for face in faces_list] 

1310 """The faces, each a list of the indices of its vertices, as they were given.""" 

1311 face_coords = [[layout[j] for j in i] for i in faces_list] 

1312 self.edges = self.get_edges(self.faces_list) 

1313 """The edges, each a pair of vertex indices.""" 

1314 self.faces = self.create_faces(face_coords) 

1315 """The faces: a group of [Polygon][manimgx.Polygon]s, in the order of 

1316 `faces_list`.""" 

1317 self.graph = Graph( 

1318 vertex_indices, 

1319 self.edges, 

1320 **(graph_config | GraphOptions(layout=layout)), 

1321 ) 

1322 """The vertices and edges: a [Graph][manimgx.Graph], `graph[i]` the vertex of 

1323 index i.""" 

1324 self.add(self.faces, self.graph) 

1325 self.add_updater(self.update_faces) 

1326 

1327 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1328 def get_edges(self, faces_list: list[list[int]]) -> list[tuple[int, int]]: 

1329 """Find the edges of faces: each two vertices next to each other around a face, 

1330 each edge once. 

1331 

1332 Args: 

1333 faces_list: The faces, each a list of the indices of its vertices, in order 

1334 around it. 

1335 

1336 Returns: 

1337 The edges, each a pair of vertex indices, in the order the faces first give 

1338 them. 

1339 """ 

1340 # each edge once (CE listed it once per face, doubling a translucent edge) 

1341 edges: dict[frozenset[int], tuple[int, int]] = {} 

1342 for face in faces_list: 

1343 for edge in zip(face, face[1:] + face[:1], strict=True): 

1344 edges.setdefault(frozenset(edge), edge) 

1345 return list(edges.values()) 

1346 

1347 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1348 def create_faces( 

1349 self, face_coords: Sequence[Sequence[Point3DLike]] 

1350 ) -> VGroup[Polygon]: 

1351 """Make faces: a polygon through each list of points, styled by the 

1352 polyhedron's `faces_config`. 

1353 

1354 Args: 

1355 face_coords: The faces' corners, a list of points for each face. 

1356 

1357 Returns: 

1358 A new group of the polygons. 

1359 """ 

1360 return VGroup[Polygon]( 

1361 *(Polygon(*face, **self.faces_config) for face in face_coords) 

1362 ) 

1363 

1364 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1365 def update_faces(self, m: Mobject) -> Self: 

1366 """Put the faces back through the vertices, where they are now: the updater the 

1367 polyhedron runs every frame. 

1368 

1369 Args: 

1370 m: The mobject the updater runs for (the polyhedron); unused. 

1371 """ 

1372 for face, coords in zip(self.faces, self.extract_face_coords(), strict=True): 

1373 face.set_points_as_corners([*coords, coords[0]]) 

1374 return self 

1375 

1376 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1377 def extract_face_coords(self) -> list[list[Point3D]]: 

1378 """The faces' corners where the vertices are now: the centers of the graph's 

1379 vertices. 

1380 

1381 Returns: 

1382 A list of points for each face, in the order of `faces_list`. 

1383 """ 

1384 vertices = [vertex.get_center() for vertex in self.graph.vertices.values()] 

1385 return [[vertices[i] for i in face] for face in self.faces_list] 

1386 

1387 

1388class Tetrahedron(Polyhedron): 

1389 """A regular tetrahedron: four triangular faces, centered at the origin; a 

1390 [Polyhedron][manimgx.Polyhedron], blue half-opaque faces with white dots at the 

1391 vertices unless styled. 

1392 

1393 Args: 

1394 edge_length: The length of its edges, in scene units. 

1395 **kwargs: [Polyhedron keywords][manimgx.mobjects.three_d.PolyhedronOptions]: 

1396 `faces_config`, `graph_config`. 

1397 

1398 Examples: 

1399 ```python 

1400 import manimgx as m 

1401 

1402 

1403 class TetrahedronExample(m.ThreeDScene): 

1404 def construct(self) -> None: 

1405 self.set_camera_orientation(phi=70 * m.DEGREES, theta=30 * m.DEGREES) 

1406 self.add(m.Tetrahedron(edge_length=4)) 

1407 ``` 

1408 """ 

1409 

1410 def __init__(self, edge_length: float = 1, **kwargs: Unpack[PolyhedronOptions]): 

1411 unit = edge_length * np.sqrt(2) / 4 

1412 super().__init__( 

1413 vertex_coords=[ 

1414 np.array([unit, unit, unit]), 

1415 np.array([unit, -unit, -unit]), 

1416 np.array([-unit, unit, -unit]), 

1417 np.array([-unit, -unit, unit]), 

1418 ], 

1419 faces_list=[[0, 1, 2], [3, 0, 2], [0, 1, 3], [3, 1, 2]], 

1420 **kwargs, 

1421 ) 

1422 

1423 

1424class Octahedron(Polyhedron): 

1425 """A regular octahedron: eight triangular faces, its vertices on the axes, centered 

1426 at the origin; a [Polyhedron][manimgx.Polyhedron], blue half-opaque faces with 

1427 white dots at the vertices unless styled. 

1428 

1429 Args: 

1430 edge_length: The length of its edges, in scene units. 

1431 **kwargs: [Polyhedron keywords][manimgx.mobjects.three_d.PolyhedronOptions]: 

1432 `faces_config`, `graph_config`. 

1433 

1434 Examples: 

1435 ```python 

1436 import manimgx as m 

1437 

1438 

1439 class OctahedronExample(m.ThreeDScene): 

1440 def construct(self) -> None: 

1441 self.set_camera_orientation(phi=70 * m.DEGREES, theta=30 * m.DEGREES) 

1442 octahedron = m.Octahedron(edge_length=3) 

1443 octahedron.faces[2].set_color(m.YELLOW) 

1444 octahedron.graph[0].set_color(m.RED) 

1445 self.add(octahedron) 

1446 ``` 

1447 """ 

1448 

1449 def __init__(self, edge_length: float = 1, **kwargs: Unpack[PolyhedronOptions]): 

1450 unit = edge_length * np.sqrt(2) / 2 

1451 super().__init__( 

1452 vertex_coords=[ 

1453 np.array([unit, 0, 0]), 

1454 np.array([-unit, 0, 0]), 

1455 np.array([0, unit, 0]), 

1456 np.array([0, -unit, 0]), 

1457 np.array([0, 0, unit]), 

1458 np.array([0, 0, -unit]), 

1459 ], 

1460 faces_list=[ 

1461 [2, 4, 1], 

1462 [0, 4, 2], 

1463 [4, 3, 0], 

1464 [1, 3, 4], 

1465 [3, 5, 0], 

1466 [1, 5, 3], 

1467 [2, 5, 1], 

1468 [0, 5, 2], 

1469 ], 

1470 **kwargs, 

1471 ) 

1472 

1473 

1474class Icosahedron(Polyhedron): 

1475 """A regular icosahedron: twenty triangular faces, centered at the origin; a 

1476 [Polyhedron][manimgx.Polyhedron], blue half-opaque faces with white dots at the 

1477 vertices unless styled. 

1478 

1479 Args: 

1480 edge_length: The length of its edges, in scene units. 

1481 **kwargs: [Polyhedron keywords][manimgx.mobjects.three_d.PolyhedronOptions]: 

1482 `faces_config`, `graph_config`. 

1483 

1484 Examples: 

1485 ```python 

1486 import manimgx as m 

1487 

1488 

1489 class IcosahedronExample(m.ThreeDScene): 

1490 def construct(self) -> None: 

1491 self.set_camera_orientation(phi=70 * m.DEGREES, theta=30 * m.DEGREES) 

1492 self.add(m.Icosahedron(edge_length=2, faces_config={"color": m.TEAL})) 

1493 ``` 

1494 """ 

1495 

1496 def __init__(self, edge_length: float = 1, **kwargs: Unpack[PolyhedronOptions]): 

1497 unit_a = edge_length * ((1 + np.sqrt(5)) / 4) 

1498 unit_b = edge_length * (1 / 2) 

1499 super().__init__( 

1500 vertex_coords=[ 

1501 np.array([0, unit_b, unit_a]), 

1502 np.array([0, -unit_b, unit_a]), 

1503 np.array([0, unit_b, -unit_a]), 

1504 np.array([0, -unit_b, -unit_a]), 

1505 np.array([unit_b, unit_a, 0]), 

1506 np.array([unit_b, -unit_a, 0]), 

1507 np.array([-unit_b, unit_a, 0]), 

1508 np.array([-unit_b, -unit_a, 0]), 

1509 np.array([unit_a, 0, unit_b]), 

1510 np.array([unit_a, 0, -unit_b]), 

1511 np.array([-unit_a, 0, unit_b]), 

1512 np.array([-unit_a, 0, -unit_b]), 

1513 ], 

1514 faces_list=[ 

1515 [1, 8, 0], 

1516 [1, 5, 7], 

1517 [8, 5, 1], 

1518 [7, 3, 5], 

1519 [5, 9, 3], 

1520 [8, 9, 5], 

1521 [3, 2, 9], 

1522 [9, 4, 2], 

1523 [8, 4, 9], 

1524 [0, 4, 8], 

1525 [6, 4, 0], 

1526 [6, 2, 4], 

1527 [11, 2, 6], 

1528 [3, 11, 2], 

1529 [0, 6, 10], 

1530 [10, 1, 0], 

1531 [10, 7, 1], 

1532 [11, 7, 3], 

1533 [10, 11, 7], 

1534 [10, 11, 6], 

1535 ], 

1536 **kwargs, 

1537 ) 

1538 

1539 

1540class Dodecahedron(Polyhedron): 

1541 """A regular dodecahedron: twelve pentagonal faces, centered at the origin; a 

1542 [Polyhedron][manimgx.Polyhedron], blue half-opaque faces with white dots at the 

1543 vertices unless styled. 

1544 

1545 Args: 

1546 edge_length: The length of its edges, in scene units. 

1547 **kwargs: [Polyhedron keywords][manimgx.mobjects.three_d.PolyhedronOptions]: 

1548 `faces_config`, `graph_config`. 

1549 

1550 Examples: 

1551 ```python 

1552 import manimgx as m 

1553 

1554 

1555 class DodecahedronExample(m.ThreeDScene): 

1556 def construct(self) -> None: 

1557 self.set_camera_orientation(phi=70 * m.DEGREES, theta=30 * m.DEGREES) 

1558 self.add( 

1559 m.Dodecahedron(edge_length=1.5, faces_config={"color": m.PURPLE}) 

1560 ) 

1561 ``` 

1562 """ 

1563 

1564 def __init__(self, edge_length: float = 1, **kwargs: Unpack[PolyhedronOptions]): 

1565 unit_a = edge_length * ((1 + np.sqrt(5)) / 4) 

1566 unit_b = edge_length * ((3 + np.sqrt(5)) / 4) 

1567 unit_c = edge_length * (1 / 2) 

1568 super().__init__( 

1569 vertex_coords=[ 

1570 np.array([unit_a, unit_a, unit_a]), 

1571 np.array([unit_a, unit_a, -unit_a]), 

1572 np.array([unit_a, -unit_a, unit_a]), 

1573 np.array([unit_a, -unit_a, -unit_a]), 

1574 np.array([-unit_a, unit_a, unit_a]), 

1575 np.array([-unit_a, unit_a, -unit_a]), 

1576 np.array([-unit_a, -unit_a, unit_a]), 

1577 np.array([-unit_a, -unit_a, -unit_a]), 

1578 np.array([0, unit_c, unit_b]), 

1579 np.array([0, unit_c, -unit_b]), 

1580 np.array([0, -unit_c, -unit_b]), 

1581 np.array([0, -unit_c, unit_b]), 

1582 np.array([unit_c, unit_b, 0]), 

1583 np.array([-unit_c, unit_b, 0]), 

1584 np.array([unit_c, -unit_b, 0]), 

1585 np.array([-unit_c, -unit_b, 0]), 

1586 np.array([unit_b, 0, unit_c]), 

1587 np.array([-unit_b, 0, unit_c]), 

1588 np.array([unit_b, 0, -unit_c]), 

1589 np.array([-unit_b, 0, -unit_c]), 

1590 ], 

1591 faces_list=[ 

1592 [18, 16, 0, 12, 1], 

1593 [3, 18, 16, 2, 14], 

1594 [3, 10, 9, 1, 18], 

1595 [1, 9, 5, 13, 12], 

1596 [0, 8, 4, 13, 12], 

1597 [2, 16, 0, 8, 11], 

1598 [4, 17, 6, 11, 8], 

1599 [17, 19, 5, 13, 4], 

1600 [19, 7, 15, 6, 17], 

1601 [6, 15, 14, 2, 11], 

1602 [19, 5, 9, 10, 7], 

1603 [7, 10, 3, 14, 15], 

1604 ], 

1605 **kwargs, 

1606 ) 

1607 

1608 

1609class ConvexHull3D(Polyhedron): 

1610 """The convex hull of points in three dimensions: the smallest convex polyhedron 

1611 around them, its faces triangles; a [Polyhedron][manimgx.Polyhedron], blue 

1612 half-opaque faces with white dots at the vertices unless styled. 

1613 

1614 Its vertices are the points on the hull (those inside are left out), and its faces 

1615 are wound counterclockwise, seen from outside. Fewer than four points raise a 

1616 ValueError. 

1617 

1618 Args: 

1619 *points: The points, in scene coordinates. 

1620 tolerance: How far outside a face a point must be to count as beyond it, in 

1621 scene units. 

1622 **kwargs: [Polyhedron keywords][manimgx.mobjects.three_d.PolyhedronOptions]: 

1623 `faces_config`, `graph_config`. 

1624 

1625 Examples: 

1626 ```python 

1627 import numpy as np 

1628 

1629 import manimgx as m 

1630 

1631 

1632 class ConvexHull3DExample(m.ThreeDScene): 

1633 def construct(self) -> None: 

1634 self.set_camera_orientation(phi=70 * m.DEGREES, theta=30 * m.DEGREES) 

1635 points = np.random.default_rng(1).uniform(-2, 2, size=(30, 3)) 

1636 hull = m.ConvexHull3D(*points, faces_config={"color": m.GREEN}) 

1637 self.add(hull, *(m.Dot3D(p, color=m.YELLOW) for p in points)) 

1638 ``` 

1639 """ 

1640 

1641 def __init__( 

1642 self, 

1643 *points: Point3DLike, 

1644 tolerance: float = 1e-05, 

1645 **kwargs: Unpack[PolyhedronOptions], 

1646 ): 

1647 array = np.array(points, dtype=float) 

1648 hull = QuickHull(tolerance) 

1649 hull.build(array) 

1650 # In the hull's own order: CE iterated hash sets of point bytes, whose order changes 

1651 # from process to process (salted hashing), and so did faces, vertex ids and draw order. 

1652 index: dict[bytes, int] = {} 

1653 vertices: list[Point3D] = [] 

1654 faces: list[list[int]] = [] 

1655 for facet in dict.fromkeys(hull.facets): 

1656 if facet in hull.removed: 

1657 continue 

1658 a, b, c = facet.coordinates 

1659 corners = ( 

1660 (a, b, c) 

1661 if np.dot(np.cross(b - a, c - a), facet.normal) > 0 

1662 else (a, c, b) 

1663 ) 

1664 for point in corners: # wound counterclockwise seen from outside 

1665 if point.tobytes() not in index: 

1666 index[point.tobytes()] = len(vertices) 

1667 vertices.append(point) 

1668 faces.append([index[point.tobytes()] for point in corners]) 

1669 super().__init__(vertex_coords=vertices, faces_list=faces, **kwargs)