# Screen effects

> Mosaic, waves, shockwaves, bloom, light shafts, glitch, film, a composite cable and a handheld screen, each one call.

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

The engine has a screen effect for most of the looks a game of the era reached for. Each is a function that returns a whole effect, spread into `usePostProcess`, and each knob is a number in `effect.uniforms` you can write every frame: here `mosaic` grows and shrinks, the `shockwave` ring moves out and starts again, and the `glitch` comes in bursts.

**Some read the frame more than once.** `bloom`, `godrays`, `blur` and `tiltShift` work in passes at half or a quarter of the game's size, so a wide glow costs about what a narrow one does. **Two remember the last frame**: `phosphor` leaves a short trail behind bright things, and `lcd` the ghost of a slow handheld panel. That costs two pictures the size of the canvas while they run, which is why only they ask for it.

Order matters, as in any chain: grade and distort first, then whatever adds light, then a palette or a dither, and the screen (`phosphor`, `ntsc`, `lcd`, `crt`) last. Press **left** and **right** to step through them.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Game } from './scenes/demo';
import { WIDTH, HEIGHT, PIXEL_RATIO, RENDERER } from './settings';

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    pixelRatio: PIXEL_RATIO,
    renderer: RENDERER,
    background: '#0a0d12'
});

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

`components/effect_controls.ts`:

```ts
import { createText, getColor, useKeyboard, useLoadBitmapFont, useUpdate } from 'nacatamalon';
import { usePostProcess } from 'nacatamalon/effects';
import { createEffectModes } from '../effects';
import { WHITE, START_EFFECT } from '../settings';

export const EffectControls = () => {
    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,
        tint: getColor(WHITE),
        transform: {
            x: 10,
            y: 196
        }
    });

    const modes = createEffectModes().map(({ name, effects }) => ({
        name,
        effects: effects.map(effect => usePostProcess({
            ...effect,
            enabled: false
        }))
    }));

    let mode = Math.max(0, modes.findIndex((m) => m.name === START_EFFECT));

    const apply = () => {
        for (const m of modes) {
            for (const effect of m.effects) {
                effect.enabled = m === modes[mode];
            }
        }

        label.text = (mode + 1) + '/' + modes.length + ' ' + modes[mode].name.toUpperCase();
    };

    apply();

    const keys = useKeyboard();

    useUpdate(() => {
        if (keys.justPressed('ArrowRight')) {
            mode = (mode + 1) % modes.length;
            apply();
        }

        if (keys.justPressed('ArrowLeft')) {
            mode = (mode + modes.length - 1) % modes.length;
            apply();
        }
    });
};
```

`components/test_card.ts`:

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

import { createBox } from '../helpers/create_box';

export const TestCard = () => {
    createBox(0, 0, 320, 70, '#f4e2a0');

    createBox(150, 10, 20, 60, '#1a1410');

    ['#e23d3d', '#3de26a', '#3d7ae2', '#e2d43d', '#c13de2', '#3ddfe2'].forEach((hex, i) => {
        createBox(12 + i * 50, 80, 44, 44, hex);
    });

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

        createBox(16 + i * 18, 132, 18, 30, 'rgb(' + v + ',' + v + ',' + v + ')');
    }

    const mover = createBox(10, 170, 16, 16, '#ffffff');

    useUpdate((_delta, time) => {
        mover.transform.x = 10 + (Math.sin(time * 2) * 0.5 + 0.5) * 280;
    });
};
```

`effects.ts`:

```ts
import { bloom, blur, colorAdjust, crt, distort, dither, glitch, godrays, grain, halftone, lcd, mosaic, motionBlur, ntsc, oldFilm, phosphor, posterize, rgbSplit, shockwave, tiltShift, wave, zoomBlur, POST_EFFECTS } from 'nacatamalon/effects';
import type { TPostProcessOptions } from 'nacatamalon/effects';

type TEffectMode = {
    name: string;
    effects: TPostProcessOptions[];
};

const fx = (name: string, effects: TPostProcessOptions[]): TEffectMode => ({
    name,
    effects
});

export const createEffectModes = (): TEffectMode[] => {
    return [
        fx('off', []),
        fx('crt', [crt()]),
        fx('crt:consumer', [crt(POST_EFFECTS.CRT_PRESETS.consumer)]),
        fx('crt:pvm', [crt(POST_EFFECTS.CRT_PRESETS.pvm)]),
        fx('crt:arcade', [crt(POST_EFFECTS.CRT_PRESETS.arcade)]),
        fx('crt:composite', [ntsc(), crt(POST_EFFECTS.CRT_PRESETS.composite)]),
        fx('phosphor+crt', [
            phosphor({
                persistence: 0.85
            }),
            crt()
        ]),
        fx('adjust', [
            colorAdjust({
                saturation: 0.4,
                contrast: 1.2,
                hue: 30,
                tint: [1, 0.9, 0.8]
            })
        ]),
        fx('wave', [wave()]),
        fx('shockwave', [
            shockwave({
                radius: 70
            })
        ]),
        fx('distort', [
            distort({
                radius: 70,
                twist: 2,
                bulge: 0.4
            })
        ]),
        fx('mosaic', [
            mosaic({
                size: 6
            })
        ]),
        fx('blur', [
            blur({
                radius: 6
            })
        ]),
        fx('zoomBlur', [
            zoomBlur({
                reach: 0.2
            })
        ]),
        fx('motionBlur', [
            motionBlur({
                velocity: {
                    x: 16,
                    y: 0
                }
            })
        ]),
        fx('tiltShift', [
            tiltShift({
                focus: 0.6
            })
        ]),
        fx('bloom', [
            bloom({
                threshold: 0.7,
                intensity: 1
            })
        ]),
        fx('godrays', [
            godrays({
                center: {
                    x: 0.5,
                    y: 0.05
                },
                threshold: 0.6,
                intensity: 0.8
            })
        ]),
        fx('halftone', [
            halftone({
                size: 5,
                ownColor: 1
            })
        ]),
        fx('halftone:lines', [
            halftone({
                mode: 'lines',
                size: 6
            })
        ]),
        fx('glitch', [
            glitch({
                amount: 0.5
            })
        ]),
        fx('rgbSplit', [
            rgbSplit({
                red: {
                    x: -2,
                    y: 0
                },
                blue: {
                    x: 2,
                    y: 1
                }
            })
        ]),
        fx('grain', [
            grain({
                amount: 0.15
            })
        ]),
        fx('oldFilm', [
            oldFilm({
                scratches: 1
            })
        ]),
        fx('ntsc', [
            ntsc({
                bleed: 1,
                artifacts: 0.6
            })
        ]),
        fx('lcd', [
            lcd({
                tint: [0.61, 0.73, 0.06],
                ghosting: 0.6
            })
        ]),
        fx('dither+crt', [
            dither({
                levels: POST_EFFECTS.COLOR_LEVELS.genesis
            }),
            crt(POST_EFFECTS.CRT_PRESETS.consumer)
        ]),
        fx('posterize', [posterize()]),
    ];
};
```

`helpers/create_box.ts`:

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

export const createBox = (x: number, y: number, width: number, height: number, tint: string) => {
    return createSprite({
        transform: {
            x,
            y
        },
        anchor: {
            x: 0,
            y: 0
        },
        width,
        height,
        tint
    });
};
```

`scenes/demo.ts`:

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

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

    return createScene();
};
```

`settings.ts`:

```ts
import type { TGameOptions } from 'nacatamalon';

export const WIDTH = 320;
export const HEIGHT = 224;
export const WHITE = '#e8eef5';

// These are launch settings for this browser example, read once per playground run.
const query = new URLSearchParams(location.search);
const backend = query.get('r')?.toUpperCase();

export const START_EFFECT = query.get('fx');
export const PIXEL_RATIO = Number(query.get('ratio') ?? 3);
export const RENDERER: TGameOptions['renderer'] = backend === 'WEBGL2' || backend === 'WEBGPU' ? backend : undefined;
```
