"""Lecture 11, why airliner wings are swept: only the flow component normal to the leading edge, M cos(sweep), sets
the transonic behaviour (flight.gasdynamics.normal_mach). Left: the decomposition on a swept wing. Right: the normal
Mach number against sweep at cruise Mach 0.78 and 0.85. Writes img/fig-11-sweep.png."""
import numpy as np
from matplotlib.patches import Polygon, FancyArrowPatch
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import gasdynamics as GD

SWEEP = np.radians(25.0)
LAMBDA = np.radians(np.linspace(0, 45, 91))
CASES = [(0.78, MAROON), (0.85, BLUE)]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.0), gridspec_kw=dict(width_ratios=[1, 1.25]))
    fig.subplots_adjust(wspace=0.25)
    t = np.tan(SWEEP)
    wing = np.array([[0, 0], [4, -4 * t], [4, -4 * t - 0.8], [0, -1.8]])
    a1.add_patch(Polygon(wing, closed=True, facecolor="#e6e0d2", edgecolor=INK, lw=1.5))
    e = np.array([np.cos(SWEEP), -np.sin(SWEEP)])      # along the leading edge, outboard
    nrm = np.array([-np.sin(SWEEP), -np.cos(SWEEP)])   # normal to the leading edge, into the wing
    L = 2.6
    S0 = np.array([2.4, 2.4])                          # the free stream comes from above (the aircraft flies up)
    def arrow(start, vec, c):
        a1.add_patch(FancyArrowPatch(tuple(start), tuple(start + vec), arrowstyle="-|>", mutation_scale=20, color=c, lw=2.4))
    arrow(S0, np.array([0.0, -L]), INK)
    arrow(S0, nrm * L * np.cos(SWEEP), MAROON)
    arrow(S0 + nrm * L * np.cos(SWEEP), e * L * np.sin(SWEEP), GREEN)
    a1.text(S0[0] + 0.12, S0[1] - 1.2, "$M$", color=INK, fontsize=14)
    a1.text(S0[0] - 1.95, S0[1] - 1.0, "$M\\cos\\Lambda$", color=MAROON, fontsize=14)
    a1.text(S0[0] - 0.6, S0[1] - L - 0.55, "along the edge", color=GREEN, fontsize=13)
    a1.text(1.0, -0.2, f"$\\Lambda={np.degrees(SWEEP):.0f}^\\circ$", fontsize=13)
    a1.plot([0, 0.9], [0, 0], color=GREY, lw=1, ls=":")
    a1.set_xlim(-0.4, 4.4); a1.set_ylim(-3.2, 2.7); a1.set_aspect("equal"); a1.axis("off")
    for M, c in CASES:
        a2.plot(np.degrees(LAMBDA), GD.normal_mach(M, LAMBDA), color=c, lw=2.5, label=f"cruise $M={M}$")
        mn = GD.normal_mach(M, SWEEP)
        a2.plot(25, mn, "o", color=c, ms=7)
        a2.text(26.5, mn + 0.006, f"{mn:.2f}", color=c, fontsize=12)
    a2.set_xlabel("sweep angle $\\Lambda$ (deg)"); a2.set_ylabel("normal Mach number $M\\cos\\Lambda$")
    a2.legend(frameon=False, fontsize=12, loc="lower left")
    despine(a2)
    save(fig, "fig-11-sweep")
