# Plasma and metaballs

> Two demoscene classics on one material: a palette-cycling plasma and six blobs of lava that melt together, one of them following the mouse.

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

**Move the mouse** to push the last blob into the others, and **click** to change the look of the screen (four levels, Mega Drive dither, the NES palette).

It is one sprite material, written in WGSL and GLSL so it runs on both backends. The engine fills in `mu.time`, and the blobs arrive as three `vec4` uniforms the game writes every frame.

A metaball is a field, not a shape: every blob gives off 1 / distance², the fields add, and wherever the total passes a threshold is inside. Two blobs close together push it over the threshold in the gap between them too, and that is the melting.

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

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

`components/lava.ts`:

```ts
import * as Settings from '../settings';
import { createMaterial, createSprite, createText, useGame, useLoadBitmapFont, usePointer, useUpdate } from 'nacatamalon';
import { dither, paletteMatch, posterize, useLoadPalette, usePostProcess, POST_EFFECTS } from 'nacatamalon/effects';
import { PLASMA, PLASMA_GLSL } from '../shaders/plasma';

export const Lava = () => {
    const game = useGame();
    const pointer = usePointer();
    const W = game.getWidth();
    const H = game.getHeight();

    // Six blobs, two to a vec4 (x, y of one and x, y of the next), because a uniform is at most
    // four numbers. The material keeps this object, so writing into it moves them next frame.
    const uniforms = {
        aspect: W / H,
        blobs01: [0, 0, 0, 0],
        blobs23: [0, 0, 0, 0],
        blobs45: [0, 0, 0, 0]
    };

    const material = createMaterial({
        name: 'plasma',
        fragment: PLASMA,
        fragmentGlsl: PLASMA_GLSL,
        uniforms
    });

    createSprite({
        material,
        width: W,
        height: H,
        transform: {
            x: W / 2,
            y: H / 2
        }
    });

    // Each blob drifts on its own slow Lissajous curve; the last one is the mouse's.
    const blobs = Array.from({
        length: Settings.BLOBS
    }, (_, i) => ({
        x: 0.5,
        y: 0.5,
        fx: 0.23 + i * 0.07,
        fy: 0.31 + i * 0.05,
        phase: i * 1.7
    }));

    let mouse: { x: number; y: number; } | null = null;

    pointer.onMove((info) => {
        mouse = {
            x: info.screenX / W,
            y: info.screenY / H
        };
    });

    // The looks, all from the engine's post chain, switched by clicking.
    const font = useLoadBitmapFont({
        json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
        atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
    });

    const nes = useLoadPalette({
        src: '/example-assets/palettes/nes.palette'
    });

    const looks = [
        {
            name: 'SMOOTH',
            effect: null
        },
        {
            name: '4 LEVELS',
            effect: usePostProcess({
                ...posterize({
                    levels: POST_EFFECTS.COLOR_LEVELS.poster
                }),
                enabled: false
            })
        },
        {
            name: 'MEGA DRIVE DITHER',
            effect: usePostProcess({
                ...dither({
                    levels: POST_EFFECTS.COLOR_LEVELS.genesis
                }),
                enabled: false
            })
        },
        {
            name: 'NES PALETTE',
            effect: usePostProcess({
                ...paletteMatch({
                    dither: 0.5
                }),
                palette: nes,
                enabled: false
            })
        },
    ];

    let look = 0;

    const label = createText({
        text: looks[0].name,
        font,
        tint: '#ffffff',
        transform: {
            x: 10,
            y: H - 20
        }
    });

    pointer.onDown(() => {
        look = (look + 1) % looks.length;
        looks.forEach((entry, i) => {
            if (entry.effect !== null) {
                entry.effect.enabled = i === look;
            }
        });
        label.text = looks[look].name;
    });

    let time = 0;

    useUpdate((delta) => {
        time += delta;
        blobs.forEach((blob, i) => {
            if (i === Settings.BLOBS - 1 && mouse !== null) {
                blob.x += (mouse.x - blob.x) * Math.min(1, delta * 6);
                blob.y += (mouse.y - blob.y) * Math.min(1, delta * 6);

                return;
            }

            blob.x = 0.5 + Math.sin(time * blob.fx + blob.phase) * 0.36;
            blob.y = 0.5 + Math.cos(time * blob.fy + blob.phase * 1.3) * 0.34;
        });

        const slots = [uniforms.blobs01, uniforms.blobs23, uniforms.blobs45];

        blobs.forEach((blob, i) => {
            slots[i >> 1][(i & 1) * 2] = blob.x;
            slots[i >> 1][(i & 1) * 2 + 1] = blob.y;
        });
    });
};
```

`scenes/demo.ts`:

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

import { Lava } from '../components/lava';

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

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const BLOBS = 6;
```

`shaders/plasma.ts`:

```ts
// The plasma is four waves added together (across, down, diagonal and round a moving centre),
// and their sum picks a colour from a palette that cycles with time: the old trick of rotating the
// palette instead of redrawing the picture.
//
// A metaball is a field, not a shape: every blob gives off 1 / distance squared, the fields add, and
// wherever the total passes a threshold is inside. Two blobs close together push the total over the
// threshold in the gap between them too, and that is the melting.

export const PLASMA = `
fn field(p: vec2<f32>, blob: vec2<f32>) -> f32 {
    let d = (p - vec2<f32>(blob.x * mu.aspect, blob.y));
    return 0.012 / max(dot(d, d), 0.00001);
}

fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
    let p = vec2<f32>(uv.x * mu.aspect, uv.y);
    let t = mu.time;

    var v = sin(p.x * 9.0 + t);
    v += sin((p.y * 7.0 + t) * 0.8);
    v += sin((p.x * 5.0 + p.y * 6.0 + t) * 0.7);
    let c = p - vec2<f32>(0.5 * mu.aspect + sin(t * 0.33) * 0.6, 0.5 + cos(t * 0.41) * 0.4);
    v += sin(length(c) * 12.0 - t * 1.5);
    let k = v * 0.25 * 3.14159 + t * 0.6;
    let plasma = vec3<f32>(0.5 + 0.5 * sin(k), 0.5 + 0.5 * sin(k + 2.094), 0.5 + 0.5 * sin(k + 4.188)) * 0.45;

    let f = field(p, mu.blobs01.xy) + field(p, mu.blobs01.zw) + field(p, mu.blobs23.xy) + field(p, mu.blobs23.zw)
          + field(p, mu.blobs45.xy) + field(p, mu.blobs45.zw);

    // Inside: hot, white at the thickest. The rim: a thin bright edge. Outside: the plasma, darkened
    // near the blobs as if they cast a glow the other way.
    let inside = smoothstep(0.95, 1.05, f);
    let rim = smoothstep(0.75, 0.95, f) * (1.0 - inside);
    let lava = mix(vec3<f32>(1.0, 0.25, 0.05), vec3<f32>(1.0, 0.95, 0.6), clamp((f - 1.0) * 0.35, 0.0, 1.0));
    var rgb = plasma * (1.0 - clamp(f * 0.5, 0.0, 0.6));
    rgb = mix(rgb, vec3<f32>(1.0, 0.8, 0.3), rim);
    rgb = mix(rgb, lava, inside);
    return vec4<f32>(rgb, 1.0);
}
`;

export const PLASMA_GLSL = `
float field(vec2 p, vec2 blob) {
    vec2 d = p - vec2(blob.x * mu.aspect, blob.y);
    return 0.012 / max(dot(d, d), 0.00001);
}

vec4 effect(vec4 color, vec2 uv) {
    vec2 p = vec2(uv.x * mu.aspect, uv.y);
    float t = mu.time;

    float v = sin(p.x * 9.0 + t);
    v += sin((p.y * 7.0 + t) * 0.8);
    v += sin((p.x * 5.0 + p.y * 6.0 + t) * 0.7);
    vec2 c = p - vec2(0.5 * mu.aspect + sin(t * 0.33) * 0.6, 0.5 + cos(t * 0.41) * 0.4);
    v += sin(length(c) * 12.0 - t * 1.5);
    float k = v * 0.25 * 3.14159 + t * 0.6;
    vec3 plasma = vec3(0.5 + 0.5 * sin(k), 0.5 + 0.5 * sin(k + 2.094), 0.5 + 0.5 * sin(k + 4.188)) * 0.45;

    float f = field(p, mu.blobs01.xy) + field(p, mu.blobs01.zw) + field(p, mu.blobs23.xy) + field(p, mu.blobs23.zw)
            + field(p, mu.blobs45.xy) + field(p, mu.blobs45.zw);

    float inside = smoothstep(0.95, 1.05, f);
    float rim = smoothstep(0.75, 0.95, f) * (1.0 - inside);
    vec3 lava = mix(vec3(1.0, 0.25, 0.05), vec3(1.0, 0.95, 0.6), clamp((f - 1.0) * 0.35, 0.0, 1.0));
    vec3 rgb = plasma * (1.0 - clamp(f * 0.5, 0.0, 0.6));
    rgb = mix(rgb, vec3(1.0, 0.8, 0.3), rim);
    rgb = mix(rgb, lava, inside);
    return vec4(rgb, 1.0);
}
`;
```
