ExperimentsFable 5.2 Python art (30 images)

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

A cratered lunar height field (thousands of stamped craters) drawn in
perspective with hard sun shadows, a procedural Earth (3D noise for
continents and clouds, lit by the same sun), and crisp stars.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/08-earthrise-moon.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 = 808
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

FOC, HZ, CX = 1500.0, 1210.0, W / 2
ELEV = math.radians(12.5)
TAN_E, SIN_E, COS_E = math.tan(ELEV), math.sin(ELEV), math.cos(ELEV)
RMOON = 1737e3


def crater_profile(r, R):
    """Height of a crater of radius R at relative distance r = dist / R."""
    d, hr = 0.42 * R, 0.085 * R
    inside = -d * (1 - r * r) + hr * r ** 4
    outside = hr * np.maximum(r, 1e-3) ** -3.2
    return np.where(r < 1, inside, outside)


def stamp(grid, cx, cy, Rc, wrap):
    """Add one crater (all values in grid cells)."""
    n = grid.shape[0]
    hw = int(min(Rc * 3.2 + 2, n // 2 - 1))
    ix, iy = int(round(cx)), int(round(cy))
    ax = np.arange(-hw, hw + 1)
    gx_, gy_ = np.meshgrid(ax - (cx - ix), ax - (cy - iy))
    r = np.hypot(gx_, gy_) / Rc
    prof = crater_profile(r, Rc) * smooth(3.2, 2.2, r)
    if wrap:
        grid[np.ix_((iy + ax) % n, (ix + ax) % n)] += prof.astype(F32)
    else:
        y0, y1, x0, x1 = iy - hw, iy + hw + 1, ix - hw, ix + hw + 1
        sy0, sx0 = max(0, -y0), max(0, -x0)
        sy1, sx1 = prof.shape[0] - max(0, y1 - n), prof.shape[1] - max(0, x1 - n)
        if sy1 > sy0 and sx1 > sx0:
            grid[y0 + sy0:y0 + sy1, x0 + sx0:x0 + sx1] += prof[sy0:sy1, sx0:sx1].astype(F32)


# far grid: 30 m cells, 72 km wide; x from -36 km, z from -2 km
FAR_N, FAR_CELL, FAR_X0, FAR_Z0 = 2400, 30.0, -36000.0, -2000.0
far = (fbm((FAR_N, FAR_N), 420, 5, rng) - 0.5) * 900.0 / FAR_CELL          # gentle highlands, in cells
HERO = [(1500.0, 6200.0, 1500.0), (-5200.0, 15500.0, 3300.0), (5200.0, 21000.0, 2400.0), (-900.0, 2600.0, 520.0)]
for (hx_, hz_, hr_) in HERO:
    stamp(far, (hx_ - FAR_X0) / FAR_CELL, (hz_ - FAR_Z0) / FAR_CELL, hr_ / FAR_CELL, False)
Rs = np.clip(90.0 * (1 - rng.random(1500)) ** (-1 / 2.0), 90, 4200)
for Rc in np.sort(Rs)[::-1]:
    stamp(far, rng.uniform(0, FAR_N), rng.uniform(0, FAR_N), Rc / FAR_CELL, False)
far *= FAR_CELL                                                         # back to metres

# small craters: a 3 km tile with 1.5 m cells that repeats
T_N, T_CELL = 2000, 1.5
tile = np.zeros((T_N, T_N), F32)
Rs = np.clip(3.5 * (1 - rng.random(5200)) ** (-1 / 1.9), 3.5, 230)
for Rc in np.sort(Rs)[::-1]:
    stamp(tile, rng.uniform(0, T_N), rng.uniform(0, T_N), Rc / T_CELL, True)
tile *= T_CELL
MIC = [ndi.gaussian_filter(rng.random((256, 256)).astype(F32), s_, mode='wrap') for s_ in (1.0, 2.5)]
MIC = [(m - m.mean()) / m.std() for m in MIC]


def hfun(x, z):
    cf = np.stack([(z - FAR_Z0) / FAR_CELL, (x - FAR_X0) / FAR_CELL])
    h = ndi.map_coordinates(far, cf, order=3, mode='nearest')
    ct = np.stack([(z / T_CELL) % T_N, (x / T_CELL) % T_N])
    h = h + ndi.map_coordinates(tile, ct, order=1, mode='grid-wrap')
    xr, zr = 0.8 * x + 0.6 * z + 700.0, -0.6 * x + 0.8 * z + 300.0            # the same tile again, turned and larger
    ct = np.stack([(zr / (T_CELL * 2.3)) % T_N, (xr / (T_CELL * 2.3)) % T_N])
    h = h + 2.3 * ndi.map_coordinates(tile, ct, order=1, mode='grid-wrap')
    return (h - (x * x + z * z) / (2 * RMOON)).astype(F32)


# ---- sample the ground on (depth step, screen column), as in a radar sweep ------------------
K = 1700
Zk = (110.0 * (95000.0 / 110.0) ** (np.arange(K) / (K - 1))).astype(F32)
MARG = 1800
U = (np.arange(-MARG, W) - CX).astype(F32)
Xg = U[None, :] * Zk[:, None] / FOC
Zg = np.broadcast_to(Zk[:, None], Xg.shape)
Hg = hfun(Xg, Zg)
camy = float(hfun(np.zeros(1, F32), np.zeros(1, F32))[0]) + 420.0

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.5, -0.02, (Hg[:, j] - S) / (dxr + 0.3))
Lit = ndi.gaussian_filter1d(Lit, 1.3, axis=0)            # soften the stair steps between depth rows
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]
Cm = np.minimum.accumulate(Ys, axis=0)
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)

# fine surface roughness per pixel
def mic(i, scale):
    c = np.stack([(Zp / scale * 16) % 256, (Xp / scale * 16) % 256])
    return ndi.map_coordinates(MIC[i], c, order=1, mode='grid-wrap')


pxm = Zp / FOC                                           # metres per pixel
rough = 0.10 * mic(0, 9.0) * smooth(4.0, 0.5, pxm) + 0.07 * mic(1, 60.0) * smooth(25.0, 3.0, pxm) + 0.05 * mic(0, 420.0)
hx2 = hx + rough
nl = np.sqrt(hx2 * hx2 + 1 + hz * hz)
diff = np.clip((hx2 * COS_E + SIN_E) / nl, 0, 1) / SIN_E * 0.42
tone = 0.82 + 0.12 * mic(1, 5200.0) + 0.05 * mic(1, 700.0) + 0.03 * mic(0, 30.0)
albedo = np.clip(tone, 0.5, 1.2)[..., None] * hexc('#c9c4ba')
moon = albedo * (np.clip(diff, 0, 1.6) ** 0.85 * lit)[..., None] * 0.95 + np.array([0.013, 0.016, 0.024], F32)
moon = moon / (1 + 0.25 * moon)

# ---- space: stars ----------------------------------------------------------------------------
sky = np.zeros((H, W, 3), F32)
band = np.exp(-(((xx - 200) * 0.55 + (yy - 520) * 0.84) / 260.0) ** 2)
n = 5200
sx_, sy_ = rng.uniform(0, W, n), rng.uniform(0, H, n)
keepp = rng.random(n) < (0.35 + 0.65 * band[sy_.astype(int), sx_.astype(int)])
sx_, sy_ = sx_[keepp], sy_[keepp]
mag = rng.random(len(sx_)) ** 7 * 1.6 + 0.07
tint = np.where(rng.random((len(sx_), 1)) < 0.25, np.array([1.0, 0.86, 0.72]), np.where(rng.random((len(sx_), 1)) < 0.4, np.array([0.78, 0.86, 1.0]), np.ones(3)))
for c in range(3):
    lay = np.zeros((H, W), F32)
    np.add.at(lay, (sy_.astype(int), sx_.astype(int)), (mag * tint[:, c]).astype(F32))
    sky[..., c] = blur(lay, 0.62) * 5.2 + blur(lay * (lay > 0.55), 1.7) * 9.0
sky += (band * (0.5 + 0.8 * fbm((H, W), 120, 4, rng)))[..., None] * np.array([0.016, 0.018, 0.028], F32)

# ---- the Earth -------------------------------------------------------------------------------
EX, EY, RE = 1030.0, 570.0, 242.0
LAT3 = rng.random((64, 64, 64)).astype(F32)


def noise3(p, freq):
    c = np.stack([(p[..., i] * freq + 17.0 * i) % 64 for i in range(3)])
    return ndi.map_coordinates(LAT3, c, order=1, mode='grid-wrap')


def fbm3(p, freq, octaves, gain=0.5):
    out, amp, tot = 0.0, 1.0, 0.0
    for o in range(octaves):
        out = out + amp * noise3(p, freq * 2 ** o)
        tot += amp
        amp *= gain
    return out / tot


x0e, x1e, y0e, y1e = int(EX - RE - 30), int(EX + RE + 30), int(EY - RE - 30), int(EY + RE + 30)
SS = 2                                                    # 2x2 samples per pixel for a clean edge
ey_, ex_ = np.mgrid[0:(y1e - y0e) * SS, 0:(x1e - x0e) * SS].astype(F32)
nx_ = ((ex_ + 0.5) / SS + x0e - EX) / RE
ny_ = -((ey_ + 0.5) / SS + y0e - EY) / RE
r2 = nx_ * nx_ + ny_ * ny_
inside = r2 < 1
nz_ = np.sqrt(np.clip(1 - r2, 0, 1))
nvec = np.stack([nx_, ny_, nz_], -1)
a1, a2 = math.radians(23), math.radians(-38)              # tilt and spin of the globe
Rx = np.array([[1, 0, 0], [0, math.cos(a1), -math.sin(a1)], [0, math.sin(a1), math.cos(a1)]])
Ry = np.array([[math.cos(a2), 0, math.sin(a2)], [0, 1, 0], [-math.sin(a2), 0, math.cos(a2)]])
Rz = np.array([[math.cos(0.3), -math.sin(0.3), 0], [math.sin(0.3), math.cos(0.3), 0], [0, 0, 1]])
p = (nvec @ (Rz @ Rx @ Ry).T.astype(F32)).astype(F32)
lat = p[..., 1]
elev = fbm3(p + 0.3 * (fbm3(p, 2.2, 3)[..., None] - 0.5), 1.5, 7, 0.56)
land = smooth(0.538, 0.546, elev)
dry = fbm3(p + 5.0, 2.0, 4)
landc = ramp(np.clip((elev - 0.535) * 9 + 0.5 * (dry - 0.5) + 0.25 * (1 - np.abs(lat) * 1.6), 0, 1),
             [(0, '#2c5c2a'), (0.45, '#3f6c30'), (0.68, '#7d7a44'), (0.85, '#b89a66'), (1, '#8a6a4a')])
sea = ramp(np.clip((0.535 - elev) * 7, 0, 1), [(0, '#1f6aa8'), (0.25, '#124a8a'), (1, '#07255c')])
surf = mix(sea, landc, land[..., None])
ice = smooth(0.80, 0.9, np.abs(lat) + 0.08 * (dry - 0.5))
surf = mix(surf, hexc('#eef4f8'), ice[..., None])
pc = p * np.array([1.0, 2.4, 1.0], F32)
warp = fbm3(p + 9.0, 1.6, 3)[..., None] - 0.5
warp2 = np.stack([fbm3(p + 21.0, 3.0, 3), fbm3(p + 33.0, 3.0, 3), fbm3(p + 45.0, 3.0, 3)], -1) - 0.5
cdens = fbm3(pc + 1.5 * warp + 0.5 * warp2, 2.6, 7, 0.6) * 0.8 + 0.2 * fbm3(p + 3.0, 0.9, 2)
cloud = smooth(0.52, 0.6, cdens) * (0.55 + 0.45 * smooth(0.5, 0.75, fbm3(pc * 3.0 + 7.0, 4.0, 4)))
cloud = np.clip(cloud + 0.5 * smooth(0.6, 0.7, cdens), 0, 1)
Lsun = np.array([-0.8, 0.2, 0.62], F32)
Lsun /= np.linalg.norm(Lsun)
ndl = nvec @ Lsun
day = smooth(-0.06, 0.22, ndl)
spec = np.clip(2 * ndl * nz_ - Lsun[2], 0, 1) ** 40 * (1 - land) * (1 - cloud)
col = surf * (0.25 + 0.95 * np.clip(ndl, 0, 1))[..., None] + spec[..., None] * np.array([1.0, 0.95, 0.85], F32) * 0.6
cshade = 0.55 + 0.6 * np.clip(ndl, 0, 1)
col = mix(col, np.array([0.97, 0.98, 1.0], F32) * cshade[..., None], (cloud * 0.93)[..., None])
limb = (1 - nz_) ** 2.5
col = col + limb[..., None] * hexc('#5aa8ff') * 0.9
col = col * day[..., None] + (1 - day[..., None]) * np.array([0.004, 0.006, 0.012], F32)
rr_ = np.sqrt(r2)
halo = np.exp(-np.clip(rr_ - 1, 0, None) / 0.016) * (rr_ >= 1) * smooth(-0.25, 0.35, (nx_ * Lsun[0] + ny_ * Lsun[1]) / np.maximum(rr_, 1e-3))
earth = np.where(inside[..., None], col, 0) + halo[..., None] * hexc('#4f9cff') * 0.75
alpha = np.where(inside, 1.0, np.clip(halo, 0, 1) * 0.0).astype(F32)
eh, ew = y1e - y0e, x1e - x0e
earth = earth.reshape(eh, SS, ew, SS, 3).mean((1, 3))
alpha = alpha.reshape(eh, SS, ew, SS).mean((1, 3))
sky[y0e:y1e, x0e:x1e] = sky[y0e:y1e, x0e:x1e] * (1 - alpha[..., None]) + earth

# ---- put it together -----------------------------------------------------------------------------
edge = blur(sky_mask.astype(F32), 0.7)[..., None]
img = mix(moon, sky, edge)
img = img + blur(np.clip(img - 0.6, 0, None), 5) * 0.25 + blur(np.clip(img - 0.5, 0, None), 30) * 0.12
img = np.clip(img, 0, 1) ** 0.95
finish(img, '08-earthrise-moon', rng, vignette=0.12, weave=0.0, grain=0.01)