# Snow trails

> A ball ploughing deep snow: a height field in 64 chunks, and only those it touched are rebuilt each frame.

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

A ball rolling through deep snow. WASD or the arrows roll it, space jumps, and R brings fresh snow. It ploughs a packed, bluish trench, pushes the snow it moves into berms at its sides and in front, kicks up powder, and leaves a crater when it lands from a jump. Left alone, the ball drives itself. V, or the button at the top right, shows the snow's mesh.

The snow is a height field of 192 by 192 cells, simulated on the CPU and painted into a picture, a pixel per vertex: its height in red and green, sixteen bits so it rises smoothly, and how packed it is in blue. The snow is one flat plane whose material reads that picture in its vertex hook, as its `field` map, and raises each corner by it; only the rectangle the ball touched is sent again, with `updatePixelTexture(texture, region)`, so the geometry never changes. The engine measures the raised surface again to light it, and the shadow moves its corners the same way. What the ball takes out is not lost: part packs down, the rest piles into the berm and slumps to its angle of repose. One `mesh3d` material, written for both cards, gives it blue shadows and grains that glint only when the sun bounces towards the camera.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Snowfield } from './scenes/snowfield';
import { ACTIONS, HEIGHT, SKY, WIDTH } from './settings';

// A ball rolling through deep snow: it ploughs a packed, bluish trench, pushes the snow it moves into
// berms at its sides and in front, kicks up powder, and leaves a crater when it lands from a jump.
//
//   WASD / arrows   move
//   space           jump
//   R               fresh snow
//   V               switch views: the snow, its mesh (or the button)
//
// Left alone, the ball drives itself.
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: SKY,
    scaling: 'contain',
    step: 60,
    actions: ACTIONS
});

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

`components/ball.ts`:

```ts
import { createMesh, useAction, useDirection, useIcoSphereGeometry, useUpdate } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { BALL, IDLE_SECONDS, SNOW, TREES } from '../settings';
import type { TPowder } from './powder';
import type { TSnow } from './snow';

/**
 * How far the ball may go from the middle, either way.
 */
const LIMIT = SNOW.size / 2 - BALL.edge;

/**
 * The red ball that ploughs the snow. It rolls, jumps and lands, sinks down to the hard ground,
 * presses the snow on its way, and throws up powder. Left alone it drives itself.
 */
export const Ball = ({ snow, powder }: { snow: TSnow; powder: TPowder; }) => {
    const mesh = createMesh({
        geometry: useIcoSphereGeometry({
            radius: BALL.radius,
            subdivisions: 3
        }),
        tint: '#e8584f',
        specular: '#ffffff',
        shininess: 40,
        castShadow: true,
        transform: {
            x: 0,
            y: 1,
            z: 0
        }
    });

    const move = useDirection('left', 'right', 'up', 'down');
    const jump = useAction('jump');
    const random = useRandom();

    const velocity = {
        x: 0,
        y: 0,
        z: 0
    };

    // Where it was last frame, to press the snow all along the way.
    const last = {
        x: 0,
        y: 1,
        z: 0
    };

    let idleFor = IDLE_SECONDS;
    let autoTime = 0;
    let autoJump = 4;
    let grounded = false;
    let rolledX = 0;
    let rolledZ = 0;

    useUpdate((delta) => {
        const at = mesh.transform;

        // Up on the stick or the keys goes away from the camera, along -z.
        let { x: ix, y: iz } = move();
        let jumping = jump.justPressed();

        idleFor = ix !== 0 || iz !== 0 || jumping ? 0 : idleFor + delta;

        if (idleFor > IDLE_SECONDS) {
            autoTime += delta * 0.32;
            ix = Math.sin(autoTime * 1.3) * 7 + Math.sin(autoTime * 0.5) * 2 - at.x;
            iz = Math.sin(autoTime * 2.1 + 1) * 6 - at.z;
            autoJump -= delta;

            if (autoJump <= 0) {
                jumping = true;
                autoJump = random.rand(5, 8);
            }
        }

        const length = Math.hypot(ix, iz);

        if (length > 1) {
            ix /= length;
            iz /= length;
        }

        // Rolling through snow slows it down.
        const steering = ix !== 0 || iz !== 0;

        velocity.x += ix * BALL.accel * delta;
        velocity.z += iz * BALL.accel * delta;

        const drag = Math.exp(-(steering ? BALL.drag : BALL.stopDrag) * delta);

        velocity.x *= drag;
        velocity.z *= drag;

        if (jumping && grounded) {
            velocity.y = BALL.jump;
            grounded = false;
        }

        velocity.y -= BALL.gravity * delta;
        at.x += velocity.x * delta;
        at.y += velocity.y * delta;
        at.z += velocity.z * delta;

        // The edges, and the trees.
        at.x = Math.min(Math.max(at.x, -LIMIT), LIMIT);
        at.z = Math.min(Math.max(at.z, -LIMIT), LIMIT);

        for (const [tx, tz, s] of TREES) {
            const dx = at.x - tx;
            const dz = at.z - tz;
            const d = Math.hypot(dx, dz);
            const min = BALL.radius + 0.2 * s;

            if (d < min && d > 0.0001) {
                at.x = tx + (dx / d) * min;
                at.z = tz + (dz / d) * min;

                const dot = (velocity.x * dx + velocity.z * dz) / d;

                if (dot < 0) {
                    velocity.x -= (dx / d) * dot * 1.5;
                    velocity.z -= (dz / d) * dot * 1.5;
                }
            }
        }

        // It sinks through the snow down to the hard ground. Landing from a jump leaves a crater.
        const rest = snow.floor + BALL.radius;
        let impact = 0;

        if (at.y <= rest) {
            impact = grounded ? 0 : -velocity.y;
            at.y = rest;
            velocity.y = 0;
            grounded = true;
        }

        const speed = Math.hypot(velocity.x, velocity.z);
        const dirX = speed > 0.01 ? velocity.x / speed : 0;
        const dirZ = speed > 0.01 ? velocity.z / speed : 0;

        // It presses every point along this frame's way too, so the trench comes out smooth and not
        // in steps however far it went.
        const travel = Math.hypot(at.x - last.x, at.z - last.z);
        const steps = Math.min(12, Math.max(1, Math.ceil(travel / 0.08)));
        let moved = 0;

        for (let k = 1; k <= steps; k++) {
            const px = last.x + ((at.x - last.x) * k) / steps;
            const py = last.y + ((at.y - last.y) * k) / steps;
            const pz = last.z + ((at.z - last.z) * k) / steps;

            if (py - BALL.radius < snow.surfaceAt(px, pz) + 0.02) {
                moved += snow.press(px, py, pz, BALL.radius, dirX, dirZ);
            }
        }

        last.x = at.x;
        last.y = at.y;
        last.z = at.z;

        if (impact > SNOW.craterImpact) {
            moved += snow.press(at.x, at.y, at.z, BALL.radius, dirX, dirZ, SNOW.craterSize);
            powder.kick(at.x, snow.floor + 0.2, at.z, Math.min(160, Math.round(impact * 14)));
        }

        if (grounded && speed > 0.6) {
            powder.kick(at.x + dirX * BALL.radius * 0.8, snow.floor + 0.25, at.z + dirZ * BALL.radius * 0.8, Math.min(6, Math.round(moved * 3 + speed * 0.6)));
        }

        // It really rolls: it turns about the axis across its way.
        rolledX += (velocity.z * delta) / BALL.radius;
        rolledZ -= (velocity.x * delta) / BALL.radius;
        at.rotationX = rolledX;
        at.rotation = rolledZ;
    });

    return {
        mesh
    };
};
```

`components/powder.ts`:

```ts
import { createParticles3d, emitParticles } from 'nacatamalon';
import { createPixels, createPixelTexture, setPixel } from 'nacatamalon/pixels';

/**
 * A soft dot for the flakes.
 */
const paintFlake = () => {
    const size = 16;
    const flake = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const d = Math.hypot(x + 0.5 - size / 2, y + 0.5 - size / 2) / (size / 2);
            const alpha = Math.max(0, 1 - d) ** 1.6;

            setPixel(flake, x, y, `rgba(255, 255, 255, ${alpha.toFixed(3)})`);
        }
    }

    return createPixelTexture(flake);
};

/**
 * The snow in the air: flakes falling round what the camera sees, and powder thrown up where the
 * ball ploughs and lands.
 */
export const Powder = () => {
    const flake = paintFlake();

    const snowfall = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: flake,
            worldSpace: true,
            max: 1400,
            emission: {
                rate: 140
            },
            shape: {
                kind: 'box',
                size: [26, 0.5, 26]
            },
            direction: {
                x: 0,
                y: -1,
                z: 0
            },
            spread: 0.4,
            speed: [0.5, 1.1],
            gravity: {
                x: 0.25,
                y: -0.15,
                z: 0.05
            },
            life: [7, 10],
            size: [0.05, 0.11],
            colorOverLife: [
                {
                    t: 0,
                    color: '#ffffff',
                    alpha: 0
                },
                {
                    t: 0.1,
                    color: '#ffffff',
                    alpha: 0.9
                },
                {
                    t: 0.9,
                    color: '#ffffff',
                    alpha: 0.9
                },
                {
                    t: 1,
                    color: '#ffffff',
                    alpha: 0
                }
            ]
        },
        transform: {
            x: 0,
            y: 8,
            z: 0
        }
    });

    const spray = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: flake,
            worldSpace: true,
            max: 600,
            emission: {
                rate: 0,
                burst: 0
            },
            shape: {
                kind: 'sphere',
                radius: 0.35,
                edge: true
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 1.3,
            speed: [1.2, 3.2],
            gravity: {
                y: -9
            },
            damping: 0.8,
            life: [0.5, 1.1],
            size: [0.05, 0.13],
            colorOverLife: [
                {
                    t: 0,
                    color: '#ffffff',
                    alpha: 1
                },
                {
                    t: 1,
                    color: '#e6eeff',
                    alpha: 0
                }
            ]
        }
    });

    return {
        /**
         * Throws up `count` grains of powder at a place in the world.
         */
        kick: (x: number, y: number, z: number, count: number) => {
            spray.transform.x = x;
            spray.transform.y = y;
            spray.transform.z = z;
            emitParticles(spray, count);
        },
        /**
         * Keeps the flakes falling over what the camera sees.
         */
        follow: (x: number, z: number) => {
            snowfall.transform.x = x;
            snowfall.transform.z = z;
        }
    };
};

export type TPowder = ReturnType<typeof Powder>;
```

`components/snow.ts`:

```ts
import { createMaterial, createMesh, useAction, useLateUpdate, usePlaneGeometry } from 'nacatamalon';
import { SNOW_GLSL, SNOW_VERTEX_GLSL, SNOW_VERTEX_WGSL, SNOW_WGSL, type TSnowKnobs } from '../shaders/snow';
import { createSnowField } from '../simulation/snow_field';
import { SNOW, SNOW_LOOK, SUN } from '../settings';

/**
 * The snow: the height field, one flat plane its material raises by the field's picture, and R for
 * fresh snow. What presses it (the ball) does so through what this returns; the part of the picture
 * it touched is sent once a frame, after everything has moved.
 */
export const Snow = () => {
    const field = createSnowField(SNOW);

    // Towards the sun, for the glints: the other way from where it shines.
    const knobs: TSnowKnobs = {
        sun: [Math.sin(SUN.rotationY) * Math.cos(SUN.rotationX), -Math.sin(SUN.rotationX), Math.cos(SUN.rotationY) * Math.cos(SUN.rotationX)],
        shadowColor: SNOW_LOOK.shadowColor,
        grain: SNOW_LOOK.grain,
        sparkles: SNOW_LOOK.sparkles,
        // Where the field's picture lies: half its size, one cell, how many pixels across, and the
        // height its sixteen bits run up to.
        field: [SNOW.size / 2, SNOW.size / SNOW.cells, SNOW.cells + 1, SNOW.maxHeight]
    };

    const material = createMaterial({
        shader: 'mesh3d',
        name: 'snow',
        vertex: SNOW_VERTEX_WGSL,
        vertexGlsl: SNOW_VERTEX_GLSL,
        fragment: SNOW_WGSL,
        fragmentGlsl: SNOW_GLSL,
        maps: {
            // Read pixel by pixel: the hook blends the four round each corner itself, since the
            // height is split over two bytes that cannot be blended apart.
            field: {
                texture: field.texture,
                smooth: false,
                wrap: 'clamp'
            }
        },
        uniforms: knobs
    });

    // A corner for every vertex of the field, flat: the hook raises each one to the snow's height.
    createMesh({
        geometry: usePlaneGeometry({
            width: SNOW.size,
            depth: SNOW.size,
            widthSegments: SNOW.cells,
            depthSegments: SNOW.cells
        }),
        material,
        // The hook raises it up to this far: the engine has to know, to tell when it is in view.
        boundsMargin: SNOW.maxHeight
    });

    const fresh = useAction('fresh');

    // How many times the snow has changed, so the mesh view knows when to draw its lines again.
    let changes = 0;

    useLateUpdate(() => {
        if (fresh.justPressed()) {
            field.reset();
        }

        if (field.flush()) {
            changes++;
        }
    });

    return {
        press: field.press,
        surfaceAt: field.surfaceAt,
        wireframe: field.wireframe,
        floor: field.floor,
        changes: () => changes
    };
};

export type TSnow = ReturnType<typeof Snow>;
```

`components/trees.ts`:

```ts
import { createMesh, useConeGeometry, useCylinderGeometry } from 'nacatamalon';
import { TREES } from '../settings';
import type { TSnow } from './snow';

/**
 * The pines, with snow on top, standing a little sunk in the snow.
 */
export const Trees = ({ snow }: { snow: TSnow; }) => {
    const trunk = useCylinderGeometry({
        radius: 0.16,
        height: 1,
        segments: 8
    });

    const crown = useConeGeometry({
        radius: 0.9,
        height: 1.6,
        segments: 10
    });

    const cap = useConeGeometry({
        radius: 0.55,
        height: 0.7,
        segments: 10
    });

    for (const [x, z, s] of TREES) {
        const base = snow.surfaceAt(x, z) - 0.2;

        createMesh({
            geometry: trunk,
            tint: '#5a4032',
            castShadow: true,
            transform: {
                x,
                y: base + 0.5 * s,
                z,
                scaleX: s,
                scaleY: s,
                scaleZ: s
            }
        });
        createMesh({
            geometry: crown,
            tint: '#2f5a48',
            castShadow: true,
            transform: {
                x,
                y: base + 1.8 * s,
                z,
                scaleX: s,
                scaleY: s,
                scaleZ: s
            }
        });
        createMesh({
            geometry: crown,
            tint: '#3b6b56',
            castShadow: true,
            transform: {
                x,
                y: base + 2.5 * s,
                z,
                scaleX: s * 0.7,
                scaleY: s * 0.8,
                scaleZ: s * 0.7
            }
        });
        createMesh({
            geometry: cap,
            tint: '#f4f8ff',
            castShadow: true,
            transform: {
                x,
                y: base + 3.05 * s,
                z,
                scaleX: s * 0.7,
                scaleY: s * 0.7,
                scaleZ: s * 0.7
            }
        });
    }
};
```

`components/views.ts`:

```ts
import { createSprite, createText, listen, setLines, useAction, useLateUpdate, useLines } from 'nacatamalon';
import { MESH_VIEW, VIEWS, WIDTH } from '../settings';
import type { TSnow } from './snow';

/**
 * The two ways to look at the snow, switched with V or the button at the top right: SNOW as it is,
 * and MESH, its height field in wireframe, drawn again as the ball deforms it.
 */
export const Views = ({ snow }: { snow: TSnow; }) => {
    let view = 0;

    const button = createSprite({
        width: 150,
        height: 18,
        tint: '#1c2338',
        anchor: {
            x: 1,
            y: 0
        },
        zIndex: 100,
        transform: {
            x: WIDTH - 8,
            y: 5
        }
    });

    const label = createText({
        text: '',
        tint: '#ffd9a0',
        anchor: {
            x: 0.5,
            y: 0
        },
        zIndex: 101,
        transform: {
            x: WIDTH - 83,
            y: 10
        }
    });

    const lines = useLines();
    const vertices: number[] = [];

    // The snow's changes the lines last showed; -1 draws them the next time the view is MESH.
    let drawn = -1;

    const show = () => {
        label.text = `[V] VIEW: ${VIEWS[view]}`;
        lines.visible = VIEWS[view] === 'MESH';
        drawn = -1;
    };

    const next = () => {
        view = (view + 1) % VIEWS.length;
        show();
    };

    listen(button, {
        onClick: next
    });
    listen(label, {
        onClick: next
    });
    show();

    const switchView = useAction('view');

    useLateUpdate((_delta, time) => {
        if (switchView.justPressed()) {
            next();
        }

        // The whole mesh is a lot of lines: drawn again only when the snow changed, and at most
        // ten times a second.
        if (VIEWS[view] === 'MESH' && drawn !== snow.changes() && Math.floor(time * 20) % 2 === 0) {
            setLines(lines, new Float32Array(snow.wireframe(MESH_VIEW.every, vertices)));
            drawn = snow.changes();
        }
    });
};
```

`scenes/snowfield.ts`:

```ts
import { cameraLookAt, createScene, createText, useAmbientLight, useCamera3d, useDirectionalLight, useFog, useSpawn, useUpdate } from 'nacatamalon';
import { Ball } from '../components/ball';
import { Powder } from '../components/powder';
import { Snow } from '../components/snow';
import { Trees } from '../components/trees';
import { Views } from '../components/views';
import { HEIGHT, SKY, SUN } from '../settings';

/**
 * A field of deep snow under a low sun, with a few pines. The snow and the powder are made before
 * the ball, which is handed what they return so it can press one and throw up the other.
 */
export const Snowfield = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            x: 0,
            y: 7,
            z: 9
        }
    });

    useFog({
        color: SKY,
        near: 10,
        far: 22
    });
    useAmbientLight({
        color: '#c4d3f0',
        intensity: 0.55
    });
    useDirectionalLight({
        color: '#fff1de',
        intensity: 1.15,
        castShadow: true,
        shadowArea: 36,
        transform: {
            rotationX: SUN.rotationX,
            rotationY: SUN.rotationY
        }
    });

    const snow = useSpawn(Snow)();

    useSpawn(Trees)({
        snow: snow.api
    });

    const powder = useSpawn(Powder)();

    const ball = useSpawn(Ball)({
        snow: snow.api,
        powder: powder.api
    });

    useSpawn(Views)({
        snow: snow.api
    });

    createText({
        text: 'WASD / ARROWS: MOVE   SPACE: JUMP   R: FRESH SNOW',
        tint: '#24304d',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });
    createText({
        text: 'SNOW TRAILS · NACATAMALON',
        tint: '#24304d',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    // The camera follows the ball from above, a little late, and the flakes fall over what it sees.
    useUpdate((delta) => {
        const at = ball.api.mesh.transform;
        const follow = 1 - Math.exp(-2.5 * delta);

        camera.transform.x += (at.x * 0.7 - camera.transform.x) * follow;
        camera.transform.z += (at.z * 0.7 + 8 - camera.transform.z) * follow;
        cameraLookAt(camera, {
            x: at.x * 0.7,
            y: 0.3,
            z: at.z * 0.7
        });
        powder.api.follow(at.x * 0.6, at.z * 0.6);
    });

    return createScene();
};
```

`settings.ts`:

```ts
import { INPUT, type TActionDef } from 'nacatamalon';

/**
 * The game's size, in its own pixels.
 */
export const WIDTH = 640;
export const HEIGHT = 360;

/**
 * The sky, and the distance fog that fades the far end into it.
 */
export const SKY = '#aebfdc';

/**
 * Moving and jumping as a platformer reads them (WASD or the arrows, space, a pad), R for fresh snow,
 * and V to switch views.
 */
export const ACTIONS: TActionDef[] = [
    ...INPUT.ACTION_PRESETS.platformer,
    {
        name: 'fresh',
        bindings: [
            {
                type: 'key',
                key: 'r'
            }
        ]
    },
    {
        name: 'view',
        bindings: [
            {
                type: 'key',
                key: 'v'
            }
        ]
    }
];

/**
 * What V and the button at the top right show: the snow as it is, and its mesh in wireframe, one
 * vertex in `every` each way.
 */
export const VIEWS = ['SNOW', 'MESH'] as const;

export const MESH_VIEW = {
    every: 2
};

/**
 * The snow: `size` by `size` world units (metres) round the middle, in `cells` by `cells` cells of
 * 12.5 cm. `floor` is the hard ground under it: nothing presses deeper. `maxHeight` is the highest
 * the picture of its shape can say it is.
 */
export const SNOW = {
    size: 24,
    cells: 192,
    maxHeight: 2,
    floor: 0.06,
    /**
     * Of what the ball takes out, the part that is not packed down but piled into the berm.
     */
    piled: 0.55,
    /**
     * A landing harder than this leaves a crater, this many times the ball's footprint.
     */
    craterImpact: 3,
    craterSize: 1.45
};

/**
 * The look of the snow, read by its shader: blue in the shadows, grains `grain` to the metre, and the
 * share of them, `sparkles`, that glint.
 */
export const SNOW_LOOK = {
    shadowColor: [0.3, 0.55, 1.0],
    grain: 28,
    sparkles: 0.02
};

/**
 * The low afternoon sun: turned down (rotationX) and to the side (rotationY).
 */
export const SUN = {
    rotationX: -0.75,
    rotationY: 0.75
};

/**
 * The red ball, in world units and seconds. It never goes nearer the edge than `edge`.
 */
export const BALL = {
    radius: 0.5,
    accel: 16,
    gravity: 20,
    jump: 7.5,
    edge: 1.2,
    /**
     * Rolling through snow slows it: gently while it is steered, faster when let go.
     */
    drag: 2.6,
    stopDrag: 5
};

/**
 * Left alone this many seconds, the ball draws curves by itself and jumps now and then.
 */
export const IDLE_SECONDS = 3;

/**
 * The pines, where they stand (x, z) and how big. They are walls for the ball.
 */
export const TREES: readonly (readonly [number, number, number])[] = [[-10.5, 8.84, 0.65], [-6.08, 4.82, 0.74], [5.36, 0.9, 0.79], [2.85, 6.65, 0.63], [4.16, -9.37, 0.79], [-0.67, 8.87, 0.83], [-7.92, 0.27, 0.87], [8.58, -2.68, 0.67], [-7.3, -4.25, 0.7], [-4.31, 9.18, 0.75]];
```

`shaders/snow.ts`:

```ts
// The snow: the engine's lighting with the height field's normals, so the trench and the berm have
// real relief, and three things that make it read as snow:
// - the shadows are not grey but blue, as snow under an open sky is;
// - glints: loose grains that only flash when the sun bounces towards the camera, so they twinkle as
//   you move;
// - packed snow (a little bluer) shines a little more, as if iced.
//
// Its shape is not in the geometry, one flat plane, but in a picture of the field the game paints:
// the vertex hook reads it and raises each corner to the snow's height, and the engine measures the
// raised surface again to light it. How packed it is goes on to the colour hook through `carry`.

export type TSnowKnobs = {
    /**
     * Towards the sun, for the glints.
     */
    sun: number[];
    shadowColor: number[];
    grain: number;
    sparkles: number;
    /**
     * Half the field's size, one cell, the picture's pixels across, and the height it runs up to.
     */
    field: number[];
};

// The height and how packed the snow is at one pixel of the field's picture: the height in red and
// green (high byte, low byte), packed in blue. Read at the pixel's middle, so nothing is blended.
// Then the four pixels round the corner blended by hand, as a smooth map would, but over the whole
// sixteen bits.
export const SNOW_VERTEX_WGSL = /* wgsl */ `
fn snowAt(cell: vec2<f32>) -> vec2<f32> {
    let s = sampleMap_field((cell + vec2<f32>(0.5)) / mu.field.z);
    return vec2<f32>((s.r * 65280.0 + s.g * 255.0) / 65535.0 * mu.field.w, s.b);
}

fn vertex(pos: vec3<f32>, ctx: VertContext) -> vec3<f32> {
    // Where the corner is on the field's grid, from where it is: the engine measures the surface
    // again a hair to each side, and has to find it raised there too.
    let grid = (pos.xz + vec2<f32>(mu.field.x)) / mu.field.y;
    let cell = floor(grid);
    let f = grid - cell;
    let near = mix(snowAt(cell), snowAt(cell + vec2<f32>(1.0, 0.0)), f.x);
    let far = mix(snowAt(cell + vec2<f32>(0.0, 1.0)), snowAt(cell + vec2<f32>(1.0, 1.0)), f.x);
    let here = mix(near, far, f.y);
    carry = vec4<f32>(here.y, 0.0, 0.0, 0.0);
    return vec3<f32>(pos.x, here.x, pos.z);
}
`;

export const SNOW_VERTEX_GLSL = /* glsl */ `
vec2 snowAt(vec2 cell) {
    vec4 s = sampleMap_field((cell + vec2(0.5)) / mu.field.z);
    return vec2((s.r * 65280.0 + s.g * 255.0) / 65535.0 * mu.field.w, s.b);
}

vec3 vertex(vec3 pos, VertContext ctx) {
    vec2 grid = (pos.xz + vec2(mu.field.x)) / mu.field.y;
    vec2 cell = floor(grid);
    vec2 f = grid - cell;
    vec2 near = mix(snowAt(cell), snowAt(cell + vec2(1.0, 0.0)), f.x);
    vec2 far = mix(snowAt(cell + vec2(0.0, 1.0)), snowAt(cell + vec2(1.0, 1.0)), f.x);
    vec2 here = mix(near, far, f.y);
    carry = vec4(here.y, 0.0, 0.0, 0.0);
    return vec3(pos.x, here.x, pos.z);
}
`;

export const SNOW_WGSL = /* wgsl */ `
fn snowHash(p: vec3<f32>) -> f32 {
    return fract(sin(dot(p, vec3<f32>(127.1, 311.7, 74.7))) * 43758.5453);
}

fn effect(plain: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    // Loose snow is white; packed, a little blue-grey, as in a real trench.
    let p = ctx.carry.x;
    let surface = plain * vec4<f32>(1.0 - p * 0.3, 1.0 - p * 0.2, 1.0 - p * 0.04, 1.0);
    let n = normalize(ctx.normal);
    let lit = ctx.light;
    let level = clamp(dot(lit, vec3<f32>(0.3333)), 0.0, 1.0);
    let cold = mu.shadowColor * smoothstep(0.75, 0.25, level) * 0.35;
    // A touch more exposure: the snow is the brightest thing in the scene.
    var color = surface.rgb * lit * 1.18 + cold * surface.rgb;

    let toSun = normalize(mu.sun);
    let halfway = normalize(toSun + ctx.viewDir);
    let glint = pow(max(dot(n, halfway), 0.0), 24.0);
    let grain = floor(ctx.worldPos * mu.grain);
    let sparkle = step(1.0 - mu.sparkles, snowHash(grain)) * glint;
    let icy = (1.0 - surface.r) * 3.0;
    color = color + vec3<f32>(1.0, 0.97, 0.9) * (sparkle * 2.5 + glint * icy * 0.35) * level;
    return vec4<f32>(color, 1.0);
}
`;

export const SNOW_GLSL = /* glsl */ `
float snowHash(vec3 p) {
    return fract(sin(dot(p, vec3(127.1, 311.7, 74.7))) * 43758.5453);
}

vec4 effect(vec4 plain, FragContext ctx) {
    float p = ctx.carry.x;
    vec4 surface = plain * vec4(1.0 - p * 0.3, 1.0 - p * 0.2, 1.0 - p * 0.04, 1.0);
    vec3 n = normalize(ctx.normal);
    vec3 lit = ctx.light;
    float level = clamp(dot(lit, vec3(0.3333)), 0.0, 1.0);
    vec3 cold = mu.shadowColor * smoothstep(0.75, 0.25, level) * 0.35;
    vec3 color = surface.rgb * lit * 1.18 + cold * surface.rgb;

    vec3 toSun = normalize(mu.sun);
    vec3 halfway = normalize(toSun + ctx.viewDir);
    float glint = pow(max(dot(n, halfway), 0.0), 24.0);
    vec3 grain = floor(ctx.worldPos * mu.grain);
    float sparkle = step(1.0 - mu.sparkles, snowHash(grain)) * glint;
    float icy = (1.0 - surface.r) * 3.0;
    color += vec3(1.0, 0.97, 0.9) * (sparkle * 2.5 + glint * icy * 0.35) * level;
    return vec4(color, 1.0);
}
`;
```

`simulation/snow_field.ts`:

```ts
import { createPixelTexture, createPixels, updatePixelTexture } from 'nacatamalon/pixels';

// The snow field: a height field (how deep the snow is at each vertex) that the ball deforms.
//
// - It is painted into a picture, a pixel per vertex, which the snow's material reads in its vertex
//   hook to raise one flat plane. Only the rectangle the ball touched is sent again, so pressing is
//   cheap however big the field is, and the geometry never changes.
// - As it passes, the ball presses the snow down to its own shape (a cap of a sphere), and what it
//   takes out is not lost: part packs down, the rest piles into a berm at its sides and in front.
// - Each vertex also keeps how packed it is, which goes to its colour: the trench comes out bluer.

const hash = (x: number, y: number) => {
    const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;

    return s - Math.floor(s);
};

const noise = (x: number, y: number) => {
    const ix = Math.floor(x);
    const iy = Math.floor(y);
    const fx = x - ix;
    const fy = y - iy;
    const ux = fx * fx * (3 - 2 * fx);
    const uy = fy * fy * (3 - 2 * fy);
    const a = hash(ix, iy);
    const b = hash(ix + 1, iy);
    const c = hash(ix, iy + 1);
    const d = hash(ix + 1, iy + 1);

    return a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy;
};

const fbm = (x: number, y: number) => noise(x, y) * 0.55 + noise(x * 2.1 + 7, y * 2.1 + 3) * 0.3 + noise(x * 4.3 + 1, y * 4.3 + 9) * 0.15;

export type TSnowFieldOptions = {
    /**
     * World units across, round the middle.
     */
    size: number;
    cells: number;
    /**
     * The hard ground under the snow: nothing presses deeper.
     */
    floor: number;
    /**
     * The highest the picture can say the snow is: the range its sixteen bits are spread over.
     */
    maxHeight: number;
    /**
     * Of what is pressed out, the part piled into the berm; the rest packs down.
     */
    piled: number;
};

export type TSnowField = ReturnType<typeof createSnowField>;

export const createSnowField = ({ size, cells, floor, maxHeight, piled }: TSnowFieldOptions) => {
    const n = cells + 1;
    const step = size / cells;
    const half = size / 2;
    const height = new Float32Array(n * n);
    const packed = new Float32Array(n * n);

    const at = (x: number, z: number) => z * n + x;

    const reset = () => {
        for (let z = 0; z < n; z++) {
            for (let x = 0; x < n; x++) {
                const wx = x * step - half;
                const wz = z * step - half;

                // Soft dunes left by the wind, and a little grain on top.
                height[at(x, z)] = 0.3 + fbm(wx * 0.18, wz * 0.18) * 0.22 + fbm(wx * 1.3, wz * 1.3) * 0.025;
                packed[at(x, z)] = 0;
            }
        }

        markDirty(0, 0, n - 1, n - 1);
    };

    // The picture the snow's material reads its shape from: a pixel for each vertex of the field,
    // the height in red and green (sixteen bits, so it rises smoothly and not in steps) and how packed
    // it is in blue. The material's vertex hook reads it and raises the plane by it.
    const shape = createPixels(n, n, '#000000');

    // The rectangle of vertices changed since the picture was last sent: x0, z0, x1, z1, or none.
    let dirty: [number, number, number, number] | null = null;

    const markDirty = (x0: number, z0: number, x1: number, z1: number) => {
        // One more each way: the snow slumping moves the vertices next to the ones pressed.
        const box: [number, number, number, number] = [Math.max(0, x0 - 1), Math.max(0, z0 - 1), Math.min(n - 1, x1 + 1), Math.min(n - 1, z1 + 1)];

        dirty = dirty === null ? box : [Math.min(dirty[0], box[0]), Math.min(dirty[1], box[1]), Math.max(dirty[2], box[2]), Math.max(dirty[3], box[3])];
    };

    const paint = (x0: number, z0: number, x1: number, z1: number) => {
        for (let z = z0; z <= z1; z++) {
            for (let x = x0; x <= x1; x++) {
                const i = at(x, z);
                const level = Math.round(Math.min(1, Math.max(0, height[i] / maxHeight)) * 65535);
                const pixel = i * 4;

                shape.data[pixel] = level >> 8;
                shape.data[pixel + 1] = level & 255;
                shape.data[pixel + 2] = Math.round(packed[i] * 255);
                shape.data[pixel + 3] = 255;
            }
        }
    };

    // The first snow, painted whole before the picture is made, so it is there from the first frame.
    reset();
    paint(0, 0, n - 1, n - 1);
    dirty = null;

    const texture = createPixelTexture(shape);

    /**
     * The ball presses the snow. `cx, cy, cz` is its centre in the world, `radius` its radius, and
     * `dirX, dirZ` where it is going (to pile more in front). `extra` widens the footprint: a landing
     * leaves a crater. Returns how much snow it moved, to throw up powder in proportion.
     */
    const press = (cx: number, cy: number, cz: number, radius: number, dirX: number, dirZ: number, extra = 1) => {
        const r = radius * extra;
        const ring = r * 2.0;
        const gx = (cx + half) / step;
        const gz = (cz + half) / step;
        const reach = Math.ceil(ring / step) + 1;
        const x0 = Math.max(1, Math.floor(gx - reach));
        const x1 = Math.min(n - 2, Math.ceil(gx + reach));
        const z0 = Math.max(1, Math.floor(gz - reach));
        const z1 = Math.min(n - 2, Math.ceil(gz + reach));
        let removed = 0;

        // 1. Down to the ball's shape (with the footprint widened if it is a crater).
        for (let z = z0; z <= z1; z++) {
            for (let x = x0; x <= x1; x++) {
                const d = Math.hypot(x * step - half - cx, z * step - half - cz);

                if (d >= r) {
                    continue;
                }

                const i = at(x, z);
                const bottom = cy - Math.sqrt(Math.max(0, radius * radius - (d / extra) ** 2));
                const target = Math.max(floor, bottom);

                if (height[i] > target) {
                    removed += height[i] - target;
                    height[i] = target;
                }

                packed[i] = Math.max(packed[i], 1 - (d / r) * 0.4);
            }
        }

        if (removed <= 0) {
            return 0;
        }

        // 2. What does not pack down piles into a berm round it, more in front and at the sides than
        //    behind (the ball has already been there).
        const keep = removed * piled;
        let weightSum = 0;

        const weightOf = (wx: number, wz: number) => {
            const d = Math.hypot(wx - cx, wz - cz);

            if (d < r * 1.02 || d > ring) {
                return 0;
            }

            const ahead = ((wx - cx) / d) * dirX + ((wz - cz) / d) * dirZ;
            const bias = 0.35 + Math.max(0, ahead) * 1.1 + (1 - Math.abs(ahead)) * 0.6;

            return Math.exp(-(((d - r * 1.3) / (r * 0.28)) ** 2)) * bias;
        };

        for (let z = z0; z <= z1; z++) {
            for (let x = x0; x <= x1; x++) {
                weightSum += weightOf(x * step - half, z * step - half);
            }
        }

        if (weightSum > 0) {
            for (let z = z0; z <= z1; z++) {
                for (let x = x0; x <= x1; x++) {
                    const w = weightOf(x * step - half, z * step - half);

                    if (w > 0) {
                        height[at(x, z)] += (keep * w) / weightSum;
                    }
                }
            }
        }

        // 3. Loose snow holds no straight walls: it slumps a little, to its angle of repose.
        const slope = step * 0.9;

        for (let pass = 0; pass < 2; pass++) {
            for (let z = z0; z <= z1; z++) {
                for (let x = x0; x <= x1; x++) {
                    const i = at(x, z);

                    for (const j of [i + 1, i - 1, i + n, i - n]) {
                        const diff = height[i] - height[j];

                        if (diff > slope && height[j] >= floor) {
                            const move = (diff - slope) * 0.25;

                            height[i] -= move;
                            height[j] += move;
                        }
                    }
                }
            }
        }

        markDirty(x0, z0, x1, z1);

        return removed;
    };

    /**
     * Sends the part of the picture that changed since the last time, and says whether there was
     * any.
     */
    const flush = () => {
        if (dirty === null) {
            return false;
        }

        const [x0, z0, x1, z1] = dirty;

        dirty = null;
        paint(x0, z0, x1, z1);
        updatePixelTexture(texture, {
            x: x0,
            y: z0,
            width: x1 - x0 + 1,
            height: z1 - z0 + 1
        });

        return true;
    };

    /**
     * How high the snow is at a place in the world, to set the ball on top of it.
     */
    const surfaceAt = (wx: number, wz: number) => {
        const gx = Math.min(n - 1.001, Math.max(0, (wx + half) / step));
        const gz = Math.min(n - 1.001, Math.max(0, (wz + half) / step));
        const x = Math.floor(gx);
        const z = Math.floor(gz);
        const fx = gx - x;
        const fz = gz - z;
        const a = height[at(x, z)] + (height[at(x + 1, z)] - height[at(x, z)]) * fx;
        const b = height[at(x, z + 1)] + (height[at(x + 1, z + 1)] - height[at(x, z + 1)]) * fx;

        return a + (b - a) * fz;
    };

    /**
     * The mesh's lines (one vertex in `every` each way) as `useLines` takes them, for the wireframe
     * view. Packed snow comes out warmer.
     */
    const wireframe = (every: number, out: number[]) => {
        out.length = 0;

        const push = (x: number, z: number) => {
            const p = packed[at(x, z)];

            out.push(x * step - half, height[at(x, z)] + 0.01, z * step - half, 0.45 + p * 0.5, 0.7, 1 - p * 0.4, 0.75);
        };

        for (let z = 0; z < n; z += every) {
            for (let x = 0; x + every < n; x += every) {
                push(x, z);
                push(x + every, z);
            }
        }

        for (let x = 0; x < n; x += every) {
            for (let z = 0; z + every < n; z += every) {
                push(x, z);
                push(x, z + every);
            }
        }

        return out;
    };

    return {
        texture,
        press,
        flush,
        reset,
        surfaceAt,
        wireframe,
        floor
    };
};
```
