from manim import *
import numpy as np
from PIL import Image, ImageDraw
def make_bg(mode, w=1920, h=1080):
    rng = np.random.default_rng(20250209 + mode)
    yy, xx = np.mgrid[0:h, 0:w]
    a = np.zeros((h, w, 4), dtype=np.float32)
    a[..., 3] = 255
    if mode == 0:
        d = np.exp(-(((xx - w * 0.72) / (w * 0.30)) ** 2 + ((yy - h * 0.42) / (h * 0.45)) ** 2))
        a[..., 0] = 40 + 150 * d + 20 * (xx / w)
        a[..., 1] = 8 + 60 * d
        a[..., 2] = 70 + 150 * d + 25 * (yy / h)
    elif mode == 1:
        a[..., 0] = 10 + 6 * (xx / w)
        a[..., 1] = 78 + 10 * np.sin(xx / 90) + rng.normal(0, 3, (h, w))
        a[..., 2] = 62 + 8 * np.cos(yy / 110) + rng.normal(0, 3, (h, w))
    else:
        a[..., 0] = 120 * (xx / w) + 40
        a[..., 1] = 90 * (1 - yy / h) + 30
        a[..., 2] = 150 * (yy / h) + 40
    a = np.clip(a, 0, 255).astype(np.uint8)
    if mode == 0:
        for _ in range(900):
            x = int(rng.integers(0, w))
            y = int(rng.integers(0, h))
            r = int(rng.integers(1, 3))
            c = int(rng.integers(180, 256))
            a[max(0, y - r):y + r + 1, max(0, x - r):x + r + 1, :3] = c
    if mode == 1:
        bd = 24
        a[:bd] = [150, 92, 40, 255]
        a[-bd:] = [150, 92, 40, 255]
        a[:, :bd] = [150, 92, 40, 255]
        a[:, -bd:] = [150, 92, 40, 255]
    if mode == 2:
        im = Image.fromarray(a[:, :, :3])
        dr = ImageDraw.Draw(im)
        for _ in range(28):
            x1 = int(rng.integers(0, w))
            y1 = int(rng.integers(0, h))
            x2 = int(rng.integers(0, w))
            y2 = int(rng.integers(0, h))
            col = tuple(int(v) for v in rng.integers(90, 256, 3))
            dr.line([(x1, y1), (x2, y2)], fill=col, width=int(rng.integers(2, 6)))
        a = np.dstack([np.array(im), np.full((h, w), 255, dtype=np.uint8)])
    return a
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)
class Method2ImageMobject(Scene):
    def construct(self):
        bg = ImageMobject(make_bg(1))
        bg.scale_to_fit_height(config.frame_height)
        bg.scale_to_fit_width(config.frame_width)
        bg.set_z_index(-100)
        self.add(bg)
        self.add(head("黑板背景：铺满画幅", "scale_to_fit_width"))
        math = MathTex(r"\int_0^\infty e^{-x^2}\,dx = \frac{\sqrt{\pi}}{2}", color=WHITE).scale(1.35)
        self.play(Write(math), run_time=2.4)
        self.play(math.animate.set_color(YELLOW), run_time=1.0)
        self.play(FadeIn(foot("铺满画幅后，前景公式处在最上层")), run_time=0.4)
        self.wait(2.4)
