#!/usr/bin/env python3
"""02 Desert dunes at golden hour.

A 3D height field of sand dunes, drawn in perspective with a low sun,
cast shadows, wind ripples, and a tiny camel caravan for scale.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/02-desert-dunes-golden-hour.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 = 202
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

FOC = 1500.0                 # focal length in pixels
HZ = 640.0                   # screen row of the horizon
CX = W / 2
ELEV = math.radians(12.0)    # sun height; the sun is exactly on the left (-x)
TAN_E, SIN_E, COS_E = math.tan(ELEV), math.sin(ELEV), math.cos(ELEV)

TEX = [vnoise((256, 256), 16, rng) for _ in range(4)]
for i in range(4):           # make the noise tiles wrap without a seam
    t = TEX[i]
    TEX[i] = np.pad(t, 8, mode='wrap')
    TEX[i] = ndi.gaussian_filter(t, 3, mode='wrap')
    TEX[i] = (TEX[i] - TEX[i].min()) / (TEX[i].max() - TEX[i].min())


def N(i, x, z, scale):
    """Tileable smooth noise in 0..1 at world position (x, z)."""
    c = np.stack([(z / scale * 16) % 256, (x / scale * 16) % 256])
    return ndi.map_coordinates(TEX[i], c, order=3, mode='grid-wrap')


def tri(u, k=0.74):
    """Dune cross-section: long gentle windward slope, short steep slip face."""
    u = u - np.floor(u)
    return np.where(u < k, (u / k) ** 1.25, (1 - (u - k) / (1 - k)) ** 1.5)


def hfun(x, z):
    """Terrain height in metres."""
    a1 = math.radians(24)
    p1 = (x * math.cos(a1) + z * math.sin(a1)) / 250.0 + 1.5 * (N(0, x, z, 900) - 0.5) + 0.22
    h = (16 + 30 * N(1, x, z, 1300)) * tri(p1)
    a2 = math.radians(-12)
    p2 = (x * math.cos(a2) + z * math.sin(a2)) / 78.0 + 2.3 * (N(2, x, z, 330) - 0.5)
    h = h + (1.5 + 7.5 * np.clip(N(3, x, z, 600), 0, 1) ** 1.5) * tri(p2, 0.7)
    return h.astype(F32)


# ---- sample the terrain on a grid of (depth step, screen column) ---------------
K = 1500
Zk = (7.0 * (7500.0 / 7.0) ** (np.arange(K) / (K - 1))).astype(F32)
MARG = 2400
U = (np.arange(-MARG, W) - CX).astype(F32)                 # screen offsets, with a left margin
Xg = U[None, :] * Zk[:, None] / FOC
Zg = np.broadcast_to(Zk[:, None], Xg.shape)
Hg = hfun(Xg, Zg)
camy = float(hfun(np.zeros(40, F32), np.linspace(0, 30, 40).astype(F32)).max()) + 15.0

# cast shadows: sweep each depth row from the sun side and carry the shadow height
dxr = Zk / FOC
S = Hg[:, 0].copy()
Lit = np.ones_like(Hg)
for j in range(1, Hg.shape[1]):
    S = np.maximum(Hg[:, j], S - dxr * TAN_E)
    Lit[:, j] = smooth(-0.9, -0.05, (Hg[:, j] - S) / np.sqrt(dxr + 0.02))

# slopes
Hx = np.gradient(Hg, axis=1) / dxr[:, None]
dZ = np.gradient(Zk)
Hz = np.gradient(Hg, axis=0) / dZ[:, None] - Hx * (U[None, :] / FOC)

sl = slice(MARG, MARG + W)
Hs, Hxs, Hzs, Lits = Hg[:, sl], Hx[:, sl], Hz[:, sl], Lit[:, sl]
Ys = HZ - FOC * (Hs - camy) / Zk[:, None]                  # screen row of every sample
Cm = np.minimum.accumulate(Ys, axis=0)

# for every pixel find the first depth step that covers it
kidx = np.zeros((H, W), np.int32)
rows = np.arange(H, dtype=F32)
for i in range(W):
    kidx[:, i] = np.searchsorted(-Cm[:, i], -rows, side='left')
sky_mask = kidx >= K
k1 = np.clip(kidx, 0, K - 1)
k0 = np.clip(k1 - 1, 0, K - 1)
cols = np.broadcast_to(np.arange(W)[None, :], (H, W))
y0, y1 = Ys[k0, cols], Ys[k1, cols]
t = np.clip((y0 - yy) / (y0 - y1 + 1e-6), 0, 1)
t = np.where(k1 == k0, 1.0, t)
g = lambda F: F[k0, cols] * (1 - t) + F[k1, cols] * t
Zp = Zk[k0] * (1 - t) + Zk[k1] * t
Xp = (xx - CX) * Zp / FOC
hx, hz, lit = g(Hxs), g(Hzs), g(Lits)

# ---- wind ripples (too small for the grid, so they are added per pixel) ----------
WL = 0.2
ppw = WL * FOC / Zp                                        # pixels per ripple
rip_fade = smooth(2.2, 7.0, ppw) * smooth(-0.32, -0.08, hx) * smooth(0.45, 0.25, hx)
phase = (Xp + 0.25 * Zp) * (2 * np.pi / WL) + 60 * N(0, Xp, Zp, 9.0) + 14 * N(2, Xp, Zp, 2.2) + 5 * N(3, Xp, Zp, 0.7)
rip = np.cos(phase) + 0.35 * np.cos(2 * phase + 1.0)
hx2 = hx + 0.2 * rip * rip_fade * (0.55 + 0.9 * N(1, Xp, Zp, 14.0))

# ---- shading ---------------------------------------------------------------
nl = np.sqrt(hx2 * hx2 + 1 + hz * hz)
diff = np.clip((hx2 * COS_E + SIN_E) / nl, 0, 1)           # sun comes from -x
ny = 1 / nl
grain = vnoise((H, W), 1.6, rng) - 0.5
albedo = hexc('#e2a468') * (1 + 0.07 * grain[..., None]) * (0.94 + 0.12 * N(1, Xp, Zp, 60))[..., None]
sun_c = np.array([1.30, 0.86, 0.48], F32) * 2.35
amb_c = np.array([0.20, 0.17, 0.30], F32)
bounce = np.array([0.16, 0.075, 0.04], F32)
light = sun_c * (diff * lit)[..., None] + amb_c * (0.55 + 0.45 * ny)[..., None] \
    + bounce * (1 - lit * 0.6)[..., None]
sand = albedo * light
# bright rim where the sun just grazes a crest
sand = sand / (1 + sand * 0.33)                            # soft shoulder
haze_c = hexc('#f3b98a')
hz_amt = (1 - np.exp(-(Zp / 2300.0) ** 1.3))[..., None]
sand = mix(sand, haze_c, hz_amt * 0.92)

# ---- sky -----------------------------------------------------------------
ts = np.clip(yy / (HZ + 60), 0, 1)
sky = ramp(ts, [(0, '#33457a'), (0.35, '#6b6c98'), (0.62, '#c98f86'), (0.85, '#f6b983'), (1, '#ffd69a')])
sky += (glow(-250, HZ - 40, 900, 1.5)[..., None] * np.array([0.55, 0.36, 0.14], F32))
cl = fbm((H, W), (26, 520), 5, rng)
cl2 = fbm((H, W), (70, 900), 4, rng)
cmask = smooth(0.52, 0.75, cl * 0.7 + cl2 * 0.45) * smooth(0.02, 0.2, ts) * smooth(1.0, 0.75, ts)
ccol = ramp(ts, [(0, '#f0b9a8'), (0.6, '#ffc78f'), (1, '#ffe2ae')])
sky = comp(sky, ccol, cmask * 0.8)
img = np.where(sky_mask[..., None], sky, sand)
# soften the far silhouette into the sky
edge = blur(sky_mask.astype(F32), 1.0)
img = mix(sand, sky, edge[..., None]) * (1 - (~sky_mask)[..., None] * 0) if False else mix(sand, sky, edge[..., None])

# low dust haze at the horizon
dust = np.exp(-((yy - HZ - 10) / 70.0) ** 2) * 0.22
img = img + dust[..., None] * hexc('#ffc58a')


# ---- caravan ---------------------------------------------------------------
def project(x, yw, z):
    return CX + FOC * x / z, HZ - FOC * (yw - camy) / z


def ground(x, z):
    return float(hfun(np.array([x], F32), np.array([z], F32))[0])


def ell(cx_, cy_, rx, ry, n=14):
    return [(cx_ + rx * math.cos(a), cy_ + ry * math.sin(a)) for a in np.linspace(0, 2 * np.pi, n, endpoint=False)]


def camel_parts(step, rider):
    """Camel outline pieces in metres: (forward, up)."""
    sw = 0.22 * math.sin(step)
    parts = [ell(0, 1.5, 0.95, 0.42), ell(-0.05, 1.98, 0.42, 0.36),
             [(0.7, 1.35), (0.95, 1.3), (1.42, 2.15), (1.2, 2.25)],
             ell(1.47, 2.25, 0.27, 0.13), ell(-0.92, 1.5, 0.12, 0.3),
             [(0.56, 1.3), (0.76, 1.3), (0.7 + sw, 0), (0.6 + sw, 0)],
             [(0.38, 1.3), (0.56, 1.3), (0.46 - sw, 0), (0.36 - sw, 0)],
             [(-0.58, 1.3), (-0.4, 1.3), (-0.46 - sw, 0), (-0.56 - sw, 0)],
             [(-0.8, 1.3), (-0.6, 1.3), (-0.64 + sw, 0), (-0.74 + sw, 0)]]
    if rider:
        parts += [[(-0.22, 2.15), (0.2, 2.15), (0.14, 2.8), (-0.14, 2.8)], ell(0.02, 2.93, 0.13, 0.15), ell(-0.35, 2.05, 0.3, 0.2)]
    else:
        parts += [ell(-0.1, 2.18, 0.55, 0.2), ell(-0.5, 1.75, 0.2, 0.3)]
    return parts


def person_parts():
    return [[(-0.17, 0), (0.17, 0), (0.22, 1.45), (-0.22, 1.45)], ell(0, 1.62, 0.14, 0.16),
            [(0.3, 0), (0.33, 0), (0.25, 1.9), (0.22, 1.9)]]


CAR_X0, CAR_Z0, CAR_DX, CAR_DZ = -34.0, 150.0, 4.6, -3.3
hd = math.hypot(CAR_DX, CAR_DZ)
DIRX, DIRZ = CAR_DX / hd, CAR_DZ / hd
shl, fig = Layer(), Layer()
members = [('person', 0)] + [('camel', i) for i in range(1, 7)]
for kind, i in members:
    x0, z0 = CAR_X0 + CAR_DX * (6 - i) * (1.0 if i else 1.1), CAR_Z0 + CAR_DZ * (6 - i) * (1.0 if i else 1.1)
    parts = person_parts() if kind == 'person' else camel_parts(i * 1.9, i in (2, 5))
    sc = 1.0 if kind == 'person' else rng.uniform(0.93, 1.07)
    g0 = ground(x0, z0)
    for poly in parts:
        up, shd = [], []
        for (b, a) in poly:
            b, a = b * sc * 1.5, a * sc * 1.5
            wx, wz = x0 + b * DIRX, z0 + b * DIRZ
            up.append(project(wx, ground(wx, wz) * 0 + g0 + a, wz))
            sx_ = wx + a / TAN_E * 0.9                      # shadow falls away from the sun (+x)
            shd.append(project(sx_, ground(sx_, wz) + 0.02, wz))
        shl.poly(shd, hexc('#4a2c2e'), 0.82)
        fig.poly(up, hexc('#2b1a17'))
        if kind == 'camel':                                # warm rim light on the sun side
            pass
# the trail they leave behind
for j in range(90):
    f = j * 0.42
    wx, wz = CAR_X0 - DIRX * (2 + f) + 0.25 * math.sin(j * 1.7), CAR_Z0 - DIRZ * (2 + f)
    px_, py_ = project(wx, ground(wx, wz), wz)
    shl.dot(px_, py_, 2.6, hexc('#7a4a32'), 0.55, ry=1.0)
img = shl.onto(img, soften=0.7)
img = fig.onto(img)

# ---- finish -----------------------------------------------------------------
img = bloom(img, 0.82, (8, 40), (0.12, 0.12))
img = np.clip(img, 0, 1)
img = img ** 1.06
finish(img, '02-desert-dunes-golden-hour', rng, vignette=0.2, weave=0.0, grain=0.014)
