"""Lecture 20, finding the flattest glide on the hodograph of Ojha's glider at 2 km: a ray from the origin to a point
moving along the curve from high speed towards the stall; its slope is the glide angle and the ratio of the two speeds
the glide ratio, largest where the ray touches the curve (fig-20-hodograph). Writes img/anim-20-tangent.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load

HD = load("fig-20-hodograph")
ok = HD.CL_ALL <= HD.G["CLmax"]
ST = HD.ST[ok][::-1]                     # from high speed (small C_L) towards the stall
IDX = np.linspace(0, len(ST) - 1, 60).astype(int)
idx_best = int(np.argmin(np.abs(HD.CL_ALL[ok][::-1] - HD.CL_STAR)))
IDX = np.unique(np.sort(np.append(IDX, idx_best)))
IDX = np.concatenate([IDX, [idx_best] * 12])             # end on the tangent

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5))
    fig.subplots_adjust(bottom=0.14)

    def frame(k):
        ax.clear()
        j = IDX[k]
        ax.plot(ST[:, 3], -ST[:, 2], color=MAROON, lw=2.6)
        v, s = ST[j, 3], ST[j, 2]
        ax.plot([0, 50], [0, -50 * s / v], color=BLUE, lw=1.8)
        ax.plot(v, -s, "o", color=BLUE, ms=9)
        ax.set_xlim(0, 50); ax.set_ylim(-2.5, 0.1)
        ax.set_xlabel("horizontal speed (m/s)"); ax.set_ylabel("vertical speed (m/s)")
        ax.set_title(f"$V={ST[j, 0]:.1f}$ m/s: glide ratio $V_h/\\dot h_s={v / s:.1f}$", fontsize=13, loc="left")
        for sp_ in ("top", "right"):
            ax.spines[sp_].set_visible(False)
        return []

    save_anim(fig, frame, len(IDX), 10, "anim-20-tangent", dpi=90, hold=2.0)
