from manim import *
import numpy as np
import sympy as sp
def head(cn, en):
    t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
    s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
    return VGroup(t, s)
def foot(cn):
    return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
def bg_image(h=60, w=100, mode=0):
    a = np.zeros((h, w, 4), dtype=np.uint8)
    a[:, :, 3] = 255
    if mode == 0:
        a[:, :, 0] = np.linspace(10, 90, w, dtype=np.uint8)[None, :]
        a[:, :, 2] = np.linspace(60, 160, w, dtype=np.uint8)[None, :]
    elif mode == 1:
        a[:, :, 1] = np.linspace(20, 110, h, dtype=np.uint8)[:, None]
        a[:, :, 2] = np.linspace(40, 130, h, dtype=np.uint8)[:, None]
    else:
        a[:, :, 0] = 120
        a[:, :, 1] = 70
        a[:, :, 2] = np.linspace(30, 140, w, dtype=np.uint8)[None, :]
    return ImageMobject(a)
class TwistAnimation(Animation):
    def __init__(self, mobject, angle=PI, strength=1.0, **kwargs):
        self.base = mobject.get_all_points().copy()
        super().__init__(mobject, **kwargs)
        self.angle = angle
        self.strength = strength
    def interpolate_mobject(self, alpha):
        new = self.base.copy()
        for k, p in enumerate(self.base):
            r = np.linalg.norm(p[:2])
            th = alpha * self.angle * self.strength * max(0.0, 1 - r / 4.5)
            c, s = np.cos(th), np.sin(th)
            new[k, 0] = p[0] * c - p[1] * s
            new[k, 1] = p[0] * s + p[1] * c
        self.mobject.set_points(new)
class TwistCircle(Scene):
    def construct(self):
        self.add(head("旋转扭曲：圆形与网格", "strength = 1.6"))
        circ = Circle(radius=2.0, color=GREEN).set_stroke(width=6)
        grid = VGroup(*[Line(LEFT * 2.4 + UP * y, RIGHT * 2.4 + UP * y, color=GREY_B)
                        for y in (-1.2, -0.4, 0.4, 1.2)]).set_stroke(width=1.5, opacity=0.6)
        self.add(grid, circ)
        self.play(TwistAnimation(grid, angle=PI * 1.5, strength=1.6, run_time=4.4))
        self.play(FadeIn(foot("直接改写 mobject 的点数组，就能得到任意扭曲")), run_time=0.4)
        self.wait(1.2)
