"""Lecture 5, where the curvature term comes from: with no forces at all, a body moves in a straight line. Over a
round Earth the local horizon under it tilts as it moves, so its flight-path angle gamma (between the velocity
and the local horizon) grows by itself, at gamma-dot = V cos(gamma)/r at first V/r. The Earth is shrunk to make
the effect visible. Writes img/anim-05-curvature.gif."""
import numpy as np
from _visual import plt, save_anim, earth_disc, INK, MAROON, BLUE, GREY

H0 = 1.15                                                     # starting radius, in Earth radii
S = np.linspace(0.0, 1.25, 110)                               # distance travelled, Earth radii
POS = np.vstack([S, np.full_like(S, H0)])
GAMMA = np.arctan2(POS[0], POS[1])                            # angle between +x and the local horizon

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 6.6))
    kw = dict(arrowstyle="-|>", mutation_scale=16, lw=2.2)

    def frame(k):
        ax.clear()
        earth_disc(ax, 1.0)
        ax.plot(POS[0, :k + 1], POS[1, :k + 1], color=MAROON, lw=2, ls="--")
        p = POS[:, k]
        up = p / np.linalg.norm(p)
        hor = np.array([up[1], -up[0]])
        ax.plot(*np.array([p - 0.35 * hor, p + 0.35 * hor]).T, color=BLUE, lw=2)
        ax.plot([0, p[0]], [0, p[1]], color=GREY, lw=0.8, ls=":")
        ax.annotate("", xy=p + np.array([0.3, 0]), xytext=p, arrowprops=dict(color=MAROON, **kw))
        ax.plot(*p, "o", color=MAROON, ms=8)
        if GAMMA[k] > np.radians(3):
            a = np.linspace(-GAMMA[k], 0, 20)
            ax.plot(p[0] + 0.22 * np.cos(a), p[1] + 0.22 * np.sin(a), color=INK, lw=1)
            ax.text(p[0] + 0.25, p[1] - 0.1, "$\\gamma$", fontsize=14)
        ax.text(-1.45, 1.55, "no forces: the body moves in a straight line (red)", fontsize=12, color=MAROON)
        ax.text(-1.45, 1.4, "blue: the local horizon under it, which tilts as it moves", fontsize=12, color=BLUE)
        ax.text(-1.45, -1.2, f"flight-path angle $\\gamma$ = {np.degrees(GAMMA[k]):4.1f}°", fontsize=14)
        ax.set_xlim(-1.5, 1.75)
        ax.set_ylim(-1.3, 1.65)
        ax.set_aspect("equal")
        ax.axis("off")
        return []

    save_anim(fig, frame, len(S), 15, "anim-05-curvature")
