#!/usr/bin/env python3
"""09 Cherry blossom tree by a river.

A tree grown by a recursive branching rule, about 47,000 blossom dabs
shaded by light direction, a winding river that reflects the sky and the
tree, petals in the air and on the water, then a soft brush repaint.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/09-cherry-blossom-river.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 = 909
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

HZ = 1120.0
BLOSSOM = [(0, '#96587f'), (0.28, '#cf6f98'), (0.52, '#f09dbc'), (0.78, '#fbcbdb'), (1, '#fff4f7')]
tg = np.clip((yy - HZ) / (H - HZ), 0, 1)

# ---- sky ----------------------------------------------------------------------------
ts = np.clip(yy / HZ, 0, 1)
sky = ramp(ts, [(0, '#7fb4e2'), (0.45, '#a9d2ee'), (0.8, '#dfeaea'), (1, '#fdeeda')])
cl = fbm((H, W), (70, 260), 5, rng)
cm = smooth(0.52, 0.72, cl) * smooth(0.95, 0.5, ts)
sky = comp(sky, hexc('#ffffff'), cm * 0.6)
sky += glow(1320, 260, 420, 1.4)[..., None] * np.array([0.1, 0.08, 0.03], F32)
img = sky

# ---- far hills and trees ------------------------------------------------------------
xs = xx[0]
for (base, amp, cell, colr, blobs) in [(1090, 190, 520, '#b4cdd9', 0), (1108, 120, 330, '#a3c6ad', 0), (1126, 70, 210, '#86b58a', 1)]:
    prof = vnoise((1, W), (1, cell), rng)[0] * 0.65 + vnoise((1, W), (1, cell / 4), rng)[0] * 0.25 + vnoise((1, W), (1, cell / 14), rng)[0] * 0.1
    top = base - amp * prof
    body = np.broadcast_to(hexc(colr), (H, W, 3)) * (0.92 + 0.16 * fbm((H, W), 40, 3, rng))[..., None]
    body = mix(body, hexc('#f4ecdf'), (np.exp(-np.clip(HZ - yy, 0, None) / 60.0) * 0.5)[..., None])
    img = comp(img, body, smooth(-1.5, 1.5, yy - top[None, :]) * (yy < HZ + 4))
    if blobs:
        tl = Layer()
        for _ in range(240):
            x = rng.uniform(0, W)
            y = float(np.interp(x, xs, top)) + rng.uniform(-6, 26)
            r = rng.uniform(9, 26)
            c = hexc(rng.choice(['#6fa873', '#7fb682', '#5f9a68', '#f4bcd0', '#fbdbe6', '#8fc08a']))
            tl.dot(x, y, r, c, 0.95, ry=r * 0.8)
        img = tl.onto(img, soften=1.0)

# ---- the banks ------------------------------------------------------------------------
xc = lambda t: 600 + 500 * t ** 1.2 + 230 * np.sin(t * 3.4) * (1 - t) ** 0.8
hwf = lambda t: 26 + 530 * t ** 1.12
grass = ramp(tg, [(0, '#bcd596'), (0.25, '#93c06a'), (0.6, '#6aa646'), (1, '#4f8f38')])
gn = fbm((H, W), (26, 80), 4, rng)
grass *= (0.82 + 0.36 * gn)[..., None]
sunpatch = smooth(0.5, 0.7, fbm((H, W), (60, 240), 3, rng))
grass += sunpatch[..., None] * hexc('#e6e07a') * 0.16
treesh = np.exp(-(((xx - 640) / 420.0) ** 2 + ((yy - 1560) / 85.0) ** 2))
grass *= (1 - 0.42 * treesh * (0.6 + 0.6 * gn))[..., None]
img = comp(img, grass, smooth(-2, 2, yy - HZ))

# ---- the river --------------------------------------------------------------------------
wd = (xx - xc(tg)) / hwf(tg)
wmask = smooth(1.0, 0.97, np.abs(wd)) * (yy > HZ)
water = ramp(tg, [(0, '#d6e4e6'), (0.15, '#aacfe4'), (0.5, '#7fb0d6'), (1, '#4a82b4')])
water *= (0.9 + 0.2 * fbm((H, W), (40, 300), 3, rng))[..., None]
bankref = np.exp(-((1 - np.abs(wd)) / 0.2) ** 2)
water = mix(water, hexc('#3f6f44'), (bankref * 0.75)[..., None])
rip = fbm((H, W), (5, 90), 4, rng)
rows = np.clip(tg ** 0.6 * (H - 1), 0, H - 1).astype(int)
rip = np.take_along_axis(rip, rows, 0)
water += (smooth(0.55, 0.75, rip) * (0.3 + 0.7 * tg))[..., None] * hexc('#ffffff') * 0.22
water -= (smooth(0.5, 0.25, rip) * tg)[..., None] * 0.05
glit = (vnoise((H, W), (2.5, 14), rng) > 0.8) * np.exp(-((xx - 1250) / 260.0) ** 2) * smooth(0.25, 0.9, tg)
water += blur(glit.astype(F32), 0.9)[..., None] * hexc('#fff6da') * 0.5


# ---- grow the tree ---------------------------------------------------------------------------
SEGS, ANCH = [], []


def grow(x, y, ang, ln, wdt, depth):
    steps = 3
    for s_ in range(steps):
        a2 = ang + rng.normal(0, 0.13)
        x2, y2 = x + math.cos(a2) * ln / steps, y + math.sin(a2) * ln / steps
        w2 = wdt * (1 - 0.1)
        SEGS.append((x, y, x2, y2, wdt, w2, depth))
        if depth >= 3:
            ANCH.append((x2, y2, depth))
        x, y, ang, wdt = x2, y2, a2, w2
    if depth >= 7 or wdt < 2.2:
        ANCH.append((x, y, depth + 1))
        return
    nchild = 2 if rng.random() < 0.6 else 3
    spread = rng.uniform(0.5, 0.95)
    for c in range(nchild):
        off = (c / (nchild - 1) - 0.5) * 2 * spread + rng.normal(0, 0.12)
        a_child = ang + off
        a_child += 0.2 * math.sin(-math.pi / 2 - a_child)           # lean back toward the sky
        grow(x, y, a_child, ln * rng.uniform(0.7, 0.84), wdt * rng.uniform(0.58, 0.7), depth + 1)


TREE_X, TREE_Y = 440.0, 1560.0
grow(TREE_X, TREE_Y, math.radians(-78), 350, 100, 0)
grow(TREE_X + 30, TREE_Y - 260, math.radians(-24), 300, 42, 2)       # one long limb over the water
grow(TREE_X + 10, TREE_Y - 300, math.radians(-152), 250, 36, 2)

SUN = np.array([0.62, -0.78])


def blossoms(L, sd_scale, n_per, shift, alpha):
    for (ax, ay, dp) in ANCH:
        sd = rng.uniform(22, 46) * sd_scale
        n = int(n_per * rng.uniform(0.6, 1.4))
        ox, oy = rng.normal(0, sd, n), rng.normal(0, sd * 0.8, n)
        for dx, dy in zip(ox, oy):
            v = 0.55 + 0.42 * (dx * SUN[0] + dy * SUN[1]) / sd + rng.normal(0, 0.12) + shift
            c = ramp(np.array([np.clip(v, 0, 1)]), BLOSSOM)[0]
            r = rng.uniform(4.5, 10.5)
            L.dot(ax + dx, ay + dy, r, c, alpha, ry=r * rng.uniform(0.65, 1.0))


back = Layer()
blossoms(back, 1.5, 16, -0.28, 0.9)
wood = Layer()
for (x1, y1, x2, y2, w1, w2, dp) in SEGS:
    dx, dy = x2 - x1, y2 - y1
    dl = math.hypot(dx, dy) + 1e-6
    nx_, ny_ = -dy / dl, dx / dl
    wood.poly([(x1 + nx_ * w1 / 2, y1 + ny_ * w1 / 2), (x2 + nx_ * w2 / 2, y2 + ny_ * w2 / 2),
               (x2 - nx_ * w2 / 2, y2 - ny_ * w2 / 2), (x1 - nx_ * w1 / 2, y1 - ny_ * w1 / 2)], hexc('#3a2620'))
    wood.dot(x2, y2, w2 / 2, hexc('#3a2620'))
    if w1 > 9:                                                # light on the right side, bark marks
        wood.poly([(x1 - nx_ * w1 * 0.5, y1 - ny_ * w1 * 0.5), (x2 - nx_ * w2 * 0.5, y2 - ny_ * w2 * 0.5),
                   (x2 - nx_ * w2 * 0.2, y2 - ny_ * w2 * 0.2), (x1 - nx_ * w1 * 0.2, y1 - ny_ * w1 * 0.2)], hexc('#7c5444'), 0.8)
        for _ in range(int(w1 / 9)):
            f, g_ = rng.random(), rng.uniform(-0.4, 0.4)
            bx_, by_ = mix(x1, x2, f) + nx_ * w1 * g_, mix(y1, y2, f) + ny_ * w1 * g_
            wood.line([(bx_, by_), (bx_ + dx / dl * 22, by_ + dy / dl * 22)], hexc('#1f1310'), 2.2, 0.7)
for (ra_, rl_) in [(-95, 0), (-40, 1), (40, 1), (100, 0)]:                      # roots
    wood.poly([(TREE_X + ra_ * 0.35 - 14, TREE_Y - 70), (TREE_X + ra_ * 0.35 + 14, TREE_Y - 70), (TREE_X + ra_ + 8, TREE_Y + 10 + 8 * rl_), (TREE_X + ra_ - 12, TREE_Y + 12 + 8 * rl_)], hexc('#35221c'))
front = Layer()
blossoms(front, 1.0, 34, 0.0, 0.96)

# reflection of the tree in the water: flip the tree layers about the water's edge near the trunk
tree_rgb = np.zeros((H, W, 3), F32)
for L in (back, wood, front):
    tree_rgb = L.onto(tree_rgb)
_, a_b = back.arrays()
_, a_w = wood.arrays()
_, a_f = front.arrays()
tree_a = 1 - (1 - a_b) * (1 - a_w) * (1 - a_f)
MIRY = 1540
src = np.clip(2 * MIRY - np.arange(H), 0, H - 1).astype(int)
ref_rgb, ref_a = tree_rgb[src], tree_a[src]
wob = (fbm((H, W), (6, 80), 3, rng) - 0.5) * 36 * tg
co = np.stack([yy, np.clip(xx + wob, 0, W - 1)])
ref_a = ndi.map_coordinates(blur(ref_a, 5), co, order=1)
ref_rgb = np.stack([ndi.map_coordinates(blur(ref_rgb[..., c], 5), co, order=1) for c in range(3)], -1)
water = water * (1 - 0.55 * ref_a[..., None]) + ref_rgb * 0.55 * 0.92
img = comp(img, water, wmask.astype(F32))
# a thin dark edge where grass meets water
edge = np.exp(-((np.abs(wd) - 1.0) / 0.012) ** 2) * (yy > HZ + 6)
img = mix(img, hexc('#3b5a2c'), (edge * 0.7)[..., None])

# petals on the water, in drifting lines
pw = Layer()
for _ in range(34):
    u0 = rng.uniform(-0.92, 0.92)
    t0, t1 = sorted(rng.uniform(0.1, 1.0, 2))
    for _k in range(int(60 * (t1 - t0) + 12)):
        t = rng.uniform(t0, t1)
        u = u0 + rng.normal(0, 0.04)
        if abs(u) > 0.96:
            continue
        y = HZ + (H - HZ) * t
        x = float(xc(t) + u * hwf(t))
        sz = (1.5 + 7.5 * t) * rng.uniform(0.7, 1.3)
        pw.dot(x, y, sz, hexc(rng.choice(['#ffe3ec', '#fbc4d6', '#fff5f8', '#f5a9c4'])), 0.95, ry=sz * 0.45)
img = pw.onto(img)

for L in (back, wood, front):
    img = L.onto(img)

# petals in the air and on the grass
pa = Layer()
for _ in range(330):
    x, y = rng.normal(820, 380), rng.uniform(380, 1880)
    sz = rng.uniform(3.5, 9) * (0.7 + 0.5 * y / H)
    a = rng.uniform(0, np.pi)
    c = hexc(rng.choice(['#ffe3ec', '#fbc4d6', '#fff5f8', '#f7b3ca']))
    pa.line([(x - math.cos(a) * sz, y - math.sin(a) * sz), (x + math.cos(a) * sz, y + math.sin(a) * sz)], c, sz * 0.9, 0.95)
for _ in range(900):
    t = rng.uniform(0.3, 1.0)
    y = HZ + (H - HZ) * t
    x = rng.normal(560, 330)
    if abs(x - float(xc(t))) < float(hwf(t)):
        continue
    sz = (1.2 + 5 * t) * rng.uniform(0.7, 1.3)
    pa.dot(x, y, sz, hexc(rng.choice(['#ffe3ec', '#fbc4d6', '#fff5f8'])), 0.9, ry=sz * 0.5)
img = pa.onto(img)

# wild flowers on the banks
wf = Layer()
for _ in range(1400):
    t = rng.uniform(0.05, 1.0) ** 1.3
    y = HZ + (H - HZ) * t
    x = rng.uniform(0, W)
    if abs(x - float(xc(t))) < float(hwf(t)) + 6:
        continue
    sz = (1.0 + 4.5 * t) * rng.uniform(0.7, 1.3)
    wf.dot(x, y, sz, hexc(rng.choice(['#fff7c8', '#ffe45a', '#ffffff', '#f6d2ff', '#ffd84a'])), 0.9, ry=sz * 0.7)
img = wf.onto(img)

# grass blades in the near corner
gb = Layer()
for _ in range(1900):
    x = rng.uniform(-20, 760)
    y = rng.uniform(1640, 2040) if rng.random() < 0.8 else rng.uniform(TREE_Y - 6, TREE_Y + 30)
    tq = min(1.0, max(0.0, (y - HZ) / (H - HZ)))
    if abs(x - float(xc(tq))) < float(hwf(tq)) + 10:
        continue
    hgt = rng.uniform(26, 80) * (0.5 + max(0.0, y - 1650) / 400)
    if y < 1640:
        x = TREE_X + rng.uniform(-150, 150)
    lean = rng.uniform(-0.35, 0.45)
    c = mix(hexc('#2f6b2a'), hexc('#a9d05a'), rng.random() ** 1.5)
    gb.line([(x, y), (x + lean * hgt * 0.5, y - hgt * 0.6), (x + lean * hgt * 1.3, y - hgt)], c, rng.uniform(2, 4.5), 0.95)
img = gb.onto(img)

# ---- soft light and brush pass ------------------------------------------------------------------
img += glow(1320, 260, 620, 1.3)[..., None] * np.array([0.06, 0.05, 0.02], F32)
ref = np.clip(img, 0, 1)
flow = 0.3 * (fbm((H, W), 260, 2, rng) - 0.5) * 3
painted = painterly(ref, rng, sizes=(30, 15, 8, 4.5), thresh=(0, 0.05, 0.045, 0.04), base_angle=flow, relief=0.2, jitter=0.035, length=5)
img = mix(painted, ref, 0.15)
img = bloom(img, 0.86, (8, 36), (0.1, 0.12))
img = np.clip(img, 0, 1) ** 1.03
finish(img, '09-cherry-blossom-river', rng, vignette=0.16)
