Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Introduce a `Manager` for render-flow coordination (#4916)

Benjamin Hackl9a9873ef158e
diff --git a/docs/source/guides/deep_dive.rst b/docs/source/guides/deep_dive.rst
index 6c4cd1e2f..050eb052d 100644
--- a/docs/source/guides/deep_dive.rst
+++ b/docs/source/guides/deep_dive.rst
@@ -5,10 +5,10 @@ A deep dive into Manim's internals
.. admonition:: Disclaimer
- This guide reflects the state of the library as of version ``v0.16.0``
- and primarily treats the Cairo renderer. The situation in the latest
- version of Manim might be different; in case of substantial deviations
- we will add a note below.
+ This guide was originally written for version ``v0.16.0`` and primarily
+ treats the Cairo renderer. Its high-level lifecycle discussion has been
+ updated for the :class:`.Manager` coordination layer, but some lower-level
+ implementation details may still differ from the latest version of Manim.
Introduction
------------
@@ -104,10 +104,12 @@ discussing the contents of the following chapters on a very high level.
steps through a time line and renders frame by frame. The final part
does some post-processing and seals the encoding job for a short video segment
("partial movie file") before cleaning up for the next call to
- :meth:`.Scene.play`. Depending on the encoding configuration, the partial movie
- file can continue encoding while the next animation is rendered. In the end,
- after all of :meth:`.Scene.construct` has been run, the library waits for any
- remaining encoding jobs and combines the partial movie files into one video.
+ :meth:`.Scene.play`. The :class:`.Manager` is the coordination layer around
+ these calls, while the renderer still implements most of the per-animation
+ processing described here. Depending on the encoding configuration, the partial
+ movie file can continue encoding while the next animation is rendered. In the
+ end, after all of :meth:`.Scene.construct` has been run, the library waits for
+ any remaining encoding jobs and combines the partial movie files into one video.
And with that, let us get *in medias res*.
@@ -220,12 +222,12 @@ dictionary, and upon leaving the context the original version of the
configuration is restored. TL;DR: it provides a fancy way of temporarily setting
configuration options.
-Inside the context manager, two things happen: an actual ``ToyExample``-scene
-object is instantiated, and the ``render`` method is called. Every way of using
-Manim ultimately does something along of these lines, the library always instantiates
-the scene object and then calls its ``render`` method. To illustrate that this
-really is the case, let us briefly look at the two most common ways of rendering
-scenes:
+Inside the context manager, two things happen: an actual ``ToyExample`` scene
+object is instantiated, and its ``render`` method is called. The render lifecycle
+is coordinated by a :class:`.Manager` attached to that scene. The CLI attaches a
+manager explicitly, while direct calls to :meth:`.Scene.render` create one lazily
+if necessary. To illustrate this, let us briefly look at the two most common ways
+of rendering scenes:
**Command Line Interface.** When using the CLI and running the command
``manim -qm -p toy_example.py ToyExample`` in your terminal, the actual
@@ -234,15 +236,16 @@ entry point is Manim's ``__main__.py`` file (located
Manim uses `Click <https://click.palletsprojects.com/en/8.0.x/>`__ to implement
the command line interface, and the corresponding code is located in Manim's
``cli`` module (https://github.com/ManimCommunity/manim/tree/main/manim/cli).
-The corresponding code creating the scene class and calling its render method
-is located `here <https://github.com/ManimCommunity/manim/blob/ac1ee9a683ce8b92233407351c681f7d71a4f2db/manim/cli/render/commands.py#L139-L141>`__.
+The corresponding code instantiates the scene, attaches a :class:`.Manager`, and
+then calls the scene's render method in the
+`render command <https://github.com/ManimCommunity/manim/blob/main/manim/cli/render/commands.py>`__.
**Jupyter notebooks.** In Jupyter notebooks, the communication with the library
is handled by the ``%%manim`` magic command, which is implemented in the
``manim.utils.ipython_magic`` module. There is
:meth:`some documentation <.ManimMagic.manim>` available for the magic command,
-and the code creating the scene class and calling its render method is located
-`here <https://github.com/ManimCommunity/manim/blob/ac1ee9a683ce8b92233407351c681f7d71a4f2db/manim/utils/ipython_magic.py#L137-L138>`__.
+The implementation instantiates the requested scene and calls its render method;
+the scene attaches a manager lazily through that entry point.
Now that we know that either way, a :class:`.Scene` object is created, let us investigate
@@ -273,29 +276,29 @@ renderer (see the implementation `here <https://github.com/ManimCommunity/manim/
does some additional setup to enable the realtime rendering preview window, which we do not go
into detail further here.
-.. warning::
+After the renderer has been instantiated and initialized its file writer, the scene
+populates further initial attributes (notable mention: the ``mobjects`` attribute
+which keeps track of the mobjects that have been added to the scene). Its ``manager``
+attribute is initially ``None`` unless the caller attaches a manager explicitly.
- Currently, there is a lot of interplay between a scene and its renderer. This is a flaw
- in Manim's current architecture, and we are working on reducing this interdependency to
- achieve a less convoluted code flow.
+.. warning::
-After the renderer has been instantiated and initialized its file writer, the scene populates
-further initial attributes (notable mention: the ``mobjects`` attribute which keeps track
-of the mobjects that have been added to the scene). It is then done with its instantiation
-and ready to be rendered.
+ :class:`.Manager` is an incremental coordination boundary. At this stage the
+ renderer still owns its camera, clock, play count, skip state, and file writer;
+ the manager exposes forwarding views of them. The scene and renderer therefore
+ still have substantial interplay that later refactors aim to remove.
The rest of this article is concerned with the last line in our toy example script::
scene.render()
-This is where the actual magic happens.
+This is where the actual magic happens. :meth:`.Scene.render` obtains the scene's
+manager, creating and attaching a :class:`.Manager` if necessary, and delegates to
+:meth:`.Manager.render`. The manager describes the full *render cycle* of a scene
+through four methods: :meth:`.Manager.setup`, :meth:`.Manager.construct`,
+:meth:`.Manager.tear_down`, and :meth:`.Manager.post_construct`.
-Inspecting the `implementation of the render method <https://github.com/ManimCommunity/manim/blob/df1a60421ea1119cbbbd143ef288d294851baaac/manim/scene/scene.py#L211>`__
-reveals that there are several hooks that can be used for pre- or postprocessing
-a scene. Unsurprisingly, :meth:`.Scene.render` describes the full *render cycle*
-of a scene. During this life cycle, there are three custom methods whose base
-implementation is empty and that can be overwritten to suit your purposes. In
-the order they are called, these customizable methods are:
+The first three call the corresponding customizable scene hooks:
- :meth:`.Scene.setup`, which is intended for preparing and, well, *setting up*
the scene for your animation (e.g., adding initial mobjects, assigning custom
@@ -309,19 +312,18 @@ the order they are called, these customizable methods are:
hook is more relevant for situations where Manim is used within other
Python scripts).
-After these three methods are run, the animations have been fully rendered,
-and Manim calls :meth:`.CairoRenderer.scene_finished` to gracefully
-complete the rendering process. This checks whether any animations have been
-played -- and if so, it tells the :class:`.SceneFileWriter` to finish the output.
-For video output, this first waits for any partial movie files that are still
-being encoded and then combines them into the final movie. If no animations have
-been played, Manim assumes that a static image should be output, which it renders
-using the same strategy by calling the render loop (see below) once.
+After these hooks have run, :meth:`.Manager.post_construct` asks the renderer to
+finish the scene. For Cairo this calls :meth:`.CairoRenderer.scene_finished`,
+which checks whether animations have been played and tells the
+:class:`.SceneFileWriter` to finish the output. For video output, the file writer
+waits for partial movie files that are still being encoded and combines them into
+the final movie. If no animations have been played, Manim assumes that a static
+image should be output.
-**Back in our toy example,** the call to :meth:`.Scene.render` first
-triggers :meth:`.Scene.setup` (which only consists of ``pass``), followed by
-a call of :meth:`.Scene.construct`. At this point, our *animation script*
-is run, starting with the initialization of ``orange_square``.
+**Back in our toy example,** the call to :meth:`.Scene.render` creates a manager,
+then :meth:`.Manager.render` triggers :meth:`.Scene.setup` (which only consists of
+``pass``), followed by :meth:`.Scene.construct`. At this point, our *animation
+script* is run, starting with the initialization of ``orange_square``.
Mobject Initialization
@@ -699,19 +701,19 @@ walk through the code that is run when :meth:`.Scene.play` is called.
and lifecycle of mobjects is still more or less the same. There are more
substantial differences when it comes to the rendering loop.
-As you will see when inspecting the method, :meth:`.Scene.play` almost
-immediately passes over to the ``play`` method of the renderer,
-in our case :class:`.CairoRenderer.play`. The one thing :meth:`.Scene.play`
-takes care of is the management of subcaptions that you might have
-passed to it (see the the documentation of :meth:`.Scene.play` and
-:meth:`.Scene.add_subcaption` for more information).
+As you will see when inspecting the method, :meth:`.Scene.play` first handles
+an OpenGL interactive-thread guard and then delegates to :meth:`.Manager.play`.
+The manager records the current renderer time and calls the renderer's ``play``
+method, in our case :meth:`.CairoRenderer.play`. Once the renderer returns, the
+manager uses the elapsed time to schedule an optional subcaption (see
+:meth:`.Scene.play` and :meth:`.Scene.add_subcaption` for more information).
.. warning::
- As has been said before, the communication between scene and renderer
- is not in a very clean state at this point, so the following paragraphs
- might be confusing if you don't run a debugger and step through the
- code yourself a bit.
+ The manager currently coordinates the call but deliberately preserves the
+ existing renderer implementation. Most compilation, caching, frame iteration,
+ and output behavior described in the following paragraphs still belongs to the
+ renderer and scene during this transitional stage.
Inside :meth:`.CairoRenderer.play`, the renderer first checks whether
it may skip rendering of the current play call. This might happen, for example,
@@ -813,9 +815,9 @@ example and discuss how the generic :meth:`.Scene.play` call
setup looks like there.
For the call that plays the :class:`.ReplacementTransform`, there
-is no subcaption to be taken care of. The renderer then asks
-the scene to compile the animation data: the passed argument
-already is an animation (no additional preparations needed),
+is no subcaption for the manager to schedule. The manager forwards the call,
+and the renderer then asks the scene to compile the animation data: the passed
+argument already is an animation (no additional preparations needed),
there is no need for processing any keyword arguments (as
we did not specify any additional ones to ``play``). The
mobject bound to the animation, ``orange_square``, is already
@@ -1030,14 +1032,15 @@ remaining :meth:`.Scene.play` and :meth:`.Scene.wait` calls follow the exact sam
procedure as discussed in the render loop section above; each such call produces
a corresponding partial movie file.
-Once the :meth:`.Scene.construct` method has been fully processed, the scene calls
-its cleanup method :meth:`.Scene.tear_down`, and then asks its renderer to finish
-the scene. The renderer, in turn, asks its scene file writer to wrap things up by
+Once the :meth:`.Scene.construct` method has been fully processed, the manager
+calls the scene's cleanup method :meth:`.Scene.tear_down`, followed by
+:meth:`.Manager.post_construct`. The manager asks the renderer to finish the
+scene, and the renderer in turn asks its scene file writer to wrap things up by
calling :meth:`.SceneFileWriter.finish`. The file writer first waits for all
remaining encoding jobs, then combines the completed partial movie files into the
-final product. If rendering aborts during a play instead, the current job is
-sealed and drained, and its incomplete partial movie file is removed so that it
-cannot be mistaken for a valid cached result on a later render.
+final product. If rendering aborts during a play instead, the manager asks the file
+writer to abort its encoding jobs; the incomplete current partial movie file is
+removed so that it cannot be mistaken for a valid cached result on a later render.
And there you go! This is a more or less detailed description of how Manim works
under the hood. While we did not discuss every single line of code in detail
diff --git a/docs/source/reference_index/scenes.rst b/docs/source/reference_index/scenes.rst
index 38f09119d..70c42de2c 100644
--- a/docs/source/reference_index/scenes.rst
+++ b/docs/source/reference_index/scenes.rst
@@ -6,6 +6,7 @@ Scenes
.. autosummary::
:toctree: ../reference
+ manager
~scene.moving_camera_scene
~scene.section
~scene.scene
diff --git a/docs/source/tutorials/building_blocks.rst b/docs/source/tutorials/building_blocks.rst
index 46d6ea278..5878f3a49 100644
--- a/docs/source/tutorials/building_blocks.rst
+++ b/docs/source/tutorials/building_blocks.rst
@@ -53,7 +53,7 @@ Creating and displaying mobjects
================================
As explained in :doc:`quickstart`, usually all of the code in a manim
-script is put inside the :meth:`.construct` method of a :class:`.Scene` class.
+script is put inside the :meth:`.Scene.construct` method of a :class:`.Scene` class.
To display a mobject on the screen, call the :meth:`~.Scene.add` method of the
containing :class:`.Scene`. This is the principal way of displaying a mobject
on the screen when it is not being animated. To remove a mobject from the
diff --git a/manim/__init__.py b/manim/__init__.py
index 975987c92..9fd8e65f1 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -47,6 +47,7 @@ from .camera.moving_camera import *
from .camera.multi_camera import *
from .camera.three_d_camera import *
from .constants import *
+from .manager import *
from .mobject.frame import *
from .mobject.geometry.arc import *
from .mobject.geometry.boolean_ops import *
diff --git a/manim/cli/render/commands.py b/manim/cli/render/commands.py
index fde82f497..5c36b41a9 100644
--- a/manim/cli/render/commands.py
+++ b/manim/cli/render/commands.py
@@ -32,6 +32,7 @@ from manim.cli.render.global_options import global_options
from manim.cli.render.output_options import output_options
from manim.cli.render.render_options import render_options
from manim.constants import EPILOG, RendererType
+from manim.manager import Manager
from manim.utils.module_ops import scene_classes_from_file
__all__ = ["render"]
@@ -104,6 +105,8 @@ def render(**kwargs: Any) -> ClickArgs | dict[str, Any]:
for SceneClass in scene_classes_from_file(file):
with tempconfig({}):
scene = SceneClass(renderer)
+ # Attach explicitly, but preserve custom Scene.render overrides.
+ Manager(scene)
rerun = scene.render()
if rerun or config["write_all"]:
renderer.num_plays = 0
@@ -122,6 +125,8 @@ def render(**kwargs: Any) -> ClickArgs | dict[str, Any]:
try:
with tempconfig({}):
scene = SceneClass()
+ # Attach explicitly, but preserve custom Scene.render overrides.
+ Manager(scene)
scene.render()
except Exception:
error_console.print_exception()
diff --git a/manim/manager.py b/manim/manager.py
new file mode 100644
index 000000000..dae957e53
--- /dev/null
+++ b/manim/manager.py
@@ -0,0 +1,305 @@
+"""Orchestration for rendering a scene."""
+
+from __future__ import annotations
+
+import datetime
+from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast
+
+import srt
+
+from . import config, logger
+from .scene.section import DefaultSectionType
+from .utils.exceptions import EndSceneEarlyException, RerunSceneException
+from .utils.file_ops import open_media_file
+
+if TYPE_CHECKING:
+ from .animation.animation import Animation
+ from .camera.camera import Camera
+ from .mobject.mobject import Mobject, _AnimationBuilder
+ from .renderer.cairo_renderer import CairoRenderer
+ from .renderer.opengl_renderer import OpenGLCamera, OpenGLRenderer
+ from .scene.scene import Scene
+ from .scene.scene_file_writer import SceneFileWriter
+
+__all__ = ["Manager"]
+
+SceneT = TypeVar("SceneT", bound="Scene")
+
+
+class Manager(Generic[SceneT]):
+ """Coordinate the render lifecycle for a single scene.
+
+ A manager is attached to exactly one :class:`~manim.scene.scene.Scene`. It
+ coordinates the scene lifecycle, delegates animation playback to the current
+ renderer, and routes section, subcaption, and audio operations to the current
+ file writer. Calling :meth:`~manim.scene.scene.Scene.render` creates a manager
+ lazily when one has not already been attached.
+
+ Parameters
+ ----------
+ scene
+ The scene coordinated by this manager. A scene that already has a manager
+ cannot be attached to another one.
+
+ Attributes
+ ----------
+ scene
+ The managed scene.
+
+ Notes
+ -----
+ This class is the coordination boundary for an incremental render-flow
+ refactor. Renderer, camera, clock, and output ownership still remain on the
+ scene and renderer for compatibility. The :attr:`renderer`, :attr:`camera`,
+ :attr:`file_writer`, :attr:`time`, :attr:`num_plays`, and
+ :attr:`skip_animations` properties are forwarding views for now.
+
+ Examples
+ --------
+ A scene normally creates its manager when :meth:`~manim.scene.scene.Scene.render`
+ is called. It can also be attached explicitly::
+
+ scene = Scene()
+ manager = Manager(scene)
+ manager.render()
+ """
+
+ def __init__(self, scene: SceneT) -> None:
+ if scene.manager is not None:
+ raise ValueError("A manager is already attached to this scene.")
+ self.scene = scene
+ scene.manager = self
+
+ @property
+ def renderer(self) -> CairoRenderer | OpenGLRenderer:
+ """Return the scene's current renderer."""
+ return self.scene.renderer
+
+ @property
+ def camera(self) -> Camera | OpenGLCamera:
+ """Return the current renderer's camera."""
+ return self.renderer.camera
+
+ @property
+ def file_writer(self) -> SceneFileWriter:
+ """Return the current renderer's file writer."""
+ return cast("SceneFileWriter", self.renderer.file_writer)
+
+ @property
+ def time(self) -> float:
+ """Return the current renderer time."""
+ return self.renderer.time
+
+ @time.setter
+ def time(self, value: float) -> None:
+ self.renderer.time = value
+
+ @property
+ def num_plays(self) -> int:
+ """Return the current renderer's play count."""
+ return self.renderer.num_plays
+
+ @num_plays.setter
+ def num_plays(self, value: int) -> None:
+ self.renderer.num_plays = value
+
+ @property
+ def skip_animations(self) -> bool:
+ """Return the current renderer's animation skip state."""
+ return self.renderer.skip_animations
+
+ @skip_animations.setter
+ def skip_animations(self, value: bool) -> None:
+ self.renderer.skip_animations = value
+
+ def render(self, preview: bool = False) -> bool:
+ """Run the complete render lifecycle for the managed scene.
+
+ The lifecycle invokes :meth:`setup`, :meth:`construct`,
+ :meth:`tear_down`, and :meth:`post_construct`, in that order. Reaching a
+ configured animation boundary ends construction normally. Exceptions
+ raised while constructing the scene abort active encoding jobs before
+ they are propagated.
+
+ Parameters
+ ----------
+ preview
+ Whether the rendered media should be opened after rendering.
+
+ Returns
+ -------
+ bool
+ ``True`` when an interactive rerun was requested; otherwise
+ ``False``. This matches the return value of
+ :meth:`~manim.scene.scene.Scene.render`.
+ """
+ self.setup()
+ try:
+ self.construct()
+ except EndSceneEarlyException:
+ # Reaching the configured animation boundary ends the scene normally.
+ pass
+ except RerunSceneException:
+ self.scene.remove(*self.scene.mobjects)
+ # TODO: The CairoRenderer does not have the method clear_screen().
+ self.renderer.clear_screen() # type: ignore[union-attr]
+ self.num_plays = 0
+ # The rerun replaces the file writer; tear down its encode jobs so
+ # no worker is still writing a partial file the new writer may
+ # reuse. Encoder failures propagate: a rerun must not silently
+ # continue past corrupt output.
+ self.file_writer.abort_encode_jobs(reraise_encoder_failures=True)
+ return True
+ except BaseException:
+ # A mid-play exception leaves an unsealed encode job whose
+ # non-daemon worker would hang the process at exit.
+ self.file_writer.abort_encode_jobs()
+ raise
+ self.tear_down()
+ self.post_construct()
+
+ # If preview open up the render after rendering.
+ if preview:
+ config["preview"] = True
+
+ if config["preview"] or config["show_in_file_browser"]:
+ open_media_file(self.file_writer)
+
+ return False
+
+ def setup(self) -> None:
+ """Run the managed scene's :meth:`~manim.scene.scene.Scene.setup` hook."""
+ self.scene.setup()
+
+ def construct(self) -> None:
+ """Run the managed scene's :meth:`~manim.scene.scene.Scene.construct` hook."""
+ self.scene.construct()
+
+ def post_construct(self) -> None:
+ """Finalize output after scene construction and tear-down.
+
+ This asks the renderer to finish the scene and logs the number of played
+ animations. It intentionally runs after :meth:`tear_down` to preserve the
+ established render lifecycle.
+ """
+ # We have to reset these settings in case of multiple renders.
+ self.renderer.scene_finished(self.scene)
+
+ # Show info only if animations are rendered or to get image.
+ if self.num_plays or config["format"] == "png" or config["save_last_frame"]:
+ logger.info(
+ f"Rendered {str(self.scene)}\nPlayed {self.num_plays} animations",
+ )
+
+ def tear_down(self) -> None:
+ """Run the managed scene's :meth:`~manim.scene.scene.Scene.tear_down` hook."""
+ self.scene.tear_down()
+
+ def play(
+ self,
+ *args: Animation | Mobject | _AnimationBuilder,
+ subcaption: str | None = None,
+ subcaption_duration: float | None = None,
+ subcaption_offset: float = 0,
+ **kwargs: Any,
+ ) -> None:
+ """Coordinate an animation request and its optional subcaption.
+
+ Parameters
+ ----------
+ args
+ Animations, mobjects, or animation builders passed by
+ :meth:`~manim.scene.scene.Scene.play`.
+ subcaption
+ Content to add to the external subcaption file for this play call.
+ subcaption_duration
+ Duration of the subcaption. When omitted, the elapsed animation time
+ is used.
+ subcaption_offset
+ Offset in seconds from the beginning of the play call.
+ kwargs
+ Additional animation arguments forwarded to the renderer.
+ """
+ start_time = self.time
+ self.renderer.play(self.scene, *args, **kwargs)
+ run_time = self.time - start_time
+
+ if subcaption:
+ if subcaption_duration is None:
+ subcaption_duration = run_time
+ # The start of the subcaption needs to be offset by the run time
+ # because it is added after the animation has already played.
+ # Route through Scene's public API to preserve its customization hook.
+ self.scene.add_subcaption(
+ content=subcaption,
+ duration=subcaption_duration,
+ offset=-run_time + subcaption_offset,
+ )
+
+ def next_section(
+ self,
+ name: str = "unnamed",
+ section_type: str = DefaultSectionType.NORMAL,
+ skip_animations: bool = False,
+ ) -> None:
+ """Create a new output section.
+
+ Parameters
+ ----------
+ name
+ The section name.
+ section_type
+ The section type stored in the section manifest.
+ skip_animations
+ Whether animation output in this section should be skipped.
+ """
+ self.file_writer.next_section(name, section_type, skip_animations)
+
+ def add_subcaption(
+ self, content: str, duration: float = 1, offset: float = 0
+ ) -> None:
+ """Add a subcaption at the current scene time.
+
+ Parameters
+ ----------
+ content
+ The subcaption text.
+ duration
+ The duration in seconds for which the subcaption is displayed.
+ offset
+ The offset in seconds from the current scene time.
+ """
+ subtitle = srt.Subtitle(
+ index=len(self.file_writer.subcaptions),
+ content=content,
+ start=datetime.timedelta(seconds=float(self.time + offset)),
+ end=datetime.timedelta(seconds=float(self.time + offset + duration)),
+ )
+ self.file_writer.subcaptions.append(subtitle)
+
+ def add_sound(
+ self,
+ sound_file: str,
+ time_offset: float = 0,
+ gain: float | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Add sound to the output at the current scene time.
+
+ No sound is added while animations are being skipped.
+
+ Parameters
+ ----------
+ sound_file
+ The path to the sound file.
+ time_offset
+ The offset in seconds from the current scene time.
+ gain
+ The gain adjustment applied to the sound.
+ kwargs
+ Additional arguments forwarded to
+ :meth:`~manim.scene.scene_file_writer.SceneFileWriter.add_sound`.
+ """
+ if self.skip_animations:
+ return
+ self.file_writer.add_sound(sound_file, self.time + time_offset, gain, **kwargs)
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index 07c4a8f76..b4ef54f38 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -9,7 +9,6 @@ from ..mobject.mobject import _AnimationBuilder
__all__ = ["Scene"]
import copy
-import datetime
import inspect
import platform
import random
@@ -19,8 +18,6 @@ from dataclasses import dataclass
from pathlib import Path
from queue import Queue
-import srt
-
from manim.scene.section import DefaultSectionType
try:
@@ -49,14 +46,14 @@ from .. import config, logger
from ..animation.animation import Animation, Wait, prepare_animation
from ..camera.camera import Camera
from ..constants import *
+from ..manager import Manager
from ..renderer.cairo_renderer import CairoRenderer
from ..renderer.opengl_renderer import OpenGLCamera, OpenGLMobject, OpenGLRenderer
from ..renderer.shader import Object3D
from ..utils import opengl, space_ops
-from ..utils.exceptions import EndSceneEarlyException, RerunSceneException
+from ..utils.exceptions import RerunSceneException
from ..utils.family import extract_mobject_family_members
from ..utils.family_ops import restructure_list_to_exclude_certain_family_members
-from ..utils.file_ops import open_media_file
from ..utils.iterables import list_difference_update, list_update
from ..utils.module_ops import scene_classes_from_file
@@ -148,9 +145,10 @@ class Scene:
screen by calling :meth:`Scene.remove`. All mobjects currently on screen are kept
in :attr:`Scene.mobjects`. Animations are played by calling :meth:`Scene.play`.
- A :class:`Scene` is rendered internally by calling :meth:`Scene.render`. This in
- turn calls :meth:`Scene.setup`, :meth:`Scene.construct`, and
- :meth:`Scene.tear_down`, in that order.
+ A :class:`Scene` is rendered internally by calling :meth:`Scene.render`. This
+ delegates the render lifecycle to a :class:`~manim.manager.Manager`, which calls
+ :meth:`Scene.setup`, :meth:`Scene.construct`, and :meth:`Scene.tear_down`, in
+ that order.
It is not recommended to override the ``__init__`` method in user Scenes. For code
that should be ran before a Scene is rendered, use :meth:`Scene.setup` instead.
@@ -197,6 +195,7 @@ class Scene:
self.key_to_function_map: dict[str, Callable[[], None]] = {}
self.mouse_press_callbacks: list[Callable[[], None]] = []
self.interactive_mode = False
+ self.manager: Manager[Self] | None = None
if config.renderer == RendererType.OPENGL:
# Items associated with interaction
@@ -237,68 +236,39 @@ class Scene:
result = cls.__new__(cls)
clone_from_id[id(self)] = result
for k, v in self.__dict__.items():
- if k in ["renderer", "time_progression"]:
+ if k in ["manager", "renderer", "time_progression"]:
continue
if k == "camera_class":
setattr(result, k, v)
setattr(result, k, copy.deepcopy(v, clone_from_id))
+ result.manager = None
return result
def render(self, preview: bool = False) -> bool:
- """
- Renders this Scene.
+ """Render this scene through its :class:`~manim.manager.Manager`.
+
+ A manager is created and attached lazily if the scene does not already
+ have one.
Parameters
- ---------
+ ----------
preview
- If true, opens scene in a file viewer.
- """
- self.setup()
- try:
- self.construct()
- except EndSceneEarlyException:
- pass
- except RerunSceneException:
- self.remove(*self.mobjects)
- # TODO: The CairoRenderer does not have the method clear_screen()
- self.renderer.clear_screen() # type: ignore[union-attr]
- self.renderer.num_plays = 0
- # The rerun replaces the file writer; tear down its encode jobs so
- # no worker is still writing a partial file the new writer may
- # reuse. Encoder failures propagate: a rerun must not silently
- # continue past corrupt output.
- self.renderer.file_writer.abort_encode_jobs(
- reraise_encoder_failures=True,
- )
- return True
- except BaseException:
- # A mid-play exception leaves an unsealed encode job whose
- # non-daemon worker would hang the process at exit.
- self.renderer.file_writer.abort_encode_jobs()
- raise
- self.tear_down()
- # We have to reset these settings in case of multiple renders.
- self.renderer.scene_finished(self)
-
- # Show info only if animations are rendered or to get image
- if (
- self.renderer.num_plays
- or config["format"] == "png"
- or config["save_last_frame"]
- ):
- logger.info(
- f"Rendered {str(self)}\nPlayed {self.renderer.num_plays} animations",
- )
-
- # If preview open up the render after rendering.
- if preview:
- config["preview"] = True
+ Whether to open the rendered media after rendering.
- if config["preview"] or config["show_in_file_browser"]:
- open_media_file(self.renderer.file_writer)
+ Returns
+ -------
+ bool
+ Whether an interactive rerun was requested.
+ """
+ return self._get_manager().render(preview)
- return False
+ def _get_manager(self) -> Manager[Self]:
+ """Return this scene's manager, creating it for legacy entry points."""
+ manager = self.manager
+ if manager is None:
+ manager = Manager(self)
+ return manager
def setup(self) -> None:
"""
@@ -359,7 +329,7 @@ class Scene:
``skip_animations`` skips the rendering of all animations in this section.
Refer to :doc:`the documentation</tutorials/output_and_config>` on how to use sections.
"""
- self.renderer.file_writer.next_section(name, section_type, skip_animations)
+ self._get_manager().next_section(name, section_type, skip_animations)
def __str__(self) -> str:
return self.__class__.__name__
@@ -1205,21 +1175,13 @@ class Scene:
self.queue.put(SceneInteractRerun("play", **kwargs))
return
- start_time = self.time
- self.renderer.play(self, *args, **kwargs)
- run_time = self.time - start_time
- if subcaption:
- if subcaption_duration is None:
- subcaption_duration = run_time
- # The start of the subcaption needs to be offset by the
- # run_time of the animation because it is added after
- # the animation has already been played (and Scene.time
- # has already been updated).
- self.add_subcaption(
- content=subcaption,
- duration=subcaption_duration,
- offset=-run_time + subcaption_offset,
- )
+ self._get_manager().play(
+ *args,
+ subcaption=subcaption,
+ subcaption_duration=subcaption_duration,
+ subcaption_offset=subcaption_offset,
+ **kwargs,
+ )
def wait(
self,
@@ -1751,13 +1713,7 @@ class Scene:
)
"""
- subtitle = srt.Subtitle(
- index=len(self.renderer.file_writer.subcaptions),
- content=content,
- start=datetime.timedelta(seconds=float(self.time + offset)),
- end=datetime.timedelta(seconds=float(self.time + offset + duration)),
- )
- self.renderer.file_writer.subcaptions.append(subtitle)
+ self._get_manager().add_subcaption(content, duration, offset)
def add_sound(
self,
@@ -1801,10 +1757,7 @@ class Scene:
Download the resource for the previous example `here <https://github.com/ManimCommunity/manim/blob/main/docs/source/_static/click.wav>`_ .
"""
- if self.renderer.skip_animations:
- return
- time = self.time + time_offset
- self.renderer.file_writer.add_sound(sound_file, time, gain, **kwargs)
+ self._get_manager().add_sound(sound_file, time_offset, gain, **kwargs)
def on_mouse_motion(self, point: Point3D, d_point: Point3D) -> None:
assert isinstance(self.camera, OpenGLCamera)
diff --git a/tests/control_data/logs_data/BasicSceneLoggingTest.txt b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
index de56ea93c..0f49c5618 100644
--- a/tests/control_data/logs_data/BasicSceneLoggingTest.txt
+++ b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
@@ -7,4 +7,4 @@
{"levelname": "INFO", "module": "scene_file_writer", "message": "Combining to Movie file."}
{"levelname": "DEBUG", "module": "scene_file_writer", "message": "Partial movie files to combine (1 files): <>"}
{"levelname": "INFO", "module": "scene_file_writer", "message": "\nFile ready at <>\n"}
-{"levelname": "INFO", "module": "scene", "message": "Rendered SquareToCircle\nPlayed 1 animations"}
+{"levelname": "INFO", "module": "manager", "message": "Rendered SquareToCircle\nPlayed 1 animations"}
diff --git a/tests/module/test_manager.py b/tests/module/test_manager.py
new file mode 100644
index 000000000..df85ae6f4
--- /dev/null
+++ b/tests/module/test_manager.py
@@ -0,0 +1,383 @@
+from __future__ import annotations
+
+import copy
+import datetime
+import threading
+from unittest.mock import Mock
+
+import pytest
+import srt
+
+from manim import Manager, Scene, tempconfig
+from manim.animation.animation import Wait
+from manim.constants import RendererType
+from manim.scene.scene import SceneInteractRerun
+from manim.utils.exceptions import EndSceneEarlyException, RerunSceneException
+
+
+def test_manager_attaches_to_existing_scene(dry_run):
+ scene = Scene()
+
+ manager = Manager(scene)
+
+ assert manager.scene is scene
+ assert scene.manager is manager
+
+
+def test_manager_rejects_second_attachment(dry_run):
+ scene = Scene()
+ manager = Manager(scene)
+
+ with pytest.raises(ValueError, match="already attached"):
+ Manager(scene)
+
+ assert scene.manager is manager
+
+
+def test_deepcopy_leaves_clone_managerless(dry_run):
+ scene = Scene()
+ manager = Manager(scene)
+ scene.queue = None
+
+ clone = copy.deepcopy(scene)
+
+ assert scene.manager is manager
+ assert clone.manager is None
+
+
+def test_scene_render_lazily_creates_manager(dry_run):
+ lifecycle: list[str] = []
+
+ class LifecycleScene(Scene):
+ def setup(self):
+ lifecycle.append("setup")
+
+ def construct(self):
+ lifecycle.append("construct")
+
+ def tear_down(self):
+ lifecycle.append("tear_down")
+
+ scene = LifecycleScene()
+ assert scene.manager is None
+
+ assert scene.render() is False
+
+ assert isinstance(scene.manager, Manager)
+ assert lifecycle == ["setup", "construct", "tear_down"]
+
+
+def test_cli_style_render_preserves_scene_render_override(dry_run):
+ calls: list[bool] = []
+
+ class RenderOverrideScene(Scene):
+ def render(self, preview: bool = False) -> bool:
+ calls.append(preview)
+ return True
+
+ scene = RenderOverrideScene()
+ Manager(scene)
+
+ assert scene.render(preview=True) is True
+ assert calls == [True]
+
+
+def test_manager_render_uses_scene_lifecycle(dry_run):
+ lifecycle: list[str] = []
+
+ class LifecycleScene(Scene):
+ def setup(self):
+ lifecycle.append("setup")
+
+ def construct(self):
+ lifecycle.append("construct")
+
+ def tear_down(self):
+ lifecycle.append("tear_down")
+
+ scene = LifecycleScene()
+
+ assert Manager(scene).render() is False
+
+ assert lifecycle == ["setup", "construct", "tear_down"]
+
+
+def test_manager_render_uses_lifecycle_hooks(dry_run):
+ hooks: list[str] = []
+
+ class HookManager(Manager[Scene]):
+ def setup(self):
+ hooks.append("setup")
+ super().setup()
+
+ def construct(self):
+ hooks.append("construct")
+ super().construct()
+
+ def tear_down(self):
+ hooks.append("tear_down")
+ super().tear_down()
+
+ def post_construct(self):
+ hooks.append("post_construct")
+ super().post_construct()
+
+ assert HookManager(Scene()).render() is False
+
+ assert hooks == ["setup", "construct", "tear_down", "post_construct"]
+
+
+def test_manager_render_handles_rerun_without_finishing_scene(dry_run):
+ lifecycle: list[str] = []
+ renderer = Mock()
+ renderer.num_plays = 3
+
+ class RerunScene(Scene):
+ def construct(self):
+ raise RerunSceneException
+
+ def tear_down(self):
+ lifecycle.append("tear_down")
+
+ scene = RerunScene(renderer)
+
+ assert Manager(scene).render() is True
+
+ renderer.clear_screen.assert_called_once_with()
+ assert renderer.num_plays == 0
+ renderer.scene_finished.assert_not_called()
+ assert lifecycle == []
+
+
+def test_manager_render_finalizes_after_early_scene_end(dry_run):
+ lifecycle: list[str] = []
+ renderer = Mock()
+ renderer.num_plays = 0
+ renderer.scene_finished.side_effect = lambda scene: lifecycle.append(
+ "post_construct"
+ )
+
+ class EarlyEndScene(Scene):
+ def construct(self):
+ raise EndSceneEarlyException
+
+ def tear_down(self):
+ lifecycle.append("tear_down")
+
+ scene = EarlyEndScene(renderer)
+
+ assert Manager(scene).render() is False
+
+ renderer.scene_finished.assert_called_once_with(scene)
+ assert lifecycle == ["tear_down", "post_construct"]
+
+
+def test_scene_play_forwards_through_manager(dry_run, monkeypatch):
+ scene = Scene()
+ renderer_play = Mock()
+ file_writer = Mock()
+ file_writer.subcaptions = []
+ monkeypatch.setattr(scene.renderer, "play", renderer_play)
+ scene.renderer.file_writer = file_writer
+ animation = Wait()
+
+ scene.play(animation, run_time=2)
+
+ assert isinstance(scene.manager, Manager)
+ renderer_play.assert_called_once_with(scene, animation, run_time=2)
+ assert file_writer.subcaptions == []
+
+
+def test_scene_play_adds_subcaption_with_explicit_duration(dry_run, monkeypatch):
+ scene = Scene()
+ file_writer = Mock()
+ file_writer.subcaptions = []
+ scene.renderer.file_writer = file_writer
+ scene.renderer.time = 2.5
+ renderer_play = Mock(
+ side_effect=lambda *args, **kwargs: setattr(scene.renderer, "time", 4.5)
+ )
+ monkeypatch.setattr(scene.renderer, "play", renderer_play)
+ animation = Wait()
+
+ scene.play(
+ animation,
+ run_time=2,
+ subcaption="Hello",
+ subcaption_duration=1.25,
+ subcaption_offset=0.25,
+ )
+
+ renderer_play.assert_called_once_with(scene, animation, run_time=2)
+ assert file_writer.subcaptions == [
+ srt.Subtitle(
+ index=0,
+ content="Hello",
+ start=datetime.timedelta(seconds=2.75),
+ end=datetime.timedelta(seconds=4.0),
+ )
+ ]
+
+
+def test_scene_play_preserves_scene_add_subcaption_override(dry_run, monkeypatch):
+ subcaptions: list[tuple[str, float, float]] = []
+
+ class CustomSubcaptionScene(Scene):
+ def add_subcaption(
+ self, content: str, duration: float = 1, offset: float = 0
+ ) -> None:
+ subcaptions.append((content, duration, offset))
+
+ scene = CustomSubcaptionScene()
+ scene.renderer.time = 2.5
+ renderer_play = Mock(
+ side_effect=lambda *args, **kwargs: setattr(scene.renderer, "time", 4.5)
+ )
+ monkeypatch.setattr(scene.renderer, "play", renderer_play)
+
+ scene.play(
+ Wait(),
+ subcaption="Hello",
+ subcaption_duration=1.25,
+ subcaption_offset=0.25,
+ )
+
+ assert subcaptions == [("Hello", 1.25, -1.75)]
+
+
+def test_scene_play_uses_animation_duration_for_default_subcaption_after_skip(
+ dry_run, monkeypatch
+):
+ scene = Scene()
+ file_writer = Mock()
+ file_writer.subcaptions = []
+ scene.renderer.file_writer = file_writer
+ scene.renderer.time = 1.0
+ scene.renderer.skip_animations = True
+ renderer_play = Mock(
+ side_effect=lambda *args, **kwargs: setattr(scene.renderer, "time", 3.5)
+ )
+ monkeypatch.setattr(scene.renderer, "play", renderer_play)
+
+ scene.play(Wait(), subcaption="Hello")
+
+ assert file_writer.subcaptions == [
+ srt.Subtitle(
+ index=0,
+ content="Hello",
+ start=datetime.timedelta(seconds=1.0),
+ end=datetime.timedelta(seconds=3.5),
+ )
+ ]
+
+
+def test_scene_play_queues_interactive_calls_without_attaching_manager(
+ dry_run, monkeypatch
+):
+ scene = Scene()
+ scene.interactive_mode = True
+ renderer_play = Mock()
+ monkeypatch.setattr(scene.renderer, "play", renderer_play)
+ worker_thread = threading.Thread(name="Worker")
+ monkeypatch.setattr(threading, "current_thread", lambda: worker_thread)
+
+ with tempconfig({"renderer": RendererType.OPENGL}):
+ scene.play(
+ Wait(),
+ run_time=2,
+ subcaption="Hello",
+ subcaption_duration=1.25,
+ subcaption_offset=0.5,
+ )
+
+ assert scene.manager is None
+ renderer_play.assert_not_called()
+ queued_call = scene.queue.get_nowait()
+ assert isinstance(queued_call, SceneInteractRerun)
+ assert queued_call.sender == "play"
+ assert queued_call.kwargs == {
+ "run_time": 2,
+ "subcaption": "Hello",
+ "subcaption_duration": 1.25,
+ "subcaption_offset": 0.5,
+ }
+
+
+def test_manager_views_follow_the_scene_renderer(dry_run):
+ scene = Scene()
+ manager = Manager(scene)
+ replacement_renderer = Mock()
+ replacement_renderer.camera = Mock()
+ replacement_renderer.file_writer = Mock()
+ replacement_renderer.time = 1.5
+ replacement_renderer.num_plays = 2
+ replacement_renderer.skip_animations = False
+
+ scene.renderer = replacement_renderer
+
+ assert manager.renderer is replacement_renderer
+ assert manager.camera is replacement_renderer.camera
+ assert manager.file_writer is replacement_renderer.file_writer
+ assert manager.time == 1.5
+ assert manager.num_plays == 2
+ assert manager.skip_animations is False
+
+ manager.time = 2.5
+ manager.num_plays = 3
+ manager.skip_animations = True
+
+ assert replacement_renderer.time == 2.5
+ assert replacement_renderer.num_plays == 3
+ assert replacement_renderer.skip_animations is True
+
+
+def test_scene_next_section_delegates_to_manager(dry_run):
+ scene = Scene()
+ file_writer = Mock()
+ scene.renderer.file_writer = file_writer
+
+ section_type = "presentation.skip"
+
+ scene.next_section("intro", section_type, skip_animations=True)
+
+ assert isinstance(scene.manager, Manager)
+ file_writer.next_section.assert_called_once_with("intro", section_type, True)
+
+
+def test_scene_add_subcaption_delegates_to_manager(dry_run):
+ scene = Scene()
+ file_writer = Mock()
+ file_writer.subcaptions = []
+ scene.renderer.file_writer = file_writer
+ scene.renderer.time = 2.5
+
+ scene.add_subcaption("Hello", duration=1.5, offset=0.25)
+
+ assert isinstance(scene.manager, Manager)
+ assert file_writer.subcaptions == [
+ srt.Subtitle(
+ index=0,
+ content="Hello",
+ start=datetime.timedelta(seconds=2.75),
+ end=datetime.timedelta(seconds=4.25),
+ )
+ ]
+
+
+def test_scene_add_sound_delegates_to_manager_and_honors_skip_state(dry_run):
+ scene = Scene()
+ file_writer = Mock()
+ scene.renderer.file_writer = file_writer
+ scene.renderer.time = 2.5
+
+ scene.add_sound("bell.wav", time_offset=0.25, gain=-3, marker="test")
+
+ assert isinstance(scene.manager, Manager)
+ file_writer.add_sound.assert_called_once_with("bell.wav", 2.75, -3, marker="test")
+
+ file_writer.add_sound.reset_mock()
+ scene.renderer.skip_animations = True
+
+ scene.add_sound("skipped.wav")
+
+ file_writer.add_sound.assert_not_called()