#!/usr/bin/env python3
"""05 Lighthouse in a storm.

Torn storm clouds, a cliff with a lighthouse, layered breaking waves,
a particle simulation for the spray, a light beam through slanted rain,
then a heavy brush-stroke repaint.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/05-lighthouse-storm.py
"""
import os, sys, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

# ----------------------------------------------------------------------------
# Shared helper code (copied into every script so that each script runs alone)
# ----------------------------------------------------------------------------
W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
F32 = np.float32


def hexc(s):
    s = s.lstrip('#')
    return np.array([int(s[i:i + 2], 16) for i in (0, 2, 4)], F32) / 255.0


def c8(c):
    return tuple(int(max(0, min(255, round(float(v) * 255)))) for v in c)


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


def mix(a, b, t):
    return a + (b - a) * t


def ramp(t, stops):
    """Colour gradient. stops = [(position, '#hex'), ...]; t is an array."""
    pos = [p for p, _ in stops]
    cols = np.array([hexc(c) if isinstance(c, str) else c for _, c in stops])
    return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F32)


def vnoise(shape, cell, rng):
    """Smooth value noise in 0..1: a random grid, enlarged with cubic interpolation."""
    h, w = shape
    cy, cx = (cell, cell) if np.isscalar(cell) else cell
    cy, cx = max(1.0, float(cy)), max(1.0, float(cx))
    gh, gw = int(h / cy) + 4, int(w / cx) + 4
    g = rng.random((gh, gw)).astype(F32)
    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)
    z = z[oy:oy + h, ox:ox + w]
    if z.shape != (h, w):
        z = np.pad(z, ((0, h - z.shape[0]), (0, w - z.shape[1])), mode='edge')
    return z


def fbm(shape, cell, octaves, rng, gain=0.5, lac=2.0):
    """Fractal noise in about 0..1 (sum of value noise octaves)."""
    cy, cx = (cell, cell) if np.isscalar(cell) else cell
    out = np.zeros(shape, F32)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, (cy, cx), rng)
        tot += amp
        amp *= gain
        cy /= lac
        cx /= lac
    return out / tot


def blur(a, s):
    """Gaussian blur for 2D or 3D (h, w, c) arrays; large radii use a small copy."""
    if s <= 0:
        return a
    if s > 10:
        k = int(s // 5)
        h, w = a.shape[:2]
        ph, pw = (-h) % k, (-w) % k
        pad = ((0, ph), (0, pw)) + (((0, 0),) if a.ndim == 3 else ())
        b = np.pad(a, pad, mode='edge')
        hh, ww = b.shape[0] // k, b.shape[1] // k
        if a.ndim == 3:
            b = b.reshape(hh, k, ww, k, -1).mean((1, 3))
            b = ndi.gaussian_filter(b, (s / k, s / k, 0), mode='nearest')
            b = ndi.zoom(b, (k, k, 1), order=1)
        else:
            b = b.reshape(hh, k, ww, k).mean((1, 3))
            b = ndi.gaussian_filter(b, s / k, mode='nearest')
            b = ndi.zoom(b, (k, k), order=1)
        return b[:h, :w].astype(F32)
    sig = (s, s, 0) if a.ndim == 3 else s
    return ndi.gaussian_filter(a, sig, mode='nearest').astype(F32)


def bloom(a, thresh=0.7, sigmas=(6, 20, 60), gains=(0.35, 0.3, 0.25)):
    """Soft glow around bright areas."""
    lum = a.max(-1)
    hi = a * smooth(thresh, thresh + 0.25, lum)[..., None]
    out = a.copy()
    for s, g in zip(sigmas, gains):
        out += g * blur(hi, s)
    return out


def glow(cx, cy, r, power=2.0):
    """Radial falloff field, 1 at the centre."""
    yy, xx = np.mgrid[0:H, 0:W].astype(F32)
    d2 = ((xx - cx) ** 2 + (yy - cy) ** 2) / (r * r)
    return 1.0 / (1.0 + d2) ** power


def comp(base, rgb, a):
    """Alpha composite. rgb may be one colour or an image; a is an (h, w) mask."""
    return base * (1 - a[..., None]) + np.asarray(rgb, F32) * a[..., None]


class Layer:
    """Vector drawing layer (PIL) drawn at 2x size, then averaged down for smooth edges."""

    def __init__(self, ss=2):
        self.ss = ss
        self.im = Image.new('RGBA', (W * ss, H * ss), (0, 0, 0, 0))
        self.d = ImageDraw.Draw(self.im)

    def _p(self, pts):
        s = self.ss
        return [(float(x) * s, float(y) * s) for x, y in pts]

    def poly(self, pts, col, a=1.0):
        self.d.polygon(self._p(pts), fill=c8(col) + (int(a * 255),))

    def line(self, pts, col, width=1.0, a=1.0):
        wd = max(1, int(round(width * self.ss)))
        self.d.line(self._p(pts), fill=c8(col) + (int(a * 255),), width=wd, joint='curve')

    def dot(self, x, y, rx, col, a=1.0, ry=None):
        s = self.ss
        ry = rx if ry is None else ry
        self.d.ellipse([(x - rx) * s, (y - ry) * s, (x + rx) * s, (y + ry) * s],
                       fill=c8(col) + (int(a * 255),))

    def arrays(self):
        im = self.im.convert('RGBa').reduce(self.ss)       # premultiplied alpha
        a = np.asarray(im).astype(F32) / 255.0
        return a[..., :3], a[..., 3]

    def onto(self, base, opacity=1.0, soften=0.0):
        rgb, a = self.arrays()
        if soften > 0:
            rgb, a = blur(rgb, soften), blur(a, soften)
        return base * (1 - a[..., None] * opacity) + rgb * opacity


def painterly(ref, rng, sizes=(44, 22, 11, 6), thresh=(0, 0.06, 0.05, 0.04), ss=2,
              jitter=0.035, length=5, base_angle=None, edge_follow=1.0, relief=0.3,
              density=1.0, tol=0.22, underblur=30, keep=None):
    """Repaint an image with oriented brush strokes, coarse to fine.

    Strokes follow the edges of the picture (structure tensor) and a flow field
    elsewhere. Finer strokes are added only where the canvas still differs from
    the reference. A separate height map of the strokes gives the paint relief.
    keep: optional (h, w) probability mask that limits where fine strokes go.
    """
    h, w = ref.shape[:2]
    lum = ref @ np.array([0.3, 0.59, 0.11], F32)
    l2 = ndi.gaussian_filter(lum, 2.0)
    gx, gy = ndi.sobel(l2, axis=1), ndi.sobel(l2, axis=0)
    jxx, jyy, jxy = blur(gx * gx, 6), blur(gy * gy, 6), blur(gx * gy, 6)
    theta = 0.5 * np.arctan2(2 * jxy, jxx - jyy) + np.pi / 2
    coh = np.sqrt((jxx - jyy) ** 2 + 4 * jxy ** 2)
    cw = smooth(0.0004, 0.01, coh) * edge_follow
    if base_angle is None:
        base_angle = fbm((h, w), 320, 3, rng) * np.pi * 3
    base_angle = np.broadcast_to(np.asarray(base_angle, F32), (h, w))
    c2 = cw * np.cos(2 * theta) + (1 - cw) * np.cos(2 * base_angle)
    s2 = cw * np.sin(2 * theta) + (1 - cw) * np.sin(2 * base_angle)
    ang = 0.5 * np.arctan2(s2, c2)
    dxf, dyf = np.cos(ang).astype(F32), np.sin(ang).astype(F32)

    start = np.clip(blur(ref, underblur), 0, 1)
    canvas = Image.fromarray((start * 255).astype(np.uint8)).resize((w * ss, h * ss), Image.BILINEAR)
    hmap = Image.new('L', (w * ss, h * ss), 128)
    dr, hd = ImageDraw.Draw(canvas), ImageDraw.Draw(hmap)

    for li, s in enumerate(sizes):
        sp = max(2.0, s * 0.45 / density)
        ny, nx = int(h / sp) + 1, int(w / sp) + 1
        gy_, gx_ = np.mgrid[0:ny, 0:nx].astype(F32)
        px = (gx_ + rng.random((ny, nx))).ravel() * sp
        py = (gy_ + rng.random((ny, nx))).ravel() * sp
        ok = (px < w - 1) & (py < h - 1)
        px, py = px[ok], py[ok]
        xi, yi = px.astype(int), py.astype(int)
        sel = np.ones(len(px), bool)
        if thresh[li] > 0:
            cur = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
            diff = blur(np.abs(cur - ref).sum(-1), s * 0.5)
            sel &= diff[yi, xi] > thresh[li]
        if keep is not None and li >= 1:
            sel &= rng.random(len(px)) < keep[yi, xi]
        px, py, xi, yi = px[sel], py[sel], xi[sel], yi[sel]
        n = len(px)
        if n == 0:
            continue
        col0 = ref[yi, xi]
        K = int(length)
        step = s * 0.6
        pts = np.zeros((n, 2 * K + 1, 2), F32)
        pts[:, K, 0], pts[:, K, 1] = px, py
        for sgn in (1, -1):
            x, y = px.copy(), py.copy()
            ddx, ddy = dxf[yi, xi] * sgn, dyf[yi, xi] * sgn
            alive = np.ones(n, bool)
            for k in range(1, K + 1):
                ix = np.clip(x.astype(int), 0, w - 1)
                iy = np.clip(y.astype(int), 0, h - 1)
                ndx, ndy = dxf[iy, ix], dyf[iy, ix]
                flip = np.where(ndx * ddx + ndy * ddy < 0, -1.0, 1.0)
                ddx, ddy = ndx * flip, ndy * flip
                nx_, ny_ = x + ddx * step, y + ddy * step
                jx = np.clip(nx_.astype(int), 0, w - 1)
                jy = np.clip(ny_.astype(int), 0, h - 1)
                alive &= np.abs(ref[jy, jx] - col0).sum(-1) < tol
                x = np.where(alive, nx_, x)
                y = np.where(alive, ny_, y)
                pts[:, K + sgn * k, 0], pts[:, K + sgn * k, 1] = x, y
        colj = col0 * (1 + jitter * rng.standard_normal((n, 1))) + 0.4 * jitter * rng.standard_normal((n, 3))
        cols = (np.clip(colj, 0, 1) * 255).astype(np.uint8)
        order = rng.permutation(n)
        P = (pts[order] * ss).reshape(n, -1).tolist()
        Cc = cols[order].tolist()
        G = rng.integers(40, 216, n).tolist()
        Bo = (rng.standard_normal((n, 3)) * s * ss * 0.28).tolist()
        Bl = (1 + 0.07 * rng.standard_normal((n, 3))).tolist()
        wd = max(1, int(s * ss))
        r = wd / 2.0
        for i in range(n):
            p = P[i]
            c = tuple(Cc[i])
            dr.line(p, fill=c, width=wd, joint='curve')
            hd.line(p, fill=G[i], width=wd, joint='curve')
            for ex, ey in ((p[0], p[1]), (p[-2], p[-1])):
                box = [ex - r, ey - r, ex + r, ey + r]
                dr.ellipse(box, fill=c)
                hd.ellipse(box, fill=G[i])
            if s >= 9:        # bristle streaks inside the larger strokes
                vx, vy = p[-2] - p[0], p[-1] - p[1]
                vl = math.hypot(vx, vy) + 1e-6
                ox_, oy_ = -vy / vl, vx / vl
                for b in range(3):
                    o = Bo[i][b]
                    q = [v + (o * ox_ if j % 2 == 0 else o * oy_) for j, v in enumerate(p)]
                    cb = tuple(int(max(0, min(255, v * Bl[i][b]))) for v in c)
                    dr.line(q, fill=cb, width=max(1, wd // 5), joint='curve')
                    hd.line(q, fill=int(max(0, min(255, G[i] + 40 * (Bl[i][b] - 1) * 14))), width=max(1, wd // 5))
    out = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
    if relief > 0:
        hm = ndi.gaussian_filter(np.asarray(hmap.reduce(ss)).astype(F32), 0.8)
        sh = np.clip((-ndi.sobel(hm, axis=1) * 0.5 - ndi.sobel(hm, axis=0) * 0.85) / 255.0, -1, 1)
        out = out * (1 + relief * sh[..., None])
    return out


def finish(a, name, rng, vignette=0.22, grain=0.012, weave=0.018):
    """Vignette, canvas weave, grain, then save to ../images/<name>.png."""
    yy, xx = np.mgrid[0:H, 0:W].astype(F32)
    r = np.sqrt(((xx / W - 0.5) * 1.15) ** 2 + (yy / H - 0.5) ** 2)
    a = a * (1 - vignette * smooth(0.3, 0.8, r))[..., None]
    if weave > 0:
        wv = (np.sin(xx * 2.1) * np.sin(yy * 2.1)) * 0.5 + (vnoise((H, W), 2.5, rng) - 0.5)
        a = a * (1 + weave * wv)[..., None]
    if grain > 0:
        a = a + grain * rng.standard_normal((H, W, 1)).astype(F32)
    out = os.path.join(HERE, '..', 'images', name + '.png')
    os.makedirs(os.path.dirname(out), exist_ok=True)
    Image.fromarray((np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8)).save(out)
    print(f'saved {os.path.normpath(out)}  ({time.time() - T0:.1f} s)')

# ----------------------------------------------------------------------------
# The picture
# ----------------------------------------------------------------------------
SEED = 505
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

HZ = 1130.0
TX, TBASE, TTOP = 1165.0, 880.0, 470.0       # tower axis, foot row, gallery row
LANT = (TX, TTOP - 28.0)

TEX = []
for i in range(4):
    t = ndi.gaussian_filter(rng.random((256, 256)).astype(F32), 3, mode='wrap')
    TEX.append((t - t.min()) / (t.max() - t.min()))


def N(i, x, z, scale):
    c = np.stack([(z / scale * 16) % 256, (x / scale * 16) % 256])
    return ndi.map_coordinates(TEX[i], c, order=1, mode='grid-wrap')


# ---- sky: warped cloud noise ---------------------------------------------------
base = fbm((H, W), 240, 6, rng)
wx_, wy_ = fbm((H, W), 330, 3, rng) - 0.5, fbm((H, W), 330, 3, rng) - 0.5
cl = ndi.map_coordinates(base, np.stack([np.clip(yy + 420 * wy_, 0, H - 1), np.clip(xx + 520 * wx_, 0, W - 1)]), order=1)
cl = (cl - cl.min()) / (cl.max() - cl.min())
moon = glow(300, 250, 330, 1.3) + 0.55 * glow(930, 1000, 330, 1.5)
v = np.clip(cl * 0.95 + 0.42 * moon - 0.16 + 0.3 * np.exp(-((yy - HZ + 60) / 200.0) ** 2), 0, 1)
sky = ramp(v, [(0, '#05080f'), (0.35, '#101b2a'), (0.55, '#223346'), (0.72, '#40566a'), (0.88, '#7b8e9b'), (1, '#b9c4c6')])
img = sky

# ---- open sea: a flat plane seen in perspective, with ridged wave patterns --------------
FOC, CAMH, CX = 1400.0, 15.0, 800.0
gz = CAMH * FOC / np.maximum(yy - HZ, 0.5)
gx = (xx - CX) * gz / FOC
h1 = 1 - np.abs(np.sin((gx * 0.5 + gz * 0.85) / 19.0 * np.pi + 3.0 * N(0, gx, gz, 60)))
h2 = 1 - np.abs(np.sin((gx * 0.2 + gz) / 6.5 * np.pi + 4.0 * N(1, gx, gz, 25)))
far = smooth(520, 140, gz)
hh = 0.5 * h1 ** 1.5 + far * (0.3 * h2 ** 1.5 + 0.15 * N(2, gx, gz, 3.0) + 0.05 * N(3, gx, gz, 0.9)) + (1 - far) * 0.2
foam = smooth(0.6, 0.8, hh + 0.3 * (N(3, gx, gz, 2.0) - 0.5))
veins = smooth(0.58, 0.78, N(2, gx, gz * 0.3, 5.0)) * 0.3 * far
sea = ramp(hh, [(0, '#06111c'), (0.45, '#102b39'), (0.75, '#27585f'), (1, '#5a938f')])
sea = comp(sea, hexc('#d6e4e6'), np.clip(foam * 0.9 + veins, 0, 1))
fogf = (1 - np.exp(-gz / 420.0))[..., None]
sea = mix(sea, hexc('#2c3b49'), fogf)
img = comp(img, sea, smooth(-2, 2, yy - HZ))

# ---- breaking waves in front, with spray ---------------------------------------------------
def spray(n, x0, y0, ang, ang_sd, v_lo, v_hi, tmax, wind=140.0, grav=620.0, sx=30.0, sy=20.0):
    """Ballistic droplets; returns a density image."""
    a = np.radians(rng.normal(ang, ang_sd, n))
    v = rng.uniform(v_lo, v_hi, n) * rng.random(n) ** 0.5
    t = rng.random(n) ** 0.7 * tmax
    px = x0 + rng.normal(0, sx, n) + v * np.cos(a) * t + wind * t * t
    py = y0 + rng.normal(0, sy, n) + v * np.sin(a) * t + 0.5 * grav * t * t
    wgt = np.exp(-t / tmax * 1.6)
    d, _, _ = np.histogram2d(py, px, bins=(H, W), range=((0, H), (0, W)), weights=wgt)
    return d.astype(F32)


def wave_layer(img, ybase, amp, cell, seed_shift, tint=1.0, bump=None):
    prof = np.zeros(W, F32)
    for o, a in enumerate((1.0, 0.5, 0.28, 0.16, 0.09)):
        n = vnoise((1, W), (1, cell / 2 ** o), rng)[0]
        prof += a * (1 - np.abs(2 * n - 1)) ** 1.3
    prof /= 2.03
    if bump is not None:
        prof = prof * 0.55 + bump
    top = ybase - amp * prof
    d = yy - top[None, :]
    m = smooth(-1.5, 1.5, d)
    face = fbm((H, W), (9, 110), 4, rng)
    face = ndi.map_coordinates(face, np.stack([(yy - 0.3 * xx) % H, xx]), order=1, mode='wrap')
    body = ramp(np.clip(d / (amp * 1.5 + 80), 0, 1), [(0, '#4f9a94'), (0.12, '#2b6b6d'), (0.45, '#12333f'), (1, '#07141f')])
    body = body * tint * (0.9 + 0.2 * face)[..., None]
    streak = smooth(0.55, 0.78, face) * smooth(amp * 1.6 + 60, 0, d) * 0.4
    body = comp(body, hexc('#cfe0e2'), streak)
    ragged = 10 + 34 * prof[None, :] * (0.4 + 1.2 * vnoise((H, W), (10, 22), rng))
    crest = smooth(1.0, 0.25, d / ragged) * m
    body = comp(body, hexc('#eef5f5'), crest * (0.35 + 0.65 * smooth(0.25, 0.6, prof))[None, :])
    img = comp(img, body, m)
    # wind-blown spray from the highest crests
    dens = np.zeros((H, W), F32)
    peaks = np.argsort(prof)[-260:]
    for xp in peaks[::13]:
        dens += spray(2600, float(xp), float(top[xp]) - 4, -70, 26, 60, 330, 0.9, wind=230, sx=26, sy=8)
    al = 1 - np.exp(-(blur(dens, 2.2) * 1.5 + blur(dens, 9) * 3.0))
    return comp(img, hexc('#dfeaec'), np.clip(al, 0, 0.95) * 0.85)



img = wave_layer(img, 1335, 120, 420, 0, tint=0.85)

# ---- the cliff -----------------------------------------------------------------------
ny1 = vnoise((1, H), (1, 60), rng)[0] - 0.5
ny2 = vnoise((1, H), (1, 14), rng)[0] - 0.5
xleft = 1040 - 215 * smooth(880, 1500, np.arange(H)) ** 0.75 + 70 * ny1 + 16 * ny2
nx1 = vnoise((1, W), (1, 90), rng)[0] - 0.5
ytop = 884 - 26 * smooth(1010, 1600, xx[0]) + 16 * nx1
cmask = smooth(-1.5, 1.5, xx - xleft[:, None]) * smooth(-1.5, 1.5, yy - ytop[None, :])
strata = fbm((H, W), (14, 160), 5, rng)
strata = ndi.map_coordinates(strata, np.stack([np.clip(yy + 0.25 * (xx - 1000), 0, H - 1), xx]), order=1)
cracks = 1 - np.abs(2 * fbm((H, W), (70, 26), 4, rng) - 1)
rockv = np.clip(0.55 * strata + 0.45 * cracks ** 2, 0, 1)
rock = ramp(rockv, [(0, '#030405'), (0.5, '#0c0f13'), (0.8, '#1b2027'), (1, '#323a44')])
rim = np.exp(-np.clip(xx - xleft[:, None], 0, None) / 38.0)
rock = rock + rim[..., None] * hexc('#7d909c') * (0.3 + 1.3 * strata * cracks)[..., None]
toprim = np.exp(-np.clip(yy - ytop[None, :], 0, None) / 16.0)
rock = rock + toprim[..., None] * hexc('#5a6a70') * 0.5 + (glow(TX, TBASE + 10, 120, 1.6) * toprim)[..., None] * hexc('#ffcf80') * 0.5
grass = np.exp(-np.clip(yy - ytop[None, :], 0, None) / 9.0)
rock = mix(rock, hexc('#1c2a22'), np.clip(grass, 0, 1)[..., None] * 0.8)
img = comp(img, rock, cmask)

# ---- keeper's house and the lighthouse --------------------------------------------------
hs = Layer()
gy = lambda x: float(np.interp(x, xx[0], ytop))
hx0, hx1 = 1262.0, 1420.0
hs.poly([(hx0, gy(hx0) + 4), (hx1, gy(hx1) + 4), (hx1, 806), (hx0, 806)], hexc('#2f3944'))
hs.poly([(hx0 - 12, 808), (hx1 + 12, 808), (hx1 - 22, 752), (hx0 + 22, 752)], hexc('#12161c'))
hs.poly([(hx1 - 50, 770), (hx1 - 32, 770), (hx1 - 32, 728), (hx1 - 50, 728)], hexc('#1a1f27'))
hs.poly([(hx0 + 30, 828), (hx0 + 56, 828), (hx0 + 56, 858), (hx0 + 30, 858)], hexc('#ffc56a'))
hs.line([(hx0 + 43, 828), (hx0 + 43, 858)], hexc('#3a2a18'), 2)
hs.line([(hx0 + 30, 843), (hx0 + 56, 843)], hexc('#3a2a18'), 2)
hs.poly([(hx0 + 92, 830), (hx0 + 114, 830), (hx0 + 114, gy(hx0 + 100) + 4), (hx0 + 92, gy(hx0 + 100) + 4)], hexc('#151a21'))
img = hs.onto(img)

hw = lambda y: np.interp(y, [TTOP, TBASE + 10], [31.0, 50.0])
uu = (xx - TX) / hw(yy)
tm = smooth(1.0, 0.96, np.abs(uu)) * (yy >= TTOP) * (yy <= TBASE + 8)
shade = np.clip(0.62 - 0.42 * uu - 0.2 * uu * uu, 0.08, 1.0)
tfrac = (yy - TTOP) / (TBASE - TTOP)
red = ((tfrac > 0.2) & (tfrac < 0.4)) | ((tfrac > 0.64) & (tfrac < 0.84))
paint = np.where(red[..., None], hexc('#a03029'), hexc('#c3cdd4'))
tower = paint * shade[..., None] * (0.86 + 0.28 * vnoise((H, W), (30, 6), rng))[..., None]
tower *= np.array([0.8, 0.9, 1.0], F32)
for (wy_c, wu) in [(560, -0.25), (700, 0.2), (805, -0.2)]:                 # slit windows
    wmask = (np.abs(yy - wy_c) < 13) & (np.abs(uu - wu) < 0.12)
    tower = np.where(wmask[..., None], np.array([0.02, 0.025, 0.035], F32), tower)
img = comp(img, tower, tm.astype(F32))

lh = Layer()
iron = hexc('#0c0f14')
lh.poly([(TX - 46, TTOP + 6), (TX + 46, TTOP + 6), (TX + 40, TTOP - 4), (TX - 40, TTOP - 4)], iron)      # gallery
for k in range(-4, 5):
    lh.line([(TX + k * 10.5, TTOP - 4), (TX + k * 10.5, TTOP - 22)], iron, 1.6)
lh.line([(TX - 44, TTOP - 22), (TX + 44, TTOP - 22)], iron, 2.2)
lh.poly([(TX - 24, TTOP - 4), (TX + 24, TTOP - 4), (TX + 24, TTOP - 56), (TX - 24, TTOP - 56)], hexc('#ffe9a8'))   # lantern room
lh.poly([(TX - 9, TTOP - 10), (TX + 9, TTOP - 10), (TX + 9, TTOP - 50), (TX - 9, TTOP - 50)], hexc('#fffbe6'))
for k in (-24, -8, 8, 24):
    lh.line([(TX + k, TTOP - 4), (TX + k, TTOP - 56)], iron, 2.6)
lh.poly([(TX - 30, TTOP - 55), (TX + 30, TTOP - 55), (TX + 18, TTOP - 78), (TX, TTOP - 92), (TX - 18, TTOP - 78)], iron)
lh.line([(TX, TTOP - 90), (TX, TTOP - 112)], iron, 2.4)
lh.dot(TX, TTOP - 96, 4.5, iron)
lh.poly([(TX - 11, TBASE + 8), (TX + 11, TBASE + 8), (TX + 11, TBASE - 26), (TX - 11, TBASE - 26)], hexc('#101419'))  # door
img = lh.onto(img)


# the big burst against the cliff
dens = spray(60000, 905, 1330, -100, 22, 250, 950, 1.3, wind=60, sx=42, sy=60)
dens += spray(25000, 880, 1400, -150, 30, 100, 600, 1.0, wind=20, sx=50, sy=40)
for fa in (-158, -141, -127, -115, -104, -93, -81, -68, -52):          # separate jets of the burst
    fa2 = fa + rng.uniform(-4, 4)
    dens += spray(9000, 915 + rng.uniform(-30, 30), 1300 + rng.uniform(-40, 40), fa2, 3.5,
                  500, rng.uniform(900, 1500), rng.uniform(0.8, 1.25), wind=70, sx=16, sy=16)
al = 1 - np.exp(-(blur(dens, 1.3) * 0.8 + blur(dens, 5) * 1.1 + blur(dens, 24) * 1.3))
burst_col = ramp(np.clip(blur(dens, 6) * 1.3, 0, 1), [(0, '#74899a'), (0.45, '#b9cad2'), (1, '#f6fbfb')])
img = comp(img, burst_col, np.clip(al, 0, 0.93))

bump2 = 0.75 * np.exp(-((xx[0] - 430) / 330.0) ** 2)
img = wave_layer(img, 1620, 230, 520, 1, tint=1.0, bump=bump2)
img = wave_layer(img, 1930, 150, 600, 2, tint=0.8)

# dark rocks in the lower left corner
rk = Layer()
for (rx0, rx1, ry, rh, seed_c) in [(-40, 420, 2010, 250, 0), (300, 640, 2010, 120, 1)]:
    n = int((rx1 - rx0) / 14)
    xs_ = np.linspace(rx0, rx1, n)
    prof = np.sin(np.linspace(0, np.pi, n)) ** 0.6 * (0.7 + 0.5 * rng.random(n))
    pts = [(rx0, ry)] + [(float(x), float(ry - rh * p)) for x, p in zip(xs_, prof)] + [(rx1, ry)]
    rk.poly(pts, hexc('#06080b'))
    for j in range(2, n - 2, 2):
        rk.line([(xs_[j], ry - rh * prof[j] + 3), (xs_[j] + 9, ry - rh * prof[j] + 26 + 30 * rng.random())],
                hexc('#2b3640'), 4, 0.6)
img = rk.onto(img)
dens = spray(26000, 250, 1790, -80, 40, 60, 420, 0.9, wind=120, sx=150, sy=22)
al = 1 - np.exp(-(blur(dens, 2) * 1.2 + blur(dens, 12) * 3.5))
img = comp(img, hexc('#d5e2e6'), np.clip(al, 0, 0.9) * 0.8)

# ---- the beam -----------------------------------------------------------------------------
def beam(ang_deg, spread, reach, gain):
    a = math.radians(ang_deg)
    ux, uy = math.cos(a), math.sin(a)
    rx, ry = xx - LANT[0], yy - LANT[1]
    along = rx * ux + ry * uy
    perp = -rx * uy + ry * ux
    wdt = 9 + np.clip(along, 0, None) * spread
    b = np.exp(-(perp / wdt) ** 2) * (along > 0) * np.exp(-np.clip(along, 0, None) / reach) * (9 / wdt) ** 0.35
    return b * gain


rainn = fbm((H, W), (90, 9), 3, rng)
rainn = ndi.map_coordinates(rainn, np.stack([yy, (xx - 0.36 * yy) % W]), order=1, mode='wrap')
bm = beam(187.0, 0.07, 1700.0, 1.0) + beam(7.0, 0.07, 500.0, 0.6)
bm0 = bm.copy()
bm = bm * (0.55 + 0.9 * rainn)
BEAMC = hexc('#fff0bc')
img = img + bm0[..., None] * BEAMC * 0.75

# ---- rain before the paint (soft) ----------------------------------------------------------
rain = Layer()
for _ in range(2600):
    x, y = rng.uniform(-300, W), rng.uniform(-80, H)
    ln = rng.uniform(40, 150)
    rain.line([(x, y), (x + ln * 0.36, y + ln)], (0.75, 0.82, 0.88), rng.uniform(1.0, 2.6), rng.uniform(0.05, 0.16))
img = rain.onto(img, soften=1.0)

# ---- brush pass ---------------------------------------------------------------------------
flow = np.where(yy < HZ, 0.45 + 2.2 * (fbm((H, W), 380, 3, rng) - 0.5), 0.25 * (fbm((H, W), 300, 2, rng) - 0.5) * 3)
ref = np.clip(img, 0, 1)
painted = painterly(ref, rng, sizes=(48, 26, 13, 7, 4), thresh=(0, 0.07, 0.06, 0.05, 0.05),
                    base_angle=flow, relief=0.34, jitter=0.055, length=5)
img = painted

# ---- light and sharp rain on top ------------------------------------------------------------
img = img + bm[..., None] * BEAMC * 0.3
img += glow(LANT[0], LANT[1], 16, 2.0)[..., None] * hexc('#fff6d8') * 1.0
img += glow(LANT[0], LANT[1], 70, 1.6)[..., None] * hexc('#ffd98a') * 0.5
img += glow(LANT[0], LANT[1], 300, 1.4)[..., None] * hexc('#ffcf80') * 0.12
img += glow(hx0 + 43, 843, 26, 1.8)[..., None] * hexc('#ffb45a') * 0.5
rain = Layer()
for _ in range(3800):
    x, y = rng.uniform(-300, W), rng.uniform(-80, H)
    ln = rng.uniform(24, 110)
    inb = float(bm[int(np.clip(y, 0, H - 1)), int(np.clip(x, 0, W - 1))])
    a = min(0.8, rng.uniform(0.04, 0.16) + inb * 0.9)
    rain.line([(x, y), (x + ln * 0.36, y + ln)], (0.86, 0.9, 0.93) if inb < 0.15 else (1.0, 0.96, 0.8),
              rng.uniform(0.7, 1.7), a)
img = rain.onto(img, soften=0.4)
img = bloom(img, 0.8, (6, 24), (0.2, 0.18))
img = np.clip(img, 0, 1) ** 0.95
finish(img, '05-lighthouse-storm', rng, vignette=0.32)
