# Storm

> A village in the rain: a click on the ground calls down a bolt that lights everything, and the thunder arrives later the further away it struck.

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

**Click the ground** to call the lightning down there: the flash is instant and throws every shadow at once, and the thunder arrives later the further away it struck. Turn the sound on.

The rain is 1,400 streaks of `useLines`, and the splashes a particle emitter spread over the street (the era's trick: they are not where the drops land, and nobody can tell). The bolt is a jagged line, and the sky is the one light that casts, flashed for a tenth of a second.

The thunder and the rain are synthesized by the example, sample by sample, as WAV files loaded with `useLoadAudio`.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import * as Settings from './settings';
import { Night } from './scenes/demo';

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#05060b',
    msaa: 4
});

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

`audio/sound.ts`:

```ts
import * as Settings from '../settings';

/** A mono 16-bit WAV of the given length, each sample from sample(t), as a URL the engine can load. */
const wav = (seconds: number, sample: (t: number) => number): string => {
    const count = Math.floor(seconds * Settings.RATE);
    const bytes = new ArrayBuffer(44 + count * 2);
    const view = new DataView(bytes);

    const text = (at: number, s: string) => {
        for (let i = 0; i < s.length; i++) {
            view.setUint8(at + i, s.charCodeAt(i));
        }
    };

    text(0, 'RIFF');
    view.setUint32(4, 36 + count * 2, true);
    text(8, 'WAVE');
    text(12, 'fmt ');
    view.setUint32(16, 16, true);
    view.setUint16(20, 1, true);
    view.setUint16(22, 1, true);
    view.setUint32(24, Settings.RATE, true);
    view.setUint32(28, Settings.RATE * 2, true);
    view.setUint16(32, 2, true);
    view.setUint16(34, 16, true);
    text(36, 'data');
    view.setUint32(40, count * 2, true);

    for (let i = 0; i < count; i++) {
        const s = Math.max(-1, Math.min(1, sample(i / Settings.RATE)));

        view.setInt16(44 + i * 2, s * 32767, true);
    }

    return URL.createObjectURL(new Blob([bytes], {
        type: 'audio/wav'
    }));
};

/**
 * Thunder: a crack of white noise, then a long rumble of brown noise (noise that wanders instead of
 * jumping, which is what makes it low) that swells and fades.
 */
export const thunderSound = (): string => {
    let brown = 0;
    let smooth = 0;

    return wav(5, (t) => {
        const white = Math.random() * 2 - 1;

        brown = (brown + 0.02 * white) / 1.02;
        smooth += 0.08 * (brown - smooth);

        const crack = white * Math.exp(-t * 14) * 0.5;
        const swell = 0.65 + 0.35 * Math.sin(t * 4.5 + Math.sin(t * 1.7) * 3);
        const rumble = smooth * 9 * (1 - Math.exp(-t * 10)) * Math.exp(-t * 0.75) * swell;

        return crack + rumble;
    });
};

/** Rain: soft noise, and every so often a drop landing close by. Three seconds, looped. */
export const rainSound = (): string => {
    let soft = 0;
    let drop = 0;

    return wav(3, () => {
        const white = Math.random() * 2 - 1;

        soft += 0.3 * (white - soft);

        if (Math.random() < 0.0012) {
            drop = 0.6;
        }

        drop *= 0.985;

        return soft * 0.5 + white * drop * 0.3;
    });
};
```

`components/village.ts`:

```ts
import { createMesh, useConeGeometry, useCubeGeometry, useCylinderGeometry, usePlaneGeometry, usePointLight, useSpawn } from 'nacatamalon';

/**
 * The street, the houses either side of it and a lamp. The ground is shiny: rain on stone.
 */
export const Village = () => {
    createMesh({
        geometry: usePlaneGeometry({
            width: 60,
            depth: 60
        }),
        tint: '#3a3f47',
        specular: '#6b7686',
        shininess: 60,
        castShadow: false,
    });

    const box = useCubeGeometry();

    const roof = useConeGeometry({
        radius: 1,
        height: 1,
        segments: 4
    });

    const houses = [
        {
            x: -4.2,
            z: 0,
            w: 2.6,
            h: 2.4,
            d: 3,
            turn: 0.1
        },
        {
            x: -4.6,
            z: -5,
            w: 3,
            h: 3.2,
            d: 3,
            turn: -0.05
        },
        {
            x: -3.8,
            z: -10.5,
            w: 2.4,
            h: 2.2,
            d: 2.6,
            turn: 0.2
        },
        {
            x: 4.4,
            z: -1.5,
            w: 2.8,
            h: 2.8,
            d: 3.2,
            turn: -0.1
        },
        {
            x: 4.8,
            z: -7,
            w: 3.2,
            h: 2.4,
            d: 3,
            turn: 0.05
        },
        {
            x: 4,
            z: -12.5,
            w: 2.4,
            h: 3,
            d: 2.6,
            turn: -0.2
        },
    ];

    for (const house of houses) {
        createMesh({
            geometry: box,
            tint: '#5d5146',
            transform: {
                x: house.x,
                y: house.h / 2,
                z: house.z,
                rotationY: house.turn,
                scaleX: house.w,
                scaleY: house.h,
                scaleZ: house.d
            },
        });
        createMesh({
            geometry: roof,
            tint: '#6b2e25',
            transform: {
                x: house.x,
                y: house.h + 0.6,
                z: house.z,
                rotationY: house.turn + Math.PI / 4,
                scaleX: house.w * 0.85,
                scaleY: 1.2,
                scaleZ: house.d * 0.85
            },
        });

        // A lit window facing the street.
        const side = house.x < 0 ? 1 : -1;

        createMesh({
            geometry: box,
            tint: '#000000',
            emissive: '#ffb04a',
            transform: {
                x: house.x + side * (house.w / 2 + 0.01),
                y: house.h * 0.55,
                z: house.z,
                rotationY: house.turn,
                scaleX: 0.02,
                scaleY: 0.5,
                scaleZ: 0.5
            },
        });
    }

    // The lamp post, and its light on an object of its own.
    createMesh({
        geometry: useCylinderGeometry({
            radius: 0.06,
            height: 3,
            segments: 8
        }),
        tint: '#2b2f36',
        transform: {
            x: 1.8,
            y: 1.5,
            z: 1
        }
    });
    createMesh({
        geometry: box,
        tint: '#000000',
        emissive: '#ffd48a',
        transform: {
            x: 1.8,
            y: 3.05,
            z: 1,
            scaleX: 0.3,
            scaleY: 0.25,
            scaleZ: 0.3
        }
    });
    useSpawn(() => {
        usePointLight({
            color: '#ffc46b',
            intensity: 1.4,
            range: 7,
            transform: {
                x: 1.8,
                y: 2.8,
                z: 1
            }
        });
    })();
};
```

`components/weather.ts`:

```ts
import * as Settings from '../settings';
import { createParticles3d, screenToRay, useGame, setLines, useLines, useLoadAudio, useLoadParticles, usePointer, useSound, useUpdate, type TCamera3d, type TDirectionalLight } from 'nacatamalon';
import { rainSound, thunderSound } from '../audio/sound';

// how long a drop's streak is, in seconds of its fall

type Strike = { x: number; z: number; age: number; pulse: number; bolt: Float32Array; };

/** A jagged bolt from the clouds to (x, z), with a couple of branches: lines, seven numbers a corner. */
const makeBolt = (x: number, z: number): Float32Array => {
    const corners: number[] = [];

    const segment = (ax: number, ay: number, az: number, bx: number, by: number, bz: number, bright: number) => {
        corners.push(ax, ay, az, 0.8 * bright, 0.85 * bright, bright, 1, bx, by, bz, 0.8 * bright, 0.85 * bright, bright, 1);
    };

    const walk = (fromX: number, fromY: number, fromZ: number, toY: number, steps: number, bright: number, branches: boolean) => {
        let px = fromX, py = fromY, pz = fromZ;

        for (let i = 1; i <= steps; i++) {
            const ny = fromY + (toY - fromY) * (i / steps);
            const nx = (i === steps && branches ? x : px + (Math.random() - 0.5) * 1.4);
            const nz = (i === steps && branches ? z : pz + (Math.random() - 0.5) * 0.8);

            segment(px, py, pz, nx, ny, nz, bright);

            if (branches && Math.random() < 0.18) {
                walk(nx, ny, nz, ny - 2 - Math.random() * 3, 5, 0.55, false);
            }

            px = nx;
            py = ny;
            pz = nz;
        }
    };

    walk(x + (Math.random() - 0.5) * 4, 16, z, 0, 16, 1, true);

    return new Float32Array(corners);
};

export const Weather = (camera: TCamera3d, sky: TDirectionalLight) => {
    const game = useGame();
    const pointer = usePointer();
    const streaks = useLines();

    // The rain is lines, one streak a drop, because that is what rain looks like at this speed.
    // Particles would draw each drop as a dot, and their trails as dots a sixtieth of a second
    // apart. The splashes ARE particles: an emitter spread over the street, which is the era's
    // trick (they are not where the drops land, and nobody can tell).
    const dx = new Float32Array(Settings.DROPS);
    const dy = new Float32Array(Settings.DROPS);
    const dz = new Float32Array(Settings.DROPS);

    const dropAt = (i: number, y: number) => {
        dx[i] = (Math.random() - 0.5) * 22;
        dy[i] = y;
        dz[i] = 5 - Math.random() * 26;
    };

    for (let i = 0; i < Settings.DROPS; i++) {
        dropAt(i, Math.random() * 14);
    }

    createParticles3d({
        effect: useLoadParticles({
            src: '/example-assets/effects/storm_splash3d.particles'
        }),
        transform: {
            y: 0.02,
            z: -4
        }
    });

    // Both sounds are made by the example, sample by sample (see sound.ts), and loaded like files.
    useSound(useLoadAudio({
        src: rainSound(),
        key: 'storm-rain'
    }), {
        loop: true,
        autoplay: true,
        volume: 0.3
    });

    const thunder = useSound(useLoadAudio({
        src: thunderSound(),
        key: 'storm-thunder'
    }), {
        volume: 1
    });

    const strikes: Strike[] = [];
    const rumbles: { at: number; volume: number; rate: number; }[] = [];
    let time = 0;

    const strike = (x: number, z: number) => {
        strikes.push({
            x,
            z,
            age: 0,
            pulse: 0,
            bolt: makeBolt(x, z)
        });

        // The flash is now; the thunder is when the sound gets here.
        const distance = Math.hypot(x - camera.transform.x, z - camera.transform.z);

        rumbles.push({
            at: time + distance / Settings.SOUND_SPEED,
            volume: Math.max(0.25, 1 - distance / 60),
            rate: distance < 12 ? 1 : 0.8
        });
    };

    pointer.onDown((info) => {
        const ray = screenToRay(camera, game.getWidth(), game.getHeight(), info.screenX, info.screenY);

        if (ray.direction.y >= -0.01) {
            return;
        }

        const t = -ray.origin.y / ray.direction.y;

        strike(ray.origin.x + ray.direction.x * t, ray.origin.z + ray.direction.z * t);
    });

    let nextStrike = 2;

    useUpdate((delta) => {
        time += delta;
        nextStrike -= delta;

        if (nextStrike <= 0) {
            nextStrike = 5 + Math.random() * 7;
            strike((Math.random() - 0.5) * 50, -15 - Math.random() * 30);
        }

        // A flash is not one blink: it flickers two or three times as the bolt restrikes.
        let flash = 0;
        let lines = 0;

        for (let i = strikes.length - 1; i >= 0; i--) {
            const s = strikes[i];

            s.age += delta;
            s.pulse = s.age < 0.06 ? 1 : s.age < 0.12 ? 0.25 : s.age < 0.2 ? 0.8 : s.age < 0.45 ? 0.35 * (1 - (s.age - 0.2) / 0.25) : 0;
            flash = Math.max(flash, s.pulse);

            if (s.age > 0.5) {
                strikes.splice(i, 1);
            } else if (s.pulse > 0.3) {
                lines += s.bolt.length;
            }
        }

        sky.intensity = 0.06 + flash * 2.6;

        const vertices = new Float32Array(Settings.DROPS * 14 + lines);
        let n = 0;
        const shade = 0.42 + flash * 0.5;

        for (let i = 0; i < Settings.DROPS; i++) {
            dx[i] += Settings.FALL.x * delta;
            dy[i] += Settings.FALL.y * delta;

            if (dy[i] < 0) {
                dropAt(i, 14 + Math.random() * 2);
            }

            vertices[n++] = dx[i];
            vertices[n++] = dy[i];
            vertices[n++] = dz[i];
            vertices[n++] = shade * 0.85;
            vertices[n++] = shade * 0.92;
            vertices[n++] = shade;
            vertices[n++] = 1;
            vertices[n++] = dx[i] - Settings.FALL.x * Settings.STREAK;
            vertices[n++] = dy[i] - Settings.FALL.y * Settings.STREAK;
            vertices[n++] = dz[i];
            vertices[n++] = shade * 0.3;
            vertices[n++] = shade * 0.33;
            vertices[n++] = shade * 0.4;
            vertices[n++] = 1;
        }

        // The bolt is only there while it is bright.
        for (const s of strikes) {
            if (s.pulse > 0.3) {
                vertices.set(s.bolt, n);
                n += s.bolt.length;
            }
        }

        setLines(streaks, vertices);

        for (let i = rumbles.length - 1; i >= 0; i--) {
            if (time >= rumbles[i].at) {
                thunder.setVolume(rumbles[i].volume);
                thunder.setRate(rumbles[i].rate);
                thunder.play();
                rumbles.splice(i, 1);
            }
        }

        // The camera breathes a little, as if standing in the rain.
        camera.transform.rotationY = Math.sin(time * 0.2) * 0.12;
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useCamera3d, useDirectionalLight, useSpawn } from 'nacatamalon';

import { Village } from '../components/village';
import { Weather } from '../components/weather';

export const Night = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 55,
        near: 0.1,
        far: 120,
        transform: {
            y: 1.7,
            z: 7,
            rotationX: -0.08
        }
    });

    // The sky: almost nothing most of the time, blinding for a tenth of a second. It is the one
    // light that casts, so a flash throws every shadow in the village at once.
    const sky = useDirectionalLight({
        color: '#c9d8ff',
        intensity: 0.06,
        ambient: 0.05,
        transform: {
            rotationX: -1.0,
            rotationY: 0.5
        },
        castShadow: true,
        shadowArea: 30,
        shadowDistance: 40,
    });

    useSpawn(Village)();
    useSpawn(Weather)(camera, sky);

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const SOUND_SPEED = 9;
// units a second: slowed down, so the wait is easy to hear
export const DROPS = 1400;
export const FALL = {
    x: 1.2,
    y: -14
};
// units a second, with a little wind
export const STREAK = 0.045;
// Two sounds, made sample by sample and wrapped as WAV files the engine loads like any other.

export const RATE = 22050;
```
