datacut 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. datacut/__init__.py +121 -0
  2. datacut/__main__.py +122 -0
  3. datacut/animation/__init__.py +0 -0
  4. datacut/animation/animation.py +336 -0
  5. datacut/animation/composition.py +258 -0
  6. datacut/animation/creation.py +315 -0
  7. datacut/animation/fading.py +328 -0
  8. datacut/animation/growing.py +90 -0
  9. datacut/animation/indication.py +608 -0
  10. datacut/animation/movement.py +165 -0
  11. datacut/animation/numbers.py +92 -0
  12. datacut/animation/physics.py +453 -0
  13. datacut/animation/rotation.py +95 -0
  14. datacut/animation/specialized.py +956 -0
  15. datacut/animation/transform.py +505 -0
  16. datacut/animation/transform_matching_parts.py +343 -0
  17. datacut/animation/update.py +95 -0
  18. datacut/camera/__init__.py +0 -0
  19. datacut/camera/camera.py +795 -0
  20. datacut/camera/camera_frame.py +320 -0
  21. datacut/camera/cinematography.py +1166 -0
  22. datacut/config.py +479 -0
  23. datacut/constants.py +160 -0
  24. datacut/css/__init__.py +189 -0
  25. datacut/css/easing.py +328 -0
  26. datacut/css/engine.py +1727 -0
  27. datacut/css/gradients.py +678 -0
  28. datacut/css/motion.py +1615 -0
  29. datacut/css/parser.py +741 -0
  30. datacut/css/presets.py +143 -0
  31. datacut/css/shader_fill.py +703 -0
  32. datacut/css/values.py +650 -0
  33. datacut/default_config.yml +224 -0
  34. datacut/event_handler/__init__.py +6 -0
  35. datacut/event_handler/event_dispatcher.py +161 -0
  36. datacut/event_handler/event_listner.py +31 -0
  37. datacut/event_handler/event_type.py +11 -0
  38. datacut/event_handler/picking.py +111 -0
  39. datacut/event_keys.py +53 -0
  40. datacut/extract_scene.py +200 -0
  41. datacut/layout/__init__.py +39 -0
  42. datacut/layout/components.py +425 -0
  43. datacut/layout/containers.py +1520 -0
  44. datacut/logger.py +13 -0
  45. datacut/mobject/__init__.py +0 -0
  46. datacut/mobject/boolean_ops.py +168 -0
  47. datacut/mobject/changing.py +209 -0
  48. datacut/mobject/coordinate_systems.py +1056 -0
  49. datacut/mobject/fractals.py +348 -0
  50. datacut/mobject/frame.py +80 -0
  51. datacut/mobject/functions.py +147 -0
  52. datacut/mobject/geometry.py +1834 -0
  53. datacut/mobject/gltf.py +243 -0
  54. datacut/mobject/interactive.py +906 -0
  55. datacut/mobject/lights.py +366 -0
  56. datacut/mobject/materials.py +207 -0
  57. datacut/mobject/matrix.py +570 -0
  58. datacut/mobject/mesh3d.py +2288 -0
  59. datacut/mobject/mobject.py +2885 -0
  60. datacut/mobject/mobject_update_utils.py +123 -0
  61. datacut/mobject/model.py +543 -0
  62. datacut/mobject/number_line.py +517 -0
  63. datacut/mobject/numbers.py +441 -0
  64. datacut/mobject/probability.py +536 -0
  65. datacut/mobject/shape_matchers.py +161 -0
  66. datacut/mobject/subtitles.py +260 -0
  67. datacut/mobject/svg/__init__.py +0 -0
  68. datacut/mobject/svg/brace.py +356 -0
  69. datacut/mobject/svg/drawings.py +1041 -0
  70. datacut/mobject/svg/old_tex_mobject.py +335 -0
  71. datacut/mobject/svg/path_cache.py +155 -0
  72. datacut/mobject/svg/special_tex.py +216 -0
  73. datacut/mobject/svg/string_mobject.py +622 -0
  74. datacut/mobject/svg/svg_mobject.py +657 -0
  75. datacut/mobject/svg/svg_parse.py +437 -0
  76. datacut/mobject/svg/tex_mobject.py +499 -0
  77. datacut/mobject/svg/text_mobject.py +702 -0
  78. datacut/mobject/svg/typst_mobject.py +864 -0
  79. datacut/mobject/three_dimensions.py +686 -0
  80. datacut/mobject/types/__init__.py +0 -0
  81. datacut/mobject/types/dot_cloud.py +220 -0
  82. datacut/mobject/types/image_mobject.py +130 -0
  83. datacut/mobject/types/point_cloud_mobject.py +138 -0
  84. datacut/mobject/types/shader_mobject.py +268 -0
  85. datacut/mobject/types/surface.py +848 -0
  86. datacut/mobject/types/vectorized_mobject.py +1749 -0
  87. datacut/mobject/types/video_mobject.py +3902 -0
  88. datacut/mobject/value_tracker.py +110 -0
  89. datacut/mobject/vector_field.py +585 -0
  90. datacut/module_loader.py +176 -0
  91. datacut/reactive/__init__.py +25 -0
  92. datacut/reactive/signals.py +610 -0
  93. datacut/renderer/__init__.py +4 -0
  94. datacut/renderer/drawing.py +1066 -0
  95. datacut/renderer/gpu.py +800 -0
  96. datacut/renderer/material.py +88 -0
  97. datacut/renderer/pipeline.py +179 -0
  98. datacut/renderer/post_process.py +577 -0
  99. datacut/renderer/renderer.py +1285 -0
  100. datacut/renderer/shader_source.py +146 -0
  101. datacut/renderer/shared_buffer.py +185 -0
  102. datacut/renderer/texture.py +217 -0
  103. datacut/renderer/uniform_block.py +118 -0
  104. datacut/scene/__init__.py +0 -0
  105. datacut/scene/incremental.py +233 -0
  106. datacut/scene/interactive_scene.py +758 -0
  107. datacut/scene/performance.py +226 -0
  108. datacut/scene/presentation_scene.py +783 -0
  109. datacut/scene/recording.py +541 -0
  110. datacut/scene/safe_zones.py +323 -0
  111. datacut/scene/scene.py +2849 -0
  112. datacut/scene/scene_embed.py +277 -0
  113. datacut/scene/scene_file_writer.py +1014 -0
  114. datacut/scene/scene_task.py +183 -0
  115. datacut/scene/sfx.py +164 -0
  116. datacut/scene/sound.py +702 -0
  117. datacut/scene/sound_clip.py +580 -0
  118. datacut/scene/timeline.py +1689 -0
  119. datacut/scene/transcript.py +503 -0
  120. datacut/shaders/fill.wgsl +107 -0
  121. datacut/shaders/fill_depth.wgsl +198 -0
  122. datacut/shaders/image.wgsl +25 -0
  123. datacut/shaders/inserts/NOTE.md +16 -0
  124. datacut/shaders/inserts/clip_test.wgsl +14 -0
  125. datacut/shaders/inserts/complex_functions.wgsl +20 -0
  126. datacut/shaders/inserts/fill_color.wgsl +10 -0
  127. datacut/shaders/inserts/finalize_color.wgsl +44 -0
  128. datacut/shaders/inserts/frame_uniforms.wgsl +37 -0
  129. datacut/shaders/inserts/frame_units.wgsl +18 -0
  130. datacut/shaders/inserts/image_quad.wgsl +28 -0
  131. datacut/shaders/inserts/mobject_uniforms.wgsl +11 -0
  132. datacut/shaders/inserts/project_point.wgsl +44 -0
  133. datacut/shaders/inserts/quad_corners.wgsl +12 -0
  134. datacut/shaders/inserts/read_data.wgsl +33 -0
  135. datacut/shaders/inserts/surface_mesh.wgsl +106 -0
  136. datacut/shaders/mandelbrot_fractal.wgsl +100 -0
  137. datacut/shaders/mesh.wgsl +474 -0
  138. datacut/shaders/newton_fractal.wgsl +200 -0
  139. datacut/shaders/present.wgsl +62 -0
  140. datacut/shaders/stroke.wgsl +1141 -0
  141. datacut/shaders/stroke_depth.wgsl +1136 -0
  142. datacut/shaders/surface.wgsl +40 -0
  143. datacut/shaders/textured_surface.wgsl +59 -0
  144. datacut/shaders/true_dot.wgsl +78 -0
  145. datacut/shaders/video.wgsl +42 -0
  146. datacut/tex_templates.yml +736 -0
  147. datacut/transcribe.py +32 -0
  148. datacut/typing.py +412 -0
  149. datacut/utils/__init__.py +0 -0
  150. datacut/utils/bezier.py +467 -0
  151. datacut/utils/browser_audio.py +423 -0
  152. datacut/utils/browser_code_transform.py +1293 -0
  153. datacut/utils/browser_completions.py +2255 -0
  154. datacut/utils/browser_fonts.py +143 -0
  155. datacut/utils/browser_pathops.py +47 -0
  156. datacut/utils/browser_scheduler.py +18 -0
  157. datacut/utils/browser_typst.py +82 -0
  158. datacut/utils/cache.py +34 -0
  159. datacut/utils/cinematic_vfx.py +779 -0
  160. datacut/utils/color.py +203 -0
  161. datacut/utils/debug.py +46 -0
  162. datacut/utils/dict_ops.py +22 -0
  163. datacut/utils/directories.py +55 -0
  164. datacut/utils/editor_signatures.py +1806 -0
  165. datacut/utils/editor_thumbnails.py +769 -0
  166. datacut/utils/family_ops.py +48 -0
  167. datacut/utils/file_ops.py +65 -0
  168. datacut/utils/images.py +52 -0
  169. datacut/utils/iterables.py +216 -0
  170. datacut/utils/native.py +280 -0
  171. datacut/utils/paths.py +83 -0
  172. datacut/utils/rate_functions.py +154 -0
  173. datacut/utils/render_geometry.py +186 -0
  174. datacut/utils/simple_functions.py +99 -0
  175. datacut/utils/sounds.py +43 -0
  176. datacut/utils/space_ops.py +460 -0
  177. datacut/utils/structured_array.py +256 -0
  178. datacut/utils/svg_export.py +102 -0
  179. datacut/utils/tex.py +139 -0
  180. datacut/utils/tex_file_writing.py +164 -0
  181. datacut/utils/tex_to_symbol_count.py +186 -0
  182. datacut/utils/typst_file_writing.py +205 -0
  183. datacut/utils/vfx_presets.py +4543 -0
  184. datacut/utils/visual_css.py +737 -0
  185. datacut/utils/visual_editor.py +4292 -0
  186. datacut/utils/window_audio.py +760 -0
  187. datacut/window.py +910 -0
  188. datacut-0.1.0.dist-info/METADATA +226 -0
  189. datacut-0.1.0.dist-info/RECORD +193 -0
  190. datacut-0.1.0.dist-info/WHEEL +5 -0
  191. datacut-0.1.0.dist-info/entry_points.txt +2 -0
  192. datacut-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  193. datacut-0.1.0.dist-info/top_level.txt +1 -0
datacut/scene/scene.py ADDED
@@ -0,0 +1,2849 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import Counter, OrderedDict
4
+ import copy
5
+ import os
6
+ import platform
7
+ import random
8
+ import time
9
+ import subprocess
10
+ import sys
11
+ import inspect
12
+ from functools import wraps
13
+ from contextlib import contextmanager
14
+ from contextlib import ExitStack
15
+
16
+ import numpy as np
17
+ from tqdm.auto import tqdm as ProgressDisplay
18
+
19
+ from datacut.animation.animation import prepare_animation
20
+ from datacut.animation.animation import prepare_animation_async
21
+ from datacut.camera.camera import Camera
22
+ from datacut.camera.camera_frame import CameraFrame
23
+ from datacut.config import manim_config
24
+ from datacut.event_handler import EVENT_DISPATCHER
25
+ from datacut.event_handler.event_type import EventType
26
+ from datacut.event_handler.picking import mouse_event_data
27
+ from datacut.event_keys import Keys
28
+ from datacut.event_keys import Mods
29
+ from datacut.logger import log
30
+ from datacut.mobject.mobject import _AnimationBuilder
31
+ from datacut.mobject.mobject import Group
32
+ from datacut.mobject.mobject import Mobject
33
+ from datacut.mobject.mobject import Point
34
+ from datacut.mobject.types.vectorized_mobject import VGroup
35
+ from datacut.mobject.types.vectorized_mobject import VMobject
36
+ if sys.platform != "emscripten":
37
+ from datacut.scene.scene_embed import InteractiveSceneEmbed
38
+ from datacut.scene.scene_embed import CheckpointManager
39
+ from datacut.scene.scene_file_writer import SceneFileWriter
40
+ from datacut.scene.scene_task import BackgroundAnimation, ScheduledCall, SceneTask, run_tasks
41
+ from datacut.scene.timeline import PlayRecord, SceneTimeline, caller_source
42
+ from datacut.scene.recording import InteractionRecorder
43
+ from datacut.scene.performance import PerformanceMonitor
44
+ from datacut.scene.safe_zones import SafeZoneOverlay, apply_aspect_preset
45
+ from datacut.scene.sfx import sfx
46
+ from datacut.scene.sound import Sound
47
+ from datacut.scene.sound_clip import SoundClip
48
+ from datacut.utils.dict_ops import merge_dicts_recursively
49
+ from datacut.utils.family_ops import extract_mobject_family_members
50
+ from datacut.utils.family_ops import recursive_mobject_remove
51
+ from datacut.utils.sounds import play_sound
52
+ from datacut.utils.sounds import get_full_sound_file_path
53
+
54
+ if sys.platform == "emscripten":
55
+ from datacut.utils.browser_audio import browser_audio
56
+ from datacut.utils.color import color_to_rgba
57
+ from datacut.window import Window
58
+
59
+ from typing import TYPE_CHECKING
60
+
61
+ if TYPE_CHECKING:
62
+ from typing import Callable, Iterable, TypeVar, Optional
63
+ from datacut.typing import Vect3
64
+
65
+ T = TypeVar('T')
66
+
67
+ from PIL.Image import Image
68
+
69
+ from datacut.animation.animation import Animation
70
+
71
+
72
+ class Scene(object):
73
+ random_seed: int = 0
74
+ pan_sensitivity: float = 0.5
75
+ scroll_sensitivity: float = 20
76
+ drag_to_pan: bool = True
77
+ max_num_saved_states: int = 50
78
+ # Keep the scene's past, for a window to go back to any moment of, see
79
+ # datacut.scene.timeline, and how many snapshots of it at most
80
+ keep_timeline: bool = True
81
+ # In a window, play back what was recorded in it, see datacut.scene.recording. A movie
82
+ # written always plays it back. Shift + M changes it as the scene runs
83
+ play_recordings_in_window: bool = True
84
+ max_timeline_snapshots: int | None = 4000
85
+ default_camera_config: dict = dict()
86
+ default_file_writer_config: dict = dict()
87
+ aspect_ratio: str | None = None
88
+ safe_zones_preset: str | None = None
89
+ samples = 0
90
+ # Euler angles, in degrees
91
+ default_frame_orientation = (0, 0)
92
+
93
+ def __init__(
94
+ self,
95
+ window: Optional[Window] = None,
96
+ camera_config: dict = dict(),
97
+ file_writer_config: dict = dict(),
98
+ skip_animations: bool = False,
99
+ always_update_mobjects: bool = False,
100
+ start_at_animation_number: int | None = None,
101
+ end_at_animation_number: int | None = None,
102
+ show_animation_progress: bool = False,
103
+ leave_progress_bars: bool = False,
104
+ preview_while_skipping: bool = True,
105
+ presenter_mode: bool = False,
106
+ default_wait_time: float = 1.0,
107
+ invert_zoom_scroll: bool = False,
108
+ hot_reload: bool = True,
109
+ play_recordings_in_window: bool | None = None,
110
+ resume_time: float | None = None,
111
+ resume_view: float | None = None,
112
+ safe_zones_preset: str | None = None,
113
+ ):
114
+ self.skip_animations = skip_animations
115
+ self.always_update_mobjects = always_update_mobjects
116
+ self.start_at_animation_number = start_at_animation_number
117
+ self.end_at_animation_number = end_at_animation_number
118
+ self.show_animation_progress = show_animation_progress
119
+ self.leave_progress_bars = leave_progress_bars
120
+ self.preview_while_skipping = preview_while_skipping
121
+ self.presenter_mode = presenter_mode
122
+ self.default_wait_time = default_wait_time
123
+ self.invert_zoom_scroll = invert_zoom_scroll
124
+ # Made again from its file when that is saved, see check_hot_reload, carrying on from
125
+ # where the last one had got to: skipped through up to resume_time, then, if the past
126
+ # was being looked at, at resume_view in it
127
+ self.resume_time = resume_time
128
+ self.resume_view = resume_view
129
+ if play_recordings_in_window is not None:
130
+ self.play_recordings_in_window = play_recordings_in_window
131
+
132
+ self.camera_config = merge_dicts_recursively(
133
+ manim_config.camera, # Global default
134
+ self.default_camera_config, # Updated configuration that subclasses may specify
135
+ camera_config, # Updated configuration from instantiation
136
+ )
137
+ if self.aspect_ratio and "resolution" not in camera_config:
138
+ self.camera_config["resolution"] = apply_aspect_preset(
139
+ self.aspect_ratio,
140
+ base_resolution=self.camera_config.get("resolution"),
141
+ )
142
+ self.file_writer_config = merge_dicts_recursively(
143
+ manim_config.file_writer,
144
+ self.default_file_writer_config,
145
+ file_writer_config,
146
+ )
147
+
148
+ self.window = window
149
+ if self.window:
150
+ self.window.init_for_scene(self)
151
+ # Make sure the camera and the window sync
152
+ # self.camera_config["fps"] = 30
153
+
154
+ # Core state of the scene
155
+ self.camera: Camera = Camera(
156
+ window=self.window,
157
+ samples=self.samples,
158
+ **self.camera_config
159
+ )
160
+ self.frame: CameraFrame = self.camera.frame
161
+ self.frame.reorient(*self.default_frame_orientation)
162
+ self.frame.make_orientation_default()
163
+
164
+ self.file_writer = SceneFileWriter(self, **self.file_writer_config)
165
+ self.mobjects: list[Mobject] = [self.camera.frame]
166
+ self.id_to_mobject_map: dict[int, Mobject] = dict()
167
+ self.num_plays: int = 0
168
+ self.time: float = 0
169
+ self.max_time: float = 0
170
+ self.skip_time: float = 0
171
+ self.original_skipping_status: bool = self.skip_animations
172
+ self.undo_stack = []
173
+ self.redo_stack = []
174
+ self.timeline = SceneTimeline(self, self.max_timeline_snapshots)
175
+ # What is done in the window, recorded and played back, see datacut.scene.recording
176
+ self.recorder = InteractionRecorder(self)
177
+ # Where each frame's time goes, see datacut.scene.performance
178
+ self.performance = PerformanceMonitor(self)
179
+ self.camera.performance = self.performance
180
+ # Preview-only safe-zone guides (Shorts / Reels / TikTok / Broadcast)
181
+ resolved_safe_zones = (
182
+ safe_zones_preset
183
+ if safe_zones_preset is not None
184
+ else self.safe_zones_preset
185
+ )
186
+ self.safe_zones = SafeZoneOverlay(self, preset=resolved_safe_zones)
187
+ # (time, name) of every play and wait, window or none, for the movie's chapters,
188
+ # see SceneFileWriter.write_chapters
189
+ self.chapters: list[tuple[float, str]] = []
190
+ # Played without being drawn, its frames being taken from before, see
191
+ # datacut.scene.incremental
192
+ self.dry_run: bool = False
193
+
194
+ if self.start_at_animation_number is not None:
195
+ self.skip_animations = True
196
+ if self.resume_time is not None:
197
+ self.skip_animations = True
198
+
199
+ self._reload_requested: bool = False
200
+ self._reload_resume: dict = dict()
201
+ self._embed = None
202
+ self._watched: list | None = None
203
+ if hot_reload and self.window is not None and sys.platform != "emscripten":
204
+ path = manim_config.run.file_name
205
+ if path and os.path.exists(path):
206
+ # The file, when it was last changed, and when that was last looked at
207
+ self._watched = [path, os.path.getmtime(path), 0.0]
208
+ if self.file_writer.has_progress_display():
209
+ self.show_animation_progress = False
210
+
211
+ # Items associated with interaction
212
+ self.mouse_point = Point()
213
+ self.mouse_drag_point = Point()
214
+ self.hold_on_wait = self.presenter_mode
215
+ self.quit_interaction = False
216
+ self._active_sound_processes: list[subprocess.Popen] = []
217
+ self._interactive_sound_events: list[tuple[float, str, float]] = []
218
+ self._browser_sound_clips: list[SoundClip] = []
219
+ self._window_audio_mixer = None
220
+ # Background animations and scheduled calls, see datacut.scene.scene_task
221
+ self.tasks: list[SceneTask] = []
222
+ self._in_task: bool = False
223
+
224
+ # Much nicer to work with deterministic scenes
225
+ if self.random_seed is not None:
226
+ random.seed(self.random_seed)
227
+ np.random.seed(self.random_seed)
228
+
229
+ # Playback controls
230
+ self.should_end_playing: bool = False
231
+ self.paused: bool = False
232
+ self._is_torn_down: bool = False
233
+ self._stop_requested: bool = False
234
+
235
+ def __str__(self) -> str:
236
+ return self.__class__.__name__
237
+
238
+ def get_window(self) -> Window | None:
239
+ return self.window
240
+
241
+ def run(self) -> None:
242
+ """Run the scene on native platforms; browser scenes use build_async()."""
243
+ if sys.platform == "emscripten":
244
+ raise RuntimeError(
245
+ "Use await run_scene_from_class(...) for Pyodide scenes"
246
+ )
247
+ self.build()
248
+ self.playback()
249
+
250
+ def _begin_build(self) -> None:
251
+ self.virtual_animation_start_time = 0
252
+ self.real_animation_start_time = time.time()
253
+ self.file_writer.begin()
254
+ self.setup()
255
+ self.recorder.install()
256
+
257
+ async def _begin_build_async(self) -> None:
258
+ self.virtual_animation_start_time = 0
259
+ self.real_animation_start_time = time.time()
260
+ self.file_writer.begin()
261
+ setup_res = self.setup()
262
+ if inspect.isawaitable(setup_res):
263
+ await setup_res
264
+ self.recorder.install()
265
+
266
+ def build(self):
267
+ if sys.platform == "emscripten":
268
+ raise RuntimeError("Use await build_async() in Pyodide")
269
+ self._begin_build()
270
+ try:
271
+ self.construct()
272
+ extra = self.recorder.extend_scene()
273
+ if extra > 0:
274
+ self.wait(extra, name="Recorded")
275
+ except EndScene:
276
+ pass
277
+ except KeyboardInterrupt:
278
+ print("", end="\r")
279
+ self.file_writer.ended_with_interrupt = True
280
+ if self._window_audio_mixer is not None:
281
+ self._window_audio_mixer.finalize_open_loops(self.time)
282
+ for clip in self._browser_sound_clips:
283
+ if clip.loops_until_end and clip.loop_until is None:
284
+ clip.loop_until = max(0.0, self.time - clip.scene_start)
285
+ return self
286
+
287
+ async def build_async(self):
288
+ """Construct a browser scene without blocking the event loop."""
289
+ if sys.platform != "emscripten":
290
+ return self.build()
291
+ await self._begin_build_async()
292
+ try:
293
+ result = self.construct()
294
+ if inspect.isawaitable(result):
295
+ await result
296
+ extra = self.recorder.extend_scene()
297
+ if extra > 0:
298
+ await self.wait_async(extra, name="Recorded")
299
+ except EndScene:
300
+ pass
301
+ except KeyboardInterrupt:
302
+ print("", end="\r")
303
+ self.file_writer.ended_with_interrupt = True
304
+ if self._window_audio_mixer is not None:
305
+ self._window_audio_mixer.finalize_open_loops(self.time)
306
+ for clip in self._browser_sound_clips:
307
+ if clip.loops_until_end and clip.loop_until is None:
308
+ clip.loop_until = max(0.0, self.time - clip.scene_start)
309
+ return self
310
+
311
+ async def run_live(self):
312
+ """Run a browser scene directly, keeping computation and rendering live."""
313
+ if sys.platform != "emscripten":
314
+ return self.run()
315
+
316
+ await self._begin_build_async()
317
+
318
+ try:
319
+ result = self.construct()
320
+ if inspect.isawaitable(result):
321
+ await result
322
+ extra = self.recorder.extend_scene()
323
+ if extra > 0:
324
+ await self.wait_async(extra, name="Recorded")
325
+ except EndScene:
326
+ pass
327
+ except KeyboardInterrupt:
328
+ print("", end="\r")
329
+ self.file_writer.ended_with_interrupt = True
330
+
331
+ for clip in self._browser_sound_clips:
332
+ if clip.loops_until_end and clip.loop_until is None:
333
+ clip.loop_until = max(0.0, self.time - clip.scene_start)
334
+ self.arrive_at_resume()
335
+ # Present the final live scene automatically. Explicit browser_present()
336
+ # calls are no longer required from user scenes.
337
+ await self.update_frame_async(force_draw=True)
338
+ await self._poll_window_events_async()
339
+ await self._browser_frame()
340
+ await self.browser_interaction_loop()
341
+
342
+ def playback(self) -> None:
343
+ if sys.platform == "emscripten":
344
+ raise RuntimeError("Use await run_scene_from_class(...) for Pyodide scenes")
345
+ try:
346
+ self.interact()
347
+ except ReloadScene:
348
+ # The window stays, for the scene made again from the file
349
+ raise
350
+ except BaseException:
351
+ self.tear_down()
352
+ raise
353
+ else:
354
+ self.tear_down()
355
+
356
+ def setup(self) -> None:
357
+ """
358
+ This is meant to be implemented by any scenes which
359
+ are commonly subclassed, and have some common setup
360
+ involved before the construct method is called.
361
+ """
362
+ if sys.platform == "emscripten":
363
+ return self.setup_async()
364
+ pass
365
+
366
+ async def setup_async(self) -> None:
367
+ pass
368
+
369
+ def construct(self) -> None:
370
+ # Where all the animation happens
371
+ # To be implemented in subclasses
372
+ pass
373
+
374
+ def _get_window_audio_mixer(self):
375
+ if self._window_audio_mixer is None:
376
+ from datacut.utils.window_audio import WindowAudioMixer
377
+ self._window_audio_mixer = WindowAudioMixer(self)
378
+ return self._window_audio_mixer
379
+
380
+ def stop_sound_processes(self) -> None:
381
+ if self._window_audio_mixer is not None:
382
+ self._window_audio_mixer.stop()
383
+ for process in self._active_sound_processes:
384
+ if isinstance(process, subprocess.Popen) and process.poll() is None:
385
+ process.terminate()
386
+ self._active_sound_processes.clear()
387
+
388
+ def replay_interactive_sounds(self, scene_time: float) -> None:
389
+ if self.window is None:
390
+ return
391
+ if sys.platform == "emscripten":
392
+ browser_audio.seek(scene_time, self._interactive_sound_events, self._browser_sound_clips)
393
+ return
394
+
395
+ if self._window_audio_mixer is not None and self._window_audio_mixer.has_clips():
396
+ self._window_audio_mixer.play_from(scene_time)
397
+ return
398
+
399
+ for event_time, sound_file, duration in self._interactive_sound_events:
400
+ elapsed = scene_time - event_time
401
+ if elapsed >= duration or elapsed < 0:
402
+ # Over, or still to come, which the scene's clock starts when it gets there
403
+ continue
404
+ process = play_sound(sound_file, max(0.0, elapsed))
405
+ self._active_sound_processes.append(process)
406
+
407
+ def tear_down(self) -> None:
408
+ self._is_torn_down = True
409
+ self._stop_requested = True
410
+ self.hold_on_wait = False
411
+ self.quit_interaction = True
412
+ self.should_end_playing = True
413
+
414
+ if self.recorder.recording:
415
+ self.recorder.stop()
416
+ self.stop_sound_processes()
417
+ if self._window_audio_mixer is not None:
418
+ self._window_audio_mixer.close()
419
+ self._window_audio_mixer = None
420
+ self.stop_skipping()
421
+ self.clear_event_listeners()
422
+
423
+ # Stop browser tasks owned by this scene
424
+ build_task = getattr(self, "_build_task", None)
425
+ if build_task is not None and not build_task.done():
426
+ build_task.cancel()
427
+
428
+ interaction_task = getattr(self, "_browser_interaction_task", None)
429
+ if interaction_task is not None and not interaction_task.done():
430
+ interaction_task.cancel()
431
+ if self.window is not None:
432
+ for task in tuple(getattr(self.window, "_browser_input_tasks", ())):
433
+ task.cancel()
434
+
435
+ self.file_writer.finish()
436
+ if self.window:
437
+ if getattr(self.window, "scene", None) is self:
438
+ self.window.scene = None
439
+ self.window.destroy()
440
+ self.window = None
441
+
442
+ def clear_event_listeners(self) -> None:
443
+ # EventDispatcher is global, so listeners otherwise survive after this
444
+ # scene is discarded and fire alongside listeners from the next run.
445
+ seen = set()
446
+ for mobject in self.mobjects:
447
+ for member in mobject.get_family():
448
+ if id(member) in seen:
449
+ continue
450
+ seen.add(id(member))
451
+ for listener in tuple(member.get_event_listners()):
452
+ EVENT_DISPATCHER.remove_listner(listener)
453
+ member.event_listners.clear()
454
+ if hasattr(EVENT_DISPATCHER, "clear"):
455
+ EVENT_DISPATCHER.clear()
456
+ else:
457
+ for et in tuple(getattr(EVENT_DISPATCHER, "event_listners", {}).keys()):
458
+ EVENT_DISPATCHER.event_listners[et].clear()
459
+ EVENT_DISPATCHER.draggable_object_listners.clear()
460
+ EVENT_DISPATCHER.pressed_keys.clear()
461
+
462
+ def release_for_reload(self) -> None:
463
+ """
464
+ Lets go of what would outlive this scene once another is made from the same file in
465
+ the same window, see check_hot_reload
466
+ """
467
+ if self.recorder.recording:
468
+ self.recorder.stop()
469
+ self.stop_sound_processes()
470
+ if self._window_audio_mixer is not None:
471
+ self._window_audio_mixer.close()
472
+ self._window_audio_mixer = None
473
+ self.clear_event_listeners()
474
+ self.tasks.clear()
475
+
476
+ # Hot reload
477
+
478
+ def check_hot_reload(self) -> None:
479
+ """
480
+ Whether the scene's file has been saved since it was read, in which case the scene is
481
+ made again from it, see datacut.__main__.run_scenes, carrying on from the moment it
482
+ had got to, and from the moment of its past being looked at, if one was. A file which
483
+ does not compile is left until it is saved again.
484
+
485
+ Raises ReloadScene, from wherever the scene's clock is being moved: a play, a wait,
486
+ a presenter's pause, the loop at the end. In the embed shell, the shell is ended first,
487
+ see InteractiveSceneEmbed.enable_gui.
488
+ """
489
+ if self._reload_requested:
490
+ if self._embed is None:
491
+ raise ReloadScene(self, **self._reload_resume)
492
+ return
493
+ watched = self._watched
494
+ if watched is None:
495
+ return
496
+ now = time.time()
497
+ if now - watched[2] < 0.25:
498
+ return
499
+ watched[2] = now
500
+ path = watched[0]
501
+ try:
502
+ mtime = os.path.getmtime(path)
503
+ except OSError:
504
+ return
505
+ if mtime == watched[1]:
506
+ return
507
+ watched[1] = mtime
508
+ try:
509
+ with open(path, encoding="utf-8") as file:
510
+ compile(file.read(), path, "exec")
511
+ except SyntaxError as error:
512
+ log.error(f"Not reloaded: {path}, line {error.lineno}: {error.msg}")
513
+ return
514
+ self.request_reload()
515
+
516
+ def request_reload(self) -> None:
517
+ timeline = self.timeline
518
+ self._reload_resume = dict(
519
+ resume_time=timeline.duration,
520
+ resume_view=timeline.time if timeline.browsing else None,
521
+ )
522
+ self._reload_requested = True
523
+ log.info("Reloading...")
524
+ if self._embed is None:
525
+ raise ReloadScene(self, **self._reload_resume)
526
+
527
+ def arrive_at_resume(self, view: bool = True) -> None:
528
+ """
529
+ The scene made again on its file being saved has got as far as the last one had, or
530
+ is not going any further: it goes on at its own pace, at the moment in the past being
531
+ looked at if one was
532
+ """
533
+ if self.resume_time is not None:
534
+ self.resume_time = None
535
+ if not self.original_skipping_status:
536
+ self.stop_skipping()
537
+ self.replay_interactive_sounds(self.time)
538
+ # The past is only gone to where the scene rests, the next play otherwise coming
539
+ # straight back to now
540
+ if view and self.resume_view is not None:
541
+ view, self.resume_view = self.resume_view, None
542
+ self.update_frame(force_draw=True)
543
+ if view < self.timeline.duration:
544
+ self.timeline.seek(view)
545
+
546
+ def interact(self) -> None:
547
+ """
548
+ If there is a window, enter a loop which updates the frame, each of those
549
+ pulling whatever events the window has to report
550
+ """
551
+ if self.window is None:
552
+ return
553
+ # In the browser, rendercanvas owns the event loop. Blocking here with a
554
+ # Python while-loop would prevent requestAnimationFrame and DOM events from running.
555
+ if sys.platform == "emscripten":
556
+ return
557
+ log.info(
558
+ "\nTips: Using the keys `d`, `f`, or `z` " +
559
+ "you can interact with the scene. " +
560
+ "Press `command + q` or `esc` to quit"
561
+ )
562
+ self.arrive_at_resume()
563
+ self.skip_animations = False
564
+ while not self.is_window_closing():
565
+ self.update_frame(1 / self.camera.fps)
566
+
567
+ def embed(
568
+ self,
569
+ close_scene_on_exit: bool = True,
570
+ show_animation_progress: bool = False,
571
+ ) -> None:
572
+ if not self.window:
573
+ # Embed is only relevant for interactive development with a Window
574
+ return
575
+ self.show_animation_progress = show_animation_progress
576
+ self.arrive_at_resume()
577
+ self.stop_skipping()
578
+ self.update_frame(force_draw=True)
579
+
580
+ self._embed = InteractiveSceneEmbed(self)
581
+ try:
582
+ self._embed.launch()
583
+ finally:
584
+ self._embed = None
585
+ if self._reload_requested:
586
+ raise ReloadScene(self, **self._reload_resume)
587
+
588
+ # End scene when exiting an embed
589
+ if close_scene_on_exit:
590
+ raise EndScene()
591
+
592
+ # Only these methods should touch the camera
593
+
594
+ def get_image(self) -> Image:
595
+ if self.window is None:
596
+ self.camera.capture(*self.mobjects)
597
+ return self.camera.get_image()
598
+ # A window has the camera drawing at its size, so the frame has to be drawn again
599
+ # at the resolution an image of it is meant to come out at
600
+ with self.camera.at_output_resolution():
601
+ self.camera.capture(*self.mobjects)
602
+ return self.camera.get_image()
603
+
604
+ def show(self) -> None:
605
+ self.update_frame(force_draw=True)
606
+ self.get_image().show()
607
+
608
+ def update_frame(self, dt: float = 0, force_draw: bool = False) -> None:
609
+ self.check_hot_reload()
610
+ if self.timeline.browsing:
611
+ self._update_frame_in_past(dt, force_draw)
612
+ return
613
+ if not self.paused:
614
+ self.increment_time(dt)
615
+ self.update_mobjects(dt)
616
+ self.timeline.note_frame(dt)
617
+ self.draw_frame(dt, force_draw)
618
+
619
+ def update_mobjects_in_steps(self, dt: float) -> None:
620
+ if not self.should_update_mobjects():
621
+ return
622
+ remaining = max(0.0, float(dt))
623
+ max_step = 1.0 / max(1.0, float(self.camera.fps))
624
+ # Cap substeps per frame to prevent a frame-time death spiral when a frame runs slow
625
+ max_substeps = 4
626
+ if remaining > max_step * max_substeps:
627
+ step = remaining / max_substeps
628
+ for _ in range(max_substeps):
629
+ self.update_mobjects(step)
630
+ return
631
+ while remaining > 1e-9:
632
+ step = min(remaining, max_step)
633
+ self.update_mobjects(step)
634
+ remaining -= step
635
+
636
+ async def update_mobjects_in_steps_async(self, dt: float) -> None:
637
+ """Apply a possibly delayed browser time interval in safe updater steps.
638
+
639
+ Browsers throttle requestAnimationFrame when a window/tab is hidden.
640
+ On return, a single large dt can destabilize time-based updaters. Keep
641
+ the full elapsed timeline interval, but subdivide updater calls and draw
642
+ only after the caller has finished catching up.
643
+ """
644
+ if not self.should_update_mobjects():
645
+ return
646
+ if not any(mob.has_async_updaters() for mob in self.mobjects):
647
+ self.update_mobjects_in_steps(dt)
648
+ return
649
+ remaining = max(0.0, float(dt))
650
+ max_step = 1.0 / max(1.0, float(self.camera.fps))
651
+ max_substeps = 4
652
+ if remaining > max_step * max_substeps:
653
+ step = remaining / max_substeps
654
+ for _ in range(max_substeps):
655
+ await self.update_mobjects_async(step)
656
+ return
657
+ while remaining > 1e-9:
658
+ step = min(remaining, max_step)
659
+ await self.update_mobjects_async(step)
660
+ remaining -= step
661
+
662
+ def _update_frame_in_past(self, dt: float, force_draw: bool) -> None:
663
+ # In the past the scene's clock is the timeline's, which moves only while it plays,
664
+ # but the window goes on answering, and a loop which counted on drawing to pace it
665
+ # is paced here instead
666
+ if self.timeline.playing:
667
+ self.timeline.tick()
668
+ else:
669
+ self.draw_frame(0, force_draw)
670
+ if dt > 0 and self.window is not None and sys.platform != "emscripten":
671
+ time.sleep(dt)
672
+
673
+ async def update_frame_async(self, dt: float = 0, force_draw: bool = False) -> None:
674
+ if self.timeline.browsing:
675
+ self._update_frame_in_past(dt, force_draw)
676
+ return
677
+ if not self.paused:
678
+ self.increment_time(dt)
679
+ stepped = sys.platform == "emscripten" and dt > 1.0 / max(1.0, float(self.camera.fps))
680
+ if stepped:
681
+ await self.update_mobjects_in_steps_async(dt)
682
+ else:
683
+ await self.update_mobjects_async(dt)
684
+ self.timeline.note_frame(dt, stepped=stepped)
685
+ from datacut.css import engine as _css_engine
686
+ if _css_engine._FONT_TASKS:
687
+ # Text restyled to another font is being built: draw it with its glyphs
688
+ await _css_engine.css_fonts_ready()
689
+ self.draw_frame(dt, force_draw)
690
+
691
+ def draw_frame(self, dt: float = 0, force_draw: bool = False) -> None:
692
+ if self.skip_animations and not force_draw:
693
+ return
694
+
695
+ if self.is_window_closing():
696
+ raise EndScene()
697
+
698
+ if self.window and dt == 0 and not self.window.has_undrawn_event() and not force_draw:
699
+ # In this case, there's no need for new rendering, but we
700
+ # shoudl still listen for new events
701
+ self.window.poll_events()
702
+ return
703
+
704
+ if self.dry_run:
705
+ return
706
+ self.performance.frame_boundary()
707
+ if self.file_writer.transparent:
708
+ # Whatever background the scene sets, a movie with its alpha has none, and a clear
709
+ # one, so that what is drawn over it is not tinted by a color never to be seen
710
+ self.camera.background_rgba[:] = [0.0, 0.0, 0.0, 0.0]
711
+ self._unpremultiply_frame()
712
+ self.camera.renderer.post_processor.time = self.time
713
+ self.camera.capture(
714
+ *self.mobjects,
715
+ *self.recorder.indicator(),
716
+ *self.performance.overlay(),
717
+ *self.safe_zones.overlay(),
718
+ )
719
+
720
+ if self.window and not self.skip_animations:
721
+ vt = self.time - self.virtual_animation_start_time
722
+ rt = time.time() - self.real_animation_start_time
723
+ if sys.platform != "emscripten":
724
+ with self.performance.measure("pause"):
725
+ time.sleep(max(vt - rt, 0))
726
+
727
+ def _unpremultiply_frame(self) -> None:
728
+ """
729
+ Drawn over nothing, every pixel's color comes out multiplied by its alpha, and editors
730
+ take a movie's alpha as straight: the last thing done to each frame is to divide it out
731
+ """
732
+ frame = self.camera.frame
733
+ if any(getattr(e, "name", "") == "Unpremultiply" for e in getattr(frame, "_vfx_effects", [])):
734
+ return
735
+ from datacut.utils.vfx_presets import CustomVFX
736
+ frame.add_vfx(CustomVFX(
737
+ "if (color.a > 0.0) { return vec4f(clamp(color.rgb / color.a, vec3f(0.0), vec3f(1.0)), color.a); } "
738
+ "return vec4f(0.0);",
739
+ order=10 ** 6, name="Unpremultiply", allow_multiple=False,
740
+ ))
741
+
742
+ def emit_frame(self) -> None:
743
+ if not self.skip_animations:
744
+ with self.performance.measure("video"):
745
+ self.file_writer.write_frame()
746
+
747
+ def set_safe_zones(self, preset: str | None) -> None:
748
+ """Set or clear the preview-only safe-zone guide preset (e.g. 'youtube_shorts', 'tiktok', 'reels', 'title_safe')."""
749
+ self.safe_zones.set_preset(preset)
750
+
751
+ def toggle_safe_zones(self) -> bool:
752
+ """Toggle visibility of the preview-only safe-zone guide overlay."""
753
+ return self.safe_zones.toggle()
754
+
755
+ # Related to updating
756
+
757
+ def update_mobjects(self, dt: float) -> None:
758
+ for mobject in self.mobjects:
759
+ mobject.update(dt, frame_rate=self.camera.fps)
760
+
761
+ async def update_mobjects_async(self, dt: float) -> None:
762
+ if not any(mob.has_async_updaters() for mob in self.mobjects):
763
+ self.update_mobjects(dt)
764
+ return
765
+ for mobject in self.mobjects:
766
+ await mobject.update_async(dt, frame_rate=self.camera.fps)
767
+
768
+ def should_update_mobjects(self) -> bool:
769
+ return self.always_update_mobjects or any(
770
+ mob.has_updaters() for mob in self.mobjects
771
+ )
772
+
773
+ # Related to time
774
+ def get_max_time(self) -> float:
775
+ return self.max_time
776
+
777
+ def get_time(self) -> float:
778
+ return self.time
779
+
780
+ def increment_time(self, dt: float) -> None:
781
+ start = self.time
782
+ self.time += dt
783
+ self.max_time = max(self.max_time, self.time)
784
+ if (
785
+ self._window_audio_mixer is not None
786
+ and not self.skip_animations
787
+ and not self.paused
788
+ and not self.timeline.browsing
789
+ ):
790
+ self._window_audio_mixer.sync_clock(self.time)
791
+ if self.tasks and not self.timeline.browsing:
792
+ timeline = self.timeline
793
+ before = timeline.task_signature(self.tasks) if timeline.enabled else None
794
+ run_tasks(self, self.tasks, start, self.time)
795
+ if before is not None and before != timeline.task_signature(self.tasks):
796
+ timeline.record(
797
+ "event", "scheduled", play=timeline.current_play,
798
+ pending_dt=self.time - start,
799
+ )
800
+
801
+ # Related to internal mobject organization
802
+
803
+ def get_top_level_mobjects(self) -> list[Mobject]:
804
+ # Return only those which are not in the family
805
+ # of another mobject from the scene
806
+ mobjects = self.get_mobjects()
807
+ if len(mobjects) <= 1:
808
+ return list(mobjects)
809
+
810
+ counts = Counter()
811
+ for m in mobjects:
812
+ counts.update(set(m.get_family()))
813
+
814
+ return [m for m in mobjects if counts[m] == 1]
815
+
816
+ def get_mobject_family_members(self) -> list[Mobject]:
817
+ return extract_mobject_family_members(self.mobjects)
818
+
819
+ @staticmethod
820
+ def affects_mobject_list(func: Callable[..., T]) -> Callable[..., T]:
821
+ @wraps(func)
822
+ def wrapper(self, *args, **kwargs):
823
+ func(self, *args, **kwargs)
824
+ return self
825
+ return wrapper
826
+
827
+ @affects_mobject_list
828
+ def add(self, *new_mobjects: Mobject, at: float | None = None):
829
+ """
830
+ Mobjects will be displayed, from background to
831
+ foreground in the order with which they are added.
832
+ When `at` is given and lies ahead on the scene's clock, the mobjects
833
+ are added at that time via `self.schedule` without blocking.
834
+ """
835
+ if at is not None and float(at) > self.get_time():
836
+ self.schedule(float(at), lambda: self.add(*new_mobjects))
837
+ return self
838
+ self.remove(*new_mobjects)
839
+ self.mobjects += new_mobjects
840
+ # No reordering by z_index here: this list stays in the order things were added, and
841
+ # the renderer settles what a z_index has to say about drawing order, see
842
+ # Renderer.resolve
843
+ self.id_to_mobject_map.update({
844
+ id(sm): sm
845
+ for m in new_mobjects
846
+ for sm in m.get_family()
847
+ })
848
+ return self
849
+
850
+ def add_mobjects_among(self, values: Iterable):
851
+ """
852
+ This is meant mostly for quick prototyping,
853
+ e.g. to add all mobjects defined up to a point,
854
+ call self.add_mobjects_among(locals().values())
855
+ """
856
+ self.add(*filter(
857
+ lambda m: isinstance(m, Mobject),
858
+ values
859
+ ))
860
+ return self
861
+
862
+ @affects_mobject_list
863
+ def replace(self, mobject: Mobject, *replacements: Mobject):
864
+ if mobject in self.mobjects:
865
+ index = self.mobjects.index(mobject)
866
+ self.mobjects = [
867
+ *self.mobjects[:index],
868
+ *replacements,
869
+ *self.mobjects[index + 1:]
870
+ ]
871
+ return self
872
+
873
+ @affects_mobject_list
874
+ def remove(self, *mobjects_to_remove: Mobject, at: float | None = None):
875
+ """
876
+ Removes anything in mobjects from scenes mobject list, but in the event that one
877
+ of the items to be removed is a member of the family of an item in mobject_list,
878
+ the other family members are added back into the list.
879
+
880
+ For example, if the scene includes Group(m1, m2, m3), and we call scene.remove(m1),
881
+ the desired behavior is for the scene to then include m2 and m3 (ungrouped).
882
+ When `at` is given and lies ahead on the scene's clock, the removal happens
883
+ at that time via `self.schedule` without blocking.
884
+ """
885
+ if at is not None and float(at) > self.get_time():
886
+ self.schedule(float(at), lambda: self.remove(*mobjects_to_remove))
887
+ return self
888
+ to_remove = set(extract_mobject_family_members(mobjects_to_remove))
889
+ new_mobjects, _ = recursive_mobject_remove(self.mobjects, to_remove)
890
+ self.mobjects = new_mobjects
891
+
892
+ @affects_mobject_list
893
+ def remove_all_except(self, *mobjects_to_keep : Mobject):
894
+ self.clear()
895
+ self.add(*mobjects_to_keep)
896
+
897
+ def bring_to_front(self, *mobjects: Mobject):
898
+ self.add(*mobjects)
899
+ return self
900
+
901
+ @affects_mobject_list
902
+ def bring_to_back(self, *mobjects: Mobject):
903
+ self.remove(*mobjects)
904
+ self.mobjects = list(mobjects) + self.mobjects
905
+ return self
906
+
907
+ @affects_mobject_list
908
+ def clear(self):
909
+ self.mobjects = []
910
+ return self
911
+
912
+ def get_mobjects(self) -> list[Mobject]:
913
+ return list(self.mobjects)
914
+
915
+ def get_mobject_copies(self) -> list[Mobject]:
916
+ return [m.copy() for m in self.mobjects]
917
+
918
+ def point_to_mobject(
919
+ self,
920
+ point: np.ndarray,
921
+ search_set: Iterable[Mobject] | None = None,
922
+ buff: float = 0
923
+ ) -> Mobject | None:
924
+ """
925
+ E.g. if clicking on the scene, this returns the top layer mobject
926
+ under a given point
927
+ """
928
+ if search_set is None:
929
+ search_set = self.mobjects
930
+ for mobject in reversed(search_set):
931
+ if mobject.is_point_touching(point, buff=buff):
932
+ return mobject
933
+ return None
934
+
935
+ def get_group(self, *mobjects):
936
+ if all(isinstance(m, VMobject) for m in mobjects):
937
+ return VGroup(*mobjects)
938
+ else:
939
+ return Group(*mobjects)
940
+
941
+ def id_to_mobject(self, id_value):
942
+ return self.id_to_mobject_map[id_value]
943
+
944
+ def ids_to_group(self, *id_values):
945
+ return self.get_group(*filter(
946
+ lambda x: x is not None,
947
+ map(self.id_to_mobject, id_values)
948
+ ))
949
+
950
+ def i2g(self, *id_values):
951
+ return self.ids_to_group(*id_values)
952
+
953
+ def i2m(self, id_value):
954
+ return self.id_to_mobject(id_value)
955
+
956
+ # Related to skipping
957
+
958
+ def update_skipping_status(self) -> None:
959
+ if self.resume_time is not None and self.time >= self.resume_time - 1e-6:
960
+ self.arrive_at_resume(view=False)
961
+ if self.start_at_animation_number is not None:
962
+ if self.num_plays == self.start_at_animation_number:
963
+ self.skip_time = self.time
964
+ if not self.original_skipping_status:
965
+ self.stop_skipping()
966
+ if self.end_at_animation_number is not None:
967
+ if self.num_plays >= self.end_at_animation_number:
968
+ raise EndScene()
969
+
970
+ def stop_skipping(self) -> None:
971
+ self.virtual_animation_start_time = self.time
972
+ self.real_animation_start_time = time.time()
973
+ self.skip_animations = False
974
+
975
+ # Methods associated with running animations
976
+
977
+ def get_time_progression(
978
+ self,
979
+ run_time: float,
980
+ n_iterations: int | None = None,
981
+ desc: str = "",
982
+ override_skip_animations: bool = False
983
+ ) -> list[float] | np.ndarray | ProgressDisplay:
984
+ if self.skip_animations and not override_skip_animations:
985
+ return [run_time]
986
+
987
+ times = np.arange(0, run_time, 1 / self.camera.fps) + 1 / self.camera.fps
988
+
989
+ self.file_writer.set_progress_display_description(sub_desc=desc)
990
+
991
+ if self.show_animation_progress:
992
+ return ProgressDisplay(
993
+ times,
994
+ total=n_iterations,
995
+ leave=self.leave_progress_bars,
996
+ ascii=True if platform.system() == 'Windows' else None,
997
+ desc=desc,
998
+ bar_format="{l_bar} {n_fmt:3}/{total_fmt:3} {rate_fmt}{postfix}",
999
+ )
1000
+ else:
1001
+ return times
1002
+
1003
+ def get_run_time(self, animations: Iterable[Animation]) -> float:
1004
+ return np.max([animation.get_run_time() for animation in animations])
1005
+
1006
+ def get_animation_time_progression(
1007
+ self,
1008
+ animations: Iterable[Animation]
1009
+ ) -> list[float] | np.ndarray | ProgressDisplay:
1010
+ animations = list(animations)
1011
+ run_time = self.get_run_time(animations)
1012
+ description = f"{self.num_plays} {animations[0]}"
1013
+ if len(animations) > 1:
1014
+ description += ", etc."
1015
+ time_progression = self.get_time_progression(run_time, desc=description)
1016
+ return time_progression
1017
+
1018
+ def get_wait_time_progression(
1019
+ self,
1020
+ duration: float,
1021
+ stop_condition: Callable[[], bool] | None = None
1022
+ ) -> list[float] | np.ndarray | ProgressDisplay:
1023
+ kw = {"desc": f"{self.num_plays} Waiting"}
1024
+ if stop_condition is not None:
1025
+ kw["n_iterations"] = -1 # So it doesn't show % progress
1026
+ kw["override_skip_animations"] = True
1027
+ return self.get_time_progression(duration, **kw)
1028
+
1029
+ def pre_play(self):
1030
+ # Presenter pauses belong to play()/wait(), not this shared setup method.
1031
+ # Keeping a hold loop here makes wait() enter it twice on the first play.
1032
+ self.update_skipping_status()
1033
+
1034
+ if not self.skip_animations:
1035
+ self.file_writer.begin_animation()
1036
+
1037
+ if self.window:
1038
+ self.virtual_animation_start_time = self.time
1039
+ self.real_animation_start_time = time.time()
1040
+
1041
+ def post_play(self):
1042
+ if not self.skip_animations:
1043
+ self.file_writer.end_animation()
1044
+
1045
+ if self.preview_while_skipping and self.skip_animations and self.window is not None:
1046
+ # Show some quick frames along the way
1047
+ self.update_frame(dt=0, force_draw=True)
1048
+
1049
+ self.num_plays += 1
1050
+
1051
+ def begin_animations(self, animations: Iterable[Animation]) -> None:
1052
+ all_mobjects = set(self.get_mobject_family_members())
1053
+ for animation in animations:
1054
+ animation.begin()
1055
+ # Anything animated that's not already in the
1056
+ # scene gets added to the scene. Note, for
1057
+ # animated mobjects that are in the family of
1058
+ # those on screen, this can result in a restructuring
1059
+ # of the scene.mobjects list, which is usually desired.
1060
+ # A group holding nothing but mobjects already on screen is
1061
+ # itself already on screen, though, and restructuring for its
1062
+ # sake would cost its ancestors whatever points they draw
1063
+ # themselves, so leave the scene as it is.
1064
+ family = animation.mobject.get_family()
1065
+ drawn = [mob for mob in family if mob.has_points()]
1066
+ shown_already = len(drawn) > 0 and all(mob in all_mobjects for mob in drawn)
1067
+ if animation.mobject not in all_mobjects and not shown_already:
1068
+ self.add(animation.mobject)
1069
+ all_mobjects = all_mobjects.union(family)
1070
+
1071
+ def progress_through_animations(self, animations: Iterable[Animation]) -> bool:
1072
+ with self.timeline.advancing_time():
1073
+ return self._progress_through_animations(animations)
1074
+
1075
+ def _progress_through_animations(self, animations: Iterable[Animation]) -> bool:
1076
+ last_t = 0
1077
+ for t in self.get_animation_time_progression(animations):
1078
+ self.check_hot_reload()
1079
+ if self.should_end_playing:
1080
+ self.should_end_playing = False
1081
+ return False
1082
+ dt = t - last_t
1083
+ last_t = t
1084
+ # The clock moves before anything else in the frame, so that time
1085
+ # based updaters are evaluated at the moment the frame stands for.
1086
+ self.increment_time(dt)
1087
+ if sys.platform == "emscripten":
1088
+ browser_audio.sync(self.time, self._interactive_sound_events, self._browser_sound_clips)
1089
+ for animation in animations:
1090
+ animation.update_reference_mobjects(dt, frame_rate=self.camera.fps)
1091
+ alpha = t / animation.run_time
1092
+ animation.interpolate(alpha)
1093
+ # Updaters on the mobjects themselves have the last word, applied
1094
+ # on top of whatever the animations just interpolated
1095
+ self.update_mobjects(dt)
1096
+ self.timeline.note_frame(dt, t)
1097
+ self.draw_frame(dt)
1098
+ self.emit_frame()
1099
+ return True
1100
+
1101
+ def finish_animations(self, animations: Iterable[Animation]) -> None:
1102
+ for animation in animations:
1103
+ animation.finish()
1104
+ animation.clean_up_from_scene(self)
1105
+ # Note that the passage of time during the animation, including
1106
+ # for the case of skipped animations, is handled by
1107
+ # progress_through_animations
1108
+ self.update_mobjects(0)
1109
+
1110
+ def pause(self) -> None:
1111
+ self.paused = True
1112
+ if sys.platform == "emscripten":
1113
+ browser_audio.stop_all()
1114
+ elif self._window_audio_mixer is not None:
1115
+ self._window_audio_mixer.stop()
1116
+
1117
+ def resume(self) -> None:
1118
+ self.paused = False
1119
+ if sys.platform == "emscripten":
1120
+ if self._interactive_sound_events:
1121
+ browser_audio.seek(self.time, self._interactive_sound_events, self._browser_sound_clips)
1122
+ elif self._window_audio_mixer is not None and self._window_audio_mixer.has_clips():
1123
+ self._window_audio_mixer.play_from(self.time)
1124
+
1125
+ def play(
1126
+ self,
1127
+ *proto_animations: Animation | _AnimationBuilder,
1128
+ run_time: float | None = None,
1129
+ rate_func: Callable[[float], float] | None = None,
1130
+ lag_ratio: float | None = None,
1131
+ register: bool = True,
1132
+ name: str | None = None,
1133
+ ) -> None:
1134
+ """
1135
+ `name` is what the play is called on the timeline's bar, see datacut.scene.timeline,
1136
+ rather than after its animations
1137
+ """
1138
+ if len(proto_animations) == 0:
1139
+ log.warning("Called Scene.play with no animations")
1140
+ return
1141
+ self._refuse_inside_task("play")
1142
+ animations = list(map(prepare_animation, proto_animations))
1143
+ for anim in animations:
1144
+ anim.update_rate_info(run_time, rate_func, lag_ratio)
1145
+ # Preserve the initial presenter pause for play(), without making wait()
1146
+ # enter the same hold loop twice through pre_play().
1147
+ if self.presenter_mode and self.num_plays == 0:
1148
+ self.hold_loop()
1149
+ if register:
1150
+ self.timeline.go_live()
1151
+ preserve_clock = not register and self.timeline._in_input > 0
1152
+ if preserve_clock:
1153
+ saved_time = self.time
1154
+ saved_num_plays = self.num_plays
1155
+ self.pre_play()
1156
+ before = self.timeline.state_before_play(animations) if register else None
1157
+ self.begin_animations(animations)
1158
+ play_record = self._record_play(animations, register, before, name)
1159
+ try:
1160
+ no_interrupt = self.progress_through_animations(animations)
1161
+ finally:
1162
+ if register:
1163
+ self.timeline.current_play = None
1164
+ if preserve_clock:
1165
+ self.time = saved_time
1166
+ self.num_plays = saved_num_plays
1167
+ self.virtual_animation_start_time = saved_time
1168
+ self.real_animation_start_time = time.time()
1169
+ if not no_interrupt and register:
1170
+ return
1171
+ self.finish_animations(animations)
1172
+ if register:
1173
+ self.timeline.record("end", f"end of {play_record.label}" if play_record else "")
1174
+ if not preserve_clock:
1175
+ self.post_play()
1176
+
1177
+ def _record_play(self, animations: list[Animation], register: bool, before=None, name=None):
1178
+ # Kept just after the animations have begun, so that any moment of the play can be
1179
+ # worked out from here, and with the scene as it was before they began, for erasing
1180
+ # the future from here, see datacut.scene.timeline
1181
+ record = PlayRecord(animations, self.time)
1182
+ record.label = name or self._animations_label(animations)
1183
+ if register:
1184
+ self.timeline.current_play = record
1185
+ self.chapters.append((self.time, record.label))
1186
+ self.file_writer.begin_chapter(animations)
1187
+ self.timeline.record(
1188
+ "play", record.label, play=record, before=before,
1189
+ source=caller_source() if self.timeline.enabled else None,
1190
+ )
1191
+ return record
1192
+
1193
+ def _browser_now(self) -> float:
1194
+ """Current browser clock in seconds, matching requestAnimationFrame timestamps."""
1195
+ from js import performance
1196
+ return float(performance.now()) / 1000.0
1197
+
1198
+ async def _browser_frame(self) -> float | None:
1199
+ """Yield to the browser and return the frame timestamp in seconds."""
1200
+ if sys.platform != "emscripten":
1201
+ return None
1202
+ from datacut.utils.browser_scheduler import next_animation_frame
1203
+ # Waiting on the browser for the next frame is no work of the scene's, see
1204
+ # datacut.scene.performance
1205
+ with self.performance.measure("pause"):
1206
+ return await next_animation_frame()
1207
+
1208
+ async def play_async(
1209
+ self,
1210
+ *proto_animations: Animation | _AnimationBuilder,
1211
+ run_time: float | None = None,
1212
+ rate_func: Callable[[float], float] | None = None,
1213
+ lag_ratio: float | None = None,
1214
+ register: bool = True,
1215
+ name: str | None = None,
1216
+ ) -> None:
1217
+ """Play an animation without blocking the browser event loop."""
1218
+ if sys.platform != "emscripten":
1219
+ return self.play(*proto_animations, run_time=run_time, rate_func=rate_func,
1220
+ lag_ratio=lag_ratio, register=register, name=name)
1221
+ if not proto_animations:
1222
+ log.warning("Called Scene.play_async with no animations")
1223
+ return
1224
+ animations = [await prepare_animation_async(anim) for anim in proto_animations]
1225
+ for anim in animations:
1226
+ anim.update_rate_info(run_time, rate_func, lag_ratio)
1227
+ if self.presenter_mode and self.num_plays == 0:
1228
+ await self.hold_loop_async()
1229
+ if register:
1230
+ self.timeline.go_live()
1231
+ preserve_clock = not register and self.timeline._in_input > 0
1232
+ if preserve_clock:
1233
+ saved_time = self.time
1234
+ saved_num_plays = self.num_plays
1235
+ self.pre_play()
1236
+ before = self.timeline.state_before_play(animations) if register else None
1237
+ self.begin_animations(animations)
1238
+ play_record = self._record_play(animations, register, before, name)
1239
+ if self.skip_animations:
1240
+ # Skipped through in one go, as play does, see get_time_progression
1241
+ try:
1242
+ self.progress_through_animations(animations)
1243
+ finally:
1244
+ if register:
1245
+ self.timeline.current_play = None
1246
+ if preserve_clock:
1247
+ self.time = saved_time
1248
+ self.num_plays = saved_num_plays
1249
+ self.virtual_animation_start_time = saved_time
1250
+ self.real_animation_start_time = time.time()
1251
+ self.finish_animations(animations)
1252
+ if register:
1253
+ self.timeline.record("end", f"end of {play_record.label}")
1254
+ if not preserve_clock:
1255
+ self.post_play()
1256
+ return
1257
+ duration = run_time or self.get_run_time(animations)
1258
+ # requestAnimationFrame is the browser clock. The configured render FPS
1259
+ # controls update granularity, not elapsed wall-clock time.
1260
+ last_frame_time = self._browser_now()
1261
+ elapsed = 0.0
1262
+ self.timeline._advancing += 1
1263
+ try:
1264
+ while elapsed < duration:
1265
+ if self.is_window_closing() or self.window is None:
1266
+ break
1267
+ t_before_poll = self._browser_now()
1268
+ await self._poll_window_events_async()
1269
+ last_frame_time += max(0.0, self._browser_now() - t_before_poll)
1270
+ if self.should_end_playing:
1271
+ self.should_end_playing = False
1272
+ break
1273
+ if self.paused:
1274
+ last_frame_time = await self._browser_frame()
1275
+ self.draw_frame(0, force_draw=True)
1276
+ continue
1277
+ if self.timeline.browsing:
1278
+ self.timeline.go_live()
1279
+ frame_time = await self._browser_frame()
1280
+ wall_dt = max(0.0, float(frame_time - last_frame_time))
1281
+ last_frame_time = frame_time
1282
+ dt = min(wall_dt, max(0.0, duration - elapsed))
1283
+ if dt <= 0:
1284
+ continue
1285
+
1286
+ # Keep interactive animation time aligned with active scene audio.
1287
+ # can_advance_scene() ignores rejected play() promises, so blocked audio
1288
+ # cannot deadlock keyboard-triggered animations. If media is behind,
1289
+ # hold this frame until its clock catches up; if media is ahead, pause it.
1290
+ if not browser_audio.can_advance_scene(
1291
+ self.time, self.time + dt, self._interactive_sound_events, self._browser_sound_clips
1292
+ ):
1293
+ continue
1294
+
1295
+ elapsed += dt
1296
+ if not preserve_clock:
1297
+ self.increment_time(dt)
1298
+ for animation in animations:
1299
+ animation.update_reference_mobjects(dt, frame_rate=self.camera.fps)
1300
+ animation.interpolate(float(elapsed) / animation.run_time)
1301
+ if not preserve_clock:
1302
+ await self.update_mobjects_in_steps_async(dt)
1303
+ self.timeline.note_frame(dt, elapsed, stepped=True)
1304
+ browser_audio.sync(self.time, self._interactive_sound_events, self._browser_sound_clips)
1305
+ self.draw_frame(dt, force_draw=True)
1306
+ if not preserve_clock:
1307
+ self.emit_frame()
1308
+ finally:
1309
+ self.timeline._advancing -= 1
1310
+ if register:
1311
+ self.timeline.current_play = None
1312
+ if preserve_clock:
1313
+ self.time = saved_time
1314
+ self.num_plays = saved_num_plays
1315
+ self.virtual_animation_start_time = saved_time
1316
+ self.real_animation_start_time = time.time()
1317
+ self.finish_animations(animations)
1318
+ if register:
1319
+ self.timeline.record("end", f"end of {play_record.label}")
1320
+ if not preserve_clock:
1321
+ self.post_play()
1322
+
1323
+ async def wait_async(
1324
+ self,
1325
+ duration: float | None = None,
1326
+ stop_condition: Callable[[], bool] | None = None,
1327
+ note: str | None = None,
1328
+ ignore_presenter_mode: bool = False,
1329
+ register: bool = True,
1330
+ name: str | None = None,
1331
+ ) -> None:
1332
+ """Wait asynchronously, using elapsed browser time as the clock."""
1333
+ if sys.platform != "emscripten":
1334
+ return self.wait(
1335
+ duration=duration,
1336
+ stop_condition=stop_condition,
1337
+ note=note,
1338
+ ignore_presenter_mode=ignore_presenter_mode,
1339
+ register=register,
1340
+ name=name,
1341
+ )
1342
+
1343
+ duration = self.default_wait_time if duration is None else max(0.0, duration)
1344
+ if self.presenter_mode and self.num_plays == 0:
1345
+ await self.hold_loop_async()
1346
+ if register:
1347
+ self.timeline.go_live()
1348
+ self.pre_play()
1349
+ await self.update_mobjects_async(0)
1350
+ if register:
1351
+ self.chapters.append((self.time, name or self._wait_label(duration, stop_condition, note)))
1352
+ self.file_writer.begin_chapter([])
1353
+ self.timeline.record(
1354
+ "wait", name or self._wait_label(duration, stop_condition, note),
1355
+ source=caller_source() if self.timeline.enabled else None,
1356
+ )
1357
+
1358
+ presenter_wait = (
1359
+ self.presenter_mode
1360
+ and not self.skip_animations
1361
+ and not ignore_presenter_mode
1362
+ )
1363
+ if self.skip_animations and not presenter_wait:
1364
+ # Skipped through in one go, as wait does
1365
+ await self.update_frame_async(duration)
1366
+ self.post_play()
1367
+ return
1368
+ if presenter_wait:
1369
+ if note:
1370
+ log.info(note)
1371
+ await self.hold_loop_async()
1372
+ else:
1373
+ # Do not advance by a fixed 1 / camera.fps per requestAnimationFrame:
1374
+ # the browser may deliver RAF callbacks at a different rate (e.g.
1375
+ # 60 Hz while camera.fps is 30), which made waits finish too early.
1376
+ last_frame_time = self._browser_now()
1377
+ elapsed = 0.0
1378
+ self.timeline._advancing += 1
1379
+ while elapsed < duration:
1380
+ if self.is_window_closing() or self.window is None:
1381
+ break
1382
+ t_before_poll = self._browser_now()
1383
+ await self._poll_window_events_async()
1384
+ last_frame_time += max(0.0, self._browser_now() - t_before_poll)
1385
+ if self.should_end_playing and register:
1386
+ self.should_end_playing = False
1387
+ self.timeline._advancing -= 1
1388
+ await self._browser_frame()
1389
+ self.post_play()
1390
+ return
1391
+ if self.paused:
1392
+ last_frame_time = await self._browser_frame()
1393
+ self.draw_frame(0, force_draw=True)
1394
+ continue
1395
+ if self.timeline.browsing:
1396
+ self.timeline.go_live()
1397
+
1398
+ frame_time = await self._browser_frame()
1399
+ wall_dt = max(0.0, float(frame_time - last_frame_time))
1400
+ last_frame_time = frame_time
1401
+ dt = min(wall_dt, max(0.0, duration - elapsed))
1402
+ if dt <= 0:
1403
+ continue
1404
+
1405
+ if not browser_audio.can_advance_scene(
1406
+ self.time, self.time + dt, self._interactive_sound_events, self._browser_sound_clips
1407
+ ):
1408
+ continue
1409
+
1410
+ elapsed += dt
1411
+ await self.update_frame_async(dt, force_draw=True)
1412
+ browser_audio.sync(self.time, self._interactive_sound_events, self._browser_sound_clips)
1413
+ self.emit_frame()
1414
+ if stop_condition is not None and stop_condition():
1415
+ break
1416
+ self.timeline._advancing -= 1
1417
+ self.post_play()
1418
+
1419
+ async def hold_loop_async(self) -> None:
1420
+ """Browser equivalent of hold_loop(), without blocking the event loop."""
1421
+ if sys.platform != "emscripten":
1422
+ return self.hold_loop()
1423
+ self.arrive_at_resume()
1424
+ last_frame_time = self._browser_now()
1425
+ while self.hold_on_wait and not self.is_window_closing():
1426
+ if self.window is None:
1427
+ break
1428
+ t_before_poll = self._browser_now()
1429
+ await self._poll_window_events_async()
1430
+ last_frame_time += max(0.0, self._browser_now() - t_before_poll)
1431
+ if self.is_window_closing():
1432
+ break
1433
+ frame_time = await self._browser_frame()
1434
+ dt = max(0.0, float(frame_time - last_frame_time))
1435
+ last_frame_time = frame_time
1436
+ if dt <= 0.0:
1437
+ continue
1438
+ if not browser_audio.can_advance_scene(
1439
+ self.time, self.time + dt, self._interactive_sound_events, self._browser_sound_clips
1440
+ ):
1441
+ continue
1442
+ await self.update_frame_async(dt=dt, force_draw=True)
1443
+ browser_audio.sync(self.time, self._interactive_sound_events, self._browser_sound_clips)
1444
+ self.hold_on_wait = True
1445
+ # The scene's code goes on from now
1446
+ self.timeline.go_live()
1447
+
1448
+ def wait(
1449
+ self,
1450
+ duration: Optional[float] = None,
1451
+ stop_condition: Callable[[], bool] = None,
1452
+ note: str = None,
1453
+ ignore_presenter_mode: bool = False,
1454
+ register: bool = True,
1455
+ name: str | None = None,
1456
+ ):
1457
+ """`name` is what the wait is called on the timeline's bar, see datacut.scene.timeline"""
1458
+ self._refuse_inside_task("wait")
1459
+ if duration is None:
1460
+ duration = self.default_wait_time
1461
+ if duration <= 0 and stop_condition is None and not (self.presenter_mode and not self.skip_animations and not ignore_presenter_mode):
1462
+ return
1463
+ if register:
1464
+ self.timeline.go_live()
1465
+ self.pre_play()
1466
+ self.update_mobjects(dt=0) # Any problems with this?
1467
+ if register:
1468
+ self.chapters.append((self.time, name or self._wait_label(duration, stop_condition, note)))
1469
+ self.file_writer.begin_chapter([])
1470
+ self.timeline.record(
1471
+ "wait", name or self._wait_label(duration, stop_condition, note),
1472
+ source=caller_source() if self.timeline.enabled else None,
1473
+ )
1474
+ if self.presenter_mode and not self.skip_animations and not ignore_presenter_mode:
1475
+ if note:
1476
+ log.info(note)
1477
+ self.hold_loop()
1478
+ else:
1479
+ time_progression = self.get_wait_time_progression(duration, stop_condition)
1480
+ last_t = 0
1481
+ with self.timeline.advancing_time():
1482
+ for t in time_progression:
1483
+ if self.should_end_playing and register:
1484
+ self.should_end_playing = False
1485
+ return
1486
+ dt = t - last_t
1487
+ last_t = t
1488
+ self.update_frame(dt)
1489
+ self.emit_frame()
1490
+ if stop_condition is not None and stop_condition():
1491
+ break
1492
+ self.post_play()
1493
+
1494
+ def _animations_label(self, animations: list[Animation]) -> str:
1495
+ first = animations[0]
1496
+ methods = getattr(first, "methods", None)
1497
+ if getattr(first, "has_given_name", False):
1498
+ label = first.name
1499
+ elif methods:
1500
+ # mob.animate.shift(...).scale(...) reads as Mesh3D.animate.shift.scale
1501
+ names = ".".join(getattr(m, "__name__", "?") for m in methods)
1502
+ label = f"{type(first.mobject).__name__}.animate.{names}"
1503
+ else:
1504
+ label = str(first)
1505
+ if len(animations) > 1:
1506
+ label += f" (+{len(animations) - 1})"
1507
+ return label
1508
+
1509
+ def _wait_label(self, duration, stop_condition, note) -> str:
1510
+ if note:
1511
+ return f"Wait: {note}"
1512
+ if stop_condition is not None:
1513
+ return "Wait (until condition)"
1514
+ return f"Wait({duration:g})"
1515
+
1516
+ def hold_loop(self):
1517
+ self.arrive_at_resume()
1518
+ while self.hold_on_wait:
1519
+ self.update_frame(dt=1 / self.camera.fps)
1520
+ self.hold_on_wait = True
1521
+ # The scene's code goes on from now
1522
+ self.timeline.go_live()
1523
+
1524
+ def force_skipping(self):
1525
+ self.original_skipping_status = self.skip_animations
1526
+ self.skip_animations = True
1527
+ return self
1528
+
1529
+ def revert_to_original_skipping_status(self):
1530
+ if hasattr(self, "original_skipping_status"):
1531
+ self.skip_animations = self.original_skipping_status
1532
+ return self
1533
+
1534
+ def add_sound(
1535
+ self,
1536
+ sound_file: str | Sound | np.ndarray,
1537
+ time_offset: float = 0,
1538
+ gain: float | None = None,
1539
+ gain_to_background: float | None = None,
1540
+ fade_in: float = 0.0,
1541
+ fade_out: float = 0.0,
1542
+ voice: bool = False,
1543
+ duck: bool | float = False,
1544
+ loop: bool | int = False,
1545
+ sample_rate: int = 44100,
1546
+ at: float | None = None,
1547
+ transcript=None,
1548
+ ) -> SoundClip:
1549
+ """
1550
+ Plays a sound from now, or `time_offset` seconds from now, `gain` decibels louder.
1551
+
1552
+ The sound is a file's name, a Sound (see datacut.scene.sound), which need never have
1553
+ been a file, a pydub AudioSegment, or samples as a numpy array, `sample_rate` a second.
1554
+
1555
+ fade_in, fade_out: seconds it fades in from silence and out to it at its end
1556
+ voice: it is narration, which sounds asked to duck drop under
1557
+ duck: drop under narration while it plays, by 12 decibels, or by as many as given
1558
+ loop: play it over and over, until stopped or the scene ends for True, or that many
1559
+ times in all, fade_out then fading out the end of the whole
1560
+ at: when on the scene's clock it starts, as SoundClip.at hands back, over time_offset:
1561
+ add_sound("boom.wav", at=voice.at("clave"))
1562
+ transcript: what is said in it, a Transcript or a JSON file's name, used rather than
1563
+ transcribing it, see datacut.scene.transcript; one beside the sound file is
1564
+ found on its own
1565
+
1566
+ Hands back the SoundClip, which can change its volume or stop it later on, see
1567
+ datacut.scene.sound_clip. All of this is in the movie written; a window or the browser
1568
+ plays the sound as it is, and while animations are skipped there is no sound at all, the
1569
+ clip handed back then taking the same calls and doing nothing with them.
1570
+ """
1571
+ time = self.get_time() + time_offset if at is None else float(at)
1572
+ transcription = getattr(self, "transcription_options", None)
1573
+ if isinstance(sound_file, np.ndarray):
1574
+ sound_file = Sound.from_array(sound_file, sample_rate)
1575
+ elif not isinstance(sound_file, (str, os.PathLike, Sound)):
1576
+ # A pydub AudioSegment
1577
+ sound_file = Sound.from_segment(sound_file)
1578
+ # What a clip handed back while nothing is written knows: enough to wait on its words
1579
+ quiet_clip = SoundClip(
1580
+ source=sound_file, scene_start=time, transcription=transcription,
1581
+ transcript=transcript,
1582
+ )
1583
+ if self.skip_animations and self.resume_time is None:
1584
+ return self._note_voice(quiet_clip, voice)
1585
+
1586
+ if self.window is not None:
1587
+ event_time = time
1588
+ if sys.platform == "emscripten":
1589
+ # Register browser audio during scene construction. Playback starts
1590
+ # as the scene clock advances through each event's scheduled time.
1591
+ is_sound = isinstance(sound_file, Sound)
1592
+ if is_sound:
1593
+ key = f"datacut-sound-{id(sound_file)}"
1594
+ browser_audio.register_wav(key, sound_file.gain(gain or 0).to_wav_bytes())
1595
+ event_sound_ref = key
1596
+ else:
1597
+ browser_audio.register(sound_file)
1598
+ event_sound_ref = sound_file
1599
+ self._interactive_sound_events.append((event_time, event_sound_ref, 0.0))
1600
+ browser_clip = SoundClip(
1601
+ source=sound_file,
1602
+ scene_start=event_time,
1603
+ fade_in=fade_in,
1604
+ fade_out=fade_out,
1605
+ voice=voice,
1606
+ duck=duck,
1607
+ loop=loop,
1608
+ transcription=transcription,
1609
+ transcript=transcript,
1610
+ )
1611
+ browser_clip.browser_scene = self
1612
+ browser_clip.browser_event = self._interactive_sound_events[-1]
1613
+ browser_clip.browser_gain = gain or 0.0
1614
+ browser_clip.browser_gain_baked = is_sound
1615
+ browser_clip.browser_gain_to_background = gain_to_background
1616
+ self._browser_sound_clips.append(browser_clip)
1617
+ return self._note_voice(browser_clip, voice)
1618
+ else:
1619
+ from pydub import AudioSegment
1620
+ if isinstance(sound_file, Sound):
1621
+ new_segment = sound_file.to_segment()
1622
+ event_ref = ""
1623
+ else:
1624
+ file_path = get_full_sound_file_path(sound_file)
1625
+ new_segment = AudioSegment.from_file(file_path)
1626
+ event_ref = str(sound_file)
1627
+ if gain:
1628
+ new_segment = new_segment.apply_gain(gain)
1629
+ mixer = self._get_window_audio_mixer()
1630
+ clip = SoundClip(
1631
+ None,
1632
+ new_segment,
1633
+ scene_start=event_time,
1634
+ fade_in=fade_in,
1635
+ fade_out=fade_out,
1636
+ voice=voice,
1637
+ duck=duck,
1638
+ loop=loop,
1639
+ source=sound_file,
1640
+ transcription=transcription,
1641
+ transcript=transcript,
1642
+ window_mixer=mixer,
1643
+ )
1644
+ handle = mixer.add_clip(
1645
+ clip,
1646
+ gain_to_background=gain_to_background,
1647
+ start_playback=not self.skip_animations,
1648
+ )
1649
+ self._active_sound_processes.append(handle)
1650
+ self._interactive_sound_events.append((event_time, event_ref, clip.duration))
1651
+ return self._note_voice(clip, voice)
1652
+ return self._note_voice(quiet_clip, voice)
1653
+
1654
+ return self._note_voice(self.file_writer.add_sound(
1655
+ sound_file, time, gain, gain_to_background,
1656
+ fade_in=fade_in, fade_out=fade_out, voice=voice, duck=duck,
1657
+ scene_start=time, loop=loop, transcription=transcription, transcript=transcript,
1658
+ ), voice)
1659
+
1660
+ def _note_voice(self, clip: SoundClip, voice: bool) -> SoundClip:
1661
+ """Keeps narration, for subtitles drawn in the video to follow, see add_subtitles"""
1662
+ if voice:
1663
+ clip.voice = True
1664
+ if not hasattr(self, "voice_clips"):
1665
+ self.voice_clips = []
1666
+ self.voice_clips.append(clip)
1667
+ return clip
1668
+
1669
+ def add_sfx(
1670
+ self,
1671
+ name: str | Sound,
1672
+ time_offset: float = 0,
1673
+ gain: float | None = None,
1674
+ gain_to_background: float | None = None,
1675
+ fade_in: float = 0.0,
1676
+ fade_out: float = 0.0,
1677
+ loop: bool | int = False,
1678
+ at: float | None = None,
1679
+ **params,
1680
+ ) -> SoundClip:
1681
+ """
1682
+ Plays a sound effect from your library from now, or `time_offset` seconds from now:
1683
+ a sound file in your effects folder called by its name, one registered with
1684
+ register_sfx, or a Sound. See datacut.scene.sfx.
1685
+
1686
+ self.add_sfx("click") # sfx/click.wav, say
1687
+ self.add_sfx("memes/fah", gain=-3) # sfx/memes/fah.mp3
1688
+ self.add_sfx("boom", at=voice.at("clave")) # right as it is said
1689
+
1690
+ `params` go to an effect registered as a function.
1691
+ """
1692
+ sound = name if isinstance(name, Sound) else sfx(name, **params)
1693
+ return self.add_sound(
1694
+ sound, time_offset, gain, gain_to_background,
1695
+ fade_in=fade_in, fade_out=fade_out, loop=loop, at=at,
1696
+ )
1697
+
1698
+ def wait_until(
1699
+ self,
1700
+ time: float | Callable[[], bool],
1701
+ max_time: float = 60,
1702
+ note: str | None = None,
1703
+ ) -> None:
1704
+ """
1705
+ Waits until `time` on the scene's clock, as handed back by SoundClip.at, to start
1706
+ something right as it is said:
1707
+
1708
+ voice = self.add_sound("overview1.wav", voice=True)
1709
+ self.wait_until(voice.at("probabilidad"))
1710
+ self.play(Write(title))
1711
+
1712
+ A time already past is not waited for, and said so if it is past by more than a frame.
1713
+ Handed a function instead, waits until it is true, for `max_time` seconds at most.
1714
+ """
1715
+ if callable(time):
1716
+ self.wait(max_time, stop_condition=time, note=note)
1717
+ return
1718
+ remaining = float(time) - self.get_time()
1719
+ if remaining > 1e-9:
1720
+ self.wait(remaining, note=note)
1721
+ elif remaining < -1.0 / self.camera.fps:
1722
+ log.warning(f"Asked to wait until {time:.2f}s, but the scene is already at {self.get_time():.2f}s")
1723
+
1724
+ async def wait_until_async(
1725
+ self,
1726
+ time: float | Callable[[], bool],
1727
+ max_time: float = 60,
1728
+ note: str | None = None,
1729
+ ) -> None:
1730
+ """wait_until, without blocking the browser"""
1731
+ if callable(time):
1732
+ await self.wait_async(max_time, stop_condition=time, note=note)
1733
+ return
1734
+ remaining = float(time) - self.get_time()
1735
+ if remaining > 1e-9:
1736
+ await self.wait_async(remaining, note=note)
1737
+ elif remaining < -1.0 / self.camera.fps:
1738
+ log.warning(f"Asked to wait until {time:.2f}s, but the scene is already at {self.get_time():.2f}s")
1739
+
1740
+ async def wait_for_word_async(
1741
+ self,
1742
+ phrase: str,
1743
+ clip: SoundClip | None = None,
1744
+ occurrence: int | None = None,
1745
+ end: bool = False,
1746
+ note: str | None = None,
1747
+ ) -> float:
1748
+ """wait_for_word, without blocking the browser"""
1749
+ time = self.time_of_word(phrase, clip, occurrence, end)
1750
+ await self.wait_until_async(time, note=note)
1751
+ self._word_waited_for = time
1752
+ return time
1753
+
1754
+ def wait_for_word(
1755
+ self,
1756
+ phrase: str,
1757
+ clip: SoundClip | None = None,
1758
+ occurrence: int | None = None,
1759
+ end: bool = False,
1760
+ note: str | None = None,
1761
+ ) -> float:
1762
+ """
1763
+ Waits until `phrase` is said, the next time it is from now in any voice of the scene,
1764
+ see add_sound's voice=True, or in `clip`:
1765
+
1766
+ voice = self.add_sound("overview1.wav", voice=True)
1767
+ self.play_background(Write(formula))
1768
+ self.wait_for_word("clave")
1769
+ self.play(Indicate(formula))
1770
+
1771
+ `occurrence` picks which time it is said in `clip`, or in the latest voice, counting
1772
+ from 1, rather than the next; end=True waits until it has been said. Found regardless of
1773
+ case, accents and punctuation, see Transcript.find. Hands back the time waited until.
1774
+ """
1775
+ time = self.time_of_word(phrase, clip, occurrence, end)
1776
+ self.wait_until(time, note=note)
1777
+ # Asked again, the next time it is said, not this one the clock is now on
1778
+ self._word_waited_for = time
1779
+ return time
1780
+
1781
+ def time_of_word(
1782
+ self,
1783
+ phrase: str,
1784
+ clip: SoundClip | None = None,
1785
+ occurrence: int | None = None,
1786
+ end: bool = False,
1787
+ ) -> float:
1788
+ """When on the scene's clock wait_for_word would wait until, see there"""
1789
+ clips = [clip] if clip is not None else list(getattr(self, "voice_clips", []))
1790
+ if not clips:
1791
+ raise ValueError(
1792
+ "No narration to listen to: add it with add_sound(..., voice=True), or hand "
1793
+ "wait_for_word the clip"
1794
+ )
1795
+ if occurrence is not None:
1796
+ return clips[-1].at(phrase, occurrence, end)
1797
+ now = self.get_time()
1798
+ after = max(now - 1e-6, getattr(self, "_word_waited_for", -1.0) + 1e-6)
1799
+ found = []
1800
+ for c in clips:
1801
+ try:
1802
+ found.append(c.at(phrase, end=end, after=after))
1803
+ except KeyError:
1804
+ pass
1805
+ if not found:
1806
+ raise KeyError(f"{phrase!r} is not said from {now:.2f}s on in the scene's narration")
1807
+ return min(found)
1808
+
1809
+ def schedule(self, time: float, function: Callable[[], object]) -> ScheduledCall:
1810
+ """
1811
+ Calls `function` at `time` on the scene's clock, as handed back by SoundClip.at, while
1812
+ the scene plays and waits meanwhile, see datacut.scene.scene_task:
1813
+
1814
+ self.schedule(voice.at("clave"), lambda: self.add_sfx("boom"))
1815
+ self.play(Write(formula), run_time=5) # "clave" is said somewhere in here
1816
+
1817
+ Made right away for a time already past. Hands back the task, which cancel() calls off.
1818
+ """
1819
+ task = ScheduledCall(self, max(float(time), self.get_time()), function)
1820
+ if task.start <= self.get_time():
1821
+ task.advance(task.start)
1822
+ return task
1823
+ self.tasks.append(task)
1824
+ return task
1825
+
1826
+ def play_background(
1827
+ self,
1828
+ *proto_animations: Animation | _AnimationBuilder,
1829
+ run_time: float | None = None,
1830
+ rate_func: Callable[[float], float] | None = None,
1831
+ lag_ratio: float | None = None,
1832
+ at: float | None = None,
1833
+ ) -> BackgroundAnimation:
1834
+ """
1835
+ Plays animations while the scene goes on, rather than waiting for them to end as play
1836
+ does, from now or from `at` on the scene's clock, see datacut.scene.scene_task:
1837
+
1838
+ gear_turning = self.play_background(Rotate(gear, TAU, run_time=8))
1839
+ self.play(Write(title)) # the gear turns meanwhile
1840
+ self.play_background(Flash(dot), at=voice.at("clave"))
1841
+ gear_turning.wait() # until it is done
1842
+
1843
+ Each animation runs as long as it is, and is finished and cleaned up from the scene at
1844
+ its own end, as play would. Hands back the task: wait() waits for it, finish() puts it
1845
+ at its end at once, cancel() stops it where it is.
1846
+ """
1847
+ animations = list(map(prepare_animation, proto_animations))
1848
+ for anim in animations:
1849
+ anim.update_rate_info(run_time, rate_func, lag_ratio)
1850
+ start = self.get_time() if at is None else max(float(at), self.get_time())
1851
+ task = BackgroundAnimation(self, start, animations)
1852
+ if start <= self.get_time():
1853
+ task.advance(start)
1854
+ if not task.done:
1855
+ self.tasks.append(task)
1856
+ return task
1857
+
1858
+ def _refuse_inside_task(self, what: str) -> None:
1859
+ if self._in_task:
1860
+ raise RuntimeError(
1861
+ f"Scene.{what} can't be called from a scheduled call, the scene being in the "
1862
+ "middle of a frame: play in the background with play_background instead"
1863
+ )
1864
+
1865
+ def set_transcription(self, **options) -> None:
1866
+ """
1867
+ How this scene's sounds are transcribed unless told otherwise, see
1868
+ datacut.scene.transcript.transcribe: language="es", model="large-v3-turbo" (the
1869
+ default), prompt=...
1870
+ For sounds added from then on.
1871
+ """
1872
+ self.transcription_options = dict(options)
1873
+
1874
+ def enable_subtitles(self, **cue_options) -> None:
1875
+ """
1876
+ Writes subtitles of what every sound added with voice=True says beside the movie, as an
1877
+ .srt of the same name, see Transcript.cues for `cue_options`: max_chars, max_duration
1878
+ and max_gap. Each voice is transcribed once and kept, see datacut.scene.transcript.
1879
+ """
1880
+ self.file_writer.subtitle_options = dict(cue_options)
1881
+
1882
+ def add_subtitles(self, *clips: SoundClip, **kwargs):
1883
+ """
1884
+ Draws subtitles of the narration in the video, the word being said lit up, see
1885
+ datacut.mobject.subtitles.Subtitles for the options:
1886
+
1887
+ self.add_subtitles()
1888
+ self.add_subtitles(text=MyTypstText, text_config=dict(font_size=40))
1889
+
1890
+ Of `clips` where given, otherwise of every sound added with voice=True, those added
1891
+ later included. Hands back the Subtitles, already added to the scene.
1892
+ """
1893
+ from datacut.mobject.subtitles import Subtitles
1894
+ if clips:
1895
+ followed = list(clips)
1896
+ else:
1897
+ if not hasattr(self, "voice_clips"):
1898
+ self.voice_clips = []
1899
+ followed = self.voice_clips
1900
+ subtitles = Subtitles(self, followed, **kwargs)
1901
+ self.add(subtitles)
1902
+ return subtitles
1903
+
1904
+ def set_master_audio(self, process: Callable[[Sound], Sound] | None) -> None:
1905
+ """
1906
+ Puts the whole of the movie's audio through `process` before it is written, as the
1907
+ master bus of a mixer:
1908
+
1909
+ self.set_master_audio(lambda mix: mix.normalize_loudness(-14).limit(-1))
1910
+
1911
+ None takes it off again. Only the movie written hears it.
1912
+ """
1913
+ self.file_writer.master_audio = process
1914
+
1915
+ async def _poll_window_events_async(self) -> None:
1916
+ if self.window is None:
1917
+ return
1918
+ poll_async = getattr(self.window, "poll_events_async", None)
1919
+ if poll_async is not None:
1920
+ await poll_async()
1921
+ else:
1922
+ self.window.poll_events()
1923
+
1924
+ async def browser_interaction_loop(self) -> None:
1925
+ """Keep browser input and mobject updaters alive after playback."""
1926
+ if sys.platform != "emscripten":
1927
+ raise RuntimeError("browser_interaction_loop() is only available in Pyodide")
1928
+ from datacut.utils.browser_scheduler import next_animation_frame
1929
+ from js import window
1930
+
1931
+ previous_time = await next_animation_frame()
1932
+ # MotionBlur eases out over several rendered frames after input stops.
1933
+ # Keep drawing briefly after the last browser event so that release
1934
+ # frames are presented even when the scene has no active updaters.
1935
+ postprocess_settle_until = 0.0
1936
+ postprocess_settle_seconds = 0.5
1937
+
1938
+ while not self.is_window_closing():
1939
+ if self.window is None:
1940
+ break
1941
+ with self.performance.measure("pause"):
1942
+ current_time = await next_animation_frame()
1943
+ if self.is_window_closing() or self.window is None:
1944
+ break
1945
+ dt = max(0.0, current_time - previous_time)
1946
+ previous_time = current_time
1947
+
1948
+ if self.window is None:
1949
+ break
1950
+ t_before_poll = self._browser_now()
1951
+ await self._poll_window_events_async()
1952
+ previous_time += max(0.0, self._browser_now() - t_before_poll)
1953
+ has_undrawn_event = self.window.has_undrawn_event()
1954
+
1955
+ # Keep the live canvas advancing while browser recording is active.
1956
+ # Otherwise a static scene draws only in response to input events,
1957
+ # so the recorder gets no frames throughout an idle interactive period.
1958
+ recording_active = bool(
1959
+ getattr(window, "__manimCaptureWebGPUFrame", None)
1960
+ )
1961
+
1962
+ # requestAnimationFrame is the browser clock. Update animated scenes
1963
+ # as usual, and also draw every browser frame while recording so the
1964
+ # capture callback receives a continuous video timeline.
1965
+ if self.should_update_mobjects() or recording_active or self.timeline.playing:
1966
+ await self.update_frame_async(dt=dt, force_draw=True)
1967
+ elif has_undrawn_event:
1968
+ postprocess_settle_until = (
1969
+ current_time + postprocess_settle_seconds
1970
+ )
1971
+ await self.update_frame_async(force_draw=True)
1972
+ elif current_time < postprocess_settle_until:
1973
+ # Motion blur's temporal strength decays during these frames.
1974
+ await self.update_frame_async(dt=dt, force_draw=True)
1975
+
1976
+ # Helpers for interactive development
1977
+
1978
+ def get_state(
1979
+ self,
1980
+ ignore: list[Mobject] | None = None,
1981
+ previous: SceneState | None = None,
1982
+ ) -> SceneState:
1983
+ return SceneState(self, ignore=ignore, previous=previous)
1984
+
1985
+ @affects_mobject_list
1986
+ def restore_state(self, scene_state: SceneState):
1987
+ scene_state.restore_scene(self)
1988
+
1989
+ def save_state(self) -> None:
1990
+ state = self.get_state()
1991
+ if self.undo_stack and state.mobjects_match(self.undo_stack[-1]):
1992
+ return
1993
+ self.redo_stack = []
1994
+ self.undo_stack.append(state)
1995
+ if len(self.undo_stack) > self.max_num_saved_states:
1996
+ self.undo_stack.pop(0)
1997
+
1998
+ def undo(self):
1999
+ if self.undo_stack:
2000
+ self.redo_stack.append(self.get_state())
2001
+ self.restore_state(self.undo_stack.pop())
2002
+
2003
+ def redo(self):
2004
+ if self.redo_stack:
2005
+ self.undo_stack.append(self.get_state())
2006
+ self.restore_state(self.redo_stack.pop())
2007
+
2008
+ @contextmanager
2009
+ def temp_skip(self):
2010
+ prev_status = self.skip_animations
2011
+ self.skip_animations = True
2012
+ try:
2013
+ yield
2014
+ finally:
2015
+ if not prev_status:
2016
+ self.stop_skipping()
2017
+
2018
+ @contextmanager
2019
+ def temp_progress_bar(self):
2020
+ prev_progress = self.show_animation_progress
2021
+ self.show_animation_progress = True
2022
+ try:
2023
+ yield
2024
+ finally:
2025
+ self.show_animation_progress = prev_progress
2026
+
2027
+ @contextmanager
2028
+ def temp_record(self):
2029
+ with self.camera.at_output_resolution():
2030
+ self.file_writer.begin_insert()
2031
+ try:
2032
+ yield
2033
+ finally:
2034
+ self.file_writer.end_insert()
2035
+
2036
+ def temp_config_change(self, skip=False, record=False, progress_bar=False):
2037
+ stack = ExitStack()
2038
+ if skip:
2039
+ stack.enter_context(self.temp_skip())
2040
+ if record:
2041
+ stack.enter_context(self.temp_record())
2042
+ if progress_bar:
2043
+ stack.enter_context(self.temp_progress_bar())
2044
+ return stack
2045
+
2046
+ def is_window_closing(self):
2047
+ if self.window is None:
2048
+ return False
2049
+ if getattr(self, "_is_torn_down", False) or getattr(self, "_stop_requested", False):
2050
+ return True
2051
+ return self.window.is_closing or self.quit_interaction
2052
+
2053
+ # Event handling
2054
+ def set_floor_plane(self, plane: str = "xy"):
2055
+ if plane == "xy":
2056
+ self.frame.set_euler_axes("zxz")
2057
+ elif plane == "xz":
2058
+ self.frame.set_euler_axes("zxy")
2059
+ else:
2060
+ raise Exception("Only `xz` and `xy` are valid floor planes")
2061
+
2062
+ def on_mouse_motion(
2063
+ self,
2064
+ point: Vect3,
2065
+ d_point: Vect3
2066
+ ) -> None:
2067
+ if sys.platform == "emscripten":
2068
+ return self.on_mouse_motion_async(point, d_point)
2069
+ if self.window is None:
2070
+ return
2071
+ self.mouse_point.move_to(point)
2072
+
2073
+ event_data = {"point": point, "d_point": d_point, **mouse_event_data(self.frame, point)}
2074
+ propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseMotionEvent, **event_data)
2075
+ if propagate_event is not None and propagate_event is False:
2076
+ return
2077
+
2078
+ frame = self.camera.frame
2079
+ # Handle perspective changes
2080
+ if self.window.is_key_pressed(ord(manim_config.key_bindings.pan_3d)):
2081
+ ff_d_point = frame.to_fixed_frame_point(d_point, relative=True)
2082
+ ff_d_point *= self.pan_sensitivity
2083
+ frame.increment_theta(-ff_d_point[0])
2084
+ frame.increment_phi(ff_d_point[1])
2085
+ # Handle frame movements
2086
+ elif self.window.is_key_pressed(ord(manim_config.key_bindings.pan)):
2087
+ frame.shift(-d_point)
2088
+
2089
+
2090
+ async def on_mouse_motion_async(
2091
+ self,
2092
+ point: Vect3,
2093
+ d_point: Vect3
2094
+ ) -> None:
2095
+ if self.window is None:
2096
+ return
2097
+ self.mouse_point.move_to(point)
2098
+
2099
+ event_data = {"point": point, "d_point": d_point, **mouse_event_data(self.frame, point)}
2100
+ propagate_event = await EVENT_DISPATCHER.dispatch_async(EventType.MouseMotionEvent, **event_data)
2101
+ if propagate_event is not None and propagate_event is False:
2102
+ return
2103
+
2104
+ frame = self.camera.frame
2105
+ # Handle perspective changes
2106
+ if self.window.is_key_pressed(ord(manim_config.key_bindings.pan_3d)):
2107
+ ff_d_point = frame.to_fixed_frame_point(d_point, relative=True)
2108
+ ff_d_point *= self.pan_sensitivity
2109
+ frame.increment_theta(-ff_d_point[0])
2110
+ frame.increment_phi(ff_d_point[1])
2111
+ # Handle frame movements
2112
+ elif self.window.is_key_pressed(ord(manim_config.key_bindings.pan)):
2113
+ frame.shift(-d_point)
2114
+
2115
+ def on_mouse_drag(
2116
+ self,
2117
+ point: Vect3,
2118
+ d_point: Vect3,
2119
+ buttons: int,
2120
+ modifiers: int
2121
+ ) -> None:
2122
+ if sys.platform == "emscripten":
2123
+ return self.on_mouse_drag_async(point, d_point, buttons, modifiers)
2124
+ self.mouse_drag_point.move_to(point)
2125
+ if self.drag_to_pan:
2126
+ self.frame.shift(-d_point)
2127
+
2128
+ event_data = {"point": point, "d_point": d_point, "buttons": buttons, "modifiers": modifiers, **mouse_event_data(self.frame, point)}
2129
+ propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseDragEvent, **event_data)
2130
+ if propagate_event is not None and propagate_event is False:
2131
+ return
2132
+
2133
+
2134
+ async def on_mouse_drag_async(
2135
+ self,
2136
+ point: Vect3,
2137
+ d_point: Vect3,
2138
+ buttons: int,
2139
+ modifiers: int
2140
+ ) -> None:
2141
+ self.mouse_drag_point.move_to(point)
2142
+ if self.drag_to_pan:
2143
+ self.frame.shift(-d_point)
2144
+
2145
+ event_data = {"point": point, "d_point": d_point, "buttons": buttons, "modifiers": modifiers, **mouse_event_data(self.frame, point)}
2146
+ propagate_event = await EVENT_DISPATCHER.dispatch_async(EventType.MouseDragEvent, **event_data)
2147
+ if propagate_event is not None and propagate_event is False:
2148
+ return
2149
+
2150
+
2151
+ def on_mouse_press(
2152
+ self,
2153
+ point: Vect3,
2154
+ button: int,
2155
+ mods: int
2156
+ ) -> None:
2157
+ if sys.platform == "emscripten":
2158
+ return self.on_mouse_press_async(point, button, mods)
2159
+ self.mouse_drag_point.move_to(point)
2160
+ event_data = {"point": point, "button": button, "mods": mods, **mouse_event_data(self.frame, point)}
2161
+ propagate_event = EVENT_DISPATCHER.dispatch(EventType.MousePressEvent, **event_data)
2162
+ if propagate_event is not None and propagate_event is False:
2163
+ return
2164
+
2165
+
2166
+ async def on_mouse_press_async(
2167
+ self,
2168
+ point: Vect3,
2169
+ button: int,
2170
+ mods: int
2171
+ ) -> None:
2172
+ self.mouse_drag_point.move_to(point)
2173
+ event_data = {"point": point, "button": button, "mods": mods, **mouse_event_data(self.frame, point)}
2174
+ propagate_event = await EVENT_DISPATCHER.dispatch_async(EventType.MousePressEvent, **event_data)
2175
+ if propagate_event is not None and propagate_event is False:
2176
+ return
2177
+
2178
+
2179
+ def on_mouse_release(
2180
+ self,
2181
+ point: Vect3,
2182
+ button: int,
2183
+ mods: int
2184
+ ) -> None:
2185
+ if sys.platform == "emscripten":
2186
+ return self.on_mouse_release_async(point, button, mods)
2187
+ event_data = {"point": point, "button": button, "mods": mods, **mouse_event_data(self.frame, point)}
2188
+ propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseReleaseEvent, **event_data)
2189
+ if propagate_event is not None and propagate_event is False:
2190
+ return
2191
+
2192
+
2193
+ async def on_mouse_release_async(
2194
+ self,
2195
+ point: Vect3,
2196
+ button: int,
2197
+ mods: int
2198
+ ) -> None:
2199
+ event_data = {"point": point, "button": button, "mods": mods, **mouse_event_data(self.frame, point)}
2200
+ propagate_event = await EVENT_DISPATCHER.dispatch_async(EventType.MouseReleaseEvent, **event_data)
2201
+ if propagate_event is not None and propagate_event is False:
2202
+ return
2203
+
2204
+
2205
+ def on_mouse_scroll(
2206
+ self,
2207
+ point: Vect3,
2208
+ offset: Vect3,
2209
+ x_pixel_offset: float,
2210
+ y_pixel_offset: float
2211
+ ) -> None:
2212
+ if sys.platform == "emscripten":
2213
+ return self.on_mouse_scroll_async(point, offset, x_pixel_offset, y_pixel_offset)
2214
+ event_data = {"point": point, "offset": offset, **mouse_event_data(self.frame, point)}
2215
+ propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseScrollEvent, **event_data)
2216
+ if propagate_event is not None and propagate_event is False:
2217
+ return
2218
+
2219
+ rel_offset = -y_pixel_offset / self.camera.get_pixel_height()
2220
+ if self.invert_zoom_scroll:
2221
+ rel_offset *= -1
2222
+ self.frame.scale(
2223
+ 1 - self.scroll_sensitivity * rel_offset,
2224
+ about_point=point
2225
+ )
2226
+
2227
+
2228
+ async def on_mouse_scroll_async(
2229
+ self,
2230
+ point: Vect3,
2231
+ offset: Vect3,
2232
+ x_pixel_offset: float,
2233
+ y_pixel_offset: float
2234
+ ) -> None:
2235
+ event_data = {"point": point, "offset": offset, **mouse_event_data(self.frame, point)}
2236
+ propagate_event = await EVENT_DISPATCHER.dispatch_async(EventType.MouseScrollEvent, **event_data)
2237
+ if propagate_event is not None and propagate_event is False:
2238
+ return
2239
+
2240
+ rel_offset = -y_pixel_offset / self.camera.get_pixel_height()
2241
+ if self.invert_zoom_scroll:
2242
+ rel_offset *= -1
2243
+ self.frame.scale(
2244
+ 1 - self.scroll_sensitivity * rel_offset,
2245
+ about_point=point
2246
+ )
2247
+
2248
+
2249
+ def on_key_release(
2250
+ self,
2251
+ symbol: int,
2252
+ modifiers: int
2253
+ ) -> None:
2254
+ if sys.platform == "emscripten":
2255
+ return self.on_key_release_async(symbol, modifiers)
2256
+ event_data = {"symbol": symbol, "modifiers": modifiers}
2257
+ propagate_event = EVENT_DISPATCHER.dispatch(EventType.KeyReleaseEvent, **event_data)
2258
+ if propagate_event is not None and propagate_event is False:
2259
+ return
2260
+
2261
+
2262
+ async def on_key_release_async(
2263
+ self,
2264
+ symbol: int,
2265
+ modifiers: int
2266
+ ) -> None:
2267
+ event_data = {"symbol": symbol, "modifiers": modifiers}
2268
+ propagate_event = await EVENT_DISPATCHER.dispatch_async(EventType.KeyReleaseEvent, **event_data)
2269
+ if propagate_event is not None and propagate_event is False:
2270
+ return
2271
+
2272
+
2273
+ def on_key_press(
2274
+ self,
2275
+ symbol: int,
2276
+ modifiers: int
2277
+ ) -> None:
2278
+ if sys.platform == "emscripten":
2279
+ return self.on_key_press_async(symbol, modifiers)
2280
+ try:
2281
+ char = chr(symbol)
2282
+ except OverflowError:
2283
+ log.warning("The value of the pressed key is too large.")
2284
+ return
2285
+
2286
+ event_data = {"symbol": symbol, "modifiers": modifiers}
2287
+ propagate_event = EVENT_DISPATCHER.dispatch(EventType.KeyPressEvent, **event_data)
2288
+ if propagate_event is not None and propagate_event is False:
2289
+ return
2290
+
2291
+ if char == manim_config.key_bindings.reset:
2292
+ self.play(self.camera.frame.animate.to_default_state(), register=False)
2293
+ elif char == "z" and (modifiers & Mods.CTRL_OR_CMD) and (modifiers & Mods.SHIFT):
2294
+ self.redo()
2295
+ elif char == "z" and (modifiers & Mods.CTRL_OR_CMD):
2296
+ self.undo()
2297
+ elif char == "g" and (modifiers & Mods.SHIFT):
2298
+ self.toggle_safe_zones()
2299
+ # command + q
2300
+ elif char == manim_config.key_bindings.quit and (modifiers & Mods.CTRL_OR_CMD):
2301
+ self.quit_interaction = True
2302
+ # Space or right arrow
2303
+ elif char == " " or symbol == Keys.RIGHT:
2304
+ self.hold_on_wait = False
2305
+
2306
+
2307
+ async def on_key_press_async(
2308
+ self,
2309
+ symbol: int,
2310
+ modifiers: int
2311
+ ) -> None:
2312
+ try:
2313
+ char = chr(symbol)
2314
+ except OverflowError:
2315
+ log.warning("The value of the pressed key is too large.")
2316
+ return
2317
+
2318
+ event_data = {"symbol": symbol, "modifiers": modifiers}
2319
+ propagate_event = await EVENT_DISPATCHER.dispatch_async(EventType.KeyPressEvent, **event_data)
2320
+ if propagate_event is not None and propagate_event is False:
2321
+ return
2322
+
2323
+ if char == manim_config.key_bindings.reset:
2324
+ await self.play_async(
2325
+ self.camera.frame.animate.to_default_state(),
2326
+ register=False,
2327
+ )
2328
+ elif char == "z" and (modifiers & Mods.CTRL_OR_CMD) and (modifiers & Mods.SHIFT):
2329
+ self.redo()
2330
+ elif char == "z" and (modifiers & Mods.CTRL_OR_CMD):
2331
+ self.undo()
2332
+ elif char == "g" and (modifiers & Mods.SHIFT):
2333
+ self.toggle_safe_zones()
2334
+ # command + q
2335
+ elif char == manim_config.key_bindings.quit and (modifiers & Mods.CTRL_OR_CMD):
2336
+ self.quit_interaction = True
2337
+ # Space or right arrow
2338
+ elif char == " " or symbol == Keys.RIGHT:
2339
+ self.hold_on_wait = False
2340
+
2341
+
2342
+ def on_resize(self, width: int, height: int) -> None:
2343
+ if sys.platform == "emscripten":
2344
+ return self.on_resize_async(width, height)
2345
+ pass
2346
+
2347
+
2348
+ async def on_resize_async(self, width: int, height: int) -> None:
2349
+ pass
2350
+
2351
+
2352
+ def on_show(self) -> None:
2353
+ pass
2354
+
2355
+ def on_hide(self) -> None:
2356
+ pass
2357
+
2358
+ def on_close(self) -> None:
2359
+ if sys.platform == "emscripten":
2360
+ return self.on_close_async()
2361
+ pass
2362
+
2363
+
2364
+ async def on_close_async(self) -> None:
2365
+ pass
2366
+
2367
+
2368
+ def focus(self) -> None:
2369
+ """
2370
+ Puts focus on the DataCut window.
2371
+ """
2372
+ if not self.window:
2373
+ return
2374
+ self.window.focus()
2375
+
2376
+ def set_shadow_map_size(self, size: int) -> Scene:
2377
+ """Sharper shadows over a big scene, see Camera.set_shadow_map_size"""
2378
+ self.camera.set_shadow_map_size(size)
2379
+ return self
2380
+
2381
+ def set_environment(self, image=None, intensity: float = 1.0, rotation: float = 0.0) -> Scene:
2382
+ """
2383
+ Surroundings for Mesh3D to reflect and be lit by from all round, as an
2384
+ equirectangular image, the sky at the top and the ground at the bottom, see
2385
+ mobject.materials: a file, a PIL image or an array, or gradient_environment(...).
2386
+ Shiny and metallic meshes mirror it, blurred as they are rough; every mesh takes some
2387
+ of its light. None takes it away.
2388
+
2389
+ self.set_environment("studio.hdr.png", intensity=1.2)
2390
+ self.set_environment(gradient_environment(zenith="#334466", ground="#221811"))
2391
+ """
2392
+ self.camera.set_environment(image, intensity, rotation)
2393
+ return self
2394
+
2395
+ def set_background_color(self, background_color, background_opacity=1) -> None:
2396
+ self.camera.background_rgba = list(color_to_rgba(
2397
+ background_color, background_opacity
2398
+ ))
2399
+
2400
+ # Full-frame post-processing effects (delegated to self.camera)
2401
+ def add_vfx(self, *effects) -> Scene:
2402
+ self.camera.add_vfx(*effects)
2403
+ return self
2404
+
2405
+ def remove_vfx(self, effect_type_or_name=None) -> Scene:
2406
+ self.camera.remove_vfx(effect_type_or_name)
2407
+ return self
2408
+
2409
+ def clear_vfx(self) -> Scene:
2410
+ self.camera.clear_vfx()
2411
+ return self
2412
+
2413
+ def has_vfx(self) -> bool:
2414
+ return self.camera.has_vfx()
2415
+
2416
+ def get_vfx_list(self) -> list:
2417
+ return self.camera.get_vfx_list()
2418
+
2419
+ add_post_process = add_vfx
2420
+ remove_post_process = remove_vfx
2421
+ clear_post_process = clear_vfx
2422
+ has_post_process = has_vfx
2423
+ get_post_process_list = get_vfx_list
2424
+
2425
+ def set_mask(
2426
+ self,
2427
+ mask: Mobject,
2428
+ invert: bool = False,
2429
+ use_luminance: bool = False,
2430
+ mode: str = "intersect",
2431
+ ) -> Scene:
2432
+ self.camera.set_mask(mask, invert=invert, use_luminance=use_luminance, mode=mode)
2433
+ return self
2434
+
2435
+ def add_mask(
2436
+ self,
2437
+ mask: Mobject,
2438
+ invert: bool = False,
2439
+ use_luminance: bool = False,
2440
+ mode: str = "intersect",
2441
+ ) -> Scene:
2442
+ self.camera.add_mask(mask, invert=invert, use_luminance=use_luminance, mode=mode)
2443
+ return self
2444
+
2445
+ def remove_mask(self, mask: Mobject | None = None) -> Scene:
2446
+ self.camera.remove_mask(mask)
2447
+ return self
2448
+
2449
+ def set_gaussian_blur(self, radius: float = 12.0, downscale: float = 1.0) -> Scene:
2450
+ self.camera.set_gaussian_blur(radius=radius, downscale=downscale)
2451
+ return self
2452
+
2453
+ def set_grain(self, intensity: float = 0.08, speed: float = 24.0, colored: bool = False) -> Scene:
2454
+ self.camera.set_grain(intensity=intensity, speed=speed, colored=colored)
2455
+ return self
2456
+
2457
+ def set_vignette(
2458
+ self,
2459
+ radius: float = 0.5,
2460
+ softness: float = 0.45,
2461
+ intensity: float = 0.7,
2462
+ center=(0.5, 0.5),
2463
+ color=None,
2464
+ keep_circular: bool = True,
2465
+ ) -> Scene:
2466
+ self.camera.set_vignette(
2467
+ radius=radius, softness=softness, intensity=intensity,
2468
+ center=center, color=color, keep_circular=keep_circular,
2469
+ )
2470
+ return self
2471
+
2472
+ def set_drop_shadow(
2473
+ self,
2474
+ offset=(6.0, -6.0),
2475
+ radius: float = 12.0,
2476
+ opacity: float = 0.75,
2477
+ color=None,
2478
+ shadow_only: bool = False,
2479
+ ) -> Scene:
2480
+ self.camera.set_drop_shadow(
2481
+ offset=offset, radius=radius, opacity=opacity,
2482
+ color=color, shadow_only=shadow_only,
2483
+ )
2484
+ return self
2485
+
2486
+ def set_liquid_glass(self, **kwargs) -> Scene:
2487
+ self.camera.set_liquid_glass(**kwargs)
2488
+ return self
2489
+
2490
+ def set_glow(
2491
+ self,
2492
+ radius: float = 30.0,
2493
+ intensity: float = 1.5,
2494
+ threshold: float = 0.0,
2495
+ softness: float = 0.5,
2496
+ color=None,
2497
+ ) -> Scene:
2498
+ self.camera.set_glow(
2499
+ radius=radius, intensity=intensity, threshold=threshold,
2500
+ softness=softness, color=color,
2501
+ )
2502
+ return self
2503
+
2504
+ def set_glitch(
2505
+ self,
2506
+ intensity: float = 0.6,
2507
+ speed: float = 8.0,
2508
+ slice_height: float = 16.0,
2509
+ ) -> Scene:
2510
+ self.camera.set_glitch(intensity=intensity, speed=speed, slice_height=slice_height)
2511
+ return self
2512
+
2513
+ def set_chromatic_aberration(self, offset: float = 0.02) -> Scene:
2514
+ self.camera.set_chromatic_aberration(offset=offset)
2515
+ return self
2516
+
2517
+ def set_motion_blur(
2518
+ self,
2519
+ direction=None,
2520
+ strength: float = 1.0,
2521
+ auto_direction: bool | None = None,
2522
+ max_blur: float = 0.25,
2523
+ ) -> Scene:
2524
+ self.camera.set_motion_blur(
2525
+ direction=direction, strength=strength,
2526
+ auto_direction=auto_direction, max_blur=max_blur,
2527
+ )
2528
+ return self
2529
+
2530
+ def set_zoom_blur(
2531
+ self,
2532
+ strength: float = 1.0,
2533
+ center=None,
2534
+ uv_center=None,
2535
+ decay: float = 0.98,
2536
+ mode: str = "auto",
2537
+ auto_scale: bool = True,
2538
+ max_blur: float = 0.45,
2539
+ ) -> Scene:
2540
+ self.camera.set_zoom_blur(
2541
+ strength=strength, center=center, uv_center=uv_center,
2542
+ decay=decay, mode=mode, auto_scale=auto_scale, max_blur=max_blur,
2543
+ )
2544
+ return self
2545
+
2546
+ def set_custom_vfx(self, fragment_wgsl: str, uniforms=None, **kwargs) -> Scene:
2547
+ self.camera.set_custom_vfx(fragment_wgsl, uniforms=uniforms, **kwargs)
2548
+ return self
2549
+
2550
+
2551
+ # The kinds of attribute SceneState compares and puts back beside a mobject's arrays
2552
+ SIMPLE_ATTRIBUTE_TYPES = (bool, int, float, complex, str, tuple, np.ndarray, np.generic)
2553
+ # Not state but what is worked out from it and kept, which putting back would leave out of step
2554
+ # with what it was worked out from. Private attributes are left alone for the same reason.
2555
+ DERIVED_ATTRIBUTES = {"view_matrix", "id4x4", "opaque", "opaque_version", "skip_box_interpolation"}
2556
+
2557
+
2558
+ class SceneState():
2559
+ def __init__(
2560
+ self,
2561
+ scene: Scene,
2562
+ ignore: list[Mobject] | None = None,
2563
+ previous: SceneState | None = None,
2564
+ ):
2565
+ self.time = scene.time
2566
+ self.num_plays = scene.num_plays
2567
+ self.mobjects_to_copies = OrderedDict.fromkeys(scene.mobjects)
2568
+ if ignore:
2569
+ for mob in ignore:
2570
+ self.mobjects_to_copies.pop(mob, None)
2571
+
2572
+ # A mobject unchanged since the previous state, the last undo unless another is
2573
+ # given, shares its copy rather than being copied again
2574
+ if previous is None and scene.undo_stack:
2575
+ previous = scene.undo_stack[-1]
2576
+ last_m2c = previous.mobjects_to_copies if previous is not None else dict()
2577
+ for mob in self.mobjects_to_copies:
2578
+ # If it hasn't changed since the last state, just point to the
2579
+ # same copy as before
2580
+ if mob in last_m2c:
2581
+ prev_copy = last_m2c[mob]
2582
+ if self.unchanged(mob, prev_copy):
2583
+ self.mobjects_to_copies[mob] = prev_copy
2584
+ continue
2585
+ shared = self._copy_sharing_data(mob, prev_copy)
2586
+ if shared is not None:
2587
+ self.mobjects_to_copies[mob] = shared
2588
+ continue
2589
+ mob_copy = mob.copy()
2590
+ self._tag_copy(mob, mob_copy)
2591
+ self.mobjects_to_copies[mob] = mob_copy
2592
+
2593
+ def __eq__(self, state: SceneState):
2594
+ return all((
2595
+ self.time == state.time,
2596
+ self.num_plays == state.num_plays,
2597
+ self.mobjects_to_copies == state.mobjects_to_copies
2598
+ ))
2599
+
2600
+ def mobjects_match(self, state: SceneState):
2601
+ return self.mobjects_to_copies == state.mobjects_to_copies
2602
+
2603
+ def n_changes(self, state: SceneState):
2604
+ m2c = state.mobjects_to_copies
2605
+ return sum(
2606
+ 1 - int(mob in m2c and mob.looks_identical(m2c[mob]))
2607
+ for mob in self.mobjects_to_copies
2608
+ )
2609
+
2610
+ def restore_scene(self, scene: Scene):
2611
+ scene.time = self.time
2612
+ scene.num_plays = self.num_plays
2613
+ scene.mobjects = [
2614
+ self.restore_mobject(mob, mob_copy)
2615
+ for mob, mob_copy in self.mobjects_to_copies.items()
2616
+ ]
2617
+ # What keeps a clock outside its arrays, the scene a VideoMobject plays, goes to
2618
+ # where the state has it
2619
+ for mob in scene.mobjects:
2620
+ for sm in mob.get_family():
2621
+ hook = getattr(sm, "_on_state_restored", None)
2622
+ if hook is not None:
2623
+ hook()
2624
+
2625
+ @staticmethod
2626
+ def _simple_attributes(mob: Mobject) -> dict:
2627
+ """
2628
+ What a mobject holds of its own beside its arrays, and which become leaves alone: a
2629
+ light's intensity, a decimal number's number, a mesh's time, a tracker's value
2630
+ """
2631
+ return {
2632
+ key: value for key, value in mob.__dict__.items()
2633
+ if isinstance(value, SIMPLE_ATTRIBUTE_TYPES)
2634
+ and not key.startswith("_") and key not in DERIVED_ATTRIBUTES
2635
+ }
2636
+
2637
+ @staticmethod
2638
+ def _tag_copy(mob: Mobject, mob_copy: Mobject) -> None:
2639
+ for sm, sm_copy in zip(mob.get_family(), mob_copy.get_family()):
2640
+ sm_copy._state_data_ver = (id(sm.data), sm.data.version)
2641
+ sm_copy._state_unif_ver = (id(sm.uniforms), sm.uniforms.version)
2642
+ sm_copy._state_built_key = getattr(sm, "_built_key", None)
2643
+
2644
+ @staticmethod
2645
+ def _shareable_textures(mob: Mobject) -> bool:
2646
+ return all(src.copy() is src for src in mob.textures.values())
2647
+
2648
+ @classmethod
2649
+ def _copy_sharing_data(cls, mob: Mobject, prev_copy: Mobject) -> Mobject | None:
2650
+ """
2651
+ Fast snapshot copy when a mobject's family structure is unchanged since `prev_copy`:
2652
+ each submobject whose vertex `data` has not changed (e.g. a heavy Mesh3D moved via
2653
+ `set_transform`) shares immutable `data`, `source`, and `textures`, while only
2654
+ submobjects whose points actually changed copy their `data`.
2655
+ """
2656
+ fam1 = mob.get_family()
2657
+ fam_prev = prev_copy.get_family()
2658
+ if len(fam1) != len(fam_prev):
2659
+ return None
2660
+ sentinel = object()
2661
+ for m1, mp in zip(fam1, fam_prev):
2662
+ if (
2663
+ type(m1) is not type(mp)
2664
+ or bool(getattr(m1, "_vfx_effects", None))
2665
+ or bool(getattr(mp, "_vfx_effects", None))
2666
+ or not cls._shareable_textures(m1)
2667
+ or getattr(m1, "_built_key", None) != getattr(mp, "_state_built_key", sentinel)
2668
+ ):
2669
+ return None
2670
+
2671
+ clones = []
2672
+ for m1, mp in zip(fam1, fam_prev):
2673
+ c = copy.copy(m1)
2674
+ c.parents = []
2675
+ c.target = None
2676
+ c.saved_state = None
2677
+ same_data = (id(m1.data), m1.data.version) == getattr(mp, "_state_data_ver", None)
2678
+ c.data = mp.data if same_data else m1.data.copy()
2679
+ if not same_data and hasattr(m1, "source"):
2680
+ c.source = m1.source.copy()
2681
+ c.uniforms = m1.uniforms.copy()
2682
+ c.bounding_box = m1.bounding_box.copy()
2683
+ c.textures = mp.textures
2684
+ c.updaters = list(m1.updaters)
2685
+ for key, val in cls._simple_attributes(m1).items():
2686
+ if isinstance(val, np.ndarray):
2687
+ setattr(c, key, val.copy())
2688
+ if hasattr(m1, "_transform") and m1._transform is not None:
2689
+ c._transform = m1._transform.copy()
2690
+ c._state_data_ver = (id(m1.data), m1.data.version)
2691
+ c._state_unif_ver = (id(m1.uniforms), m1.uniforms.version)
2692
+ c._state_built_key = getattr(m1, "_built_key", None)
2693
+ clones.append(c)
2694
+
2695
+ id_to_clone = {id(m1): c for m1, c in zip(fam1, clones)}
2696
+ for m1, c in zip(fam1, clones):
2697
+ c.submobjects = [id_to_clone[id(sm)] for sm in m1.submobjects]
2698
+ for sm in c.submobjects:
2699
+ sm.parents = [c]
2700
+ c.family = [id_to_clone[id(sm)] for sm in m1.get_family()]
2701
+ for attr, val in m1.__dict__.items():
2702
+ if isinstance(val, Mobject) and val is not m1:
2703
+ mapped = id_to_clone.get(id(val))
2704
+ if mapped is not None:
2705
+ setattr(c, attr, mapped)
2706
+ for vfx_attr in ("_vfx_group", "_vfx_local"):
2707
+ if hasattr(m1, vfx_attr):
2708
+ val = getattr(m1, vfx_attr)
2709
+ setattr(c, vfx_attr, id_to_clone.get(id(val), val))
2710
+ return clones[0]
2711
+
2712
+ @classmethod
2713
+ def unchanged(cls, mob: Mobject, mob_copy: Mobject) -> bool:
2714
+ """Whether mob is still exactly as mob_copy has it"""
2715
+ fam1 = mob.get_family()
2716
+ fam2 = mob_copy.get_family()
2717
+ if len(fam1) != len(fam2):
2718
+ return False
2719
+ for m1, m2 in zip(fam1, fam2):
2720
+ if (
2721
+ type(m1) is not type(m2)
2722
+ or len(m1.updaters) != len(m2.updaters)
2723
+ or m1.updating_suspended != m2.updating_suspended
2724
+ ):
2725
+ return False
2726
+ if (id(m1.data), m1.data.version) != getattr(m2, "_state_data_ver", None):
2727
+ if m1.data.array.dtype != m2.data.array.dtype or not np.array_equal(m1.data.array, m2.data.array):
2728
+ return False
2729
+ if (id(m1.uniforms), m1.uniforms.version) != getattr(m2, "_state_unif_ver", None):
2730
+ if m1.uniforms.array.dtype != m2.uniforms.array.dtype or not np.array_equal(m1.uniforms.array, m2.uniforms.array):
2731
+ return False
2732
+ attrs1 = cls._simple_attributes(m1)
2733
+ attrs2 = cls._simple_attributes(m2)
2734
+ if attrs1.keys() != attrs2.keys():
2735
+ return False
2736
+ for key, v1 in attrs1.items():
2737
+ v2 = attrs2[key]
2738
+ if isinstance(v1, np.ndarray) or isinstance(v2, np.ndarray):
2739
+ if not (isinstance(v1, np.ndarray) and isinstance(v2, np.ndarray)):
2740
+ return False
2741
+ if v1.shape != v2.shape or not np.array_equal(v1, v2):
2742
+ return False
2743
+ elif type(v1) is not type(v2) or not bool(v1 == v2):
2744
+ return False
2745
+ return True
2746
+
2747
+ @classmethod
2748
+ def restore_mobject(cls, mob: Mobject, mob_copy: Mobject) -> Mobject:
2749
+ """Puts mob back as mob_copy has it, exactly"""
2750
+ if cls.unchanged(mob, mob_copy):
2751
+ return mob
2752
+ fam1 = mob.get_family()
2753
+ fam2 = mob_copy.get_family()
2754
+ sentinel = object()
2755
+ if len(fam1) == len(fam2) and all(
2756
+ type(m1) is type(m2)
2757
+ and not bool(getattr(m1, "_vfx_effects", None))
2758
+ and not bool(getattr(m2, "_vfx_effects", None))
2759
+ and cls._shareable_textures(m2)
2760
+ and getattr(m1, "_built_key", None) == getattr(m2, "_state_built_key", sentinel)
2761
+ for m1, m2 in zip(fam1, fam2)
2762
+ ):
2763
+ for sm, sm_copy in zip(fam1, fam2):
2764
+ if (id(sm.data), sm.data.version) != getattr(sm_copy, "_state_data_ver", None):
2765
+ if (
2766
+ len(sm.data) != len(sm_copy.data)
2767
+ or sm.data.dtype != sm_copy.data.dtype
2768
+ or not np.array_equal(sm.data.array, sm_copy.data.array)
2769
+ ):
2770
+ sm.set_data(sm_copy.data)
2771
+ sm.data[:] = sm_copy.data.array
2772
+ sm_copy._state_data_ver = (id(sm.data), sm.data.version)
2773
+ if (id(sm.uniforms), sm.uniforms.version) != getattr(sm_copy, "_state_unif_ver", None):
2774
+ sm.set_uniforms(sm_copy.uniforms)
2775
+ sm_copy._state_unif_ver = (id(sm.uniforms), sm.uniforms.version)
2776
+ sm.bounding_box[:] = sm_copy.bounding_box
2777
+ sm._needs_new_bounding_box = sm_copy._needs_new_bounding_box
2778
+ sm.pointlike_uniform_keys = sm_copy.pointlike_uniform_keys
2779
+ sm.shader_file = sm_copy.shader_file
2780
+ sm.texture_filter = sm_copy.texture_filter
2781
+ sm.depth_test = sm_copy.depth_test
2782
+ sm.updating_suspended = sm_copy.updating_suspended
2783
+ sm.updaters = list(sm_copy.updaters)
2784
+ for key, value in cls._simple_attributes(sm_copy).items():
2785
+ setattr(sm, key, value.copy() if isinstance(value, np.ndarray) else value)
2786
+ if hasattr(sm_copy, "_transform"):
2787
+ sm._transform = None if sm_copy._transform is None else sm_copy._transform.copy()
2788
+ return mob
2789
+
2790
+ mob.become(mob_copy, match_updaters=True)
2791
+ for sm, sm_copy in zip(mob.get_family(), mob_copy.get_family()):
2792
+ for key, value in cls._simple_attributes(sm_copy).items():
2793
+ setattr(sm, key, value.copy() if isinstance(value, np.ndarray) else value)
2794
+ # Whether updaters were held off, as an animation under way holds off those of
2795
+ # what it moves, which become leaves as it was
2796
+ sm.updating_suspended = sm_copy.updating_suspended
2797
+ # Exactly the data kept, what become works out again from the points included:
2798
+ # a partly drawn path's subpath ranges are blended rather than found from its
2799
+ # points, see VMobject.set_subpath_range
2800
+ if len(sm.data) == len(sm_copy.data) and sm.data.dtype == sm_copy.data.dtype:
2801
+ if not np.array_equal(sm.data.array, sm_copy.data.array):
2802
+ sm.data[:] = sm_copy.data.array
2803
+ cls._tag_copy(mob, mob_copy)
2804
+ return mob
2805
+
2806
+
2807
+ class EndScene(Exception):
2808
+ pass
2809
+
2810
+
2811
+ class ReloadScene(Exception):
2812
+ """
2813
+ The scene's file was saved: the scene is to be made again from it in the same window,
2814
+ carrying on from resume_time, and at resume_view in its past if that was being looked at,
2815
+ see Scene.check_hot_reload and datacut.__main__.run_scenes
2816
+ """
2817
+
2818
+ def __init__(self, scene: Scene, resume_time: float | None = None, resume_view: float | None = None):
2819
+ super().__init__("reload")
2820
+ self.scene = scene
2821
+ self.resume_time = resume_time
2822
+ self.resume_view = resume_view
2823
+
2824
+
2825
+ class ThreeDScene(Scene):
2826
+ samples = 4
2827
+ default_frame_orientation = (-30, 70)
2828
+ always_depth_test = True
2829
+
2830
+ def add(self, *mobjects: Mobject, set_depth_test: bool = True, perp_stroke: bool = True, at: float | None = None):
2831
+ if at is not None and float(at) > self.get_time():
2832
+ self.schedule(
2833
+ float(at),
2834
+ lambda: self.add(*mobjects, set_depth_test=set_depth_test, perp_stroke=perp_stroke),
2835
+ )
2836
+ return self
2837
+ for mob in mobjects:
2838
+ # Asked of each member of the family in turn, rather than of what holds them.
2839
+ # A group has a say of its own on being fixed in frame, which is nothing to do
2840
+ # with what it holds, and animations wrap what they are given in a fresh one,
2841
+ # so text fixed in frame would otherwise find itself depth tested for the
2842
+ # length of a FadeTransform, and vanish behind whatever it was written over.
2843
+ if set_depth_test and self.always_depth_test:
2844
+ for sm in mob.get_family():
2845
+ if not sm.is_fixed_in_frame():
2846
+ sm.apply_depth_test(recurse=False)
2847
+ if isinstance(mob, VMobject) and mob.has_stroke() and perp_stroke:
2848
+ mob.set_flat_stroke(False)
2849
+ super().add(*mobjects)