"""Lecture 36: schematic of the aerodynamic centre of a straight tapered swept wing by strips. Each strip has its own
aerodynamic centre at its quarter chord; for a lift proportional to the strip's area and a straight quarter-chord line,
their weighted mean lies on that line at the spanwise station of the mean aerodynamic chord (flight.aero.tapered_wing).
Writes img/fig-36-swept-ac.png."""
import numpy as np
from matplotlib.patches import Polygon
from _visual import plt, save, MAROON, BLUE, INK, GREY
from flight import aero as AE

B, CR, LAM, SW = 10.0, 2.4, 0.4, np.radians(32)
_, _, MAC, Y_MAC = AE.tapered_wing(B, CR, LAM)


def x_quarter(y):
    return CR / 4 + np.abs(y) * np.tan(SW)


def x_le(y):
    return x_quarter(y) - AE.tapered_chord(y, B, CR, LAM) / 4


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    ys = np.array([-B / 2, 0, B / 2])
    pts = [(y, -x_le(y)) for y in ys] + [(y, -(x_le(y) + AE.tapered_chord(y, B, CR, LAM))) for y in ys[::-1]]
    ax.add_patch(Polygon(pts, closed=True, facecolor="#e6e1d6", edgecolor=INK, lw=1.6))
    for y in np.linspace(0.45, B / 2 - 0.45, 6):
        for s in (-1, 1):
            c = AE.tapered_chord(y, B, CR, LAM)
            ax.plot([s * y] * 2, [-x_le(y), -(x_le(y) + c)], color=GREY, lw=0.9)
            ax.plot(s * y, -x_quarter(y), "o", color=BLUE, ms=3 + 3 * c)
    yy = np.linspace(0, B / 2, 2)
    for s in (-1, 1):
        ax.plot(s * yy, -x_quarter(yy), color=BLUE, lw=1.4, ls="--")
        ax.plot(s * Y_MAC, -x_quarter(Y_MAC), "o", color=MAROON, ms=10, zorder=5)
    ax.plot([-Y_MAC, Y_MAC], [-x_quarter(Y_MAC)] * 2, color=MAROON, lw=1.4)
    ax.plot(0, -x_quarter(Y_MAC), "X", color=MAROON, ms=15, zorder=6)
    ax.annotate("aerodynamic centre\nof the whole wing", (0, -x_quarter(Y_MAC)), xytext=(0.8, -4.85), fontsize=12.5, color=MAROON,
                arrowprops=dict(arrowstyle="->", color=MAROON))
    ax.annotate("", xy=(5.6, -x_quarter(Y_MAC)), xytext=(5.6, -x_quarter(0)), arrowprops=dict(arrowstyle="<->", color=INK))
    ax.plot([0, 5.7], [-x_quarter(0)] * 2, color=GREY, lw=0.8, ls=":"); ax.plot([0, 5.7], [-x_quarter(Y_MAC)] * 2, color=GREY, lw=0.8, ls=":")
    ax.text(5.8, -(x_quarter(0) + x_quarter(Y_MAC)) / 2, "$y_{mac}\\,\\tan\\Lambda$", fontsize=13, va="center")
    ax.text(2.2, 0.15, "each dot: the aerodynamic centre of a strip,\nat its quarter chord; size shows its share of lift", fontsize=11, color=BLUE, ha="left")
    ax.annotate("", xy=(-5.0, -0.1), xytext=(-5.0, 0.7), arrowprops=dict(arrowstyle="-|>", color=GREY, lw=2)); ax.text(-4.85, 0.3, "flow", color=GREY, fontsize=12)
    ax.set_xlim(-5.8, 7.6); ax.set_ylim(-5.4, 0.9); ax.set_aspect("equal"); ax.axis("off")
    save(fig, "fig-36-swept-ac")
