# Tentacles

> A creature with eight arms of 24 joints, solved by inverse kinematics: they reach for the mouse, and a click sends it swimming.

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

**Move the mouse** and the arms that can reach it reach for it while the rest curl and drift; **click** and it swims there, its arms trailing behind.

Nobody animates an arm. Each is told where its tip should be, and FABRIK (inverse kinematics: one pass from the tip and one from the base each frame) works out every joint.

It is all the example's own code; the engine draws about 200 tinted discs.

## Code

`index.ts`:

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

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

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

`art/disc.ts`:

```ts
export const disc = () => {
    const canvas = document.createElement('canvas');

    canvas.width = canvas.height = 32;

    const g = canvas.getContext('2d')!;
    const shade = g.createRadialGradient(12, 11, 2, 16, 16, 16);

    shade.addColorStop(0, '#ffffff');
    shade.addColorStop(0.8, '#d9d9d9');
    shade.addColorStop(1, 'rgba(200,200,200,0)');
    g.fillStyle = shade;
    g.beginPath();
    g.arc(16, 16, 16, 0, Math.PI * 2);
    g.fill();

    return canvas.toDataURL();
};
```

`components/creature.ts`:

```ts
import { disc } from '../art/disc';
import * as Settings from '../settings';
import { createSprite, getColor, lerpColor, useGame, useLoadTexture, usePointer, useUpdate, type TSprite } from 'nacatamalon';
import { reach } from '../simulation/fabrik';

/** A soft white disc: every joint, the body and the eyes are this one picture, tinted. */
export const Creature = () => {
    const game = useGame();
    const pointer = usePointer();
    const W = game.getWidth();
    const H = game.getHeight();

    const picture = useLoadTexture({
        src: disc(),
        key: 'tentacle-disc'
    });

    const root = getColor('#7a2d8f');
    const tip = getColor('#ff9ec4');

    const body = {
        x: W / 2,
        y: H / 2,
        vx: 0,
        vy: 0
    };

    let goal = {
        x: body.x,
        y: body.y
    };
    let mouse: { x: number; y: number; } | null = null;

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

    // Each arm: its joints, where its tip is heading, and a sprite per joint. The arms are drawn
    // under the body, and their thin ends under their thick ones.
    const arms = Array.from({
        length: Settings.ARMS
    }, (_, a) => {
        const angle = (a / Settings.ARMS) * Math.PI * 2;
        const xs = new Float32Array(Settings.JOINTS + 1);
        const ys = new Float32Array(Settings.JOINTS + 1);

        for (let j = 0; j <= Settings.JOINTS; j++) {
            xs[j] = body.x + Math.cos(angle) * j * Settings.LINK;
            ys[j] = body.y + Math.sin(angle) * j * Settings.LINK;
        }

        const sprites: TSprite[] = [];

        for (let j = 0; j <= Settings.JOINTS; j++) {
            const t = j / Settings.JOINTS;
            const size = 16 * (1 - t) + 3;

            sprites.push(createSprite({
                texture: picture,
                width: size,
                height: size,
                tint: lerpColor(root, tip, t),
                zIndex: -j
            }));
        }

        return {
            angle,
            xs,
            ys,
            sprites,
            target: {
                x: xs[Settings.JOINTS],
                y: ys[Settings.JOINTS]
            },
            phase: a * 1.3
        };
    });

    const shell = createSprite({
        texture: picture,
        width: Settings.BODY * 2.2,
        height: Settings.BODY * 2,
        tint: '#9d46b5',
        zIndex: 10
    });

    const eyes = [-1, 1].map((side) => ({
        side,
        white: createSprite({
            texture: picture,
            width: 13,
            height: 13,
            tint: '#fff6e8',
            zIndex: 12
        }),
        pupil: createSprite({
            texture: picture,
            width: 6,
            height: 6,
            tint: '#120418',
            zIndex: 13
        }),
    }));

    let time = 0;

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

        time += delta;

        // Swimming: a pull towards the goal, and water that slows everything.
        body.vx += (goal.x - body.x) * 2.2 * delta;
        body.vy += (goal.y - body.y) * 2.2 * delta;
        body.vx *= 1 - 2.5 * delta;
        body.vy *= 1 - 2.5 * delta;
        body.x += body.vx * delta;
        body.y += body.vy * delta + Math.sin(time * 1.6) * 0.15;

        const stretch = Math.min(0.25, Math.hypot(body.vx, body.vy) / 600);

        shell.transform.x = body.x;
        shell.transform.y = body.y;
        shell.transform.rotation = Math.atan2(body.vy, body.vx);
        shell.transform.scaleX = 1 + stretch;
        shell.transform.scaleY = 1 - stretch;

        for (const arm of arms) {
            // Where the arm starts, on the edge of the body.
            const baseX = body.x + Math.cos(arm.angle) * Settings.BODY * 0.7;
            const baseY = body.y + Math.sin(arm.angle) * Settings.BODY * 0.6;

            // What its tip wants: the mouse, when it is in reach and on this arm's side; otherwise a
            // lazy curl that trails behind as the creature swims.
            let wantX: number;
            let wantY: number;
            const toMouse = mouse === null ? Infinity : Math.hypot(mouse.x - baseX, mouse.y - baseY);
            const facing = mouse === null ? -1 : ((mouse.x - baseX) * Math.cos(arm.angle) + (mouse.y - baseY) * Math.sin(arm.angle)) / (toMouse || 1);

            if (mouse !== null && toMouse < Settings.REACH * 0.95 && facing > -0.2) {
                wantX = mouse.x;
                wantY = mouse.y;
            } else {
                const sway = arm.angle + Math.sin(time * 1.3 + arm.phase) * 0.6;
                const length = Settings.REACH * (0.62 + 0.12 * Math.sin(time * 0.9 + arm.phase));

                wantX = baseX + Math.cos(sway) * length - body.vx * 0.25;
                wantY = baseY + Math.sin(sway) * length - body.vy * 0.25;
            }

            arm.target.x += (wantX - arm.target.x) * Math.min(1, delta * 7);
            arm.target.y += (wantY - arm.target.y) * Math.min(1, delta * 7);

            reach(arm.xs, arm.ys, Settings.LINK, baseX, baseY, arm.target.x, arm.target.y);

            for (let j = 0; j <= Settings.JOINTS; j++) {
                arm.sprites[j].transform.x = arm.xs[j];
                arm.sprites[j].transform.y = arm.ys[j];
            }
        }

        // The eyes follow the mouse.
        const lookX = mouse === null ? 0 : Math.max(-1, Math.min(1, (mouse.x - body.x) / 120));
        const lookY = mouse === null ? 0 : Math.max(-1, Math.min(1, (mouse.y - body.y) / 120));

        for (const eye of eyes) {
            const ex = body.x + eye.side * 11;
            const ey = body.y - 6;

            eye.white.transform.x = ex;
            eye.white.transform.y = ey;
            eye.pupil.transform.x = ex + lookX * 3;
            eye.pupil.transform.y = ey + lookY * 3;
        }
    });
};
```

`scenes/demo.ts`:

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

import { Creature } from '../components/creature';

export const Deep = () => {
    useSpawn(Creature)();

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const ARMS = 8;
export const JOINTS = 24;
export const LINK = 5.2; // pixels between two joints
export const REACH = JOINTS * LINK;
export const BODY = 26;
```

`simulation/fabrik.ts`:

```ts
/**
 * FABRIK (Forward And Backward Reaching Inverse Kinematics, Aristidou and Lasenby, 2011).
 *
 * A chain of joints a fixed length apart has to start at its base and end as near the target as it
 * can. Walk it from the tip, putting the tip on the target and dragging every joint after it at the
 * right distance; then walk it from the base, putting the base back and dragging the other way. One
 * of each is already close; a creature redoes it every frame, so it never needs more than that.
 */
export const reach = (
    xs: Float32Array, ys: Float32Array, link: number,
    baseX: number, baseY: number, targetX: number, targetY: number,
): void => {
    const last = xs.length - 1;

    // Backwards: the tip to the target.
    xs[last] = targetX;
    ys[last] = targetY;

    for (let j = last - 1; j >= 0; j--) {
        const dx = xs[j] - xs[j + 1];
        const dy = ys[j] - ys[j + 1];
        const d = Math.hypot(dx, dy) || 1;

        xs[j] = xs[j + 1] + (dx / d) * link;
        ys[j] = ys[j + 1] + (dy / d) * link;
    }

    // Forwards: the base back where it belongs.
    xs[0] = baseX;
    ys[0] = baseY;

    for (let j = 1; j <= last; j++) {
        const dx = xs[j] - xs[j - 1];
        const dy = ys[j] - ys[j - 1];
        const d = Math.hypot(dx, dy) || 1;

        xs[j] = xs[j - 1] + (dx / d) * link;
        ys[j] = ys[j - 1] + (dy / d) * link;
    }
};
```
