# Mipmaps

> A road of tiles into the distance, with and without mipmaps: without them the far road shimmers and crawls.

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

A road of tiles running into the distance, flown over low. **Space** shows it with and without mipmaps: without them the far road shimmers and crawls as the camera moves; with them it settles into an even blend.

Far away, one pixel on the screen covers many of the tile's, and without mipmaps it gets whichever one it lands on, a different one every frame. Mipmaps are smaller and smaller copies of the picture, each half the one before and already averaged, made on the graphics card when the texture is: `createPixelTexture(tile, { mipmaps: true })`, or `useLoadTexture({ src, mipmaps: true })` for a file. A model then reads the copy its size on the screen asks for, and with `smooth: true` blends between two. Only models read them; sprites and map layers are drawn at the size they are.

The road's material reads its tile as a map, at its `uv` times how many times the tile repeats, 3 across and 60 along. It says so with `composerMapSample('tile', onTile, { scale: [3, 60] })` (in a shader by hand, `sampleMapScaled_tile(uv, vec2(3.0, 60.0))`): the copy is picked by how fast the place read runs across the screen, and without the scale the engine would judge it by the road's own `uv`, sixty times slower, and read a copy far too sharp.

## Code

`index.ts`:

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

// A road of tiles running into the distance. Far away, a pixel on the screen covers many of the
// tile's, and without mipmaps it is given whichever one it lands on, so the road shimmers and crawls
// as the camera moves. With them, it is read from a smaller copy of the tile, already averaged.
//
//   space   mipmaps on / off
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: SKY,
    actions: [
        {
            name: 'toggle',
            bindings: [
                {
                    type: 'key',
                    key: ' '
                }
            ]
        }
    ]
});

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

`art/tile.ts`:

```ts
import { createPixels, fillRect, type TPixels } from 'nacatamalon/pixels';
import { TILE } from '../settings';

/**
 * One tile of the road, painted in code: a checker framed by a thin line. Fine, sharp detail like
 * this is what shimmers far away without mipmaps, because a pixel on the screen there covers many
 * of the picture's and is given whichever one it lands on.
 */
export const paintTile = (): TPixels => {
    const pixels = createPixels(TILE.size, TILE.size, TILE.light);
    const cell = TILE.size / TILE.cells;

    for (let y = 0; y < TILE.cells; y++) {
        for (let x = 0; x < TILE.cells; x++) {
            if ((x + y) % 2 === 1) {
                fillRect(pixels, x * cell, y * cell, cell, cell, TILE.dark);
            }
        }
    }

    // The frame, two pixels wide, on two sides: repeated, each tile gets it on all four.
    fillRect(pixels, 0, 0, TILE.size, 2, TILE.line);
    fillRect(pixels, 0, 0, 2, TILE.size, TILE.line);

    return pixels;
};
```

`components/road.ts`:

```ts
import { createMaterial, createMesh, usePlaneGeometry, type TTexture } from 'nacatamalon';
import { ROAD } from '../settings';
import { ROAD_SHADER } from '../shaders/road';

/**
 * What the road lets the scene do: show its tile from another texture.
 */
export type TRoad = {
    show: (tile: TTexture) => void;
};

/**
 * The road: one long plane whose material repeats a tile along it, read from the material's map
 * named `tile`.
 */
export const Road = ({ tile }: { tile: TTexture; }): TRoad => {
    const material = createMaterial({
        ...ROAD_SHADER,
        maps: {
            // Smooth, so far away it blends between two of the tile's copies rather than jumping
            // from one to the next; repeated, so the tile runs on past its edge.
            tile: {
                texture: tile,
                smooth: true,
                wrap: 'repeat'
            }
        }
    });

    createMesh({
        geometry: usePlaneGeometry({
            width: ROAD.width,
            depth: ROAD.length
        }),
        material,
        transform: {
            z: -ROAD.length / 2
        }
    });

    return {
        // The material reads its maps every frame, so the other texture shows at once.
        show: (next) => {
            material.maps!.tile.texture = next;
        }
    };
};
```

`scenes/highway.ts`:

```ts
import { createScene, createText, useAction, useAmbientLight, useCamera3d, useDirectionalLight, useFog, useSpawn, useUpdate } from 'nacatamalon';
import { createPixelTexture } from 'nacatamalon/pixels';
import { paintTile } from '../art/tile';
import { Road } from '../components/road';
import { CAMERA, HEIGHT, ROAD, SKY } from '../settings';

/**
 * A road of tiles running into the distance, flown over low. Space shows it with and without
 * mipmaps.
 */
export const Highway = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 60,
        transform: {
            y: CAMERA.height,
            rotationX: CAMERA.tilt
        }
    });

    useFog({
        color: SKY,
        near: 60,
        far: 140
    });
    useAmbientLight({
        color: '#ffffff',
        intensity: 0.55
    });
    useDirectionalLight({
        color: '#fff2dc',
        intensity: 0.7,
        transform: {
            rotationX: -0.9,
            rotationY: 0.5
        }
    });

    // One picture, two textures: the same tile, one with its mipmaps and one without.
    const tile = paintTile();

    const textures = {
        on: createPixelTexture(tile, {
            mipmaps: true
        }),
        off: createPixelTexture(tile)
    };

    let mipmaps = true;

    const road = useSpawn(Road)({
        tile: textures.on
    });

    createText({
        text: 'SPACE: MIPMAPS ON / OFF',
        tint: '#3a2a1a',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });

    const state = createText({
        text: 'MIPMAPS: ON',
        tint: '#3a2a1a',
        zIndex: 100,
        transform: {
            x: 8,
            y: 22
        }
    });

    createText({
        text: 'MIPMAPS · NACATAMALON',
        tint: '#3a2a1a',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    const toggle = useAction('toggle');
    // One tile's length: flying on by it and jumping back looks the same, so the road never ends.
    const tileLength = ROAD.length / ROAD.tiles[1];

    useUpdate((delta) => {
        if (toggle.justPressed()) {
            mipmaps = !mipmaps;
            road.api.show(mipmaps ? textures.on : textures.off);
            state.text = mipmaps ? 'MIPMAPS: ON' : 'MIPMAPS: OFF';
        }

        camera.transform.z -= CAMERA.speed * delta;

        if (camera.transform.z < -tileLength) {
            camera.transform.z += tileLength;
        }
    });

    return createScene();
};
```

`settings.ts`:

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

/**
 * The sky, and the fog that fades the far end of the road into it.
 */
export const SKY = '#f3d9b0';

/**
 * The road: `width` units across and `length` units long, with its picture repeated `tiles` times
 * across and along, so each tile is a square of the same size.
 */
export const ROAD = {
    width: 12,
    length: 240,
    tiles: [3, 60] as [number, number]
};

/**
 * The tile's picture, `size` pixels square: a checker of `cells` by `cells`, framed by a line.
 */
export const TILE = {
    size: 128,
    cells: 8,
    light: '#f2ead8',
    dark: '#2f4f7f',
    line: '#c8553d'
};

/**
 * The camera: how high it flies over the road, how far down it looks, and how fast it goes forward,
 * in units a second.
 */
export const CAMERA = {
    height: 1.4,
    tilt: -0.12,
    speed: 6
};
```

`shaders/road.ts`:

```ts
import {
    compileShader, composerAdd, composerLight, composerMapSample, composerMul, composerShine, composerSwizzle, composerUv,
    composerVec2
} from 'nacatamalon/shader';
import { ROAD } from '../settings';

// The road's material, written once with the shader composer so it draws on both cards.

// The road's own uv runs once along its whole length; the tile is read at the uv times how many
// times it repeats, so it runs that many times as fast.
const onTile = composerMul(composerUv(), composerVec2(ROAD.tiles[0], ROAD.tiles[1]));

export const ROAD_SHADER = compileShader({
    shader: 'mesh3d',
    color: composerAdd(
        composerMul(
            // `scale` says how much faster than the uv the tile is read: the same numbers it is
            // multiplied by. A picture with mipmaps picks its copy by it. Without it, the tile far
            // away would be read from a copy sixty times too sharp along the road, and shimmer as if
            // it had no mipmaps at all.
            composerSwizzle(composerMapSample('tile', onTile, {
                scale: ROAD.tiles
            }), 'rgb'),
            composerLight()
        ),
        composerShine()
    )
});
```
