# Second UV

> A courtyard made with createGeometry whose tile repeats by uvs while its baked shade is laid once by uv2.

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

A courtyard of stone tiles with the shade under its pillars baked into one picture. **Space** lays that shade by the first picture coordinate instead, and it repeats with every tile.

The floor is made corner by corner with `createGeometry`, and each corner has two places in the pictures: `uvs`, where it is in the stone tile, which repeats every one and a half units, and `uv2`, where it is across the whole court, 0 to 1. The tile is laid by the first. The shade is an occlusion map, white where the light from all around reaches the floor and darker at the foot of each pillar, laid by the second: `occlusion: { texture, uv: 'uv2' }`. One small picture then shades the whole court, however the tiles repeat. A shader reads the second coordinate as `ctx.uv2`, or `composerUv2()` in the composer. A glTF model brings its own; left out, `uv2` is `uvs` again.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Courtyard } from './scenes/courtyard';
import { HEIGHT, SKY, WIDTH } from './settings';

// A shape with two picture coordinates. The courtyard floor is made corner by corner with
// createGeometry: its stone tile repeats by the first coordinate (`uvs`), and the shade under the
// pillars, baked once into one picture for the whole court, is laid by the second (`uv2`).
//
//   space   lay the shade by uv2 / by uv
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: SKY,
    actions: [
        {
            name: 'swap',
            bindings: [
                {
                    type: 'key',
                    key: ' '
                }
            ]
        }
    ]
});

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

`art/pictures.ts`:

```ts
import { createPixels, fillCircle, fillRect, type TPixels } from 'nacatamalon/pixels';
import { BAKE, COURT, PILLARS } from '../settings';

// The two pictures of the court, painted in code.

/**
 * One stone tile, with grout along two of its edges: repeated, each tile gets it all round.
 */
export const paintTile = (): TPixels => {
    const tile = createPixels(32, 32, '#d8cdb8');

    fillRect(tile, 0, 0, 32, 2, '#8f846f');
    fillRect(tile, 0, 0, 2, 32, '#8f846f');
    fillRect(tile, 9, 12, 6, 3, '#cbbfa7');
    fillRect(tile, 20, 22, 5, 2, '#e4dac6');

    return tile;
};

/**
 * The shade of the whole court, once: white where the light from all around reaches the floor, darker
 * round the foot of each pillar and along the edge, where walls would stand. Only the red is read.
 * Laid by the court's second picture coordinate, which runs 0 to 1 across the whole court, so a
 * pixel here is one place on the floor, however the tiles repeat.
 */
export const paintBake = (): TPixels => {
    const bake = createPixels(BAKE.size, BAKE.size, '#ffffff');
    const perUnit = BAKE.size / COURT.size;

    // Along the edge: four steps darker towards it.
    for (let step = 0; step < 4; step++) {
        const grey = Math.round(150 + step * 25).toString(16).padStart(2, '0');
        const inset = step;

        fillRect(bake, inset, inset, BAKE.size - inset * 2, 1, `#${grey}${grey}${grey}`);
        fillRect(bake, inset, BAKE.size - 1 - inset, BAKE.size - inset * 2, 1, `#${grey}${grey}${grey}`);
        fillRect(bake, inset, inset, 1, BAKE.size - inset * 2, `#${grey}${grey}${grey}`);
        fillRect(bake, BAKE.size - 1 - inset, inset, 1, BAKE.size - inset * 2, `#${grey}${grey}${grey}`);
    }

    // Round each pillar: rings from light, far out, to dark, at its foot.
    const rings = 6;

    for (const [x, z] of PILLARS.places) {
        const cx = (x / COURT.size + 0.5) * BAKE.size;
        const cy = (z / COURT.size + 0.5) * BAKE.size;

        for (let ring = 0; ring < rings; ring++) {
            const along = ring / (rings - 1);
            const radius = BAKE.reach * perUnit * (1 - along * 0.75);
            const grey = Math.round(235 - along * 150).toString(16).padStart(2, '0');

            fillCircle(bake, cx, cy, radius, `#${grey}${grey}${grey}`);
        }
    }

    return bake;
};
```

`components/court.ts`:

```ts
import { createGeometry, createMesh, useCubeGeometry } from 'nacatamalon';
import { createPixelTexture } from 'nacatamalon/pixels';
import { paintBake, paintTile } from '../art/pictures';
import { COURT, PILLARS } from '../settings';

/**
 * What the court lets the scene do: lay its shade by one picture coordinate or the other.
 */
export type TCourt = {
    layShadeBy: (uv: 'uv' | 'uv2') => void;
};

/**
 * The courtyard floor, made corner by corner with `createGeometry`, and its pillars.
 *
 * Every corner has two places in the pictures: `uvs`, where it is in the stone tile, which repeats
 * every `COURT.tile` units, and `uv2`, where it is across the whole court, 0 to 1. The tile is laid
 * by the first; the shade, baked once for the whole court, by the second.
 */
export const Court = (): TCourt => {
    const corners = COURT.segments + 1;
    const positions: number[] = [];
    const uvs: number[] = [];
    const uv2: number[] = [];
    const indices: number[] = [];

    for (let row = 0; row < corners; row++) {
        for (let column = 0; column < corners; column++) {
            const x = (column / COURT.segments - 0.5) * COURT.size;
            const z = (row / COURT.segments - 0.5) * COURT.size;

            positions.push(x, 0, z);
            // The tile, once every `COURT.tile` units.
            uvs.push(x / COURT.tile, z / COURT.tile);
            // The whole court, once.
            uv2.push(x / COURT.size + 0.5, z / COURT.size + 0.5);
        }
    }

    for (let row = 0; row < COURT.segments; row++) {
        for (let column = 0; column < COURT.segments; column++) {
            const a = row * corners + column;

            // Counter-clockwise seen from above, the side that is drawn.
            indices.push(a, a + corners, a + 1, a + 1, a + corners, a + corners + 1);
        }
    }

    const floor = createMesh({
        geometry: createGeometry({
            positions,
            indices,
            uvs,
            uv2
        }),
        texture: createPixelTexture(paintTile(), {
            mipmaps: true
        }),
        wrap: 'repeat',
        smooth: true,
        // The shade, laid by the second coordinate: once over the whole court.
        occlusion: {
            texture: createPixelTexture(paintBake()),
            uv: 'uv2'
        }
    });

    for (const [x, z] of PILLARS.places) {
        createMesh({
            geometry: useCubeGeometry({
                width: PILLARS.width,
                height: PILLARS.height,
                depth: PILLARS.width
            }),
            tint: '#e9e1d0',
            transform: {
                x,
                y: PILLARS.height / 2,
                z
            }
        });
    }

    return {
        // The material reads which coordinate its shade is laid by every frame.
        layShadeBy: (uv) => {
            floor.material.occlusion!.uv = uv;
        }
    };
};
```

`scenes/courtyard.ts`:

```ts
import { cameraLookAt, createScene, createText, useAction, useAmbientLight, useCamera3d, useDirectionalLight, useSpawn, useUpdate } from 'nacatamalon';
import { Court } from '../components/court';
import { HEIGHT, ORBIT } from '../settings';

/**
 * A courtyard of repeated stone tiles with its shade baked into one picture, seen from a camera going
 * slowly round it. Space lays the shade by the first picture coordinate instead, to show why it
 * needs the second.
 */
export const Courtyard = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50
    });

    // Occlusion only darkens the light from all around, so that is most of the light here, and the
    // sun is soft: the baked shade is what shapes the floor.
    useAmbientLight({
        color: '#ffffff',
        intensity: 0.8
    });
    useDirectionalLight({
        color: '#fff2dc',
        intensity: 0.35,
        transform: {
            rotationX: -0.9,
            rotationY: 0.6
        }
    });

    const court = useSpawn(Court)();

    createText({
        text: 'SPACE: SHADE BY UV2 / BY UV',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });

    const state = createText({
        text: 'SHADE LAID BY UV2: ONCE OVER THE COURT',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: 22
        }
    });

    createText({
        text: 'SECOND UV · NACATAMALON',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    const swap = useAction('swap');
    let bySecond = true;

    useUpdate((_delta, time) => {
        if (swap.justPressed()) {
            bySecond = !bySecond;
            court.api.layShadeBy(bySecond ? 'uv2' : 'uv');
            state.text = bySecond ? 'SHADE LAID BY UV2: ONCE OVER THE COURT' : 'SHADE LAID BY UV: REPEATED WITH EVERY TILE';
        }

        const angle = time * ORBIT.speed * Math.PI * 2;

        camera.transform.x = Math.sin(angle) * ORBIT.distance;
        camera.transform.y = ORBIT.height;
        camera.transform.z = Math.cos(angle) * ORBIT.distance;
        cameraLookAt(camera, {
            x: 0,
            y: 0.5,
            z: 0
        });
    });

    return createScene();
};
```

`settings.ts`:

```ts
/**
 * The game's size, in its own pixels.
 */
export const WIDTH = 640;
export const HEIGHT = 360;

/**
 * The sky.
 */
export const SKY = '#a9c6de';

/**
 * The courtyard: a square `size` units across, cut into `segments` squares each way, paved with one
 * stone tile every `tile` units.
 */
export const COURT = {
    size: 12,
    segments: 12,
    tile: 1.5
};

/**
 * The pillars standing on it, where they stand, and how tall.
 */
export const PILLARS = {
    places: [[-3, -3], [3, -3], [-3, 3], [3, 3], [0, 0]] as Array<[number, number]>,
    width: 0.8,
    height: 3
};

/**
 * The shade baked under the pillars and along the edge of the court: a picture `size` pixels square
 * laid once over the whole court.
 */
export const BAKE = {
    size: 64,
    // How far the shade reaches round a pillar, in units.
    reach: 1.6
};

/**
 * How fast the camera goes round, in turns a second, and how far out and up it stays.
 */
export const ORBIT = {
    speed: 0.03,
    distance: 13,
    height: 7
};
```
