"""Lecture 34, equilibrium glide of a representative glider (B = 300 kg/m^2) at L/D 0.5, 1 and 2: height against speed.
Dashed: Vinh's equilibrium glide. Solid: simulator started on it. Dotted (L/D 1): started level at the same height,
which leaves a slowly damped oscillation about the glide. Writes img/fig-34-glide.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK
import _entry33 as X
from flight import entry as E
from flight.constants import MU, R_EARTH, RHO0_SL

CASES = [(0.5, GREEN), (1.0, BLUE), (2.0, MAROON)]


def curve(ld):
    """The equilibrium glide: (speed, height) arrays."""
    u = np.linspace(0.04, 0.95, 300)
    h = np.full_like(u, 60e3)
    for _ in range(6):
        h = E.altitude_of_density(E.glide_density(u, X.GLIDE_B, ld, R_EARTH + h), RHO0_SL, X.H)
    return np.sqrt(u * MU / (R_EARTH + h)), h


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.5), gridspec_kw=dict(wspace=0.28))
    for ld, c in CASES:
        V, h = curve(ld)
        tr = X.glide(ld)
        a.plot(tr.V / 1e3, tr.h / 1e3, color=c, lw=2.4, label=f"L/D = {ld:g}")
        a.plot(V / 1e3, h / 1e3, color=INK, lw=1.2, ls="--")
        b.plot(tr.downrange / 1e3, tr.h / 1e3, color=c, lw=2.2)
    lv = X.glide(1.0, True)
    b.plot(lv.downrange / 1e3, lv.h / 1e3, color=BLUE, lw=1.6, ls=":")
    a.set_xlabel("speed (km/s)"); a.set_ylabel("height (km)"); a.set_xlim(0, 7.9); a.set_ylim(20, 100)
    b.set_xlabel("distance along the ground (km)"); b.set_ylabel("height (km)"); b.set_ylim(20, 100)
    despine(a); despine(b)
    fig.legend(*a.get_legend_handles_labels(), frameon=False, fontsize=11, ncol=3, loc="upper center", bbox_to_anchor=(0.5, 0.0))
    save(fig, "fig-34-glide")
