"""Lecture 13, thickness drag on a double-wedge section at zero angle of attack in linear supersonic theory
(flight.aero.ackeret_cp, ackeret_thickness_drag). Left: the section (thickness exaggerated) with the pressure force on
each face: the front faces are pushed in, the rear faces are sucked out, and all four forces have a part pointing
downstream. Right: the wave-drag coefficient against t/c at three Mach numbers. Writes img/fig-13-double-wedge.png."""
import numpy as np
from matplotlib.patches import Polygon
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from flight import aero as AE

TC = np.linspace(0.0, 0.12, 200)
MACHS = [(1.4, MAROON), (2.0, BLUE), (3.0, GREEN)]
DRAWN = 0.22                                                  # thickness ratio of the sketch, exaggerated


def cd_from_faces(tc, mach):
    """C_Dw summed face by face: |C_p| x the face's frontal height t/2, over the chord, for four faces."""
    return 4 * abs(AE.ackeret_cp(tc, mach)) * tc / 2


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.8), gridspec_kw=dict(width_ratios=[1.15, 1]))
    fig.subplots_adjust(wspace=0.25)
    h = DRAWN / 2
    pts = np.array([[0, 0], [0.5, h], [1, 0], [0.5, -h]])
    a.add_patch(Polygon(pts, closed=True, facecolor="#e6e1d6", edgecolor=INK, lw=1.6))
    for p, q, front in ((pts[0], pts[1], True), (pts[1], pts[2], False), (pts[0], pts[3], True), (pts[3], pts[2], False)):
        mid = (p + q) / 2
        t = (q - p) / np.linalg.norm(q - p)
        n = np.array([-t[1], t[0]])
        if np.dot(n, mid - np.array([0.5, 0.0])) < 0:
            n = -n                                             # outward normal
        for s in (0.3, 0.7):
            r = p + s * (q - p)
            tail, tip = (r + 0.17 * n, r + 0.01 * n) if front else (r + 0.01 * n, r + 0.17 * n)
            a.annotate("", xy=tip, xytext=tail, arrowprops=dict(arrowstyle="-|>", color=MAROON if front else BLUE, lw=2.2, mutation_scale=14))
    a.annotate("", xy=(-0.12, 0), xytext=(-0.36, 0), arrowprops=dict(arrowstyle="-|>", color=INK, lw=2, mutation_scale=16))
    a.text(-0.24, 0.035, "flow", ha="center", fontsize=12)
    a.text(0.12, 0.36, "front faces:\npushed in", ha="center", fontsize=12, color=MAROON)
    a.text(0.9, 0.36, "rear faces:\nsucked out", ha="center", fontsize=12, color=BLUE)
    a.text(0.5, -0.43, "every force has a part\npointing downstream", ha="center", fontsize=12)
    a.set_xlim(-0.38, 1.18); a.set_ylim(-0.52, 0.5); a.set_aspect("equal"); a.axis("off")
    for M, c in MACHS:
        b.plot(100 * TC, AE.ackeret_thickness_drag(TC, M), color=c, lw=2.6, label=f"Mach {M:g}")
    b.set_xlim(0, 12); b.set_ylim(0, 0.062)
    b.set_xlabel("thickness ratio $t/c$ (%)"); b.set_ylabel("wave drag $C_{D_w}$")
    b.legend(frameon=False, fontsize=12, loc="upper left")
    despine(b)
    save(fig, "fig-13-double-wedge")
