ExperimentsFable 5.2 Python art (30 images)

Synthwave sunset, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""25 Synthwave sunset.

A retro 1980s scene: striped sun, neon wire-frame valley, glowing grid road.
Fable 5.2 Python art experiment: every pixel comes from the code below.
The valley is a real 3D mesh of triangles seen in perspective; it is drawn
from far to near so that near hills hide far ones. The neon lines get a soft
glow, the road mirrors the sun, and the picture is finished like an old
video tape (scan lines, colour fringes, grain).
Run: .venv/bin/python scripts/25-synthwave-sunset.py
"""
import os, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

W, H = 1600, 2000
SS = 2
SEED = 25
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '25-synthwave-sunset.png')
F = np.float32
rng = np.random.default_rng(SEED)
HOR = 1190                 # horizon row
FOC = 1500.0               # focal length in pixels
CAMH = 2.3                 # camera height above the road
SUNX, SUNY, SUNR = 800, 850, 410


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


def ramp(t, stops):
    pos = [p for p, _ in stops]
    cols = np.array([c for _, c in stops], F)
    return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F)


def ridge(n, r, octaves=5, first=6):
    """Jagged skyline made of straight pieces (low-poly look)."""
    x = np.linspace(0, 1, n)
    out = np.zeros(n)
    amp, k = 1.0, first
    for _ in range(octaves):
        pts = r.random(k + 2)
        out += amp * np.interp(x * k, np.arange(k + 2), pts)
        amp *= 0.5
        k *= 2
    return out / 2.0


def main():
    yy, xx = np.mgrid[0:H, 0:W].astype(F)
    # ------------------------------------------------------------------ sky
    t = yy / HOR
    sky = ramp(t, [(0.0, (0.012, 0.006, 0.055)), (0.30, (0.045, 0.012, 0.150)), (0.55, (0.150, 0.022, 0.290)),
                   (0.78, (0.430, 0.050, 0.420)), (0.93, (0.900, 0.230, 0.400)), (1.0, (1.000, 0.500, 0.300))])
    # stars, fewer near the horizon
    srng = np.random.default_rng(1)
    stars = np.zeros((H, W), F)
    n = 2600
    sx = srng.integers(0, W, n); sy = (srng.random(n) ** 1.5 * HOR * 0.8).astype(int)
    stars[sy, sx] = srng.random(n) ** 3 * 1.6 + 0.12
    big = srng.choice(n, 70, replace=False)
    glow = np.zeros((H, W), F)
    glow[sy[big], sx[big]] = srng.uniform(1.5, 4.0, 70)
    cross = np.zeros((H, W), F)
    for i in big[:26]:
        L = srng.integers(8, 22)
        for d in range(-L, L + 1):
            k = (1 - abs(d) / L) ** 2
            if 0 <= sx[i] + d < W:
                cross[sy[i], sx[i] + d] += k
            if 0 <= sy[i] + d < H:
                cross[sy[i] + d, sx[i]] += k
    starl = stars + ndi.gaussian_filter(glow, 1.4) * 5 + ndi.gaussian_filter(glow, 5) * 14 + ndi.gaussian_filter(cross, 0.7) * 0.9
    starfade = 1 - smooth(0.45, 0.85, t)
    sky += (starl * starfade)[..., None] * np.array([0.85, 0.9, 1.0], F)
    # a shooting star
    m = Image.new('L', (W, H), 0)
    d = ImageDraw.Draw(m)
    for k in range(60):
        a = k / 59
        d.line([(1240 - 230 * a, 250 + 105 * a), (1240 - 230 * (a + 0.02), 250 + 105 * (a + 0.02))], fill=int(255 * (1 - a) ** 2), width=3)
    sky += (ndi.gaussian_filter(np.asarray(m, F) / 255, 1.2) * 1.3)[..., None] * np.array([0.9, 0.95, 1.0], F)

    # a ringed planet, lit from the side of the sun
    pxc, pyc, pr = 330.0, 430.0, 78.0
    dpl = np.hypot(xx - pxc, yy - pyc)
    pdisc = smooth(pr + 1, pr - 1, dpl)
    nz = np.sqrt(np.clip(1 - (dpl / pr) ** 2, 0, 1))
    lit = np.clip(((xx - pxc) / pr) * 0.55 + ((yy - pyc) / pr) * 0.65 + nz * 0.35, 0, 1)
    band = 0.85 + 0.15 * np.sin((yy - pyc) * 0.16 + 0.004 * (xx - pxc) * (yy - pyc) / 6)
    pcol = (np.array([0.10, 0.04, 0.22], F)[None, None, :] * (1 - lit[..., None])
            + np.array([0.95, 0.45, 0.75], F)[None, None, :] * (lit * band)[..., None])
    ca, sa = math.cos(-0.38), math.sin(-0.38)
    ru = ((xx - pxc) * ca + (yy - pyc) * sa) / (pr * 2.15)
    rv = (-(xx - pxc) * sa + (yy - pyc) * ca) / (pr * 0.50)
    rr = np.hypot(ru, rv)
    ring = (smooth(0.62, 0.66, rr) * (1 - smooth(0.98, 1.02, rr))) * (0.55 + 0.45 * np.sin(rr * 60) ** 2) * (1 - 0.8 * smooth(0.78, 0.80, rr) * (1 - smooth(0.83, 0.85, rr)))
    back = rv < 0
    ringcol = np.array([0.55, 0.85, 1.0], F)
    sky = sky * (1 - (ring * back * 0.8)[..., None]) + ringcol * (ring * back * 0.8)[..., None]
    sky = sky * (1 - pdisc[..., None]) + pcol * pdisc[..., None]
    sky = sky * (1 - (ring * ~back * 0.9)[..., None]) + ringcol * (ring * ~back * 0.9)[..., None]

    # ------------------------------------------------------------------ sun
    dsun = np.hypot(xx - SUNX, yy - SUNY)
    ts = np.clip((yy - (SUNY - SUNR)) / (2 * SUNR), 0, 1)
    suncol = ramp(ts, [(0.0, (1.0, 0.95, 0.30)), (0.30, (1.0, 0.70, 0.10)), (0.55, (1.0, 0.36, 0.22)), (0.80, (1.0, 0.12, 0.50)), (1.0, (0.85, 0.08, 0.62))])
    disc = smooth(SUNR + 1.2, SUNR - 1.2, dsun)
    # cut-out stripes that grow wider toward the bottom
    cut = np.zeros((H, W), F)
    y0 = SUNY - SUNR * 0.22
    k = 0
    while y0 < SUNY + SUNR:
        gap = 8 + 6.5 * k
        cut = np.maximum(cut, smooth(y0 - 1, y0 + 1, yy) * (1 - smooth(y0 + gap - 1, y0 + gap + 1, yy)))
        y0 += gap + max(26, 62 - 3.0 * k)
        k += 1
    sunmask = disc * (1 - cut)
    halo = np.exp(-np.clip(dsun - SUNR, 0, None) / 110.0) * 0.36 + np.exp(-np.clip(dsun - SUNR, 0, None) / 380.0) * 0.12
    sky += (halo * (1 - disc))[..., None] * np.array([1.0, 0.32, 0.52], F)
    sky = sky * (1 - sunmask[..., None]) + suncol * 1.6 * sunmask[..., None]
    sunlayer = suncol * sunmask[..., None]                   # kept for the reflection on the road

    # ------------------------------------------------------------------ far mountains (flat low-poly ranges)
    img = sky
    mrng = np.random.default_rng(6)
    for li, (base, amp, c_top, c_bot, rim) in enumerate((
            (HOR - 10, 250, (0.32, 0.07, 0.46), (0.62, 0.13, 0.50), 0.55),
            (HOR + 4, 170, (0.13, 0.03, 0.27), (0.30, 0.06, 0.38), 0.8))):
        r = ridge(W, mrng, 5, 5 + 2 * li)
        centre = 1 - 0.80 * np.exp(-((np.arange(W) - W / 2) / (300 + 60 * li)) ** 2)     # a gap in front of the sun
        ytop = base - amp * (0.25 + r) * centre
        inside = smooth(-0.8, 0.8, yy - ytop[None, :])
        slope = np.gradient(ytop)
        facet = np.where(slope[None, :] * np.sign(np.arange(W) - W / 2)[None, :] > 0, 1.0, 0.72)   # faces toward the sun are lighter
        tt = np.clip((yy - ytop[None, :]) / (amp * 1.0), 0, 1)
        colr = (np.array(c_top, F)[None, None, :] * (1 - tt[..., None]) + np.array(c_bot, F)[None, None, :] * tt[..., None]) * facet[..., None]
        rimk = np.exp(-np.clip(yy - ytop[None, :], 0, None) / 3.0) * rim
        colr = colr + rimk[..., None] * np.array([1.0, 0.45, 0.70], F)
        img = img * (1 - inside[..., None]) + colr * inside[..., None]

    # ------------------------------------------------------------------ ground: base colour and sun reflection
    below = smooth(HOR - 0.7, HOR + 0.7, yy)
    dy = np.clip(yy - HOR, 0.5, None)
    zf = FOC * CAMH / dy
    xw = (xx - W / 2) * zf / FOC
    ground = ramp(np.clip(dy / (H - HOR), 0, 1), [(0, (0.20, 0.03, 0.30)), (0.12, (0.085, 0.012, 0.17)), (1.0, (0.030, 0.006, 0.075))])
    # the sun mirrored on the road: a column of glowing bars that get shorter toward the viewer
    half = SUNR * 0.80 * np.clip(1 - dy / 760.0, 0, 1) ** 0.7
    bars = smooth(0.35, 0.6, 0.5 + 0.5 * np.sin(np.log1p(dy / 10.0) * 30.0))
    glit = smooth(half + 20, half - 20, np.abs(xx - SUNX)) * bars * np.exp(-dy / 300.0)
    refl = ramp(np.clip(dy / 700.0, 0, 1), [(0, (1.0, 0.45, 0.40)), (0.4, (1.0, 0.20, 0.55)), (1.0, (0.7, 0.10, 0.70))])
    ground = ground + refl * (0.62 * ndi.gaussian_filter(glit, 2.0))[..., None]
    road = np.exp(-(xw / 5.0) ** 2)
    ground = ground + (0.10 * road * np.exp(-dy / 500.0))[..., None] * np.array([1.0, 0.3, 0.7], F)
    ground += (np.exp(-dy / 30.0) * 0.55)[..., None] * np.array([1.0, 0.35, 0.60], F)
    img = img * (1 - below[..., None]) + ground * below[..., None]

    # ------------------------------------------------------------------ 3D valley mesh
    NXV, NZV, CELL = 45, 78, 2.0
    gx = (np.arange(NXV) - NXV // 2) * CELL
    gz = 3.2 + np.arange(NZV) * CELL
    hrng = np.random.default_rng(11)
    rnd = hrng.random((NZV, NXV))
    rnd = 0.6 * rnd + 0.4 * ndi.gaussian_filter(rnd, 1.0, mode='wrap') * 1.0
    side = smooth(4.0, 15.0, np.abs(gx))[None, :]
    far = 0.75 + 0.5 * smooth(20, 90, gz)[:, None]
    hgt = side * (1.0 + 16.0 * rnd ** 1.6) * far
    hgt += side * 3.0 * np.sin(gz[:, None] * 0.13 + gx[None, :] * 0.2) ** 2
    X = np.broadcast_to(gx[None, :], hgt.shape)
    Z = np.broadcast_to(gz[:, None], hgt.shape)
    PXs = (W / 2 + FOC * X / Z) * SS
    PYs = (HOR + FOC * (CAMH - hgt) / Z) * SS
    fill = Image.new('RGB', (W * SS, H * SS), (0, 0, 0))
    mask = Image.new('L', (W * SS, H * SS), 0)
    lines = Image.new('RGB', (W * SS, H * SS), (0, 0, 0))
    df, dm, dl = ImageDraw.Draw(fill), ImageDraw.Draw(mask), ImageDraw.Draw(lines)
    PINK = np.array([1.0, 0.16, 0.80]); CYAN = np.array([0.15, 0.95, 1.0])
    sun_dir = np.array([0.0, 0.35, 1.0]); sun_dir /= np.linalg.norm(sun_dir)
    for iz in range(NZV - 2, -1, -1):
        for ix in range(NXV - 1):
            idx = [(iz, ix), (iz, ix + 1), (iz + 1, ix + 1), (iz + 1, ix)]
            P3 = np.array([[X[a], hgt[a], Z[a]] for a in idx])
            P2 = [(PXs[a], PYs[a]) for a in idx]
            if max(p[0] for p in P2) < -50 or min(p[0] for p in P2) > W * SS + 50:
                continue
            hmean = P3[:, 1].mean()
            flat = hmean < 0.05
            flip = (ix + iz) % 2 == 0
            tris = ((0, 1, 2), (0, 2, 3)) if flip else ((0, 1, 3), (1, 2, 3))
            zc = P3[:, 2].mean()
            fog = math.exp(-zc / 70.0)
            for tri in tris:
                a, b, c = P3[list(tri)]
                nrm = np.cross(b - a, c - a)
                nrm /= np.linalg.norm(nrm) + 1e-9
                if nrm[1] < 0:
                    nrm = -nrm
                lit = max(0.0, float(nrm @ sun_dir))
                hk = min(1.0, hmean / 14.0)
                base = np.array([0.050, 0.008, 0.115]) * (1 - hk) + np.array([0.11, 0.02, 0.24]) * hk
                colr = base + np.array([0.75, 0.16, 0.50]) * lit ** 1.5 * 0.55
                colr = colr * fog + np.array([0.25, 0.035, 0.31]) * (1 - fog)
                pts = [P2[i] for i in tri]
                if not flat:
                    df.polygon(pts, fill=tuple(int(min(255, v * 255)) for v in colr))
                    dm.polygon(pts, fill=255)
                    dl.polygon(pts, fill=(0, 0, 0))
            hk = min(1.0, max(0.0, (hmean - 0.5) / 8.0))
            lc = PINK * (1 - hk) + CYAN * hk
            inten = 0.30 + 0.70 * math.exp(-zc / 55.0)
            lw = int(max(SS, min(5 * SS, round(SS * 26.0 / zc))))
            colr = tuple(int(255 * v * inten) for v in lc)
            dl.line(P2 + [P2[0]], fill=colr, width=lw)
            if not flat:
                d0, d1 = (0, 2) if flip else (1, 3)
                dl.line([P2[d0], P2[d1]], fill=tuple(int(v * 0.55) for v in colr), width=max(SS, lw - SS))
    fill = np.asarray(fill.resize((W, H), Image.BOX), F) / 255
    maskm = np.asarray(mask.resize((W, H), Image.BOX), F) / 255
    linem = np.asarray(lines.resize((W, H), Image.BOX), F) / 255
    print('mesh drawn %.1fs' % (time.time() - T0))
    img = img * (1 - maskm[..., None]) + fill * maskm[..., None]
    lg = linem * 1.4 + ndi.gaussian_filter(linem, (3, 3, 0)) * 0.9 + ndi.gaussian_filter(linem, (11, 11, 0)) * 0.7 \
        + ndi.gaussian_filter(linem, (36, 36, 0)) * 0.35
    img = img + lg
    # bright line of light on the horizon
    hl = np.exp(-((yy - HOR) / 2.2) ** 2) * (1 - maskm) * (0.5 + 0.5 * np.exp(-((xx - W / 2) / 520) ** 2))
    img += hl[..., None] * np.array([1.0, 0.75, 0.85], F) * 0.9

    # ------------------------------------------------------------------ finish
    hi = np.clip(img - 0.75, 0, 4)
    img = img + 0.20 * ndi.gaussian_filter(hi, (14, 14, 0)) + 0.10 * ndi.gaussian_filter(hi, (60, 60, 0))
    img = 1 - np.exp(-img * 1.15)
    g = img.mean(-1, keepdims=True)
    img = np.clip(g + (img - g) * 1.18, 0, 1)
    # colour fringes, stronger at the edges (like a cheap lens)
    cxn, cyn = (xx - W / 2) / W, (yy - H / 2) / H
    out = np.empty_like(img)
    for i, k in enumerate((1.0028, 1.0, 0.9972)):
        out[..., i] = ndi.map_coordinates(img[..., i], [H / 2 + cyn * H * k, W / 2 + cxn * W * k], order=1, mode='nearest')
    img = out
    scan = 1 - 0.07 * (0.5 + 0.5 * np.sin(yy * math.pi / 2.0))
    img *= scan[..., None]
    vig = 1 - 0.38 * smooth(0.45, 1.15, np.hypot(cxn, cyn) * 1.7)
    img *= vig[..., None]
    img = np.clip(img, 0, 1) ** (1 / 1.12)
    img += (rng.random((H, W, 1)).astype(F) - 0.5) * 0.03
    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()