# Falling cubes

> The intro to 3D physics with the opt-in nacatamalon/physics3d adapter (Box3D in WASM). Click to kick the cubes.

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

The intro to rigid bodies through the opt-in `nacatamalon/physics3d` adapter (Erin Catto's Box3D, in WASM). The engine keeps the colliders but cannot move them; installing the adapter steps Box3D on a fixed timestep and writes each body's place and facing back onto its object.

The facing is a whole turn (a quaternion) rather than three angles, which is what lets a cube tumble end over end. **Click** the canvas to kick the cubes.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';

import { installPhysics3d } from 'nacatamalon/physics3d';
import * as Settings from './settings';
import { Scene } from './scenes/demo';

installPhysics3d();

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

// Declare Scenes
game({
    Scene
}, 'Scene');
```

`components/cube.ts`:

```ts
import { createMesh, getColor, useCubeGeometry, usePhysicsBody3d, useTransform } from 'nacatamalon';
import { quatFromEuler } from 'nacatamalon/math';

// Each cube is its OWN object, because a collider belongs to an object the way its shape does:
// one object, one collider. Dropped with a random tilt so it topples when it lands.
export const Cube = (x: number, y: number, z: number, turn: ReturnType<typeof quatFromEuler>, tint: string) => {
    useTransform({
        x,
        y,
        z,
        quaternion: turn
    });
    createMesh({
        geometry: useCubeGeometry(),
        tint: getColor(tint)
    });
    usePhysicsBody3d({
        body: 'dynamic',
        collider: {
            shape: 'box',
            size: [1, 1, 1]
        },
        density: 30
    });
};
```

`components/ground.ts`:

```ts
import { createMesh, useCubeGeometry, usePhysicsBody3d, useTransform } from 'nacatamalon';

// A wide flat slab whose TOP surface sits at y = 0. The shape drawn is a cube stretched by the
// object's own size, and the collider is given the finished measurements, so what you see is what
// things land on.
export const Ground = () => {
    useTransform({
        y: -0.5,
        scaleX: 16,
        scaleZ: 16
    });
    createMesh({
        geometry: useCubeGeometry(),
        tint: '#2a2a3a'
    });
    usePhysicsBody3d({
        body: 'static',
        collider: {
            shape: 'box',
            size: [1, 1, 1]
        },
        friction: 0.5
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useCamera3d, useDirectionalLight, usePhysicsWorld3d, usePointer, useSpawn } from 'nacatamalon';
import { quatFromEuler, useRandom } from 'nacatamalon/math';
import { getPhysicsBody3d } from 'nacatamalon/physics3d';
import * as Settings from '../settings';
import { Ground } from '../components/ground';
import { Cube } from '../components/cube';

export const Scene = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 55,
        near: 0.1,
        far: 100,
        transform: {
            y: 6,
            z: 13,
            rotationX: -0.4
        }
    });
    useDirectionalLight({
        color: '#ffffff',
        intensity: 1.1,
        ambient: 0.25
    });

    const rng = useRandom();

    usePhysicsWorld3d({
        gravity: {
            x: 0,
            y: -9.81,
            z: 0
        }
    });

    useSpawn(Ground)();

    const spawnCube = useSpawn(Cube);
    const cubes: ReturnType<typeof spawnCube>[] = [];

    for (let i = 0; i < 7; i++) {
        cubes.push(spawnCube(
            rng.rand(-3.5, 3.5),
            4 + i * 1.5,
            rng.rand(-3.5, 3.5),
            quatFromEuler(rng.rand(-1, 1), rng.rand(-1, 1), rng.rand(-1, 1)),
            rng.choose(Settings.PALETTE),
        ));
    }

    // Click the canvas to kick every cube up and out. The engine hands back what an object is
    // MADE OF, so the shove goes to the body the simulation made of it, asked for when needed.
    //
    // An impulse is weight times the change in speed, and weight is density times volume, so
    // these numbers follow from the density above rather than being picked.
    const pointer = usePointer();

    pointer.onDown(() => {
        for (const cube of cubes) {
            getPhysicsBody3d(cube)?.applyImpulse(rng.rand(-60, 60), 180, rng.rand(-60, 60));
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
// Two conventions, and both are the opposite of the flat adapter's:
//
//   1. Units are METRES, so gravity is m/s2 and weight comes out in the numbers you would write
//      on paper. In two dimensions the unit is the pixel and an impulse runs into the tens of
//      thousands.
//   2. +y is UP, so gravity is NEGATIVE.
//
// The facing is written back as a whole turn rather than as three angles, which is why a cube can
// tumble end over end without ever reaching a facing its three angles cannot say.

export const PALETTE = ['#4cff91', '#ff6b6b', '#5db6ff', '#ffd93d', '#c77dff', '#ff9f45'];
```
