"""Lecture 25, the forces on an aircraft at four points of a circular loop flown at constant speed with V^2/(gR) = 2
(flight.performance.loop_load_factor, Ojha eq. 11.48). At the bottom, quarter, top and three-quarter points: the weight
(down), the lift (towards the centre) and the load factor n = L/W = cos(theta) + 2, with arrows in units of the weight.
The lift plus the part of the weight along the radius gives the centripetal force 2 W, the same at every point.
Writes img/fig-25-loop-forces.png."""
import numpy as np
from matplotlib.patches import Circle
from _visual import plt, save, MAROON, BLUE, INK, GREY
from flight import performance as PF

K = 2.0                                                  # V^2/(g R)
V2_OVER_GR = K
POINTS = [(0.0, "bottom"), (np.pi / 2, "going up"), (np.pi, "top"), (3 * np.pi / 2, "coming down")]
N = [PF.loop_load_factor(th, np.sqrt(K), 1.0, g=1.0) for th, _ in POINTS]
R, U = 2.6, 0.55                                         # circle radius and arrow length per unit weight (drawing units)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(9, 7.6))
    ax.add_patch(Circle((0, 0), R, fill=False, edgecolor=GREY, lw=1.5, ls="--"))
    kw = dict(arrowstyle="-|>", lw=3, mutation_scale=20)
    for (th, name), n in zip(POINTS, N):
        p = R * np.array([np.sin(th), -np.cos(th)])
        inward = -p / R
        ax.plot(*p, "o", color=INK, ms=10, zorder=6)
        off = np.array([0.1, 0.0]) if name in ("bottom", "top") else np.array([0.0, 0.1])
        lt = p + inward * n * U
        ax.annotate("", xy=lt + off * (name in ("bottom", "top")), xytext=p + off * (name in ("bottom", "top")), arrowprops=dict(color=BLUE, **kw), zorder=5)
        wt = p + np.array([0.0, -U])
        shift = np.array([-0.14, 0.0]) if name in ("bottom", "top") else np.array([0.0, 0.0])
        ax.annotate("", xy=wt + shift, xytext=p + shift, arrowprops=dict(color=MAROON, **kw), zorder=5)
        lab = {"bottom": (0.0, -R - 0.95, "center", "top"), "going up": (R + 0.25, 0.2, "left", "center"),
               "top": (0.0, R + 0.35, "center", "bottom"), "coming down": (-R - 0.25, 0.2, "right", "center")}[name]
        ax.text(lab[0], lab[1], f"{name}: $n$ = {n:.0f}\n$L$ = " + ("" if round(n) == 1 else f"{n:.0f}") + "$W$", ha=lab[2], va=lab[3], fontsize=13)
    ax.annotate("", xy=(R * np.sin(0.62), -R * np.cos(0.62)), xytext=(R * np.sin(0.3), -R * np.cos(0.3)),
                arrowprops=dict(arrowstyle="-|>", color=INK, lw=1.5, connectionstyle="arc3,rad=0.12"))
    ax.text(0.0, 1.05, "lift $L$ (blue), towards the centre\nweight $W$ (maroon), always down",
            ha="center", va="center", fontsize=12.5)
    ax.text(0.0, -0.58, "$V^2/(gR)=2$: each point needs\n$2W$ towards the centre", ha="center", va="center", fontsize=12.5)
    ax.set_xlim(-4.4, 4.4); ax.set_ylim(-4.2, 3.7); ax.set_aspect("equal"); ax.axis("off")
    save(fig, "fig-25-loop-forces")
