from manim import *
import numpy as np
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 SphericalDemo(ThreeDScene):
    def construct(self):
        self.set_camera_orientation(phi=65 * DEGREES, theta=-40 * DEGREES)
        self.add_fixed_in_frame_mobjects(head("球极坐标可视化", "Sphere / (r, theta, phi)"))
        R = 1.8
        axes = ThreeDAxes(x_length=5, y_length=5, z_length=5,
                          axis_config={"color": GREY_B})
        sphere = Sphere(radius=R, resolution=(24, 24)).set_fill(BLUE, opacity=0.10)
        sphere.set_stroke(BLUE_E, width=1, opacity=0.5)
        grid = VGroup()
        for i in range(1, 6):
            z = R * np.cos(i * PI / 6)
            rr = R * np.sin(i * PI / 6)
            lat = Circle(radius=rr, color=BLUE_E).set_stroke(width=1.5, opacity=0.45)
            lat.shift(z * OUT)
            grid.add(lat)
        for k in range(6):
            mer = Circle(radius=R, color=BLUE_E).set_stroke(width=1.5, opacity=0.35)
            mer.rotate(PI / 2, axis=RIGHT).rotate(k * PI / 6, axis=OUT)
            grid.add(mer)
        def spiral(t):
            phi = 0.25 + (t / (4 * PI)) * (PI - 0.5)
            rad = R * 1.02
            return np.array([rad * np.sin(phi) * np.cos(t),
                             rad * np.sin(phi) * np.sin(t),
                             rad * np.cos(phi)])
        curve = ParametricFunction(spiral, t_range=[0, 4 * PI, 0.02], color=RED).set_stroke(width=6)
        self.add(axes, sphere, grid)
        self.play(Create(curve), run_time=3.4)
        self.begin_ambient_camera_rotation(rate=0.15)
        self.wait(2.0)
        self.stop_ambient_camera_rotation()
        self.add_fixed_in_frame_mobjects(foot("红色螺旋：theta 绕轴旋转，phi 由北极走向南极"))
        self.wait(1.2)
