The helper functions the shaders share, each with what it does, the episode that introduced it, and the code to copy. Most are a few lines long; the ones that need another function say which.
Noise and randomness
hash21
Turns a 2D point into a pseudo-random number from 0 to 1. The same point always gives the same number, and neighboring points give unrelated ones.
float hash21(float2 p) {
p = fract(p * float2(123.34, 456.21));
p += dot(p, p + 45.32);
returnfract(p.x * p.y);
}
hash11
Turns one number into a pseudo-random number from 0 to 1. The same number always gives the same result, so smoothing between the results at whole numbers gives noise along a line.
A whole number in, a random number from 0 to 1 out. It works on integers, so noise built on it stays exact for minutes of sound, where a float hash would lose precision.
float hashU(uint n) {
n = (n << 13u) ^ n;
n = n * (n * n * 15731u + 789221u) + 1376312589u;
returnfloat(n & 0x7fffffffu) / float(0x7fffffff);
}
hashBitswhole-number hash
Scrambles the bits of a whole number with shifts, XORs and two multiplies, the same on every GPU: a step number, a pattern seed or a sample's number in, 32 random-looking bits out.
float fbm(float2 p) {
float v = 0.0, a = 0.5;
for (int i = 0; i < 5; i++) {
v += a * vnoise(p);
p = p * 2.03 + float2(17.1, 9.2);
a *= 0.5;
}
return v;
}
voronoiVoronoi cells
Voronoi cells around a random point in each grid square. Returns the distance to the nearest edge between two cells, the distance to the nearest point, and a random number for the cell.
float noise1(float t, float rate, uint seed) {
float x = t * rate;
float i = floor(x), f = fract(x);
f = f * f * (3.0 - 2.0 * f);
uint k = uint(i) + seed * 7919u;
returnmix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}
gnoisegradient noise
Gradient noise in 3D, roughly -1 to 1: a random slope at each corner of a grid of cubes (a direction on a sphere, from the corner's hash), blended with a smooth curve. Zero at every corner, so its grid hardly shows; the third coordinate can be time.
A flow from a landscape: its slope, measured with four samples a small step apart, turned a quarter, so the flow follows the contour lines and never gathers anywhere.
float2 curl(float2 x, float t, constantParams& p) {
float2 a = float2(0.002, 0.0), b = float2(0.0, 0.002);
float dx = potential(x + a, t, p) - potential(x - a, t, p);
float dy = potential(x + b, t, p) - potential(x - b, t, p);
returnfloat2(dy, -dx) / 0.004;
}
hash313D hash
Turns a 3D point into a pseudo-random number from 0 to 1, the same for every point in the same whole-numbered cube. It mixes the cube's three whole numbers with integer arithmetic, so neighboring cubes give unrelated numbers.
A random 0 to 1 for each whole-numbered point in space: the three whole numbers become unsigned integers, each multiplied by a large prime, combined with XOR and put through hashU, so neighboring cubes give unrelated numbers and the result is exact however far out.
float hash3(float3 c) {
uint x = uint(int(c.x) + 4096);
uint y = uint(int(c.y) + 4096);
uint z = uint(int(c.z) + 4096);
return hashU(x * 73856093u ^ y * 19349663u ^ z * 83492791u);
}
vnoise33D value noise
Value noise one dimension up: a random value at each corner of a grid of cubes (from hash31), blended smoothly across each cube, eight corners instead of four.
float vnoise3(float3 p) {
float3 i = floor(p), f = fract(p);
f = f * f * (3.0 - 2.0 * f);
float a = hash31(i), b = hash31(i + float3(1, 0, 0));
float c = hash31(i + float3(0, 1, 0)), d = hash31(i + float3(1, 1, 0));
float e = hash31(i + float3(0, 0, 1)), g = hash31(i + float3(1, 0, 1));
float h = hash31(i + float3(0, 1, 1)), k = hash31(i + float3(1, 1, 1));
float lo = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
float hi = mix(mix(e, g, f.x), mix(h, k, f.x), f.y);
returnmix(lo, hi, f.z);
}
valueNoise33D value noise
Value noise in three dimensions from hash3: a random value at every whole-numbered point, blended smoothly across the cube between eight of them. Spinning Planet reads it on the ball so its noise closes without a seam; Black Hole reads it on a cylinder round the disk.
float valueNoise3(float3 x) {
float3 i = floor(x);
float3 f = x - i;
f = f * f * (3.0 - 2.0 * f);
float a = mix(hash3(i), hash3(i + float3(1, 0, 0)), f.x);
float b = mix(hash3(i + float3(0, 1, 0)), hash3(i + float3(1, 1, 0)), f.x);
float c = mix(hash3(i + float3(0, 0, 1)), hash3(i + float3(1, 0, 1)), f.x);
float d = mix(hash3(i + float3(0, 1, 1)), hash3(i + float3(1, 1, 1)), f.x);
returnmix(mix(a, b, f.y), mix(c, d, f.y), f.z);
}
fbm33D fractal noise
Octaves of 3D value noise, each about twice as fine and half as strong as the one before, around 0.5 on average. Smoke Stack's takes the number of octaves, so a light march can get by with fewer.
float fbm3(float3 p) {
float v = 0.0, a = 0.5;
for (int i = 0; i < 5; i++) {
v += a * vnoise3(p);
p = p * 2.02 + float3(17.1, 9.2, 4.7);
a *= 0.5;
}
return v;
}
wrapwrap into a period
x wrapped into 0 to m, below 0 as well as above (x minus m times floor(x / m)). Wrapping a lattice point's number before hashing it makes noise repeat every m cells.
float sdBox(float2 p, float2 b) {
float2 d = abs(p) - b;
returnlength(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
}
segmentsegment distance
The distance from a point (the first argument) to the line segment between the other two: projected onto the segment, clamped to its ends, and measured from there.
float segment(float2 p, float2 a, float2 b) {
float2 pa = p - a, ba = b - a;
returnlength(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}
lineAtline from a distance
Turns a distance into ink: 1 on the shape, falling smoothly to 0 by w away (one minus a smoothstep), so a distance function becomes a line or a solid shape with an antialiased edge a pixel or two wide.
The smooth minimum. Like min, but when two distances are within k of each other it pulls the result below both, so two shapes melt into one with a smooth neck between them.
float2 rot(float2 p, float a) {
float c = cos(a), s = sin(a);
returnfloat2(c * p.x - s * p.y, s * p.x + c * p.y);
}
kaleidokaleidoscope fold
Folds the plane into n slices around the center, each mirrored down its middle, so whatever is drawn in one half-slice appears in all of them. spin turns the folds and twist turns them more the further out they are.
float2 kaleido(float2 q, float n, float spin, float twist) {
float r = length(q);
float a = atan2(q.y, q.x) + spin + twist * r;
float slice = TAU / n;
// Angular repetition: every slice lands on the first.
a -= slice * floor(a / slice);
// Mirror fold: the two halves of a slice reflect each other.
a = abs(a - slice * 0.5);
return r * float2(cos(a), sin(a));
}
travelcamera travel
How far along its path the camera has flown at time t: the time times a fixed speed. Everything else about the camera (where it is, where it looks, how it leans) is worked out from that distance.
How fast something goes round at a distance from the center, in radians a second, so an angle can be turned by rate × time. Each episode has its own law: Spiral Galaxy's is a rotation curve that rises through the core and then holds, so outer stars lag; Black Hole's is Kepler's, falling as r to the three halves, so the inner gas shears past the outer.
float orbitRate(float a, constantParams& p) {
float v = 0.11 * a / sqrt(a * a + CORE * CORE);
return p.speed * v / max(a, 0.01);
}
viewOfthe particles' view
Where a point of a particle episode's own space is on the picture, one unit the half height, with no perspective: turned about the scene's axis with rot (the pointer turns it too) and leaned toward the eye. Spiral Galaxy takes a place in the disk and a height out of it; Lorenz Attractor a point of Lorenz's three numbers, with z up.
float2 viewOf(float2 position, float height,
constantUniforms& u, constantParams& p) {
float2 v = viewAngles(u, p);
float2 r = rot(position, v.x);
returnfloat2(r.x, r.y * cos(v.y) + height * sin(v.y));
}
zoomOffit to the picture
How large the subject is drawn: its usual size, or smaller, 0.95 of the picture's width over its height, in a picture taller than wide, so it fits a phone held upright.
The direction a surface faces at a point: how the scene's distance changes for a small step along each axis. Its arguments are whatever the episode's map takes.
Marches from a surface point towards the light. The nearer the ray passes to something, compared with how far it has gone, the darker the shadow, so its edge fades over a band; w sets how wide.
float softShadow(float3 ro, float3 rd, float w,
float t, int n, float rise, float k) {
float res = 1.0;
float s = 0.02;
for (int i = 0; i < 48; i++) {
float h = map(ro + rd * s, t, n, rise, k);
res = min(res, h / (w * s));
if (res < 0.001 || s > 6.0) break;
s += clamp(h, 0.01, 0.3);
}
res = clamp(res, 0.0, 1.0);
return res * res * (3.0 - 2.0 * res);
}
ambientOcclusionambient occlusion
Takes a few short steps out along the normal. Where the scene is nearer than the step, something blocks light from that side, so creases and corners come out darker.
float ambientOcclusion(float3 pos, float3 nrm,
float t, int n, float rise, float k) {
float occ = 0.0;
float weight = 1.0;
for (int i = 0; i < 5; i++) {
float h = 0.02 + 0.12 * float(i);
occ += (h - map(pos + nrm * h, t, n, rise, k)) * weight;
weight *= 0.8;
}
returnclamp(1.0 - 2.0 * occ, 0.0, 1.0);
}
fresnelFresnel
Schlick's Fresnel: how much of the light a surface mirrors at an angle. f0 is the share mirrored head on, worked out from the index of refraction, and toward a grazing angle the share climbs to all of it by (1 - cos)⁵.
Where the kiln's light comes from, as a unit direction: high and to one side. Pottery Wheel's goes round with the camera, so the subject is always lit from the viewer's side.
What a ray sees that meets nothing: the dark of the kiln, a little warmer toward the horizon, and glowing where it points toward the light, its hot mouth.
The brightness of the kiln's floor at a point: tiles of fired clay, each a slightly different shade from a hash of its number, with dark grout between them, and the shadow of whatever stands on it cast along the light.
float floorLevel(float3 p, float3 l, float glow) {
float2 g = p.xz * 1.6;
float2 f = abs(fract(g) - 0.5);
float grout = smoothstep(0.47, 0.44, max(f.x, f.y));
float2 id = floor(g);
float tone = 0.28 + 0.08 * fract(sin(dot(id, float2(12.9, 78.2))) * 437.5);
// The orb's shadow, cast along the light onto the floor.float3 toOrb = -p;
float along = dot(toOrb, l);
float miss = length(toOrb - l * along);
float shadow = along > 0.0 ? smoothstep(0.55, 1.15, miss) : 1.0;
// The caustic: the orb works as a lens, so the light it bends gathers in// a spot inside the shadow.float focus = exp(-miss * miss * 18.0) * step(0.0, along);
float level = tone * grout * (0.35 + 0.65 * shadow) + 0.9 * focus;
// The ember's own glow reaches the floor nearby.
level += glow * 0.35 * exp(-length(p.xz) * 1.5);
return level;
}
envthe room
Everything a free ray sees of the room: the floor if it points down, found without marching since the floor is flat, fading into the kiln's haze with distance; otherwise the kiln's dark. Reflections ask it what they see.
float env(float3 ro, float3 rd, float t, float glow) {
float3 l = lightDir(t);
float back = sky(rd, l);
if (rd.y < -0.001) {
float d = (FLOOR - ro.y) / rd.y;
float3 p = ro + rd * d;
if (d > 0.0) returnmix(back, floorLevel(p, l, glow), exp(-d * 0.12));
}
return back;
}
kilnSkykiln sky
The sky in a direction, for water to mirror: gold at the horizon fading to near-black overhead, with the kiln's glow low ahead and a haze around it, all through the kiln palette; heat slides it hotter or cooler.
The night sky in a direction: dark blue overhead and paler toward the horizon. Smoke Stack's adds a warm haze low down, stars and a moon with a glow round it; Lighthouse's is the two blues alone, with its stars in a function of their own, so the sea can mirror the sky without them.
float3 nightSky(float3 rd, float t) {
float up = clamp(rd.y, 0.0, 1.0);
float3 col = mix(float3(0.10, 0.045, 0.040), float3(0.012, 0.016, 0.040),
smoothstep(-0.05, 0.45, rd.y));
float2 a = float2(atan2(rd.x, rd.z), rd.y) * 90.0;
float star = hash31(float3(floor(a), 1.0));
float2 at = fract(a) - 0.5;
col += step(0.985, star) * up * smoothstep(0.12, 0.0, length(at)) * 0.7
* (0.75 + 0.25 * sin(t * 3.0 + star * 60.0));
float m = dot(rd, MOON);
col += MOONLIGHT * smoothstep(0.9993, 0.9995, m) * 1.4;
m = max(m, 0.0);
col += MOONLIGHT * (pow(m, 300.0) * 0.25 + pow(m, 12.0) * 0.05);
return col;
}
mirrorFresnel mirror
How much water mirrors, by Schlick's Fresnel: 2% seen from straight above, rising to nearly all of it edge-on. It takes how squarely the eye faces the surface, from 0 to 1.
The share of each color a pane of stained glass lets through, by Beer-Lambert: the glass's color raised to its thickness, which wanders with noise, and nothing where the lead is.
A SwiftUI layer seen through rough glass at one point: the average of sixteen samples on a spiral around it, each the golden angle on from the last, out to a radius in points; the last argument turns the spiral.
half4 through(SwiftUI::Layer layer, float2 at, float radius, float turn) {
half4 sum = half4(0.0h);
for (int i = 0; i < 16; i++) {
float r = radius * sqrt((float(i) + 0.5) / 16.0);
float a = float(i) * 2.39996 + turn;
sum += layer.sample(at + r * float2(cos(a), sin(a)));
}
return sum / 16.0h;
}
Vertex cameras
cameraAxesthe camera's axes
The camera's three directions as the columns of a matrix: forward from the eye to the point it looks at, right across it (crossed with straight up), and up as the cross of those two. The background turns each pixel's ray with the same three.
A point in the world as a vertex episode's host wants it: measured along the camera's three axes from the eye, x and y scaled by the zoom (x also by the aspect), the depth from near to far mapped to 0 to 1 for the depth test, and the depth itself as w, which the host divides by so far things come out smaller.
Where the eye is: a fixed distance from what it looks at, moved round it left and right and up and down by where the pointer is in the picture. The middle of the picture, or no pointer, is the episode's own view from the front.
float voice(float ph, float bright) {
constfloat tau = 6.2831853;
returnsin(tau * ph) + bright * (0.45 * sin(2.0 * tau * ph) + 0.25 * sin(3.0 * tau * ph) + 0.12 * sin(4.0 * tau * ph));
}
morphWavea morphing wave
One wave blending a sine, a square and a triangle, by the three weights in w. The square and triangle are built from their first four odd harmonics, so they stay soft.
Thunder after a lightning strike: low noise from noise1 that swells in and rolls away over a few seconds. x is the time since the strike (Rain on Glass) or since its sound arrived (Lightning, where a near strike cracks first and a far one rumbles lower and longer).
A struck bell: a tone and two partials at 2.76 and 5.4 times its pitch, which are not whole multiples of it, the higher ones dying away sooner. since is the time since it was struck.