# Ripples

> A pond seen from above: every drop sends out a ring that refracts the bottom and catches the light.

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

**Move the mouse** and small ripples trail behind it; **click** for a big drop. Each ring bends the picture of the bottom as it passes and catches the light, and the sun plays on the stones.

The water remembers nothing between frames. Each of the last eight drops is four numbers (where, when, how hard) in a `vec4` uniform, and the sprite's material works out from them where every ring is now.

The bottom is painted by the example on a canvas.

## Code

`index.ts`:

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

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

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

`art/bottom.ts`:

```ts
// The bottom of the pond, painted once on a canvas: sand, pebbles, weed, and three koi resting.

export const drawBottom = (width: number, height: number) => {
    const rand = (() => {
        let s = 11;

        return () => ((s = (s * 16807) % 2147483647) / 2147483647);
    })();

    const canvas = document.createElement('canvas');

    canvas.width = width;
    canvas.height = height;

    const g = canvas.getContext('2d')!;

    const sand = g.createRadialGradient(width / 2, height / 2, 20, width / 2, height / 2, width * 0.7);

    sand.addColorStop(0, '#6f8f7a');
    sand.addColorStop(1, '#23413d');
    g.fillStyle = sand;
    g.fillRect(0, 0, width, height);

    for (let i = 0; i < 260; i++) {
        const x = rand() * width;
        const y = rand() * height;
        const r = 2 + rand() * 9;
        const shade = 55 + rand() * 60;

        g.fillStyle = 'rgb(' + (shade + 20) + ',' + (shade + 15) + ',' + shade + ')';
        g.beginPath();
        g.ellipse(x, y, r, r * (0.6 + rand() * 0.4), rand() * Math.PI, 0, Math.PI * 2);
        g.fill();
        g.fillStyle = 'rgba(255,255,255,0.1)';
        g.beginPath();
        g.ellipse(x - r * 0.3, y - r * 0.3, r * 0.4, r * 0.25, 0, 0, Math.PI * 2);
        g.fill();
    }

    g.strokeStyle = 'rgba(40,110,60,0.8)';
    g.lineWidth = 3;

    for (let i = 0; i < 14; i++) {
        const x = rand() * width;
        const y = rand() * height;

        g.beginPath();
        g.moveTo(x, y);
        g.bezierCurveTo(x + 20, y - 15, x - 10, y - 35, x + 15, y - 55);
        g.stroke();
    }

    const koi = (x: number, y: number, turn: number, a: string, b: string) => {
        g.save();
        g.translate(x, y);
        g.rotate(turn);
        g.fillStyle = a;
        g.beginPath();
        g.ellipse(0, 0, 26, 10, 0, 0, Math.PI * 2);
        g.fill();
        g.beginPath();
        g.moveTo(-22, 0);
        g.lineTo(-42, -11);
        g.lineTo(-36, 0);
        g.lineTo(-42, 11);
        g.fill();
        g.fillStyle = b;
        g.beginPath();
        g.ellipse(6, -2, 8, 5, 0.3, 0, Math.PI * 2);
        g.fill();
        g.beginPath();
        g.ellipse(-10, 3, 6, 4, -0.2, 0, Math.PI * 2);
        g.fill();
        g.restore();
    };

    koi(width * 0.3, height * 0.35, 0.4, '#f06a1c', '#ffffff');
    koi(width * 0.68, height * 0.6, 2.6, '#ffffff', '#e2361b');
    koi(width * 0.55, height * 0.25, -0.9, '#f0a21c', '#1b1b1b');

    return canvas;
};
```

`components/pond.ts`:

```ts
import { useRandom } from 'nacatamalon/math';
import * as Settings from '../settings';
import { createMaterial, createSprite, useGame, useLoadTexture, usePointer, useUpdate } from 'nacatamalon';
import { drawBottom } from '../art/bottom';
import { WATER, WATER_GLSL } from '../shaders/water';

export const Pond = () => {
    const random = useRandom();
    const game = useGame();
    const pointer = usePointer();
    const W = game.getWidth();
    const H = game.getHeight();

    // The water keeps no picture of itself from one frame to the next: every ring is only where it
    // started, when, and how hard. The shader works out from those where each ring is now and how
    // much it bends the bottom, so there is no state to carry and nothing to feed back.
    // Eight rings, one vec4 each (x, y, start time, strength), reused oldest first.
    const uniforms: Record<string, number | number[]> = {
        now: 0,
        aspect: W / H
    };

    for (let i = 0; i < Settings.RINGS; i++) {
        uniforms['ring' + i] = [0, 0, -100, 0];
    }

    const water = createMaterial({
        name: 'water',
        fragment: WATER,
        fragmentGlsl: WATER_GLSL,
        uniforms
    });

    const bottom = useLoadTexture({
        src: drawBottom(W, H).toDataURL(),
        key: 'pond-bottom'
    });

    createSprite({
        texture: bottom,
        material: water,
        width: W,
        height: H,
        transform: {
            x: W / 2,
            y: H / 2
        }
    });

    let time = 0;
    let next = 0;

    const drop = (x: number, y: number, strength: number) => {
        // Written into the array that is already there: the material reads these very numbers.
        const ring = uniforms['ring' + next] as number[];

        ring[0] = x / W;
        ring[1] = y / H;
        ring[2] = time;
        ring[3] = strength;
        next = (next + 1) % Settings.RINGS;
    };

    let lastTrail = 0;

    pointer.onMove((info) => {
        if (time - lastTrail > 0.12) {
            lastTrail = time;
            drop(info.screenX, info.screenY, 0.35);
        }
    });
    pointer.onDown((info) => drop(info.screenX, info.screenY, 1));

    let rain = 1;

    useUpdate((delta) => {
        time += delta;
        uniforms.now = time;
        // Now and then a drop falls on its own, so the pond is never quite still.
        rain -= delta;

        if (rain <= 0) {
            rain = 0.8 + random.rand() * 1.6;
            drop(random.rand() * W, random.rand() * H, 0.5);
        }
    });
};
```

`scenes/demo.ts`:

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

import { Pond } from '../components/pond';

export const Garden = () => {
    useSpawn(Pond)();

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const RINGS = 8;
```

`shaders/water.ts`:

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

// Each ring is a short wave travelling outwards: at a distance d from where it fell, after age
// seconds, the wave is at d = age * speed, with a bump either side that fades with age. The picture
// of the bottom is read a little off to the side where the water slopes, which is refraction, and
// a slope that faces the light gets a highlight. On top, the dancing light of the sun on the stones:
// two moving grids of waves, brightened where they agree.

const RING_WGSL = (i: number) => `
    {
        let r = mu.ring${i};
        let age = mu.now - r.z;
        let d = distance(p, vec2<f32>(r.x * mu.aspect, r.y));
        let front = d - age * 0.28;
        let wave = sin(front * 70.0) * exp(-front * front * 500.0) * r.w * exp(-age * 0.7) * step(0.0, age);
        let away = select(vec2<f32>(0.0), normalize(p - vec2<f32>(r.x * mu.aspect, r.y)), d > 0.0001);
        slope += away * wave;
    }`;

const RING_GLSL = (i: number) => `
    {
        vec4 r = mu.ring${i};
        float age = mu.now - r.z;
        float d = distance(p, vec2(r.x * mu.aspect, r.y));
        float front = d - age * 0.28;
        float wave = sin(front * 70.0) * exp(-front * front * 500.0) * r.w * exp(-age * 0.7) * step(0.0, age);
        vec2 away = d > 0.0001 ? normalize(p - vec2(r.x * mu.aspect, r.y)) : vec2(0.0);
        slope += away * wave;
    }`;

const rings = (one: (i: number) => string) => Array.from({
    length: Settings.RINGS
}, (_, i) => one(i)).join('\n');

export const WATER = `
fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
    let p = vec2<f32>(uv.x * mu.aspect, uv.y);
    var slope = vec2<f32>(0.0);
${rings(RING_WGSL)}
    let bent = uv + slope * 0.03;
    var rgb = sampleTexture(bent).rgb;

    let t = mu.now;
    let c1 = sin(p.x * 38.0 + sin(p.y * 21.0 + t * 1.3) * 1.5 + t);
    let c2 = sin(p.y * 34.0 + sin(p.x * 25.0 - t * 1.1) * 1.5 - t * 0.8);
    let caustic = pow(max(0.0, c1 * c2), 3.0) * 0.18;

    let light = max(0.0, dot(slope, vec2<f32>(-0.7, -0.7)));
    rgb = rgb * vec3<f32>(0.78, 0.92, 1.0) + vec3<f32>(caustic) + vec3<f32>(light * 1.1);
    return vec4<f32>(rgb, 1.0);
}
`;

export const WATER_GLSL = `
vec4 effect(vec4 color, vec2 uv) {
    vec2 p = vec2(uv.x * mu.aspect, uv.y);
    vec2 slope = vec2(0.0);
${rings(RING_GLSL)}
    vec2 bent = uv + slope * 0.03;
    vec3 rgb = sampleTexture(bent).rgb;

    float t = mu.now;
    float c1 = sin(p.x * 38.0 + sin(p.y * 21.0 + t * 1.3) * 1.5 + t);
    float c2 = sin(p.y * 34.0 + sin(p.x * 25.0 - t * 1.1) * 1.5 - t * 0.8);
    float caustic = pow(max(0.0, c1 * c2), 3.0) * 0.18;

    float light = max(0.0, dot(slope, vec2(-0.7, -0.7)));
    rgb = rgb * vec3(0.78, 0.92, 1.0) + vec3(caustic) + vec3(light * 1.1);
    return vec4(rgb, 1.0);
}
`;
```
