# Dither

> dither() cuts each channel to a few steps and hides the bands with an ordered pattern, the way consoles of the era did.

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

`dither()` cuts every colour channel down to a few steps, the way the machines of the era stored colour, and hides the bands with an ordered 4×4 pattern: each pixel is nudged up or down by less than a step, so a gradient becomes a mix of two steps instead of a hard edge.

It has two numbers, both in `effect.uniforms`, so changing one is writing it: `levels` is steps per channel (`POST_EFFECTS.COLOR_LEVELS` has the real ones: 8 on a Mega Drive, 32 on a SNES) and `amount` is how much pattern is mixed in; at 0 it is plain posterize, bands and all.

**Click** to change machine, **↑** **↓** for the pattern strength and **Space** to switch it off. Watch the balls: the moving light makes gradients nobody drew, and that is where it shows first.

## Code

`index.ts`:

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

import { Game } from './scenes/demo';
import { WIDTH, HEIGHT } from './settings';

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

// Declare Scenes
game({
    Game,
});
```

`components/effect_controls.ts`:

```ts
import { createText, useKeyboard, useLoadBitmapFont, usePointer, useUpdate, useScreenSpace } from 'nacatamalon';
import { clamp } from 'nacatamalon/math';
import { dither, usePostProcess } from 'nacatamalon/effects';

import { MACHINES, EFFECT_SETTINGS } from '../settings';

export const EffectControls = () => {
    useScreenSpace();

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

    const label = createText({
        text: '',
        font,
        style: {
            fontSize: 8,
        },
        tint: '#ffffff',
        transform: {
            x: 12,
            y: 14,
        },
    });

    createText({
        text: 'CLICK MACHINE   UP DOWN STRENGTH   SPACE OFF',
        font,
        style: {
            fontSize: 8,
        },
        tint: '#8c82a6',
        transform: {
            x: 12,
            y: 30,
        },
    });

    const effect = usePostProcess(dither(EFFECT_SETTINGS));

    let machine = 0;

    const show = () => {
        const amount = Math.round(effect.uniforms.amount * 100);

        label.text = effect.enabled
            ? MACHINES[machine].name + '  ' + MACHINES[machine].levels + ' LEVELS  PATTERN ' + amount
            : 'OFF  THE FRAME AS DRAWN';
    };

    show();

    usePointer().onDown(() => {
        machine = (machine + 1) % MACHINES.length;
        effect.uniforms.levels = MACHINES[machine].levels;
        show();
    });

    const keys = useKeyboard();

    useUpdate(() => {
        const step = keys.justPressed('ArrowUp') ? 0.25 : keys.justPressed('ArrowDown') ? -0.25 : 0;

        if (step !== 0) {
            effect.uniforms.amount = clamp(effect.uniforms.amount + step, 0, 1);
            show();
        }

        // Switched off, not removed: it keeps its place in the chain for when it comes back.
        if (keys.justPressed(' ')) {
            effect.enabled = !effect.enabled;
            show();
        }
    });
};
```

`components/stage.ts`:

```ts
import { WIDTH, HEIGHT } from '../settings';
import { createMaterial, createMesh, createSprite, getColor, useCamera3d, useDirectionalLight, useLoadTexture, useUpdate, useSphereGeometry } from 'nacatamalon';

// The test card every post-processing example draws, so the only thing that changes between them
// is the effect. Each part is here because it shows something a screen effect does:
//
//   lit balls   smooth gradients that nobody drew, made by the light as it turns. Banding shows
//               there first, because a gradient is exactly what a few steps cannot hold.
//   hue ramp    every colour at once, which is where a palette has to make its hardest choices.
//   grey ramp   sixteen even steps: whether an effect keeps them even is visible at a glance.
//   gammix      pixel art, already limited, so it shows what an effect does to a sprite that was
//               drawn for a small palette in the first place.

export const Stage = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            z: 5,
            y: 0.4
        },
    });

    const light = useDirectionalLight({
        color: '#ffffff',
        intensity: 1.2,
        ambient: 0.25,
        transform: {
            rotationX: -0.5
        },
    });

    const geometry = useSphereGeometry();

    ['#ff7a3d', '#3dd6c6', '#9b5cff'].forEach((hex, i) => {
        const material = createMaterial({
            name: 'post-card-' + i,
            shader: 'mesh3d',
            tint: getColor(hex),
            specular: '#ffffff',
            shininess: 24,
        });

        createMesh({
            geometry,
            material,
            transform: {
                x: (i - 1) * 2.1,
                y: 0.6,
            },
        });
    });

    // The light swings from side to side in front of the balls, so the gradients move and a
    // static effect cannot hide in one lucky frame.
    useUpdate((_, time) => {
        light.transform.rotationY = Math.sin(time * 0.8) * 0.9;
    });

    for (let i = 0; i < 48; i++) {
        createSprite({
            width: WIDTH / 48,
            height: 18,
            tint: getColor('hsl(' + Math.round((i / 48) * 360) + ', 85%, 55%)'),
            transform: {
                x: (i + 0.5) * WIDTH / 48,
                y: HEIGHT - 38,
            },
        });
    }

    for (let i = 0; i < 16; i++) {
        const v = Math.round((i / 15) * 255);

        createSprite({
            width: WIDTH / 16,
            height: 18,
            tint: getColor('rgb(' + v + ',' + v + ',' + v + ')'),
            transform: {
                x: (i + 0.5) * WIDTH / 16,
                y: HEIGHT - 18,
            },
        });
    }

    const gammix = useLoadTexture({
        src: '/example-assets/assets/gammix.png',
        key: 'gammix',
    });

    createSprite({
        texture: gammix,
        width: 48,
        height: 48,
        transform: {
            x: WIDTH - 34,
            y: 34,
        },
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import { Stage } from '../components/stage';
import { EffectControls } from '../components/effect_controls';

export const Game = () => {
    useSpawn(Stage)();
    useSpawn(EffectControls)();

    return createScene();
};
```

`settings.ts`:

```ts
import { POST_EFFECTS } from 'nacatamalon/effects';

export const WIDTH = 480;
export const HEIGHT = 300;

// dither() cuts every colour channel down to a few steps, the way the machines of the era stored
// colour, and hides the bands with an ordered 4x4 pattern: neighbouring pixels are nudged up and
// down by less than one step, so a smooth gradient becomes a mix of two steps instead of a hard edge.
//
// Two numbers drive it, and both live in effect.uniforms, so changing one is writing it:
//
//   levels    steps per channel. POST_EFFECTS.COLOR_LEVELS has the real ones: 8 on a Mega Drive, 32 on a SNES.
//   amount    how much of the pattern to mix in. At 0 it is plain posterize, bands and all.
export const MACHINES = [
    {
        name: 'MEGA DRIVE',
        levels: POST_EFFECTS.COLOR_LEVELS.genesis,
    },
    {
        name: 'SNES',
        levels: POST_EFFECTS.COLOR_LEVELS.snes,
    },
    {
        name: 'POSTER',
        levels: POST_EFFECTS.COLOR_LEVELS.poster,
    },
    {
        name: 'TWO STEPS',
        levels: 2,
    },
];

export const EFFECT_SETTINGS = {
    levels: MACHINES[0].levels,
};
```
