# Post-processing

> A shader over the whole frame: scanlines and colour quantisation, switched on and off live.

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

A shader over the whole **frame** rather than over one object. `usePostProcess` adds one to the game's chain and returns the effect, so you tune it by changing its fields and switch it off with `enabled`, which keeps its place between the effects around it; removing and re-adding it would lose that.

The function is the same `fn effect(color, uv)` a sprite material uses, so CRT lines written for one run on the other unchanged: only now `color` is the finished frame and `uv` walks the whole screen. **Click** the canvas to cycle. Watch the **IDENTITY** step: it returns the colour untouched, so it must be indistinguishable from **OFF**.

## 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: '#0a0d12'
});

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

`components/effect_controls.ts`:

```ts
import { createText, getColor, usePointer } from 'nacatamalon';
import { dither, paletteMatch, posterize, useLoadPalette, usePostProcess, POST_EFFECTS } from 'nacatamalon/effects';
import type { TBitmapFont } from 'nacatamalon';
import { WHITE, DIM } from '../settings';
import { IDENTITY, IDENTITY_GLSL, SCANLINES, SCANLINES_GLSL } from '../shaders';

export const EffectControls = (font: TBitmapFont) => {
    const label = createText({
        text: '',
        font,
        tint: getColor(WHITE),
        transform: {
            x: 20,
            y: 210
        }
    });

    createText({
        text: 'CLICK TO CYCLE',
        font,
        tint: getColor(DIM),
        transform: {
            x: 20,
            y: 232
        }
    });

    // Installed once and switched between, rather than added and removed on each click. That keeps
    // the ORDER of the chain fixed, which is the thing a chain has that a set does not.
    const scanlines = usePostProcess({
        name: 'scanlines',
        fragment: SCANLINES,
        fragmentGlsl: SCANLINES_GLSL,
        uniforms: {
            strength: 0.35
        },
        enabled: false,
    });

    const flat = usePostProcess({
        ...posterize({
            levels: 4
        }),
        enabled: false
    });

    // The two side by side are the whole argument for ordered dithering: the same eight steps a
    // Mega Drive had, once with flat bands and once with the pattern breaking them up.
    const banded = usePostProcess({
        ...posterize({
            levels: POST_EFFECTS.COLOR_LEVELS.genesis
        }),
        enabled: false
    });

    const dithered = usePostProcess({
        ...dither({
            levels: POST_EFFECTS.COLOR_LEVELS.genesis
        }),
        enabled: false
    });

    const identity = usePostProcess({
        name: 'identity',
        fragment: IDENTITY,
        fragmentGlsl: IDENTITY_GLSL,
        enabled: false,
    });

    // The one that takes a FILE. A palette is a list somebody chose, spread unevenly, which is what
    // the ones above cannot express: they land on an even grid of colours no console ever had.
    const nes = useLoadPalette({
        src: '/example-assets/palettes/nes.palette'
    });

    const paletted = usePostProcess({
        ...paletteMatch({
            dither: 0
        }),
        palette: nes,
        enabled: false
    });

    const all = [scanlines, flat, banded, dithered, paletted, identity];

    const modes = [
        {
            label: 'OFF - no chain at all',
            on: []
        },
        {
            label: 'IDENTITY - must look like OFF',
            on: [identity]
        },
        {
            label: 'SCANLINES',
            on: [scanlines]
        },
        {
            label: 'POSTERIZE 4 LEVELS',
            on: [flat]
        },
        {
            label: 'POSTERIZE + SCANLINES',
            on: [flat, scanlines]
        },
        {
            label: 'GENESIS 8 LEVELS - BANDED',
            on: [banded]
        },
        {
            label: 'GENESIS 8 LEVELS - DITHERED',
            on: [dithered]
        },
        {
            label: 'NES PALETTE - 54 FIXED COLOURS',
            on: [paletted]
        },
    ];

    let mode = 0;

    const apply = () => {
        for (const effect of all) {
            effect.enabled = modes[mode].on.some(candidate => candidate === effect);
        }

        label.text = modes[mode].label;
    };

    apply();

    usePointer().onDown(() => {
        mode = (mode + 1) % modes.length;
        apply();
    });
};
```

`components/test_card.ts`:

```ts
import { createSprite, createText, getColor } from 'nacatamalon';

import type { TBitmapFont } from 'nacatamalon';
import { WHITE } from '../settings';

export const TestCard = (font: TBitmapFont) => {
    // A test card: flat blocks and a grey ramp. Flat colour is what shows banding, and a ramp is
    // what shows whether the steps are evenly spaced. Laid out by their top left corners, like the
    // words.
    ['#e23d3d', '#3de26a', '#3d7ae2', '#e2d43d', '#c13de2', '#3ddfe2'].forEach((hex, i) => {
        createSprite({
            transform: {
                x: 20 + i * 72,
                y: 60
            },
            anchor: {
                x: 0,
                y: 0
            },
            width: 64,
            height: 64,
            tint: getColor(hex)
        });
    });

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

        createSprite({
            transform: {
                x: 20 + i * 27,
                y: 140
            },
            anchor: {
                x: 0,
                y: 0
            },
            width: 27,
            height: 48,
            tint: getColor('rgb(' + v + ',' + v + ',' + v + ')'),
        });
    }

    createText({
        text: 'POST-PROCESS',
        font,
        tint: getColor(WHITE),
        transform: {
            x: 20,
            y: 22
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useLoadBitmapFont, useSpawn } from 'nacatamalon';
import { TestCard } from '../components/test_card';
import { EffectControls } from '../components/effect_controls';
import { FONT } from '../settings';

export const Game = () => {
    const font = useLoadBitmapFont(FONT);

    useSpawn(TestCard)(font);
    useSpawn(EffectControls)(font);

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 260;
export const WHITE = '#e8eef5';
export const DIM = '#6c8299';
export const FONT = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
};
```

`shaders.ts`:

```ts
// A full-screen effect: a shader that reads the FRAME, not one object.
//
// usePostProcess puts one in the game's chain and hands back the record, so tuning it is changing
// it: writing a number into its uniforms lands next frame, and switching it off leaves it where it
// is between the two around it.
//
// Three things worth noticing here:
//
//  1. The scene is deliberately STILL. This page doubles as the check that an identity effect
//     changes nothing, and that check is a pixel comparison of two captures. Anything moving would
//     make them differ for reasons that have nothing to do with the chain.
//  2. IDENTITY hands back what it was given. With it on, the frame has to be indistinguishable
//     from OFF. If it is not, the picture in the middle or the way the chain passes it along is
//     wrong, and every effect after it inherits that quietly.
//  3. fn effect(color, uv) is the SAME hook a sprite material uses. That is not a coincidence: a
//     CRT written for one runs on the other with nothing rewritten.

export const IDENTITY = 'fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> { return color; }';

export const IDENTITY_GLSL = 'vec4 effect(vec4 color, vec2 uv) { return color; }';

// uv walks the whole screen here, which is what makes this a screen effect and not stripes painted
// on one sprite: the lines stay put while things move under them.
export const SCANLINES = `
fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
    let line = floor(uv.y * mu.resolution.y * 0.5);
    let dark = 1.0 - mu.strength * (1.0 - (line - floor(line * 0.5) * 2.0));
    return vec4<f32>(color.rgb * dark, color.a);
}
`;

export const SCANLINES_GLSL = `
vec4 effect(vec4 color, vec2 uv) {
    float line = floor(uv.y * mu.resolution.y * 0.5);
    float dark = 1.0 - mu.strength * (1.0 - (line - floor(line * 0.5) * 2.0));
    return vec4(color.rgb * dark, color.a);
}
`;
```
