#!/usr/bin/env python3
"""29 Spiral galaxy.

A tilted spiral galaxy with dust lanes, blue star clusters, pink gas clouds and
a faint nebula glow, in the style of a long-exposure telescope picture.
Fable 5.2 Python art experiment: every pixel comes from the code below.
The galaxy is first built face-on from a few formulas: a logarithmic spiral for
the arms, noise that is wound up along the arms for clumps, and dark dust lanes
that dim and redden the light behind them. That flat picture is then tilted into
the view, a round golden bulge is added, and about a million single stars are
scattered where the galaxy is bright. The result is processed like astronomy
data (a strong brightness stretch that lifts the faint outer arms).
Run: .venv/bin/python scripts/29-spiral-galaxy.py
"""
import os, time, math
import numpy as np
from PIL import Image
from scipy import ndimage as ndi

W, H = 1600, 2000
G = 2000                       # size of the face-on galaxy map
SEED = 29
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '29-spiral-galaxy.png')
F = np.float32
rng = np.random.default_rng(SEED)
CX, CY = 800.0, 985.0
SCALE = 900.0                  # pixels per galaxy unit
PA = math.radians(-57.0)       # direction of the long axis
INC = math.radians(54.0)       # tilt (0 = face-on)
EXT = 1.12


def smooth(a, b, x):
    t = np.clip((x - a) / (b - a + 1e-9), 0, 1)
    return t * t * (3 - 2 * t)


def vnoise(shape, cell, r, wrap_x=False):
    h, w = shape
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    gh, gw = int(h / cy) + 4, int(round(w / cx)) if wrap_x else int(w / cx) + 4
    g = r.random((gh, gw)).astype(F)
    if wrap_x:                                   # repeat the grid so that the noise joins up left to right
        g = np.concatenate([g, g, g], 1)
        z = ndi.zoom(g, (cy, w / gw), order=3)
        return z[int(cy * 1.5):int(cy * 1.5) + h, w:2 * w]
    z = ndi.zoom(g, (cy, cx), order=3 if min(cy, cx) >= 3 else 1)
    oy, ox = int(cy * 1.5), int(cx * 1.5)
    return z[oy:oy + h, ox:ox + w]


def fbm(shape, cell, octaves, r, wrap_x=False):
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    out = np.zeros(shape, F)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, (max(1.5, cy), max(1.5, cx)), r, wrap_x)
        tot += amp
        amp *= 0.55
        cy /= 2; cx /= 2
    return out / tot


def lookup(tex, u, v):
    """tex[v, u] with linear interpolation, wrapping in u."""
    h, w = tex.shape
    u = u % w
    v = np.clip(v, 0, h - 1.001)
    u0 = u.astype(np.int32); v0 = v.astype(np.int32)
    fu = u - u0; fv = v - v0
    u1 = (u0 + 1) % w
    return (tex[v0, u0] * (1 - fu) + tex[v0, u1] * fu) * (1 - fv) + (tex[v0 + 1, u0] * (1 - fu) + tex[v0 + 1, u1] * fu) * fv


def face_on():
    """Brightness of old stars, young stars and dust depth, seen from straight above."""
    ax = np.linspace(-EXT, EXT, G, dtype=F)
    xf, yf = np.meshgrid(ax, ax)
    r = np.hypot(xf, yf)
    th = np.arctan2(yf, xf)
    lr = np.log(np.maximum(r, 0.015))
    tanp = math.tan(math.radians(23.0))
    big = fbm((G, G), 520, 2, rng)
    psi = th - lr / tanp + 0.9 * (big - 0.5)                     # spiral phase: constant along an arm
    NW, NL = 1024, 640
    lr0, lr1 = math.log(0.015), math.log(EXT * 1.5)
    u = psi / (2 * math.pi) * NW
    v = (lr - lr0) / (lr1 - lr0) * (NL - 1)
    iso = fbm((G, G), 60, 5, rng)                                # ordinary cloud noise, not wound up
    iso2 = fbm((G, G), 22, 4, rng)
    clump = 0.3 * lookup(fbm((NL, NW), (22, 20), 4, rng, True), u, v) + 0.7 * iso
    clump2 = 0.3 * lookup(fbm((NL, NW), (12, 10), 3, rng, True), u, v) + 0.7 * iso2
    fil = 0.35 * lookup(fbm((NL, NW), (40, 16), 4, rng, True), u, v) + 0.65 * fbm((G, G), 80, 6, rng)
    fil2 = 0.3 * lookup(fbm((NL, NW), (18, 9), 4, rng, True), u, v) + 0.7 * fbm((G, G), 30, 5, rng)
    fine = fbm((G, G), 9, 3, rng)

    arm = (0.5 + 0.5 * np.cos(2 * psi)) ** 2.6
    spur = (0.5 + 0.5 * np.cos(4 * psi + 1.3)) ** 4 * smooth(0.38, 0.62, r) * 0.45
    arms = np.clip(arm + spur * (1 - arm), 0, 1)
    edge = smooth(1.02, 0.80, r + 0.10 * (big - 0.5))
    inner = smooth(0.05, 0.16, r)
    disc = np.exp(-r / 0.235) * edge
    old = disc * (0.24 + 0.90 * arms ** 0.8) * (0.7 + 0.6 * clump)
    bar = np.exp(-((xf * math.cos(0.6) + yf * math.sin(0.6)) / 0.13) ** 2 - ((-xf * math.sin(0.6) + yf * math.cos(0.6)) / 0.045) ** 2)
    old = old + 0.9 * bar
    young = np.exp(-r / 0.36) * edge * inner * arms ** 1.5 * (smooth(0.36, 0.66, clump) * 1.3 + 0.9 * smooth(0.42, 0.68, clump2)) * (0.6 + 0.8 * fine)
    young *= 3.0
    # dust: lanes on the inner side of each arm, broken into filaments
    lane = (0.5 + 0.5 * np.cos(2 * (psi + 0.42))) ** 5
    ridged = np.clip(1 - np.abs(2 * fil - 1) * 3.0, 0, 1) ** 1.3
    ridged2 = np.clip(1 - np.abs(2 * fil2 - 1) * 3.4, 0, 1) ** 1.3
    env = smooth(0.035, 0.10, r) * smooth(0.95, 0.55, r)
    tau = env * (2.3 * lane * (0.30 + 1.2 * ridged) + 0.8 * ridged2 * (0.25 + 0.75 * arms) + 0.35 * lane)
    tau += env * 0.8 * (0.5 + 0.5 * np.cos(4 * psi + 2.4)) ** 6 * ridged * smooth(0.3, 0.5, r)
    return xf, yf, r, old.astype(F), young.astype(F), tau.astype(F), arms.astype(F)


def main():
    xf, yf, rr, old, young, tau, arms = face_on()
    print('face-on maps %.1fs' % (time.time() - T0))
    # pink gas clouds (star-forming regions): small bright knots along the arms
    prob = (arms ** 3 * np.exp(-rr / 0.33) * smooth(0.14, 0.24, rr) * smooth(1.0, 0.8, rr) * (young + 0.02)).ravel().astype(np.float64)
    prob /= prob.sum()
    hrng = np.random.default_rng(31)
    idx = hrng.choice(G * G, 300, p=prob)
    hii = np.zeros((G, G), F)
    knots = np.zeros((G, G), F)
    hy, hx = np.divmod(idx, G)
    amp = hrng.lognormal(0, 0.8, len(idx)).astype(F)
    np.add.at(hii, (hy, hx), amp)
    hii_small = ndi.gaussian_filter(hii, 1.8) * 5 + ndi.gaussian_filter(hii, 5.0) * 22
    # blue clusters: more, smaller knots
    idx = hrng.choice(G * G, 2600, p=prob)
    ky, kx = np.divmod(idx, G)
    np.add.at(knots, (ky, kx), hrng.lognormal(0, 0.9, len(idx)).astype(F))
    knots = ndi.gaussian_filter(knots, 1.3) * 5 + ndi.gaussian_filter(knots, 3.5) * 14

    OLD = np.array([1.00, 0.84, 0.66], F)
    YOUNG = np.array([0.52, 0.72, 1.00], F)
    PINK = np.array([1.00, 0.34, 0.52], F)
    ext = np.array([0.80, 1.05, 1.45], F)                   # dust dims blue light more than red
    face = (old[..., None] * OLD * 1.0 + (young + 0.5 * knots)[..., None] * YOUNG * 1.15 + hii_small[..., None] * PINK * 0.9)
    face = face * np.exp(-tau[..., None] * ext[None, None, :])
    # faint brown glow of the dust itself keeps the lanes from going pure black
    face += (tau * np.exp(-rr / 0.3) * 0.012)[..., None] * np.array([0.9, 0.5, 0.3], F)

    # ------------------------------------------------------------ tilt into the view
    yy, xx = np.mgrid[0:H, 0:W].astype(F)
    dx, dy = xx - CX, yy - CY
    ca, sa = math.cos(PA), math.sin(PA)
    a = (dx * ca + dy * sa) / SCALE
    b = (-dx * sa + dy * ca) / SCALE
    gx = (a + EXT) / (2 * EXT) * (G - 1)
    gy = (b / math.cos(INC) + EXT) / (2 * EXT) * (G - 1)
    img = np.stack([ndi.map_coordinates(face[..., i], [gy, gx], order=1, mode='constant') for i in range(3)], -1)
    tau_v = ndi.map_coordinates(tau, [gy, gx], order=1, mode='constant')
    # round bulge of old golden stars; the dust in front of it only hides its near side
    rb = np.hypot(a, b / 0.80)
    bulge = 2.6 * np.exp(-(rb / 0.016) ** 0.42) + 0.5 * np.exp(-(rb / 0.004) ** 0.8) * 6
    near = smooth(-0.03, 0.05, b)
    img += bulge[..., None] * np.array([1.0, 0.84, 0.60], F) * np.exp(-tau_v[..., None] * (0.25 + 0.85 * near[..., None]) * ext)
    # wide faint halo
    re = np.hypot(a, b / math.cos(INC))
    img += (np.exp(-re / 0.42) * 0.010)[..., None] * np.array([0.7, 0.8, 1.0], F)
    print('projected %.1fs' % (time.time() - T0))

    # ------------------------------------------------------------ about a million single stars in the disc
    lum = (face @ np.array([0.3, 0.4, 0.3], F)).ravel().astype(np.float64)
    lum = lum ** 0.8
    lum /= lum.sum()
    srng = np.random.default_rng(32)
    n = 1100000
    idx = srng.choice(G * G, n, p=lum)
    sy, sx = np.divmod(idx, G)
    fxs = (sx + srng.random(n)) / (G - 1) * 2 * EXT - EXT
    fys = (sy + srng.random(n)) / (G - 1) * 2 * EXT - EXT
    av = fxs * SCALE
    bv = fys * math.cos(INC) * SCALE + srng.normal(0, 2.0, n)        # the disc has a little thickness
    px = CX + av * ca - bv * sa
    py = CY + av * sa + bv * ca
    ok = (px >= 0) & (px < W - 1) & (py >= 0) & (py < H - 1)
    wgt = srng.lognormal(0, 1.0, n)[ok]
    grains = np.bincount((py[ok].astype(int) * W + px[ok].astype(int)), weights=wgt, minlength=W * H).reshape(H, W).astype(F)
    grains = ndi.gaussian_filter(grains, 0.55)
    tint = img / (img.max(-1, keepdims=True) + 1e-4)
    img += grains[..., None] * (tint * 0.6 + 0.4) * 0.05

    # ------------------------------------------------------------ deep sky: faint nebula, far galaxies, foreground stars
    nrng = np.random.default_rng(33)
    n1 = fbm((H, W), 420, 5, nrng)
    n2 = fbm((H, W), 300, 5, nrng)
    n3 = fbm((H, W), 120, 5, nrng)
    wisps = (1 - np.abs(2 * n3 - 1)) ** 3
    neb = smooth(0.50, 0.80, n1)[..., None] * np.array([0.050, 0.012, 0.022], F) * (0.4 + 1.2 * wisps[..., None]) \
        + smooth(0.52, 0.82, n2)[..., None] * np.array([0.006, 0.022, 0.034], F) * (0.5 + wisps[..., None])
    corner = smooth(0.25, 0.75, np.hypot((xx - 150) / W, (yy - 1850) / H) * -1 + 0.85) + 0.5 * smooth(0.3, 0.8, 0.8 - np.hypot((xx - 1500) / W, (yy - 120) / H))
    img += neb * (0.35 + 1.5 * corner[..., None])
    img += np.array([0.0030, 0.0036, 0.0065], F)
    # a few far-away galaxies
    for (gx_, gy_, s_, e_, ang_, c_) in ((250, 330, 13, 0.35, 0.6, (1.0, 0.8, 0.6)), (1390, 1700, 9, 0.7, 2.1, (0.8, 0.85, 1.0)),
                                         (1280, 250, 6, 0.5, 1.2, (1.0, 0.75, 0.55)), (180, 1280, 7, 0.25, 2.6, (0.9, 0.85, 0.9)),
                                         (1480, 980, 5, 0.6, 0.3, (1.0, 0.8, 0.7)), (620, 1880, 5, 0.4, 1.0, (0.85, 0.9, 1.0))):
        u_ = (xx - gx_) * math.cos(ang_) + (yy - gy_) * math.sin(ang_)
        v_ = -(xx - gx_) * math.sin(ang_) + (yy - gy_) * math.cos(ang_)
        d_ = np.hypot(u_, v_ / e_)
        img += (np.exp(-(d_ / s_) ** 0.7) * 0.09)[..., None] * np.array(c_, F)
    # foreground stars of our own galaxy
    ns = 2600
    fx = nrng.uniform(0, W, ns); fy = nrng.uniform(0, H, ns)
    fb = nrng.pareto(1.25, ns).astype(F) * 0.02 + 0.006
    fb = np.minimum(fb, 6.0)
    temp = nrng.random(ns)
    fcol = np.stack([np.interp(temp, [0, 0.5, 1], [1.0, 1.0, 0.70]), np.interp(temp, [0, 0.5, 1], [0.62, 0.94, 0.82]),
                     np.interp(temp, [0, 0.5, 1], [0.38, 0.86, 1.0])], 1).astype(F)
    pts = np.zeros((H, W, 3), F)
    for i in range(ns):
        x0, y0 = int(fx[i]), int(fy[i])
        if 1 <= x0 < W - 1 and 1 <= y0 < H - 1:
            pts[y0, x0] += fcol[i] * fb[i]
    stars = ndi.gaussian_filter(pts, (0.75, 0.75, 0)) * 9 + ndi.gaussian_filter(pts, (2.2, 2.2, 0)) * 6 + ndi.gaussian_filter(pts, (9, 9, 0)) * 5
    img += stars
    # diffraction spikes on the brightest stars
    order = np.argsort(-fb)[:16]
    for i in order:
        L = int(26 + 60 * min(1.0, fb[i] / 1.5))
        x0, y0 = int(fx[i]), int(fy[i])
        ys, xs = slice(max(0, y0 - L), min(H, y0 + L + 1)), slice(max(0, x0 - L), min(W, x0 + L + 1))
        ddx, ddy = xx[ys, xs] - fx[i], yy[ys, xs] - fy[i]
        k = min(1.0, fb[i] / 1.2) * 0.9 + 0.25
        spike = np.exp(-(ddy / 0.9) ** 2) * np.exp(-np.abs(ddx) / (L * 0.28)) + np.exp(-(ddx / 0.9) ** 2) * np.exp(-np.abs(ddy) / (L * 0.28))
        d1, d2 = (ddx + ddy) / 1.414, (ddx - ddy) / 1.414
        spike += 0.25 * (np.exp(-(d2 / 0.8) ** 2) * np.exp(-np.abs(d1) / (L * 0.12)) + np.exp(-(d1 / 0.8) ** 2) * np.exp(-np.abs(d2) / (L * 0.12)))
        core = np.exp(-(ddx ** 2 + ddy ** 2) / (2 * (1.6 + 1.6 * k) ** 2))
        img[ys, xs] += (spike * 0.55 * k + core * 1.6 * k)[..., None] * (fcol[i] * 0.6 + 0.4)
    print('stars %.1fs' % (time.time() - T0))

    # ------------------------------------------------------------ stretch like telescope data
    hi = np.clip(img - 0.9, 0, 6)
    img += 0.10 * ndi.gaussian_filter(hi, (10, 10, 0))
    lumv = img.max(-1, keepdims=True)
    k = 13.0
    stretched = np.arcsinh(lumv * k) / np.arcsinh(2.2 * k)
    img = img / (lumv + 1e-6) * stretched
    img = np.clip(img, 0, 1)
    gmean = img.mean(-1, keepdims=True)
    img = np.clip(gmean + (img - gmean) * 1.25, 0, 1)
    img = img ** 1.25
    vig = 1 - 0.25 * smooth(0.55, 1.2, np.hypot((xx - W / 2) / W, (yy - H / 2) / H) * 1.7)
    img *= vig[..., None]
    img += rng.normal(0, 0.006, (H, W, 3)).astype(F)
    Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
    print('saved %s  %.1fs' % (os.path.abspath(OUT), time.time() - T0))


if __name__ == '__main__':
    main()
