#!/usr/bin/env python3
"""20 Interference waves.

A pond seen from straight above. Seven "drops" each send out circular ripples
with their own wavelength, and the ripple heights are simply added. Where the
rings of two drops cross, crests and troughs cancel or double, which makes the
lattice and the fan-shaped quiet lines (moire) between the centres.
The summed height map is then shaded as water: the slope of the surface bends
the view of the pond bed (refraction), mirrors a sky that is warm on the sun
side and blue on the other, and focuses light into bright lines on the bed.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/20-interference-waves.py
"""
import os, time, math
import numpy as np
from PIL import Image
from scipy import ndimage as ndi

W, H = 1600, 2000
SS = 2                        # everything is computed at 2x and averaged down
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '20-interference-waves.png')
F32 = np.float32
rng = np.random.default_rng(2020)
w, h = W * SS, H * SS
yy, xx = np.mgrid[0:h, 0:w].astype(F32)
yy /= SS; xx /= SS            # coordinates in final-picture pixels


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 smoothstep(a, b, x):
    t = np.clip((x - a) / (b - a), 0, 1)
    return t * t * (3 - 2 * t)


def noise(sigma, shape=None):
    """Smooth noise at quarter size, scaled up to the working grid."""
    n = ndi.gaussian_filter(rng.standard_normal((h // 4, w // 4)).astype(F32), sigma * SS / 4, mode='wrap')
    n = ndi.zoom(n, 4, order=1)
    return (n - n.mean()) / n.std()


# ----------------------------------------------------------------------------
# 1. The water surface: a sum of circular ripple trains
# ----------------------------------------------------------------------------
# x, y, wavelength, amplitude, radius the ripple front has reached, phase
DROPS = [
    (505, 650, 47.0, 1.00, 1750, 0.0),      # old, wide ripples
    (1150, 1215, 41.0, 0.95, 1500, 1.3),
    (360, 1585, 30.0, 0.80, 640, 0.4),      # younger
    (1255, 365, 25.0, 0.70, 430, 2.1),
    (835, 1850, 21.0, 0.60, 300, 0.9),
    (1010, 800, 17.0, 0.55, 205, 0.0),      # the newest, smallest
    (190, 250, 19.0, 0.50, 230, 1.7),
]
height = np.zeros((h, w), F32)
for (cx, cy, lam, amp, front, ph) in DROPS:
    r = np.hypot(xx - cx, yy - cy)
    # Ripples get slightly longer toward the front (long waves travel faster).
    k = 2 * math.pi / lam
    phase = k * r * (1 - 0.10 * r / front) - ph
    env = amp * (0.30 + 0.85 / np.sqrt(1 + r / (3.0 * lam)))   # strong near the drop, then a slow fade
    env *= 1 - smoothstep(front * 0.72, front, r)              # soft leading edge
    env *= 1 - np.exp(-(r / (0.55 * lam)) ** 2)                # calm exact centre
    height += env * np.cos(phase) * lam / 40.0
# A little slow swell so that the calm parts are not perfectly flat.
height += 0.10 * noise(70) + 0.03 * noise(16)

gy, gx = np.gradient(height, 1.0 / SS)
SLOPE = 5.2
nx, ny = -gx * SLOPE, -gy * SLOPE                             # tilt of the surface normal
tilt = np.hypot(nx, ny)
lap = ndi.gaussian_laplace(height, 2.0 * SS) * (SS * SS)

# ----------------------------------------------------------------------------
# 2. Pond bed, seen through the moving surface (refraction)
# ----------------------------------------------------------------------------
def ramp(stops, t):
    pos = np.array([p for p, _ in stops], F32)
    col = np.stack([hexc(c) for _, c in stops])
    return np.stack([np.interp(t, pos, col[:, c]) for c in range(3)], -1).astype(F32)


bed_n = 0.60 * noise(210) + 0.30 * noise(60) + 0.16 * noise(18)
peb = smoothstep(0.1, 1.1, noise(7)) * (0.5 + 0.5 * smoothstep(-0.5, 0.8, noise(50)))   # pebbles
DEPTH = 13.0
sx = np.clip(xx * SS + nx * DEPTH * SS, 0, w - 1)
sy = np.clip(yy * SS + ny * DEPTH * SS, 0, h - 1)
bed_r = ndi.map_coordinates(bed_n, [sy, sx], order=1)
peb_r = ndi.map_coordinates(peb, [sy, sx], order=1)
# The pond is deeper (darker) toward the lower right.
deep = (xx / W - 0.5) * 0.7 + (yy / H - 0.5) * 0.9
BED = [(-1.8, '#03202c'), (-0.6, '#06404a'), (0.3, '#0b5f5c'), (1.0, '#1c8270'), (1.9, '#58a67a')]
img = ramp(BED, bed_r - deep * 1.1)
img = img * (1 - 0.45 * peb_r[..., None]) + peb_r[..., None] * hexc('#6d8f6a') * 0.40
# Caustics: crests act as lenses and gather light into bright lines on the bed.
caus = np.clip(-lap * 10.0, 0, None)
caus = caus / (1 + 0.5 * caus)
img = img * (0.78 + 0.30 * np.tanh(-lap * 6.0))[..., None] + caus[..., None] * hexc('#9ff0c8') * 0.34

# ----------------------------------------------------------------------------
# 3. Reflection of an evening sky. A slope that faces the sun mirrors the warm,
#    bright part of the sky; a slope that faces away mirrors the dark blue part.
# ----------------------------------------------------------------------------
sun = np.array([-0.62, -0.78], F32)                            # sun toward the upper left
facing = nx * sun[0] + ny * sun[1]                             # > 0: slope faces the sun
cross = nx * sun[1] - ny * sun[0]
SKY_GOLD = [(-1.3, '#070f38'), (-0.55, '#0f2f66'), (-0.05, '#1b6a86'), (0.25, '#58b9b0'),
            (0.55, '#ffcf86'), (0.95, '#fff3d2'), (1.5, '#ffffff')]
SKY_ROSE = [(-1.3, '#0a0a34'), (-0.55, '#1b2466'), (-0.05, '#2a5a94'), (0.25, '#8aa6d6'),
            (0.55, '#ff9f92'), (0.95, '#ffe3d0'), (1.5, '#ffffff')]
# The sky colour changes across the pond: gold near the sun, rose far from it.
far = smoothstep(-0.25, 0.55, deep + 0.10 * noise(240))
sky = ramp(SKY_GOLD, facing) * (1 - far[..., None]) + ramp(SKY_ROSE, facing) * far[..., None]
sky = sky * (1 + 0.10 * np.tanh(cross * 1.5))[..., None]
refl = 0.42 + 0.50 * smoothstep(-0.15, 0.55, facing)           # dark slopes let the bed show through
img = img * (1 - refl[..., None]) + sky * refl[..., None]
# Sun glints: a sharp highlight where the tilt mirrors the sun exactly.
s0 = sun * 0.95
spec = np.exp(-((nx - s0[0]) ** 2 + (ny - s0[1]) ** 2) / (2 * 0.16 ** 2))
img += spec[..., None] * hexc('#fff4d6') * 0.9

# ----------------------------------------------------------------------------
# 3b. Lily pads and one flower float on top and give the pond its scale
# ----------------------------------------------------------------------------
def over(col, a):
    global img
    img = img * (1 - a[..., None]) + col * a[..., None]


def pad(cx, cy, r, notch_deg, hue):
    dx, dy = xx - cx, yy - cy
    d = np.hypot(dx, dy)
    if True:
        ang = np.arctan2(dy, dx) - math.radians(notch_deg)
        ang = (ang + math.pi) % (2 * math.pi) - math.pi          # 0 at the notch
        # Wavy outline and a V-shaped notch that closes toward the centre.
        rr = r * (1 + 0.018 * np.sin(ang * 9 + cx) + 0.012 * np.sin(ang * 17 + cy))
        notch = np.abs(ang) * d - 0.16 * d - 1.0
        sd = np.maximum(d - rr, -notch)
        a = np.clip(0.5 - sd * SS, 0, 1)
        # Soft shadow on the water, away from the sun.
        ds = np.hypot(dx - 16, dy - 20)
        sh = (1 - smoothstep(r * 0.80, r * 1.16, ds)) * (1 - a)
        img[:] = img * (1 - 0.50 * sh[..., None])
        veins = np.abs(np.sin(ang * 11.0)) ** 14 * smoothstep(0.08, 0.3, d / r) * (1 - smoothstep(0.80, 0.98, d / r))
        t = d / r
        base = hexc('#2f8a3e') * (1 - hue) + hexc('#6a9a2f') * hue
        col = base[None, None, :] * (0.78 + 0.34 * (1 - t) + 0.10 * (-(dx * 0.6 + dy * 0.8) / r))[..., None]
        col = col * (0.90 + 0.07 * bed_n[..., None]) * np.array([1.0, 0.97, 0.90], F32)
        col = col + veins[..., None] * hexc('#c9e48a') * 0.22
        col = col * (1 - 0.30 * smoothstep(0.90, 1.0, t))[..., None]       # darker rim
        col = col + (smoothstep(0.93, 0.985, t) * smoothstep(-0.2, 0.9, -(dx * 0.6 + dy * 0.8) / r))[..., None] * hexc('#ffe9b0') * 0.35
        over(col, a)


def flower(cx, cy, r):
    dx, dy = xx - cx, yy - cy
    ds = np.hypot(dx - 10, dy - 13)
    img[:] = img * (1 - 0.45 * (1 - smoothstep(r * 0.5, r * 1.15, ds)))[..., None]
    for layer, (n, rad, wid, rot, c0, c1) in enumerate([
            (11, 1.00, 0.30, 0.0, '#f48fb1', '#ffe1ea'),
            (9, 0.74, 0.28, 0.33, '#f7a8c2', '#fff0f4'),
            (7, 0.48, 0.24, 0.1, '#ffd3de', '#fffaf6')]):
        for i in range(n):
            a0 = rot + 2 * math.pi * i / n
            ca, sa = math.cos(a0), math.sin(a0)
            u = dx * ca + dy * sa                 # along the petal
            v = -dx * sa + dy * ca                # across the petal
            L = r * rad
            s = np.clip(u / L, 0, 1)
            half = wid * L * np.clip(np.sin(math.pi * s ** 0.8), 0, 1) ** 0.9 + 0.01     # pointed-oval outline
            sd = np.where((u > 0) & (u < L), np.abs(v) - half, 1e3)
            a = np.clip(0.5 - sd * SS, 0, 1)
            col = hexc(c0)[None, None, :] * (1 - s[..., None]) + hexc(c1)[None, None, :] * s[..., None]
            col = col * (1 - 0.22 * (np.abs(v) / (half + 1e-3)) ** 2)[..., None]   # fold along the middle
            col = col * (0.90 + 0.10 * ((i * 7 + layer * 3) % 5) / 4.0)
            over(col, a * 0.98)
    d = np.hypot(dx, dy)
    over(np.broadcast_to(hexc('#f6c12d'), img.shape) * (1 - 0.3 * smoothstep(0, r * 0.15, d))[..., None],
         np.clip(0.5 - (d - r * 0.15) * SS, 0, 1))


pad(1385, 1700, 150, 200, 0.1)
pad(1190, 1835, 105, 310, 0.5)
pad(1480, 1905, 88, 140, 0.8)
pad(150, 985, 118, 20, 0.3)
pad(60, 1180, 84, 250, 0.7)
pad(700, 130, 96, 75, 0.4)
pad(880, 62, 70, 160, 0.9)
flower(1292, 1745, 74)

# ----------------------------------------------------------------------------
# 4. Scale down and finish
# ----------------------------------------------------------------------------
img = img.reshape(H, SS, W, SS, 3).mean(axis=(1, 3))
lum = img @ np.array([0.3, 0.55, 0.15], F32)
bright = img * smoothstep(0.6, 1.0, lum)[..., None]
img = img + 0.22 * np.stack([ndi.gaussian_filter(bright[..., c], 9) for c in range(3)], -1)
Y, X = np.mgrid[0:H, 0:W].astype(F32)
vig = 1 - 0.30 * smoothstep(0.45, 1.30, np.hypot((X - W * 0.45) / (W / 2), (Y - H * 0.42) / (H / 2)))
img *= vig[..., None]
img = np.clip(img, 0, None)
img = img / (1 + 0.18 * img)                                   # soft shoulder for the highlights
img = np.clip(img * 1.16, 0, 1) ** 0.94
img += rng.standard_normal((H, W, 1)).astype(F32) * 0.007
Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))
