Coverage for src/manimgx/scene.py: 97%

1070 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"""Scenes and their cameras: mutable worlds evaluated in exact time.""" 

7 

8from __future__ import annotations 

9 

10from collections.abc import Iterable 

11from typing import TYPE_CHECKING, Literal, overload 

12 

13from typing_extensions import TypedDict 

14 

15from manimgx.constants import DEGREES, DOWN, LEFT, OUT, RIGHT, UP 

16from manimgx.drawing.paint import ManimColor, ParsableManimColor 

17from manimgx.mobject import Mobject, ValueTracker 

18from manimgx.settings import config 

19 

20if TYPE_CHECKING: 

21 from manimgx.animation.transform import Animate 

22import inspect 

23import os 

24import pathlib 

25from collections.abc import Callable, Sequence 

26from fractions import Fraction 

27from typing import TYPE_CHECKING, NamedTuple, Self, Unpack, cast 

28from warnings import deprecated 

29 

30import numpy as np 

31 

32from manimgx.animation import clock 

33from manimgx.constants import ( 

34 DEFAULT_MOBJECT_TO_EDGE_BUFFER, 

35 DEFAULT_WAIT_TIME, 

36 ORIGIN, 

37 UR, 

38) 

39from manimgx.drawing.paint import WHITE 

40from manimgx.mobject import ( 

41 Group, 

42 _family, 

43 _has_updater, 

44 _per_frame, 

45 _Recorder, 

46 flow, 

47 records, 

48 remove_list_redundancies, 

49 simulated, 

50) 

51from manimgx.rendering.film import ( 

52 DEFAULT_ENCODER_CRF, 

53 DEFAULT_ENCODER_PRESET, 

54 Caption, 

55 Cut, 

56 Film, 

57 FrameSink, 

58 Play, 

59 PlayHook, 

60 SectionType, 

61 Take, 

62 X264Preset, 

63) 

64from manimgx.typing import Point3D, Point3DLike, Vector3DLike 

65 

66if TYPE_CHECKING: 

67 from manimgx.animation.timeline import Animation, Route, Window 

68 from manimgx.animation.transform import Compositor, Transform, TransformOptions 

69 from manimgx.audio import Speech, Voice 

70 from manimgx.audio.sound import Clip, Sound 

71 from manimgx.drawing.geometry import Path 

72 from manimgx.mobject import ValueTracker 

73 from manimgx.mobjects.images import ImageCameraOptions 

74from dataclasses import dataclass 

75from typing import TYPE_CHECKING, ClassVar 

76 

77import numpy.typing as npt 

78 

79from manimgx.animation.motion import ( 

80 ApplyPointwiseFunction, 

81 Create, 

82 DrawBorderThenFill, 

83 GrowArrow, 

84 Write, 

85) 

86from manimgx.animation.timeline import Animation 

87from manimgx.animation.transform import Transform, TransformOptions 

88from manimgx.constants import DL, LARGE_BUFF, SMALL_BUFF 

89from manimgx.drawing.geometry import angle_of_vector 

90from manimgx.drawing.paint import ( 

91 BLUE_D, 

92 GREEN_C, 

93 GREY, 

94 PURE_YELLOW, 

95 RED_C, 

96 Colors, 

97) 

98from manimgx.mobject import VGroup, VMobject 

99from manimgx.mobjects.grid import Matrix, MatrixOptions 

100from manimgx.mobjects.plotting import ( 

101 Axes, 

102 NumberPlane, 

103 NumberPlaneOptions, 

104 merged_axis_config, 

105) 

106from manimgx.mobjects.shapes import ( 

107 Arrow, 

108 ArrowTips, 

109 ArrowTipsBase, 

110 Line, 

111 Rectangle, 

112 Vector, 

113) 

114from manimgx.mobjects.text import MathTex, SingleStringMathTex, Tex 

115 

116if TYPE_CHECKING: 

117 from typing import Self 

118 

119 from manimgx.typing import ( 

120 ManimTextLabel, 

121 MappingFunction, 

122 Point3D, 

123 Vector3DLike, 

124 ) 

125 

126__all__ = [ 

127 "Camera", 

128 "LinearTransformationScene", 

129 "MovingCameraScene", 

130 "Scene", 

131 "ThreeDScene", 

132 "VectorScene", 

133 "ZoomedScene", 

134] 

135 

136 

137def _view_rectangle(height: float, width: float) -> Mobject: 

138 from manimgx.mobject import VMobject 

139 

140 w, h = width / 2, height / 2 

141 return VMobject(stroke_width=0).set_points_as_corners( 

142 [[-w, h, 0], [w, h, 0], [w, -h, 0], [-w, -h, 0], [-w, h, 0]] 

143 ) 

144 

145 

146class Camera: 

147 """What a frame shows: a view of the scene, made of mobjects, so that whatever moves 

148 a mobject moves the view. 

149 

150 Its [`frame`][manimgx.Camera.frame] is a rectangle in the scene whose center and 

151 size are the view: move it, scale it or animate it, and the view pans and zooms. In 

152 three dimensions (a [`ThreeDScene`][manimgx.ThreeDScene]'s camera), it also orbits 

153 the frame's center, with perspective: five [value trackers][manimgx.ValueTracker] 

154 hold its angles `phi` and `theta`, its roll `gamma`, its `zoom` and its 

155 `focal_distance` (`phi_tracker`, `theta_tracker`, `gamma_tracker`, `zoom_tracker` 

156 and `focal_distance_tracker`), and its light is a point, 

157 [`light_source`][manimgx.Camera.light_source]. A camera only describes the view: it 

158 never draws. 

159 

160 Args: 

161 three_d: Whether it sees in three dimensions: with perspective and depth, from 

162 its orbit. 

163 frame_width: The width of its frame, in scene units; None for the configured one 

164 (about 14.2 at 16:9). Its height is the configured one; a width out of the 

165 video's proportions stretches the picture. 

166 phi: The angle between its line of sight and the z axis, in radians: 0 looks 

167 straight down on the xy plane. 

168 theta: Its angle around the z axis, in radians, counterclockwise from the x 

169 axis: at −90° it looks from the side of negative y, so that x points right. 

170 gamma: How far it turns about its line of sight, in radians. 

171 focal_distance: Its distance from the frame's center, in scene units: the 

172 nearer, the stronger the perspective. 

173 zoom: How much it magnifies: 2 shows everything twice as large. 

174 light_source_start_point: Where the light is, in scene coordinates. 

175 """ 

176 

177 def __init__( 

178 self, 

179 *, 

180 three_d: bool = False, 

181 frame_width: float | None = None, 

182 phi: float = 0, 

183 theta: float = -90 * DEGREES, 

184 gamma: float = 0, 

185 focal_distance: float = 20.0, 

186 zoom: float = 1, 

187 light_source_start_point: Point3D = 9 * DOWN + 7 * LEFT + 10 * OUT, 

188 ) -> None: 

189 from manimgx.mobject import Point 

190 

191 self.three_d = three_d 

192 """Whether the camera sees in three dimensions: with perspective and depth, from 

193 its orbit.""" 

194 self.frame = _view_rectangle( 

195 config.frame_height, frame_width or config.frame_width 

196 ) 

197 """The view: a rectangle in the scene, centered on the point the camera looks 

198 at, as wide and as tall as what it shows. 

199 

200 Move it, scale it or animate it to pan and zoom: 

201 `self.play(self.camera.frame.animate.scale(0.5))` zooms in, showing half as 

202 much, twice as large. Its outline is not drawn (a stroke width of 0). 

203 """ 

204 self.phi_tracker, self.theta_tracker, self.gamma_tracker = ( 

205 ValueTracker(phi), 

206 ValueTracker(theta), 

207 ValueTracker(gamma), 

208 ) 

209 self.focal_distance_tracker, self.zoom_tracker = ( 

210 ValueTracker(focal_distance), 

211 ValueTracker(zoom), 

212 ) 

213 self.light_source = Point(light_source_start_point) 

214 """Where the light comes from: a point in the scene, which lights the mobjects 

215 shaded in three dimensions (`shade_in_3d`). Move it like any mobject.""" 

216 # the mobjects pinned to the screen, as they were given: what they are made of 

217 # is read every frame (see `fixed_in_frame_mobjects`) 

218 self._fixed_in_frame: dict[Mobject, None] = {} 

219 self.background_color = config.background_color 

220 self.background_opacity = config.background_opacity 

221 """The opacity of the background, from 0 to 1: the configured one unless 

222 changed.""" 

223 self.exposure = 1.0 

224 """How much the light that mobjects with a [material][manimgx.Material] reflect 

225 is scaled before it is shown: 2 is twice as bright (one stop).""" 

226 self.tone_mapping: Literal["linear", "agx"] = "linear" 

227 """How light brighter than white is shown: "linear" clips it (a lit surface's 

228 colors as they are, up to white), "agx" rolls it off as film does (AgX: highlights 

229 desaturate toward white, and nothing clips). The light lit surfaces send into a 

230 pixel is averaged first and shown once, as a camera records it.""" 

231 self.ambient_occlusion = 0.0 

232 """How strongly the light from all around (an ambient or an environment light) is 

233 shut out of corners, creases and the ground under things, where the surfaces near 

234 them block it: 0 not at all (off), 1 the standard strength, more darker. Only 

235 mobjects with a [material][manimgx.Material] are lit by that light, and only opaque 

236 ones shut it out or are darkened; a sun's, a point's or a spot's light is left as it 

237 is. 

238 

239 It is found from what the view shows (screen-space ambient obscurance): a 

240 surface the view cannot see, such as a wall seen edge-on, shuts nothing out. 

241 Light bounces between the surfaces that shut it out, so light-colored ones 

242 darken less, and white ones hardly at all.""" 

243 self.ambient_occlusion_radius = 0.3 

244 """How far around a point the surfaces that shut light out of it are sought, in 

245 scene units: about the size of the creases and contacts to darken.""" 

246 self.bloom = 0.0 

247 """How much of the light that mobjects with a [material][manimgx.Material] send 

248 into the view the lens spreads around it, as a glow (bloom), from 0 to 1: 0 none 

249 (off), 0.05 a lens's faint glow, plain around light brighter than white, 1 all of 

250 it. What the glow spreads, the light leaves: the view keeps the light it has, 

251 spread. 

252 

253 It is spread from the light the view shows: what lies nearer, a mobject fixed in 

254 the frame too, hides the light behind it. It falls off with the distance from 

255 the light: half of it lies within a twentieth of the view's height, nearly all of 

256 it within a quarter. It is light, over everything the view shows: over a lit 

257 surface, it adds to the surface's light before the tone mapping shows them; over 

258 display paint (the background, mobjects without a material, mobjects fixed in the 

259 frame), the tone mapping shows it on its own and it adds to the paint, as a screen 

260 adds light (white stays white); where the view shows nothing (a transparent 

261 background), it shows alone, as opaque as it is bright. Mobjects without a material 

262 send no light: they never glow.""" 

263 

264 @property 

265 def background_color(self) -> ManimColor: 

266 """The color of the background: the configured one unless changed. Set it to any 

267 color.""" 

268 return self._background_color 

269 

270 @background_color.setter 

271 def background_color(self, color: ParsableManimColor) -> None: 

272 self._background_color = ManimColor(color) 

273 

274 # ── the view (CE MovingCamera semantics: the frame mobject is the truth) ──── 

275 @property 

276 def frame_center(self) -> Point3D: 

277 """The point the camera looks at: its frame's center. Set it to move the frame 

278 there.""" 

279 return self.frame.get_center() 

280 

281 @frame_center.setter 

282 def frame_center(self, point: Point3D) -> None: 

283 self.frame.move_to(point) 

284 

285 @property 

286 def frame_width(self) -> float: 

287 """The width of the view, in scene units: its frame's.""" 

288 return self.frame.width 

289 

290 @property 

291 def frame_height(self) -> float: 

292 """The height of the view, in scene units: its frame's.""" 

293 return self.frame.height 

294 

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

296 def get_mobjects_indicating_movement(self) -> list[Mobject]: 

297 """The mobjects the view is made of: moving any of them moves the camera. 

298 

299 Returns: 

300 The frame, the five trackers of the orbit, and the light, in a new list. 

301 """ 

302 # the view (`feed.view`) reads nothing else a tween can move 

303 return [self.frame, *self.get_value_trackers(), self.light_source] 

304 

305 @overload 

306 def auto_zoom( 

307 self, 

308 mobjects: Iterable[Mobject], 

309 margin: float = 0, 

310 animate: Literal[True] = True, 

311 ) -> Animate[Mobject]: ... 

312 @overload 

313 def auto_zoom( 

314 self, mobjects: Iterable[Mobject], margin: float = 0, *, animate: Literal[False] 

315 ) -> Mobject: ... 

316 @overload 

317 def auto_zoom( 

318 self, mobjects: Iterable[Mobject], margin: float, animate: Literal[False] 

319 ) -> Mobject: ... 

320 def auto_zoom( 

321 self, 

322 mobjects: Iterable[Mobject], 

323 margin: float = 0, 

324 animate: bool = True, 

325 ) -> Animate[Mobject] | Mobject: 

326 """Fit the view around mobjects, in two dimensions: center the frame on them, 

327 and size it to fit them. 

328 

329 The frame keeps its proportions: its width fits the mobjects, or its height, 

330 whichever of the two they fill more of, and `margin` is added to it. 

331 

332 Args: 

333 mobjects: The mobjects to fit, the frame itself left out; at least one must 

334 remain (a ValueError otherwise). 

335 margin: How much wider (or taller) than the mobjects the view is, in scene 

336 units. 

337 animate: Whether to return an animation of the frame, to play, rather than 

338 fit it at once. 

339 

340 Returns: 

341 The animation, to play; with `animate` False, the frame, fitted. 

342 """ 

343 mobs = [m for m in mobjects if m is not self.frame] 

344 if not mobs: 

345 raise ValueError( 

346 "Could not determine bounding box of the mobjects given to 'auto_zoom'." 

347 ) 

348 left, right = ( 

349 min(m.get_critical_point(LEFT)[0] for m in mobs), 

350 max(m.get_critical_point(RIGHT)[0] for m in mobs), 

351 ) 

352 up, down = ( 

353 max(m.get_critical_point(UP)[1] for m in mobs), 

354 min(m.get_critical_point(DOWN)[1] for m in mobs), 

355 ) 

356 target = ( 

357 (self.frame.animate if animate else self.frame) 

358 .set_x((left + right) / 2) 

359 .set_y((up + down) / 2) 

360 ) 

361 if (right - left) / self.frame.width > (up - down) / self.frame.height: 

362 return target.set(width=right - left + margin) 

363 return target.set(height=up - down + margin) 

364 

365 # ── the 3D orbit ─────────────────────────────────────────────────────────── 

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

367 def get_value_trackers(self) -> list[ValueTracker]: 

368 """The five trackers of the camera's orbit. 

369 

370 Returns: 

371 The trackers of `phi`, `theta`, the focal distance, `gamma` and the zoom, in 

372 that order, in a new list. 

373 """ 

374 return [ 

375 self.phi_tracker, 

376 self.theta_tracker, 

377 self.focal_distance_tracker, 

378 self.gamma_tracker, 

379 self.zoom_tracker, 

380 ] 

381 

382 def get_phi(self) -> float: 

383 """The angle between the camera's line of sight and the z axis. 

384 

385 Returns: 

386 The angle, in radians. 

387 """ 

388 return self.phi_tracker.get_value() 

389 

390 def get_theta(self) -> float: 

391 """The camera's angle around the z axis, counterclockwise from the x axis. 

392 

393 Returns: 

394 The angle, in radians. 

395 """ 

396 return self.theta_tracker.get_value() 

397 

398 def get_gamma(self) -> float: 

399 """How far the camera turns about its line of sight. 

400 

401 Returns: 

402 The angle, in radians. 

403 """ 

404 return self.gamma_tracker.get_value() 

405 

406 def get_zoom(self) -> float: 

407 """How much the camera magnifies. 

408 

409 Returns: 

410 The zoom: 1 for none. 

411 """ 

412 return self.zoom_tracker.get_value() 

413 

414 def get_focal_distance(self) -> float: 

415 """The camera's distance from its frame's center. 

416 

417 Returns: 

418 The distance, in scene units. 

419 """ 

420 return self.focal_distance_tracker.get_value() 

421 

422 def set_phi(self, value: float) -> None: 

423 """Set the angle between the camera's line of sight and the z axis, at once. 

424 

425 Args: 

426 value: The angle, in radians: 0 looks straight down on the xy plane. 

427 """ 

428 self.phi_tracker.set_value(value) 

429 

430 def set_theta(self, value: float) -> None: 

431 """Set the camera's angle around the z axis, at once. 

432 

433 Args: 

434 value: The angle, in radians, counterclockwise from the x axis. 

435 """ 

436 self.theta_tracker.set_value(value) 

437 

438 def set_gamma(self, value: float) -> None: 

439 """Set how far the camera turns about its line of sight, at once. 

440 

441 Args: 

442 value: The angle, in radians. 

443 """ 

444 self.gamma_tracker.set_value(value) 

445 

446 # ── objects pinned to the screen ───────────────────────────────────────────── 

447 @property 

448 def fixed_in_frame_mobjects(self) -> set[Mobject]: 

449 """The mobjects pinned to the screen: those given to 

450 [`add_fixed_in_frame_mobjects`][manimgx.Camera.add_fixed_in_frame_mobjects], 

451 with every member of their families as they are now: a part one gains later (a 

452 number's new digits, what an updater or a Transform makes) is pinned with it.""" 

453 return {m for mob in self._fixed_in_frame for m in mob.get_family()} 

454 

455 def add_fixed_in_frame_mobjects(self, *mobjects: Mobject) -> None: 

456 """Pin mobjects to the screen: each is drawn where its points are, as in a 

457 two-dimensional view centered on the origin, over everything else. 

458 

459 They stay where they are on the screen whatever the camera's angles, zoom and 

460 center: a title placed with `to_corner` stays in its corner. Everything in them 

461 is pinned, now and later: a member added later (a number's new digits, what an 

462 updater or a Transform makes) is pinned too. 

463 

464 Args: 

465 *mobjects: The mobjects to pin, with their families. 

466 """ 

467 self._fixed_in_frame.update(dict.fromkeys(mobjects)) 

468 

469 def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject) -> None: 

470 """Unpin mobjects from the screen: undo 

471 [`add_fixed_in_frame_mobjects`][manimgx.Camera.add_fixed_in_frame_mobjects], so 

472 the camera's angles, zoom and center move them again, among the scene's depths. 

473 

474 A mobject that was not pinned is passed over. One that is a member of a pinned 

475 mobject stays pinned with it: unpin that mobject instead. 

476 

477 Args: 

478 *mobjects: The mobjects to unpin, as they were pinned. 

479 """ 

480 for mob in mobjects: 

481 self._fixed_in_frame.pop(mob, None) 

482 

483 

484type Act = Callable[[Fraction, "Route | None"], Callable[[], None] | None] 

485"""A play's step at an instant: it brings what runs there (of the parts given, if any), and 

486returns what opens there (to run once the world is there), if anything.""" 

487 

488 

489class Concern(NamedTuple): 

490 """What an instant of a play concerns (`Scene._exact`): the route to its parts, and the 

491 mobjects whose time-based updaters are brought there.""" 

492 

493 parts: Route 

494 mobjects: list[Mobject] 

495 

496 

497class ZoomedCameraConfig(TypedDict, total=False): 

498 """The zoomed camera's look: its frame's stroke and its picture's background.""" 

499 

500 default_frame_stroke_width: float 

501 """The width of the zoomed camera frame's outline, in hundredths of a scene unit 

502 (default 2).""" 

503 default_frame_stroke_color: ParsableManimColor 

504 """The color of the zoomed camera frame's outline (default white).""" 

505 background_opacity: float 

506 """The opacity of the zoomed picture's background, from 0 to 1 (default 1: it hides 

507 what is behind the display).""" 

508 

509 

510class Scene: 

511 """A scene: one video, and what happens in it. 

512 

513 Make a class from it, and write what happens in its 

514 [`construct`][manimgx.Scene.construct] method: ManimGX runs it once, from top to 

515 bottom, and [`render`][manimgx.Scene.render] records the video. A mobject shows from 

516 the moment the scene holds it ([`add`][manimgx.Scene.add] puts one in). Time passes 

517 only in [`play`][manimgx.Scene.play] and [`wait`][manimgx.Scene.wait]: whatever 

518 `construct` does between them happens at one moment. 

519 

520 Each frame shows the scene at its own exact time, so a scene is the same at every 

521 frame rate: a second of animation is 60 frames at 60 frames a second, and 30 at 30. 

522 When `construct` ends, a last frame shows the scene as it ends, so that its last 

523 animation is seen landing. The methods that change a scene give it back, so that 

524 their calls chain. 

525 

526 Examples: 

527 ```python 

528 import manimgx as m 

529 

530 

531 class SceneExample(m.Scene): 

532 def construct(self) -> None: 

533 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5) 

534 self.play(m.Create(square)) # from 0 s to 1 s 

535 self.wait() # from 1 s to 2 s 

536 self.play(square.animate.rotate(m.PI / 4)) # from 2 s to 3 s 

537 ``` 

538 """ 

539 

540 three_d: bool = False 

541 """Whether the scene's camera sees in three dimensions: True for a 

542 [`ThreeDScene`][manimgx.ThreeDScene].""" 

543 compositor: Compositor | None = None # a play's: its tweens' leaves (`play`) 

544 

545 def __init__(self) -> None: 

546 clock.reset() # a new world: its clock at 0 

547 self.camera = Camera(three_d=self.three_d) 

548 """The scene's camera: what a frame shows. Move, scale or animate its 

549 [`frame`][manimgx.Camera.frame] to pan and zoom.""" 

550 self.mobjects: list[Mobject] = [] 

551 """The mobjects the scene holds, in drawing order: each is drawn over those 

552 before it, at an equal z-index. [`add`][manimgx.Scene.add] and 

553 [`remove`][manimgx.Scene.remove] change it.""" 

554 self.foreground_mobjects: list[Mobject] = [] 

555 """The mobjects kept in front: drawn over all the others, at an equal z-index 

556 (see [`add_foreground_mobjects`][manimgx.Scene.add_foreground_mobjects]). They 

557 are among the scene's [`mobjects`][manimgx.Scene.mobjects] too.""" 

558 self.updaters: list[Callable[[float], object]] = [] 

559 """The scene's own updaters, in the order they run (see 

560 [`add_updater`][manimgx.Scene.add_updater]).""" 

561 self._since: dict[object, Fraction] = {} # when each scene updater was last run 

562 self.clock = Fraction(0) 

563 """The scene's time, exact: a fraction of seconds (see 

564 [`time`][manimgx.Scene.time]).""" 

565 self.frame = 0 

566 """How many frames the scene has recorded: the number of the next one, which 

567 shows the world at `frame / fps` seconds.""" 

568 self._records = False # does anything record the world (`_recording`), this run 

569 # the play's instants no frame shows, with what each concerns (`_exact`, `_ticks`) 

570 self._events: dict[Fraction, Concern | None] = {} 

571 self._playing: list[Mobject] = [] # what the play running acts on (`_running`) 

572 # while animations begin together (`_together`): what the scene held, by id, and 

573 # the list of mobjects it was found in (`_introduce`) 

574 self._beginning = False 

575 self._holding: tuple[list[Mobject], set[int]] | None = None 

576 # the play running: its animations may hide parts of the scene (`display_list`) 

577 self._animation: Animation | None = None 

578 self.num_plays = 0 

579 """How many plays and waits the scene has run.""" 

580 self.film = Film() 

581 """The film the scene records: [`render`][manimgx.Scene.render] makes a new one, 

582 and returns it.""" 

583 

584 @property 

585 @deprecated( 

586 "Manim CE's: the scene is its own renderer: use the scene", category=None 

587 ) 

588 def renderer(self) -> Self: 

589 """The scene itself: Manim code reaches the camera and the time through 

590 `self.renderer`, and a scene has both.""" 

591 return self 

592 

593 @property 

594 def time(self) -> float: 

595 """The scene's time, in seconds. 

596 

597 In `construct`, it is 0 when the scene begins, and the end of each play or wait 

598 once it returns. During a play, while animations and updaters run, it is the time 

599 of the frame being made. 

600 """ 

601 return float(clock.now) 

602 

603 # ── lifecycle ───────────────────────────────────────────────────────────── 

604 def setup(self) -> None: 

605 """Prepare the scene: [`render`][manimgx.Scene.render] calls it before 

606 `construct`. 

607 

608 It does nothing unless overridden: override it for what several scenes share, in 

609 a class they derive from. 

610 """ 

611 

612 def construct(self) -> None: 

613 """Describe the scene, what happens and when: override it. 

614 

615 [`render`][manimgx.Scene.render] runs it once, from top to bottom, and the film 

616 is what it leaves behind. It is ordinary Python: loops, functions and variables 

617 work as they do anywhere. 

618 """ 

619 

620 def tear_down(self) -> None: 

621 """Finish the scene: [`render`][manimgx.Scene.render] calls it after 

622 `construct`, before the closing frame. 

623 

624 It does nothing unless overridden. 

625 """ 

626 

627 @staticmethod 

628 def _fps() -> Fraction: 

629 return clock.rational(config.frame_rate) 

630 

631 def render( 

632 self, 

633 video: str | os.PathLike[str] | None = None, 

634 *, 

635 preset: X264Preset = DEFAULT_ENCODER_PRESET, 

636 crf: float = DEFAULT_ENCODER_CRF, 

637 frames: FrameSink | None = None, 

638 plays: PlayHook | None = None, 

639 take: Take | None = None, 

640 ) -> Film: 

641 """Run the scene and record its film: `setup`, `construct` and `tear_down`, then 

642 a closing frame. 

643 

644 Each frame is sent as it is made: encoded into `video`, an MP4 file, and handed to 

645 `frames`, if given; each play or wait, as it ends, is handed to `plays`, if given. 

646 A frame is drawn only for the video, or when `frames` asks for its pixels: with 

647 neither, the frames are counted, not drawn, which checks a scene quickly. Frames 

648 `k = 0, 1, …` sample `k / fps` seconds, after events at the same float instant; 

649 the closing frame then shows it at its own instant: the scene's end if a frame falls 

650 there, or else the first frame time after it. So the scene's last animation is 

651 seen landing. 

652 

653 Either function, and a take, may raise [`Cut`][manimgx.rendering.film.Cut] to end the 

654 film there: the scene stops, and the video is written up to the last frame sent. 

655 If the scene fails, the video is not written. A scene renders once: make a new 

656 one to render it again. 

657 

658 Args: 

659 video: The MP4 file to write, if any, at the size and frame rate of 

660 [`config`][manimgx.config] (a whole number of frames a second, 

661 and an even width and height); its folder is made if it is missing. 

662 preset: The x264 encoding preset; faster presets make larger files. 

663 crf: The x264 constant rate factor, from 0 to 51; lower values give 

664 higher quality. 

665 frames: A function handed each frame as it is sent (a 

666 [`FrameSink`][manimgx.rendering.film.FrameSink]): a [`Frame`][manimgx.rendering.film.Frame], 

667 which knows its place in the film and draws its pixels when asked. 

668 plays: A function called as each play or wait ends (a 

669 [`PlayHook`][manimgx.rendering.film.PlayHook]), with the [`Play`][manimgx.rendering.film.Play] 

670 and the animations it played, the world as the play left it. 

671 take: Record the film as a take instead, for ManimGX's player to draw: a 

672 function handed its bytes as they are recorded (a 

673 [`Take`][manimgx.rendering.film.Take]). A take has no video, and no frames for 

674 `frames`. 

675 

676 Returns: 

677 The film: how many frames it has, its plays, sections, sounds and captions, 

678 and how its video was made. 

679 """ 

680 self.film = Film( 

681 video, frames=frames, plays=plays, take=take, preset=preset, crf=crf 

682 ) 

683 clock.reset() 

684 try: 

685 self.setup() 

686 self.construct() 

687 self.tear_down() 

688 closing = Fraction(self.frame) / self._fps() 

689 if float(closing) > float( 

690 clock.now 

691 ): # the scene ended between frames: the world at frame N 

692 self._records = self._recording() 

693 self._frame(closing, self._simulation_rate()) 

694 self._emit() 

695 except Cut: 

696 pass # the film ends where it was cut 

697 except BaseException: 

698 self.film.abort() 

699 raise 

700 self.film.close() 

701 return self.film 

702 

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

704 def display_list(self) -> list[Mobject]: 

705 """The mobjects a frame draws, in the order it draws them. 

706 

707 They are the members with points of the scene's mobjects, in family order (a 

708 mobject before its submobjects), the foreground mobjects last, but the parts the 

709 play running hides (its animations' [`hidden`][manimgx.Animation.hidden]); then 

710 sorted by z-index, which keeps that order among equal ones. A member held twice 

711 is drawn once, at its last place. 

712 

713 Returns: 

714 A new list. 

715 """ 

716 members = _family([*self.mobjects, *self.foreground_mobjects]) 

717 if self._animation is not None and (parts := self._animation.hidden): 

718 hidden = {id(m) for m in _family(parts)} 

719 members = [m for m in members if id(m) not in hidden] 

720 leaves = [m for m in members if m.has_points()] 

721 leaves.sort(key=lambda m: m.z_index) 

722 return leaves 

723 

724 def _emit(self, repeat: int = 1) -> None: 

725 """Record frames self.frame … self.frame + repeat − 1 (identical: one packet, repeated).""" 

726 if repeat > 0: 

727 self.film.record(self.camera, self.display_list(), repeat) 

728 self.frame += repeat 

729 

730 def _run( 

731 self, 

732 end: Fraction, 

733 act: Act | None = None, 

734 stop: Callable[[], bool] | None = None, 

735 frozen: bool = False, 

736 boundaries: dict[float, Fraction] | None = None, 

737 ) -> None: 

738 """Run to `end`: frames in the observed [clock, end) show the world at their instants (`act` is 

739 the play's step, before the updaters); then the world is brought to `end`. `stop` ends the run 

740 at the frame it holds after. A frozen run, or one where nothing can change, is one held frame; 

741 while anything is simulated, the world also steps at the simulation clock's ticks. 

742 """ 

743 fps, stopped = self._fps(), False 

744 limit = clock.frame_at(end, fps) 

745 if frozen or (act is None and stop is None and not self._anything_runs()): 

746 self._emit(limit - self.frame) 

747 if frozen: 

748 for mob in self.mobjects: 

749 mob._stamp(end) 

750 self._since = dict.fromkeys(self._since, end) 

751 clock.now = end 

752 else: 

753 rate = self._simulation_rate() 

754 self._records = self._recording() 

755 while self.frame < limit: 

756 t = self._sample(Fraction(self.frame) / fps, boundaries) 

757 self._frame(t, rate, act) 

758 self._emit() 

759 if stop is not None and stop(): 

760 end, stopped = t, True 

761 break 

762 self._ticks(end, rate, act) 

763 if act is not None or end != clock.now: # a play's end, even one of no duration 

764 self._instant(end, act) 

765 elif ( 

766 stopped 

767 ): # a wait's end at a frame: an event, where what is simulated steps 

768 self._instant(end, act, framing=False) 

769 self.clock = end 

770 

771 def _sample( 

772 self, t: Fraction, boundaries: dict[float, Fraction] | None = None 

773 ) -> Fraction: 

774 # A frame observes all events at the same binary64 instant, in exact order. 

775 # It must not rewind an event just beyond its mathematical grid time. 

776 return max(t, self.clock, boundaries.get(float(t), t) if boundaries else t) 

777 

778 def _simulation_rate(self) -> int | None: 

779 """The simulation clock's rate, if anything in the scene is simulated (a time-based 

780 updater that is not a flow — an integrator, a traced path), or in what the play 

781 running will bring into it or run; else None.""" 

782 if any(simulated(u) for u in self.updaters) or any( 

783 simulated(u) for m in self._running() for u in m.updaters 

784 ): 

785 return config.simulation_rate 

786 return None 

787 

788 def _recording(self) -> bool: 

789 """Does anything in the scene, or that the play running runs, record the world (a 

790 traced path)?""" 

791 return any(records(u) for m in self._running() for u in m.updaters) 

792 

793 def _running(self) -> list[Mobject]: 

794 """The scene's members, and the mobjects the play running acts on and their 

795 families (it may bring them into the scene, or run a target's updaters).""" 

796 return self.get_mobject_family_members() + [ 

797 m for mob in self._playing for m in mob.get_family() 

798 ] 

799 

800 def _ticks( 

801 self, 

802 until: Fraction, 

803 rate: int | None, 

804 act: Act | None = None, 

805 ) -> None: 

806 """The world at every instant after now and before `until` that no frame shows: the 

807 simulation clock's ticks, where what is simulated steps, and the play's events (its 

808 parts' windows opening and closing), where it does not (a simulation's steps are its 

809 clock's, whatever the plays).""" 

810 ticks = ( 

811 set() 

812 if rate is None 

813 else { 

814 Fraction(k, rate) 

815 for k in range(clock.now * rate // 1 + 1, -(-until * rate // 1)) 

816 } 

817 ) 

818 events = {e: c for e, c in self._events.items() if clock.now < e < until} 

819 for t in sorted(ticks | events.keys()): 

820 concern = events.get(t) 

821 if act is None or t in ticks or concern is None: 

822 self._instant( 

823 t, act, stepping=t in ticks or rate is None, framing=False 

824 ) 

825 else: 

826 self._event(t, act, concern) 

827 

828 def _frame( 

829 self, 

830 t: Fraction, 

831 rate: int | None, 

832 act: Act | None = None, 

833 ) -> None: 

834 """The world a frame at `t` shows: the simulation clock's ticks until then, then `t` — 

835 where what is simulated steps only if `t` is a tick.""" 

836 self._ticks(t, rate, act) 

837 self._instant(t, act, rate is None or (t * rate).denominator == 1) 

838 

839 def _anything_runs(self) -> bool: 

840 return bool(self.updaters) or any( 

841 m.updaters for m in self.get_mobject_family_members() 

842 ) 

843 

844 def _instant( 

845 self, 

846 t: Fraction, 

847 act: Act | None = None, 

848 stepping: bool = True, 

849 framing: bool = True, 

850 ) -> None: 

851 """The world at `t`: the play's step, then every updater brought to `t` (simulated ones only 

852 where `stepping`, per-frame ones only where `framing`), then the recorders. In a scene 

853 that records (`_records`), a frame or an event is computed twice: the world as time 

854 brought it there (as a tick sees it), then with its per-frame updaters run; the 

855 recorders record both (`TracedPath` spreads what the per-frame updaters changed over the 

856 frame).""" 

857 if framing and self._records: 

858 self._pass(t, act, stepping, False) 

859 self._pass(t, act, False, True) 

860 else: 

861 self._pass(t, act, stepping, framing) 

862 clock.stepping = clock.framing = True 

863 

864 def _pass( 

865 self, 

866 t: Fraction, 

867 act: Act | None, 

868 stepping: bool, 

869 framing: bool, 

870 ) -> None: 

871 clock.now, clock.stepping, clock.framing = t, stepping, framing 

872 # the play brings what runs to `t`, then the updaters; then what opens at `t` begins, 

873 # the world at `t` 

874 opening = act(t, None) if act is not None else None 

875 recorders: list[_Recorder] | None = [] if self._records else None 

876 for mob in self.mobjects: 

877 mob.advance(t, recorders=recorders) 

878 updaters = self.updaters 

879 for func in updaters: 

880 if updaters is not self.updaters and not _has_updater(self.updaters, func): 

881 continue 

882 if not stepping and simulated(func): 

883 continue 

884 since = self._since.get(func, t) 

885 self._since[func] = t 

886 func(float(t - since)) 

887 if opening is not None: 

888 self._together(opening) 

889 for mob, recorder, _ in recorders or (): # if still there when its turn comes 

890 if not mob.updating_suspended and _has_updater(mob.updaters, recorder): 

891 mob._bring(recorder, t) 

892 

893 def _pure_tweens( 

894 self, anim: Animation, alpha: list[float] 

895 ) -> tuple[list[tuple[Transform, Path]], set[int]] | None: 

896 """A play that is a pure function of time — its tweens (Transforms along a `Path` between 

897 fixed keyframes, one per leaf, under compositions that only time them, going forward) and the 

898 objects it introduces; None if anything else acts (updaters, procedures, a camera's picture), 

899 and then every frame is computed. Its groups begin every part now (`begin_all`): nothing a 

900 part reads when it begins can change before its window opens.""" 

901 from manimgx.animation.timeline import ( 

902 Animation, 

903 AnimationGroup, 

904 Wait, 

905 _held, 

906 _updating, 

907 walk, 

908 ) 

909 from manimgx.animation.transform import Transform 

910 from manimgx.audio.sound import Sound 

911 from manimgx.drawing.geometry import Path 

912 

913 members = self.get_mobject_family_members() 

914 if self.updaters or any( 

915 m.updaters or isinstance(m.paint.texture, Camera) for m in members 

916 ): 

917 return None 

918 tweens: list[tuple[Transform, Path]] = [] 

919 begins: list[int] = [] # the frame each tween begins at 

920 for node, progress, closes in walk(anim, np.array(alpha)): 

921 if not _forward(progress): 

922 return None 

923 if isinstance(node, AnimationGroup): # it only times its parts 

924 if type(node).interpolate is not AnimationGroup.interpolate or ( 

925 closes.any() # and closes before the play ends, changing the 

926 and type(node).clean_up_from_scene # scene only as its parts do 

927 is not AnimationGroup.clean_up_from_scene 

928 ): 

929 return None 

930 continue 

931 if isinstance(node, Sound | Wait): # acts on nothing 

932 continue 

933 if not isinstance(node, Transform): 

934 return None 

935 kind, path = type(node), node.path_func 

936 if not ( 

937 isinstance(path, Path) 

938 and kind.interpolate is Animation.interpolate 

939 and kind.interpolate_mobject is Animation.interpolate_mobject 

940 and kind.interpolate_keyframes is Transform.interpolate_keyframes 

941 and kind.hidden is Animation.hidden # (it hides nothing) 

942 and not _updating(node.mobject) # (no updaters act while it plays) 

943 and node.moving_target() is None 

944 ): 

945 return None 

946 if closes.any() and ( # it leaves before the play ends: as a remover 

947 node.replace_mobject_with_target_in_scene # (showing nothing as it 

948 or not ( # leaves), or changing nothing 

949 node.is_remover() 

950 or kind.clean_up_from_scene is Transform.clean_up_from_scene 

951 ) 

952 ): 

953 return None 

954 tweens.append((node, path)) 

955 begun = progress == progress 

956 begins.append(int(np.argmax(begun)) if begun.any() else len(alpha)) 

957 driven = [id(m) for tween, _ in tweens for m in tween.mobject.get_family()] 

958 if len(driven) != len( 

959 set(driven) 

960 ): # a leaf two tweens drive: every frame computed 

961 return None 

962 for (tween, _), first in zip(tweens, begins, strict=True): 

963 target = { 

964 id(m) 

965 for key in tween.keys 

966 if isinstance(key, Mobject) 

967 for m in key.get_family() 

968 } 

969 if first == 0 or not target: 

970 continue 

971 if any( 

972 begin < first 

973 and not target.isdisjoint(id(m) for m in other.mobject.get_family()) 

974 for (other, _), begin in zip(tweens, begins, strict=True) 

975 ): # its target is moved before it begins: every frame computed 

976 return None 

977 present = {id(m) for m in self.mobjects} 

978 if isinstance(anim, AnimationGroup): 

979 self._together(anim.begin_all) 

980 # what the parts brought into the scene as they began (not the parts aligning a 

981 # mobject split out of it: those were there, and show until their part's window 

982 # opens), in the order they begin, as frame by frame 

983 opens = { 

984 id(mob): b 

985 for (t, _), b in zip(tweens, begins, strict=True) 

986 for mob in _held(t.mobject) 

987 } 

988 new = [root for root in self.mobjects if id(root) not in present] 

989 new.sort(key=lambda root: opens.get(id(root), 0)) 

990 self.mobjects = [r for r in self.mobjects if id(r) in present] + new 

991 introduced = {id(x) for root in new for x in root.get_family()} 

992 # each tween's path as its beginning decided it (`.animate` makes its turns a motion 

993 # when it begins): read now, not before its part began (a Path stays a Path) 

994 return [ 

995 (tween, cast("Path", tween.path_func)) for tween, _ in tweens 

996 ], introduced 

997 

998 def _advance_tweens( 

999 self, 

1000 anim: Animation, 

1001 tweens: list[tuple[Transform, Path]], 

1002 alpha: list[float], 

1003 introduced: set[int], 

1004 ) -> None: 

1005 """A pure play at once: each tween's alpha at every frame from its compositions' clocks 

1006 (`schedule`); the film mixes the frames.""" 

1007 leaves = _tracks(anim, tweens, np.array(alpha), introduced) 

1008 self.film.tween(self.camera, self.display_list(), leaves) 

1009 self.frame += len(alpha) 

1010 

1011 # ── membership (CE semantics, including group restructuring) ──────────────── 

1012 def add(self, *mobjects: Mobject) -> Self: 

1013 """Put mobjects in the scene, from now on, in front of those it holds. 

1014 

1015 Each is drawn over the mobjects added before it (at an equal z-index), and under 

1016 the foreground mobjects. A mobject the scene holds already moves to the front. 

1017 One that is part of a group the scene holds is taken out of the group's place: 

1018 the group is split, its other members staying where they are, each on its own 

1019 (and the group's own updaters no longer run); a group added takes its members 

1020 from wherever the scene held them. The updaters of the mobjects added run from 

1021 now on: a time-based one's first `dt` counts from the moment its mobject joins 

1022 the scene. 

1023 

1024 Args: 

1025 *mobjects: The mobjects, in order: the last is drawn on top. 

1026 

1027 Examples: 

1028 ```python 

1029 import manimgx as m 

1030 

1031 

1032 class SceneAddExample(m.Scene): 

1033 def construct(self) -> None: 

1034 square = m.Square(side_length=3.5, color=m.BLUE, fill_opacity=1) 

1035 circle = m.Circle(radius=1.8, color=m.YELLOW, fill_opacity=1) 

1036 circle.shift(1.8 * m.RIGHT) 

1037 self.add(square, circle) # the circle, added last, is on top 

1038 self.wait() 

1039 self.add(square) # adding it again brings it to the front 

1040 self.wait() 

1041 ``` 

1042 """ 

1043 if any(m.updaters for mob in mobjects for m in mob.get_family()): 

1044 present = {id(m) for m in self.get_mobject_family_members()} 

1045 for mob in mobjects: # joining the world: its updaters are live from now 

1046 for m in mob.get_family(): 

1047 if id(m) not in present: 

1048 m._stamp(clock.now, recursive=False) 

1049 new = remove_list_redundancies([*mobjects, *self.foreground_mobjects]) 

1050 self.mobjects = _restructure(self.mobjects, new) + new 

1051 return self 

1052 

1053 def remove(self, *mobjects: Mobject) -> Self: 

1054 """Take mobjects out of the scene: they are no longer drawn, and their updaters 

1055 stop. 

1056 

1057 A mobject that is part of a group the scene holds is taken out the same way: the 

1058 group is split, its other members staying in the scene, each on its own. A 

1059 mobject the scene does not hold is ignored. The mobjects themselves are not 

1060 changed: adding one again shows it as it is then. 

1061 

1062 Args: 

1063 *mobjects: The mobjects to take out. 

1064 """ 

1065 self.mobjects = _restructure(self.mobjects, mobjects, extract=False) 

1066 self.foreground_mobjects = _restructure( 

1067 self.foreground_mobjects, mobjects, extract=False 

1068 ) 

1069 return self 

1070 

1071 def add_foreground_mobjects(self, *mobjects: Mobject) -> Self: 

1072 """Put mobjects in the scene, in front: drawn over all the others, at an equal 

1073 z-index, even those added after them. 

1074 

1075 Args: 

1076 *mobjects: The mobjects, in order: the last is drawn on top. 

1077 """ 

1078 self.foreground_mobjects = remove_list_redundancies( 

1079 [*self.foreground_mobjects, *mobjects] 

1080 ) 

1081 return self.add(*mobjects) 

1082 

1083 @deprecated( 

1084 "add_foreground_mobject is add_foreground_mobjects: use it", category=None 

1085 ) 

1086 def add_foreground_mobject(self, *mobjects: Mobject) -> Self: 

1087 """The same as 

1088 [`add_foreground_mobjects`][manimgx.Scene.add_foreground_mobjects].""" 

1089 return self.add_foreground_mobjects(*mobjects) 

1090 

1091 def remove_foreground_mobjects(self, *mobjects: Mobject) -> Self: 

1092 """Take mobjects out of the front: they stay in the scene, where they are in its 

1093 drawing order, and mobjects added later are drawn over them. 

1094 """ 

1095 self.foreground_mobjects = _restructure(self.foreground_mobjects, mobjects) 

1096 return self 

1097 

1098 @deprecated( 

1099 "remove_foreground_mobject is remove_foreground_mobjects: use it", category=None 

1100 ) 

1101 def remove_foreground_mobject(self, *mobjects: Mobject) -> Self: 

1102 """The same as 

1103 [`remove_foreground_mobjects`][manimgx.Scene.remove_foreground_mobjects].""" 

1104 return self.remove_foreground_mobjects(*mobjects) 

1105 

1106 def bring_to_front(self, *mobjects: Mobject) -> Self: 

1107 """Draw mobjects over the others, but under the foreground mobjects: the same as 

1108 [`add`][manimgx.Scene.add]. 

1109 

1110 Args: 

1111 *mobjects: The mobjects, in order: the last is drawn on top. 

1112 """ 

1113 return self.add(*mobjects) 

1114 

1115 def bring_to_back(self, *mobjects: Mobject) -> Self: 

1116 """Draw mobjects under all the others, at an equal z-index: they move to the 

1117 start of the scene's mobjects, out of the foreground if they were in it. 

1118 

1119 A mobject the scene does not hold is added there, at the bottom. 

1120 

1121 Args: 

1122 *mobjects: The mobjects, in order: the first is drawn at the bottom. 

1123 """ 

1124 self.remove(*mobjects) 

1125 self.mobjects = [*mobjects, *self.mobjects] 

1126 return self 

1127 

1128 def clear(self) -> Self: 

1129 """Take every mobject out of the scene, the foreground ones too; the scene's own 

1130 updaters stay. 

1131 """ 

1132 self.mobjects, self.foreground_mobjects = [], [] 

1133 return self 

1134 

1135 def replace(self, old: Mobject, new: Mobject) -> None: 

1136 """Put a mobject in the scene in another's place: where the other is drawn, even 

1137 inside a group, which then holds the new one. 

1138 

1139 `new` is first taken out of the list it joins, if it is there. 

1140 [`ReplacementTransform`][manimgx.ReplacementTransform] ends with it. A mobject 

1141 the scene does not hold raises a ValueError. 

1142 

1143 Args: 

1144 old: The mobject to replace: one the scene holds, or a part of one. 

1145 new: The mobject to put in its place. 

1146 """ 

1147 

1148 def replace_in(lst: list[Mobject]) -> bool: 

1149 if new in lst: 

1150 lst.remove(new) 

1151 for i, m in enumerate(lst): 

1152 if m is old: 

1153 lst[i] = new 

1154 return True 

1155 return any(replace_in(m.submobjects) for m in lst) 

1156 

1157 if not (replace_in(self.mobjects) or replace_in(self.foreground_mobjects)): 

1158 raise ValueError(f"Could not find {old} in scene") 

1159 self._holding = None # (what it holds changed in place) 

1160 

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

1162 def get_mobject_family_members(self) -> list[Mobject]: 

1163 """Every mobject in the scene, with all its submobjects, each once. 

1164 

1165 Returns: 

1166 A new list, in family order, then sorted by z-index (which keeps that order 

1167 among equal ones). 

1168 """ 

1169 members = _family(self.mobjects) 

1170 members.sort(key=lambda m: m.z_index) 

1171 return members 

1172 

1173 def add_updater(self, func: Callable[[float], object]) -> None: 

1174 """Add an updater to the scene itself: a function it calls with the time that 

1175 passed. 

1176 

1177 It is handed `dt`, the scene time in seconds since it last ran (or was added), 

1178 at each instant the scene computes, after the updaters of the mobjects. It steps 

1179 as a mobject's time-based updater does: on the simulation clock 

1180 ([`config.simulation_rate`][manimgx.settings.Config.simulation_rate] ticks a 

1181 second, and the end of each play and wait), unless it is a 

1182 [flow][manimgx.mobject.flow], which runs at every frame. What it returns is 

1183 ignored. 

1184 

1185 Args: 

1186 func: The updater: a function of one parameter, named `dt`. 

1187 """ 

1188 self.updaters.append(func) 

1189 self._since[func] = clock.now 

1190 

1191 def remove_updater(self, func: Callable[[float], object]) -> None: 

1192 """Remove an updater from the scene, every time it was added. 

1193 

1194 This also cancels calls that have not yet run in the current update. 

1195 

1196 Args: 

1197 func: The updater. 

1198 """ 

1199 self.updaters = [f for f in self.updaters if f is not func] 

1200 if func not in self.updaters: 

1201 self._since.pop(func, None) 

1202 

1203 # ── time ───────────────────────────────────────────────────────────────────── 

1204 def play(self, *animations: Animation, **options: Unpack[TransformOptions]) -> None: 

1205 """Play animations, together, from the scene's present time. 

1206 

1207 Each animation starts now and lasts its own run time, and ends when its time is up, 

1208 whatever else still plays: the play lasts as long as the longest one. Then 

1209 `construct` goes on, at the time the play ended. To play animations one after 

1210 another, or each a little after the one before it, play a 

1211 [`Succession`][manimgx.Succession] or a [`LaggedStart`][manimgx.LaggedStart]. 

1212 

1213 A play brings into the scene what its animations change, if the scene doesn't 

1214 hold it yet, in the order given. An animation that brings its mobject in 

1215 ([`Create`][manimgx.Create], [`FadeIn`][manimgx.FadeIn], …) adds it as it starts, 

1216 and a replacement adds the mobject it turns into as it ends. One that takes its 

1217 mobject out ([`FadeOut`][manimgx.FadeOut], …) removes it as it ends. A 

1218 [`Wait`][manimgx.Wait] played alone is a [`wait`][manimgx.Scene.wait]. 

1219 

1220 Args: 

1221 *animations: The animations, or iterables of them; at least one. 

1222 **options: [Transform options][manimgx.animation.transform.TransformOptions] 

1223 for every animation: each option given replaces that animation's own. So 

1224 `run_time=2` plays each for 2 seconds, and a `lag_ratio` staggers the 

1225 parts of each (a [`LaggedStart`][manimgx.LaggedStart] staggers the 

1226 animations). 

1227 

1228 Examples: 

1229 ```python 

1230 import manimgx as m 

1231 

1232 

1233 class ScenePlayExample(m.Scene): 

1234 def construct(self) -> None: 

1235 colors = (m.BLUE, m.YELLOW, m.GREEN) 

1236 dots = m.VGroup(*(m.Dot(radius=0.3, color=c) for c in colors)) 

1237 dots.arrange(m.DOWN, buff=1.5).shift(5 * m.LEFT) 

1238 self.add(dots) 

1239 self.play( # all three begin now; the play lasts 3 s 

1240 dots[0].animate(run_time=1).shift(10 * m.RIGHT), 

1241 dots[1].animate(run_time=2).shift(10 * m.RIGHT), 

1242 dots[2].animate(run_time=3).shift(10 * m.RIGHT), 

1243 rate_func=m.linear, # for each of the three 

1244 ) 

1245 ``` 

1246 """ 

1247 from manimgx.animation.timeline import AnimationGroup, Wait, _flatten, prepare 

1248 from manimgx.animation.transform import Compositor 

1249 

1250 anims = [prepare(a) for a in _flatten(animations)] 

1251 if not anims: 

1252 raise ValueError("Called Scene.play with no animations") 

1253 for anim in anims: 

1254 for key, value in options.items(): 

1255 if value is not None: 

1256 setattr(anim, key, value) 

1257 start, index, where = self.clock, self.num_plays, _written() 

1258 wait = anims[0] if len(anims) == 1 and isinstance(anims[0], Wait) else None 

1259 self.num_plays += 1 

1260 if wait is not None: 

1261 end = start + wait._duration 

1262 self._run(end, stop=wait.stop_condition, frozen=bool(wait.is_static_wait)) 

1263 else: 

1264 anim = ( 

1265 anims[0] 

1266 if len(anims) == 1 

1267 else AnimationGroup( 

1268 *anims, group=Group(), suspend_mobject_updating=False 

1269 ) 

1270 ) 

1271 end = start + anim._duration 

1272 self.compositor, self._animation = Compositor(), anim 

1273 try: 

1274 self._play(anim, start, end) 

1275 finally: 

1276 self.compositor, self._animation = None, None 

1277 self.film.played(Play(index, start, self.clock, where), tuple(anims)) 

1278 

1279 def _play(self, anim: Animation, start: Fraction, end: Fraction) -> None: 

1280 from manimgx.animation.timeline import AnimationGroup, Wait, windows 

1281 from manimgx.audio.sound import Clip, Sound 

1282 

1283 self._bring(anim) 

1284 anim._setup_scene(self) 

1285 anim.begin() 

1286 # its sounds start as their windows open: where the layout puts them, whatever path 

1287 # computes the frames 

1288 if _sounds(anim): 

1289 for window in windows(anim): 

1290 if isinstance(window.part, Sound): 

1291 at = start + window.opens * (end - start) 

1292 self.film.clips.append(Clip(window.part, at)) 

1293 if all(isinstance(p, Sound | Wait) for p in _leaves(anim)): 

1294 self._run(end) # nothing on screen moves: as a wait 

1295 anim.finish() 

1296 anim.clean_up_from_scene(self) 

1297 return 

1298 finished = False 

1299 

1300 def act(t: Fraction, only: Route | None) -> Callable[[], None] | None: 

1301 nonlocal finished 

1302 if finished: # the end again, with its per-frame updaters (`_instant`) 

1303 return None 

1304 if t < end: 

1305 alpha = float((t - start) / (end - start)) 

1306 if ( # its parts open once all is at t 

1307 isinstance(anim, AnimationGroup) 

1308 and type(anim).interpolate is AnimationGroup.interpolate 

1309 ): 

1310 anim.advance(t, only) 

1311 return anim._step(alpha, only) 

1312 anim.advance(t) 

1313 anim.interpolate(alpha) 

1314 return None 

1315 # the end: the model as time brought it here; the object's per-frame updaters run 

1316 # once, in this instant's pass, not on the model as well 

1317 framing, clock.framing = clock.framing, False 

1318 anim.advance(t) 

1319 clock.framing = framing 

1320 anim.finish() 

1321 anim.clean_up_from_scene(self) 

1322 finished = True 

1323 return None 

1324 

1325 fps = self._fps() 

1326 parts = windows(anim) 

1327 boundaries: dict[float, Fraction] = {} 

1328 for part in parts: 

1329 for at in (part.opens, part.closes): 

1330 if at is not None: 

1331 time = start + at * (end - start) 

1332 boundaries[float(time)] = max( 

1333 boundaries.get(float(time), time), time 

1334 ) 

1335 frames = range(self.frame, clock.frame_at(end, fps)) 

1336 alpha = [ 

1337 float((self._sample(Fraction(k) / fps, boundaries) - start) / (end - start)) 

1338 for k in frames 

1339 ] 

1340 pure = self._pure_tweens(anim, alpha) 

1341 if pure is None: 

1342 # its parts begin and finish at their windows, whatever the frame rate: at 

1343 # instants of their own where that shows (then the first at its start) 

1344 self._playing = _acted_on(anim) 

1345 self._events = { 

1346 start + x * (end - start): concern 

1347 for x, concern in self._exact(parts).items() 

1348 } 

1349 try: 

1350 if self._events and Fraction(self.frame) / fps != start: 

1351 self._instant(start, act, framing=False) 

1352 self._run(end, act, boundaries=boundaries) 

1353 finally: 

1354 self._events, self._playing = {}, [] 

1355 else: 

1356 tweens, introduced = pure 

1357 self._advance_tweens(anim, tweens, alpha, introduced) 

1358 self._instant(end, act) 

1359 self.clock = end 

1360 

1361 def _exact(self, parts: list[Window]) -> dict[Fraction, Concern | None]: 

1362 """Where in the play (its progress) its parts begin and finish: each an instant the 

1363 scene computes, a frame there or not, with what it concerns: the parts beginning or 

1364 finishing there, the parts running across it that drive what those read or drive, 

1365 and, among what those read or drive, the mobjects with time-based updaters. None: 

1366 everything (a scene's own time-based updater may move anything).""" 

1367 full = any(not _per_frame(u) for u in self.updaters) 

1368 moving = { 

1369 id(m): m 

1370 for m in self._running() 

1371 if any(not _per_frame(u) for u in m.updaters) 

1372 } 

1373 from manimgx.animation.timeline import route 

1374 

1375 writers: dict[int, list[tuple[int, Fraction, Fraction | None]]] = {} 

1376 for part, opens, closes, _ in parts: 

1377 for m in part.mobject.get_family(): 

1378 writers.setdefault(id(m), []).append((id(part), opens, closes)) 

1379 paths = {id(window.part): window.path for window in parts} 

1380 found: dict[Fraction, tuple[set[int], dict[int, Mobject]]] = {} 

1381 

1382 def concern(at: Fraction, part: Animation, touched: list[Mobject]) -> None: 

1383 ids, mobs = found.setdefault(at, (set(), {})) 

1384 ids.add(id(part)) 

1385 for m in touched: 

1386 ids.update( 

1387 other 

1388 for other, o, c in writers.get(id(m), ()) 

1389 if o < at and (c is None or at < c) # running across it 

1390 ) 

1391 if id(m) in moving: 

1392 mobs[id(m)] = m 

1393 

1394 for part, opens, closes, _ in parts: 

1395 if 0 < opens < 1: 

1396 reads = [part.mobject] + [ 

1397 k for k in part.keys if isinstance(k, Mobject) 

1398 ] 

1399 concern(opens, part, [m for key in reads for m in key.get_family()]) 

1400 if closes is not None and 0 < closes < 1: 

1401 concern(closes, part, part.mobject.get_family()) 

1402 return { 

1403 at: ( 

1404 None 

1405 if full 

1406 else Concern(route(paths[i] for i in ids), list(mobs.values())) 

1407 ) 

1408 for at, (ids, mobs) in sorted(found.items()) 

1409 } 

1410 

1411 def _event(self, t: Fraction, act: Act, concern: Concern) -> None: 

1412 """An instant no frame shows, where parts of the play begin or finish: only what it 

1413 concerns is brought to `t` (see `_exact`); the rest waits for the next frame, where 

1414 nothing can have read it meanwhile. What is simulated does not step here (its steps 

1415 are its clock's), and no per-frame updater runs.""" 

1416 clock.now, clock.stepping, clock.framing = t, False, False 

1417 opening = act(t, concern.parts) 

1418 for mob in concern.mobjects: 

1419 mob.advance(t, recursive=False) 

1420 if opening is not None: 

1421 self._together(opening) 

1422 clock.stepping = clock.framing = True 

1423 

1424 def _together(self, begin: Callable[[], object]) -> None: 

1425 """Run `begin`, in which animations begin together: they all find the scene as it 

1426 was, and what they bring in (`_introduce`) is looked for in what it holds, found 

1427 once for them all.""" 

1428 self._beginning, self._holding = True, None 

1429 try: 

1430 begin() 

1431 finally: 

1432 self._beginning, self._holding = False, None 

1433 

1434 def _introduce(self, mobjects: Sequence[Mobject]) -> None: 

1435 """Bring in, as an animation that introduces them begins, those of `mobjects` the 

1436 scene lacks (with something to draw or to run), each by itself, as `add` does: one 

1437 none of whose family the scene holds joins it without its being searched again.""" 

1438 holding = self._holding 

1439 if holding is None or holding[0] is not self.mobjects: 

1440 holding = (self.mobjects, {id(m) for m in _family(self.mobjects)}) 

1441 held = holding[1] 

1442 lacking = [ 

1443 mob 

1444 for mob in mobjects 

1445 if id(mob) not in held 

1446 and any(m.has_points() or m.updaters for m in mob.get_family()) 

1447 ] 

1448 if lacking: 

1449 family = _family(lacking) 

1450 if self.foreground_mobjects or any(id(m) in held for m in family): 

1451 self.add(*lacking) # (what the scene held of them leaves its place) 

1452 holding = None 

1453 else: 

1454 if any(m.updaters for m in family): # their updaters run from now on 

1455 for m in family: 

1456 m._stamp(clock.now, recursive=False) 

1457 self.mobjects = [*self.mobjects, *remove_list_redundancies(lacking)] 

1458 held.update(id(m) for m in family) 

1459 holding = (self.mobjects, held) 

1460 if self._beginning: 

1461 self._holding = holding 

1462 

1463 def _bring(self, anim: Animation) -> None: 

1464 """Bring into the scene, as a play begins, what its animations act on that it lacks, 

1465 in their order, each by itself (what it holds stays in place): all but what an 

1466 animation introduces (it joins as that animation begins) and what a replacement 

1467 puts in (as it finishes).""" 

1468 from manimgx.animation.timeline import AnimationGroup, _held, _lacks 

1469 from manimgx.animation.transform import Transform 

1470 

1471 promised: set[int] = set() 

1472 members = self.get_mobject_family_members() 

1473 

1474 def visit(anim: Animation) -> None: 

1475 if isinstance(anim, AnimationGroup): 

1476 for part in anim.animations: 

1477 visit(part) 

1478 elif anim.is_introducer(): 

1479 promised.update(id(mob) for mob in _held(anim.mobject)) 

1480 else: 

1481 for mob in _held(anim.mobject): 

1482 if id(mob) not in promised and _lacks(mob, members): 

1483 self.add(mob) 

1484 members.extend(mob.get_family()) 

1485 if ( 

1486 isinstance(anim, Transform) 

1487 and anim.replace_mobject_with_target_in_scene 

1488 and anim.target_mobject is not None 

1489 ): 

1490 promised.add(id(anim.target_mobject)) 

1491 

1492 visit(anim) 

1493 

1494 def wait( 

1495 self, 

1496 duration: float = DEFAULT_WAIT_TIME, 

1497 stop_condition: Callable[[], bool] | None = None, 

1498 frozen_frame: bool | None = None, 

1499 ) -> None: 

1500 """Let time pass, playing nothing: the updaters keep running. 

1501 

1502 The video goes on for `duration` seconds, and `construct` goes on at their end. 

1503 With a `stop_condition`, the wait ends at the first frame at which the condition 

1504 holds, and the scene goes on from that frame's time. With `frozen_frame`, the 

1505 picture holds instead: the video goes on for `duration`, but nothing moves, no 

1506 updater runs, and time-based updaters go on afterward as if no time had passed 

1507 (see [`pause`][manimgx.Scene.pause]). 

1508 

1509 Args: 

1510 duration: How long, in seconds. 

1511 stop_condition: A function of no arguments, checked at every frame once it 

1512 is drawn: the wait ends at the first at which it returns True. None: the 

1513 wait lasts its whole duration. 

1514 frozen_frame: Whether the picture holds while the world stands still; it 

1515 cannot be combined with a `stop_condition` (a ValueError). None or 

1516 False: time runs. 

1517 

1518 Examples: 

1519 ```python 

1520 import manimgx as m 

1521 

1522 

1523 class SceneWaitExample(m.Scene): 

1524 def construct(self) -> None: 

1525 square = m.Square(side_length=3, color=m.BLUE, fill_opacity=0.5) 

1526 square.add_updater(lambda mob, dt: mob.rotate(dt * m.PI / 3)) 

1527 self.add(square) 

1528 self.wait(2) # time passes: the updater turns the square 

1529 self.wait(1, frozen_frame=True) # the picture holds 

1530 self.wait(2) # it turns on from where it stopped 

1531 ``` 

1532 """ 

1533 from manimgx.animation.timeline import Wait 

1534 

1535 self.play( 

1536 Wait( 

1537 run_time=duration, 

1538 stop_condition=stop_condition, 

1539 frozen_frame=frozen_frame, 

1540 ) 

1541 ) 

1542 

1543 def pause(self, duration: float = DEFAULT_WAIT_TIME) -> None: 

1544 """Hold the picture while the world stands still: a [`wait`][manimgx.Scene.wait] 

1545 with `frozen_frame`. 

1546 

1547 The video goes on for `duration`; no updater runs, and time-based updaters go on 

1548 afterwards as if no time had passed. 

1549 

1550 Args: 

1551 duration: How long, in seconds. 

1552 """ 

1553 self.wait(duration, frozen_frame=True) 

1554 

1555 def wait_until( 

1556 self, stop_condition: Callable[[], bool], max_time: float = 60 

1557 ) -> None: 

1558 """Let time pass until a condition holds: a [`wait`][manimgx.Scene.wait] that 

1559 ends at the first frame at which `stop_condition` returns True, or after 

1560 `max_time` seconds. 

1561 

1562 Args: 

1563 stop_condition: A function of no arguments, checked at every frame once it 

1564 is drawn. 

1565 max_time: The longest it waits, in seconds. 

1566 """ 

1567 self.wait(max_time, stop_condition=stop_condition) 

1568 

1569 def next_section( 

1570 self, 

1571 name: str = "unnamed", 

1572 section_type: SectionType = "default.normal", 

1573 skip_animations: bool = False, 

1574 *, 

1575 notes: str = "", 

1576 ) -> None: 

1577 """Begin a section of the film here: a slide, when the film is presented. 

1578 

1579 A film is a row of sections, each lasting until the next begins (the first begins 

1580 with the film). Presented (`manimgx present`), the film plays a section and, by 

1581 its type, stops at its end until the presenter goes on, goes on by itself, or 

1582 plays it again and again until the presenter goes on. A section begins at a 

1583 frame, whose picture a presentation stops on: if the scene's time falls between 

1584 two frames, the world holds still until the next one. Rendered, a film just plays 

1585 through its sections. 

1586 

1587 Args: 

1588 name: The section's name. 

1589 section_type: How a presentation plays the section that begins here: 

1590 `"default.normal"` (or `"presentation.normal"`) stops at its end; 

1591 `"presentation.skip"` goes on by itself; `"presentation.loop"` plays it 

1592 again until the presenter goes on; `"presentation.complete_loop"` too, 

1593 finishing its round first. 

1594 skip_animations: Accepted for Manim compatibility; ignored. 

1595 notes: What the presenter reads during the section. 

1596 """ 

1597 fps = self._fps() 

1598 at = Fraction(self.frame) / fps 

1599 if at != self.clock: # to its frame, the world held still 

1600 self._run(at, frozen=True) 

1601 self.film.section(name, self.clock, section_type, notes) 

1602 

1603 def add_subcaption( 

1604 self, content: str, duration: float = 1, offset: float = 0 

1605 ) -> None: 

1606 """Caption the film: `content` shown from now plus `offset`, for `duration` seconds. 

1607 

1608 The film's [`captions`][manimgx.Film.captions] hold it, with those of its 

1609 speech; `manimgx render` writes them beside the video, as subtitles. 

1610 

1611 Args: 

1612 content: The caption's text. 

1613 duration: How long it shows, in seconds. 

1614 offset: How long after now it begins, in seconds. 

1615 """ 

1616 start = float(clock.now) + offset 

1617 self.film.subcaptions.append(Caption(start, start + duration, content)) 

1618 

1619 def say( 

1620 self, script: str, *animations: Animation, voice: Voice | None = None 

1621 ) -> Speech: 

1622 """Speak a script, playing animations as it is said; the scene waits for both. 

1623 

1624 Mark in brackets the words an animation belongs to: the animations given play, 

1625 in order, during the bracketed words, each starting as its words start and 

1626 lasting as long as they take to say, or its own run time if that is longer (an 

1627 empty `[]` starts one where it stands). Without brackets, the animations play 

1628 during the whole speech. The brackets are not spoken: a span is one `[` and its 

1629 `]`, so a nested, unclosed or stray bracket is an error (a ValueError). Text is 

1630 timed in the pieces Unicode lets a line break between, so in text written without 

1631 spaces a span can start on any Chinese or Japanese character, or any Thai word. 

1632 

1633 Args: 

1634 script: What to say, with a bracketed span for each animation (or none). 

1635 *animations: The animations, one per span. 

1636 voice: Who says it; by default the scene's [`voice`][manimgx.Scene.voice]. 

1637 

1638 Returns: 

1639 The speech, with its words and when each is said. 

1640 

1641 Examples: 

1642 ```python 

1643 import manimgx as m 

1644 

1645 

1646 class SayExample(m.Scene): 

1647 def construct(self) -> None: 

1648 x2 = m.MathTex("x^2").shift(2 * m.LEFT) 

1649 dx = m.MathTex("2x").shift(2 * m.RIGHT) 

1650 self.add(x2) 

1651 self.say( 

1652 "The derivative of [x squared] is [two x].", 

1653 m.Indicate(x2), 

1654 m.Write(dx), 

1655 ) 

1656 ``` 

1657 """ 

1658 from manimgx.animation.timeline import AnimationGroup, Succession, Wait 

1659 from manimgx.audio.sound import spans, times 

1660 

1661 text, found = spans(script) 

1662 if found and len(found) != len(animations): 

1663 raise ValueError( 

1664 f"{len(found)} bracketed spans for {len(animations)} animations: give" 

1665 " one animation per span" 

1666 ) 

1667 speech = self.speech(text, voice) 

1668 parts: list[Animation] = [speech] 

1669 for anim, span in zip( 

1670 animations, found or [None] * len(animations), strict=True 

1671 ): 

1672 start, end = (0.0, speech.duration) if span is None else times(speech, span) 

1673 anim.run_time = max(anim.run_time, end - start) 

1674 parts.append(Succession(Wait(start), anim) if start > 0 else anim) 

1675 self.play(AnimationGroup(*parts)) 

1676 return speech 

1677 

1678 def speech(self, text: str, voice: Voice | None = None) -> Speech: 

1679 """What the scene's voice says for `text`, without playing it. 

1680 

1681 Spoken once, then kept in `voice/` beside the scene's file (named by the text), so 

1682 the scene renders again without speaking again; replace a file there with your 

1683 own recording of the same words, and it is used instead. Play the speech, add it 

1684 ([`add_sound`][manimgx.Scene.add_sound]: it speaks while the scene goes on), or 

1685 read its [`words`][manimgx.Speech.words]. 

1686 

1687 Args: 

1688 text: What to say. 

1689 voice: Who says it; by default the scene's [`voice`][manimgx.Scene.voice]. 

1690 

1691 Returns: 

1692 The speech. 

1693 """ 

1694 from manimgx.audio import Fal, cached 

1695 

1696 # the scene's voice, as given: a function set on the class is not a method of it 

1697 own = self.__dict__.get("voice", inspect.getattr_static(type(self), "voice")) 

1698 if isinstance(own, staticmethod): 

1699 own = own.__func__ 

1700 return cached(voice or own or Fal(), text, _voice_folder(self)) 

1701 

1702 voice: Voice | None = None 

1703 """Who speaks the scene's [`say`][manimgx.Scene.say]: any 

1704 [voice][manimgx.Voice]; None for fal.ai's default model 

1705 ([`Fal()`][manimgx.Fal]).""" 

1706 

1707 def add_sound( 

1708 self, 

1709 sound: str | os.PathLike[str] | Sound, 

1710 time_offset: float = 0, 

1711 gain: float | None = None, 

1712 ) -> Clip: 

1713 """Start a sound: now, or `time_offset` seconds from now; it takes no time. 

1714 

1715 The scene goes on at once, and the sound plays over whatever follows, until it 

1716 ends (or the film does, or its clip is stopped). Called by an updater, it starts 

1717 at the instant the updater runs for: a bounce sounds exactly at the bounce. To 

1718 wait for a sound, [`play`][manimgx.Scene.play] it instead. 

1719 

1720 Args: 

1721 sound: The sound, or its file. 

1722 time_offset: How long after now it starts, in seconds. 

1723 gain: How much louder it plays, in decibels (negative: quieter). 

1724 

1725 Returns: 

1726 Its clip: [`stop`][manimgx.audio.sound.Clip.stop] it to end it early. 

1727 """ 

1728 from manimgx.audio.sound import Clip, Sound 

1729 

1730 if not isinstance(sound, Sound): 

1731 sound = Sound(sound) 

1732 if gain: 

1733 sound = sound.gain(gain) 

1734 # decoded now: a file it cannot read fails here, not at the end of the render 

1735 _ = sound.samples 

1736 clip = Clip(sound, clock.now + clock.rational(time_offset)) 

1737 self.film.clips.append(clip) 

1738 return clip 

1739 

1740 

1741@deprecated( 

1742 "MovingCameraScene is Scene: every scene's camera moves (self.camera.frame)", 

1743 category=None, 

1744) 

1745class MovingCameraScene(Scene): 

1746 """A scene whose camera moves: the name Manim CE knows it by. Every scene's camera 

1747 moves, so it is a [`Scene`][manimgx.Scene]: animate `self.camera.frame` to pan and 

1748 zoom. 

1749 """ 

1750 

1751 

1752class ZoomedScene(Scene): 

1753 """A scene with a second camera, whose picture is shown in the frame: a magnifying 

1754 glass. 

1755 

1756 `zoomed_camera` sees what its frame, a small rectangle in the scene 

1757 (`zoomed_camera.frame`), covers, and `zoomed_display` shows its picture, larger, in 

1758 a corner of the frame. Both appear with 

1759 [`activate_zooming`][manimgx.ZoomedScene.activate_zooming]; move, scale or animate 

1760 the zoomed camera's frame to look elsewhere, and the picture follows. 

1761 

1762 Args: 

1763 zoomed_display_height: The display's height, in scene units. 

1764 zoomed_display_width: The display's width, in scene units. 

1765 zoomed_display_center: Where the display's center is; None for a corner of the 

1766 frame. 

1767 zoomed_display_corner: Which corner of the frame the display is in, when it has 

1768 no `zoomed_display_center`: a direction, such as [`UR`][manimgx.UR]. 

1769 zoomed_display_corner_buff: The display's distance from the edges at that 

1770 corner, in scene units. 

1771 zoomed_camera_config: [The zoomed camera's look][manimgx.scene.ZoomedCameraConfig]: 

1772 its frame's outline, and its picture's background. 

1773 zoomed_camera_image_mobject_config: Keywords for the display, the picture of 

1774 what the zoomed camera sees: its style, and its outline's 

1775 (`default_display_frame_config`). 

1776 zoomed_camera_frame_starting_position: Where the zoomed camera's frame starts. 

1777 zoom_factor: The size of the zoomed camera's frame, as a fraction of the 

1778 display's: the display magnifies `1 / zoom_factor` times. 

1779 image_frame_stroke_width: Accepted for Manim compatibility; ignored. 

1780 zoom_activated: Whether zooming is active: 

1781 [`activate_zooming`][manimgx.ZoomedScene.activate_zooming] sets it, and it 

1782 shows nothing by itself. 

1783 

1784 Examples: 

1785 ```python 

1786 import manimgx as m 

1787 

1788 

1789 class ZoomedSceneExample(m.ZoomedScene): 

1790 def construct(self) -> None: 

1791 title = m.Text("manimgx", font_size=120).shift(m.LEFT) 

1792 note = m.Text("exact in time, typed throughout", font_size=14) 

1793 note.next_to(title, m.DOWN) 

1794 self.add(title, note) 

1795 frame = self.zoomed_camera.frame 

1796 frame.move_to(note.get_left()) 

1797 self.activate_zooming(animate=True) 

1798 self.play(frame.animate.move_to(note.get_right()), run_time=2) 

1799 ``` 

1800 """ 

1801 

1802 def __init__( 

1803 self, 

1804 zoomed_display_height: float = 3, 

1805 zoomed_display_width: float = 3, 

1806 zoomed_display_center: Point3DLike | None = None, 

1807 zoomed_display_corner: Vector3DLike = UR, 

1808 zoomed_display_corner_buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER, 

1809 zoomed_camera_config: ZoomedCameraConfig | None = None, 

1810 zoomed_camera_image_mobject_config: ImageCameraOptions | None = None, 

1811 zoomed_camera_frame_starting_position: Point3DLike = ORIGIN, 

1812 zoom_factor: float = 0.15, 

1813 image_frame_stroke_width: float = 3, 

1814 zoom_activated: bool = False, 

1815 ) -> None: 

1816 self.zoomed_display_height = zoomed_display_height 

1817 self.zoomed_display_width = zoomed_display_width 

1818 self.zoomed_display_center = zoomed_display_center 

1819 self.zoomed_display_corner = zoomed_display_corner 

1820 self.zoomed_display_corner_buff = zoomed_display_corner_buff 

1821 self.zoomed_camera_config = ZoomedCameraConfig( 

1822 default_frame_stroke_width=2, background_opacity=1 

1823 ) | (zoomed_camera_config or ZoomedCameraConfig()) 

1824 self.zoomed_camera_image_mobject_config: ImageCameraOptions = ( 

1825 zoomed_camera_image_mobject_config or {} 

1826 ) 

1827 self.zoomed_camera_frame_starting_position = ( 

1828 zoomed_camera_frame_starting_position 

1829 ) 

1830 self.zoom_factor = zoom_factor 

1831 self.image_frame_stroke_width = ( 

1832 image_frame_stroke_width # CE stores it and never reads it 

1833 ) 

1834 self.zoom_activated = zoom_activated 

1835 super().__init__() 

1836 

1837 def setup(self) -> None: 

1838 """Make the zoomed camera and its display: [`render`][manimgx.Scene.render] 

1839 calls it before `construct`. A subclass that overrides it calls this one first. 

1840 """ 

1841 from manimgx.mobjects.images import ImageMobjectFromCamera 

1842 

1843 super().setup() 

1844 options = self.zoomed_camera_config 

1845 camera = Camera() 

1846 camera.background_opacity = options.get("background_opacity", 1) 

1847 camera.frame.set_stroke( 

1848 options.get("default_frame_stroke_color", WHITE), 

1849 options.get("default_frame_stroke_width", 2), 

1850 ) 

1851 display = ImageMobjectFromCamera( 

1852 camera, **self.zoomed_camera_image_mobject_config 

1853 ).add_display_frame() 

1854 for mob in (camera.frame, display): 

1855 mob.stretch_to_fit_height(self.zoomed_display_height) 

1856 mob.stretch_to_fit_width(self.zoomed_display_width) 

1857 camera.frame.scale(self.zoom_factor) 

1858 camera.frame.move_to(self.zoomed_camera_frame_starting_position) 

1859 if self.zoomed_display_center is not None: 

1860 display.move_to(self.zoomed_display_center) 

1861 else: 

1862 display.to_corner( 

1863 self.zoomed_display_corner, buff=self.zoomed_display_corner_buff 

1864 ) 

1865 self.zoomed_camera = camera 

1866 self.zoomed_display = display 

1867 

1868 def activate_zooming(self, animate: bool = False) -> None: 

1869 """Show the zoomed camera's frame and its display, in front of everything else. 

1870 

1871 Args: 

1872 animate: Whether to animate their coming first, in two plays: the frame 

1873 shrinks from the whole view to its place (`get_zoom_in_animation`), then 

1874 the display grows out of it to its own 

1875 (`get_zoomed_display_pop_out_animation`). 

1876 """ 

1877 self.zoom_activated = True 

1878 if animate: 

1879 self.play(self.get_zoom_in_animation()) 

1880 self.play(self.get_zoomed_display_pop_out_animation()) 

1881 self.add_foreground_mobjects(self.zoomed_camera.frame, self.zoomed_display) 

1882 

1883 def get_zoom_in_animation(self, **kwargs: Unpack[TransformOptions]) -> Animation: 

1884 """Make the animation in which the zoomed camera's frame shrinks from the whole 

1885 view to its place. 

1886 

1887 The frame moves to its start at once: it covers the view, centered on the 

1888 origin, without its outline, until the animation plays. 

1889 

1890 Args: 

1891 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] (2 

1892 seconds long unless given a `run_time`). 

1893 

1894 Returns: 

1895 The animation, to play. 

1896 """ 

1897 from manimgx.animation.motion import Restore 

1898 

1899 kwargs.setdefault("run_time", 2) 

1900 frame = self.zoomed_camera.frame 

1901 frame.save_state() 

1902 frame.stretch_to_fit_width(self.camera.frame_width) 

1903 frame.stretch_to_fit_height(self.camera.frame_height) 

1904 frame.center() 

1905 frame.set_stroke(width=0) 

1906 return Restore(frame, **kwargs) 

1907 

1908 def get_zoomed_display_pop_out_animation( 

1909 self, **kwargs: Unpack[TransformOptions] 

1910 ) -> Animation: 

1911 """Make the animation in which the display grows out of the zoomed camera's 

1912 frame to its place. 

1913 

1914 The display moves to its start at once: over the zoomed camera's frame, until 

1915 the animation plays. 

1916 

1917 Args: 

1918 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions]. 

1919 

1920 Returns: 

1921 The animation, to play. 

1922 """ 

1923 from manimgx.animation.motion import Restore 

1924 

1925 display = self.zoomed_display 

1926 display.save_state() 

1927 display.replace(self.zoomed_camera.frame, stretch=True) 

1928 return Restore(display, **kwargs) 

1929 

1930 def get_zoom_factor(self) -> float: 

1931 """How small the zoomed camera's frame is next to the display. 

1932 

1933 Returns: 

1934 The frame's height over the display's: the display magnifies its inverse. 

1935 """ 

1936 return self.zoomed_camera.frame.height / self.zoomed_display.height 

1937 

1938 

1939class ThreeDScene(Scene): 

1940 r"""A scene seen in three dimensions: from a camera that orbits it, with perspective 

1941 and depth. 

1942 

1943 The camera looks at the center of its frame from the angles `phi`, from the z axis 

1944 (0 looks straight down on the xy plane), and `theta`, around it (−90° by default, so 

1945 that x points right); `gamma` turns it about its line of sight, `zoom` magnifies, 

1946 and `focal_distance` is how far it is from the point it looks at. Each is a 

1947 [value tracker][manimgx.ValueTracker] of the [camera][manimgx.Camera], so it moves 

1948 as any mobject does: [`move_camera`][manimgx.ThreeDScene.move_camera] animates it, 

1949 and an ambient rotation keeps it turning. Nearer surfaces hide farther ones; 

1950 mobjects fixed in the frame are drawn flat on the screen, over everything. 

1951 

1952 Examples: 

1953 ```python 

1954 import numpy as np 

1955 

1956 import manimgx as m 

1957 

1958 

1959 class ThreeDSceneExample(m.ThreeDScene): 

1960 def construct(self) -> None: 

1961 self.set_camera_orientation( 

1962 phi=65 * m.DEGREES, theta=-50 * m.DEGREES, zoom=0.6 

1963 ) 

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

1965 surface = m.Surface( 

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

1967 u_range=(-3, 3), 

1968 v_range=(-3, 3), 

1969 resolution=(24, 24), 

1970 ).set_fill_by_checkerboard(m.BLUE_D, m.TEAL, opacity=0.9) 

1971 title = m.MathTex(r"z = \sin x \cos y", font_size=64).to_corner(m.UL) 

1972 self.add_fixed_in_frame_mobjects(title) 

1973 self.add(axes, surface) 

1974 ``` 

1975 """ 

1976 

1977 three_d = True 

1978 

1979 def set_camera_orientation( 

1980 self, 

1981 phi: float | None = None, 

1982 theta: float | None = None, 

1983 gamma: float | None = None, 

1984 zoom: float | None = None, 

1985 focal_distance: float | None = None, 

1986 frame_center: Point3DLike | Mobject | None = None, 

1987 ) -> None: 

1988 """Set where the camera looks from, at once: each setting given; the others stay 

1989 as they are. 

1990 

1991 Args: 

1992 phi: The angle between the camera's line of sight and the z axis, in 

1993 radians: 0 looks straight down on the xy plane. 

1994 theta: The camera's angle around the z axis, in radians, counterclockwise 

1995 from the x axis: at −90° it looks from the side of negative y, so that x 

1996 points right. 

1997 gamma: How far the camera turns about its line of sight, in radians. 

1998 zoom: How much the camera magnifies: 2 shows everything twice as large. 

1999 focal_distance: The camera's distance from the point it looks at, in scene 

2000 units: the nearer, the stronger the perspective. 

2001 frame_center: The point the camera looks at, or a mobject whose center it 

2002 is: the camera's frame moves there. 

2003 """ 

2004 cam = self.camera 

2005 for value, tracker in ( 

2006 (phi, cam.phi_tracker), 

2007 (theta, cam.theta_tracker), 

2008 (gamma, cam.gamma_tracker), 

2009 (zoom, cam.zoom_tracker), 

2010 (focal_distance, cam.focal_distance_tracker), 

2011 ): 

2012 if value is not None: 

2013 tracker.set_value(value) 

2014 if frame_center is not None: 

2015 cam.frame.move_to(frame_center) 

2016 

2017 def _tracker(self, about: str) -> ValueTracker: 

2018 return { 

2019 "theta": self.camera.theta_tracker, 

2020 "phi": self.camera.phi_tracker, 

2021 "gamma": self.camera.gamma_tracker, 

2022 }[about.lower()] 

2023 

2024 def begin_ambient_camera_rotation( 

2025 self, rate: float = 0.02, about: str = "theta" 

2026 ) -> None: 

2027 """Start turning the camera steadily, through plays and waits alike, until 

2028 `stop_ambient_camera_rotation`. 

2029 

2030 One of the camera's angles grows at a steady rate: its tracker gets an updater 

2031 (a [flow][manimgx.mobject.flow]) and joins the scene. 

2032 

2033 Args: 

2034 rate: How fast the angle grows, in radians per second; a negative rate turns 

2035 the other way. 

2036 about: The angle: "theta" (around the z axis), "phi" or "gamma", in any 

2037 case. 

2038 

2039 Examples: 

2040 ```python 

2041 import manimgx as m 

2042 

2043 

2044 class ThreeDSceneAmbientRotationExample(m.ThreeDScene): 

2045 def construct(self) -> None: 

2046 self.set_camera_orientation( 

2047 phi=70 * m.DEGREES, theta=-45 * m.DEGREES 

2048 ) 

2049 torus = m.Torus(major_radius=2.5, minor_radius=0.8) 

2050 self.add(m.ThreeDAxes(), torus.set_color(m.TEAL)) 

2051 self.begin_ambient_camera_rotation(rate=m.PI / 4) # 45° a second 

2052 self.wait(4) 

2053 ``` 

2054 """ 

2055 tracker = self._tracker(about) 

2056 tracker.add_updater(flow(lambda m, dt: m.increment_value(rate * dt))) 

2057 self.add(tracker) 

2058 

2059 def stop_ambient_camera_rotation(self, about: str = "theta") -> None: 

2060 """Stop turning the camera: every updater of the angle's tracker is removed, and 

2061 the tracker leaves the scene. The camera stays where it turned to. 

2062 

2063 Args: 

2064 about: The angle: "theta", "phi" or "gamma", in any case. 

2065 """ 

2066 tracker = self._tracker(about) 

2067 tracker.clear_updaters() 

2068 self.remove(tracker) 

2069 

2070 def begin_3dillusion_camera_rotation( 

2071 self, 

2072 rate: float = 1, 

2073 origin_phi: float | None = None, 

2074 origin_theta: float | None = None, 

2075 ) -> None: 

2076 """Start swaying the camera around its orientation, for an illusion of depth, 

2077 through plays and waits alike, until `stop_3dillusion_camera_rotation`. 

2078 

2079 The camera circles a little: `theta` swings 0.2 radians either side of 

2080 `origin_theta`, and `phi` between `origin_phi` and 0.2 radians less, a quarter 

2081 of a cycle apart. The trackers of the two angles get updaters (flows) and join 

2082 the scene. 

2083 

2084 Args: 

2085 rate: How fast it sways, in radians of its cycle per second: a cycle takes 

2086 2π / `rate` seconds. 

2087 origin_phi: The `phi` it sways from; None for the camera's present one. 

2088 origin_theta: The `theta` it sways about; None for the camera's present one. 

2089 """ 

2090 cam = self.camera 

2091 origin_theta = cam.get_theta() if origin_theta is None else origin_theta 

2092 origin_phi = cam.get_phi() if origin_phi is None else origin_phi 

2093 clocks = [0.0, 0.0] 

2094 

2095 def swing_theta(m: ValueTracker, dt: float) -> None: 

2096 clocks[0] += dt * rate 

2097 m.set_value(origin_theta + 0.2 * np.sin(clocks[0])) 

2098 

2099 def swing_phi(m: ValueTracker, dt: float) -> None: 

2100 clocks[1] += dt * rate 

2101 m.set_value(origin_phi + 0.1 * np.cos(clocks[1]) - 0.1) 

2102 

2103 cam.theta_tracker.add_updater(flow(swing_theta)) 

2104 cam.phi_tracker.add_updater(flow(swing_phi)) 

2105 self.add(cam.theta_tracker, cam.phi_tracker) 

2106 

2107 def stop_3dillusion_camera_rotation(self) -> None: 

2108 """Stop swaying the camera: every updater of the `theta` and `phi` trackers is 

2109 removed, and they leave the scene. The camera stays where the sway left it.""" 

2110 for tracker in (self.camera.theta_tracker, self.camera.phi_tracker): 

2111 tracker.clear_updaters() 

2112 self.remove(tracker) 

2113 

2114 def move_camera( 

2115 self, 

2116 phi: float | None = None, 

2117 theta: float | None = None, 

2118 gamma: float | None = None, 

2119 zoom: float | None = None, 

2120 focal_distance: float | None = None, 

2121 frame_center: Point3DLike | Mobject | None = None, 

2122 added_anims: Sequence[Animation] = (), 

2123 **kwargs: Unpack[TransformOptions], 

2124 ) -> None: 

2125 """Animate the camera to a new orientation, in one play: each setting given; the 

2126 others stay as they are. 

2127 

2128 Each setting moves steadily from its value to the new one, eased by the rate 

2129 function, so a `theta` 2π greater takes the camera once around. The frame moves 

2130 to `frame_center` if given, and `added_anims` play along. 

2131 

2132 Args: 

2133 phi: The angle between the camera's line of sight and the z axis, in 

2134 radians: 0 looks straight down on the xy plane. 

2135 theta: The camera's angle around the z axis, in radians, counterclockwise 

2136 from the x axis. 

2137 gamma: How far the camera turns about its line of sight, in radians. 

2138 zoom: How much the camera magnifies: 2 shows everything twice as large. 

2139 focal_distance: The camera's distance from the point it looks at, in scene 

2140 units. 

2141 frame_center: The point for the camera to look at, or a mobject whose center 

2142 it is. 

2143 added_anims: Animations to play along. 

2144 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

2145 every animation of the play, the added ones too. 

2146 

2147 Examples: 

2148 ```python 

2149 import manimgx as m 

2150 

2151 

2152 class ThreeDSceneMoveCameraExample(m.ThreeDScene): 

2153 def construct(self) -> None: 

2154 cube = m.Cube(side_length=2.5, fill_opacity=0.8, fill_color=m.BLUE) 

2155 self.add(m.ThreeDAxes(), cube) 

2156 self.move_camera( 

2157 phi=70 * m.DEGREES, theta=-45 * m.DEGREES, run_time=2 

2158 ) 

2159 self.move_camera(theta=45 * m.DEGREES, zoom=1.5, run_time=2) 

2160 ``` 

2161 """ 

2162 cam = self.camera 

2163 pairs = ( 

2164 (phi, cam.phi_tracker), 

2165 (theta, cam.theta_tracker), 

2166 (focal_distance, cam.focal_distance_tracker), 

2167 (gamma, cam.gamma_tracker), 

2168 (zoom, cam.zoom_tracker), 

2169 ) 

2170 anims: list[Animation] = [ 

2171 tracker.animate.set_value(value) 

2172 for value, tracker in pairs 

2173 if value is not None 

2174 ] 

2175 if frame_center is not None: 

2176 anims.append(cam.frame.animate.move_to(frame_center)) 

2177 self.play(*anims, *added_anims, **kwargs) 

2178 if frame_center is not None: 

2179 self.remove(cam.frame) 

2180 

2181 def add_fixed_in_frame_mobjects(self, *mobjects: Mobject) -> None: 

2182 """Add mobjects pinned to the screen: each is drawn where its points are, as in 

2183 a two-dimensional view centered on the origin, over everything else. 

2184 

2185 They are added to the scene, and stay where they are on the screen whatever the 

2186 camera's angles, zoom and center: a title placed with `to_corner` stays in its 

2187 corner. Everything in them is pinned, now and later: a member added later (a 

2188 number's new digits, what an updater or a Transform makes) is pinned too. 

2189 """ 

2190 self.add(*mobjects) 

2191 self.camera.add_fixed_in_frame_mobjects(*mobjects) 

2192 

2193 def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject) -> None: 

2194 """Unpin mobjects from the screen, undoing 

2195 [`add_fixed_in_frame_mobjects`][manimgx.ThreeDScene.add_fixed_in_frame_mobjects]: 

2196 they stay in the scene, and the camera moves them again. A member of a pinned 

2197 mobject stays pinned with it. 

2198 """ 

2199 self.camera.remove_fixed_in_frame_mobjects(*mobjects) 

2200 

2201 

2202def _tracks( 

2203 anim: Animation, 

2204 tweens: list[tuple[Transform, Path]], 

2205 alpha: np.ndarray, 

2206 introduced: set[int], 

2207) -> list[tuple[Mobject, list[Mobject], Path, np.ndarray, np.ndarray]]: 

2208 """A pure play at these alphas: per leaf, its keyframes, path, and per instant its interval 

2209 and t (-1: not begun, as the play found it; -2: absent, before the part that brings it 

2210 begins or after a remover's window closes).""" 

2211 from manimgx.animation.timeline import keyframe_at, schedule 

2212 

2213 alphas = {id(tween): (a, c) for tween, a, c in schedule(anim, alpha)} 

2214 out = [] 

2215 for tween, path in tweens: 

2216 family = list(tween.get_all_families_zipped()) 

2217 steps = len(family[0]) - 2 if family else 0 # keyframe intervals 

2218 progress, closed = alphas[id(tween)] 

2219 for i, (leaf, *keys) in enumerate(family): 

2220 index = np.full(len(alpha), -2 if id(leaf) in introduced else -1) 

2221 fraction = np.zeros(len(alpha)) 

2222 for f, a in enumerate(progress): 

2223 if a == a: # begun 

2224 index[f], fraction[f] = keyframe_at( 

2225 steps, tween.get_sub_alpha(float(a), i, len(family)) 

2226 ) 

2227 if tween.is_remover(): # gone once its window closed 

2228 index[closed] = -2 

2229 out.append((leaf, keys, path, index, fraction)) 

2230 return out 

2231 

2232 

2233def _voice_folder(scene: Scene) -> pathlib.Path: 

2234 """Where a scene keeps what its voices said: `voice/` beside its file; for a scene 

2235 with no file (a notebook's), the user's cache.""" 

2236 try: 

2237 return pathlib.Path(inspect.getfile(type(scene))).parent / "voice" 

2238 except (TypeError, OSError): 

2239 return pathlib.Path.home() / ".cache" / "manimgx" / "voice" 

2240 

2241 

2242def _leaves(anim: Animation) -> Iterable[Animation]: 

2243 """The animations under `anim` that act themselves: its parts, and theirs.""" 

2244 from manimgx.animation.timeline import AnimationGroup 

2245 

2246 if isinstance(anim, AnimationGroup): 

2247 for part in anim.animations: 

2248 yield from _leaves(part) 

2249 else: 

2250 yield anim 

2251 

2252 

2253def _sounds(anim: Animation) -> bool: 

2254 from manimgx.audio.sound import Sound 

2255 

2256 return any(isinstance(p, Sound) for p in _leaves(anim)) 

2257 

2258 

2259def _acted_on(anim: Animation) -> list[Mobject]: 

2260 """The mobjects an animation's parts act on, and the targets they run (their own 

2261 objects).""" 

2262 return [ 

2263 mob 

2264 for part in _leaves(anim) 

2265 for mob in [ 

2266 part.mobject, 

2267 *(key for key in part.keys if isinstance(key, Mobject)), 

2268 ] 

2269 ] 

2270 

2271 

2272def _forward(alpha: np.ndarray) -> bool: 

2273 """Does a part's alpha only go forward — once begun, never not begun again, never back?""" 

2274 begun = alpha == alpha 

2275 first = int(np.argmax(begun)) if begun.any() else len(alpha) 

2276 return bool(begun[first:].all() and np.all(np.diff(alpha[first:]) >= 0)) 

2277 

2278 

2279_PACKAGE = os.path.dirname(__file__) + os.sep 

2280 

2281 

2282def _written() -> tuple[str, int] | None: 

2283 """Where the scene's own code is running: the innermost caller outside ManimGX (a scene's 

2284 `play`, or the `wait` that plays).""" 

2285 here = inspect.currentframe() 

2286 frame = None if here is None else here.f_back # `play`'s 

2287 frame = None if frame is None else frame.f_back 

2288 while frame is not None and frame.f_code.co_filename.startswith(_PACKAGE): 

2289 frame = frame.f_back 

2290 return None if frame is None else (frame.f_code.co_filename, frame.f_lineno) 

2291 

2292 

2293def _restructure( 

2294 mobjects: Sequence[Mobject], to_remove: Iterable[Mobject], extract: bool = True 

2295) -> list[Mobject]: 

2296 """Drop members, replacing each containing group with its surviving children.""" 

2297 removing = {id(mob) for mob in (_family(to_remove) if extract else to_remove)} 

2298 if not removing: 

2299 return list(mobjects) 

2300 broken: set[int] = set() 

2301 # A family's last-occurrence order puts every parent before its children. 

2302 # Fold in reverse: groups lose their place when a descendant is removed, 

2303 # and vanish altogether when none of their children survive. 

2304 for mob in reversed(_family(mobjects)): 

2305 if id(mob) in removing or not mob.submobjects: 

2306 continue 

2307 if any( 

2308 id(child) in removing or id(child) in broken for child in mob.submobjects 

2309 ): 

2310 if all(id(child) in removing for child in mob.submobjects): 

2311 removing.add(id(mob)) 

2312 else: 

2313 broken.add(id(mob)) 

2314 out: list[Mobject] = [] 

2315 pending = list(reversed(mobjects)) 

2316 while pending: 

2317 mob = pending.pop() 

2318 if id(mob) in removing: 

2319 continue 

2320 if id(mob) in broken: 

2321 pending.extend(reversed(mob.submobjects)) 

2322 else: 

2323 out.append(mob) 

2324 return out 

2325 

2326 

2327X_COLOR = GREEN_C 

2328Y_COLOR = RED_C 

2329Z_COLOR = BLUE_D 

2330 

2331 

2332class _LabelPlacement(TypedDict, total=False): 

2333 """LabelPlacement's keys, open, for the keywords that add to them.""" 

2334 

2335 at_tip: bool 

2336 """Whether the label goes beyond the vector's tip, rather than beside its middle 

2337 (default False).""" 

2338 direction: Literal["left", "right"] 

2339 """Which side of the vector the label goes on, looking along the vector (default 

2340 "left").""" 

2341 rotate: bool 

2342 """Whether the label turns with the vector, rather than staying upright (default 

2343 False).""" 

2344 

2345 

2346class LabelPlacement(_LabelPlacement, total=False, closed=True): 

2347 """Where a vector's label sits (for the methods that pass it on).""" 

2348 

2349 

2350class VectorLabelOptions(_LabelPlacement, total=False, closed=True): 

2351 """Where a vector's label sits, its color and its size (for the methods that pass 

2352 them on).""" 

2353 

2354 color: ParsableManimColor | None 

2355 """The label's color, when it is made from a string (default None: the vector's).""" 

2356 label_scale_factor: float 

2357 """How much the label is scaled (default 0.8).""" 

2358 

2359 

2360class UnitSquareOptions(TypedDict, total=False, closed=True): 

2361 """The unit square's look (for the methods that pass it on).""" 

2362 

2363 color: Colors 

2364 """The color of its fill and its stroke (default yellow).""" 

2365 opacity: float 

2366 """Its fill's opacity, from 0 to 1 (default 0.3).""" 

2367 stroke_width: float 

2368 """Its stroke's width, in hundredths of a scene unit (default 3).""" 

2369 

2370 

2371class VectorScene(Scene): 

2372 """A scene for drawing vectors: arrows from the origin, their labels and their 

2373 coordinates. 

2374 

2375 Its methods add a plane and axes, draw vectors and label them, and animate the 

2376 passage from a vector to its coordinates and back. 

2377 [`add_vector`][manimgx.VectorScene.add_vector] draws a vector from the origin, in 

2378 scene units; [`get_vector`][manimgx.VectorScene.get_vector] makes one in the 

2379 coordinates of the scene's [`plane`][manimgx.VectorScene.plane]. 

2380 

2381 Args: 

2382 basis_vector_stroke_width: The stroke width of the basis vectors (see 

2383 [`get_basis_vectors`][manimgx.VectorScene.get_basis_vectors]), in hundredths 

2384 of a scene unit. 

2385 

2386 Examples: 

2387 ```python 

2388 import manimgx as m 

2389 

2390 

2391 class VectorSceneExample(m.VectorScene): 

2392 def construct(self) -> None: 

2393 self.add_plane() 

2394 vector = self.add_vector([3, 2], color=m.YELLOW) 

2395 self.write_vector_coordinates(vector) 

2396 self.wait() 

2397 ``` 

2398 """ 

2399 

2400 plane: NumberPlane 

2401 """The plane whose coordinates [`get_vector`][manimgx.VectorScene.get_vector] reads: 

2402 a [`LinearTransformationScene`][manimgx.LinearTransformationScene] makes it; in a 

2403 vector scene, assign it (`self.plane = self.add_plane()`).""" 

2404 grows_vectors: ClassVar[bool] = ( 

2405 True # `add_vector` animates unless told (CE's defaults) 

2406 ) 

2407 """Whether [`add_vector`][manimgx.VectorScene.add_vector] shows a vector growing 

2408 unless told otherwise: True in a vector scene, False in a transformation scene.""" 

2409 

2410 def __init__(self, basis_vector_stroke_width: float = 6.0) -> None: 

2411 super().__init__() 

2412 self.basis_vector_stroke_width = basis_vector_stroke_width 

2413 

2414 def add_plane( 

2415 self, animate: bool = False, **kwargs: Unpack[NumberPlaneOptions] 

2416 ) -> NumberPlane: 

2417 """Add a number plane to the scene. 

2418 

2419 Args: 

2420 animate: Whether to draw it in ([`Create`][manimgx.Create], its lines 

2421 overlapping). 

2422 **kwargs: [Number plane keywords][manimgx.NumberPlane]. 

2423 

2424 Returns: 

2425 The plane. It is not the scene's [`plane`][manimgx.VectorScene.plane] unless 

2426 assigned to it. 

2427 """ 

2428 plane = NumberPlane(**kwargs) 

2429 if animate: 

2430 self.play(Create(plane, lag_ratio=0.5)) 

2431 self.add(plane) 

2432 return plane 

2433 

2434 def add_axes(self, animate: bool = False, color: Colors = WHITE) -> Axes: 

2435 """Add axes to the scene, one scene unit to one unit. 

2436 

2437 Args: 

2438 animate: Whether to draw them in ([`Create`][manimgx.Create]). 

2439 color: Their color. 

2440 

2441 Returns: 

2442 The axes. 

2443 """ 

2444 axes = Axes(color=color, axis_config={"unit_size": 1}) 

2445 if animate: 

2446 self.play(Create(axes)) 

2447 self.add(axes) 

2448 return axes 

2449 

2450 def get_vector( 

2451 self, numerical_vector: Vector3DLike, **kwargs: Unpack[ArrowTips] 

2452 ) -> Arrow: 

2453 """Make an arrow from the origin of the scene's plane to a point given in its 

2454 coordinates. 

2455 

2456 Args: 

2457 numerical_vector: The point's coordinates on 

2458 [`plane`][manimgx.VectorScene.plane]: x and y (a z is ignored). 

2459 **kwargs: [Arrow keywords][manimgx.Arrow]. 

2460 

2461 Returns: 

2462 A new arrow, not added to the scene. 

2463 """ 

2464 x, y = np.asarray(numerical_vector, dtype=float)[:2] 

2465 return Arrow( 

2466 self.plane.coords_to_point(0, 0), 

2467 self.plane.coords_to_point(x, y), 

2468 buff=0, 

2469 **kwargs, 

2470 ) 

2471 

2472 @overload 

2473 def add_vector[A: Arrow]( 

2474 self, 

2475 vector: A, 

2476 color: Colors = ..., 

2477 animate: bool = ..., 

2478 **kwargs: Unpack[ArrowTipsBase], 

2479 ) -> A: ... 

2480 @overload 

2481 def add_vector( 

2482 self, 

2483 vector: Vector3DLike, 

2484 color: Colors = ..., 

2485 animate: bool = ..., 

2486 **kwargs: Unpack[ArrowTipsBase], 

2487 ) -> Vector: ... 

2488 def add_vector( 

2489 self, 

2490 vector: Arrow | Vector3DLike, 

2491 color: Colors = PURE_YELLOW, 

2492 animate: bool | None = None, 

2493 **kwargs: Unpack[ArrowTipsBase], 

2494 ) -> Arrow: 

2495 """Add a vector to the scene: the arrow given, or a [Vector][manimgx.Vector] from 

2496 the origin to the coordinates given. 

2497 

2498 It is shown growing from the origin ([GrowArrow][manimgx.GrowArrow]) if `animate` 

2499 says so, or else if the scene's `grows_vectors` does (a vector scene's does, a 

2500 transformation scene's doesn't); then the scene takes it up: a 

2501 [LinearTransformationScene][manimgx.LinearTransformationScene] moves it with the 

2502 plane. 

2503 

2504 Args: 

2505 vector: An arrow, or the coordinates of a vector's tip, in scene units. 

2506 color: The vector's color, when it is made from coordinates. 

2507 animate: Whether it grows in a play; None for the scene's `grows_vectors`. 

2508 **kwargs: [Arrow keywords][manimgx.mobjects.shapes.ArrowTipsBase] for 

2509 a vector made from coordinates. 

2510 

2511 Returns: 

2512 The arrow. 

2513 """ 

2514 if not isinstance(vector, Arrow): 

2515 vector = Vector(np.asarray(vector, dtype=float), color=color, **kwargs) 

2516 if self.grows_vectors if animate is None else animate: 

2517 self.play(GrowArrow(vector)) 

2518 self.add(vector) 

2519 self.added_vector(vector) 

2520 return vector 

2521 

2522 @deprecated("Manim CE's machinery: vector_to_coords calls it", category=None) 

2523 def added_vector(self, vector: Arrow) -> None: 

2524 """Take up a vector that [add_vector][manimgx.VectorScene.add_vector] added: a 

2525 vector scene does nothing with it, and a 

2526 [LinearTransformationScene][manimgx.LinearTransformationScene] moves it with its 

2527 transformations. 

2528 """ 

2529 

2530 def write_vector_coordinates( 

2531 self, vector: Vector, **kwargs: Unpack[MatrixOptions] 

2532 ) -> Matrix: 

2533 """Write a vector's coordinates beside its tip, as a column (its 

2534 `coordinate_label`), in a play of [`Write`][manimgx.Write]. 

2535 

2536 Args: 

2537 **kwargs: [Matrix keywords][manimgx.mobjects.grid.MatrixOptions] for the 

2538 column. 

2539 

2540 Returns: 

2541 The column. 

2542 """ 

2543 coords = vector.coordinate_label(**kwargs) 

2544 self.play(Write(coords)) 

2545 return coords 

2546 

2547 def get_basis_vectors( 

2548 self, i_hat_color: Colors = X_COLOR, j_hat_color: Colors = Y_COLOR 

2549 ) -> VGroup: 

2550 """Make the basis vectors î and ĵ: arrows from the origin to (1, 0) and (0, 1), 

2551 in scene units. 

2552 

2553 Args: 

2554 i_hat_color: The color of î. 

2555 j_hat_color: The color of ĵ. 

2556 

2557 Returns: 

2558 A new group of the two, î first. 

2559 """ 

2560 return VGroup( 

2561 *( 

2562 Vector( 

2563 np.asarray(vect, dtype=float), 

2564 color=color, 

2565 stroke_width=self.basis_vector_stroke_width, 

2566 ) 

2567 for vect, color in [([1, 0], i_hat_color), ([0, 1], j_hat_color)] 

2568 ) 

2569 ) 

2570 

2571 def get_basis_vector_labels(self, **kwargs: Unpack[LabelPlacement]) -> VGroup: 

2572 """Make labels for the basis vectors: î and ĵ, in the colors of the x and y axes 

2573 (green and red). 

2574 

2575 Args: 

2576 **kwargs: [Label placement keywords][manimgx.scene.LabelPlacement]. 

2577 

2578 Returns: 

2579 A new group of the two labels, î's first. 

2580 """ 

2581 i_hat, j_hat = self.get_basis_vectors().submobjects 

2582 return VGroup( 

2583 *( 

2584 self.get_vector_label( 

2585 vect, label, color=color, label_scale_factor=1, **kwargs 

2586 ) 

2587 for vect, label, color in [ 

2588 (i_hat, "\\hat{\\imath}", X_COLOR), 

2589 (j_hat, "\\hat{\\jmath}", Y_COLOR), 

2590 ] 

2591 if isinstance(vect, Vector) 

2592 ) 

2593 ) 

2594 

2595 def get_vector_label( 

2596 self, 

2597 vector: Vector, 

2598 label: ManimTextLabel | str, 

2599 at_tip: bool = False, 

2600 direction: Literal["left", "right"] = "left", 

2601 rotate: bool = False, 

2602 color: ParsableManimColor | None = None, 

2603 label_scale_factor: float = LARGE_BUFF - 0.2, 

2604 ) -> ManimTextLabel: 

2605 r"""Make a label for a vector: beside its middle, on its left or its right, or 

2606 beyond its tip. 

2607 

2608 A string is typeset as LaTeX, a single letter as a bold vector 

2609 (`\vec{\textbf{v}}`), in the vector's color. The label gets a background 

2610 rectangle, to be read over the lines under it. 

2611 

2612 Args: 

2613 vector: The vector, from the origin. 

2614 label: The label: a mobject, or LaTeX. 

2615 at_tip: Whether it goes beyond the vector's tip, rather than beside its 

2616 middle. 

2617 direction: Which side of the vector it goes on, looking along the vector. 

2618 rotate: Whether it turns with the vector, rather than staying upright. 

2619 color: Its color, when it is made from a string; None for the vector's. 

2620 label_scale_factor: How much it is scaled. 

2621 

2622 Returns: 

2623 The label, not added to the scene. 

2624 """ 

2625 if isinstance(label, str): 

2626 if len(label) == 1: 

2627 label = f"\\vec{{\\textbf{{{label}}}}}" 

2628 label = MathTex(label) 

2629 label.set_color(vector.get_color() if color is None else color) 

2630 label.scale(label_scale_factor) 

2631 label.add_background_rectangle() 

2632 if at_tip: 

2633 vect = vector.get_vector() 

2634 label.next_to( 

2635 vector.get_end(), vect / np.linalg.norm(vect), buff=SMALL_BUFF 

2636 ) 

2637 else: 

2638 angle = vector.get_angle() 

2639 if not rotate: 

2640 label.rotate(-angle, about_point=ORIGIN) 

2641 if direction == "left": 

2642 label.shift(-np.asarray(label.get_bottom()) + 0.1 * UP) 

2643 else: 

2644 label.shift(-np.asarray(label.get_top()) + 0.1 * DOWN) 

2645 label.rotate(angle, about_point=ORIGIN) 

2646 label.shift((vector.get_end() - vector.get_start()) / 2) 

2647 return label 

2648 

2649 def label_vector( 

2650 self, 

2651 vector: Vector, 

2652 label: ManimTextLabel | str, 

2653 animate: bool = True, 

2654 **kwargs: Unpack[VectorLabelOptions], 

2655 ) -> ManimTextLabel: 

2656 """Label a vector, and add the label to the scene (see 

2657 [`get_vector_label`][manimgx.VectorScene.get_vector_label]). 

2658 

2659 Args: 

2660 vector: The vector, from the origin. 

2661 label: The label: a mobject, or LaTeX. 

2662 animate: Whether to write it in ([`Write`][manimgx.Write]). 

2663 **kwargs: [Vector label keywords][manimgx.scene.VectorLabelOptions]. 

2664 

2665 Returns: 

2666 The label. 

2667 """ 

2668 mathtex_label = self.get_vector_label(vector, label, **kwargs) 

2669 if animate: 

2670 self.play(Write(mathtex_label, run_time=1)) 

2671 self.add(mathtex_label) 

2672 return mathtex_label 

2673 

2674 @deprecated("Manim CE's machinery: vector_to_coords calls it", category=None) 

2675 def position_x_coordinate( 

2676 self, x_coord: Mobject, x_line: Line, vector: Vector3DLike 

2677 ) -> Mobject: 

2678 """Place a vector's x coordinate by the line of its x component, in green: under 

2679 it for a vector that points up, over it for one that points down. 

2680 

2681 Args: 

2682 x_coord: The coordinate. 

2683 x_line: The line from the origin along x to the vector's x. 

2684 vector: The vector's coordinates. 

2685 

2686 Returns: 

2687 The coordinate, placed. 

2688 """ 

2689 x_coord.next_to(x_line, -np.sign(vector[1]) * UP) 

2690 x_coord.set_color(X_COLOR) 

2691 return x_coord 

2692 

2693 @deprecated("Manim CE's machinery: vector_to_coords calls it", category=None) 

2694 def position_y_coordinate( 

2695 self, y_coord: Mobject, y_line: Line, vector: Vector3DLike 

2696 ) -> Mobject: 

2697 """Place a vector's y coordinate by the line of its y component, in red: right 

2698 of it for a vector that points right, left of it for one that points left. 

2699 

2700 Args: 

2701 y_coord: The coordinate. 

2702 y_line: The line along y up (or down) to the vector's tip. 

2703 vector: The vector's coordinates. 

2704 

2705 Returns: 

2706 The coordinate, placed. 

2707 """ 

2708 y_coord.next_to(y_line, np.sign(vector[0]) * RIGHT) 

2709 y_coord.set_color(Y_COLOR) 

2710 return y_coord 

2711 

2712 def vector_to_coords( 

2713 self, 

2714 vector: Vector | Vector3DLike, 

2715 integer_labels: bool = True, 

2716 clean_up: bool = True, 

2717 ) -> tuple[Matrix, Line, Line]: 

2718 """Show how a vector gives its coordinates, in a series of plays. 

2719 

2720 The vector (drawn first, when it is given by its coordinates) gets a line along 

2721 x and a line up to its tip, each written with its coordinate; the coordinates 

2722 then move into a column beside its tip. 

2723 

2724 Args: 

2725 vector: The vector, from the origin, or its coordinates. 

2726 integer_labels: Whether the coordinates are rounded to integers. 

2727 clean_up: Whether the scene is left holding what it held before, at the end. 

2728 

2729 Returns: 

2730 The column of coordinates, the line along x and the line up to the tip. 

2731 """ 

2732 starting_mobjects = list(self.mobjects) 

2733 show_creation = not isinstance(vector, Vector) 

2734 arrow = vector if isinstance(vector, Vector) else Vector(vector) 

2735 end = arrow.get_end()[:2] 

2736 array = arrow.coordinate_label(integer_labels=integer_labels) 

2737 x_line = Line(ORIGIN, end[0] * RIGHT) 

2738 y_line = Line(x_line.get_end(), arrow.get_end()) 

2739 x_line.set_color(X_COLOR) 

2740 y_line.set_color(Y_COLOR) 

2741 x_coord, y_coord = array.get_entries().submobjects[:2] 

2742 x_coord_start = self.position_x_coordinate(x_coord.copy(), x_line, end) 

2743 y_coord_start = self.position_y_coordinate(y_coord.copy(), y_line, end) 

2744 brackets = array.get_brackets() 

2745 if show_creation: 

2746 self.play(Create(arrow)) 

2747 self.play(Create(x_line), Write(x_coord_start), run_time=1) 

2748 self.play(Create(y_line), Write(y_coord_start), run_time=1) 

2749 self.wait() 

2750 self.play( 

2751 Transform(x_coord_start, x_coord, lag_ratio=0), 

2752 Transform(y_coord_start, y_coord, lag_ratio=0), 

2753 Write(brackets, run_time=1), 

2754 ) 

2755 self.wait() 

2756 self.remove(x_coord_start, y_coord_start, brackets) 

2757 self.add(array) 

2758 if clean_up: 

2759 self.clear() 

2760 self.add(*starting_mobjects) 

2761 return array, x_line, y_line 

2762 

2763 

2764@dataclass 

2765class _TransformableLabel: 

2766 """A vector's label that follows the transformations: rewritten as `target_text` (or kept).""" 

2767 

2768 label: Mobject 

2769 vector: Vector 

2770 target_text: str | ManimTextLabel 

2771 options: VectorLabelOptions 

2772 

2773 

2774def _merged_plane( 

2775 defaults: NumberPlaneOptions, given: NumberPlaneOptions | None 

2776) -> NumberPlaneOptions: 

2777 """A plane config over its defaults, key by key (and inside its axis and line styles).""" 

2778 given = given or NumberPlaneOptions() 

2779 merged = defaults | given 

2780 merged["axis_config"] = merged_axis_config( 

2781 defaults.get("axis_config"), given.get("axis_config") 

2782 ) 

2783 merged["background_line_style"] = (defaults.get("background_line_style") or {}) | ( 

2784 given.get("background_line_style") or {} 

2785 ) 

2786 return merged 

2787 

2788 

2789class LinearTransformationScene(VectorScene): 

2790 """A scene for linear transformations of the plane: a matrix applied to the plane 

2791 and to everything on it, in one animation. 

2792 

2793 Before `construct`, it lays a still plane in the background (`background_plane`), a 

2794 plane over it that the transformations move ([`plane`][manimgx.VectorScene.plane]), 

2795 and the basis vectors î and ĵ (`i_hat` and `j_hat`, together `basis_vectors`). 

2796 [`apply_matrix`][manimgx.LinearTransformationScene.apply_matrix] then transforms 

2797 what the scene holds, by kind: the points of the transformable mobjects, as the 

2798 plane's; the vectors, redrawn to where their tips go; the labels that follow them; 

2799 and the moving mobjects, moved whole to where their centers go. The background and 

2800 foreground mobjects stay where they are. 

2801 

2802 Args: 

2803 include_background_plane: Whether a plane stays still in the background. 

2804 include_foreground_plane: Whether a plane over it moves with the 

2805 transformations: the scene's `plane`. 

2806 background_plane_kwargs: [Number plane keywords][manimgx.NumberPlane] 

2807 for the background plane, over its own (grey lines). 

2808 foreground_plane_kwargs: [Number plane keywords][manimgx.NumberPlane] 

2809 for the moving plane, over its own (it reaches past the frame, so that the 

2810 frame stays covered as it moves). 

2811 show_coordinates: Whether the background plane's axes are numbered. 

2812 show_basis_vectors: Whether the basis vectors are drawn; they move with the 

2813 transformations. 

2814 basis_vector_stroke_width: The basis vectors' stroke width, in hundredths of a 

2815 scene unit. 

2816 i_hat_color: The color of î. 

2817 j_hat_color: The color of ĵ. 

2818 leave_ghost_vectors: Whether each transformation leaves faded copies of the 

2819 vectors where they were. 

2820 

2821 Examples: 

2822 ```python 

2823 import manimgx as m 

2824 

2825 

2826 class LinearTransformationSceneExample(m.LinearTransformationScene): 

2827 def __init__(self) -> None: 

2828 super().__init__(show_coordinates=True, leave_ghost_vectors=True) 

2829 

2830 def construct(self) -> None: 

2831 self.add_unit_square() 

2832 self.add_vector([-1, 2], color=m.YELLOW) 

2833 self.apply_matrix([[1, 1], [0, 1]]) # a shear 

2834 self.wait() 

2835 ``` 

2836 """ 

2837 

2838 grows_vectors: ClassVar[bool] = False 

2839 

2840 def __init__( 

2841 self, 

2842 include_background_plane: bool = True, 

2843 include_foreground_plane: bool = True, 

2844 background_plane_kwargs: NumberPlaneOptions | None = None, 

2845 foreground_plane_kwargs: NumberPlaneOptions | None = None, 

2846 show_coordinates: bool = False, 

2847 show_basis_vectors: bool = True, 

2848 basis_vector_stroke_width: float = 6, 

2849 i_hat_color: ParsableManimColor = X_COLOR, 

2850 j_hat_color: ParsableManimColor = Y_COLOR, 

2851 leave_ghost_vectors: bool = False, 

2852 ) -> None: 

2853 super().__init__() 

2854 self.include_background_plane = include_background_plane 

2855 self.include_foreground_plane = include_foreground_plane 

2856 self.show_coordinates = show_coordinates 

2857 self.show_basis_vectors = show_basis_vectors 

2858 self.basis_vector_stroke_width = basis_vector_stroke_width 

2859 self.i_hat_color = ManimColor(i_hat_color) 

2860 self.j_hat_color = ManimColor(j_hat_color) 

2861 self.leave_ghost_vectors = leave_ghost_vectors 

2862 self.ghost_vectors = VGroup() 

2863 """The faded copies the transformations left of what they moved whole, where it 

2864 was, with `leave_ghost_vectors`.""" 

2865 self.background_plane_kwargs = _merged_plane( 

2866 { 

2867 "color": GREY, 

2868 "axis_config": {"color": GREY}, 

2869 "background_line_style": {"stroke_color": GREY, "stroke_width": 1}, 

2870 }, 

2871 background_plane_kwargs, 

2872 ) 

2873 self.foreground_plane_kwargs = _merged_plane( 

2874 { 

2875 "x_range": (-config.frame_width, config.frame_width, 1.0), 

2876 "y_range": (-config.frame_width, config.frame_width, 1.0), 

2877 "faded_line_ratio": 1, 

2878 }, 

2879 foreground_plane_kwargs, 

2880 ) 

2881 

2882 def setup(self) -> None: 

2883 """Lay out the planes and the basis vectors, and add them to the scene. 

2884 

2885 [`render`][manimgx.Scene.render] calls it before `construct`; it acts once. A 

2886 subclass that overrides it calls this one first. 

2887 """ 

2888 if hasattr(self, "has_already_setup"): 

2889 return 

2890 self.has_already_setup = True 

2891 self.background_mobjects: list[Mobject] = [] 

2892 self.foreground_mobjects: list[Mobject] = [] 

2893 self.transformable_mobjects: list[Mobject] = [] 

2894 self.moving_vectors: list[Mobject] = [] 

2895 self.transformable_labels: list[_TransformableLabel] = [] 

2896 self.moving_mobjects: list[Mobject] = [] 

2897 self.background_plane = NumberPlane(**self.background_plane_kwargs) 

2898 if self.show_coordinates: 

2899 self.background_plane.add_coordinates() 

2900 if self.include_background_plane: 

2901 self.add_background_mobject(self.background_plane) 

2902 if self.include_foreground_plane: 

2903 self.plane = NumberPlane(**self.foreground_plane_kwargs) 

2904 self.add_transformable_mobject(self.plane) 

2905 if self.show_basis_vectors: 

2906 self.basis_vectors = self.get_basis_vectors( 

2907 i_hat_color=self.i_hat_color, j_hat_color=self.j_hat_color 

2908 ) 

2909 self.moving_vectors += list(self.basis_vectors) 

2910 self.i_hat, self.j_hat = self.basis_vectors 

2911 self.add(self.basis_vectors) 

2912 

2913 @deprecated("Manim CE's machinery: apply_matrix calls it", category=None) 

2914 def add_special_mobjects( 

2915 self, mob_list: list[Mobject], *mobs_to_add: Mobject 

2916 ) -> None: 

2917 """Add mobjects to the scene and to one of its lists of mobjects of a kind 

2918 (background, foreground, transformable, moving), each once. 

2919 

2920 Args: 

2921 mob_list: The list. 

2922 *mobs_to_add: The mobjects, in order; one the list holds already is skipped. 

2923 """ 

2924 for mobject in mobs_to_add: 

2925 if mobject not in mob_list: 

2926 mob_list.append(mobject) 

2927 self.add(mobject) 

2928 

2929 def add_background_mobject(self, *mobjects: Mobject) -> None: 

2930 """Add mobjects that the transformations leave where they are, as they leave the 

2931 background plane. 

2932 """ 

2933 self.add_special_mobjects(self.background_mobjects, *mobjects) 

2934 

2935 def add_foreground_mobject(self, *mobjects: Mobject) -> Self: 

2936 """Add mobjects that stay in front: drawn over everything else, and left where 

2937 they are by the transformations. 

2938 """ 

2939 self.add_special_mobjects(self.foreground_mobjects, *mobjects) 

2940 return self 

2941 

2942 def add_transformable_mobject(self, *mobjects: Mobject) -> None: 

2943 """Add mobjects that the transformations move point by point, as they move the 

2944 plane. 

2945 """ 

2946 self.add_special_mobjects(self.transformable_mobjects, *mobjects) 

2947 

2948 def add_moving_mobject( 

2949 self, mobject: Mobject, target_mobject: Mobject | None = None 

2950 ) -> None: 

2951 """Add a mobject that the transformations move whole, its shape unchanged: to 

2952 where they take its center. 

2953 

2954 Args: 

2955 target_mobject: What it becomes as it moves, placed where the transformation 

2956 takes its center; None for itself. 

2957 """ 

2958 mobject.target = target_mobject 

2959 self.add_special_mobjects(self.moving_mobjects, mobject) 

2960 

2961 def get_ghost_vectors(self) -> VGroup: 

2962 """The faded copies the transformations left of what they moved whole, where it 

2963 was, with `leave_ghost_vectors`. 

2964 

2965 Returns: 

2966 The group of them. 

2967 """ 

2968 return self.ghost_vectors 

2969 

2970 def get_unit_square( 

2971 self, color: Colors = PURE_YELLOW, opacity: float = 0.3, stroke_width: float = 3 

2972 ) -> Rectangle: 

2973 """Make a rectangle over the plane's unit square: from its origin, one unit of x 

2974 wide and one unit of y tall. 

2975 

2976 Args: 

2977 color: The color of its fill and its stroke. 

2978 opacity: Its fill's opacity, from 0 to 1. 

2979 stroke_width: Its stroke's width, in hundredths of a scene unit. 

2980 

2981 Returns: 

2982 A new rectangle, also kept as the scene's `square`. 

2983 """ 

2984 square = self.square = Rectangle( 

2985 color=color, 

2986 width=self.plane.get_x_unit_size(), 

2987 height=self.plane.get_y_unit_size(), 

2988 stroke_color=color, 

2989 stroke_width=stroke_width, 

2990 fill_color=color, 

2991 fill_opacity=opacity, 

2992 ) 

2993 square.move_to(self.plane.coords_to_point(0, 0), DL) 

2994 return square 

2995 

2996 def add_unit_square( 

2997 self, animate: bool = False, **kwargs: Unpack[UnitSquareOptions] 

2998 ) -> Self: 

2999 """Add the plane's unit square, which the transformations move with the plane: 

3000 its area shows how they scale areas. 

3001 

3002 The moving vectors are then brought to the front, over it. 

3003 

3004 Args: 

3005 animate: Whether to draw it in: its border, then its fill. 

3006 **kwargs: [Unit square keywords][manimgx.scene.UnitSquareOptions]. 

3007 """ 

3008 square = self.get_unit_square(**kwargs) 

3009 if animate: 

3010 self.play( 

3011 DrawBorderThenFill(square), Animation(Group(*self.moving_vectors)) 

3012 ) 

3013 self.add_transformable_mobject(square) 

3014 self.bring_to_front(*self.moving_vectors) 

3015 self.square = square 

3016 return self 

3017 

3018 def added_vector(self, vector: Arrow) -> None: 

3019 self.moving_vectors.append(vector) 

3020 

3021 def write_vector_coordinates( 

3022 self, vector: Vector, **kwargs: Unpack[MatrixOptions] 

3023 ) -> Matrix: 

3024 """Write a vector's coordinates beside its tip, as a column that stays in front, 

3025 where it is, through the transformations. 

3026 

3027 Args: 

3028 **kwargs: [Matrix keywords][manimgx.mobjects.grid.MatrixOptions] for the 

3029 column. 

3030 

3031 Returns: 

3032 The column. 

3033 """ 

3034 coords = super().write_vector_coordinates(vector, **kwargs) 

3035 self.add_foreground_mobject(coords) 

3036 return coords 

3037 

3038 def add_transformable_label( 

3039 self, 

3040 vector: Vector, 

3041 label: ManimTextLabel | str, 

3042 transformation_name: str | ManimTextLabel = "L", 

3043 new_label: str | ManimTextLabel | None = None, 

3044 *, 

3045 animate: bool = True, 

3046 **kwargs: Unpack[VectorLabelOptions], 

3047 ) -> ManimTextLabel: 

3048 """Label a vector with a label that the transformations carry along and rewrite. 

3049 

3050 After a transformation, the label sits by the vector where it went, and reads 

3051 `new_label`, or else the label in the transformation's name: `L(v)` for a label 

3052 `v`. 

3053 

3054 Args: 

3055 vector: The vector, from the origin. 

3056 label: The label: a mobject, or LaTeX (see 

3057 [`get_vector_label`][manimgx.VectorScene.get_vector_label]). 

3058 transformation_name: The name of the transformation. 

3059 new_label: What the label reads after a transformation; None for the 

3060 transformation's name around it. 

3061 animate: Whether to write it in. 

3062 **kwargs: [Vector label keywords][manimgx.scene.VectorLabelOptions]. 

3063 

3064 Returns: 

3065 The label. 

3066 """ 

3067 label_mob = self.label_vector(vector, label, animate, **kwargs) 

3068 if new_label: 

3069 target_text: str | ManimTextLabel = new_label 

3070 else: 

3071 written = ( 

3072 label_mob.tex_string 

3073 if isinstance(label_mob, (MathTex, SingleStringMathTex)) 

3074 else str(label) 

3075 ) 

3076 target_text = f"{transformation_name}({written})" 

3077 self.transformable_labels.append( 

3078 _TransformableLabel(label_mob, vector, target_text, kwargs) 

3079 ) 

3080 return label_mob 

3081 

3082 def add_title( 

3083 self, title: str | Mobject, scale_factor: float = 1.5, animate: bool = False 

3084 ) -> Self: 

3085 """Add a title at the top of the frame, in front and still, on a background 

3086 rectangle. 

3087 

3088 Args: 

3089 title: The title: a mobject, or text, typeset as [`Tex`][manimgx.Tex]. 

3090 scale_factor: How much text is scaled. 

3091 animate: Whether to write it in. 

3092 """ 

3093 if not isinstance(title, Mobject): 

3094 title = Tex(title).scale(scale_factor) 

3095 title.to_edge(UP) 

3096 title.add_background_rectangle() 

3097 if animate: 

3098 self.play(Write(title)) 

3099 self.add_foreground_mobject(title) 

3100 self.title = title 

3101 return self 

3102 

3103 @deprecated("Manim CE's machinery: apply_matrix calls it", category=None) 

3104 def get_matrix_transformation( 

3105 self, matrix: npt.ArrayLike 

3106 ) -> Callable[[Point3D], Point3D]: 

3107 """The function that applies a matrix to a point. 

3108 

3109 Args: 

3110 matrix: A 2 × 2 matrix, which acts on x and y, or a 3 × 3 one; any other 

3111 shape raises a ValueError. 

3112 

3113 Returns: 

3114 The function from a point to its image. 

3115 """ 

3116 return self.get_transposed_matrix_transformation(np.array(matrix).T) 

3117 

3118 @deprecated("Manim CE's machinery: apply_matrix calls it", category=None) 

3119 def get_transposed_matrix_transformation( 

3120 self, transposed_matrix: npt.ArrayLike 

3121 ) -> Callable[[Point3D], Point3D]: 

3122 """The function that applies a matrix to a point, given its transpose. 

3123 

3124 Args: 

3125 transposed_matrix: The matrix's transpose, whose rows are where the matrix 

3126 takes î and ĵ: 2 × 2, acting on x and y, or 3 × 3; any other shape 

3127 raises a ValueError. 

3128 

3129 Returns: 

3130 The function from a point to its image. 

3131 """ 

3132 matrix = np.array(transposed_matrix, dtype=float) 

3133 if matrix.shape == (2, 2): 

3134 full = np.identity(3) 

3135 full[:2, :2] = matrix 

3136 matrix = full 

3137 elif matrix.shape != (3, 3): 

3138 raise ValueError("Matrix has bad dimensions") 

3139 return lambda point: np.dot(point, matrix) 

3140 

3141 @deprecated("Manim CE's machinery: apply_matrix calls it", category=None) 

3142 def get_piece_movement(self, pieces: Iterable[Mobject]) -> Transform: 

3143 """The animation that moves mobjects whole into their targets (their `target` 

3144 each), all together. 

3145 

3146 With `leave_ghost_vectors`, a faded copy of them is left in the scene where they 

3147 are. 

3148 

3149 Args: 

3150 pieces: The mobjects; those that are not paths are left out. 

3151 

3152 Returns: 

3153 A [`Transform`][manimgx.Transform] of them into their targets. 

3154 """ 

3155 v_pieces = [piece for piece in pieces if isinstance(piece, VMobject)] 

3156 start = VGroup(*v_pieces) 

3157 target = VGroup(*(mob.target for mob in v_pieces if mob.target is not None)) 

3158 if self.leave_ghost_vectors and start.submobjects: 

3159 self.ghost_vectors.add(start.copy().fade(0.7)) 

3160 self.add(self.ghost_vectors[-1]) 

3161 return Transform(start, target, lag_ratio=0) 

3162 

3163 @deprecated("Manim CE's machinery: apply_matrix calls it", category=None) 

3164 def get_moving_mobject_movement(self, func: MappingFunction) -> Transform: 

3165 """The animation that moves the moving mobjects whole to where a function takes 

3166 their centers. 

3167 

3168 Args: 

3169 func: The function, from a point to its image. 

3170 

3171 Returns: 

3172 A [`Transform`][manimgx.Transform] of them. 

3173 """ 

3174 for m in self.moving_mobjects: 

3175 if m.target is None: 

3176 m.target = m.copy() 

3177 m.target.move_to(func(m.get_center())) 

3178 return self.get_piece_movement(self.moving_mobjects) 

3179 

3180 @deprecated("Manim CE's machinery: apply_matrix calls it", category=None) 

3181 def get_vector_movement(self, func: MappingFunction) -> Transform: 

3182 """The animation that redraws the moving vectors to where a function takes their 

3183 tips; a vector that ends up shorter than 0.1 gets a tip as small. 

3184 

3185 Args: 

3186 func: The function, from a point to its image. 

3187 

3188 Returns: 

3189 A [`Transform`][manimgx.Transform] of them. 

3190 """ 

3191 for v in self.moving_vectors: 

3192 target = Vector(func(v.get_end()), color=v.get_color()) 

3193 norm = float(np.linalg.norm(target.get_end())) 

3194 if norm < 0.1: 

3195 target.get_tip().scale(norm) 

3196 v.target = target 

3197 return self.get_piece_movement(self.moving_vectors) 

3198 

3199 @deprecated("Manim CE's machinery: apply_matrix calls it", category=None) 

3200 def get_transformable_label_movement(self) -> Transform: 

3201 """The animation that moves each transformable label to where its vector goes, 

3202 rewritten: it follows `get_vector_movement`, which moves the vectors. 

3203 

3204 Returns: 

3205 A [`Transform`][manimgx.Transform] of the labels. 

3206 """ 

3207 for item in self.transformable_labels: 

3208 moved = item.vector.target 

3209 item.label.target = self.get_vector_label( 

3210 moved if isinstance(moved, Vector) else item.vector, 

3211 item.target_text, 

3212 **item.options, 

3213 ) 

3214 return self.get_piece_movement(item.label for item in self.transformable_labels) 

3215 

3216 def apply_matrix( 

3217 self, matrix: npt.ArrayLike, **kwargs: Unpack[TransformOptions] 

3218 ) -> None: 

3219 """Apply a matrix to the plane and to everything on it, in one play. 

3220 

3221 Everything the transformations move goes where the matrix takes it (see 

3222 [`apply_function`][manimgx.LinearTransformationScene.apply_function]). Unless a 

3223 `path_arc` is given, the points travel along arcs that turn through the mean of 

3224 the angles the matrix turns î and ĵ through. 

3225 

3226 Args: 

3227 matrix: A 2 × 2 matrix, which acts on x and y, or a 3 × 3 one: its columns 

3228 are where it takes î and ĵ. 

3229 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

3230 every animation of the play (3 seconds long unless given a `run_time`). 

3231 """ 

3232 self.apply_transposed_matrix(np.array(matrix).T, **kwargs) 

3233 

3234 def apply_inverse( 

3235 self, matrix: npt.ArrayLike, **kwargs: Unpack[TransformOptions] 

3236 ) -> None: 

3237 """Apply the inverse of a matrix to the plane and to everything on it: undo 

3238 [`apply_matrix`][manimgx.LinearTransformationScene.apply_matrix] of the same 

3239 matrix. 

3240 

3241 Args: 

3242 matrix: The matrix, 2 × 2 or 3 × 3, which must be invertible. 

3243 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

3244 every animation of the play. 

3245 """ 

3246 self.apply_matrix(np.linalg.inv(np.asarray(matrix, dtype=float)), **kwargs) 

3247 

3248 def apply_transposed_matrix( 

3249 self, transposed_matrix: npt.ArrayLike, **kwargs: Unpack[TransformOptions] 

3250 ) -> None: 

3251 """Apply a matrix, given by its transpose, to the plane and to everything on it: 

3252 as [`apply_matrix`][manimgx.LinearTransformationScene.apply_matrix] does. 

3253 

3254 Args: 

3255 transposed_matrix: The matrix's transpose, whose rows are where the matrix 

3256 takes î and ĵ. 

3257 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

3258 every animation of the play. 

3259 """ 

3260 func = self.get_transposed_matrix_transformation(transposed_matrix) 

3261 if "path_arc" not in kwargs: 

3262 kwargs["path_arc"] = float( 

3263 np.mean( 

3264 [ 

3265 angle_of_vector(func(RIGHT)), 

3266 angle_of_vector(func(UP)) - np.pi / 2, 

3267 ] 

3268 ) 

3269 ) 

3270 self.apply_function(func, **kwargs) 

3271 

3272 def apply_inverse_transpose( 

3273 self, t_matrix: npt.ArrayLike, **kwargs: Unpack[TransformOptions] 

3274 ) -> None: 

3275 """Apply the inverse of a matrix's transpose to the plane and to everything on 

3276 it. 

3277 

3278 Args: 

3279 t_matrix: The matrix, 2 × 2 or 3 × 3, which must be invertible. 

3280 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

3281 every animation of the play. 

3282 """ 

3283 t_inv = np.linalg.inv(np.array(t_matrix, dtype=float).T).T 

3284 self.apply_transposed_matrix(t_inv, **kwargs) 

3285 

3286 def apply_nonlinear_transformation( 

3287 self, 

3288 function: Callable[[np.ndarray], np.ndarray], 

3289 **kwargs: Unpack[TransformOptions], 

3290 ) -> None: 

3291 """Apply a function that need not be linear to the plane and to everything on 

3292 it. 

3293 

3294 The plane's lines are first divided into many curves, so that they can bend (see 

3295 [`apply_function`][manimgx.LinearTransformationScene.apply_function]). 

3296 

3297 Args: 

3298 function: The function, from a point to its image, in scene coordinates. 

3299 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

3300 every animation of the play. 

3301 """ 

3302 self.plane.prepare_for_nonlinear_transform() 

3303 self.apply_function(function, **kwargs) 

3304 

3305 def apply_function( 

3306 self, 

3307 function: MappingFunction, 

3308 added_anims: Sequence[Animation] | None = None, 

3309 **kwargs: Unpack[TransformOptions], 

3310 ) -> None: 

3311 """Apply a function to the plane and to everything on it, in one play. 

3312 

3313 Every point of the transformable mobjects goes where `function` takes it; each 

3314 vector is redrawn to where its tip goes, and its transformable label follows it; 

3315 each moving mobject moves whole to where its center goes; the foreground 

3316 mobjects stay where they are. With `leave_ghost_vectors`, faded copies of what 

3317 moves whole are left behind. 

3318 

3319 Args: 

3320 function: The function, from a point to its image, in scene coordinates. 

3321 added_anims: Animations to play along. 

3322 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

3323 every animation of the play (3 seconds long unless given a `run_time`). 

3324 """ 

3325 kwargs.setdefault("run_time", 3) 

3326 anims: list[Animation] = [ 

3327 *( 

3328 ApplyPointwiseFunction(function, t_mob) 

3329 for t_mob in self.transformable_mobjects 

3330 ), 

3331 self.get_vector_movement(function), 

3332 self.get_transformable_label_movement(), 

3333 self.get_moving_mobject_movement(function), 

3334 *(Animation(f_mob) for f_mob in self.foreground_mobjects), 

3335 *(added_anims or ()), 

3336 ] 

3337 self.play(*anims, **kwargs)