The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add spatial motion examples
Sina Atalay8751afa3771c
diff --git a/examples/heavy_top.py b/examples/heavy_top.pynew file mode 100644index 00000000..abe20e03--- /dev/null+++ b/examples/heavy_top.py@@ -0,0 +1,419 @@+"""The dance of a spinning top: it does not fall, it precesses and nods.++A symmetric top pinned at its tip, L = ½I₁(θ̇² + φ̇² sin²θ) + ½I₃(ψ̇ + φ̇ cos θ)² − Mgl cos θ.+Its spin p_ψ = I₃ω₃, its vertical angular momentum p_φ and its energy are conserved, so θ+moves in the effective potential V(θ) = (p_φ − p_ψ cos θ)²/(2I₁ sin²θ) + Mgl cos θ and nods+between two turning points, while φ̇ = (p_φ − p_ψ cos θ)/(I₁ sin²θ) carries it around. Three+identical tops tilted 32° and spun alike are let go at rest, pushed backward and pushed+forward: the tip of each axis writes cusps, loops or waves on a glass sphere between its+two bounding circles. Integrated with RK4; moments computed from the drawn top.+"""++import numpy as np++import manimgx as m+++def camera_axes(phi: float, theta: float, gamma: float) -> np.ndarray:+ """The camera's axes for its orbit angles, as rows: right, up, and toward the viewer."""++ def spin(a: float) -> np.ndarray: # a turn about z+ return np.array(+ [[np.cos(a), -np.sin(a), 0.0], [np.sin(a), np.cos(a), 0.0], [0.0, 0.0, 1.0]]+ )++ c, s = np.cos(phi), np.sin(phi)+ tilt = np.array(+ [[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]]+ ) # a turn by −φ about x+ return spin(gamma) @ tilt @ spin(-theta - np.pi / 2)+++TILT = 32 * m.DEGREES # every top starts here, θ̇ = 0+SPIN = 2.2 * m.TAU # ω₃, rad/s+MGL = 4.979 # gravity × height of the center of mass, per unit mass: tuned so the top+# let go at rest draws exactly four cusps a turn (and the one pushed back five loops)+PUSHES = (0.0, -1.362, 0.4) # initial φ̇ in units of the steady precession rate+RATE, SUBSTEPS, DURATION = 60, 10, 31.0+CONE_H, CONE_R, DISK_Z, DISK_R, DISK_T = 0.75, 0.32, 0.9, 0.95, 0.22+PEN, SPINDLE_R, KNOB_R = 1.8, 0.05, 0.08 # the spindle's knob writes on the glass+GLASS_R, SKIRT = 1.9, 0.62 # a bell jar: a glass dome over the tip and a short wall+GOLD, CORAL, TEAL = "#f4c95d", "#ef6f6c", "#2ec4b6"+++def moments() -> tuple[float, float]:+ """I₁ (about a transverse axis through the tip) and I₃ (about the spin axis), per unit+ density: a cone from the tip, a disk and a spindle."""+ cone = np.pi * CONE_R**2 * CONE_H / 3+ disk = np.pi * DISK_R**2 * DISK_T+ spindle = np.pi * SPINDLE_R**2 * (PEN - DISK_Z)+ knob = 4 / 3 * np.pi * KNOB_R**3+ i3 = 0.3 * cone * CONE_R**2 + 0.5 * disk * DISK_R**2 + 0.5 * spindle * SPINDLE_R**2+ i3 += 0.4 * knob * KNOB_R**2+ i1 = cone * (3 / 20 * CONE_R**2 + 3 / 5 * CONE_H**2) # a cone about its apex+ i1 += disk * ((3 * DISK_R**2 + DISK_T**2) / 12 + DISK_Z**2)+ mid, length = (PEN + DISK_Z) / 2, PEN - DISK_Z+ i1 += spindle * ((3 * SPINDLE_R**2 + length**2) / 12 + mid**2)+ i1 += knob * (0.4 * KNOB_R**2 + PEN**2)+ mass = cone + disk + spindle + knob # MGL = gravity × mass × height: one parameter+ return i1 / mass, i3 / mass+++def simulate(i1: float, i3: float, push: float) -> tuple[np.ndarray, np.ndarray]:+ """Euler angles (θ, φ, ψ) at RATE samples a second after the release, and the effective+ potential's parameter p_φ, for a top let go at TILT with φ̇ = push."""+ p_psi = i3 * SPIN+ p_phi = i1 * push * np.sin(TILT) ** 2 + p_psi * np.cos(TILT)++ def deriv(s: np.ndarray) -> np.ndarray:+ th, thd = s[0], s[1]+ phd = (p_phi - p_psi * np.cos(th)) / (i1 * np.sin(th) ** 2)+ torque = phd * np.cos(th) * phd - p_psi / i1 * phd + MGL / i1+ return np.array([thd, torque * np.sin(th), phd, p_psi / i3 - phd * np.cos(th)])++ h = 1 / (RATE * SUBSTEPS)+ s = np.array([TILT, 0.0, 0.0, 0.0])+ samples = [s]+ for step in range(1, int(DURATION * RATE) * SUBSTEPS + 1):+ k1 = deriv(s)+ k2 = deriv(s + h / 2 * k1)+ k3 = deriv(s + h / 2 * k2)+ s = s + h / 6 * (k1 + 2 * k2 + 2 * k3 + deriv(s + h * k3))+ if step % SUBSTEPS == 0:+ samples.append(s)+ out = np.array(samples)+ return out[:, [0, 2, 3]], np.array([p_phi, p_psi])+++def steady_rate(i1: float, i3: float) -> float:+ """The slow steady precession at TILT: I₁ cos θ φ̇² − p_ψ φ̇ + Mgl = 0."""+ a, b = i1 * np.cos(TILT), i3 * SPIN+ return (b - np.sqrt(b * b - 4 * a * MGL)) / (2 * a)+++def euler(th: float, ph: float, ps: float) -> np.ndarray:+ """Body → world for Euler angles z-x-z: R = Rz(φ) Rx(θ) Rz(ψ)."""++ def rz(a: float) -> np.ndarray:+ return np.array(+ [[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]]+ )++ c, s = np.cos(th), np.sin(th)+ return rz(ph) @ np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) @ rz(ps)+++# ── smooth lit parts ────────────────────────────────────────────────────────────────────+++def revolve(profile: np.ndarray, sides: int = 48) -> np.ndarray:+ """An (rows, sides + 1, 3) grid: profile rows (r, z) swept around the z axis."""+ a = np.linspace(0, m.TAU, sides + 1)+ r, z = profile[:, :1], profile[:, 1:]+ return np.stack([r * np.cos(a), r * np.sin(a), z + 0 * a], -1)+++def surface(grid: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """Vertices and triangles of an (rows + 1, cols + 1, 3) grid of points."""+ rows, cols = grid.shape[0] - 1, grid.shape[1] - 1+ i, j = np.meshgrid(np.arange(rows), np.arange(cols), indexing="ij")+ a = (i * (cols + 1) + j).ravel()+ b, c = a + cols + 1, a + cols + 2+ tris = np.vstack([np.stack([a, b, c], 1), np.stack([a, c, a + 1], 1)])+ return grid.reshape(-1, 3), tris+++def tube(points: np.ndarray, radius: float, sides: int = 6) -> np.ndarray:+ """A grid around a polyline (parallel-transport frames), for `surface`."""+ tangent = np.gradient(points, axis=0)+ tangent /= np.linalg.norm(tangent, axis=1, keepdims=True)+ normals = [np.cross(tangent[0], [0.3, 0.5, 0.8])]+ for t in tangent:+ n = normals[-1] - (normals[-1] @ t) * t+ normals.append(n / np.linalg.norm(n))+ n_ = np.array(normals[1:])+ a = np.linspace(0, m.TAU, sides + 1)[:, None]+ ring = np.cos(a) * n_[:, None] + np.sin(a) * np.cross(tangent, n_)[:, None]+ return points[:, None] + radius * ring+++def arc(radius: float, rows: int, start: float, stop: float) -> np.ndarray:+ t = np.linspace(start, stop, rows + 1)[:, None]+ return radius * np.hstack([np.cos(t), np.sin(t)])+++def lit(grid: np.ndarray, color: str) -> m.MeshMobject:+ return m.MeshMobject(*surface(grid), shade_in_3d=True, fill_color=color)+++def top_parts() -> list[m.MeshMobject]:+ """The top along +z from its tip: a cone, a navy disk with one cream wedge (so the+ spin shows), a spindle and its knob, the pen."""+ bevel = arc(0.05, 4, -np.pi / 2, 0) + [DISK_R - 0.05, DISK_Z - DISK_T / 2 + 0.05]+ rim = np.vstack([bevel, (bevel * [1, -1] + [0, 2 * DISK_Z])[::-1]])+ disk = revolve(np.vstack([[0, rim[0, 1]], rim, [0, rim[-1, 1]]]), 96)+ navy, cream = m.ManimColor("#1d3557").to_rgb(), m.ManimColor("#f1e3c6").to_rgb()+ paint = np.where((np.arange(97) < 13)[:, None], cream, navy)+ rows = np.hstack([np.tile(paint, (len(disk), 1)), np.ones((disk.size // 3, 1))])+ knob = arc(KNOB_R, 10, -np.pi / 2, np.pi / 2) + [0, PEN]+ return [+ lit(revolve(np.array([[0, 0], [CONE_R, CONE_H], [0, CONE_H]])), "#c9ced6"),+ m.MeshMobject(*surface(disk), vertex_colors=rows, shade_in_3d=True),+ lit(revolve(np.array([[SPINDLE_R, DISK_Z], [SPINDLE_R, PEN]]), 24), "#c9ced6"),+ lit(revolve(knob, 24), "#ffffff"),+ ]+++class Jar(m.Group):+ """A glass jar and all it holds — its stand, the circles where θ turns, the pen's trace,+ the top: a mesh a part, each shown with its points and colors of the moment (what shows+ through the glass is the engine's to composite). Part 0 is the glass."""++ def __init__(self, parts: list[tuple[np.ndarray, np.ndarray, np.ndarray]]) -> None:+ self.base = [verts for verts, _, _ in parts]+ self.tint = [np.broadcast_to(c, (len(v), 4)) for v, _, c in parts]+ super().__init__(+ *(m.MeshMobject(v, tris, shade_in_3d=True) for v, tris, _ in parts)+ )++ def show(self, points: list[np.ndarray], colors: list[np.ndarray]) -> None:+ for part, p, c in zip(self.submobjects, points, colors, strict=True):+ part.points = p+ part.paint = part.paint.but(fill=c)+++def rgba(color: str, alpha: float) -> np.ndarray:+ return np.array([*m.ManimColor(color).to_rgb(), alpha])+++def project(camera: m.Camera, point: np.ndarray) -> np.ndarray:+ """Where a 3D point lands on the screen, in frame coordinates (for HUD labels)."""+ turn = camera_axes(camera.get_phi(), camera.get_theta(), camera.get_gamma())+ p = turn @ (point - camera.frame_center)+ depth = 1 - p[2] / camera.get_focal_distance()+ return np.array([*(camera.get_zoom() * p[:2] / depth), 0.0])+++def axis_of(angles: np.ndarray) -> np.ndarray:+ """The unit spin axis for Euler angles (θ, φ, …): (sin θ sin φ, −sin θ cos φ, cos θ)."""+ th, ph = angles[..., 0], angles[..., 1]+ return np.stack([np.sin(th) * np.sin(ph), -np.sin(th) * np.cos(ph), np.cos(th)], -1)+++class HeavyTop(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(+ phi=60 * m.DEGREES,+ theta=-90 * m.DEGREES,+ zoom=1.55,+ focal_distance=30,+ frame_center=[-2.8, 0, 0.5],+ )+ i1, i3 = moments()+ steady = steady_rate(i1, i3)+ spots = [np.array([x, 0.0, 0.0]) for x in (-4.7, 0.0, 4.7)]+ releases = [0.8, 13.6, 13.6]+ colors = [GOLD, CORAL, TEAL]+ facing = -90 * m.DEGREES # each top first leans to the left+ motions = [simulate(i1, i3, k * steady) for k in PUSHES]+ clock = [0.0]++ def angles(k: int) -> np.ndarray:+ """(θ, φ, ψ) of top k now: spinning in place until it is let go."""+ after = clock[0] - releases[k]+ if after < 0:+ return np.array([TILT, facing, SPIN * clock[0]])+ th, ph, ps = motions[k][0][min(round(after * RATE), len(motions[k][0]) - 1)]+ return np.array([th, ph + facing, ps + SPIN * releases[k]])++ # each top under a bell jar, its pen writing on the glass between the two circles+ # where θ turns+ pieces = top_parts()+ body = np.vstack([p.points for p in pieces])+ cuts = np.cumsum([len(p.points) for p in pieces])[:-1] # body → its pieces+ dome = np.vstack([[[GLASS_R, -SKIRT]], arc(GLASS_R, 24, 0, np.pi / 2)])+ glass, glass_tris = surface(revolve(dome, 72))+ rim, floor = GLASS_R + 0.12, -SKIRT+ plate = [[0, floor - 0.1], [rim, floor - 0.1], [rim, floor], [rim, floor]]+ plate += [[r, floor] for r in (1.4, 0.9, 0.45)]+ post = [[0.05, floor], [0.05, -0.06], [0.22, -0.06], [0.22, -0.02], [0, -0.02]]+ stand = np.array(plate + post)+ jars, ages, cycles = [], [], []+ for k, spot in enumerate(spots):+ path = motions[k][0][: round((DURATION - releases[k]) * RATE)]+ turned = np.unwrap(path[:, 1])+ cycles.append(np.argmax(np.abs(turned) >= m.TAU) / RATE) # one precession+ parts = [(glass + spot, glass_tris, rgba("#9ec9ff", 0.09))]+ parts.append((*surface(revolve(stand, 72) + spot), rgba("#07080b", 1.0)))+ for bound in (path[:, 0].min(), path[:, 0].max()):+ ring = np.stack([np.full(121, bound), np.linspace(0, m.TAU, 121)], -1)+ circle = tube((GLASS_R + 0.016) * axis_of(ring) + spot, 0.012, 4)+ parts.append((*surface(circle), rgba("#aab2c0", 1.0)))+ pen = (GLASS_R + 0.034) * axis_of(path[::2] + [0, facing, 0]) + spot+ parts.append((*surface(tube(pen, 0.03, 8)), rgba(colors[k], 0.0)))+ ages.append(np.repeat(np.arange(len(pen)) * 2 / RATE + releases[k], 9))+ parts += [(p.points, p.triangles, p.paint.fill) for p in pieces]+ jars.append(Jar(parts))+ shown = [m.ValueTracker(1.0), m.ValueTracker(0.0), m.ValueTracker(0.0)]+ rings = m.ValueTracker(0.0)++ def refresh(k: int) -> None:+ jar = jars[k]+ top = np.split(body @ euler(*angles(k)).T + spots[k], cuts)+ points = [*jar.base[: -len(top)], *top]+ colors = [np.array(c) for c in jar.tint]+ trace = colors[-len(top) - 1]+ age = clock[0] - ages[k]+ live = (age >= 0) & (age < cycles[k]) # the last full turn of the pen+ trace[:, :3] *= 1 - 0.55 * np.clip(age / cycles[k], 0, 1)[:, None]+ trace[:, 3] = live+ for circle in colors[2:4]:+ circle[:, 3] *= rings.get_value()+ for c in colors:+ c[:, 3] *= shown[k].get_value()+ jar.show(points, colors)++ for k, jar in enumerate(jars):+ jar.add_updater(lambda mob, k=k: refresh(k))+ refresh(k)++ def advance(mob: m.Mobject, dt: float) -> None:+ clock[0] += dt++ driver = m.Mobject().add_updater(advance)+ self.add(driver, jars[0])++ # heads-up display: the effective potential of the first top, and θ in its well+ p_phi, p_psi = motions[0][1]++ def potential(th: float) -> float:+ well = (p_phi - p_psi * np.cos(th)) ** 2 / (2 * i1 * np.sin(th) ** 2)+ return float(well + MGL * np.cos(th))++ low, high = motions[0][0][:, 0].min(), motions[0][0][:, 0].max()+ level = potential(TILT)+ sweep = np.linspace(20, 70, 501)+ well = np.array([potential(np.radians(d)) for d in sweep])+ depth = level - well.min()+ base, ceiling = well.min() - 0.25 * depth, level + 0.9 * depth+ span = sweep[well <= ceiling]+ left, right = span[0] - 2, span[-1] + 2+ axes = m.Axes(+ x_range=[left, right, 5],+ y_range=[base, ceiling, 1],+ x_length=4.8,+ y_length=2.8,+ tips=False,+ axis_config={"include_ticks": False, "stroke_width": 2, "color": m.GREY_B},+ ).move_to([3.7, -0.9, 0])+ curve = axes.plot(+ lambda d: potential(np.radians(d)),+ x_range=[span[0], span[-1]],+ color=m.WHITE,+ )+ energy = m.DashedLine(axes.c2p(left, level), axes.c2p(right, level))+ energy.set_stroke(GOLD, 2.5)+ marks, names, tags = m.VGroup(), m.VGroup(), m.VGroup()+ for name, bound, off in ((r"\theta_1", low, -0.2), (r"\theta_2", high, 0.2)):+ x = np.degrees(bound)+ marks.add(+ m.DashedLine(axes.c2p(x, level), axes.c2p(x, base), stroke_width=1.5)+ )+ names.add(m.MathTex(name, font_size=30).next_to(axes.c2p(x, base), m.DOWN))+ side = spots[0] + GLASS_R * axis_of(np.array([bound + off, np.pi / 2]))+ tags.add(m.MathTex(name, font_size=30).move_to(project(self.camera, side)))+ v_label = m.MathTex(r"V(\theta)", font_size=30).next_to(axes.y_axis, m.UP, 0.1)+ t_label = m.MathTex(r"\theta", font_size=30).next_to(axes.x_axis, m.RIGHT, 0.1)+ formula = m.MathTex(+ r"V(\theta) = \frac{(p_\phi - p_\psi \cos\theta)^2}{2 I_1 \sin^2\theta}"+ r" + Mgl\cos\theta",+ font_size=30,+ )+ heading = m.VGroup(+ m.Text("effective potential", font_size=22).set_color(m.GREY_B), formula+ ).arrange(m.DOWN, buff=0.18)+ heading.next_to(axes, m.UP, buff=0.55)++ def ball() -> m.VGroup:+ th = angles(0)[0]+ at = axes.c2p(np.degrees(th), level)+ below = axes.c2p(np.degrees(th), potential(th))+ return m.VGroup(m.Line(at, below, color=GOLD), m.Dot(at, 0.07, color=GOLD))++ rider = m.always_redraw(ball)+ frame = [axes, heading, v_label, t_label]+ plot = [*frame, curve, energy, rider, marks, names, tags]++ title = m.Text("The dance of a spinning top", font_size=36).to_corner(m.UL)+ subtitle = m.Text(+ "pinned at its tip, it does not fall: it precesses and nods", font_size=22+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ subtitle2 = m.Text(+ "three identical tops, spun and tilted alike, let go three ways",+ font_size=22,+ ).set_color(m.GREY_B)+ subtitle2.move_to(subtitle, aligned_edge=m.LEFT)+ closing = m.Text(+ "None of them falls: each tip stays between its two circles.", font_size=26+ ).to_edge(m.DOWN, buff=0.25)+ captions = m.VGroup()+ for k, (what, how) in enumerate(+ [+ ("cusps", "let go at rest"),+ ("loops", "pushed back"),+ ("waves", "pushed forward"),+ ]+ ):+ word = m.Text(what, font_size=30).set_color(colors[k])+ note = m.Text(how, font_size=22).set_color(m.GREY_B)+ front = spots[k] + [+ 0,+ -GLASS_R - 0.12,+ -SKIRT - 0.1,+ ] # the plate's near edge+ pair = m.VGroup(word, note).arrange(m.DOWN, buff=0.12)+ pair.add_updater(+ lambda mob, at=front: mob.move_to(+ project(self.camera, at) + 0.62 * m.DOWN+ )+ )+ captions.add(pair)+ hud = [subtitle, *plot, subtitle2, closing, captions]+ self.add_fixed_in_frame_mobjects(title, *hud)+ self.remove(*hud)++ # 0–10 s: one top, nodding between the turning points of its effective potential+ self.play(m.FadeIn(subtitle), run_time=1.2)+ self.play(*[m.FadeIn(mob) for mob in frame], run_time=1)+ self.play(m.Create(curve), m.FadeIn(energy), m.FadeIn(rider), run_time=1.2)+ turning = [m.FadeIn(mob) for mob in (marks, names, tags)]+ self.play(*turning, rings.animate.set_value(1.0), run_time=1)+ self.wait(10.4 - self.time)++ # 10–13 s: two more tops, let go with a push+ self.play(*[m.FadeOut(mob) for mob in plot], run_time=0.8)+ self.add(jars[1], jars[2])+ self.move_camera(+ phi=54 * m.DEGREES,+ theta=-97 * m.DEGREES,+ zoom=1.0,+ frame_center=[0, 0, -0.05],+ added_anims=[shown[k].animate.set_value(1.0) for k in (1, 2)],+ run_time=2.2,+ )+ self.begin_ambient_camera_rotation(rate=0.01)+ self.play(+ m.FadeOut(subtitle), m.FadeIn(subtitle2), m.FadeIn(captions), run_time=1.2+ )+ # 14–30 s: cusps, loops and waves, then all three from higher up+ self.wait(20.8 - self.time)+ self.stop_ambient_camera_rotation()+ self.move_camera(phi=40 * m.DEGREES, theta=-90 * m.DEGREES, run_time=3)+ self.wait(26.4 - self.time)+ self.play(m.FadeIn(closing, shift=0.15 * m.UP), run_time=1.2)+ self.wait(30.5 - self.time) # ends as all three tops lean away from us+++if __name__ == "__main__":+ HeavyTop().render("heavy_top.mp4")diff --git a/examples/tennis_racket.py b/examples/tennis_racket.pynew file mode 100644index 00000000..e6dd505a--- /dev/null+++ b/examples/tennis_racket.py@@ -0,0 +1,422 @@+"""Why a spinning handle flips: the tennis-racket theorem (Dzhanibekov effect).++Three identical T-handles spin at the same rate about their three principal axes. About the+axes of least and greatest moment of inertia the spin is steady; about the middle one the+handle turns over every few seconds, though nothing pushes it and its angular momentum L+(gold) never moves. Torque-free Euler equations I₁ω̇₁ = (I₂ − I₃)ω₂ω₃ (cyclic), RK4 with a+quaternion; the moments are computed from the drawn handle. Seen from the handle, L keeps+its length and the energy E = Σ L_k²/2I_k, so it slides along level curves of E on a sphere+(the polhodes). The separatrix, two great circles, cuts that sphere into four panels that+meet only at the middle axis, a saddle: a state near it is carried to the opposite side.+"""++import numpy as np++import manimgx as m+++def camera_axes(phi: float, theta: float, gamma: float) -> np.ndarray:+ """The camera's axes for its orbit angles, as rows: right, up, and toward the viewer."""++ def spin(a: float) -> np.ndarray: # a turn about z+ return np.array(+ [[np.cos(a), -np.sin(a), 0.0], [np.sin(a), np.cos(a), 0.0], [0.0, 0.0, 1.0]]+ )++ c, s = np.cos(phi), np.sin(phi)+ tilt = np.array(+ [[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]]+ ) # a turn by −φ about x+ return spin(gamma) @ tilt @ spin(-theta - np.pi / 2)+++SPIN = 0.7 * m.TAU # rad/s, the same for all three handles+WOBBLE = 0.005 # the small off-axis part of every initial spin, relative to SPIN+RATE, SUBSTEPS, DURATION = 60, 2, 31.0 # samples/s of the motion, RK4 steps per sample+STEEL, CORAL, GOLD = "#9db4cf", "#ef6f6c", "#f4c95d"+AXIS1, AXIS3 = "#2bb3a3", "#6a5acd" # the glass panels around axes 1 and 3+BAR, BAR_R, STEM, STEM_R, KNOB_R = 2.8, 0.12, 1.3, 0.08, 0.16 # crossbar ∥ x, stem ∥ y+++def moments() -> tuple[np.ndarray, np.ndarray]:+ """Center of mass and principal moments (per unit mass) of the solid T of one density:+ crossbar and stem cylinders and a ball. By symmetry the body axes are principal."""+ bar, stem, knob = BAR_R**2 * BAR, STEM_R**2 * STEM, 4 / 3 * KNOB_R**3 # masses / π+ across = [(3 * r * r + h * h) / 12 for r, h in ((BAR_R, BAR), (STEM_R, STEM))]+ parts = [+ (bar, 0.0, [BAR_R**2 / 2, across[0], across[0]]),+ (stem, STEM / 2, [across[1], STEM_R**2 / 2, across[1]]),+ (knob, STEM, [0.4 * KNOB_R**2] * 3),+ ]+ total = bar + stem + knob+ com = sum(mass * y for mass, y, _ in parts) / total+ inertia = np.zeros(3)+ for mass, y, own in parts: # parallel axes: the offsets are along y+ inertia += mass * (np.array(own) + (y - com) ** 2 * np.array([1, 0, 1]))+ return np.array([0, com, 0]), inertia / total+++def simulate(inertia: np.ndarray, omega0: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """Body angular velocities (n, k, 3) and turns (n, k, 3, 3) of k free bodies started+ at the body rates omega0 (k, 3): Euler's equations and Ṙ = R [ω]×, by RK4."""+ i1, i2, i3 = inertia+ p, q, r = (i2 - i3) / i1, (i3 - i1) / i2, (i1 - i2) / i3++ def deriv(w: np.ndarray, turn: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ w1, w2, w3 = w.T+ o = 0 * w1+ cross = np.array([[o, -w3, w2], [w3, o, -w1], [-w2, w1, o]]).transpose(2, 0, 1)+ return np.stack([p * w2 * w3, q * w3 * w1, r * w1 * w2], -1), turn @ cross++ h = 1 / (RATE * SUBSTEPS)+ w, turn = omega0, np.tile(np.eye(3), (len(omega0), 1, 1))+ samples = [(w, turn)]+ for step in range(1, int(DURATION * RATE) * SUBSTEPS + 1):+ a1, b1 = deriv(w, turn)+ a2, b2 = deriv(w + h / 2 * a1, turn + h / 2 * b1)+ a3, b3 = deriv(w + h / 2 * a2, turn + h / 2 * b2)+ a4, b4 = deriv(w + h * a3, turn + h * b3)+ w = w + h / 6 * (a1 + 2 * a2 + 2 * a3 + a4)+ turn = turn + h / 6 * (b1 + 2 * b2 + 2 * b3 + b4)+ if step % SUBSTEPS == 0:+ samples.append((w, turn))+ return np.array([w for w, _ in samples]), np.array([t for _, t in samples])+++def toward_z(u: np.ndarray, hint: np.ndarray) -> np.ndarray:+ """A rotation taking the unit vector u to +z (and hint, as far as it can, to +x)."""+ x = hint - (hint @ u) * u+ x /= np.linalg.norm(x)+ return np.array([x, np.cross(u, x), u])+++# ── smooth lit parts: surfaces of revolution and tubes ──────────────────────────────────+++def revolve(profile: np.ndarray, sides: int = 28) -> np.ndarray:+ """An (rows, sides + 1, 3) grid: profile rows (r, z) swept around the z axis. A row+ given twice makes a sharp rim (normals average over faces of nonzero area)."""+ a = np.linspace(0, m.TAU, sides + 1)+ r, z = profile[:, :1], profile[:, 1:]+ return np.stack([r * np.cos(a), r * np.sin(a), z + 0 * a], -1)+++def ball(radius: float, rows: int = 14) -> np.ndarray:+ t = np.linspace(-np.pi / 2, np.pi / 2, rows + 1)[:, None]+ return radius * np.hstack([np.cos(t), np.sin(t)])+++def rod(length: float, radius: float) -> np.ndarray:+ """A rod with round ends, centered, along z."""+ cap = ball(radius)+ return np.vstack([cap[:8] - [0, length / 2], cap[7:] + [0, length / 2]])+++def arrow(length: float, radius: float, head: float, width: float) -> np.ndarray:+ shaft = length - head+ rows = [(0, 0), (radius, 0), (radius, 0), (radius, shaft), (radius, shaft)]+ return np.array(rows + [(width, shaft), (width, shaft), (0, length)])+++def surface(grid: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """Vertices and triangles of an (rows + 1, cols + 1, 3) grid of points."""+ rows, cols = grid.shape[0] - 1, grid.shape[1] - 1+ i, j = np.meshgrid(np.arange(rows), np.arange(cols), indexing="ij")+ a = (i * (cols + 1) + j).ravel()+ b, c = a + cols + 1, a + cols + 2+ tris = np.vstack([np.stack([a, b, c], 1), np.stack([a, c, a + 1], 1)])+ return grid.reshape(-1, 3), tris+++def tube(points: np.ndarray, radius: float, sides: int = 7) -> np.ndarray:+ """A grid around a polyline (parallel-transport frames), for `surface`."""+ tangent = np.gradient(points, axis=0)+ tangent /= np.linalg.norm(tangent, axis=1, keepdims=True)+ normals = [np.cross(tangent[0], [0.3, 0.5, 0.8])]+ for t in tangent:+ n = normals[-1] - (normals[-1] @ t) * t+ normals.append(n / np.linalg.norm(n))+ n_ = np.array(normals[1:])+ a = np.linspace(0, m.TAU, sides + 1)[:, None]+ ring = np.cos(a) * n_[:, None] + np.sin(a) * np.cross(tangent, n_)[:, None]+ return points[:, None] + radius * ring+++def mesh(grid: np.ndarray, color: str) -> m.MeshMobject:+ return m.MeshMobject(*surface(grid), shade_in_3d=True, fill_color=color)+++def handle_parts(com: np.ndarray) -> list[m.MeshMobject]:+ """The T in its body frame, around its center of mass: crossbar, stem and knob."""+ along_x, along_y = np.roll(np.eye(3), 1, 1), np.roll(np.eye(3), 2, 1)+ return [+ mesh(revolve(rod(BAR, BAR_R)) @ along_x - com, STEEL),+ mesh(revolve(rod(STEM, STEM_R)) @ along_y + [0, STEM / 2, 0] - com, CORAL),+ mesh(revolve(ball(KNOB_R)) + [0, STEM, 0] - com, CORAL),+ ]+++class Rigid:+ """Pose a group absolutely each frame: points = base · Rᵀ + center."""++ def __init__(self, group: m.Mobject) -> None:+ self.parts = [+ (mob, mob.points.copy()) for mob in group.family_members_with_points()+ ]++ def pose(self, turn: np.ndarray, center: np.ndarray) -> None:+ for mob, base in self.parts:+ mob.points = base @ turn.T + center+++# ── the handle's own frame: the sphere of directions of L ───────────────────────────────+++def polhodes(inertia: np.ndarray) -> list[np.ndarray]:+ """Level curves of E = ½ Σ n_k²/I_k on the unit sphere: loops around ±axis 1 and ±axis 3,+ then the separatrix, two great circles through ±axis 2."""+ inv = 1 / inertia+ s = np.linspace(0, m.TAU, 181)[:, None]+ curves = []+ for k in (0.35, 0.75): # 0: the separatrix, 1: the axis+ a = np.sqrt(1 - k)+ b = np.sqrt((1 - k) * (inv[1] - inv[2]) / (inv[0] - inv[2]))+ c = np.sqrt((1 - k) * (inv[0] - inv[1]) / (inv[0] - inv[2]))+ for sign in (1, -1):+ n2, n3 = a * np.cos(s), c * np.sin(s) # around ±axis 1+ curves.append(np.hstack([sign * np.sqrt(1 - n2**2 - n3**2), n2, n3]))+ n1, n2 = b * np.cos(s), a * np.sin(s) # around ±axis 3+ curves.append(np.hstack([n1, n2, sign * np.sqrt(1 - n1**2 - n2**2)]))+ tilt = np.array([np.sqrt(inv[1] - inv[2]), 0, np.sqrt(inv[0] - inv[1])])+ tilt /= np.linalg.norm(tilt)+ for sign in (1, -1):+ curves.append(np.cos(s) * [0, 1, 0] + np.sin(s) * tilt * [1, 0, sign])+ return curves+++def panel_colors(n: np.ndarray, inertia: np.ndarray, alpha: float) -> np.ndarray:+ """Glass tint: the panels around ±axis 1 (energy above the saddle's) and ±axis 3,+ each brightening toward its axis."""+ inv = 1 / inertia+ e = (n**2 @ inv - inv[2]) / (inv[0] - inv[2]) # 0 at axis 3, 1 at axis 1+ saddle = (inv[1] - inv[2]) / (inv[0] - inv[2])+ upper = (e > saddle)[:, None]+ depth = np.where(upper, e[:, None] - saddle, saddle - e[:, None])+ depth /= np.where(upper, 1 - saddle, saddle)+ hue = np.where(upper, m.ManimColor(AXIS1).to_rgb(), m.ManimColor(AXIS3).to_rgb())+ return np.hstack([hue * (0.45 + 0.55 * depth**0.6), np.full((len(n), 1), alpha)])+++def rgba(color: str, alpha: float) -> np.ndarray:+ return np.array([*m.ManimColor(color).to_rgb(), alpha])+++class Globe(m.Group):+ """Glass with things inside and on it: a mesh a part, each shown with its points and colors+ of the moment (what shows through the glass is the engine's to composite)."""++ def __init__(self, parts: list[tuple[np.ndarray, np.ndarray, np.ndarray]]) -> None:+ self.base = [verts for verts, _, _ in parts]+ self.tint = [np.broadcast_to(c, (len(v), 4)) for v, _, c in parts]+ super().__init__(+ *(m.MeshMobject(v, tris, shade_in_3d=True) for v, tris, _ in parts)+ )++ def show(self, points: list[np.ndarray], colors: list[np.ndarray]) -> None:+ for part, p, c in zip(self.submobjects, points, colors, strict=True):+ part.points = p+ part.paint = part.paint.but(fill=c)+++def project(camera: m.Camera, point: np.ndarray) -> np.ndarray:+ """Where a 3D point lands on the screen, in frame coordinates (for HUD labels)."""+ turn = camera_axes(camera.get_phi(), camera.get_theta(), camera.get_gamma())+ p = turn @ (point - camera.frame_center)+ depth = 1 - p[2] / camera.get_focal_distance()+ return np.array([*(camera.get_zoom() * p[:2] / depth), 0.0])+++class TennisRacket(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(+ phi=70 * m.DEGREES, theta=-90 * m.DEGREES, zoom=1.12, focal_distance=30+ )+ com, inertia = moments()++ # the motion, once: three handles spun about axes 1, 2, 3 with the same wobble+ omega, turn = simulate(inertia, SPIN * (WOBBLE + (1 - WOBBLE) * np.eye(3)))+ spin_l = omega * inertia # L in each body frame, (n, 3, 3)+ hints = np.eye(3)[[1, 0, 0]] # the body axis that starts along +x+ units = spin_l[0] / np.linalg.norm(spin_l[0], axis=1, keepdims=True)+ start = np.array([toward_z(units[k], hints[k]) for k in range(3)])+ world = np.einsum("kij,nkjl->nkil", start, turn) # L stays along +z+ stem_up = world[:, 1, 2, 1] # the height of handle 2's stem axis+ flips = np.flatnonzero(np.diff(np.sign(stem_up))) / RATE+ seen = spin_l[:, 1] / np.linalg.norm(spin_l[:, 1], axis=1, keepdims=True)++ spots = [np.array([x, 0.0, -0.25]) for x in (-4.1, 0.0, 4.1)]+ handles = [m.Group(*handle_parts(com)) for _ in spots]+ rigs = [Rigid(h) for h in handles]+ axes = [+ mesh(revolve(arrow(3.6, 0.02, 0.32, 0.085)) + p + [0, 0, -1.75], GOLD)+ for p in spots+ ]+ slide = m.ValueTracker(0.0) # handle 2 moving to the left+ goal = np.array([-3.5, 0.0, -0.25])+ clock = [0.0]++ def now() -> int:+ return min(round(clock[0] * RATE), len(world) - 1)++ def advance(mob: m.Mobject, dt: float) -> None:+ clock[0] += dt+ for k, rig in enumerate(rigs):+ moved = slide.get_value() * (goal - spots[1]) if k == 1 else 0+ rig.pose(world[now(), k], spots[k] + moved)++ driver = m.Mobject().add_updater(advance)+ advance(driver, 0)+ self.add(driver, *handles, *axes)++ # the handle's own frame: a glass globe of the directions of L, seen from between+ # its axes (closest to axis 2, which points up)+ center, radius = np.array([2.75, 0.0, -0.55]), 2.45+ cam = camera_axes(+ 70 * m.DEGREES, -90 * m.DEGREES, 0+ ) # rows: right, up, toward us+ eye = np.array([0.15, 1.3, 1.0]) / np.linalg.norm([0.15, 1.3, 1.0])+ up = np.eye(3)[1] - eye[1] * eye+ up /= np.linalg.norm(up)+ screen = np.array([cam[2], cam[1], np.cross(cam[2], cam[1])]).T+ display = screen @ np.array([eye, up, np.cross(eye, up)]) # body → world+ sphere, sphere_tris = surface(revolve(ball(1.0, 36), 72))+ parts = [(sphere @ display.T, sphere_tris, panel_colors(sphere, inertia, 0.4))]+ curves = polhodes(inertia)+ for k, curve in enumerate(curves): # the last two: the separatrix+ wide, sides, color = (+ (0.016, 6, "#ffffff") if k > 7 else (0.008, 4, "#cfe0ff")+ )+ ring = tube(curve @ display.T, wide / radius, sides)+ parts.append((*surface(ring), rgba(color, 0.9 if k > 7 else 0.45)))+ for part in handle_parts(com): # the handle at rest in its own frame+ small = part.points @ display.T * 0.6 / radius+ parts.append((small, part.triangles, part.paint.fill[0]))+ first = round((flips[1] + 1.2) * RATE) # L's path from when the globe appears+ trail = surface(tube(seen[first::2] @ display.T * 1.012, 0.018 / radius, 6))+ parts.append((*trail, rgba(GOLD, 0.0)))+ trail_age = np.repeat(np.arange(first, len(seen), 2), 7) / RATE+ pointer = surface(revolve(arrow(1.0, 0.012, 0.09, 0.03), 12))+ parts.append((*pointer, rgba(GOLD, 1.0)))+ head = surface(revolve(ball(0.035, 10), 14))+ parts.append((*head, rgba("#fff6d5", 1.0)))+ globe = Globe(parts)+ appear = m.ValueTracker(0.0)++ def refresh(mob: m.Mobject) -> None:+ i = now()+ d = seen[i] @ display.T+ points = [+ *globe.base[:-2],+ pointer[0] @ toward_z(d, np.array([0.3, 0.5, 0.8])),+ head[0] + 1.012 * d,+ ]+ colors = [np.array(c) for c in globe.tint]+ age = i / RATE - trail_age # a comet, fading to a lasting trace+ colors[-3][:, 3] = (age >= 0) * np.maximum(1 - age / 1.2, 0.3)+ for c in colors:+ c[:, 3] *= appear.get_value()+ grow = 0.85 + 0.15 * appear.get_value()+ globe.show([center + radius * grow * p for p in points], colors)++ globe.add_updater(refresh)+ refresh(globe)++ # heads-up display+ title = m.Text("Why a spinning handle flips", font_size=36).to_corner(m.UL)+ subtitle = m.Text(+ "one T-handle, spun about each of its three principal axes", font_size=22+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ subtitle2 = m.Text(+ "seen from the handle, L slides along curves of equal energy", font_size=22+ ).set_color(m.GREY_B)+ subtitle2.move_to(subtitle, aligned_edge=m.LEFT)+ labels, verdicts, ells = [], [], []+ words = [("steady", m.GREY_B), ("flips", CORAL), ("steady", m.GREY_B)]+ for k, spot in enumerate(spots):+ ratio = inertia[k] / inertia[1]+ label = m.MathTex(rf"I_{k + 1} = {ratio:.2f}", font_size=34)+ labels.append(label.move_to(project(self.camera, spot) + 2.3 * m.DOWN))+ verdict = m.Text(words[k][0], font_size=26).set_color(words[k][1])+ verdicts.append(verdict.next_to(label, m.DOWN, buff=0.18))+ tip = project(self.camera, spot + [0, 0, 1.75]) + [0.3, -0.1, 0]+ ells.append(m.MathTex("L", font_size=34, color=GOLD).move_to(tip))+ l_globe = m.MathTex("L", font_size=34, color=GOLD)++ def follow(mob: m.Mobject) -> None:+ d = seen[now()] @ display.T+ mob.move_to(project(self.camera, center + radius * d) + [0.28, 0.12, 0])+ mob.set_opacity(appear.get_value())++ l_globe.add_updater(follow)+ sphere_law = m.MathTex(r"L_1^2 + L_2^2 + L_3^2 = L^2", font_size=32)+ energy_law = m.MathTex(+ r"\frac{L_1^2}{I_1} + \frac{L_2^2}{I_2} + \frac{L_3^2}{I_3} = 2E",+ font_size=32,+ )+ laws = m.VGroup(sphere_law, energy_law).arrange(m.DOWN, aligned_edge=m.RIGHT)+ laws.to_corner(m.UR)+ closing = m.Text(+ "The middle axis is a saddle: the slightest wobble grows into a flip.",+ font_size=26,+ ).to_edge(m.DOWN, buff=0.3)+ saddle_at = project(self.camera, center + radius * (display @ np.eye(3)[1]))+ saddle = m.Text("saddle", font_size=26).move_to(saddle_at + [-1.9, 1.05, 0])+ pin = m.Line(+ saddle.get_right() + [0.08, -0.08, 0], saddle_at + [-0.12, 0.08, 0]+ )+ pin.set_stroke(m.WHITE, 2)+ hud = [subtitle, subtitle2, *labels, *verdicts, *ells, l_globe, laws, closing]+ hud += [saddle, pin]+ self.add_fixed_in_frame_mobjects(title, *hud)+ self.remove(*hud)++ # 0–9 s: three spins, one of which keeps turning over+ self.play(*[m.FadeIn(mob) for mob in [subtitle, *labels, *ells]], run_time=1.5)+ self.wait(flips[0] + 1.3 - self.time)+ self.play(*[m.FadeIn(v, shift=0.1 * m.UP) for v in verdicts], run_time=1)+ self.wait(flips[1] + 1.2 - self.time)++ # 9–12 s: the flipping one, next to the same motion seen from the handle itself+ steady: list[m.Mobject] = [handles[0], handles[2], subtitle]+ steady += [group[k] for group in (axes, labels, verdicts, ells) for k in (0, 2)]+ self.play(*[m.FadeOut(mob) for mob in steady], run_time=0.8)+ self.add(globe, l_globe)+ moved = project(self.camera, goal)[0] - project(self.camera, spots[1])[0]+ self.play(+ axes[1].animate.shift(goal - spots[1]),+ *[+ mob.animate.shift(moved * m.RIGHT)+ for mob in (labels[1], verdicts[1], ells[1])+ ],+ slide.animate.set_value(1.0),+ appear.animate.set_value(1.0),+ m.FadeIn(subtitle2),+ m.FadeIn(laws),+ run_time=1.8,+ )+ # 12–27 s: every flip is L running along the separatrix, from saddle to saddle+ self.wait(flips[3] + 0.8 - self.time)+ self.play(m.FadeIn(saddle), m.Create(pin), run_time=1)+ self.wait(flips[5] + 0.5 - self.time)+ self.play(+ m.FadeIn(closing, shift=0.15 * m.UP),+ m.FadeOut(labels[1]),+ m.FadeOut(verdicts[1]),+ run_time=1.2,+ )+ self.wait(1.8)+++if __name__ == "__main__":+ TennisRacket().render("tennis_racket.mp4")diff --git a/examples/vortex_rings.py b/examples/vortex_rings.pynew file mode 100644index 00000000..d0345a39--- /dev/null+++ b/examples/vortex_rings.py@@ -0,0 +1,217 @@+"""Leapfrogging smoke rings: two vortex rings take turns passing through each other.++Two identical smoke rings travel one behind the other. The front ring's flow squeezes the rear+ring and pulls it forward: it shrinks, speeds up and slips through the front ring, which the rear+ring's flow pushes wider and slower. Then the roles swap, again and again (Helmholtz, 1858).++Each ring is a circular vortex filament with a smoothed core. Its velocity field is exact:+complete elliptic integrals, computed by the arithmetic–geometric mean. The two rings and 12,000+smoke particles are all carried by the same field. Kelvin's impulse, proportional to r₁² + r₂², is+conserved, so when one ring shrinks the other must grow.+"""++import numpy as np++import manimgx as m++GAMMA = 1.0 # circulation of each ring+CORE = 0.1 # smoothing length of the cores+TIME_SCALE = 0.8 # model time per second of video+SCALE = 1.75 # screen units per model unit (the rings start with radius 1)+SMOKE = 9000 # particles per ring+COLORS = ["#ff9f1c", "#3ddbd9"]+++def elliptic(k2: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """The complete elliptic integrals K and E of parameter k², by the arithmetic–geometric mean."""+ a, b = np.ones_like(k2), np.sqrt(1 - k2)+ total, weight = 0.5 * k2, 0.5+ for _ in range(7):+ a, b, c = (a + b) / 2, np.sqrt(a * b), (a - b) / 2+ weight *= 2+ total = total + weight * c * c+ k = np.pi / (2 * a)+ return k, k * (1 - total)+++def induced(+ r: np.ndarray, z: np.ndarray, ring_r: float, ring_z: float+) -> tuple[np.ndarray, np.ndarray]:+ """The velocity (u_r, u_z) at meridional points (r, z) of a vortex ring of radius ring_r at+ height ring_z, its core smoothed over CORE."""+ dz = z - ring_z+ far = dz**2 + (r + ring_r) ** 2 + CORE**2+ near = dz**2 + (r - ring_r) ** 2 + CORE**2+ k, e = elliptic(np.minimum(4 * r * ring_r / far, 1 - 1e-12))+ s = GAMMA / (2 * np.pi * np.sqrt(far))+ u_r = s * dz / np.maximum(r, 1e-9) * (-k + (r**2 + ring_r**2 + dz**2) / near * e)+ u_z = s * (k + (ring_r**2 - r**2 - dz**2) / near * e)+ return u_r, u_z+++class Flow:+ """The two rings (entries 0 and 1) and the smoke, as meridional points (r, z), all carried by+ the rings' field; each smoke particle also keeps its angle around the axis."""++ def __init__(self) -> None:+ rng = np.random.default_rng(3)+ ring_r, ring_z = np.array([1.0, 1.0]), np.array([0.0, 0.7])+ owner = np.repeat([0, 1], SMOKE)+ swirl = rng.uniform(0, m.TAU, 2 * SMOKE)+ spread = 0.09 * np.sqrt(-2 * np.log(rng.uniform(1e-4, 1, 2 * SMOKE)))+ spread = np.minimum(spread, 0.3)+ self.r = np.concatenate([ring_r, ring_r[owner] + spread * np.cos(swirl)])+ self.z = np.concatenate([ring_z, ring_z[owner] + spread * np.sin(swirl)])+ self.angle = rng.uniform(0, m.TAU, 2 * SMOKE)+ self.owner = owner+ self.swirl = swirl # where around its core each particle started+ self.t = 0.0++ def velocity(self, r: np.ndarray, z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ u_r, u_z = np.zeros_like(r), np.zeros_like(z)+ for i in (0, 1):+ a, b = induced(r, z, float(r[i]), float(z[i]))+ u_r, u_z = u_r + a, u_z + b+ return u_r, u_z++ def step(self, dt: float) -> None:+ """One RK4 step for rings and smoke together."""+ r, z = self.r, self.z+ k1 = self.velocity(r, z)+ k2 = self.velocity(r + dt / 2 * k1[0], z + dt / 2 * k1[1])+ k3 = self.velocity(r + dt / 2 * k2[0], z + dt / 2 * k2[1])+ k4 = self.velocity(r + dt * k3[0], z + dt * k3[1])+ self.r = r + dt / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])+ self.z = z + dt / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])+ self.t += dt++ def middle(self) -> float:+ return float(self.z[:2].mean())++ def smoke_points(self) -> np.ndarray:+ """The smoke on screen, in the frame moving with the pair (the axis along x)."""+ r, z = self.r[2:], self.z[2:] - self.middle()+ return SCALE * np.column_stack(+ [z, r * np.cos(self.angle), r * np.sin(self.angle)]+ )+++class VortexRings(m.ThreeDScene):+ def construct(self) -> None:+ flow = Flow()++ def advance(_: m.Mobject, dt: float) -> None:+ flow.step(TIME_SCALE * dt)++ clock = m.Mobject()+ clock.add_updater(advance)++ rgba = np.ones((2 * SMOKE, 4))+ rgba[:, :3] = np.array([m.ManimColor(c).to_rgb() for c in COLORS])[flow.owner]+ # bands of denser smoke, so the rolling around each core shows+ rgba[:, 3] = np.where(np.cos(3 * flow.swirl) > 0, 0.55, 0.22)+ smoke = m.PMobject(stroke_width=3.6)+ smoke.add_points(flow.smoke_points(), rgbas=rgba)++ def carry(mob: m.Mobject) -> None:+ mob.points = flow.smoke_points()++ smoke.add_updater(carry)+ # a floor that scrolls back as the pair moves forward+ floor = m.VGroup(+ *[+ m.Line([-9, y, -2.4], [9, y, -2.4], stroke_width=1.2, color=m.GREY_D)+ for y in np.linspace(-4, 4, 9)+ ]+ )+ rungs = m.VGroup(+ *[+ m.Line([0, -4, -2.4], [0, 4, -2.4], stroke_width=1.2, color=m.GREY_D)+ for _ in range(19)+ ]+ )++ def scroll(group: m.Mobject) -> None:+ shift = (-SCALE * flow.middle()) % 1.0+ for k, rung in enumerate(group.submobjects):+ rung.move_to([k - 9 + shift, 0, -2.4])++ rungs.add_updater(scroll)++ # HUD: Kelvin's impulse as a bar split between the rings: the split moves, the total stays+ title = m.Text("Leapfrogging smoke rings", font_size=38).to_corner(m.UL)+ subtitle = m.Text(+ "two vortex rings take turns passing through each other (Helmholtz, 1858)",+ font_size=22,+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)+ bar_height = 2.6+ frame = m.Rectangle(+ width=0.5, height=bar_height, stroke_width=1.5, color=m.GREY_B+ )+ frame.to_corner(m.UR).shift(0.55 * m.DOWN + 0.9 * m.LEFT)+ total0 = float(flow.r[0] ** 2 + flow.r[1] ** 2)++ def split() -> m.VGroup:+ share = float(flow.r[0] ** 2) / total0+ full = float(flow.r[0] ** 2 + flow.r[1] ** 2) / total0+ low = m.Rectangle(+ width=0.5, height=bar_height * share, stroke_width=0, fill_opacity=0.85+ ).set_fill(COLORS[0])+ high = m.Rectangle(+ width=0.5,+ height=bar_height * (full - share),+ stroke_width=0,+ fill_opacity=0.85,+ ).set_fill(COLORS[1])+ low.align_to(frame, m.DOWN).align_to(frame, m.LEFT)+ high.next_to(low, m.UP, buff=0).align_to(frame, m.LEFT)+ return m.VGroup(low, high)++ bar = m.always_redraw(split)+ total = m.DecimalNumber(total0, num_decimal_places=3, font_size=28)+ total.add_updater(lambda d: d.set_value(float(flow.r[0] ** 2 + flow.r[1] ** 2)))+ caption = m.VGroup(+ m.MathTex(+ r"r_1^2 + r_2^2 =",+ font_size=28,+ tex_to_color_map={"r_1^2": COLORS[0], "r_2^2": COLORS[1]},+ ),+ total,+ ).arrange(m.RIGHT, buff=0.1)+ caption.next_to(frame, m.DOWN, buff=0.2).align_to(frame, m.RIGHT).shift(+ 0.2 * m.RIGHT+ )+ self.add_fixed_in_frame_mobjects(title, subtitle)++ self.set_camera_orientation(+ phi=64 * m.DEGREES,+ theta=-118 * m.DEGREES,+ zoom=1.15,+ focal_distance=16,+ frame_center=np.array([0.0, 0.0, 0.55]),+ )+ self.add(floor, rungs, clock, smoke)+ self.wait(3)+ self.add_fixed_in_frame_mobjects(frame, bar, caption)+ self.remove(frame, bar, caption)+ self.play(m.FadeIn(frame), m.FadeIn(caption), run_time=1)+ self.add(bar)+ self.wait(6)+ # swing round to look along the axis: one ring through the other+ self.move_camera(phi=72 * m.DEGREES, theta=-162 * m.DEGREES, run_time=6)+ self.wait(4)+ self.move_camera(phi=66 * m.DEGREES, theta=-100 * m.DEGREES, run_time=5)+ closing = m.Text(+ "Kelvin's impulse ∝ r₁² + r₂² is conserved: when one ring shrinks, the"+ " other grows.",+ font_size=24,+ ).to_edge(m.DOWN, buff=0.35)+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(m.FadeIn(closing), run_time=1)+ self.wait(4)+++if __name__ == "__main__":+ VortexRings().render("vortex_rings.mp4")