# 3D effects

> Surface shaders on meshes: dissolve, fresnel hologram, force field and angle-based iridescence.

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

Custom fragment materials on meshes. A `'mesh3d'` effect is a **surface shader**, `fn effect(surface, ctx)`, with a `FragContext` exposing `uv`, the world `normal` and `worldPos`, and the Gouraud `light` term separately.

That is enough for a dissolve, a fresnel hologram, a pulsing force field and hue-by-angle iridescence, all animating from `mu.time`.

## Code

`index.ts`:

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

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

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

`components/gallery.ts`:

```ts
import { createMaterial, createMesh, createText, getColor, useCubeGeometry, useIcoSphereGeometry, useLoadBitmapFont, useTorusGeometry, useUpdate, useSphereGeometry } from 'nacatamalon';
import * as Settings from '../settings';
import { DISSOLVE, DISSOLVE_GLSL, HOLOGRAM, HOLOGRAM_GLSL, SHIELD, SHIELD_GLSL, PRISM, PRISM_GLSL } from '../shaders/effects';

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

    const shapes = [
        {
            label: 'DISSOLVE',
            wgsl: DISSOLVE,
            glsl: DISSOLVE_GLSL,
            tint: '#e0503a',
            geometry: useSphereGeometry()
        },
        {
            label: 'HOLOGRAM',
            wgsl: HOLOGRAM,
            glsl: HOLOGRAM_GLSL,
            tint: '#20c0ff',
            geometry: useTorusGeometry({
                radius: 0.6,
                tube: 0.24
            })
        },
        {
            label: 'SHIELD',
            wgsl: SHIELD,
            glsl: SHIELD_GLSL,
            tint: '#3a7bff',
            geometry: useIcoSphereGeometry({
                subdivisions: 2
            })
        },
        {
            label: 'PRISM',
            wgsl: PRISM,
            glsl: PRISM_GLSL,
            tint: '#c8c8d0',
            geometry: useCubeGeometry({
                width: 0.9,
                height: 0.9,
                depth: 0.9
            })
        },
    ];

    shapes.forEach(({ label, wgsl, glsl, tint, geometry }, i) => {
        const column = i % 2;
        const row = Math.floor(i / 2);

        const material = createMaterial({
            name: label,
            shader: 'mesh3d',
            tint: getColor(tint),
            fragment: wgsl,
            fragmentGlsl: glsl,
        });

        const mesh = createMesh({
            geometry,
            material,
            transform: {
                x: (column - 0.5) * Settings.SPACING,
                y: (0.5 - row) * Settings.SPACING
            },
        });

        useUpdate((delta) => {
            mesh.transform.rotationY += delta * 0.7;
            mesh.transform.rotationX += delta * 0.25;
        });
    });

    const labels = [
        {
            text: 'DISSOLVE',
            x: 104,
            y: 148
        },
        {
            text: 'HOLOGRAM',
            x: 284,
            y: 148
        },
        {
            text: 'SHIELD',
            x: 124,
            y: 286
        },
        {
            text: 'PRISM',
            x: 316,
            y: 286
        },
    ];

    labels.forEach(({ text, x, y }) => createText({
        text,
        font,
        tint: '#8fb7ff',
        transform: {
            x,
            y,
            rotation: 0,
            scaleX: 1,
            scaleY: 1
        },
    }));
};
```

`scenes/demo.ts`:

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

import { Gallery } from '../components/gallery';

export const Game = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            z: 5.5
        }
    });
    useDirectionalLight({
        color: '#fff0d8',
        intensity: 1.1,
        ambient: 0.2,
        transform: {
            rotationX: -0.5,
            rotationY: 0.6
        }
    });

    useSpawn(Gallery)();

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const SPACING = 2;
```

`shaders/effects.ts`:

```ts
// Colour hooks, in three dimensions. A model material's is a surface shader:
//
//   fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32>
//
// and ctx carries the place on the picture, which way the surface faces, where it is in the world,
// what the lamps added up to, what it gives off by itself, and which way the eye is. So an effect
// can read the shape (the facing, for a rim) and the place (for stripes that stay put on it) and
// use the light on its own terms rather than being handed a colour with the light already stirred in.
//
// All four ride mu.time. None of these four has a picture, so 'surface' is the material's own colour.
// Each is written twice, once per language, so they run on both cards.

export const DISSOLVE = `
fn hash(p: vec2<f32>) -> f32 {
    return fract(sin(dot(p, vec2<f32>(127.1, 311.7))) * 43758.5453);
}
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let t = fract(mu.time * 0.35);
    let e = hash(floor(ctx.uv * 18.0)) - t;
    if (e < 0.0) { return vec4<f32>(0.0, 0.0, 0.0, 0.0); }
    let burn = smoothstep(0.0, 0.15, e);
    let lit = surface.rgb * ctx.light;
    return vec4<f32>(mix(vec3<f32>(1.0, 0.5, 0.1), lit, burn), surface.a);
}
`;
export const DISSOLVE_GLSL = `
float hash(vec2 p) {
    return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}
vec4 effect(vec4 surface, FragContext ctx) {
    float t = fract(mu.time * 0.35);
    float e = hash(floor(ctx.uv * 18.0)) - t;
    if (e < 0.0) { return vec4(0.0); }
    float burn = smoothstep(0.0, 0.15, e);
    vec3 lit = surface.rgb * ctx.light;
    return vec4(mix(vec3(1.0, 0.5, 0.1), lit, burn), surface.a);
}
`;
export const HOLOGRAM = `
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let fresnel = pow(1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0), 2.0);
    let scan = 0.5 + 0.5 * sin(ctx.worldPos.y * 40.0 - mu.time * 6.0);
    let flicker = 0.85 + 0.15 * sin(mu.time * 40.0);
    let glow = vec3<f32>(0.2, 0.9, 1.0) * (0.3 + 0.7 * scan) * flicker;
    return vec4<f32>(glow + fresnel, (0.25 + 0.75 * fresnel) * flicker);
}
`;
export const HOLOGRAM_GLSL = `
vec4 effect(vec4 surface, FragContext ctx) {
    float fresnel = pow(1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0), 2.0);
    float scan = 0.5 + 0.5 * sin(ctx.worldPos.y * 40.0 - mu.time * 6.0);
    float flicker = 0.85 + 0.15 * sin(mu.time * 40.0);
    vec3 glow = vec3(0.2, 0.9, 1.0) * (0.3 + 0.7 * scan) * flicker;
    return vec4(glow + fresnel, (0.25 + 0.75 * fresnel) * flicker);
}
`;
export const SHIELD = `
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let fresnel = pow(1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0), 1.8);
    let pulse = 0.7 + 0.3 * sin(mu.time * 4.0);
    // A little fill on top of the rim, or the dome reads as an outline and not a surface.
    let glow = fresnel * pulse + 0.15;
    let rim = vec3<f32>(0.35, 0.7, 1.0) * 1.5 + surface.rgb * 0.4;
    return vec4<f32>(rim * glow, clamp(glow, 0.0, 1.0));
}
`;
export const SHIELD_GLSL = `
vec4 effect(vec4 surface, FragContext ctx) {
    float fresnel = pow(1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0), 1.8);
    float pulse = 0.7 + 0.3 * sin(mu.time * 4.0);
    float glow = fresnel * pulse + 0.15;
    vec3 rim = vec3(0.35, 0.7, 1.0) * 1.5 + surface.rgb * 0.4;
    return vec4(rim * glow, clamp(glow, 0.0, 1.0));
}
`;
export const PRISM = `
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let fresnel = 1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0);
    let t = fresnel * 4.0 + mu.time;
    let sheen = 0.5 + 0.5 * cos(vec3<f32>(t, t + 2.094, t + 4.188));
    return vec4<f32>(surface.rgb * ctx.light * 0.35 + sheen * 0.85, surface.a);
}
`;
export const PRISM_GLSL = `
vec4 effect(vec4 surface, FragContext ctx) {
    float fresnel = 1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0);
    float t = fresnel * 4.0 + mu.time;
    vec3 sheen = 0.5 + 0.5 * cos(vec3(t, t + 2.094, t + 4.188));
    return vec4(surface.rgb * ctx.light * 0.35 + sheen * 0.85, surface.a);
}
`;
```
