# Cracktro

> An Amiga cracktro at 320×256: copper bars, a logo that bounces letter by letter, three layers of stars, a sine scroller and a chiptune.

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

Click the game or press a key to let the browser start the music; **M** turns it off.

Everything is sprites and bitmap text moved by sines, and the bars swap in front of and behind each other by `zIndex`. The scanlines are a post effect.

The music is synthesized by the example into a WAV (a square-wave arpeggio, a bass, a kick and a hi-hat, over the chord progression half the demoscene used) and played with `useSound`.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import * as Settings from './settings';
import { Demo } from './scenes/demo';

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#000000',
    smooth: false
});

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

`audio/music.ts`:

```ts
import * as Settings from '../settings';

const pitch = (midi: number) => 440 * Math.pow(2, (midi - 69) / 12);
const square = (t: number, f: number, duty = 0.25) => ((t * f) % 1 < duty ? 1 : -1);
const triangle = (t: number, f: number) => 1 - 4 * Math.abs(((t * f) % 1) - 0.5);

export const chiptune = (): string => {
    const seconds = Settings.STEP * 64;
    const count = Math.floor(seconds * Settings.RATE);
    const bytes = new ArrayBuffer(44 + count * 2);
    const view = new DataView(bytes);

    const text = (at: number, s: string) => {
        for (let i = 0; i < s.length; i++) {
            view.setUint8(at + i, s.charCodeAt(i));
        }
    };

    text(0, 'RIFF');
    view.setUint32(4, 36 + count * 2, true);
    text(8, 'WAVE');
    text(12, 'fmt ');
    view.setUint32(16, 16, true);
    view.setUint16(20, 1, true);
    view.setUint16(22, 1, true);
    view.setUint32(24, Settings.RATE, true);
    view.setUint32(28, Settings.RATE * 2, true);
    view.setUint16(32, 2, true);
    view.setUint16(34, 16, true);
    text(36, 'data');
    view.setUint32(40, count * 2, true);

    for (let i = 0; i < count; i++) {
        const t = i / Settings.RATE;
        const step = Math.floor(t / Settings.STEP);
        const within = t - step * Settings.STEP;
        const chord = Settings.CHORDS[Math.floor(step / 16) % 4];

        const note = chord[[0, 1, 2, 1][step % 4]] + 12;
        const arp = square(t, pitch(note)) * Math.exp(-within * 18) * 0.22;

        const eighth = Math.floor(step / 2);
        const bassNote = chord[0] - 12 + (eighth % 2) * 12;
        const bass = triangle(t, pitch(bassNote)) * 0.3;

        const beat = t % (Settings.STEP * 4);
        const kick = Math.sin(2 * Math.PI * (55 * beat + 400 * (1 - Math.exp(-beat * 30)) / 30)) * Math.exp(-beat * 14) * 0.5;

        const offBeat = (t + Settings.STEP * 2) % (Settings.STEP * 4);
        const hat = (Math.random() * 2 - 1) * Math.exp(-offBeat * 60) * 0.12;

        const sample = Math.max(-1, Math.min(1, arp + bass + kick + hat));

        view.setInt16(44 + i * 2, sample * 32767, true);
    }

    return URL.createObjectURL(new Blob([bytes], {
        type: 'audio/wav'
    }));
};
```

`components/intro.ts`:

```ts
import * as Settings from '../settings';
import { createSprite, createText, fromHsl, getColor, lerpColor, useGame, useKeyboard, useLoadAudio, useLoadBitmapFont, useLoadTexture, useSound, useUpdate, type TText } from 'nacatamalon';
import { usePostProcess } from 'nacatamalon/effects';
import { chiptune } from '../audio/music';
import { SCANLINES, SCANLINES_GLSL } from '../shaders/scanlines';

/** A bar of copper: bright in the middle, dark at its edges, white so a tint colours it. */
const barPicture = () => {
    const canvas = document.createElement('canvas');

    canvas.width = 1;
    canvas.height = 16;

    const g = canvas.getContext('2d')!;

    for (let y = 0; y < 16; y++) {
        const v = Math.round(255 * Math.sin(((y + 0.5) / 16) * Math.PI));

        g.fillStyle = 'rgb(' + v + ',' + v + ',' + v + ')';
        g.fillRect(0, y, 1, 1);
    }

    return canvas.toDataURL();
};

export const Intro = () => {
    const game = useGame();
    const keys = useKeyboard();
    const W = game.getWidth();
    const H = game.getHeight();

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

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

    const bar = useLoadTexture({
        src: barPicture(),
        key: 'cracktro-bar'
    });

    const dot = useLoadTexture({
        src: barPicture(),
        key: 'cracktro-dot'
    });

    // Scanlines over everything, as on a monitor of the time.
    usePostProcess({
        name: 'scanlines',
        fragment: SCANLINES,
        fragmentGlsl: SCANLINES_GLSL,
        uniforms: {
            strength: 0.3
        }
    });

    const music = useSound(useLoadAudio({
        src: chiptune(),
        key: 'cracktro-music'
    }), {
        loop: true,
        autoplay: true,
        volume: 0.45,
        channel: 'music'
    });

    let playing = true;

    // Stars in three layers: the further, the dimmer and slower.
    const stars = Array.from({
        length: 70
    }, (_, i) => {
        const layer = i % 3;
        const size = layer + 1;
        const shade = 0.3 + layer * 0.3;

        return {
            speed: 15 + layer * 35,
            sprite: createSprite({
                texture: dot,
                width: size,
                height: size,
                tint: {
                    r: shade,
                    g: shade,
                    b: shade,
                    a: 1
                },
                transform: {
                    x: Math.random() * W,
                    y: 8 + Math.random() * (H - 60)
                },
                zIndex: -20
            }),
        };
    });

    const bars = Settings.COPPER.map((hex) => createSprite({
        texture: bar,
        width: W,
        height: 12,
        tint: getColor(hex),
        transform: {
            x: W / 2,
            y: H / 2
        }
    }));

    // The logo, one text per letter so each can bounce on its own, three times the font's size.
    const LOGO = 'NACATAMALON';

    const letters = [...LOGO].map((char, i) =>
        createText({
            text: char,
            font: logoFont,
            transform: {
                x: W / 2 + (i - LOGO.length / 2) * 27,
                y: 60,
                scaleX: 3,
                scaleY: 3
            },
            zIndex: 10
        }));

    // The scroller: enough letters to cross the screen, reused as the message goes by.
    const ADVANCE = 18;

    const scroller: TText[] = Array.from({
        length: Math.ceil(W / ADVANCE) + 2
    }, () =>
        createText({
            text: ' ',
            font: scrollFont,
            transform: {
                x: 0,
                y: 0,
                scaleX: 2,
                scaleY: 2
            },
            zIndex: 10
        }));

    const gold = getColor('#ffe9a8');
    const deep = getColor('#c2410c');
    let time = 0;
    let scroll = 0;

    useUpdate((delta) => {
        time += delta;

        if (keys.justPressed('m')) {
            playing = !playing;

            if (playing) {
                music.play();
            } else {
                music.stop();
            }
        }

        for (const star of stars) {
            star.sprite.transform.x -= star.speed * delta;

            if (star.sprite.transform.x < -2) {
                star.sprite.transform.x = W + 2;
            }
        }

        // Each bar goes round a circle seen edge on: up and down, and in front of or behind the
        // others by where it is on that circle.
        bars.forEach((sprite, i) => {
            const phase = time * 1.8 + i * 0.42;

            sprite.transform.y = 128 + Math.sin(phase) * 62;
            sprite.zIndex = Math.cos(phase) > 0 ? 1 + i : -1 - i;
        });

        letters.forEach((letter, i) => {
            letter.transform.y = 58 - Math.abs(Math.sin(time * 3 + i * 0.35)) * 26;
            letter.tint = lerpColor(deep, gold, 0.5 + 0.5 * Math.sin(time * 4 - i * 0.6));
        });

        scroll += 70 * delta;

        const first = Math.floor(scroll / ADVANCE);
        const shift = scroll % ADVANCE;

        scroller.forEach((text, j) => {
            const x = j * ADVANCE - shift;

            text.text = Settings.MESSAGE[(first + j) % Settings.MESSAGE.length];
            text.transform.x = x;
            text.transform.y = 214 + Math.sin(x * 0.035 + time * 3.2) * 14;
            text.tint = fromHsl((x * 1.2 + time * 90) % 360, 0.9, 0.65);
        });
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';

import { Intro } from '../components/intro';

export const Demo = () => {
    useSpawn(Intro)();

    return createScene();
};

// The Amiga's own low resolution, with hard pixels.
```

`settings.ts`:

```ts
export const WIDTH = 320;
export const HEIGHT = 256;
export const MESSAGE = 'NACATAMALON PRESENTS ITS FIRST CRACKTRO    GREETINGS TO EVERY PIXEL ON THIS SCREEN    ' +
    'COPPER BARS AND SINE SCROLLERS AND THREE LAYERS OF STARS    ALL OF IT DRAWN WITH SPRITES AND TEXT    ' +
    'THE MUSIC IS MADE BY THE EXAMPLE ITSELF    PRESS M FOR SILENCE    SEE YOU IN THE NEXT DEMO    ';
export const COPPER = ['#ff2d55', '#ff9500', '#ffe45c', '#34c759', '#32ade6', '#af52de'];
// A four-bar chiptune, made sample by sample: a square-wave arpeggio running up each chord, a bass
// on the root, a kick on every beat and a hi-hat between. Am, F, C, G, as half the demoscene did.

export const RATE = 22050;
export const STEP = 60 / 140 / 4;
// a sixteenth note at 140 beats a minute
export const CHORDS = [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]];
```

`shaders/scanlines.ts`:

```ts
// Every other line of the screen darkened: the look of a monitor with visible scanlines.

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);
}
`;
```
