# A roulette wheel

> Pockets as lathe slices merged in their colours, rounded separators, extruded diamonds; click a pocket to bet, with castRay on the turning wheel.

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

**Click** a pocket to bet on it, and press **space** to throw the ball.

Everything here is made from the engine's shape hooks. One pocket is a slice of a flat ring, a `useLatheGeometry` turned a 37th of the way round; thirty-seven of them, each turned to its place with its colour painted on, are made one shape with `mergeGeometries`: one draw for the whole ring. The separators are small boxes with their edges rounded (`useCubeGeometry` with a `bevel`), and the turret in the middle is a lathe whose edges stay hard where its profile turns sharply.

The click is a `castRay` from the pointer into the scene. It meets the wheel as it is drawn, turning, and the triangle it hits says which pocket it is in.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Table } from './scenes/demo';
import { ACTIONS, HEIGHT, WIDTH } from './settings';

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: '#0c1a12',
    actions: ACTIONS
});

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

`components/ball.ts`:

```ts
import { createMaterial, createMesh, pearl, useSphereGeometry, useUpdate } from 'nacatamalon';
import type { TTexture } from 'nacatamalon';
import type { TWheel } from './wheel';
import { BALL, NUMBERS, STEP, WHEEL } from '../settings';

type TState = 'resting' | 'running' | 'dropping';

// The ball: thrown round the bowl against the wheel, slowing, dropping into a pocket and turning
// with the wheel there. Its angle goes the way `rotationY` does, as the pockets' do.
export const Ball = (studio: TTexture, wheel: TWheel) => {
    const ball = createMesh({
        geometry: useSphereGeometry({
            radius: BALL.radius,
            segments: 16,
            rings: 12
        }),
        material: createMaterial(pearl({
            tint: '#f4f1ea',
            environment: studio
        }))
    });

    const listeners: ((number: number) => void)[] = [];
    let state: TState = 'resting';
    let angle = 0;
    let speed = 0;
    let dropped = 0;
    // Where in the wheel it rests, once it has landed.
    let inPocket = STEP / 2;
    const pocketRadius = (WHEEL.pocketsOuter + WHEEL.pocketsInner) / 2;

    const place = (radius: number, y: number) => {
        ball.transform.x = Math.cos(angle) * radius;
        ball.transform.y = y;
        ball.transform.z = -Math.sin(angle) * radius;
    };

    useUpdate((delta) => {
        if (state === 'resting') {
            angle = wheel.angle() + inPocket;
            place(pocketRadius, WHEEL.pocketsY + BALL.radius);

            return;
        }

        // Against the wheel's turn, slowing as it rolls.
        speed = Math.max(0, speed - BALL.slowing * delta * speed);
        angle -= speed * delta;

        if (state === 'running') {
            place(BALL.trackRadius, BALL.trackY);

            if (speed < BALL.dropSpeed) {
                state = 'dropping';
                dropped = 0;
            }

            return;
        }

        dropped = Math.min(1, dropped + delta / BALL.dropTime);

        const t = dropped * dropped;

        place(BALL.trackRadius + (pocketRadius - BALL.trackRadius) * t, BALL.trackY + (WHEEL.pocketsY + BALL.radius - BALL.trackY) * t);

        if (dropped === 1) {
            // The pocket it is over, counted round the wheel from the zero.
            const round = Math.PI * 2;
            const there = (((angle - wheel.angle()) % round) + round) % round;
            const pocket = Math.floor(there / STEP);

            inPocket = (pocket + 0.5) * STEP;
            state = 'resting';

            for (const listener of listeners) {
                listener(NUMBERS[pocket]!);
            }
        }
    });

    return {
        // Tells `listener` the number of each pocket it lands in.
        onLand: (listener: (number: number) => void) => {
            listeners.push(listener);
        },
        spin: () => {
            if (state !== 'resting') {
                return false;
            }

            state = 'running';
            speed = BALL.speed;

            return true;
        }
    };
};

export type TBall = ReturnType<typeof Ball>;
```

`components/bowl.ts`:

```ts
import { createMaterial, createMesh, gold, mergeGeometries, useExtrudeGeometry, useLatheGeometry } from 'nacatamalon';
import type { TTexture } from 'nacatamalon';

// What stands still: the wooden bowl the ball runs round, and the gold diamonds on its slope that
// knock it about. Eight diamonds are one shape, so one draw.
export const Bowl = (studio: TTexture) => {
    createMesh({
        geometry: useLatheGeometry({
            // From the outside wall up over the rim and down the slope to the pockets; each piece
            // faces out of the wood. Its corners are hard, the slope is one smooth sweep.
            profile: [
                {
                    x: 2.3,
                    y: 0
                },
                {
                    x: 2.3,
                    y: 0.55
                },
                {
                    x: 2.18,
                    y: 0.68
                },
                {
                    x: 1.65,
                    y: 0.24
                }
            ],
            segments: 64,
            creaseAngle: Math.PI / 6
        }),
        material: createMaterial({
            shader: 'mesh3d',
            tint: '#5a3620',
            specular: '#3a2a20',
            shininess: 24,
            perPixel: true
        })
    });

    const diamond = useExtrudeGeometry({
        outline: [
            {
                x: 0,
                y: 0.9
            },
            {
                x: 0.45,
                y: 0
            },
            {
                x: 0,
                y: -0.9
            },
            {
                x: -0.45,
                y: 0
            }
        ],
        depth: 0.3,
        bevel: {
            size: 0.08,
            segments: 2
        }
    });

    createMesh({
        geometry: mergeGeometries(Array.from({
            length: 8
        }, (_, i) => {
            const angle = (i / 8) * Math.PI * 2;

            return {
                geometry: diamond,
                x: Math.cos(angle) * 1.95,
                y: 0.51,
                z: -Math.sin(angle) * 1.95,
                // Turned to face the middle, then laid back on the slope, its point up the bowl.
                rotationY: angle - Math.PI / 2,
                rotationX: -0.96,
                scale: 0.13
            };
        })),
        material: createMaterial(gold({
            environment: studio
        }))
    });
};
```

`components/hud.ts`:

```ts
import { castRay, createText, screenToRay, useAction, useGame, useLoadBitmapFont, usePointer, useScreenSpace, useUpdate } from 'nacatamalon';
import type { TCamera3d } from 'nacatamalon';
import type { TBall } from './ball';
import type { TWheel } from './wheel';
import { HEIGHT, NUMBERS, RED } from '../settings';

const FONT = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
};

const nameOf = (number: number) => number + (number === 0 ? ' GREEN' : RED.has(number) ? ' RED' : ' BLACK');

// Bets by clicking a pocket: a ray from the pointer, met against the wheel as it is drawn, turning.
// The triangle it meets says which of the thirty-seven slices of the one shape it is in.
export const Hud = (camera: TCamera3d, wheel: TWheel, ball: TBall) => {
    useScreenSpace();

    const font = useLoadBitmapFont(FONT);
    const game = useGame();
    const pointer = usePointer();
    const spin = useAction('spin');
    let bet: number | null = null;

    const pointing = createText({
        text: '',
        font,
        tint: '#bfe6c8',
        transform: {
            x: 8,
            y: 8
        }
    });

    const betText = createText({
        text: 'CLICK A POCKET TO BET',
        font,
        transform: {
            x: 8,
            y: 22
        }
    });

    const result = createText({
        text: '',
        font,
        tint: '#ffd75e',
        transform: {
            x: 8,
            y: 36
        }
    });

    createText({
        text: 'SPACE: THROW THE BALL',
        font,
        tint: '#7c9a86',
        transform: {
            x: 8,
            y: HEIGHT - 18
        }
    });

    const pocketAt = (screenX: number, screenY: number): number | null => {
        const ray = screenToRay(camera, game.getWidth(), game.getHeight(), screenX, screenY);
        const hit = castRay(ray, wheel.box)[0];

        if (hit === undefined || hit.mesh !== wheel.pockets) {
            return null;
        }

        return NUMBERS[Math.floor(hit.triangle / wheel.trianglesPerPocket)]!;
    };

    pointer.onDown((info) => {
        const number = pocketAt(info.screenX, info.screenY);

        if (number !== null) {
            bet = number;
            betText.text = 'BET ON ' + nameOf(number);
        }
    });

    useUpdate(() => {
        const at = pointer.position();
        const number = at === null ? null : pocketAt(at.screenX, at.screenY);

        pointing.text = number === null ? '' : 'POINTING AT ' + nameOf(number);

        if (spin.justPressed() && ball.spin()) {
            result.text = 'NO MORE BETS';
        }
    });

    ball.onLand((number) => {
        result.text = nameOf(number) + (bet === null ? '' : bet === number ? ': YOU WIN' : ': YOU LOSE');
    });
};
```

`components/wheel.ts`:

```ts
import { createMaterial, createMesh, gold, mergeGeometries, useCubeGeometry, useLatheGeometry, useSelf, useTransform, useUpdate } from 'nacatamalon';
import type { TTexture } from 'nacatamalon';
import { COLORS, NUMBERS, RED, STEP, WHEEL } from '../settings';

// What turns: the pockets, the separators between them and the turret in the middle.
export const Wheel = (studio: TTexture) => {
    const place = useTransform({
    });

    const self = useSelf();

    // One pocket is a slice of a flat ring, a lathe turned a 37th of the way round. Thirty-seven of
    // them, each turned to its place with its colour painted on, are one shape: one draw.
    const pocket = useLatheGeometry({
        profile: [
            {
                x: WHEEL.pocketsOuter,
                y: WHEEL.pocketsY
            },
            {
                x: WHEEL.pocketsInner,
                y: WHEEL.pocketsY
            }
        ],
        arc: STEP,
        segments: 1
    });

    const pockets = createMesh({
        geometry: mergeGeometries(NUMBERS.map((number, i) => ({
            geometry: pocket,
            rotationY: i * STEP,
            tint: number === 0 ? COLORS.green : RED.has(number) ? COLORS.red : COLORS.black
        }))),
        material: createMaterial({
            shader: 'mesh3d',
            specular: '#404040',
            shininess: 30,
            perPixel: true
        })
    });

    // A separator on every line between two pockets: a small box with its edges rounded off.
    const separator = useCubeGeometry({
        width: WHEEL.separator.length,
        height: WHEEL.separator.height,
        depth: WHEEL.separator.width,
        bevel: {
            size: 0.015,
            segments: 2
        }
    });

    const middle = (WHEEL.pocketsOuter + WHEEL.pocketsInner) / 2;

    createMesh({
        geometry: mergeGeometries(NUMBERS.map((_, i) => ({
            geometry: separator,
            x: Math.cos(i * STEP) * middle,
            y: WHEEL.pocketsY + WHEEL.separator.height / 2,
            z: -Math.sin(i * STEP) * middle,
            // Its length along the line out from the middle.
            rotationY: i * STEP
        }))),
        material: createMaterial(gold({
            environment: studio
        }))
    });

    // The turret: a dome and a handle, its edges hard where the profile turns sharply.
    createMesh({
        geometry: useLatheGeometry({
            profile: [
                {
                    x: WHEEL.pocketsInner,
                    y: WHEEL.pocketsY
                },
                {
                    x: 0.9,
                    y: 0.34
                },
                {
                    x: 0.35,
                    y: 0.46
                },
                {
                    x: 0.12,
                    y: 0.62
                },
                {
                    x: 0.1,
                    y: 0.95
                },
                {
                    x: 0.22,
                    y: 1.05
                },
                {
                    x: 0,
                    y: 1.12
                }
            ],
            segments: 48,
            creaseAngle: Math.PI / 6
        }),
        material: createMaterial(gold({
            environment: studio
        }))
    });

    useUpdate((delta) => {
        place.rotationY += delta * WHEEL.turnSpeed;
    });

    return {
        box: self,
        pockets,
        // How many triangles each pocket is, so a triangle met says which pocket it is in.
        trianglesPerPocket: pocket.indexCount / 3,
        angle: () => place.rotationY
    };
};

export type TWheel = ReturnType<typeof Wheel>;
```

`scenes/demo.ts`:

```ts
import { cameraLookAt, createScene, useCamera3d, useSpawn, useStudio } from 'nacatamalon';
import { Ball } from '../components/ball';
import { Bowl } from '../components/bowl';
import { Hud } from '../components/hud';
import { Wheel } from '../components/wheel';

export const Table = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 40,
        transform: {
            y: 4.6,
            z: 4.6
        }
    });

    cameraLookAt(camera, {
        x: 0,
        y: 0.2,
        z: 0.2
    });

    const studio = useStudio({
        ground: '#0f2a1a'
    });

    useSpawn(Bowl)(studio.environment);

    const wheel = useSpawn(Wheel)(studio.environment).api;

    const ball = useSpawn(Ball)(studio.environment, wheel).api;

    useSpawn(Hud)(camera, wheel, ball);

    return createScene();
};
```

`settings.ts`:

```ts
import type { TActionMap } from 'nacatamalon';

export const WIDTH = 640;
export const HEIGHT = 400;

// The numbers round a European wheel, in order, from the green zero.
export const NUMBERS = [0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26];
export const RED = new Set([1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]);
export const COLORS = {
    green: '#1f8a3b',
    red: '#c0282d',
    black: '#1b1b1b'
};

// How far round one pocket is.
export const STEP = (Math.PI * 2) / NUMBERS.length;

export const WHEEL = {
    // The ring of pockets, from the outside in, and how high it lies.
    pocketsOuter: 1.6,
    pocketsInner: 1.1,
    pocketsY: 0.2,
    // The separators between them.
    separator: {
        length: 0.5,
        width: 0.04,
        height: 0.12
    },
    turnSpeed: 0.5
};

export const BALL = {
    radius: 0.06,
    // Where it runs round the bowl, and how fast it starts and slows.
    trackRadius: 2.02,
    trackY: 0.62,
    speed: 9,
    slowing: 0.55,
    // Below this it drops into the pockets.
    dropSpeed: 2.2,
    dropTime: 0.9
};

export const ACTIONS: TActionMap = [
    {
        name: 'spin',
        bindings: [
            {
                type: 'key',
                key: ' '
            },
            {
                type: 'button',
                button: 'a'
            }
        ]
    }
];
```
