# Cloth

> The classic cloth: 1,040 points joined by springs. The mouse pokes it, dragging grabs and tears it, and shift cuts it.

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

**Move the mouse** over it to poke it, **click and drag** to grab it (pull too hard and the threads snap), **shift and drag** to cut it, and press **R** to hang a new one.

No physics engine: Verlet integration (a point's speed is where it is minus where it was) and springs relaxed a few times per step, in the example's own code. The step is fixed, 1/60 of a second, whatever the frame rate does.

The engine draws it with `useLines`, rewritten every frame, and `screenToRay` turns the mouse into a point on the cloth's plane through the camera. Each thread goes from white to red as it nears snapping.

## Code

`index.ts`:

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

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

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

`components/cloth.ts`:

```ts
import * as Settings from '../settings';
import { screenToRay, useGame, setLines, useLines, useKeyboard, usePointer, useUpdate, type TCamera3d } from 'nacatamalon';
import { createSheet, pinnedTop, type Sheet } from '../simulation/sheet';

/**
 * The cloth: Verlet integration (a point's speed is where it is minus where it was), springs
 * relaxed a few times per step, and the mouse turned into a point on the cloth's plane through
 * the camera. It is drawn as lines, one per thread, coloured by how stretched it is.
 *
 * It is handed the scene's camera rather than asking for one: a camera belongs to the scene, and
 * a second useCamera3d would be ignored.
 */
export const Cloth = (camera: TCamera3d) => {
    const game = useGame();
    const keys = useKeyboard();
    const pointer = usePointer();
    const lines = useLines();

    let sheet: Sheet = createSheet();
    let mouse: { x: number; y: number; } | null = null;
    let lastMouse: { x: number; y: number; } | null = null;
    let holding = false;
    let grabbed: { index: number; dx: number; dy: number; }[] = [];
    let time = 0;
    let backlog = 0;

    /** Where on the cloth's plane (z = 0) a point of the screen is. */
    const onPlane = (screenX: number, screenY: number) => {
        const ray = screenToRay(camera, game.getWidth(), game.getHeight(), screenX, screenY);
        const t = -ray.origin.z / ray.direction.z;

        return {
            x: ray.origin.x + ray.direction.x * t,
            y: ray.origin.y + ray.direction.y * t
        };
    };

    pointer.onMove((info) => {
        mouse = onPlane(info.screenX, info.screenY);
    });
    pointer.onDown((info) => {
        mouse = onPlane(info.screenX, info.screenY);
        holding = true;
        // Every point near the press is held, keeping its distance to the mouse.
        grabbed = [];

        if (keys.isDown('Shift')) {
            return;
        }

        for (let i = 0; i < sheet.count; i++) {
            const dx = sheet.x[i] - mouse.x;
            const dy = sheet.y[i] - mouse.y;

            if (Math.hypot(dx, dy, sheet.z[i]) < Settings.GRAB_RADIUS && !sheet.pinned[i]) {
                grabbed.push({
                    index: i,
                    dx,
                    dy
                });
            }
        }
    });
    pointer.onUp(() => {
        holding = false;
        grabbed = [];
    });

    const step = () => {
        time += Settings.STEP;

        const wind = Math.sin(time * 0.7) * 0.25 + Math.sin(time * 1.9) * 0.1;

        // Move every point by its own speed, plus gravity and a breeze.
        for (let i = 0; i < sheet.count; i++) {
            if (sheet.pinned[i]) {
                continue;
            }

            const vx = (sheet.x[i] - sheet.px[i]) * Settings.DAMPING;
            const vy = (sheet.y[i] - sheet.py[i]) * Settings.DAMPING;
            const vz = (sheet.z[i] - sheet.pz[i]) * Settings.DAMPING;

            sheet.px[i] = sheet.x[i];
            sheet.py[i] = sheet.y[i];
            sheet.pz[i] = sheet.z[i];
            sheet.x[i] += vx;
            sheet.y[i] += vy + Settings.GRAVITY * Settings.STEP * Settings.STEP;
            sheet.z[i] += vz + wind * Settings.STEP * Settings.STEP;
        }

        if (mouse !== null) {
            if (holding && keys.isDown('Shift')) {
                // Cutting: any thread whose middle passes under the mouse goes.
                for (const link of sheet.links) {
                    if (!link.alive) {
                        continue;
                    }

                    const mx = (sheet.x[link.a] + sheet.x[link.b]) / 2;
                    const my = (sheet.y[link.a] + sheet.y[link.b]) / 2;

                    if (Math.hypot(mx - mouse.x, my - mouse.y) < Settings.CUT_RADIUS) {
                        link.alive = false;
                    }
                }
            } else if (holding) {
                // Holding: the grabbed points follow the mouse, and drag the rest along.
                for (const hold of grabbed) {
                    sheet.x[hold.index] = mouse.x + hold.dx;
                    sheet.y[hold.index] = mouse.y + hold.dy;
                    sheet.z[hold.index] *= 0.5;
                }
            } else if (lastMouse !== null && (lastMouse.x !== mouse.x || lastMouse.y !== mouse.y)) {
                // Just passing over it: the points under the mouse are pushed back, harder at the middle.
                for (let i = 0; i < sheet.count; i++) {
                    const d = Math.hypot(sheet.x[i] - mouse.x, sheet.y[i] - mouse.y);

                    if (d < Settings.POKE_RADIUS && !sheet.pinned[i]) {
                        sheet.z[i] -= (1 - d / Settings.POKE_RADIUS) * 0.02;
                    }
                }
            }

            lastMouse = {
                ...mouse
            };
        }

        // Pull every thread back towards its length. Too long and it snaps.
        for (let pass = 0; pass < Settings.ITERATIONS; pass++) {
            for (const link of sheet.links) {
                if (!link.alive) {
                    continue;
                }

                const dx = sheet.x[link.b] - sheet.x[link.a];
                const dy = sheet.y[link.b] - sheet.y[link.a];
                const dz = sheet.z[link.b] - sheet.z[link.a];
                const length = Math.hypot(dx, dy, dz) || 1e-6;

                if (length > link.rest * Settings.TEAR) {
                    link.alive = false;
                    continue;
                }

                const push = (length - link.rest) / length;
                const pa = sheet.pinned[link.a] ? 0 : sheet.pinned[link.b] ? 1 : 0.5;
                const pb = sheet.pinned[link.b] ? 0 : sheet.pinned[link.a] ? 1 : 0.5;

                sheet.x[link.a] += dx * push * pa;
                sheet.y[link.a] += dy * push * pa;
                sheet.z[link.a] += dz * push * pa;
                sheet.x[link.b] -= dx * push * pb;
                sheet.y[link.b] -= dy * push * pb;
                sheet.z[link.b] -= dz * push * pb;
            }
        }
    };

    // Seven numbers per corner (x, y, z, r, g, b, a), two corners per thread: one buffer, reused.
    const vertices = new Float32Array(sheet.links.length * 14);

    useUpdate((delta) => {
        if (keys.justPressed('r')) {
            sheet = createSheet();
        }

        // Fixed steps, however long the frame was, and never more than a few to catch up.
        backlog = Math.min(backlog + delta, Settings.STEP * 4);

        while (backlog >= Settings.STEP) {
            step();
            backlog -= Settings.STEP;
        }

        let n = 0;

        for (const link of sheet.links) {
            if (!link.alive) {
                continue;
            }

            const length = Math.hypot(sheet.x[link.b] - sheet.x[link.a], sheet.y[link.b] - sheet.y[link.a], sheet.z[link.b] - sheet.z[link.a]);
            // White at rest, through amber, to red as it nears snapping.
            // A thread gives a little before it snaps, so full red is a quarter over its length.
            const strain = Math.min(1, Math.max(0, (length / link.rest - 1) * 4));
            const r = 0.9;
            const g = 0.9 - strain * 0.75;
            const b = 0.95 - strain * 0.9;
            const top = pinnedTop(link) ? 0.55 : 1;

            for (const i of [link.a, link.b]) {
                vertices[n++] = sheet.x[i];
                vertices[n++] = sheet.y[i];
                vertices[n++] = sheet.z[i];
                vertices[n++] = r * top;
                vertices[n++] = g * top;
                vertices[n++] = b;
                vertices[n++] = 1;
            }
        }

        setLines(lines, vertices.subarray(0, n));
    });
};
```

`scenes/demo.ts`:

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

import { Cloth } from '../components/cloth';

export const Lab = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            y: -0.2,
            z: 4.2
        }
    });

    useSpawn(Cloth)(camera);

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const STEP = 1 / 60; // the simulation runs at a fixed rate, whatever the screen's
export const GRAVITY = -3.2; // units per second squared
export const DAMPING = 0.985; // how much speed a point keeps from one step to the next
export const ITERATIONS = 4; // how many times the springs are relaxed per step: stiffer with more
export const TEAR = 2.6; // a thread snaps when stretched to this many times its length
export const POKE_RADIUS = 0.35;
export const GRAB_RADIUS = 0.22;
export const CUT_RADIUS = 0.07;
export const COLUMNS = 40;
export const ROWS = 26;
export const GAP = 0.085;
```

`simulation/sheet.ts`:

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

/** Two points joined by a thread, and the length the thread wants to be. */
export type Link = { a: number; b: number; rest: number; alive: boolean; };

/**
 * The cloth's points as flat arrays (where they are, and where they were a step ago, which is
 * their speed), which of them are nailed to the top, and the threads between neighbours.
 */
export type Sheet = {
    count: number;
    x: Float32Array; y: Float32Array; z: Float32Array;
    px: Float32Array; py: Float32Array; pz: Float32Array;
    pinned: Uint8Array;
    links: Link[];
};

/** A fresh sheet, hanging from every fourth point of its top row. */
export const createSheet = (): Sheet => {
    const count = Settings.COLUMNS * Settings.ROWS;

    const sheet: Sheet = {
        count,
        x: new Float32Array(count),
        y: new Float32Array(count),
        z: new Float32Array(count),
        px: new Float32Array(count),
        py: new Float32Array(count),
        pz: new Float32Array(count),
        pinned: new Uint8Array(count),
        links: [],
    };

    const left = -((Settings.COLUMNS - 1) * Settings.GAP) / 2;
    const top = 1.25;

    for (let row = 0; row < Settings.ROWS; row++) {
        for (let column = 0; column < Settings.COLUMNS; column++) {
            const i = row * Settings.COLUMNS + column;

            sheet.x[i] = sheet.px[i] = left + column * Settings.GAP;
            sheet.y[i] = sheet.py[i] = top - row * Settings.GAP;

            if (row === 0 && (column % 4 === 0 || column === Settings.COLUMNS - 1)) {
                sheet.pinned[i] = 1;
            }

            if (column > 0) {
                sheet.links.push({
                    a: i - 1,
                    b: i,
                    rest: Settings.GAP,
                    alive: true
                });
            }

            if (row > 0) {
                sheet.links.push({
                    a: i - Settings.COLUMNS,
                    b: i,
                    rest: Settings.GAP,
                    alive: true
                });
            }
        }
    }

    return sheet;
};

/** Whether a thread is part of the top edge, drawn a little darker so the nails read. */
export const pinnedTop = (link: Link): boolean => link.a < Settings.COLUMNS && link.b < Settings.COLUMNS;
```
