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
@@ -0,0 +1,956 @@
1
+ from __future__ import annotations
2
+
3
+ # What the Visual Editor files this module's classes under
4
+ __editor_category__ = 'Specialized'
5
+
6
+ import itertools
7
+ import math
8
+ from dataclasses import dataclass
9
+
10
+ import numpy as np
11
+
12
+ from datacut.animation.animation import Animation
13
+ from datacut.animation.composition import LaggedStart
14
+ from datacut.animation.transform import Restore
15
+ from datacut.constants import BLACK, WHITE
16
+ from datacut.mobject.geometry import Circle
17
+ from datacut.mobject.types.vectorized_mobject import VGroup
18
+ from datacut.utils.rate_functions import linear
19
+ from datacut.typing import Duration, UnsignedFloat, UnsignedInt
20
+
21
+ from typing import TYPE_CHECKING
22
+
23
+ if TYPE_CHECKING:
24
+ from datacut.typing import Annotated, Example, Vect3
25
+ from datacut.typing import Duration, Proportion, StrokeWidth
26
+ from datacut.typing import ManimColor
27
+
28
+
29
+ class Broadcast(LaggedStart):
30
+ def __init__(
31
+ self,
32
+ focal_point: Annotated[Vect3, Example('ORIGIN')],
33
+ small_radius: UnsignedFloat = 0.0,
34
+ big_radius: UnsignedFloat = 5.0,
35
+ n_circles: UnsignedInt = 5,
36
+ start_stroke_width: StrokeWidth = 8.0,
37
+ color: ManimColor = WHITE,
38
+ run_time: Duration = 3.0,
39
+ lag_ratio: Proportion = 0.2,
40
+ remover: bool = True,
41
+ **kwargs
42
+ ):
43
+ self.focal_point = focal_point
44
+ self.small_radius = small_radius
45
+ self.big_radius = big_radius
46
+ self.n_circles = n_circles
47
+ self.start_stroke_width = start_stroke_width
48
+ self.color = color
49
+
50
+ circles = VGroup()
51
+ for x in range(n_circles):
52
+ circle = Circle(
53
+ radius=big_radius,
54
+ stroke_color=BLACK,
55
+ stroke_width=0,
56
+ )
57
+ circle.add_updater(lambda c: c.move_to(focal_point))
58
+ circle.save_state()
59
+ circle.set_width(small_radius * 2)
60
+ circle.set_stroke(color, start_stroke_width)
61
+ circles.add(circle)
62
+ super().__init__(
63
+ *map(Restore, circles),
64
+ run_time=run_time,
65
+ lag_ratio=lag_ratio,
66
+ remover=remover,
67
+ **kwargs
68
+ )
69
+
70
+ editor_thumbnail = (
71
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 24">'
72
+ '<path d="M10 12Q10 12 10 11Q9 11 9 11Q9 11 9 11Q8 10 8 10Q8 10 8 11Q7 11 7 11Q7 11 7 11Q7 12 7 12Q7 12 7 13Q7 13 7 13Q7 13 8 13Q8 14 8 14Q8 14 9 13Q9 13 9 13Q9 13 10 13Q10 12 10 12Z" fill="none" stroke="#BFBFBF" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
73
+ '<path d="M8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Z" fill="none" stroke="#F7F7F7" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
74
+ '<path d="M8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Z" fill="none" stroke="#FFFFFF" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
75
+ '<path d="M8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Z" fill="none" stroke="#FFFFFF" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
76
+ '<path d="M8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Q8 12 8 12Z" fill="none" stroke="#FFFFFF" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
77
+ '<path d="M30 12Q30 11 30 10Q29 9 28 8Q27 7 26 6Q25 6 24 6Q23 6 22 6Q21 7 20 8Q19 9 18 10Q18 11 18 12Q18 13 18 14Q19 15 20 16Q21 17 22 18Q23 18 24 18Q25 18 26 18Q27 17 28 16Q29 15 30 14Q30 13 30 12Z" fill="none" stroke="#000000" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
78
+ '<path d="M30 12Q30 11 29 10Q29 9 28 8Q27 7 26 7Q25 6 24 6Q23 6 22 7Q21 7 20 8Q19 9 19 10Q18 11 18 12Q18 13 19 14Q19 15 20 16Q21 17 22 17Q23 18 24 18Q25 18 26 17Q27 17 28 16Q29 15 29 14Q30 13 30 12Z" fill="none" stroke="#111111" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
79
+ '<path d="M28 12Q28 11 28 10Q27 10 27 9Q26 9 26 8Q25 8 24 8Q23 8 22 8Q22 9 21 9Q21 10 20 10Q20 11 20 12Q20 13 20 14Q21 14 21 15Q22 15 22 16Q23 16 24 16Q25 16 26 16Q26 15 27 15Q27 14 28 14Q28 13 28 12Z" fill="none" stroke="#555555" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
80
+ '<path d="M26 12Q26 12 26 11Q26 11 25 11Q25 10 25 10Q24 10 24 10Q24 10 23 10Q23 10 23 11Q22 11 22 11Q22 12 22 12Q22 12 22 13Q22 13 23 13Q23 14 23 14Q24 14 24 14Q24 14 25 14Q25 14 25 13Q26 13 26 13Q26 12 26 12Z" fill="none" stroke="#B2B2B2" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
81
+ '<path d="M24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Q24 12 24 12Z" fill="none" stroke="#F2F2F2" stroke-opacity="1.00" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
82
+ '<path d="M46 12Q46 11 46 10Q45 9 44 8Q43 7 42 6Q41 6 40 6Q39 6 38 6Q36 7 36 8Q35 9 34 10Q34 11 34 12Q34 13 34 14Q35 15 36 16Q36 17 38 18Q39 18 40 18Q41 18 42 18Q43 17 44 16Q45 15 46 14Q46 13 46 12Z" fill="none" stroke="#888888" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
83
+ '<path d="M46 12Q46 11 46 10Q45 9 44 8Q43 7 42 6Q41 6 40 6Q39 6 38 6Q36 7 36 8Q35 9 34 10Q34 11 34 12Q34 13 34 14Q35 15 36 16Q36 17 38 18Q39 18 40 18Q41 18 42 18Q43 17 44 16Q45 15 46 14Q46 13 46 12Z" fill="none" stroke="#888888" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
84
+ '<path d="M46 12Q46 11 46 10Q45 9 44 8Q43 7 42 6Q41 6 40 6Q39 6 38 6Q36 7 36 8Q35 9 34 10Q34 11 34 12Q34 13 34 14Q35 15 36 16Q36 17 38 18Q39 18 40 18Q41 18 42 18Q43 17 44 16Q45 15 46 14Q46 13 46 12Z" fill="none" stroke="#888888" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
85
+ '<path d="M46 12Q46 11 46 10Q45 9 44 8Q43 7 42 6Q41 6 40 6Q39 6 38 6Q36 7 36 8Q35 9 34 10Q34 11 34 12Q34 13 34 14Q35 15 36 16Q36 17 38 18Q39 18 40 18Q41 18 42 18Q43 17 44 16Q45 15 46 14Q46 13 46 12Z" fill="none" stroke="#888888" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
86
+ '<path d="M46 12Q46 11 46 10Q45 9 44 8Q43 7 42 6Q41 6 40 6Q39 6 38 6Q36 7 36 8Q35 9 34 10Q34 11 34 12Q34 13 34 14Q35 15 36 16Q36 17 38 18Q39 18 40 18Q41 18 42 18Q43 17 44 16Q45 15 46 14Q46 13 46 12Z" fill="none" stroke="#888888" stroke-width="1.3" fill-rule="evenodd" stroke-linejoin="round"/>'
87
+ '</svg>'
88
+ )
89
+
90
+
91
+ # ----------------------------------------------------------------------
92
+ # Quaternions (w, x, y, z)
93
+ # ----------------------------------------------------------------------
94
+
95
+ def _qmul(a, b):
96
+ w1, x1, y1, z1 = a
97
+ w2, x2, y2, z2 = b
98
+ return np.array([
99
+ w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
100
+ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
101
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
102
+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
103
+ ])
104
+
105
+
106
+ def _quat_to_matrix(q):
107
+ w, x, y, z = q
108
+ return np.array([
109
+ [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
110
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
111
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
112
+ ])
113
+
114
+
115
+ def _quat_axis_angle(axis, angle):
116
+ axis = np.asarray(axis, dtype=float)
117
+ axis = axis / np.linalg.norm(axis)
118
+ half = 0.5 * angle
119
+ return np.array([np.cos(half), *(axis * np.sin(half))])
120
+
121
+
122
+ def _slerp(q0, q1, t):
123
+ d = float(np.dot(q0, q1))
124
+ if d < 0.0:
125
+ q1 = -q1
126
+ d = -d
127
+ if d > 0.9995:
128
+ q = q0 + t * (q1 - q0)
129
+ return q / np.linalg.norm(q)
130
+ theta = np.arccos(min(d, 1.0))
131
+ s = np.sin(theta)
132
+ return (np.sin((1 - t) * theta) * q0 + np.sin(t * theta) * q1) / s
133
+
134
+
135
+ def _smoothstep(t):
136
+ t = min(max(t, 0.0), 1.0)
137
+ return t * t * (3.0 - 2.0 * t)
138
+
139
+
140
+ # Signs of the cube's 8 corners, in the fixed order used by the simulation.
141
+ _SIGNS = tuple(itertools.product((-1.0, 1.0), repeat=3))
142
+
143
+
144
+ @dataclass
145
+ class _Throw:
146
+ positions: np.ndarray # (N, 3)
147
+ quaternions: np.ndarray # (N, 4)
148
+ face: int
149
+ settle_time: float # simulated seconds until coming to rest
150
+ yaw_error: float = 0.0 # rotation (rad) corrected at the end
151
+ target_error: float = 0.0 # distance (scene units) corrected at the end
152
+
153
+
154
+ @dataclass
155
+ class _Candidate:
156
+ """Cheap result of a simulation; only "built" if chosen."""
157
+ positions: list
158
+ quats: list
159
+ activity: list
160
+ q: np.ndarray # orientation at rest
161
+ q_flat: np.ndarray # final orientation (flat and aligned)
162
+ x: np.ndarray # center at rest
163
+ face: int
164
+ yaw: float # signed rotation spread over the motion
165
+ residual: np.ndarray | None
166
+ settle_time: float
167
+ yaw_error: float
168
+ target_error: float
169
+
170
+
171
+ class RollDice(Animation):
172
+ """
173
+ Roll of a die with real rigid-body dynamics.
174
+
175
+ What happens in the animation:
176
+
177
+ 1. The die leaves its current position with linear and angular
178
+ velocity (it goes up, spinning, in some direction).
179
+ 2. It flies along a parabola while tumbling.
180
+ 3. It hits the table on a corner: impulse with restitution and
181
+ Coulomb friction (the die bounces and its velocity is
182
+ "eaten up" naturally).
183
+ 4. It bounces, rolls and tips over edges and faces.
184
+ 5. It stops (rest detection) and settles exactly flat on the
185
+ table.
186
+
187
+ Nothing is "scripted": to get `outcome`, different random throws are
188
+ simulated and the first one that naturally ends with that face up
189
+ is played back.
190
+
191
+ Axis convention (manim): Y is up, the table is the plane
192
+ y = ground_y.
193
+
194
+ `faces_pointing` are the LOCAL normals of each face:
195
+
196
+ faces_pointing = {
197
+ 6: OUT, 3: DOWN, 1: IN, 4: UP, 5: LEFT, 2: RIGHT,
198
+ }
199
+
200
+ Units: velocities and gravity are expressed in "die sizes" (per
201
+ second and per second²), so the result looks the same regardless of
202
+ the model's scale. Angular velocities are in rad/s.
203
+
204
+ Positions (scene coordinates; the table is the XZ plane):
205
+
206
+ start_position Where the throw starts (center of the die).
207
+ With 3 values (x, y, z) it also sets the release
208
+ height; with 2 values (x, z) it keeps the die's
209
+ current height. Default: where the die is.
210
+ Note: on the first frame the die appears there.
211
+ target_position Where the die ends up on the table (center).
212
+ Accepts (x, z) or (x, y, z); y is ignored. The
213
+ die is thrown aimed at that point and any small
214
+ remaining error is spread over the motion, just
215
+ like the rotation, so there are no "jerks" at
216
+ the end.
217
+ target_tolerance How much error may remain, in die sizes, before
218
+ a throw is discarded (the remaining error is
219
+ corrected anyway). With `target_position`,
220
+ `launch_direction` is ignored.
221
+
222
+ Performance:
223
+
224
+ - The search for the throw (when building the animation) uses a
225
+ pure-Python scalar simulation, with no numpy per step.
226
+ - Only the chosen throw's full trajectory is "built"; discarded
227
+ ones are evaluated with just a few numbers.
228
+ - During the animation only the incremental transform between
229
+ frames is applied to the mobject (a single pass over its
230
+ points), and nothing is done when the pose doesn't change
231
+ (die already at rest).
232
+
233
+ Example:
234
+
235
+ self.play(
236
+ RollDice(dice, faces_pointing, outcome=5,
237
+ start_position=LEFT * 4,
238
+ target_position=RIGHT * 2 + OUT * 1.5)
239
+ )
240
+ """
241
+
242
+ UP = np.array([0.0, 1.0, 0.0])
243
+ _ZERO = np.zeros(3)
244
+
245
+ SLEEP_TIME = 0.10
246
+ SLEEP_TILT_COS = float(np.cos(np.radians(2.0)))
247
+ BLEND_TIME = 0.18
248
+ CONTACT_ITERATIONS = 10
249
+
250
+ AIR_DAMPING_LINEAR = 0.05
251
+ AIR_DAMPING_ANGULAR = 0.10
252
+ GROUND_DAMPING_LINEAR = 0.6
253
+ GROUND_DAMPING_ANGULAR = 1.2
254
+
255
+ def __init__(
256
+ self,
257
+ dice,
258
+ faces_pointing: dict[int, np.ndarray],
259
+ outcome: int | None = None,
260
+ run_time: Duration = 2.8,
261
+ seed: int | None = None,
262
+
263
+ # Physics (in die sizes)
264
+ gravity: float = 22.0,
265
+ restitution: float = 0.35,
266
+ friction: float = 0.45,
267
+
268
+ # Launch
269
+ launch_direction: np.ndarray | None = None,
270
+ launch_speed_range: tuple[float, float] = (2.0, 5.0),
271
+ vertical_speed_range: tuple[float, float] = (7.5, 10.5),
272
+ angular_speed_range: tuple[float, float] = (8.0, 18.0),
273
+
274
+ # Table and limits
275
+ ground_y: float | None = None,
276
+ max_travel: float | None = None,
277
+
278
+ # Simulation
279
+ max_attempts: int = 400,
280
+ simulation_dt: float = 1.0 / 180.0,
281
+ settle_fraction: float = 0.92,
282
+
283
+ # Final rest pose aligned with the scene axes (multiples of 90°
284
+ # around Y). Throws that already end within `yaw_tolerance_deg`
285
+ # of that alignment are preferred, so the final adjustment is
286
+ # imperceptible.
287
+ snap_yaw: bool = True,
288
+ yaw_tolerance_deg: float = 25.0,
289
+
290
+ # Start and end positions (see docstring)
291
+ start_position: np.ndarray | None = None,
292
+ target_position: np.ndarray | None = None,
293
+ target_tolerance: float = 1.0,
294
+
295
+ **kwargs,
296
+ ):
297
+ self.dice = dice
298
+ self.target_tolerance = float(target_tolerance)
299
+ self.snap_yaw = bool(snap_yaw)
300
+ self.yaw_tolerance_deg = float(yaw_tolerance_deg)
301
+
302
+ self.faces_pointing = {
303
+ int(face): self._normalize(np.asarray(normal, dtype=float))
304
+ for face, normal in faces_pointing.items()
305
+ }
306
+ if len(self.faces_pointing) != 6:
307
+ raise ValueError("`faces_pointing` must contain exactly 6 faces.")
308
+
309
+ self._faces = list(self.faces_pointing.keys())
310
+ self._normals = np.array([self.faces_pointing[f] for f in self._faces])
311
+ self._normal_rows = [tuple(float(c) for c in n) for n in self._normals]
312
+
313
+ self.rng = np.random.default_rng(seed)
314
+
315
+ if outcome is None:
316
+ outcome = int(self.rng.choice(self._faces))
317
+ self.outcome = int(outcome)
318
+ if self.outcome not in self.faces_pointing:
319
+ raise ValueError(f"Face {self.outcome} does not exist in faces_pointing.")
320
+
321
+ self.gravity_in_sizes = float(gravity)
322
+ self.restitution = float(restitution)
323
+ self.friction = float(friction)
324
+ self.launch_speed_range = launch_speed_range
325
+ self.vertical_speed_range = vertical_speed_range
326
+ self.angular_speed_range = angular_speed_range
327
+ self.max_travel = max_travel
328
+ self.max_attempts = int(max_attempts)
329
+ self.simulation_dt = float(simulation_dt)
330
+ self.settle_fraction = float(settle_fraction)
331
+
332
+ if launch_direction is not None:
333
+ d = np.asarray(launch_direction, dtype=float).copy()
334
+ d[1] = 0.0
335
+ if np.linalg.norm(d) < 1e-8:
336
+ raise ValueError("`launch_direction` must have a horizontal component.")
337
+ self.launch_direction = self._normalize(d)
338
+ else:
339
+ self.launch_direction = None
340
+
341
+ # --------------------------------------------------------------
342
+ # Die geometry
343
+ # --------------------------------------------------------------
344
+ self._initial_dice = dice.copy()
345
+ self._initial_center = np.asarray(dice.get_center(), dtype=float)
346
+
347
+ bbox = np.asarray(dice.get_bounding_box(), dtype=float)
348
+ extent = np.abs(bbox[2] - bbox[0])
349
+ self._size = float(np.mean(extent))
350
+ if self._size <= 1e-8:
351
+ raise ValueError("Could not determine the size of the die.")
352
+ self._half = self._size / 2.0
353
+
354
+ self._ground_y = float(bbox[0][1] if ground_y is None else ground_y)
355
+
356
+ # --------------------------------------------------------------
357
+ # Start and target positions
358
+ # --------------------------------------------------------------
359
+ if start_position is None:
360
+ self._start = self._initial_center.copy()
361
+ else:
362
+ sp = np.asarray(start_position, dtype=float).ravel()
363
+ if sp.size == 2:
364
+ self._start = np.array([sp[0], self._initial_center[1], sp[1]])
365
+ elif sp.size == 3:
366
+ self._start = sp.copy()
367
+ else:
368
+ raise ValueError("`start_position` must be (x, z) or (x, y, z).")
369
+
370
+ if target_position is None:
371
+ self._target_xz = None
372
+ else:
373
+ tp = np.asarray(target_position, dtype=float).ravel()
374
+ if tp.size == 2:
375
+ self._target_xz = tp.copy()
376
+ elif tp.size == 3:
377
+ self._target_xz = np.array([tp[0], tp[2]])
378
+ else:
379
+ raise ValueError("`target_position` must be (x, z) or (x, y, z).")
380
+
381
+ # With a target, the travel limit must never prevent reaching it.
382
+ self._travel_limit = self.max_travel
383
+ if self._target_xz is not None and self.max_travel is not None:
384
+ dist = float(np.linalg.norm(self._target_xz - self._start[[0, 2]]))
385
+ self._travel_limit = max(self.max_travel, 1.6 * dist + 2.0 * self._size)
386
+
387
+ # Learn "how far the die travels per unit of horizontal
388
+ # velocity", to aim better on each attempt.
389
+ self._ratios: list[float] = []
390
+ self._last_launch = None
391
+
392
+ # Unit-mass cube: I = m s² / 6 (isotropic).
393
+ self._inv_inertia = 6.0 / (self._size ** 2)
394
+ self._gravity = self.gravity_in_sizes * self._size
395
+ self._rest_threshold = max(
396
+ 0.4 * self._size, 5.0 * self._gravity * self.simulation_dt
397
+ )
398
+
399
+ # --------------------------------------------------------------
400
+ # Find a physical throw that ends on `outcome`
401
+ # --------------------------------------------------------------
402
+ self._throw: _Throw | None = None
403
+ self._time_scale = 1.0
404
+ self._find_throw(run_time)
405
+
406
+ # Pose currently applied to the mobject (for incremental
407
+ # playback).
408
+ self._cur_pos = self._initial_center.copy()
409
+ self._cur_R = np.eye(3)
410
+ self._fused_ok = True
411
+
412
+ kwargs.setdefault("rate_func", linear) # physics is not "smoothed"
413
+ super().__init__(dice, run_time=run_time, **kwargs)
414
+
415
+ # ==================================================================
416
+ # Utilities
417
+ # ==================================================================
418
+
419
+ @staticmethod
420
+ def _normalize(v):
421
+ v = np.asarray(v, dtype=float)
422
+ n = np.linalg.norm(v)
423
+ if n < 1e-12:
424
+ raise ValueError("Cannot normalize a zero-length vector.")
425
+ return v / n
426
+
427
+ # ==================================================================
428
+ # Initial launch state
429
+ # ==================================================================
430
+
431
+ def _flight_ratio(self):
432
+ """Equivalent seconds: total travel / horizontal speed."""
433
+ if not self._ratios:
434
+ return 1.0
435
+ return float(np.clip(np.median(self._ratios[-15:]), 0.3, 3.0))
436
+
437
+ def _initial_velocities(self):
438
+ s = self._size
439
+ self._last_launch = None
440
+
441
+ if self._target_xz is not None:
442
+ delta = self._target_xz - self._start[[0, 2]]
443
+ dist = float(np.linalg.norm(delta))
444
+ if dist > 1e-6:
445
+ base = np.array([delta[0], 0.0, delta[1]]) / dist
446
+ else:
447
+ a = self.rng.uniform(0.0, 2.0 * np.pi)
448
+ base = np.array([np.cos(a), 0.0, np.sin(a)])
449
+
450
+ spread = min(0.15, 0.3 * s / max(dist, 1e-6))
451
+ a = self.rng.uniform(-spread, spread)
452
+ direction = np.array([
453
+ base[0] * np.cos(a) + base[2] * np.sin(a),
454
+ 0.0,
455
+ -base[0] * np.sin(a) + base[2] * np.cos(a),
456
+ ])
457
+ h_speed = dist / self._flight_ratio() * self.rng.uniform(0.85, 1.15)
458
+ self._last_launch = (direction.copy(), h_speed)
459
+ elif self.launch_direction is None:
460
+ a = self.rng.uniform(0.0, 2.0 * np.pi)
461
+ direction = np.array([np.cos(a), 0.0, np.sin(a)])
462
+ h_speed = self.rng.uniform(*self.launch_speed_range) * s
463
+ else:
464
+ a = self.rng.uniform(-0.25, 0.25)
465
+ d = self.launch_direction
466
+ direction = np.array([
467
+ d[0] * np.cos(a) + d[2] * np.sin(a),
468
+ 0.0,
469
+ -d[0] * np.sin(a) + d[2] * np.cos(a),
470
+ ])
471
+ h_speed = self.rng.uniform(*self.launch_speed_range) * s
472
+
473
+ v = direction * h_speed
474
+ v[1] = self.rng.uniform(*self.vertical_speed_range) * s
475
+
476
+ # Spin mostly forward (like a die "rolling" through the air),
477
+ # with some noise on the other axes.
478
+ axis = np.cross(self.UP, direction) + 0.45 * self.rng.normal(size=3)
479
+ axis = self._normalize(axis)
480
+ sign = 1.0 if self.rng.random() < 0.8 else -1.0
481
+ w = axis * sign * self.rng.uniform(*self.angular_speed_range)
482
+
483
+ # Make sure no corner starts sinking into the table.
484
+ if self._start[1] - self._half <= self._ground_y + 1e-6:
485
+ wz, wx = w[2], w[0]
486
+ h = self._half
487
+ lowest = min(wz * (sx * h) - wx * (sz * h) for sx, _, sz in _SIGNS)
488
+ v[1] = max(v[1], -1.05 * lowest)
489
+
490
+ return v, w
491
+
492
+ # ==================================================================
493
+ # Contacts (sequential impulses with Coulomb friction)
494
+ # ==================================================================
495
+
496
+ def _solve_contacts(self, rs, vx, vy, vz, wx, wy, wz):
497
+ """
498
+ `rs` are the center→corner vectors (rx, ry, rz) of the corners
499
+ in contact. Returns the new linear and angular velocities.
500
+ """
501
+ inv_i = self._inv_inertia
502
+ mu = self.friction
503
+ e = self.restitution
504
+ thr = self._rest_threshold
505
+
506
+ contacts = []
507
+ for rx, ry, rz in rs:
508
+ vcn = vy + wz * rx - wx * rz
509
+ bounce = -e * vcn if vcn < -thr else 0.0
510
+ kn = 1.0 + inv_i * (rz * rz + rx * rx)
511
+ kx = 1.0 + inv_i * (rz * rz + ry * ry)
512
+ kz = 1.0 + inv_i * (ry * ry + rx * rx)
513
+ contacts.append([rx, ry, rz, bounce, kn, kx, kz, 0.0, 0.0, 0.0])
514
+
515
+ for _ in range(self.CONTACT_ITERATIONS):
516
+ for c in contacts:
517
+ rx, ry, rz, bounce, kn, kx, kz, jn, jx, jz = c
518
+ max_f = mu * jn
519
+
520
+ # Friction along X
521
+ vcx = vx + wy * rz - wz * ry
522
+ new = min(max(jx - vcx / kx, -max_f), max_f)
523
+ dj, jx = new - jx, new
524
+ vx += dj
525
+ k = inv_i * dj
526
+ wy += k * rz
527
+ wz -= k * ry
528
+
529
+ # Friction along Z
530
+ vcz = vz + wx * ry - wy * rx
531
+ new = min(max(jz - vcz / kz, -max_f), max_f)
532
+ dj, jz = new - jz, new
533
+ vz += dj
534
+ k = inv_i * dj
535
+ wx += k * ry
536
+ wy -= k * rx
537
+
538
+ # Normal
539
+ vcy = vy + wz * rx - wx * rz
540
+ new = max(jn - (vcy - bounce) / kn, 0.0)
541
+ dj, jn = new - jn, new
542
+ vy += dj
543
+ k = inv_i * dj
544
+ wx -= k * rz
545
+ wz += k * rx
546
+
547
+ c[7], c[8], c[9] = jn, jx, jz
548
+
549
+ return vx, vy, vz, wx, wy, wz
550
+
551
+ # ==================================================================
552
+ # Throw simulation (pure scalars, no numpy per step)
553
+ # ==================================================================
554
+
555
+ def _simulate_throw(self, t_limit: float) -> _Candidate | None:
556
+ dt = self.simulation_dt
557
+ half_dt = 0.5 * dt
558
+ size = self._size
559
+ h = self._half
560
+ g = self._gravity
561
+ ground = self._ground_y
562
+ margin = 1e-3 * size
563
+ v_sleep = 0.08 * size
564
+ w_sleep = 0.3
565
+ tilt_cos = self.SLEEP_TILT_COS
566
+ sleep_time = self.SLEEP_TIME
567
+ normals = self._normal_rows
568
+ limit = self._travel_limit
569
+
570
+ lin_air = math.exp(-self.AIR_DAMPING_LINEAR * dt)
571
+ ang_air = math.exp(-self.AIR_DAMPING_ANGULAR * dt)
572
+ lin_gnd = math.exp(-self.GROUND_DAMPING_LINEAR * dt)
573
+ ang_gnd = math.exp(-self.GROUND_DAMPING_ANGULAR * dt)
574
+
575
+ sx0, sy0, sz0 = (float(c) for c in self._start)
576
+ xx, xy, xz = sx0, sy0, sz0
577
+ qw, qx, qy, qz = 1.0, 0.0, 0.0, 0.0
578
+ v0, w0 = self._initial_velocities()
579
+ vx, vy, vz = (float(c) for c in v0)
580
+ wx, wy, wz = (float(c) for c in w0)
581
+
582
+ positions = [(xx, xy, xz)]
583
+ quats = [(qw, qx, qy, qz)]
584
+ activity = [0.0] # "how much it moves" at each step (rad/s + sizes/s)
585
+
586
+ sleep_t0 = None
587
+ asleep = False
588
+
589
+ for step in range(1, int(t_limit / dt) + 1):
590
+ t = step * dt
591
+
592
+ vy -= g * dt
593
+ vx *= lin_air
594
+ vy *= lin_air
595
+ vz *= lin_air
596
+ wx *= ang_air
597
+ wy *= ang_air
598
+ wz *= ang_air
599
+
600
+ xx += vx * dt
601
+ xy += vy * dt
602
+ xz += vz * dt
603
+
604
+ # q += 0.5 dt (0, w) ⊗ q (all components use the previous q)
605
+ dqw = -wx * qx - wy * qy - wz * qz
606
+ dqx = wx * qw + wy * qz - wz * qy
607
+ dqy = -wx * qz + wy * qw + wz * qx
608
+ dqz = wx * qy - wy * qx + wz * qw
609
+ qw += half_dt * dqw
610
+ qx += half_dt * dqx
611
+ qy += half_dt * dqy
612
+ qz += half_dt * dqz
613
+ n = math.sqrt(qw * qw + qx * qx + qy * qy + qz * qz)
614
+ qw /= n
615
+ qx /= n
616
+ qy /= n
617
+ qz /= n
618
+
619
+ # Y row of the rotation matrix (corner heights).
620
+ r10 = 2.0 * (qx * qy + qz * qw)
621
+ r11 = 1.0 - 2.0 * (qx * qx + qz * qz)
622
+ r12 = 2.0 * (qy * qz - qx * qw)
623
+
624
+ low = xy - ground - h * (abs(r10) + abs(r11) + abs(r12))
625
+ grounded = low < margin
626
+
627
+ if grounded:
628
+ r00 = 1.0 - 2.0 * (qy * qy + qz * qz)
629
+ r01 = 2.0 * (qx * qy - qz * qw)
630
+ r02 = 2.0 * (qx * qz + qy * qw)
631
+ r20 = 2.0 * (qx * qz - qy * qw)
632
+ r21 = 2.0 * (qy * qz + qx * qw)
633
+ r22 = 1.0 - 2.0 * (qx * qx + qy * qy)
634
+
635
+ rs = []
636
+ for sx, sy, sz in _SIGNS:
637
+ ry = h * (sx * r10 + sy * r11 + sz * r12)
638
+ if xy + ry - ground < margin:
639
+ rs.append((
640
+ h * (sx * r00 + sy * r01 + sz * r02),
641
+ ry,
642
+ h * (sx * r20 + sy * r21 + sz * r22),
643
+ ))
644
+
645
+ vx, vy, vz, wx, wy, wz = self._solve_contacts(
646
+ rs, vx, vy, vz, wx, wy, wz
647
+ )
648
+ if low < 0.0:
649
+ xy -= low
650
+ vx *= lin_gnd
651
+ vy *= lin_gnd
652
+ vz *= lin_gnd
653
+ wx *= ang_gnd
654
+ wy *= ang_gnd
655
+ wz *= ang_gnd
656
+
657
+ vspeed = math.sqrt(vx * vx + vy * vy + vz * vz)
658
+ wspeed = math.sqrt(wx * wx + wy * wy + wz * wz)
659
+
660
+ positions.append((xx, xy, xz))
661
+ quats.append((qw, qx, qy, qz))
662
+ activity.append(wspeed + vspeed / size)
663
+
664
+ if limit is not None and math.hypot(xx - sx0, xz - sz0) > limit:
665
+ return None
666
+
667
+ # --- at rest? ---------------------------------------------
668
+ if (
669
+ grounded
670
+ and vspeed < v_sleep
671
+ and wspeed < w_sleep
672
+ and max(r10 * a + r11 * b + r12 * c for a, b, c in normals) > tilt_cos
673
+ ):
674
+ if sleep_t0 is None:
675
+ sleep_t0 = t
676
+ if t - sleep_t0 >= sleep_time:
677
+ asleep = True
678
+ break
679
+ else:
680
+ sleep_t0 = None
681
+
682
+ if not asleep:
683
+ return None
684
+
685
+ q = np.array([qw, qx, qy, qz])
686
+ x = np.array([xx, xy, xz])
687
+ R = _quat_to_matrix(q)
688
+
689
+ # Record how far the die traveled relative to its initial
690
+ # horizontal speed (helps aim the next attempt better).
691
+ if self._last_launch is not None:
692
+ d_launch, h_launch = self._last_launch
693
+ if h_launch > 1e-3 * size:
694
+ proj = float(np.dot((x - self._start)[[0, 2]], d_launch[[0, 2]]))
695
+ self._ratios.append(proj / h_launch)
696
+
697
+ # --- Top face and flat orientation -------------------------
698
+ k_up = int(np.argmax((self._normals @ R.T)[:, 1]))
699
+ face_normal = R @ self._normals[k_up]
700
+
701
+ axis = np.cross(face_normal, self.UP)
702
+ sin_a = float(np.linalg.norm(axis))
703
+ cos_a = float(np.dot(face_normal, self.UP))
704
+ if sin_a > 1e-9:
705
+ q_flat = _qmul(_quat_axis_angle(axis / sin_a, np.arctan2(sin_a, cos_a)), q)
706
+ else:
707
+ q_flat = q.copy()
708
+
709
+ # --- Final rotation around Y: align with the axes -----------
710
+ # With the top face already horizontal, the four side normals
711
+ # are horizontal. Measure their angle relative to the X/Z axes
712
+ # and snap it to the nearest multiple of 90°.
713
+ yaw = 0.0
714
+ if self.snap_yaw:
715
+ R_flat = _quat_to_matrix(q_flat)
716
+ side = next(
717
+ R_flat @ n for n in self._normals
718
+ if abs((R_flat @ n)[1]) < 0.5
719
+ )
720
+ angle = np.arctan2(side[2], side[0])
721
+ quarter = 0.5 * np.pi
722
+ yaw = float((angle + quarter / 2) % quarter - quarter / 2)
723
+ q_flat = _qmul(_quat_axis_angle(self.UP, yaw), q_flat)
724
+
725
+ residual = None
726
+ target_error = 0.0
727
+ if self._target_xz is not None:
728
+ residual = self._target_xz - x[[0, 2]]
729
+ target_error = float(np.linalg.norm(residual))
730
+
731
+ blend_steps = max(1, int(self.BLEND_TIME / dt))
732
+
733
+ return _Candidate(
734
+ positions=positions,
735
+ quats=quats,
736
+ activity=activity,
737
+ q=q,
738
+ q_flat=q_flat,
739
+ x=x,
740
+ face=self._faces[k_up],
741
+ yaw=yaw,
742
+ residual=residual,
743
+ settle_time=(len(positions) - 1 + blend_steps) * dt,
744
+ yaw_error=abs(yaw),
745
+ target_error=target_error,
746
+ )
747
+
748
+ # ==================================================================
749
+ # Building the trajectory of the chosen throw
750
+ # ==================================================================
751
+
752
+ def _build_throw(self, cand: _Candidate) -> _Throw:
753
+ dt = self.simulation_dt
754
+
755
+ pos = np.array(cand.positions)
756
+ quats = np.array(cand.quats)
757
+ activity = np.array(cand.activity)
758
+
759
+ # Spread the corrections (rotation and position) over the
760
+ # motion, in proportion to how much the die moves: a lot in the
761
+ # air, almost nothing once it is still. That way there is no
762
+ # visible adjustment at the end.
763
+ cumulative = np.cumsum(activity)
764
+ if cumulative[-1] > 1e-9:
765
+ weights = cumulative / cumulative[-1]
766
+ else:
767
+ weights = np.linspace(0.0, 1.0, len(activity))
768
+
769
+ q = cand.q
770
+ if self.snap_yaw:
771
+ # Rotation around Y through the center: changes neither the
772
+ # contact with the table nor the position. Equivalent to
773
+ # multiplying each quaternion by (cos θ/2, 0, sin θ/2, 0).
774
+ half = 0.5 * cand.yaw * weights
775
+ a = np.cos(half)
776
+ b = np.sin(half)
777
+ w0, x0, y0, z0 = quats.T
778
+ quats = np.column_stack((
779
+ a * w0 - b * y0,
780
+ a * x0 + b * z0,
781
+ a * y0 + b * w0,
782
+ a * z0 - b * x0,
783
+ ))
784
+ q = quats[-1].copy()
785
+
786
+ # Exact final position in the XZ plane (horizontal shift: it
787
+ # touches neither the height nor the contact with the table).
788
+ if cand.residual is not None:
789
+ pos[:, 0] += cand.residual[0] * weights
790
+ pos[:, 2] += cand.residual[1] * weights
791
+ x = pos[-1].copy()
792
+
793
+ x_flat = x.copy()
794
+ x_flat[1] = self._ground_y + self._half
795
+
796
+ # All that is left to correct here is a tiny tilt (under ~2°)
797
+ # and a negligible height adjustment.
798
+ blend_steps = max(1, int(self.BLEND_TIME / dt))
799
+ ts = np.array([_smoothstep(k / blend_steps) for k in range(1, blend_steps + 1)])
800
+ blend_pos = x[None, :] * (1.0 - ts)[:, None] + x_flat[None, :] * ts[:, None]
801
+ blend_q = np.array([_slerp(q, cand.q_flat, a) for a in ts])
802
+
803
+ return _Throw(
804
+ positions=np.vstack((pos, blend_pos)),
805
+ quaternions=np.vstack((quats, blend_q)),
806
+ face=cand.face,
807
+ settle_time=cand.settle_time,
808
+ yaw_error=cand.yaw_error,
809
+ target_error=cand.target_error,
810
+ )
811
+
812
+ # ==================================================================
813
+ # Throw search
814
+ # ==================================================================
815
+
816
+ def _find_throw(self, run_time: Duration):
817
+ max_settle = self.settle_fraction * run_time
818
+ t_limit = 1.6 * max_settle
819
+ tol = np.radians(self.yaw_tolerance_deg)
820
+ tol_t = self.target_tolerance * self._size
821
+
822
+ # Fallback: lowest position error first, then smallest final
823
+ # rotation, then shortest time.
824
+ def cost(t):
825
+ return (
826
+ max(0.0, t.target_error - tol_t),
827
+ max(0.0, t.yaw_error - tol),
828
+ max(0.0, t.settle_time - max_settle),
829
+ )
830
+
831
+ best: _Candidate | None = None
832
+
833
+ for _ in range(self.max_attempts):
834
+ cand = self._simulate_throw(t_limit)
835
+
836
+ if cand is None or cand.face != self.outcome:
837
+ continue
838
+
839
+ if (
840
+ cand.settle_time <= max_settle
841
+ and cand.yaw_error <= tol
842
+ and cand.target_error <= tol_t
843
+ ):
844
+ best = cand
845
+ break
846
+
847
+ if best is None or cost(cand) < cost(best):
848
+ best = cand
849
+
850
+ if best is None:
851
+ raise RuntimeError(
852
+ f"Could not find a throw that ends with face "
853
+ f"{self.outcome} up after {self.max_attempts} attempts. "
854
+ "Try more `max_attempts`, a longer `run_time` or a "
855
+ "larger `max_travel`."
856
+ )
857
+
858
+ self._throw = self._build_throw(best)
859
+ # If the best throw takes longer than run_time, playback is
860
+ # slightly sped up (this almost never happens).
861
+ self._time_scale = max(1.0, best.settle_time / max_settle)
862
+
863
+ # ==================================================================
864
+ # Playback
865
+ # ==================================================================
866
+
867
+ def _set_pose_exact(self, position, quaternion):
868
+ """Exact pose from the original geometry (no drift)."""
869
+ R = _quat_to_matrix(quaternion)
870
+ position = np.asarray(position, dtype=float)
871
+ self.mobject.become(self._initial_dice)
872
+ self.mobject.apply_matrix(R, about_point=self._initial_center)
873
+ self.mobject.shift(position - self._initial_center)
874
+ self._cur_pos = position.copy()
875
+ self._cur_R = R
876
+
877
+ def _apply_pose(self, position, R):
878
+ """
879
+ Move the mobject from the current pose to (position, R) by applying
880
+ only the relative transform, in a single pass over its points.
881
+ """
882
+ cur_p, cur_R = self._cur_pos, self._cur_R
883
+
884
+ # Unchanged pose (e.g. die already at rest): touch nothing.
885
+ if (
886
+ np.abs(position - cur_p).max() < 1e-12
887
+ and np.abs(R - cur_R).max() < 1e-12
888
+ ):
889
+ return
890
+
891
+ M = R @ cur_R.T
892
+ t = position - M @ cur_p
893
+
894
+ done = False
895
+ if self._fused_ok:
896
+ MT = M.T
897
+ try:
898
+ self.mobject.apply_points_function(
899
+ lambda pts: pts @ MT + t,
900
+ about_point=self._ZERO,
901
+ )
902
+ done = True
903
+ except TypeError:
904
+ self._fused_ok = False
905
+ if not done:
906
+ self.mobject.apply_matrix(M, about_point=cur_p)
907
+ self.mobject.shift(position - cur_p)
908
+
909
+ self._cur_pos = position
910
+ self._cur_R = R
911
+
912
+ def begin(self):
913
+ # Always start from the exact original geometry (also when the
914
+ # animation is played more than once).
915
+ self.mobject.become(self._initial_dice)
916
+ self._cur_pos = self._initial_center.copy()
917
+ self._cur_R = np.eye(3)
918
+ super().begin()
919
+
920
+ def interpolate_mobject(self, alpha: float):
921
+ alpha = float(self.rate_func(float(np.clip(alpha, 0.0, 1.0))))
922
+
923
+ throw = self._throw
924
+ n = len(throw.positions)
925
+
926
+ frame = alpha * self.run_time * self._time_scale / self.simulation_dt
927
+ i0 = int(frame)
928
+
929
+ if i0 >= n - 1:
930
+ self._apply_pose(
931
+ throw.positions[-1],
932
+ _quat_to_matrix(throw.quaternions[-1]),
933
+ )
934
+ return
935
+
936
+ a = frame - i0
937
+ p = throw.positions[i0] * (1 - a) + throw.positions[i0 + 1] * a
938
+ q = _slerp(throw.quaternions[i0], throw.quaternions[i0 + 1], a)
939
+ self._apply_pose(p, _quat_to_matrix(q))
940
+
941
+ def finish(self):
942
+ # Exact final pose: removes any rounding drift.
943
+ self._set_pose_exact(self._throw.positions[-1], self._throw.quaternions[-1])
944
+ return super().finish()
945
+ editor_thumbnail = (
946
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">'
947
+ '<g transform="rotate(-14 12 12)">'
948
+ '<rect x="4" y="4" width="16" height="16" rx="3" fill="#DDDDDD"/>'
949
+ '<circle cx="8" cy="8" r="1.4" fill="#1E293B"/>'
950
+ '<circle cx="16" cy="8" r="1.4" fill="#1E293B"/>'
951
+ '<circle cx="12" cy="12" r="1.4" fill="#1E293B"/>'
952
+ '<circle cx="8" cy="16" r="1.4" fill="#1E293B"/>'
953
+ '<circle cx="16" cy="16" r="1.4" fill="#1E293B"/>'
954
+ '</g>'
955
+ '</svg>'
956
+ )