ExperimentsFable 5.2 Python art (30 images)
Image 12 of 30
Reaction-diffusion coral
The Python script
Open script.py ↗ (opens in a new tab)#!/usr/bin/env python3
"""12 Reaction-diffusion coral.
A Gray-Scott simulation: two virtual chemicals U and V spread and react on a
grid. The "feed" and "kill" rates and the diffusion speed change slowly across
the picture, so one run grows brain-coral mazes, spots and worm shapes of
different sizes. The amount of V is then treated as a height map and lit like a
wet coral surface under water.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/12-reaction-diffusion-coral.py
"""
import os, time
import numpy as np
from PIL import Image
from scipy import ndimage as ndi
W, H = 1600, 2000
MARGIN = 16 # extra cells on each side, cropped away (hides the wrap seam)
GW, GH = 640 + 2 * MARGIN, 800 + 2 * MARGIN # simulation grid, enlarged 2.5x for the picture
STEPS = 14000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '12-reaction-diffusion-coral.png')
F32 = np.float32
rng = np.random.default_rng(1212)
def smooth_noise(shape, sigma, mode='reflect'):
n = ndi.gaussian_filter(rng.standard_normal(shape).astype(F32), sigma, mode=mode)
n -= n.mean()
return n / n.std()
def smoothstep(a, b, x):
t = np.clip((x - a) / (b - a), 0, 1)
return t * t * (3 - 2 * t)
# ----------------------------------------------------------------------------
# 1. Parameter maps
# ----------------------------------------------------------------------------
gy, gx = np.mgrid[0:GH, 0:GW].astype(F32)
u = gx / GW; v = gy / GH
n1 = smooth_noise((GH, GW), 95)
n2 = smooth_noise((GH, GW), 70)
# t = 0: labyrinth (brain coral), t = 1: dividing spots.
t = smoothstep(-0.9, 1.1, n1 + 0.9 * (np.hypot(u - 0.42, v - 0.45) - 0.42) * 2.2)
feed = 0.0550 + (0.0340 - 0.0550) * t
kill = 0.0622 + (0.0640 - 0.0622) * t
# A second axis pushes some regions toward the "holes" regime.
t2 = smoothstep(0.5, 1.6, n2) * (1 - t)
feed = feed + (0.0400 - 0.0550) * t2
kill = kill + (0.0590 - 0.0622) * t2
# Diffusion scale: large features near the focus, fine ones far away.
focus = np.exp(-((u - 0.42) ** 2 + ((v - 0.45) * 1.25) ** 2) / (2 * 0.30 ** 2))
dscale = np.clip(0.36 + 0.64 * focus + 0.10 * smooth_noise((GH, GW), 60), 0.30, 1.0).astype(F32)
DU = (1.0 * dscale).astype(F32)
DV = (0.5 * dscale).astype(F32)
feed = feed.astype(F32); kill = kill.astype(F32)
fk = (feed + kill).astype(F32)
# ----------------------------------------------------------------------------
# 2. Gray-Scott simulation
# ----------------------------------------------------------------------------
U = np.ones((GH, GW), F32)
V = np.zeros((GH, GW), F32)
# Seed: many small random patches of V.
seed = rng.random((GH, GW)) < 0.0035
seed = ndi.binary_dilation(seed, iterations=3)
V[seed] = 0.5; U[seed] = 0.25
V += 0.02 * rng.random((GH, GW)).astype(F32) * seed
def lap(A, P):
"""9-point Laplacian with wrap-around edges. P is a scratch array (GH+2, GW+2)."""
P[1:-1, 1:-1] = A
P[0, 1:-1] = A[-1]; P[-1, 1:-1] = A[0]
P[:, 0] = P[:, -2]; P[:, -1] = P[:, 1]
L = 0.2 * (P[:-2, 1:-1] + P[2:, 1:-1] + P[1:-1, :-2] + P[1:-1, 2:])
L += 0.05 * (P[:-2, :-2] + P[:-2, 2:] + P[2:, :-2] + P[2:, 2:])
L -= A
return L
P = np.empty((GH + 2, GW + 2), F32)
for i in range(STEPS):
LU = lap(U, P)
LV = lap(V, P)
uvv = U * V * V
U += DU * LU - uvv + feed * (1 - U)
V += DV * LV + uvv - fk * V
print('simulation done %.1fs' % (time.time() - T0))
# ----------------------------------------------------------------------------
# 3. Render the V field as a lit, wet coral surface
# ----------------------------------------------------------------------------
Vn = np.clip(V / 0.36, 0, 1.2)
# Enlarge with cubic interpolation, then crop the margin.
ZOOM = W / (GW - 2 * MARGIN)
big = ndi.zoom(Vn, ZOOM, order=3)
o = int(MARGIN * ZOOM)
h = big[o:o + H, o:o + W]
plate = smoothstep(0.10, 0.80, ndi.gaussian_filter(h, 1.2)) # ridge footprint
# Rounded ridges: blur the footprint so the height peaks along the centre line.
dome = ndi.gaussian_filter(plate, 5.0)
dome = dome / (ndi.gaussian_filter(dome, 40) * 0.9 + 0.35)
h = np.clip(0.30 * plate + 0.70 * plate * np.clip(dome, 0, 1.3) / 1.1, 0, 1)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)
uu = xx / W; vv = yy / H
# Surface normal from the height map.
RELIEF = 26.0
hy, hx = np.gradient(h * RELIEF)
nz = 1.0 / np.sqrt(hx * hx + hy * hy + 1)
nx = -hx * nz; ny = -hy * nz
# Ambient occlusion: valleys between ridges are darker.
wide = ndi.gaussian_filter(h, 14)
ao = np.clip(0.55 + 0.9 * (h - wide) + 0.45 * h, 0.0, 1.0)
def ramp(t, stops):
pos = [p for p, _ in stops]
cols = np.array([[int(c[i:i + 2], 16) / 255 for i in (1, 3, 5)] for _, c in stops], F32)
return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F32)
# Lighting comes first, because the palettes use it: ridges are pale on the lit
# side and deep red (or deep teal, or violet) on the shaded side.
L = np.array([-0.50, -0.62, 0.60], F32); L /= np.linalg.norm(L)
diff = np.clip(nx * L[0] + ny * L[1] + nz * L[2], 0, 1)
hc = h * (0.42 + 0.62 * diff)
pal_a = ramp(hc, [(0.0, '#071a26'), (0.12, '#2b1034'), (0.32, '#8e1846'), (0.58, '#e23b4e'),
(0.82, '#ff7a4a'), (1.0, '#ffb07a')])
pal_b = ramp(hc, [(0.0, '#061c22'), (0.12, '#0a3038'), (0.32, '#0c6a6a'), (0.58, '#1fae95'),
(0.82, '#7fdc9c'), (1.0, '#d9f5a4')])
pal_c = ramp(hc, [(0.0, '#0a1430'), (0.12, '#231650'), (0.32, '#5a2a9c'), (0.58, '#b043b8'),
(0.82, '#f070a8'), (1.0, '#ffb0b8')])
m1 = ndi.zoom(smooth_noise((50, 40), 5.5), 40, order=3)[:H, :W]
m2 = ndi.zoom(smooth_noise((50, 40), 5.5), 40, order=3)[:H, :W]
wb = smoothstep(0.55, 1.35, m1)[..., None]
wc = smoothstep(0.45, 1.25, m2)[..., None] * (1 - wb)
base = pal_a * (1 - wb - wc) + pal_b * wb + pal_c * wc
# Lighting: soft key light from the upper left, cool fill, wet highlights.
Hh = L + np.array([0, 0, 1], F32); Hh /= np.linalg.norm(Hh)
spec = np.clip(nx * Hh[0] + ny * Hh[1] + nz * Hh[2], 0, 1) ** 70
fill = np.clip(-nx * 0.5 + ny * 0.6 + nz * 0.3, 0, 1)
img = base * (0.42 + 0.95 * diff)[..., None] * ao[..., None]
img += base * np.array([0.25, 0.45, 0.70], F32) * (0.30 * fill * ao)[..., None]
img += np.array([1.0, 0.95, 0.88], F32) * (spec * 0.50 * smoothstep(0.3, 0.8, h))[..., None]
# Water: caustic light ripples over everything, deeper and bluer toward the edges.
c1 = smooth_noise((H, W), 26); c2 = smooth_noise((H, W), 11)
caus = np.clip(1 - np.abs(c1 + 0.5 * c2) * 1.3, 0, 1) ** 3
img *= (0.90 + 0.30 * caus)[..., None]
# The sea floor between the ridges: dark teal, lit by the same ripples.
floor = (1 - plate) * (0.16 + 0.55 * caus) * (0.6 + 0.4 * ndi.gaussian_filter(plate, 20))
img += floor[..., None] * np.array([0.05, 0.36, 0.42], F32)
depth = np.clip(np.hypot((uu - 0.42) / 0.80, (vv - 0.45) / 0.80), 0, 1.2) ** 2
img = img * (1 - 0.55 * depth)[..., None] + np.array([0.01, 0.07, 0.11], F32) * (0.45 * depth)[..., None]
# Soft glow from the brightest ridges.
lum = img.mean(-1)
glow = ndi.gaussian_filter(np.clip(lum - 0.5, 0, 1), 12)
img += glow[..., None] * np.array([1.0, 0.7, 0.55], F32) * 0.25
img = np.clip(img, 0, None)
img = img / (1 + 0.12 * img) # gentle highlight roll-off
img = np.clip(img * 1.10, 0, 1) ** 0.95
img += rng.standard_normal((H, W, 1)).astype(F32) * 0.006
Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))

