"""Warp drives: the view from the bridge, the bubble's cost, and a shell of ordinary matter.

Copyright (c) 2026 Hugo Flayac. All rights reserved. You may download and run this script,
modified or not, for the sole purpose of checking the result. Do not redistribute it.

Every number of the page "What a warp drive would really look like" is printed here.
Units: c = G = 1, lengths in bubble (or shell) radii R.

1. The Alcubierre bubble in the frame that moves with it (xi = x - v t):
       ds^2 = -dt^2 + (dxi + w dt)^2 + dy^2 + dz^2,     w(r) = v (1 - f(r)),
   f = 1 in the cabin and 0 far away. Here f has a cosine-squared wall between r = inner and
   r = 1. The slices are flat and the lapse is 1, so free-falling observers are those at rest
   on the slices: the bridge (w = 0) and the distant stars (w = v).
   Light: H = (|p|^2 - Omega^2) / 2, Omega = p_t - w p_xi, p_t conserved; a photon's energy
   for a free-falling observer is |Omega|. Hamilton's equations are integrated backwards
   from the bridge (Dormand-Prince, order 8). Colour shift: g = E_bridge / E_star.
   Thin-wall limit, by hand: grad w is radial and the crossing instantaneous, so the
   direction is unchanged and g = 1 + v cos(angle from the bow).
2. Energy density for free-falling observers (Alcubierre 1994):
       rho = -(v^2 / 32 pi) f'^2 (y^2 + z^2) / r^2,   total  E = -(v^2 / 12) int r^2 f'^2 dr.
3. Light sent forward from the cabin obeys dxi/dt = 1 - w on the axis: it stalls where
   f = 1 - 1/v.
4. A static shell of matter: outside, Schwarzschild's metric (Birkhoff). Bending of light at
   impact parameter b by a mass M: exact integral. Thin shell of radius R, compactness
   C = 2M/R, u = sqrt(1 - C): surface energy (1 - u) / (4 pi R), surface pressure
   (1 - u)^2 / (16 pi R u) (Israel 1966). Pressure <= energy holds if and only if C <= 24/25.

Checks: two reference values obtained independently (another integrator, another session:
0.8 c, sightline at 45 degrees, a bubble that is all wall: source at 47.245 degrees,
g = 1.54309), the thin-wall limit, a tighter tolerance, and the weak-field bending 4M/b.

Run:  python warp-drive.py [output_prefix]      (numpy, scipy and Pillow; about a minute)
"""

import sys

import numpy as np
from scipy.integrate import quad, solve_ivp

G_SI, C_SI, M_SUN, M_JUP = 6.67430e-11, 299792458.0, 1.98847e30, 1.89813e27


def wall(r, inner):
    r = np.asarray(r, float)
    s = np.clip((r - inner) / (1 - inner), 0.0, 1.0)
    f = np.cos(0.5 * np.pi * s) ** 2
    df = np.where((s > 0) & (s < 1), -0.5 * np.pi * np.sin(np.pi * s) / (1 - inner), 0.0)
    return f, df


def ray(v, inner, state, sign, t_span, rtol, t_eval=None, events=None):
    """Hamilton's equations for light, p_t = -1. sign = -1 integrates backwards in the affine
    parameter; sign = +1 forwards, in coordinate time."""
    def rhs(_, y):
        x, yy, px, py = y
        r = np.hypot(x, yy)
        f, df = wall(r, inner)
        w = v * (1 - f)
        omega = -1.0 - w * px
        dw = -v * df
        gx, gy = (dw * x / r, dw * yy / r) if r > 0 else (0.0, 0.0)
        d = np.array([px + omega * w, py, -omega * px * gx, -omega * px * gy])
        return -d if sign < 0 else d / (-omega)

    return solve_ivp(rhs, t_span, state, rtol=rtol, atol=1e-12, method="DOP853", t_eval=t_eval, events=events)


def seen_from_bridge(v, alpha, inner, rtol=1e-10):
    """A sightline at `alpha` from the bow: (direction of the star in the stars' frame, g)."""
    def outside(_, y):
        return np.hypot(y[0], y[1]) - 1.5

    outside.terminal, outside.direction = True, 1
    start = [1e-9 * np.cos(alpha), 1e-9 * np.sin(alpha), -np.cos(alpha), -np.sin(alpha)]
    sol = ray(v, inner, start, -1, [0, 400], rtol, events=outside)
    if sol.status != 1:
        return np.nan, 0.0
    px, py = sol.y[2, -1], sol.y[3, -1]
    return float(np.arctan2(-py, -px)), float(1.0 / (1.0 + v * px))


def flash(v, inner, directions, t_end, steps):
    angles = np.linspace(0, 2 * np.pi, directions, endpoint=False)
    times = np.linspace(0, t_end, steps)
    xs, ys = np.empty((steps, directions)), np.empty((steps, directions))
    for j, a in enumerate(angles):
        sol = ray(v, inner, [1e-9 * np.cos(a), 1e-9 * np.sin(a), np.cos(a), np.sin(a)], 1, [0, t_end], 1e-9, t_eval=times)
        xs[:, j], ys[:, j] = sol.y[0], sol.y[1]
    return times, xs, ys


def energy(v, inner):
    value, _ = quad(lambda r: r**2 * wall(r, inner)[1] ** 2, inner, 1.0, epsabs=1e-13, epsrel=1e-12)
    return -(v**2 / 12) * value


def bending(b, mass):
    roots = np.roots([1, 0, -b * b, 2 * mass * b * b])
    u0 = 1 / max(root.real for root in roots if abs(root.imag) < 1e-9)

    def integrand(t):
        u = u0 * (1 - t * t)
        return 2 * u0 * t / np.sqrt(max(1 / (b * b) - u * u * (1 - 2 * mass * u), 1e-300))

    return 2 * quad(integrand, 0, 1, epsabs=1e-12, epsrel=1e-12, limit=400)[0] - np.pi


def save_layer(values, path):
    """A white image whose transparency carries the values: the page supplies the colour."""
    from PIL import Image

    alpha = (np.clip(values, 0, 1) * 255).astype(np.uint8)
    rgba = np.dstack([np.full_like(alpha, 255)] * 3 + [alpha])
    Image.fromarray(rgba, "RGBA").save(path, quality=90, method=6)


def figure(prefix, inner=0.7, size=(1600, 720)):
    """Five flashes of light sent from the cabin, one every 0.9 R/c: left at 0.8 c, right at 1.5 c.
    Ink: the wavefronts, the wall's two radii, the cabin. Accent: the surface the light sent
    forward cannot cross at 1.5 c (f = 1 - 1/v), and the fronts that pile up against it."""
    from PIL import Image, ImageDraw, ImageFilter

    scale, half = 110, size[0] // 2
    ink = Image.new("L", size, 0)
    accent = Image.new("L", size, 0)
    for panel, v in enumerate((0.8, 1.5)):
        cx, cy = half // 2 + 150, size[1] // 2
        p_ink, p_acc = Image.new("L", (half - 8, size[1]), 0), Image.new("L", (half - 8, size[1]), 0)
        d_ink, d_acc = ImageDraw.Draw(p_ink), ImageDraw.Draw(p_acc)
        times, xs, ys = flash(v, inner, 720, 4.5, 301)
        for age in np.arange(0.9, 4.51, 0.9):
            i = int(np.searchsorted(times, age))
            x, y = cx + np.append(xs[i], xs[i][0]) * scale, cy - np.append(ys[i], ys[i][0]) * scale
            # A front is drawn where neighbouring rays are still neighbours.
            gap = np.hypot(np.diff(x), np.diff(y))
            for k in np.nonzero(gap < 5 * np.median(gap) + 2)[0]:
                d_ink.line([(x[k], y[k]), (x[k + 1], y[k + 1])], fill=int(255 * (1.05 - 0.5 * age / 4.5)), width=3)
        for radius, shade in ((1.0, 150), (inner, 90)):
            r = radius * scale
            d_ink.ellipse([cx - r, cy - r, cx + r, cy + r], outline=shade, width=2)
        d_ink.ellipse([cx - 5, cy - 5, cx + 5, cy + 5], fill=255)
        if v > 1:
            stall = inner + 2 / np.pi * np.arccos(np.sqrt(1 - 1 / v)) * (1 - inner)
            r = stall * scale
            d_acc.arc([cx - r, cy - r, cx + r, cy + r], -75, 75, fill=255, width=6)
            times, xs, _ = flash(v, inner, 8, 7.2, 3)
            print(f"figure: at {v} c the forward flash reaches {xs[-1].max():.4f} R after {times[-1]:.1f} R/c; "
                  f"it stalls at {stall:.4f} R")
        ink.paste(p_ink, (panel * half + 4, 0))
        accent.paste(p_acc, (panel * half + 4, 0))
    save_layer(np.asarray(ink.filter(ImageFilter.GaussianBlur(0.6)), np.float32) / 255, f"{prefix}-ink.webp")
    save_layer(np.asarray(accent.filter(ImageFilter.GaussianBlur(0.8)), np.float32) / 255, f"{prefix}-accent.webp")


def main():
    prefix = sys.argv[1] if len(sys.argv) > 1 else "warp-flash"
    inner = 0.7
    deg = np.degrees

    print("-- checks")
    s, g = seen_from_bridge(0.8, np.radians(45), 0.0)
    print(f"reference, all-wall bubble, 0.8 c, 45 deg: source {deg(s):.3f} deg, g {g:.5f}   (47.245, 1.54309)")
    s, g = seen_from_bridge(1.2, np.radians(135), 0.0)
    print(f"reference, all-wall bubble, 1.2 c, 135 deg: source {deg(s):.3f} deg, g {g:.5f}   (122.887, 0.34841)")
    s, g = seen_from_bridge(0.8, np.radians(45), 0.999)
    print(f"thin wall (0.1% of R), 0.8 c, 45 deg: source {deg(s):.3f} deg, g {g:.5f}   (45, 1 + v cos = {1 + 0.8 * np.cos(np.radians(45)):.5f})")
    a, b = seen_from_bridge(0.9, 2.0, inner, 1e-10), seen_from_bridge(0.9, 2.0, inner, 1e-12)
    print(f"tolerance 1e-10 against 1e-12: direction changes by {abs(a[0] - b[0]):.1e} rad, g by {abs(a[1] - b[1]):.1e}")
    print(f"weak-field bending at b = 200 R, M = 0.2 R: {bending(200.0, 0.2):.6f} rad   (4M/b = {0.8 / 200:.6f})")

    print("-- the view from the bridge (wall: 30% of the radius)")
    alphas = np.radians(np.arange(1, 180, 2.0))
    for v in (0.5, 0.9, 0.99):
        sources = np.array([seen_from_bridge(v, x, inner)[0] for x in alphas])
        print(f"{v} c: largest shift of a star's position {deg(np.nanmax(np.abs(sources - alphas))):.2f} deg; "
              f"colour shift dead ahead {seen_from_bridge(v, 1e-4, inner)[1]:.4f}, dead astern {seen_from_bridge(v, np.pi - 1e-4, inner)[1]:.4f}")
    for v in (1.5, 2.0):
        seen = [(x, *seen_from_bridge(v, x, inner)) for x in np.radians(np.arange(0.5, 180, 0.5))]
        last = max(source for _, source, g in seen if g > 0)
        limit = np.arccos(-1 / v)
        print(f"{v} c: last star seen {deg(last):.2f} deg from the bow (arccos(-1/v) = {deg(limit):.2f}); "
              f"share of the sky no longer seen {(1 - 1 / v) / 2:.3f}; colour shift dead ahead {seen_from_bridge(v, 1e-4, inner)[1]:.4f}")

    print("-- the bubble's cost")
    for radius, inner_wall, name in ((100, 0.7, "30 m"), (100, 0.99, "1 m")):
        kg = energy(1.0, inner_wall) * radius * C_SI**2 / G_SI
        print(f"light speed, radius {radius} m, wall {name}: {kg / M_SUN:.4f} solar masses = {kg / M_JUP:.1f} Jupiter masses")
    print(f"forward light at 1.5 c stalls where f = 1 - 1/v = {1 - 1 / 1.5:.4f}")

    print("-- a shell of ordinary matter, radius 100 m")
    for c in (0.4, 24 / 25):
        u = np.sqrt(1 - c)
        sigma, p = (1 - u) / (4 * np.pi), (1 - u) ** 2 / (16 * np.pi * u)
        kg = c * 100 * C_SI**2 / (2 * G_SI)
        disc = 1 / u if c < 2 / 3 else 3 * np.sqrt(3) * c / 2
        print(f"C = {c:.2f}: mass {kg:.3e} kg = {kg / M_JUP:.1f} Jupiters; pressure / energy = {p / sigma:.4f}; "
              f"clocks inside at {u:.4f}; dark disc {disc:.3f} R; black hole of the same mass {3 * np.sqrt(3) * c / 2:.3f} R")
    for b in (1.3, 2.0, 5.0):
        print(f"bending at {b} R for C = 0.4: {deg(bending(b, 0.2)):.3f} deg")

    figure(prefix)


if __name__ == "__main__":
    main()
