A community-maintained Python framework for creating mathematical animations.
Fix `ThreeDScene.set_camera_orientation` with the OpenGL renderer (#5040)
Smaila6d029efc168
diff --git a/manim/renderer/opengl_renderer.py b/manim/renderer/opengl_renderer.pyindex cbaee2bc9..21f90f9df 100644--- a/manim/renderer/opengl_renderer.py+++ b/manim/renderer/opengl_renderer.py@@ -4,6 +4,7 @@ import contextlibimport itertools as itimport timeimport typing+import warningsfrom functools import cached_propertyfrom typing import TYPE_CHECKING, Any, Self@@ -20,6 +21,7 @@ from manim.mobject.opengl.opengl_mobject import ()from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobjectfrom manim.typing import MatrixMN, Point3D+from manim.utils.bezier import interpolatefrom manim.utils.caching import handle_caching_playfrom manim.utils.color import color_to_rgbafrom manim.utils.exceptions import EndSceneEarlyException@@ -410,6 +412,51 @@ class OpenGLCamera(OpenGLMobject):self.refresh_rotation_matrix()return self+ def set_zoom(self, zoom: float) -> Self:+ """+ Set the zoom factor of the camera.++ Parameters+ ----------+ zoom : float+ The new zoom factor. Values greater than ``1`` zoom in.++ Returns+ -------+ Self+ The camera instance. Returned for chaining.+ """+ return self.scale(config["frame_height"] / (zoom * self.get_height()))++ def set_focal_distance(self, focal_distance: float) -> Self:+ """+ Not supported by :class:`OpenGLCamera`, only emits a warning.++ Parameters+ ----------+ focal_distance : float+ Ignored.++ Returns+ -------+ Self+ The unchanged camera instance. Returned for chaining.+ """+ warnings.warn(+ "focal distance of OpenGLCamera can not be adjusted.",+ stacklevel=2,+ )+ return self++ @property+ def frame_center(self) -> Point3D:+ """The center of the camera frame."""+ return self.get_center()++ @frame_center.setter+ def frame_center(self, point: Point3DLike) -> None:+ self.move_to(point)+def get_shape(self) -> tuple[float, float]:"""Retrieve the width and height of the camera frame."""return (self.get_width(), self.get_height())@@ -451,6 +498,11 @@ class OpenGLCamera(OpenGLMobject):path_func: PathFuncType = straight_path(),) -> Self:super().interpolate(mobject1, mobject2, alpha, path_func)+ if isinstance(mobject1, OpenGLCamera) and isinstance(mobject2, OpenGLCamera):+ # Keep angles unwrapped so explicitly requested full turns are animated.+ self.euler_angles[:] = interpolate(+ mobject1.euler_angles, mobject2.euler_angles, alpha+ )self.refresh_rotation_matrix()return selfdiff --git a/manim/scene/three_d_scene.py b/manim/scene/three_d_scene.pyindex 7d2337437..70f5a15cd 100644--- a/manim/scene/three_d_scene.py+++ b/manim/scene/three_d_scene.py@@ -97,7 +97,7 @@ class ThreeDScene(Scene):if zoom is not None:self.renderer.camera.set_zoom(zoom)if frame_center is not None:- self.renderer.camera._frame_center.move_to(frame_center)+ self.renderer.camera.frame_center = frame_centerdef begin_ambient_camera_rotation(self, rate: float = 0.02, about: str = "theta"):"""diff --git a/tests/opengl/test_opengl_camera.py b/tests/opengl/test_opengl_camera.pynew file mode 100644index 000000000..8d9de3ffc--- /dev/null+++ b/tests/opengl/test_opengl_camera.py@@ -0,0 +1,83 @@+from __future__ import annotations++import numpy as np++from manim import DEGREES+from manim.renderer.opengl_renderer import OpenGLCamera+++def test_camera_interpolate_angles(using_opengl_renderer):+ # Literal -340-degree theta change and two positive gamma revolutions.+ start_angles = np.array([350, 40, -10]) * DEGREES+ target_angles = np.array([10, 65, 710]) * DEGREES+ start = OpenGLCamera().set_euler_angles(*start_angles)+ target = start.copy().set_euler_angles(*target_angles)+ camera = start.copy()+ reference = start.copy()+ start_matrix = start.inverse_rotation_matrix.copy()+ target_matrix = target.inverse_rotation_matrix.copy()++ # Repeated and out-of-order samples must still use the fixed endpoints.+ for alpha in (0, 0.25, 0.75, 0.5, 0.5, 1):+ expected = (1 - alpha) * start_angles + alpha * target_angles+ assert camera.interpolate(start, target, alpha) is camera+ np.testing.assert_allclose(camera.euler_angles, expected, atol=1e-12)+ reference.set_euler_angles(*expected)+ np.testing.assert_allclose(+ camera.inverse_rotation_matrix,+ reference.inverse_rotation_matrix,+ atol=1e-12,+ )+ np.testing.assert_array_equal(start.euler_angles, start_angles)+ np.testing.assert_array_equal(target.euler_angles, target_angles)+ np.testing.assert_array_equal(start.inverse_rotation_matrix, start_matrix)+ np.testing.assert_array_equal(target.inverse_rotation_matrix, target_matrix)+++def test_camera_interpolate_keeps_point_path_separate(using_opengl_renderer):+ start = OpenGLCamera().set_euler_angles(0.2, 0.4, -0.1)+ target = start.copy().set_euler_angles(0.7, 0.9, 0.3).move_to([1, 2, 0.5])+ camera = start.copy()++ def curved_path(start_points, target_points, alpha):+ return (+ (1 - alpha) * start_points+ + alpha * target_points+ + np.array([0, 0, np.sin(np.pi * alpha)])+ )++ camera.interpolate(start, target, 0.5, path_func=curved_path)+ np.testing.assert_allclose(+ camera.points, (start.points + target.points) / 2 + [0, 0, 1]+ )+ np.testing.assert_allclose(+ camera.euler_angles, (start.euler_angles + target.euler_angles) / 2+ )+++def test_camera_animate_interpolates_before_finish(using_opengl_renderer):+ start_angles = np.array([20, 40, -10]) * DEGREES+ target_angles = start_angles.copy()+ target_angles[0] -= 360 * DEGREES+ camera = OpenGLCamera().set_euler_angles(*start_angles)+ reference = camera.copy()+ animation = (+ camera.animate(rate_func=lambda t: t * t).set_theta(target_angles[0]).build()+ )+ animation.begin()++ for alpha in (0, 0.25, 0.5, 0.75, 1):+ progress = alpha * alpha+ expected = (1 - progress) * start_angles + progress * target_angles+ animation.interpolate(alpha)+ np.testing.assert_allclose(camera.euler_angles, expected, atol=1e-12)+ reference.set_euler_angles(*expected)+ np.testing.assert_allclose(+ camera.inverse_rotation_matrix,+ reference.inverse_rotation_matrix,+ atol=1e-12,+ )++ # The alpha=1 assertion above must pass before finish replays the setter.+ animation.finish()+ np.testing.assert_allclose(camera.euler_angles, target_angles)diff --git a/tests/opengl/test_threed_scene_opengl.py b/tests/opengl/test_threed_scene_opengl.pynew file mode 100644index 000000000..78f61ce82--- /dev/null+++ b/tests/opengl/test_threed_scene_opengl.py@@ -0,0 +1,111 @@+from __future__ import annotations++from unittest.mock import Mock++import numpy as np+import pytest++from manim import DEGREES, ThreeDScene, Transform, config, linear+++def test_set_camera_orientation(using_opengl_renderer):+ scene = ThreeDScene()+ scene.set_camera_orientation(+ phi=70 * DEGREES, theta=-35 * DEGREES, zoom=0.72, frame_center=[1, 2, 0]+ )+ theta, phi, _ = scene.camera.euler_angles+ assert phi == pytest.approx(70 * DEGREES)+ assert theta == pytest.approx(-35 * DEGREES)+ assert scene.camera.get_height() == pytest.approx(config.frame_height / 0.72)+ assert scene.camera.frame_center == pytest.approx([1, 2, 0])+++def test_set_camera_orientation_zoom_is_absolute(using_opengl_renderer):+ scene = ThreeDScene()+ scene.set_camera_orientation(zoom=2)+ scene.set_camera_orientation(zoom=2)+ assert scene.camera.get_height() == pytest.approx(config.frame_height / 2)+++def test_set_camera_orientation_focal_distance_warns(using_opengl_renderer):+ with pytest.warns(UserWarning, match="focal distance"):+ ThreeDScene().set_camera_orientation(focal_distance=5)+++def _capture_camera_animation(scene, monkeypatch, **kwargs):+ # Exercise move_camera's real target construction without a render loop.+ play = Mock()+ monkeypatch.setattr(scene, "play", play)+ scene.move_camera(**kwargs, rate_func=linear)+ play.assert_called_once()+ (animation,), play_kwargs = play.call_args+ assert isinstance(animation, Transform)+ assert animation.mobject is scene.camera+ animation.rate_func = play_kwargs["rate_func"]+ return animation+++def test_move_camera_interpolates_and_preserves_omitted_settings(+ using_opengl_renderer, monkeypatch+):+ scene = ThreeDScene()+ start_angles = np.array([20, 40, -10]) * DEGREES+ target_angles = np.array([-35, 65, 15]) * DEGREES+ start_center = np.array([-1, 0, 0.3])+ target_center = np.array([1, 0.5, 0.2])+ scene.set_camera_orientation(+ theta=start_angles[0],+ phi=start_angles[1],+ gamma=start_angles[2],+ zoom=0.72,+ frame_center=start_center,+ )+ start_height = scene.camera.get_height()+ target_zoom = 1.5+ target_height = config.frame_height / target_zoom+ aspect_ratio = scene.camera.get_width() / start_height+ animation = _capture_camera_animation(+ scene,+ monkeypatch,+ theta=target_angles[0],+ phi=target_angles[1],+ gamma=target_angles[2],+ zoom=target_zoom,+ frame_center=target_center,+ )+ animation.begin()++ for alpha in (0, 0.25, 0.5, 0.75, 1):+ animation.interpolate(alpha)+ expected_angles = (1 - alpha) * start_angles + alpha * target_angles+ expected_center = (1 - alpha) * start_center + alpha * target_center+ # Preserve OpenGL's frame-height interpolation, not linear zoom.+ expected_height = (1 - alpha) * start_height + alpha * target_height+ np.testing.assert_allclose(+ scene.camera.euler_angles, expected_angles, atol=1e-12+ )+ np.testing.assert_allclose(+ scene.camera.get_center(), expected_center, atol=1e-12+ )+ assert scene.camera.get_height() == pytest.approx(expected_height)+ assert scene.camera.get_width() == pytest.approx(aspect_ratio * expected_height)++ animation.finish()+ np.testing.assert_allclose(scene.camera.euler_angles, target_angles)+ np.testing.assert_allclose(scene.camera.get_center(), target_center)+ assert scene.camera.get_height() == pytest.approx(target_height)++ # Reuse the scene to check a partial update without another OpenGL context.+ partial_angles = target_angles.copy()+ partial_angles[1] += 15 * DEGREES+ animation = _capture_camera_animation(scene, monkeypatch, phi=partial_angles[1])+ animation.begin()+ for alpha in (0.5, 1):+ animation.interpolate(alpha)+ expected_angles = (1 - alpha) * target_angles + alpha * partial_angles+ np.testing.assert_allclose(scene.camera.euler_angles, expected_angles)+ np.testing.assert_allclose(scene.camera.get_center(), target_center)+ assert scene.camera.get_height() == pytest.approx(target_height)+ assert scene.camera.get_width() == pytest.approx(aspect_ratio * target_height)+ animation.finish()+ np.testing.assert_allclose(scene.camera.euler_angles, partial_angles)