# Rain & puddles

> A rainy night on wet cobbles: puddles shaped by the ground, with raindrop rings and lamp glints drawn in one 3D material.

Example `rain`, running at https://nacatamalon.com/en/examples/rain. The whole catalogue: https://nacatamalon.com/llms/examples.md.

A rainy night on wet cobbles. WASD or the arrows roll the ball, and space jumps. Puddles lie in the dips of the ground, raindrops ring every one, the street lamps shine in them broken up by the ripples, the ball leaves rings as it rolls through and splashes when it lands, and now and then lightning flashes. Left alone, the ball drives itself. V, or the button at the top right, shows what moves the water: red its depth, green the ball's rings, blue the raindrops'.

The water is a single plane at a fixed height: where the ground is higher, the engine's own depth test hides it, so the puddles take the shape of the ground with no edge drawn by hand. The ground's height also goes into a picture, read as a `maps` entry, so the water knows how deep it is and fades out at the shore. Nothing is simulated: the raindrops' rings and the ball's last five are drawn in one `mesh3d` material, written for both cards, which reflects the sky and each lamp through them. The lightning lights the sky with `setBackground`, the fog, the lights and what the puddles reflect.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Rain } from './scenes/rain';
import { ACTIONS, HEIGHT, NIGHT, WIDTH } from './settings';

// A rainy night on wet cobbles: puddles that form in the dips of the ground, raindrop rings on every
// puddle, street lamps reflected and broken up by the ripples, a ball that leaves rings through the
// water and splashes when it lands, and lightning now and then.
//
//   WASD / arrows   move
//   space           jump
//   V               switch views: the rain, what moves the water (or the button)
//
// Left alone, the ball drives itself.
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: NIGHT,
    scaling: 'contain',
    step: 60,
    actions: ACTIONS
});

// Declare Scenes
game({
    Rain
});
```

`art/textures.ts`:

```ts
import { createPixels, createPixelTexture, setPixel } from 'nacatamalon/pixels';

/**
 * A white picture painted from how opaque each point is, by where it is from the middle (-1 to 1
 * across and down).
 */
export const paintShape = (size: number, alphaAt: (dx: number, dy: number) => number) => {
    const pixels = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const dx = (x + 0.5 - size / 2) / (size / 2);
            const dy = (y + 0.5 - size / 2) / (size / 2);
            const alpha = Math.max(0, Math.min(1, alphaAt(dx, dy)));

            setPixel(pixels, x, y, `rgba(255, 255, 255, ${alpha.toFixed(3)})`);
        }
    }

    return createPixelTexture(pixels);
};

/**
 * Cobbles: uneven stones (each pixel takes the colour of the nearest stone) and dark joints where two
 * stones are almost as near. It tiles: the stones near each edge are also looked for across it.
 */
export const paintCobbles = () => {
    const size = 128;
    const stones = 7;
    const points: [number, number, number][] = [];
    let seed = 99;

    const random = () => {
        seed = (seed * 16807) % 2147483647;

        return seed / 2147483647;
    };

    for (let y = 0; y < stones; y++) {
        for (let x = 0; x < stones; x++) {
            points.push([(x + 0.2 + random() * 0.6) / stones, (y + 0.2 + random() * 0.6) / stones, random()]);
        }
    }

    const pixels = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const u = x / size;
            const v = y / size;
            let best = 9;
            let second = 9;
            let tone = 0;

            for (const [px, py, t] of points) {
                for (let oy = -1; oy <= 1; oy++) {
                    for (let ox = -1; ox <= 1; ox++) {
                        const d = Math.hypot(u - px - ox, v - py - oy);

                        if (d < best) {
                            second = best;
                            best = d;
                            tone = t;
                        } else if (d < second) {
                            second = d;
                        }
                    }
                }
            }

            const joint = Math.min(1, (second - best) * stones * 4);
            const grain = 0.9 + random() * 0.1;
            const k = (0.45 + tone * 0.3) * grain * (0.35 + 0.65 * joint);

            setPixel(pixels, x, y, `rgb(${Math.round(118 * k)}, ${Math.round(120 * k)}, ${Math.round(128 * k)})`);
        }
    }

    return createPixelTexture(pixels);
};
```

`components/ball.ts`:

```ts
import { createMesh, useAction, useDirection, useIcoSphereGeometry, useUpdate } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { heightAt } from '../geometry/terrain';
import { BALL, IDLE_SECONDS, LAMPS, RIPPLES, STREET, WATER_LEVEL } from '../settings';
import type { TDownpour } from './downpour';
import type { TWater } from './water';

/**
 * How far the ball may go from the middle, either way.
 */
const LIMIT = STREET.play / 2 - BALL.edge;

/**
 * The yellow ball. It rolls over the cobbles and through the puddles (slower in the water), leaves
 * faint rings as it rolls through one, and splashes when it lands in one. Left alone it goes from
 * puddle to puddle by itself.
 */
export const Ball = ({ water, downpour }: { water: TWater; downpour: TDownpour; }) => {
    const mesh = createMesh({
        geometry: useIcoSphereGeometry({
            radius: BALL.radius,
            subdivisions: 3
        }),
        tint: '#f2c230',
        specular: '#ffffff',
        shininess: 60,
        castShadow: true,
        transform: {
            x: BALL.start.x,
            y: 1,
            z: BALL.start.z
        }
    });

    const move = useDirection('left', 'right', 'up', 'down');
    const jump = useAction('jump');
    const random = useRandom();

    const velocity = {
        x: 0,
        y: 0,
        z: 0
    };

    // Where it left its last ring.
    const lastRing = {
        x: Infinity,
        z: Infinity
    };

    let idleFor = IDLE_SECONDS;
    let autoTime = 0;
    let autoJump = 4;
    let grounded = false;

    useUpdate((delta) => {
        const at = mesh.transform;

        // Up on the stick or the keys goes away from the camera, along -z.
        let { x: ix, y: iz } = move();
        let jumping = jump.justPressed();

        idleFor = ix !== 0 || iz !== 0 || jumping ? 0 : idleFor + delta;

        if (idleFor > IDLE_SECONDS) {
            autoTime += delta * 0.3;
            ix = Math.sin(autoTime * 1.1) * 5 - at.x;
            iz = Math.sin(autoTime * 1.7 + 0.5) * 4 - at.z;
            autoJump -= delta;

            if (autoJump <= 0) {
                jumping = true;
                autoJump = random.rand(5, 8);
            }
        }

        const length = Math.hypot(ix, iz);

        if (length > 1) {
            ix /= length;
            iz /= length;
        }

        velocity.x += ix * BALL.accel * delta;
        velocity.z += iz * BALL.accel * delta;

        // The water slows it more than the cobbles.
        const wet = water.isWet(at.x, at.z);
        const steering = ix !== 0 || iz !== 0;
        const drag = Math.exp(-((steering ? BALL.drag : BALL.stopDrag) + (wet ? BALL.waterDrag : 0)) * delta);

        velocity.x *= drag;
        velocity.z *= drag;

        if (jumping && grounded) {
            velocity.y = BALL.jump;
            grounded = false;
        }

        velocity.y -= BALL.gravity * delta;
        at.x += velocity.x * delta;
        at.y += velocity.y * delta;
        at.z += velocity.z * delta;

        // The edges, and the lamp posts.
        at.x = Math.min(Math.max(at.x, -LIMIT), LIMIT);
        at.z = Math.min(Math.max(at.z, -LIMIT), LIMIT);

        for (const [lx, lz] of LAMPS) {
            const dx = at.x - lx;
            const dz = at.z - lz;
            const d = Math.hypot(dx, dz);
            const min = BALL.radius + 0.1;

            if (d < min && d > 0.0001) {
                at.x = lx + (dx / d) * min;
                at.z = lz + (dz / d) * min;
            }
        }

        // It rolls on the ground (under the water, in the puddles).
        const floor = heightAt(at.x, at.z) + BALL.radius;
        let impact = 0;

        if (at.y <= floor) {
            impact = grounded ? 0 : -velocity.y;
            at.y = floor;
            velocity.y = 0;
            grounded = true;
        }

        const speed = Math.hypot(velocity.x, velocity.z);

        // Landing in a puddle: a strong ring, and a weaker one a moment later. On the cobbles, a few
        // drops.
        if (impact > RIPPLES.landing) {
            if (wet) {
                water.ring(at.x, at.z, Math.min(1, impact / 8));
                water.ring(at.x, at.z, Math.min(0.6, impact / 14), 0.18);
                downpour.splash(at.x, WATER_LEVEL + 0.05, at.z, Math.min(140, Math.round(impact * 16)));
            } else {
                downpour.splash(at.x, at.y - BALL.radius + 0.05, at.z, Math.min(30, Math.round(impact * 3)));
            }
        }

        // Rolling through the water: a faint ring every little way, and spray in front.
        if (wet && grounded && speed > 0.3 && Math.hypot(at.x - lastRing.x, at.z - lastRing.z) > RIPPLES.spacing) {
            water.ring(at.x, at.z, Math.min(0.45, speed * 0.12));
            lastRing.x = at.x;
            lastRing.z = at.z;
        }

        if (wet && grounded && speed > 1) {
            downpour.splash(at.x + (velocity.x / speed) * BALL.radius, WATER_LEVEL + 0.03, at.z + (velocity.z / speed) * BALL.radius, Math.min(5, Math.round(speed)));
        }
    });

    return {
        mesh
    };
};
```

`components/downpour.ts`:

```ts
import { createParticles3d, emitParticles } from 'nacatamalon';
import { paintShape } from '../art/textures';

/**
 * The rain: thin streaks falling at a slant over what the camera sees, tiny drops bouncing all over
 * the ground, and the spray the ball throws up.
 */
export const Downpour = () => {
    const streak = paintShape(32, (dx, dy) => Math.max(0, 1 - Math.abs(dx) * 14) * (1 - Math.abs(dy)) * 0.9);
    const droplet = paintShape(8, (dx, dy) => 1 - Math.hypot(dx, dy));

    const rain = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: streak,
            worldSpace: true,
            max: 2200,
            emission: {
                rate: 1700
            },
            shape: {
                kind: 'box',
                size: [20, 0.5, 14]
            },
            direction: {
                x: 0.12,
                y: -1,
                z: 0.05
            },
            spread: 0.03,
            speed: [11, 13],
            life: [0.75, 0.85],
            size: [0.3, 0.42],
            colorOverLife: [
                {
                    t: 0,
                    color: '#aabbd8',
                    alpha: 0.45
                },
                {
                    t: 1,
                    color: '#aabbd8',
                    alpha: 0.45
                }
            ]
        },
        transform: {
            x: 0,
            y: 9,
            z: 0
        }
    });

    const bounces = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: droplet,
            worldSpace: true,
            max: 400,
            emission: {
                rate: 420
            },
            shape: {
                kind: 'box',
                size: [16, 0.05, 16]
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 0.9,
            speed: [0.6, 1.4],
            gravity: {
                y: -12
            },
            life: [0.1, 0.2],
            size: [0.03, 0.06],
            colorOverLife: [
                {
                    t: 0,
                    color: '#dfe8ff',
                    alpha: 0.8
                },
                {
                    t: 1,
                    color: '#dfe8ff',
                    alpha: 0
                }
            ]
        },
        transform: {
            x: 0,
            y: 0.05,
            z: 0
        }
    });

    const spray = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: droplet,
            worldSpace: true,
            max: 500,
            emission: {
                rate: 0,
                burst: 0
            },
            shape: {
                kind: 'sphere',
                radius: 0.3,
                edge: true
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 1.1,
            speed: [1.5, 4],
            gravity: {
                y: -12
            },
            life: [0.35, 0.8],
            size: [0.05, 0.1],
            colorOverLife: [
                {
                    t: 0,
                    color: '#e6eeff',
                    alpha: 0.9
                },
                {
                    t: 1,
                    color: '#b0c0e0',
                    alpha: 0
                }
            ]
        }
    });

    return {
        /**
         * Throws up `count` drops at a place in the world.
         */
        splash: (x: number, y: number, z: number, count: number) => {
            spray.transform.x = x;
            spray.transform.y = y;
            spray.transform.z = z;
            emitParticles(spray, count);
        },
        /**
         * Keeps the rain falling over what the camera, looking at (x, z), sees.
         */
        follow: (x: number, z: number) => {
            rain.transform.x = x;
            // It ends a few metres short of the camera: a drop right on the lens is seen as a band.
            rain.transform.z = z - 3.5;
            bounces.transform.x = x;
            bounces.transform.z = z - 1;
        }
    };
};

export type TDownpour = ReturnType<typeof Downpour>;
```

`components/sky.ts`:

```ts
import { getColor, lerpColor, useAmbientLight, useDirectionalLight, useFog, useGame, useUpdate } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { FLASH, LIGHTNING, NIGHT } from '../settings';
import type { TWater } from './water';

/**
 * The night: its fog, its dim light and the moon, and the lightning, a double flash every few seconds
 * that lights up the sky, the fog, the street and what the puddles reflect for a moment.
 */
export const Sky = ({ water }: { water: TWater; }) => {
    const game = useGame();
    const random = useRandom();

    const fog = useFog({
        color: NIGHT,
        near: 8,
        far: 22
    });

    const ambient = useAmbientLight({
        color: '#5a6c96',
        intensity: 0.35
    });

    const moon = useDirectionalLight({
        color: '#9fb2e0',
        intensity: 0.25,
        transform: {
            rotationX: -0.9,
            rotationY: 0.4
        }
    });

    const night = getColor(NIGHT);
    const flashColor = getColor(FLASH);

    let flash = 0;
    let nextFlash = LIGHTNING.first;
    let second = -1;

    useUpdate((delta) => {
        nextFlash -= delta;

        if (nextFlash <= 0) {
            flash = 1;
            second = 0.12;
            nextFlash = random.rand(LIGHTNING.every[0], LIGHTNING.every[1]);
        }

        if (second > 0) {
            second -= delta;

            if (second <= 0) {
                flash = Math.max(flash, 0.8);
            }
        }

        flash = Math.max(0, flash - delta * 3.5);

        const sky = lerpColor(night, flashColor, flash * 0.6);

        game.setBackground(sky);
        fog.color = sky;
        ambient.intensity = 0.35 + flash * 1.6;
        moon.intensity = 0.25 + flash * 1.2;
        water.lightning(flash);
    });
};
```

`components/street.ts`:

```ts
import { createMaterial, createMesh, useCylinderGeometry, useIcoSphereGeometry, usePointLight } from 'nacatamalon';
import { paintCobbles } from '../art/textures';
import { heightAt } from '../geometry/terrain';
import { GROUND_GLSL, GROUND_WGSL } from '../shaders/ground';
import { LAMPS } from '../settings';
import type { TTerrain } from './water';

/**
 * The street: the wet cobbles, and the lamps, each a post, a glowing lantern and its light.
 */
export const Street = ({ terrain }: { terrain: TTerrain; }) => {
    createMesh({
        geometry: terrain.geometry,
        material: createMaterial({
            shader: 'mesh3d',
            name: 'wet cobbles',
            texture: paintCobbles(),
            specular: '#ffffff',
            shininess: 45,
            fragment: GROUND_WGSL,
            fragmentGlsl: GROUND_GLSL,
            uniforms: {
                wet: [0.6, 0, 0, 0]
            }
        })
    });

    const post = useCylinderGeometry({
        radius: 0.07,
        height: 3.2,
        segments: 8
    });

    const lantern = useIcoSphereGeometry({
        radius: 0.2,
        subdivisions: 2
    });

    for (const [x, z] of LAMPS) {
        const base = heightAt(x, z);

        createMesh({
            geometry: post,
            tint: '#22262e',
            castShadow: true,
            transform: {
                x,
                y: base + 1.6,
                z
            }
        });
        createMesh({
            geometry: lantern,
            tint: '#ffe2a8',
            emissive: '#ffcf7a',
            transform: {
                x,
                y: base + 3.25,
                z
            }
        });
        usePointLight({
            color: '#ffc879',
            intensity: 1.6,
            range: 8,
            transform: {
                x,
                y: base + 3.1,
                z
            }
        });
    }
};
```

`components/views.ts`:

```ts
import { createSprite, createText, listen, useAction, useUpdate } from 'nacatamalon';
import { VIEWS, WIDTH } from '../settings';
import type { TWater } from './water';

/**
 * The two ways to look at the street, switched with V or the button at the top right: RAIN as it
 * is, and WATER, what moves the water: red its depth, green the ball's rings, blue the raindrops'.
 */
export const Views = ({ water }: { water: TWater; }) => {
    let view = 0;

    const button = createSprite({
        width: 150,
        height: 18,
        tint: '#1c2338',
        anchor: {
            x: 1,
            y: 0
        },
        zIndex: 100,
        transform: {
            x: WIDTH - 8,
            y: 5
        }
    });

    const label = createText({
        text: '',
        tint: '#ffd9a0',
        anchor: {
            x: 0.5,
            y: 0
        },
        zIndex: 101,
        transform: {
            x: WIDTH - 83,
            y: 10
        }
    });

    const show = () => {
        label.text = `[V] VIEW: ${VIEWS[view]}`;
        water.showWater(VIEWS[view] === 'WATER');
    };

    const next = () => {
        view = (view + 1) % VIEWS.length;
        show();
    };

    listen(button, {
        onClick: next
    });
    listen(label, {
        onClick: next
    });
    show();

    const switchView = useAction('view');

    useUpdate(() => {
        if (switchView.justPressed()) {
            next();
        }
    });
};
```

`components/water.ts`:

```ts
import { createMaterial, createMesh, usePlaneGeometry, useUpdate } from 'nacatamalon';
import { buildTerrain, heightAt } from '../geometry/terrain';
import { SPLASHES, WATER_GLSL, WATER_WGSL, type TWaterKnobs } from '../shaders/water';
import { LAMPS, STREET, WATER_LEVEL } from '../settings';

export type TTerrain = ReturnType<typeof buildTerrain>;

/**
 * The puddles: one plane of water at `WATER_LEVEL`, as wide as the street, that shows only where the
 * ground is lower. What stirs it (the ball) and what lights it (the lightning) do so through what
 * this returns.
 */
export const Water = ({ terrain }: { terrain: TTerrain; }) => {
    const knobs: TWaterKnobs = {
        level: [WATER_LEVEL, terrain.low, terrain.high, 0],
        area: [-STREET.size / 2, -STREET.size / 2, STREET.size, STREET.size],
        lamp0: [],
        lamp1: [],
        lamp2: [],
        lampColor: [1.0, 0.78, 0.45, 0],
        skyLow: [0.1, 0.13, 0.2, 0],
        skyHigh: [0.26, 0.32, 0.46, 0]
    };

    // Where each lantern glows, for its glint in the water.
    LAMPS.forEach(([x, z], i) => {
        knobs[`lamp${i}`] = [x, heightAt(x, z) + 3.25, z, 1];
    });

    for (let i = 0; i < SPLASHES; i++) {
        knobs[`splash${i}`] = [0, 0, -10, 0];
    }

    createMesh({
        // In many pieces: the engine works its distance fog out per vertex.
        geometry: usePlaneGeometry({
            width: STREET.size,
            depth: STREET.size,
            widthSegments: 40,
            depthSegments: 40
        }),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'puddle water',
            transparent: true,
            fragment: WATER_WGSL,
            fragmentGlsl: WATER_GLSL,
            maps: {
                ground: {
                    texture: terrain.heights,
                    wrap: 'clamp',
                    smooth: true
                }
            },
            uniforms: knobs
        }),
        transform: {
            y: WATER_LEVEL
        }
    });

    // The next of the ball's rings to write, the oldest.
    let slot = 0;

    // The water measures each ring's age by the game's clock, kept here each frame. The water is made
    // before the ball, so it is already this frame's when the ball adds a ring.
    useUpdate((_delta, time) => {
        knobs.lampColor[3] = time;
    });

    return {
        /**
         * Whether a place on the street is under water.
         */
        isWet: (x: number, z: number) => heightAt(x, z) < WATER_LEVEL - 0.01,
        /**
         * A ring of the ball's at a place in the water, as strong as `strength` (0 to 1), starting
         * `after` seconds from now. It is written into the array the material already has.
         */
        ring: (x: number, z: number, strength: number, after = 0) => {
            const ring = knobs[`splash${slot}`];

            ring[0] = x;
            ring[1] = z;
            ring[2] = knobs.lampColor[3] + after;
            ring[3] = strength;
            slot = (slot + 1) % SPLASHES;
        },
        /**
         * How bright the lightning is now, 0 to 1, for the sky the water reflects.
         */
        lightning: (flash: number) => {
            knobs.skyHigh[3] = flash;
        },
        /**
         * Shows what moves the water instead of the water, or the water again.
         */
        showWater: (on: boolean) => {
            knobs.level[3] = on ? 1 : 0;
        }
    };
};

export type TWater = ReturnType<typeof Water>;
```

`geometry/terrain.ts`:

```ts
import { createGeometry } from 'nacatamalon';
import { createPixels, createPixelTexture } from 'nacatamalon/pixels';
import { BOWLS } from '../settings';

// The ground: a height field with gentle bumps and a few dips. The water is a single plane at a
// fixed height; where the ground is below it there is a puddle, and where it is above, the ground
// itself hides the water through the depth test. So the puddles take the shape of the ground with no
// edge drawn by hand.
//
// The height also goes into a picture, so the water's shader knows how deep it is and fades out at
// the shore.

const hash = (x: number, y: number) => {
    const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;

    return s - Math.floor(s);
};

const noise = (x: number, y: number) => {
    const ix = Math.floor(x);
    const iy = Math.floor(y);
    const fx = x - ix;
    const fy = y - iy;
    const ux = fx * fx * (3 - 2 * fx);
    const uy = fy * fy * (3 - 2 * fy);
    const a = hash(ix, iy);
    const b = hash(ix + 1, iy);
    const c = hash(ix, iy + 1);
    const d = hash(ix + 1, iy + 1);

    return a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy;
};

/**
 * How high the ground is at a place in the world.
 */
export const heightAt = (x: number, z: number) => {
    let h = 0.05 + (noise(x * 0.35, z * 0.35) - 0.5) * 0.08 + (noise(x * 1.7 + 4, z * 1.7 + 9) - 0.5) * 0.02;

    for (const [bx, bz, r, depth] of BOWLS) {
        // A little uneven: the edge of a puddle is not a circle.
        const wobble = 1 + (noise(x * 0.9 + bx, z * 0.9 + bz) - 0.5) * 0.5;
        const d = Math.hypot(x - bx, z - bz) / (r * wobble);

        if (d < 1) {
            h -= depth * (1 - d * d) ** 2;
        }
    }

    return h;
};

/**
 * The ground's geometry, `size` by `size` round the middle in `cells` by `cells` cells, and its
 * height as a picture for the water: 0 the lowest, 1 the highest, which are `low` and `high`.
 */
export const buildTerrain = (size: number, cells: number) => {
    const n = cells + 1;
    const step = size / cells;
    const half = size / 2;
    const positions = new Float32Array(n * n * 3);
    const indices = new Uint32Array(cells * cells * 6);
    let low = Infinity;
    let high = -Infinity;

    for (let z = 0; z < n; z++) {
        for (let x = 0; x < n; x++) {
            const wx = x * step - half;
            const wz = z * step - half;
            const h = heightAt(wx, wz);
            const i = (z * n + x) * 3;

            low = Math.min(low, h);
            high = Math.max(high, h);
            positions[i] = wx;
            positions[i + 1] = h;
            positions[i + 2] = wz;
        }
    }

    let k = 0;

    for (let z = 0; z < cells; z++) {
        for (let x = 0; x < cells; x++) {
            const a = z * n + x;

            indices[k++] = a;
            indices[k++] = a + n;
            indices[k++] = a + 1;
            indices[k++] = a + 1;
            indices[k++] = a + n;
            indices[k++] = a + n + 1;
        }
    }

    const geometry = createGeometry({
        positions,
        indices,
        uvs: 'planar',
        uvScale: 0.5
    });

    const mapSize = 128;
    const map = createPixels(mapSize, mapSize);

    for (let y = 0; y < mapSize; y++) {
        for (let x = 0; x < mapSize; x++) {
            const wx = ((x + 0.5) / mapSize) * size - half;
            const wz = ((y + 0.5) / mapSize) * size - half;
            const v = Math.round(((heightAt(wx, wz) - low) / (high - low)) * 255);
            const o = (y * mapSize + x) * 4;

            map.data[o] = v;
            map.data[o + 1] = v;
            map.data[o + 2] = v;
            map.data[o + 3] = 255;
        }
    }

    return {
        geometry,
        heights: createPixelTexture(map),
        low,
        high
    };
};
```

`scenes/rain.ts`:

```ts
import { cameraLookAt, createScene, createText, useCamera3d, useSpawn, useUpdate } from 'nacatamalon';
import { Ball } from '../components/ball';
import { Downpour } from '../components/downpour';
import { Sky } from '../components/sky';
import { Street } from '../components/street';
import { Views } from '../components/views';
import { Water } from '../components/water';
import { buildTerrain } from '../geometry/terrain';
import { HEIGHT, STREET } from '../settings';

/**
 * A rainy night on a cobbled street with puddles and three lamps. The street and the water share one
 * terrain; the water is made before the ball and the sky, which are handed what it returns so they
 * can stir it and light it.
 */
export const Rain = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            x: 0,
            y: 3.4,
            z: 7
        }
    });

    const terrain = buildTerrain(STREET.size, STREET.cells);

    useSpawn(Street)({
        terrain
    });

    const water = useSpawn(Water)({
        terrain
    });

    useSpawn(Sky)({
        water: water.api
    });

    const downpour = useSpawn(Downpour)();

    const ball = useSpawn(Ball)({
        water: water.api,
        downpour: downpour.api
    });

    useSpawn(Views)({
        water: water.api
    });

    createText({
        text: 'WASD / ARROWS: MOVE   SPACE: JUMP',
        tint: '#9fb0d8',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });
    createText({
        text: 'RAIN & PUDDLES · NACATAMALON',
        tint: '#9fb0d8',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    // The camera follows the ball from above, a little late, and the rain falls over what it sees.
    useUpdate((delta) => {
        const at = ball.api.mesh.transform;
        const follow = 1 - Math.exp(-2.5 * delta);

        camera.transform.x += (at.x * 0.7 - camera.transform.x) * follow;
        camera.transform.z += (at.z * 0.7 + 6.5 - camera.transform.z) * follow;
        cameraLookAt(camera, {
            x: at.x * 0.7,
            y: 0.2,
            z: at.z * 0.7
        });
        downpour.api.follow(at.x * 0.7, at.z * 0.7);
    });

    return createScene();
};
```

`settings.ts`:

```ts
import { INPUT, type TActionDef } from 'nacatamalon';

/**
 * The game's size, in its own pixels.
 */
export const WIDTH = 640;
export const HEIGHT = 360;

/**
 * The night sky, and the colour it turns in a flash of lightning.
 */
export const NIGHT = '#141a26';
export const FLASH = '#b9c6e6';

/**
 * Moving and jumping as a platformer reads them (WASD or the arrows, space, a pad), and V to switch
 * views.
 */
export const ACTIONS: TActionDef[] = [
    ...INPUT.ACTION_PRESETS.platformer,
    {
        name: 'view',
        bindings: [
            {
                type: 'key',
                key: 'v'
            }
        ]
    }
];

/**
 * What V and the button at the top right show: the rain as it is, and the water, red for its depth,
 * green for the ball's rings, blue for the raindrops'.
 */
export const VIEWS = ['RAIN', 'WATER'] as const;

/**
 * The street: `size` by `size` world units (metres) of cobbles round the middle, in `cells` by
 * `cells` cells. The ball keeps to the middle `play` by `play`.
 */
export const STREET = {
    size: 28,
    cells: 140,
    play: 20
};

/**
 * The height of the water. Wherever the ground is lower there is a puddle.
 */
export const WATER_LEVEL = 0;

/**
 * The dips where the water gathers: x, z, radius, depth.
 */
export const BOWLS: readonly (readonly [number, number, number, number])[] = [[0, 0.5, 3.2, 0.2], [-4.5, -2.5, 2.2, 0.16], [4.2, -3.0, 2.6, 0.18], [3.8, 3.6, 1.8, 0.15], [-3.8, 3.8, 2.4, 0.17], [-0.5, -5.5, 1.6, 0.14], [6.8, 0.5, 1.4, 0.13], [-7.0, 0.2, 1.5, 0.14]];

/**
 * The street lamps, near the puddles so they show in them: x, z.
 */
export const LAMPS: readonly (readonly [number, number])[] = [[-2.2, -1.5], [3.0, 1.2], [-1.5, 4.5]];

/**
 * The yellow ball, in world units and seconds. It never goes nearer the edge of the play area than
 * `edge`.
 */
export const BALL = {
    radius: 0.4,
    start: {
        x: 0,
        z: 3
    },
    accel: 16,
    gravity: 20,
    jump: 7,
    edge: 1,
    /**
     * How fast it slows: gently while it is steered, faster when let go, and more in the water.
     */
    drag: 2.4,
    stopDrag: 4.5,
    waterDrag: 1.2
};

/**
 * The rings the ball leaves in the water: a faint one every `spacing` world units as it rolls, and
 * two strong ones when it lands harder than `landing`.
 */
export const RIPPLES = {
    spacing: 0.3,
    landing: 3
};

/**
 * Left alone this many seconds, the ball goes from puddle to puddle by itself and jumps now and then.
 */
export const IDLE_SECONDS = 3;

/**
 * Lightning: the first flash after `first` seconds, then one every `every` seconds or so.
 */
export const LIGHTNING = {
    first: 6,
    every: [7, 15] as const
};
```

`shaders/ground.ts`:

```ts
// The wet cobbles: darker than dry, with the street lamps' glints (the `shine` the engine works out
// from the material's specular), which is what makes them look wet.

export const GROUND_WGSL = /* wgsl */ `
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let color = surface.rgb * ctx.light * 0.6 + ctx.shine * mu.wet.x;
    return vec4<f32>(color, 1.0);
}
`;

export const GROUND_GLSL = /* glsl */ `
vec4 effect(vec4 surface, FragContext ctx) {
    vec3 color = surface.rgb * ctx.light * 0.6 + ctx.shine * mu.wet.x;
    return vec4(color, 1.0);
}
`;
```

`shaders/water.ts`:

```ts
// The puddles' water. A single plane: where the ground is above it, the ground hides it.
// - Depth: from the picture of the ground's heights. See-through at the shore, darker in the middle.
// - Normal: the raindrops' rings and the ball's, all drawn here, none simulated. Raindrops: in each
//   cell of a grid one lands at a random moment and its ring grows and fades. The ball's: the game
//   says where and when it landed or rolled by, and the ring spreads from there.
// - Colour: the sky reflected (Fresnel: more of a mirror the more it is seen edge on), and the
//   glint of each street lamp, broken up by the ripples.

/**
 * How many of the ball's recent rings the water remembers. A material has 64 numbers of parameters:
 * with 5, everything else fits.
 */
export const SPLASHES = 5;

export type TWaterKnobs = Record<string, number[]> & {
    /**
     * The water's height, the ground's lowest and highest (what the heights picture's 0 and 1 are),
     * and the WATER view (0 or 1).
     */
    level: number[];
    /**
     * Where the heights picture lies: x, z, width, depth.
     */
    area: number[];
    /**
     * Each lamp: x, y, z, and how bright.
     */
    lamp0: number[];
    lamp1: number[];
    lamp2: number[];
    /**
     * The lamps' colour, and in w the game's clock, which the rings' ages are measured by.
     */
    lampColor: number[];
    skyLow: number[];
    /**
     * The sky up high, and in w the lightning.
     */
    skyHigh: number[];
};

const splashSumWgsl = Array.from({
    length: SPLASHES
}, (_, i) => `    splashes = splashes + splash(p.xz, mu.splash${i});`).join('\n');

const splashSumGlsl = Array.from({
    length: SPLASHES
}, (_, i) => `    splashes += splash(p.xz, mu.splash${i});`).join('\n');

export const WATER_WGSL = /* wgsl */ `
fn rainHash(p: vec2<f32>) -> vec2<f32> {
    let q = vec2<f32>(dot(p, vec2<f32>(127.1, 311.7)), dot(p, vec2<f32>(269.5, 183.3)));
    return fract(sin(q) * 43758.5453);
}

// The slope the raindrops' rings leave at this point.
fn raindrops(p: vec2<f32>, time: f32) -> vec2<f32> {
    let scaled = p * 3.2;
    let cell = floor(scaled);
    var slope = vec2<f32>(0.0);
    for (var j = -1; j <= 1; j = j + 1) {
        for (var i = -1; i <= 1; i = i + 1) {
            let c = cell + vec2<f32>(f32(i), f32(j));
            let r = rainHash(c);
            let center = c + r;
            let t = fract(time * (0.8 + r.y * 0.6) + r.x * 13.0);
            let away = scaled - center;
            let d = length(away);
            let front = d - t * 1.1;
            let ring = sin(front * 26.0) * exp(-front * front * 60.0) * (1.0 - t) * (1.0 - t);
            slope = slope + away / max(d, 0.0001) * ring;
        }
    }
    return slope;
}

// One of the ball's rings: (x, z, when it started, strength).
fn splash(p: vec2<f32>, e: vec4<f32>) -> vec2<f32> {
    // By the game's clock (lampColor.w), the same one the game stamps each ring with.
    let age = mu.lampColor.w - e.z;
    if (e.w <= 0.0 || age < 0.0 || age > 2.5) {
        return vec2<f32>(0.0);
    }
    let away = p - e.xy;
    let d = length(away);
    let front = d - age * 0.6;
    let ring = sin(front * 55.0) * exp(-front * front * 30.0) * exp(-age * 2.0) * e.w * smoothstep(0.0, 0.06, d);
    return away / max(d, 0.0001) * ring * 0.14;
}

fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let p = ctx.worldPos;
    let uv = (p.xz - mu.area.xy) / mu.area.zw;
    let ground = mix(mu.level.y, mu.level.z, sampleMap_ground(uv).r);
    let depth = mu.level.x - ground;
    if (depth <= 0.0) {
        return vec4<f32>(0.0);
    }

    // The ball's rings: fine ones (about 10 cm from crest to crest) that fade in a second or two,
    // as in a real puddle.
    var splashes = vec2<f32>(0.0);
${splashSumWgsl}
    let drops = raindrops(p.xz, mu.time) * 0.18;
    // The ripples tilt the surface a little, and no more: a puddle's water never stands on end.
    let tilt = clamp(splashes + drops, vec2<f32>(-0.3), vec2<f32>(0.3));
    let n = normalize(vec3<f32>(-tilt.x, 1.0, -tilt.y));

    let v = normalize(ctx.viewDir);
    // Fresnel with a calmer normal: worked out with every ripple, the whole puddle turns to a mirror
    // when stirred and looks like metal.
    let calm = normalize(mix(vec3<f32>(0.0, 1.0, 0.0), n, 0.35));
    let facing = max(dot(calm, v), 0.0);
    let fresnel = 0.02 + 0.6 * pow(1.0 - facing, 5.0);
    let r = reflect(-v, n);
    let sky = mix(mu.skyLow.rgb, mu.skyHigh.rgb, clamp(r.y, 0.0, 1.0)) * (1.0 + mu.skyHigh.w * 1.2);

    // The lamps' glints: a sharp spot and a halo, both broken up by the ripples.
    var lamps = vec3<f32>(0.0);
    for (var k = 0; k < 3; k = k + 1) {
        var lamp = mu.lamp0;
        if (k == 1) { lamp = mu.lamp1; }
        if (k == 2) { lamp = mu.lamp2; }
        let toLamp = lamp.xyz - p;
        let l = normalize(toLamp);
        let h = normalize(l + v);
        let spec = pow(max(dot(n, h), 0.0), 350.0) * 6.0 + pow(max(dot(n, h), 0.0), 40.0) * 0.25;
        lamps = lamps + mu.lampColor.rgb * spec * lamp.w / (1.0 + dot(toLamp, toLamp) * 0.04);
    }

    let deep = vec3<f32>(0.006, 0.008, 0.014);
    let color = deep * (1.0 - fresnel) + sky * fresnel + lamps;
    let edge = smoothstep(0.0, 0.035, depth);
    let alpha = clamp(edge * (0.82 + fresnel * 0.18) + length(lamps) * 0.5, 0.0, 1.0);

    // The WATER view: red the depth, green the ball's rings, blue the raindrops'.
    let debug = vec3<f32>(depth * 5.0, 0.5 + splashes.x * 4.0, 0.5 + drops.x * 2.0);
    return vec4<f32>(mix(color, debug, mu.level.w), mix(alpha, 0.9 * edge, mu.level.w));
}
`;

export const WATER_GLSL = /* glsl */ `
vec2 rainHash(vec2 p) {
    vec2 q = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)));
    return fract(sin(q) * 43758.5453);
}

vec2 raindrops(vec2 p, float time) {
    vec2 scaled = p * 3.2;
    vec2 cell = floor(scaled);
    vec2 slope = vec2(0.0);
    for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
            vec2 c = cell + vec2(float(i), float(j));
            vec2 r = rainHash(c);
            vec2 center = c + r;
            float t = fract(time * (0.8 + r.y * 0.6) + r.x * 13.0);
            vec2 away = scaled - center;
            float d = length(away);
            float front = d - t * 1.1;
            float ring = sin(front * 26.0) * exp(-front * front * 60.0) * (1.0 - t) * (1.0 - t);
            slope += away / max(d, 0.0001) * ring;
        }
    }
    return slope;
}

vec2 splash(vec2 p, vec4 e) {
    float age = mu.lampColor.w - e.z;
    if (e.w <= 0.0 || age < 0.0 || age > 2.5) {
        return vec2(0.0);
    }
    vec2 away = p - e.xy;
    float d = length(away);
    float front = d - age * 0.6;
    float ring = sin(front * 55.0) * exp(-front * front * 30.0) * exp(-age * 2.0) * e.w * smoothstep(0.0, 0.06, d);
    return away / max(d, 0.0001) * ring * 0.14;
}

vec4 effect(vec4 surface, FragContext ctx) {
    vec3 p = ctx.worldPos;
    vec2 uv = (p.xz - mu.area.xy) / mu.area.zw;
    float ground = mix(mu.level.y, mu.level.z, sampleMap_ground(uv).r);
    float depth = mu.level.x - ground;
    if (depth <= 0.0) {
        return vec4(0.0);
    }

    vec2 splashes = vec2(0.0);
${splashSumGlsl}
    vec2 drops = raindrops(p.xz, mu.time) * 0.18;
    vec2 tilt = clamp(splashes + drops, vec2(-0.3), vec2(0.3));
    vec3 n = normalize(vec3(-tilt.x, 1.0, -tilt.y));

    vec3 v = normalize(ctx.viewDir);
    vec3 calm = normalize(mix(vec3(0.0, 1.0, 0.0), n, 0.35));
    float facing = max(dot(calm, v), 0.0);
    float fresnel = 0.02 + 0.6 * pow(1.0 - facing, 5.0);
    vec3 r = reflect(-v, n);
    vec3 sky = mix(mu.skyLow.rgb, mu.skyHigh.rgb, clamp(r.y, 0.0, 1.0)) * (1.0 + mu.skyHigh.w * 1.2);

    vec3 lamps = vec3(0.0);
    for (int k = 0; k < 3; k++) {
        vec4 lamp = k == 0 ? mu.lamp0 : (k == 1 ? mu.lamp1 : mu.lamp2);
        vec3 toLamp = lamp.xyz - p;
        vec3 l = normalize(toLamp);
        vec3 h = normalize(l + v);
        float spec = pow(max(dot(n, h), 0.0), 350.0) * 6.0 + pow(max(dot(n, h), 0.0), 40.0) * 0.25;
        lamps += mu.lampColor.rgb * spec * lamp.w / (1.0 + dot(toLamp, toLamp) * 0.04);
    }

    vec3 deep = vec3(0.006, 0.008, 0.014);
    vec3 color = deep * (1.0 - fresnel) + sky * fresnel + lamps;
    float edge = smoothstep(0.0, 0.035, depth);
    float alpha = clamp(edge * (0.82 + fresnel * 0.18) + length(lamps) * 0.5, 0.0, 1.0);

    vec3 debug = vec3(depth * 5.0, 0.5 + splashes.x * 4.0, 0.5 + drops.x * 2.0);
    return vec4(mix(color, debug, mu.level.w), mix(alpha, 0.9 * edge, mu.level.w));
}
`;
```
