# Boids

> A shoal of 450 fish with no leader, following three rules. The mouse is a predator and a click drops food.

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

Each fish looks only at its neighbours and follows three rules: keep your distance, swim the way they swim, stay with them. **Move the mouse** and it becomes a predator the shoal parts around; **click** to drop food.

Craig Reynolds' boids (1986), in the example's own code, with a grid of buckets so each fish only checks the fish around it. The engine's part is 450 sprites turned and tinted every frame: each fish is coloured by its heading, so streams read as bands of colour.

Try changing `SEPARATION`, `ALIGNMENT` and `COHESION`: more cohesion and it balls up, more alignment and it streams, more separation and it spreads into a haze.

## Code

`index.ts`:

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

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

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

`art/paint.ts`:

```ts
// The pictures, drawn on canvases and loaded as data URLs.

const canvasOf = (width: number, height: number) => {
    const canvas = document.createElement('canvas');

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

    return {
        canvas,
        g: canvas.getContext('2d')!
    };
};

/** A white fish facing right: the tint gives it its colour. */
export const drawFish = () => {
    const { canvas, g } = canvasOf(28, 14);

    g.fillStyle = '#ffffff';
    g.beginPath();
    g.ellipse(16, 7, 11, 5.5, 0, 0, Math.PI * 2);
    g.fill();
    g.beginPath();
    g.moveTo(7, 7);
    g.lineTo(0, 1);
    g.lineTo(2, 7);
    g.lineTo(0, 13);
    g.closePath();
    g.fill();
    g.fillStyle = 'rgba(0,0,0,0.25)';
    g.fillRect(8, 8, 18, 3);
    g.fillStyle = '#0b1320';
    g.fillRect(21, 5, 2, 2);

    return canvas;
};

export const drawFood = () => {
    const { canvas, g } = canvasOf(8, 8);

    g.fillStyle = '#e7b35a';
    g.beginPath();
    g.arc(4, 4, 3.5, 0, Math.PI * 2);
    g.fill();

    return canvas;
};

/** Deep water: darker downwards, and a few shafts of light slanting in from the surface. */
export const drawSea = (width: number, height: number) => {
    const { canvas, g } = canvasOf(width, height);
    const depth = g.createLinearGradient(0, 0, 0, height);

    depth.addColorStop(0, '#0e4a6e');
    depth.addColorStop(1, '#020b16');
    g.fillStyle = depth;
    g.fillRect(0, 0, width, height);
    g.globalCompositeOperation = 'lighter';

    for (let i = 0; i < 6; i++) {
        const x = 40 + i * 80 + Math.sin(i * 3.1) * 25;
        const shaft = g.createLinearGradient(0, 0, 0, height);

        shaft.addColorStop(0, 'rgba(120,200,255,0.10)');
        shaft.addColorStop(1, 'rgba(120,200,255,0)');
        g.fillStyle = shaft;
        g.beginPath();
        g.moveTo(x, 0);
        g.lineTo(x + 26, 0);
        g.lineTo(x - 50, height);
        g.lineTo(x - 100, height);
        g.closePath();
        g.fill();
    }

    return canvas;
};
```

`components/shoal.ts`:

```ts
import * as Settings from '../settings';
import { createSprite, fromHsl, useGame, useLoadTexture, usePointer, useUpdate, type TSprite } from 'nacatamalon';
import { drawFish, drawFood, drawSea } from '../art/paint';

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

    const fishPicture = useLoadTexture({
        src: drawFish().toDataURL(),
        key: 'boids-fish'
    });

    const foodPicture = useLoadTexture({
        src: drawFood().toDataURL(),
        key: 'boids-food'
    });

    createSprite({
        texture: useLoadTexture({
            src: drawSea(W, H).toDataURL(),
            key: 'boids-sea'
        }),
        width: W,
        height: H,
        transform: {
            x: W / 2,
            y: H / 2
        },
        zIndex: -10
    });

    // The fish's state lives in flat arrays; the sprites only show it.
    const x = new Float32Array(Settings.FISH);
    const y = new Float32Array(Settings.FISH);
    const vx = new Float32Array(Settings.FISH);
    const vy = new Float32Array(Settings.FISH);
    const sprites: TSprite[] = [];

    for (let i = 0; i < Settings.FISH; i++) {
        x[i] = Math.random() * W;
        y[i] = Math.random() * H;

        const a = Math.random() * Math.PI * 2;

        vx[i] = Math.cos(a) * Settings.MIN_SPEED;
        vy[i] = Math.sin(a) * Settings.MIN_SPEED;

        const size = 0.8 + Math.random() * 0.5;

        sprites.push(createSprite({
            texture: fishPicture,
            width: 14 * size,
            height: 7 * size
        }));
    }

    // Food: a few pellets at a time, sinking. The pellets are made here, hidden, and reused: a
    // click happens outside the scene's body, where nothing can be created, so it only takes one.
    type Pellet = { x: number; y: number; sprite: TSprite; };

    const spare: TSprite[] = [];

    for (let k = 0; k < 60; k++) {
        spare.push(createSprite({
            texture: foodPicture,
            width: 4,
            height: 4,
            zIndex: 1,
            visible: false
        }));
    }

    const food: Pellet[] = [];

    pointer.onDown((info) => {
        for (let k = 0; k < 6 && spare.length > 0; k++) {
            const sprite = spare.pop()!;

            sprite.visible = true;
            food.push({
                x: info.screenX + (Math.random() - 0.5) * 24,
                y: info.screenY + (Math.random() - 0.5) * 12,
                sprite
            });
        }
    });

    let predator: { x: number; y: number; } | null = null;

    pointer.onMove((info) => {
        predator = {
            x: info.screenX,
            y: info.screenY
        };
    });

    // A grid of buckets, so a fish only looks at the fish in its own bucket and the eight around it.
    // Without it every fish would look at every other: 200,000 checks a frame instead of a few thousand.
    const COLS = Math.ceil(W / Settings.SEE);
    const ROWS = Math.ceil(H / Settings.SEE);
    const heads = new Int32Array(COLS * ROWS);
    const next = new Int32Array(Settings.FISH);

    const bucketOf = (px: number, py: number) =>
        Math.min(ROWS - 1, Math.max(0, Math.floor(py / Settings.SEE))) * COLS + Math.min(COLS - 1, Math.max(0, Math.floor(px / Settings.SEE)));

    let time = 0;

    useUpdate((rawDelta) => {
        const delta = Math.min(rawDelta, 1 / 30);

        time += delta;

        heads.fill(-1);

        for (let i = 0; i < Settings.FISH; i++) {
            const b = bucketOf(x[i], y[i]);

            next[i] = heads[b];
            heads[b] = i;
        }

        for (let i = 0; i < Settings.FISH; i++) {
            let sepX = 0, sepY = 0, aliX = 0, aliY = 0, cohX = 0, cohY = 0, seen = 0;
            const col = Math.floor(x[i] / Settings.SEE);
            const row = Math.floor(y[i] / Settings.SEE);

            for (let r = row - 1; r <= row + 1; r++) {
                if (r < 0 || r >= ROWS) {
                    continue;
                }

                for (let c = col - 1; c <= col + 1; c++) {
                    if (c < 0 || c >= COLS) {
                        continue;
                    }

                    for (let j = heads[r * COLS + c]; j !== -1; j = next[j]) {
                        if (j === i) {
                            continue;
                        }

                        const dx = x[j] - x[i];
                        const dy = y[j] - y[i];
                        const d2 = dx * dx + dy * dy;

                        if (d2 > Settings.SEE * Settings.SEE) {
                            continue;
                        }

                        seen++;
                        aliX += vx[j];
                        aliY += vy[j];
                        cohX += dx;
                        cohY += dy;

                        if (d2 < Settings.PERSONAL * Settings.PERSONAL && d2 > 0) {
                            // Pushed away, harder the closer.
                            sepX -= dx / d2 * Settings.PERSONAL;
                            sepY -= dy / d2 * Settings.PERSONAL;
                        }
                    }
                }
            }

            let ax = sepX * Settings.SEPARATION * 10;
            let ay = sepY * Settings.SEPARATION * 10;

            if (seen > 0) {
                ax += (aliX / seen - vx[i]) * Settings.ALIGNMENT + (cohX / seen) * Settings.COHESION;
                ay += (aliY / seen - vy[i]) * Settings.ALIGNMENT + (cohY / seen) * Settings.COHESION;
            }

            // Fear beats everything else.
            if (predator !== null) {
                const dx = x[i] - predator.x;
                const dy = y[i] - predator.y;
                const d = Math.hypot(dx, dy);

                if (d < Settings.FEAR && d > 0) {
                    const push = (1 - d / Settings.FEAR) * 900;

                    ax += dx / d * push;
                    ay += dy / d * push;
                }
            }

            // Then hunger: the nearest pellet it can smell.
            let best: Pellet | null = null;
            let bestD = Settings.HUNGER;

            for (const pellet of food) {
                const d = Math.hypot(pellet.x - x[i], pellet.y - y[i]);

                if (d < bestD) {
                    bestD = d;
                    best = pellet;
                }
            }

            if (best !== null) {
                ax += (best.x - x[i]) / bestD * 180;
                ay += (best.y - y[i]) / bestD * 180;
            }

            // And the walls of the tank: turn back before reaching them rather than bounce.
            if (x[i] < Settings.MARGIN) {
                ax += (Settings.MARGIN - x[i]) * 8;
            }

            if (x[i] > W - Settings.MARGIN) {
                ax -= (x[i] - (W - Settings.MARGIN)) * 8;
            }

            if (y[i] < Settings.MARGIN) {
                ay += (Settings.MARGIN - y[i]) * 8;
            }

            if (y[i] > H - Settings.MARGIN) {
                ay -= (y[i] - (H - Settings.MARGIN)) * 8;
            }

            vx[i] += ax * delta;
            vy[i] += ay * delta;

            const speed = Math.hypot(vx[i], vy[i]) || 1;
            const clamped = Math.min(Settings.MAX_SPEED, Math.max(Settings.MIN_SPEED, speed));

            vx[i] *= clamped / speed;
            vy[i] *= clamped / speed;
        }

        for (let i = 0; i < Settings.FISH; i++) {
            x[i] += vx[i] * delta;
            y[i] += vy[i] * delta;

            const sprite = sprites[i];
            const heading = Math.atan2(vy[i], vx[i]);

            sprite.transform.x = x[i];
            sprite.transform.y = y[i];
            // A little wiggle, faster when swimming faster.
            sprite.transform.rotation = heading + Math.sin(time * 14 + i) * 0.08;
            // Coloured by the way it is heading, so streams of fish read as bands of colour.
            sprite.tint = fromHsl(((heading / Math.PI) * 180 + 360 + time * 10) % 360, 0.7, 0.62);
        }

        // Food sinks, and a fish that reaches a pellet eats it.
        for (let k = food.length - 1; k >= 0; k--) {
            const pellet = food[k];

            pellet.y += 14 * delta;
            pellet.x += Math.sin(time * 2 + k) * 6 * delta;

            let eaten = pellet.y > H;
            const b = bucketOf(pellet.x, pellet.y);

            for (let j = heads[b]; j !== -1 && !eaten; j = next[j]) {
                if (Math.hypot(x[j] - pellet.x, y[j] - pellet.y) < 6) {
                    eaten = true;
                }
            }

            if (eaten) {
                pellet.sprite.visible = false;
                spare.push(pellet.sprite);
                food.splice(k, 1);
            } else {
                pellet.sprite.transform.x = pellet.x;
                pellet.sprite.transform.y = pellet.y;
            }
        }
    });
};
```

`scenes/demo.ts`:

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

import { Shoal } from '../components/shoal';

export const Sea = () => {
    useSpawn(Shoal)();

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const FISH = 450;
export const SEE = 38; // how far a fish looks for company
export const PERSONAL = 12; // closer than this is too close
export const MIN_SPEED = 55;
export const MAX_SPEED = 120;
export const FEAR = 90; // how close the predator has to come
export const HUNGER = 160; // how far a fish smells the food
export const MARGIN = 36; // how early a fish turns back from the edge

// How much each rule pulls. Change them and the shoal changes character: more cohesion and it
// balls up, more alignment and it streams, more separation and it spreads into a haze.
export const SEPARATION = 5.5;
export const ALIGNMENT = 1.4;
export const COHESION = 0.9;
```
