ExperimentsFable 5.2 Python art (30 images)

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

Pixel art: a log cabin on a floating piece of forest at night, warm light inside.
Fable 5.2 Python art experiment: every pixel comes from the code below.
The scene is a small world of cubes (voxels). Each visible cube is lit by the
moon and by the warm lamps, with shadows, and then drawn as a tiny 4-pixel-wide
isometric cube. The result (400 x 500 pixels) is reduced to 56 colours with
ordered dithering and enlarged 4 times without smoothing.
Run: .venv/bin/python scripts/23-isometric-cozy-cabin.py
"""
import os, time, math
import numpy as np
from PIL import Image
from scipy import ndimage as ndi

W, H = 1600, 2000
PX = 4
LW, LH = W // PX, H // PX            # logical pixel-art size
SEED = 23
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '23-isometric-cozy-cabin.png')
F = np.float32
rng = np.random.default_rng(SEED)

N, NZ, G = 92, 104, 28               # world size and ground level
U0, V0 = LW // 2, 268
solid = np.zeros((N, N, NZ), bool)
col = np.zeros((N, N, NZ, 3), F)
emis = np.zeros((N, N, NZ), bool)


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


def vnoise(shape, cell, r):
    h, w = shape
    g = r.random((int(h / cell) + 4, int(w / cell) + 4)).astype(F)
    z = ndi.zoom(g, cell, order=3 if cell >= 3 else 1)
    o = int(cell * 1.5)
    return z[o:o + h, o:o + w]


def fbm(shape, cell, octaves, r):
    out = np.zeros(shape, F)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, max(1.0, cell), r)
        tot += amp
        amp *= 0.5
        cell /= 2
    return out / tot


def C(*c):
    return np.array(c, F)


def box(x0, x1, y0, y1, z0, z1, c, jit=0.06, e=False):
    x0, y0, z0 = max(0, x0), max(0, y0), max(0, z0)
    shp = solid[x0:x1, y0:y1, z0:z1].shape
    solid[x0:x1, y0:y1, z0:z1] = True
    col[x0:x1, y0:y1, z0:z1] = np.asarray(c, F) * (1 + jit * rng.uniform(-1, 1, shp + (1,)).astype(F))
    emis[x0:x1, y0:y1, z0:z1] = e


def put(x, y, z, c, e=False, jit=0.0):
    if 0 <= x < N and 0 <= y < N and 0 <= z < NZ:
        solid[x, y, z] = True
        col[x, y, z] = np.asarray(c, F) * (1 + jit * rng.uniform(-1, 1))
        emis[x, y, z] = e


# ----------------------------------------------------------------------------
# Build the world
# ----------------------------------------------------------------------------
GRASS = C(0.30, 0.52, 0.22)
DIRT = C(0.42, 0.27, 0.16)
STONE = C(0.46, 0.46, 0.50)
LOG_A, LOG_B = C(0.56, 0.36, 0.20), C(0.43, 0.26, 0.14)
WARM = C(1.0, 0.80, 0.36)
CX0, CX1, CY0, CY1 = 28, 64, 26, 54        # cabin footprint
ZT = G + 16                                # top of the log walls
lights = []                                # (position, colour, reach)


def build_island():
    xx, yy = np.mgrid[0:N, 0:N].astype(F)
    edge = fbm((N, N), 14, 3, rng)
    d = np.maximum(np.abs(xx - 45.5), np.abs(yy - 45.5)) * 0.72 + np.hypot(xx - 45.5, yy - 45.5) * 0.36
    rim = 47.5 + (edge - 0.5) * 7
    inside = d < rim
    k = np.clip(1 - d / rim, 0, 1)
    depth = 7 + 21 * k ** 0.5 + 7 * fbm((N, N), 7, 2, rng) * k ** 0.3 + 6 * (vnoise((N, N), 5, rng) > 0.72) * k
    hill = fbm((N, N), 18, 2, rng)
    bump = np.clip(np.round((hill - 0.50) * 9), 0, 3)
    cab = (xx > CX0 - 7) & (xx < CX1 + 9) & (yy > CY0 - 5) & (yy < 92)
    bump[cab] = 0
    pond = ((xx - 18) / 10.5) ** 2 + ((yy - 70) / 7.5) ** 2
    bump[pond < 2.0] = 0
    gn = fbm((N, N), 5, 2, rng)
    for x in range(N):
        for y in range(N):
            if not inside[x, y]:
                continue
            top = G + int(bump[x, y])
            bot = max(0, int(G - depth[x, y]))
            zs = np.arange(bot, top)
            solid[x, y, bot:top] = True
            dz = top - 1 - zs
            c = np.where(dz[:, None] < 1, GRASS * (0.8 + 0.45 * gn[x, y]),
                         np.where(dz[:, None] < 5 + 2 * gn[x, y], DIRT * (1.15 + 0.3 * ((zs[:, None] + x // 3) % 2 == 0) * 0.3 + 0.1),
                                  STONE * (1.15 + 0.3 * ((zs[:, None] // 3 + (x + y) // 7) % 2))))
            col[x, y, bot:top] = c * (1 + 0.07 * rng.uniform(-1, 1, (len(zs), 1)))
            if pond[x, y] < 1.0:                       # water, one step below the grass
                solid[x, y, top - 1] = True
                col[x, y, top - 1] = C(0.16, 0.36, 0.62) * (0.9 + 0.3 * gn[x, y])
                if rng.random() < 0.05:
                    col[x, y, top - 1] = C(0.55, 0.75, 0.95)
                solid[x, y, top:] = False
                col[x, y, top - 2] = C(0.10, 0.22, 0.40)
            elif pond[x, y] < 1.35 and rng.random() < 0.55:
                put(x, y, top, STONE * rng.uniform(0.7, 1.05))
    # a stream leaves the pond and falls off the edge of the island
    for x in (17, 18, 19):
        ys = np.nonzero(inside[x])[0]
        ye = ys.max()
        for y in range(76, ye + 1):
            solid[x, y, G - 1] = True; solid[x, y, G:G + 4] = False
            col[x, y, G - 1] = C(0.22, 0.46, 0.72) * rng.uniform(0.9, 1.15)
        for z in range(0, G):
            k = rng.random()
            put(x, ye + 1, z, C(0.55, 0.78, 0.95) if k < 0.6 else C(0.86, 0.94, 1.0))
        put(x, ye + 2, G - 2, C(0.9, 0.96, 1.0))
    return inside, bump, pond


def pine(cx, cy, height, radius, tint=1.0):
    base = G + int(BUMP[int(cx), int(cy)])
    trunk_h = int(height * 0.22)
    box(int(cx) - 1, int(cx) + 1, int(cy) - 1, int(cy) + 1, base, base + trunk_h + 4, C(0.33, 0.21, 0.13), 0.1)
    tiers = max(3, int(height / 9))
    for z in range(trunk_h, height):
        t = (z - trunk_h) / (height - trunk_h)
        ft = (t * tiers) % 1.0
        r = radius * (1 - t) ** 0.85 * (1.0 - 0.55 * ft) + 0.7
        ri = int(math.ceil(r))
        for dx in range(-ri, ri + 1):
            for dy in range(-ri, ri + 1):
                dd = math.hypot(dx + 0.5 - 0.5, dy)
                if dd <= r + 0.25 * rng.uniform(-1, 1):
                    x, y = int(cx) + dx, int(cy) + dy
                    if 0 <= x < N and 0 <= y < N:
                        shade = 0.62 + 0.45 * (dd / (r + 0.01)) ** 2 + 0.22 * (ft < 0.25)
                        c = C(0.11, 0.36, 0.20) * shade * tint * (1 + 0.14 * rng.uniform(-1, 1))
                        put(x, y, base + z, c)
    put(int(cx), int(cy), base + height, C(0.14, 0.42, 0.24) * tint)


def round_tree(cx, cy, r, colr):
    base = G + int(BUMP[cx, cy])
    box(cx - 1, cx + 1, cy - 1, cy + 1, base, base + 9, C(0.30, 0.19, 0.12), 0.1)
    for dx in range(-r - 1, r + 2):
        for dy in range(-r - 1, r + 2):
            for dz in range(-r - 1, r + 2):
                d = math.sqrt(dx * dx + dy * dy + (dz * 1.15) ** 2)
                if d <= r + rng.uniform(-0.9, 0.5):
                    k = 0.75 + 0.35 * (dz / r) + 0.1 * rng.uniform(-1, 1)
                    put(cx + dx, cy + dy, base + 8 + r + dz, colr * k)


def build_cabin():
    x0, x1, y0, y1 = CX0, CX1, CY0, CY1
    box(x0, x1, y0, y1, G, G + 2, STONE * 0.9, 0.12)
    for z in range(G + 2, ZT):
        c = LOG_A if (z - G) % 2 == 0 else LOG_B
        box(x0, x1, y0, y1, z, z + 1, c, 0.05)
        # logs cross at the corners and stick out
        if (z - G) % 4 < 2:
            box(x1, x1 + 1, y1 - 1, y1, z, z + 1, C(0.74, 0.56, 0.34), 0.04)
            box(x0 - 1, x0, y1 - 1, y1, z, z + 1, c, 0.04)
        else:
            box(x1 - 1, x1, y1, y1 + 1, z, z + 1, C(0.74, 0.56, 0.34), 0.04)
            box(x1 - 1, x1, y0 - 1, y0, z, z + 1, c, 0.04)
    yc = (y0 + y1 - 1) / 2.0
    half = (y1 - y0) / 2.0 + 3
    for y in range(y0 - 3, y1 + 3):
        rz = ZT - 2 + int(round(half - abs(y - yc)))
        if y0 <= y < y1:                                # gable wall under the roof (vertical boards)
            for x in range(x0, x1):
                cc = C(0.52, 0.33, 0.18) * (0.9 + 0.16 * (x % 2))
                col[x, y, ZT:rz] = cc
                solid[x, y, ZT:rz] = True
        for x in range(x0 - 2, x1 + 2):
            sh = ((x + 2 * (y % 2)) // 3 * 7 + y * 13) % 5
            c = C(0.50, 0.22, 0.17) * (0.80 + 0.09 * sh)
            if MOSS[x, y] > 0.63:
                c = C(0.24, 0.42, 0.22) * (0.8 + 0.08 * sh)
            put(x, y, rz, c * 0.80)
            put(x, y, rz + 1, c)
    rzt = ZT - 2 + int(round(half))
    box(x0 - 2, x1 + 2, int(yc), int(yc) + 2, rzt + 1, rzt + 2, C(0.32, 0.16, 0.12), 0.05)
    # small window in the gable
    ym = int(yc)
    for y in range(ym - 1, ym + 3):
        for z in range(ZT + 4, ZT + 9):
            put(x1 - 1, y, z, WARM * 0.95, e=True)
    for z in range(ZT + 4, ZT + 9):
        put(x1 - 1, ym - 2, z, C(0.30, 0.17, 0.10)); put(x1 - 1, ym + 3, z, C(0.30, 0.17, 0.10))
    for y in range(ym - 2, ym + 4):
        put(x1 - 1, y, ZT + 3, C(0.30, 0.17, 0.10)); put(x1 - 1, y, ZT + 9, C(0.30, 0.17, 0.10))
        put(x1 - 1, y, ZT + 6, C(0.36, 0.20, 0.10))
    # chimney
    cx, cy = x1 - 13, y0 + 6
    box(cx, cx + 6, cy, cy + 6, G, ZT + 27, STONE * 1.0, 0.16)
    for z in range(G, ZT + 27, 2):                       # brick courses
        col[cx:cx + 6, cy:cy + 6, z] *= 0.84
    box(cx - 1, cx + 7, cy - 1, cy + 7, ZT + 27, ZT + 28, STONE * 1.2, 0.08)
    box(cx + 1, cx + 5, cy + 1, cy + 5, ZT + 27, ZT + 28, C(0.08, 0.07, 0.08), 0)
    global CHIM
    CHIM = (cx + 3.0, cy + 3.0, ZT + 28)
    FR = C(0.30, 0.17, 0.10)
    MU = C(0.38, 0.21, 0.10)
    FLW = [C(0.85, 0.25, 0.30), C(0.95, 0.70, 0.25), C(0.25, 0.55, 0.25), C(0.9, 0.45, 0.6)]

    def window_y(xa, xb):                                # window in the wall that faces left
        y = y1 - 1
        box(xa - 1, xb + 1, y, y + 1, G + 5, G + 13, FR, 0.03)
        for x in range(xa, xb):
            for z in range(G + 6, G + 12):
                put(x, y, z, WARM * (0.84 + 0.16 * (z - G - 6) / 5), e=True)
        mid = (xa + xb) // 2
        for z in range(G + 6, G + 12):
            put(mid, y, z, MU)
        for x in range(xa, xb):
            put(x, y, G + 9, MU)
        # shutters and a flower box
        box(xa - 3, xa - 1, y + 1, y + 2, G + 6, G + 12, C(0.20, 0.36, 0.34), 0.05)
        box(xb + 1, xb + 3, y + 1, y + 2, G + 6, G + 12, C(0.20, 0.36, 0.34), 0.05)
        box(xa - 1, xb + 1, y + 1, y + 2, G + 4, G + 5, C(0.36, 0.22, 0.13), 0.04)
        for x in range(xa - 1, xb + 1):
            put(x, y + 1, G + 5, FLW[rng.integers(0, 4)])
        lights.append(((mid + 0.5, y + 5.0, G + 8.0), WARM * 1.35, 21.0))

    def window_x(ya, yb):                                # window in the wall that faces right
        x = x1 - 1
        box(x, x + 1, ya - 1, yb + 1, G + 5, G + 13, FR, 0.03)
        for y in range(ya, yb):
            for z in range(G + 6, G + 12):
                put(x, y, z, WARM * (0.84 + 0.16 * (z - G - 6) / 5), e=True)
        mid = (ya + yb) // 2
        for z in range(G + 6, G + 12):
            put(x, mid, z, MU)
        for y in range(ya, yb):
            put(x, y, G + 9, MU)
        box(x + 1, x + 2, ya - 3, ya - 1, G + 6, G + 12, C(0.20, 0.36, 0.34), 0.05)
        box(x + 1, x + 2, yb + 1, yb + 3, G + 6, G + 12, C(0.20, 0.36, 0.34), 0.05)
        box(x + 1, x + 2, ya - 1, yb + 1, G + 4, G + 5, C(0.36, 0.22, 0.13), 0.04)
        for y in range(ya - 1, yb + 1):
            put(x + 1, y, G + 5, FLW[rng.integers(0, 4)])
        lights.append(((x + 5.0, mid + 0.5, G + 8.0), WARM * 1.35, 21.0))

    window_y(x0 + 5, x0 + 11)
    window_y(x1 - 10, x1 - 4)
    window_x(y0 + 16, y0 + 22)
    # door with a small window, a step and a lamp
    y = y1 - 1
    dx0 = x0 + 15
    box(dx0, dx0 + 8, y, y + 1, G + 2, G + 14, FR, 0.03)
    for x in range(dx0 + 1, dx0 + 7):
        for z in range(G + 2, G + 13):
            put(x, y, z, C(0.56, 0.22, 0.14) * (0.86 + 0.14 * (x % 2)))
    for x in range(dx0 + 2, dx0 + 6):
        for z in (G + 9, G + 10, G + 11):
            put(x, y, z, WARM, e=True)
    put(dx0 + 6, y, G + 7, C(0.95, 0.8, 0.3))
    box(dx0 - 1, dx0 + 9, y + 1, y + 4, G, G + 1, STONE * 1.05, 0.1)
    box(dx0, dx0 + 8, y + 1, y + 2, G + 1, G + 2, STONE * 1.1, 0.1)
    put(dx0 + 9, y + 1, G + 12, C(0.2, 0.15, 0.1))
    put(dx0 + 9, y + 1, G + 11, C(1.0, 0.9, 0.55), e=True)
    lights.append(((dx0 + 9.5, y + 3.5, G + 10.5), WARM * 1.1, 14.0))
    lights.append(((dx0 + 4.0, y + 5.5, G + 7.0), WARM * 0.8, 14.0))
    # woodpile at the right wall
    for yy in range(y0 + 1, y0 + 11):
        for z in range(G, G + 5 - (yy == y0 + 1) - (yy == y0 + 10)):
            for x in (x1, x1 + 1, x1 + 2):
                put(x, yy, z, C(0.45, 0.29, 0.17) * (0.85 + 0.3 * rng.random()))
            put(x1 + 2, yy, z, C(0.80, 0.63, 0.40) * (0.85 + 0.2 * rng.random()))


def build_details():
    # stepping-stone path from the door to the front of the island
    pts = [(46, 59), (46, 64), (47, 69), (49, 74), (52, 78), (56, 82), (61, 85), (66, 88)]
    for (x, y) in pts:
        w = rng.integers(3, 5)
        for dx in range(w):
            for dy in range(3):
                if 0 <= x + dx < N and y + dy < N and solid[x + dx, y + dy, G - 1]:
                    col[x + dx, y + dy, G - 1] = STONE * rng.uniform(0.95, 1.2)
    # lantern post beside the path
    lx, ly = 58, 71
    box(lx, lx + 1, ly, ly + 1, G, G + 9, C(0.25, 0.17, 0.12), 0.05)
    box(lx - 1, lx + 2, ly - 1, ly + 2, G + 12, G + 13, C(0.2, 0.14, 0.1), 0.02)
    box(lx - 1, lx + 2, ly - 1, ly + 2, G + 9, G + 10, C(0.2, 0.14, 0.1), 0.02)
    box(lx, lx + 1, ly, ly + 1, G + 10, G + 12, C(1.0, 0.9, 0.55), 0, e=True)
    put(lx, ly + 1, G + 10, C(1.0, 0.85, 0.45), e=True); put(lx + 1, ly, G + 10, C(1.0, 0.85, 0.45), e=True)
    put(lx, ly + 1, G + 11, C(1.0, 0.85, 0.45), e=True); put(lx + 1, ly, G + 11, C(1.0, 0.85, 0.45), e=True)
    lights.append(((lx + 2.2, ly + 2.2, G + 9.0), WARM * 1.9, 17.0))
    # tree stump with an axe
    box(74, 77, 46, 49, G, G + 3, C(0.40, 0.26, 0.15), 0.08)
    box(74, 77, 46, 49, G + 2, G + 3, C(0.78, 0.62, 0.40), 0.06)
    box(75, 76, 47, 48, G + 3, G + 8, C(0.55, 0.38, 0.22), 0.03)
    box(75, 76, 46, 49, G + 6, G + 8, C(0.70, 0.72, 0.78), 0.03)
    # fence along the right front edge
    for y in range(40, 84, 1):
        x = 87 - max(0, y - 72) * 1
        if not solid[min(x, N - 1), y, G - 1]:
            continue
        if y % 5 == 0:
            box(x, x + 1, y, y + 1, G, G + 5, C(0.50, 0.36, 0.22), 0.06)
        else:
            put(x, y, G + 3, C(0.56, 0.42, 0.26), jit=0.08)
            put(x, y, G + 1, C(0.56, 0.42, 0.26), jit=0.08)
    # flowers, mushrooms, small rocks, tall grass
    for _ in range(420):
        x, y = rng.integers(2, N - 2, 2)
        z = G + int(BUMP[x, y])
        if not solid[x, y, z - 1] or solid[x, y, z] or POND[x, y] < 1.4:
            continue
        if CX0 - 2 <= x < CX1 + 4 and CY0 - 2 <= y < CY1 + 5:
            continue
        k = rng.random()
        if k < 0.50:
            put(x, y, z, C(0.26, 0.58, 0.24) * rng.uniform(0.8, 1.15))
        elif k < 0.66:
            put(x, y, z, [C(0.95, 0.85, 0.35), C(0.95, 0.5, 0.65), C(0.75, 0.6, 0.95), C(0.95, 0.95, 0.9)][rng.integers(0, 4)])
        elif k < 0.74:
            put(x, y, z, C(0.92, 0.9, 0.85)); put(x, y, z + 1, C(0.85, 0.2, 0.2))
        elif k < 0.82:
            put(x, y, z, STONE * rng.uniform(0.8, 1.1))
            if rng.random() < 0.5:
                put(x + 1, y, z, STONE * rng.uniform(0.8, 1.1))
    # reeds at the pond
    for (x, y) in ((11, 64), (12, 66), (13, 62), (28, 74), (29, 72)):
        z = G + int(BUMP[x, y])
        for dz in range(4):
            put(x, y, z + dz, C(0.30, 0.50, 0.22))
        put(x, y, z + 4, C(0.45, 0.28, 0.15)); put(x, y, z + 5, C(0.45, 0.28, 0.15))


# ----------------------------------------------------------------------------
# Lighting and drawing
# ----------------------------------------------------------------------------
def visible(P, target=None, direction=None, maxd=70.0):
    n = len(P)
    vis = np.ones(n, bool)
    if target is not None:
        D = np.asarray(target, F)[None, :] - P
        dist = np.linalg.norm(D, axis=1)
        D = D / (dist[:, None] + 1e-6)
    else:
        D = np.broadcast_to(np.asarray(direction, F), P.shape)
        dist = np.full(n, maxd, F)
    steps = int(min(maxd, dist.max()) / 0.6) + 1
    for s in range(1, steps):
        t = s * 0.6
        q = P + D * t
        qi = np.floor(q).astype(int)
        inb = (qi[:, 0] >= 0) & (qi[:, 0] < N) & (qi[:, 1] >= 0) & (qi[:, 1] < N) & (qi[:, 2] >= 0) & (qi[:, 2] < NZ) & (t < dist - 0.7)
        qi = np.clip(qi, 0, [N - 1, N - 1, NZ - 1])
        vis &= ~(solid[qi[:, 0], qi[:, 1], qi[:, 2]] & inb)
    return vis


def render_voxels():
    pad = np.pad(solid, ((0, 1), (0, 1), (0, 1)))
    ex_top = ~pad[:-1, :-1, 1:]
    ex_x = ~pad[1:, :-1, :-1]
    ex_y = ~pad[:-1, 1:, :-1]
    surf = solid & (ex_top | ex_x | ex_y)
    X, Y, Z = np.nonzero(surf)
    P0 = np.stack([X, Y, Z], 1).astype(F)
    base = col[X, Y, Z]
    em = emis[X, Y, Z]
    occ = ndi.uniform_filter(solid.astype(F), 5, mode='constant')
    moon = np.array([-0.42, 0.50, 0.76], F); moon /= np.linalg.norm(moon)
    amb = C(0.17, 0.23, 0.40)
    moonc = C(0.44, 0.54, 0.80) * 1.2
    faces = [((0, 0, 1), 1.0), ((0, 1, 0), 0.78), ((1, 0, 0), 0.50)]
    out = []
    for nrm, ambk in faces:
        nrm = np.array(nrm, F)
        Pc = P0 + 0.5 + nrm * 0.62
        qi = np.clip(np.floor(P0 + 0.5 + nrm * 2.0).astype(int), 0, [N - 1, N - 1, NZ - 1])
        ao = np.clip(1.25 - 1.5 * occ[qi[:, 0], qi[:, 1], qi[:, 2]], 0.35, 1.0)
        light = amb[None, :] * (ambk * ao)[:, None]
        ndl = float(nrm @ moon)
        if ndl > 0:
            vis = visible(Pc, direction=moon)
            light += moonc[None, :] * (ndl * vis)[:, None]
        for (lp, lc, reach) in lights:
            lp = np.array(lp, F)
            D = lp[None, :] - Pc
            dist = np.linalg.norm(D, axis=1)
            near = dist < reach * 2.2
            if not near.any():
                continue
            k = np.zeros(len(Pc), F)
            nl = np.clip((D[near] @ nrm) / (dist[near] + 1e-6), 0, 1) * 0.8 + 0.2
            v = visible(Pc[near], target=lp, maxd=reach * 2.2)
            k[near] = nl * v / (1 + (dist[near] / (reach * 0.42)) ** 2.2)
            light += k[:, None] * lc[None, :]
        c = base * light
        c = np.where(em[:, None], base * (1.0 if nrm[2] == 0 else 0.9), c)
        out.append(c)
    print('  lighting done (%d cubes) %.1fs' % (len(X), time.time() - T0))

    uc = 2 * (X - Y) + U0
    vc = (X + Y + 1) - 2 * (Z + 1) + V0
    depth = (X + Y + Z).astype(F)
    sprite = [(0, [(-1, -1), (0, -1), (-2, 0), (-1, 0), (0, 0), (1, 0)]),
              (1, [(-2, 1), (-1, 1), (-2, 2), (-1, 2)]),
              (2, [(0, 1), (1, 1), (0, 2), (1, 2)])]
    pix, dep, cc, emm = [], [], [], []
    for fi, offs in sprite:
        for du, dv in offs:
            u = uc + du; v = vc + dv
            ok = (u >= 0) & (u < LW) & (v >= 0) & (v < LH)
            pix.append((v * LW + u)[ok]); dep.append(depth[ok] + 0.1 * (fi == 0)); cc.append(out[fi][ok]); emm.append(em[ok])
    pix = np.concatenate(pix); dep = np.concatenate(dep); cc = np.concatenate(cc); emm = np.concatenate(emm)
    order = np.argsort(dep, kind='stable')
    img = np.zeros((LH * LW, 3), F)
    dbuf = np.full(LH * LW, -1.0, F)
    ebuf = np.zeros(LH * LW, F)
    img[pix[order]] = cc[order]
    dbuf[pix[order]] = dep[order]
    ebuf[pix[order]] = emm[order]
    return img.reshape(LH, LW, 3), dbuf.reshape(LH, LW), ebuf.reshape(LH, LW)


def sky_layer():
    yy, xx = np.mgrid[0:LH, 0:LW].astype(F)
    t = yy / LH
    stops = [(0.0, C(0.030, 0.035, 0.11)), (0.35, C(0.055, 0.075, 0.20)), (0.7, C(0.12, 0.13, 0.30)), (1.0, C(0.22, 0.17, 0.34))]
    sky = np.stack([np.interp(t, [s[0] for s in stops], [s[1][i] for s in stops]) for i in range(3)], -1).astype(F)
    mx, my = 74, 62
    d = np.hypot(xx - mx, yy - my)
    sky += (0.20 * np.exp(-(d / 60) ** 2) + 0.10 * np.exp(-(d / 150) ** 2))[..., None] * C(0.55, 0.65, 1.0)
    # stars
    srng = np.random.default_rng(4)
    for _ in range(330):
        x, y = srng.integers(0, LW), srng.integers(0, int(LH * 0.86))
        b = srng.random() ** 2.2 * (1 - 0.6 * y / LH)
        c = C(0.85, 0.9, 1.0) if srng.random() < 0.75 else C(1.0, 0.85, 0.7)
        sky[y, x] += c * (0.25 + 0.85 * b)
        if b > 0.55 and 1 < x < LW - 2 and 1 < y < LH - 2:
            for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                sky[y + dy, x + dx] += c * 0.3
    # crescent moon
    disc = d < 17.5
    cut = np.hypot(xx - mx - 8.5, yy - my + 4.5) < 15.5
    moon = disc & ~cut
    sky[moon] = C(0.98, 0.95, 0.80)
    sky[disc & cut] += C(0.05, 0.06, 0.10)
    # clouds below the island: three rows of round lumps, lighter on top
    crng = np.random.default_rng(8)
    for lvl, (y0, cc_) in enumerate(((418, C(0.115, 0.125, 0.29)), (446, C(0.155, 0.16, 0.35)), (474, C(0.21, 0.205, 0.42)))):
        top = np.full(LW, 1e9, F)
        x = -20.0
        while x < LW + 20:
            r = crng.uniform(9, 26)
            cy = y0 + crng.uniform(-6, 8) + r * 0.25
            xs = np.arange(LW)
            dx = xs - x
            ins = np.abs(dx) < r
            yt = cy - np.sqrt(np.clip(r * r - dx * dx, 0, None))
            top = np.where(ins, np.minimum(top, yt), top)
            x += r * crng.uniform(0.7, 1.3)
        top = np.minimum(top, y0 + 12)
        mask = yy > top[None, :]
        depth_in = yy - top[None, :]
        shade = np.where(depth_in < 2.5, 1.55, np.where(depth_in < 7, 1.2, 1.0))
        sky = np.where(mask[..., None], cc_[None, None, :] * shade[..., None], sky)
    return sky


def smoke_layer(img, behind):
    """Chimney smoke as round pixel puffs in three tones. `behind` marks pixels where smoke is hidden."""
    yy, xx = np.mgrid[0:LH, 0:LW].astype(F)
    sx = 2 * (CHIM[0] - CHIM[1]) + U0
    sy = (CHIM[0] + CHIM[1]) - 2 * CHIM[2] + V0
    srng = np.random.default_rng(31)
    for i in range(15):
        t = i / 14
        px = sx + 34 * t ** 1.4 + 7 * math.sin(t * 6.5) + srng.uniform(-2, 2)
        py = sy - 3 - 125 * t ** 0.95
        r = 3.0 + 9.5 * t ** 0.7 * (1 - 0.35 * t)
        if t > 0.75:
            r *= (1 - t) * 3.2 + 0.2
        d = np.hypot(xx - px, yy - py)
        m = (d < r) & ~behind
        tone = C(0.40, 0.43, 0.62) * (1 - 0.45 * t) + C(0.10, 0.11, 0.24) * 0.45 * t
        img[m] = tone
        hi = (np.hypot(xx - px + r * 0.3, yy - py + r * 0.3) < r * 0.55) & m
        img[hi] = tone * 1.22
    return img


def kmeans_palette(px, k, r, iters=14):
    samp = px[r.choice(len(px), 60000, replace=False)]
    cent = samp[r.choice(len(samp), k, replace=False)].copy()
    for _ in range(iters):
        d = ((samp[:, None, :] - cent[None, :, :]) ** 2).sum(-1)
        lab = d.argmin(1)
        for j in range(k):
            m = lab == j
            if m.any():
                cent[j] = samp[m].mean(0)
            else:
                cent[j] = samp[r.integers(0, len(samp))]
    return cent


def main():
    global BUMP, POND, MOSS
    MOSS = fbm((N, N), 9, 3, np.random.default_rng(77))
    inside, BUMP, POND = build_island()
    build_cabin()
    for (x, y, h, r_) in [(8, 18, 52, 9), (20, 8, 60, 10), (35, 7, 68, 11), (50, 6, 58, 10), (64, 8, 64, 11),
                          (78, 13, 54, 9), (87, 28, 40, 7), (9, 36, 46, 8), (18, 25, 40, 7), (6, 54, 34, 6),
                          (76, 23, 34, 6), (12, 87, 20, 5)]:
        pine(x, y, h, r_, tint=rng.uniform(0.85, 1.12))
    round_tree(74, 82, 6, C(1.0, 0.50, 0.12))
    round_tree(30, 86, 4, C(1.0, 0.34, 0.16))
    build_details()
    print('world built %.1fs' % (time.time() - T0))
    img, dbuf, ebuf = render_voxels()
    sky = sky_layer()
    mask = dbuf >= 0
    # dark outline where a near object stands in front of a far one
    edge = np.zeros_like(mask)
    for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
        nb = np.roll(dbuf, (dy, dx), (0, 1))
        edge |= mask & (nb - dbuf > 7)
    img[edge & (ebuf < 0.5)] *= 0.62
    pic = np.where(mask[..., None], img, sky)
    pic = smoke_layer(pic, dbuf > CHIM[0] + CHIM[1] + CHIM[2] - 2)
    # warm glow around the lit windows and lamps
    g = ndi.gaussian_filter(ebuf, 3.0) * 0.55 + ndi.gaussian_filter(ebuf, 9.0) * 0.9
    pic = pic + g[..., None] * C(1.0, 0.55, 0.18) * 0.42
    # fireflies
    frng = np.random.default_rng(12)
    fl = np.zeros((LH, LW), F)
    for _ in range(26):
        x = frng.integers(60, LW - 60); y = frng.integers(230, 370)
        fl[y, x] = 1
    pic += ndi.gaussian_filter(fl, 1.6)[..., None] * C(0.8, 1.0, 0.3) * 5.0
    pic[fl > 0] = C(0.95, 1.0, 0.6)
    pic = np.clip(pic, 0, 1) ** (1 / 1.9)
    # 56-colour palette with ordered dithering
    flat = pic.reshape(-1, 3)
    pal = kmeans_palette(flat, 56, np.random.default_rng(1))
    bayer = np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]], F) / 16 - 0.47
    yy, xx = np.mgrid[0:LH, 0:LW]
    dith = (bayer[yy % 4, xx % 4] * np.where(mask, 0.03, 0.05))[..., None]
    q = (pic + dith).reshape(-1, 3)
    lab = np.empty(len(q), int)
    for i in range(0, len(q), 50000):
        lab[i:i + 50000] = ((q[i:i + 50000, None, :] - pal[None]) ** 2).sum(-1).argmin(1)
    small = pal[lab].reshape(LH, LW, 3)
    big = np.repeat(np.repeat(small, PX, 0), PX, 1)
    Image.fromarray((np.clip(big, 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()