# Grass

> A meadow of about 37,000 blades, each an instance of one shape, bent in the vertex hook of one 3D material, with the ball's trail painted into a picture of the meadow.

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

A meadow of about 37,000 blades that sway in travelling gusts. WASD or the arrows roll the ball through it, and space jumps. The grass parts round the ball, stays trodden where it went and slowly stands back up, and a landing flattens a ring round it. Glowing orbs wander over the meadow: roll into the low ones, jump for the high ones. Left alone, the ball drives itself. V, or the button at the top right, shows what bends each blade: red is the ball and its trail, blue the wind.

Every blade is the same shape of 7 vertices, made once with `createGeometry` and drawn as instances: the meadow is 100 chunks, each a `createMeshInstances` that places, sizes and colours its blades, so the engine can leave out the chunks out of view. Each blade's seed rides in its instance's own numbers, and the hook reads it and where the blade is planted (`ctx.instance`, `ctx.origin`). Everything moves in the vertex hook of one `mesh3d` material, written for both cards: nothing changes on the CPU. The trail is a picture over the whole meadow, the material's `trail` map, that says at each place which way the grass lies and how far: the game paints it where the ball goes and fades it as the grass stands up, and the vertex hook reads it at the root of each blade, so the trail is as long as the ball makes it. The hook also says every blade faces up (`surfaceNormal`), so the grass is lit by the engine itself, sun, orbs and the ball's shadow included, as a thin blade with no dark side; each blade is its triangles twice, one set for each side, so both are lit that way. The orbs are additive 3D particles with a point light each.

## Code

`index.ts`:

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

// A meadow of about 37,000 blades that sway in travelling gusts, part round a rolling ball, stay
// trodden where it went and slowly stand back up. Landing from a jump flattens a ring round it.
// Glowing orbs wander over the meadow: roll into the low ones, jump for the high ones.
//
//   WASD / arrows   move
//   space           jump
//   V               switch views: the grass, what bends it (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({
    Meadow
});
```

`components/ball.ts`:

```ts
import { createMesh, useAction, useDirection, useIcoSphereGeometry, useUpdate } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { BALL, IDLE_SECONDS, MEADOW, ROCKS, TRAIL } from '../settings';
import type { TGrass } from './grass';
import type { TPollen } from './pollen';

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

/**
 * The white ball that treads the grass. It rolls, jumps and lands, bumps into the rocks, tells the
 * grass where it is and where it went, and flattens a ring when it lands. Left alone it drives
 * itself.
 */
export const Ball = ({ grass, pollen }: { grass: TGrass; pollen: TPollen; }) => {
    const mesh = createMesh({
        geometry: useIcoSphereGeometry({
            radius: BALL.radius,
            subdivisions: 3
        }),
        tint: '#f0f0f4',
        specular: '#ffffff',
        shininess: 30,
        castShadow: true,
        transform: {
            x: BALL.start.x,
            y: BALL.radius,
            z: BALL.start.z
        }
    });

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

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

    // Where it last left a point of the trail.
    const mark = {
        x: Infinity,
        z: Infinity
    };

    let idleFor = IDLE_SECONDS;
    let autoTime = 0;
    let autoJump = 4;
    let grounded = true;

    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.35;
            ix = Math.sin(autoTime * 1.2) * 6.5 - at.x;
            iz = Math.sin(autoTime * 2.0 + 1) * 5.5 - 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;
        }

        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;

        let impact = 0;

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

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

        for (const [rx, rz, r] of ROCKS) {
            const dx = at.x - rx;
            const dz = at.z - rz;
            const d = Math.hypot(dx, dz);
            const min = BALL.radius + r * 0.85;

            if (d < min && d > 0.0001) {
                at.x = rx + (dx / d) * min;
                at.z = rz + (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;
                }
            }
        }

        const speed = Math.hypot(velocity.x, velocity.z);

        at.rotationY += delta * speed;
        grass.ballAt(at);

        // The grass remembers where it trod: a point every little way, with which way it went.
        if (grounded && speed > 0.2 && Math.hypot(at.x - mark.x, at.z - mark.z) > TRAIL.spacing) {
            grass.tread(at.x, at.z, velocity.x / speed, velocity.z / speed);
            mark.x = at.x;
            mark.z = at.z;
        }

        // Landing lays the grass round it down, outward.
        if (impact > TRAIL.landing) {
            for (let k = 0; k < 4; k++) {
                const a = (k / 4) * Math.PI * 2 + 0.4;

                grass.tread(at.x + Math.cos(a) * 0.45, at.z + Math.sin(a) * 0.45, Math.cos(a), Math.sin(a));
            }

            pollen.kick(at.x, at.z, Math.min(120, Math.round(impact * 10)));
        }
    });

    return {
        mesh
    };
};
```

`components/grass.ts`:

```ts
import { createMaterial, createMeshInstances, useUpdate } from 'nacatamalon';
import { bladeShape, plantBlades } from '../geometry/blades';
import { createPixelTexture, createPixels, updatePixelTexture } from 'nacatamalon/pixels';
import { GRASS_FRAGMENT_GLSL, GRASS_FRAGMENT_WGSL, GRASS_VERTEX_GLSL, GRASS_VERTEX_WGSL, type TGrassKnobs } from '../shaders/grass';
import { BALL, MEADOW, ROCKS, SUN, TRAIL } from '../settings';

type TPoint = {
    x: number;
    y: number;
    z: number;
};

/**
 * The meadow: the blades in chunks, each chunk one blade drawn many times, the one material that
 * bends them all, the wind, and the memory of where the ball went. What treads it (the ball) does so
 * through what this returns.
 */
export const Grass = () => {
    const knobs: TGrassKnobs = {
        ball: [BALL.start.x, BALL.radius, BALL.start.z, BALL.radius],
        wind: [0.8, 0.3, 0.55, 0],
        // Towards the sun: the other way from where it shines.
        sun: [Math.sin(SUN.rotationY) * Math.cos(SUN.rotationX), -Math.sin(SUN.rotationX), Math.cos(SUN.rotationY) * Math.cos(SUN.rotationX), 0],
        sunColor: [1.05, 0.95, 0.78, 0],
        exposure: 1.7,
        meadow: MEADOW.size
    };

    // The trail: at each place of the meadow, which way the grass lies and how far, -1 to 1 each way.
    // Kept here in full, and painted into a picture for the material, which reads it as its `trail`
    // map: red and green, with the middle grey for grass standing up.
    const trail = new Float32Array(TRAIL.mapSize * TRAIL.mapSize * 2);
    const trailPixels = createPixels(TRAIL.mapSize, TRAIL.mapSize, '#808000');
    const trailMap = createPixelTexture(trailPixels);
    // Whether any grass is still lying down, so a meadow standing up sends nothing.
    let trodden = false;

    const material = createMaterial({
        shader: 'mesh3d',
        name: 'grass',
        vertex: GRASS_VERTEX_WGSL,
        vertexGlsl: GRASS_VERTEX_GLSL,
        fragment: GRASS_FRAGMENT_WGSL,
        fragmentGlsl: GRASS_FRAGMENT_GLSL,
        maps: {
            // Smooth, so the grass lies down in a curve and not pixel by pixel; clamped, so the edge
            // of the meadow does not read the other side.
            trail: {
                texture: trailMap,
                smooth: true,
                wrap: 'clamp'
            }
        },
        uniforms: knobs
    });

    const planted = plantBlades({
        ...MEADOW,
        avoid: (x, z) => ROCKS.some(([rx, rz, r]) => Math.hypot(x - rx, z - rz) < r * 0.85)
    });

    // One blade, drawn once for every blade of the meadow.
    const blade = bladeShape();

    for (const blades of planted) {
        if (blades.length === 0) {
            continue;
        }

        // A chunk is one model drawn as many blades. The vertex hook moves the tips: the engine has
        // to know how far, so it does not leave out a chunk whose grass leans into view.
        const chunk = createMeshInstances({
            geometry: blade,
            material,
            capacity: blades.length,
            boundsMargin: 0.7,
            // The grass receives the shadows of the ball and the rocks, and casts none: a meadow of
            // blades shadowing each other only comes out darker, and costs the shadow pass every one.
            castShadow: false
        });

        blades.forEach((placement, i) => chunk.set(i, placement));
    }

    useUpdate((delta, time) => {
        // The trodden grass stands back up, and what is left is painted for the material.
        if (trodden) {
            const recover = Math.exp(-TRAIL.recover * delta);
            let left = 0;

            for (let i = 0; i < trail.length; i += 2) {
                const x = trail[i] * recover;
                const z = trail[i + 1] * recover;

                trail[i] = x;
                trail[i + 1] = z;
                left = Math.max(left, Math.abs(x), Math.abs(z));
                trailPixels.data[i * 2] = Math.round(128 + x * 127);
                trailPixels.data[i * 2 + 1] = Math.round(128 + z * 127);
            }

            updatePixelTexture(trailMap);
            // Below half a step of the picture, it has stood up.
            trodden = left > 0.5 / 127;
        }

        // The wind changes strength little by little.
        knobs.wind[2] = 0.45 + Math.sin(time * 0.23) * 0.2 + Math.sin(time * 0.61) * 0.1;
    });

    return {
        /**
         * Where the ball is, each frame.
         */
        ballAt: (at: TPoint) => {
            knobs.ball[0] = at.x;
            knobs.ball[1] = at.y;
            knobs.ball[2] = at.z;
        },
        /**
         * Lays the grass down round a place on the ground, towards (dx, dz) and a little outward
         * from the middle, and most near it. Added to what already lies there, up to all the way.
         */
        tread: (x: number, z: number, dx: number, dz: number) => {
            const radius = knobs.ball[3];
            const reach = radius * 1.35;
            const cell = MEADOW.size / TRAIL.mapSize;
            const toPixel = (world: number) => (world / MEADOW.size + 0.5) * TRAIL.mapSize - 0.5;
            const left = Math.max(0, Math.floor(toPixel(x - reach)));
            const right = Math.min(TRAIL.mapSize - 1, Math.ceil(toPixel(x + reach)));
            const top = Math.max(0, Math.floor(toPixel(z - reach)));
            const bottom = Math.min(TRAIL.mapSize - 1, Math.ceil(toPixel(z + reach)));

            for (let py = top; py <= bottom; py++) {
                for (let px = left; px <= right; px++) {
                    // The middle of this pixel, in the meadow.
                    const wx = (px + 0.5) * cell - MEADOW.size / 2;
                    const wz = (py + 0.5) * cell - MEADOW.size / 2;
                    const ax = wx - x;
                    const az = wz - z;
                    const d = Math.hypot(ax, az);
                    const t = Math.min(1, Math.max(0, (d - radius * 0.55) / (reach - radius * 0.55)));
                    const weight = 1 - t * t * (3 - 2 * t);

                    if (weight <= 0) {
                        continue;
                    }

                    // Which way: mostly the ball's, and a little away from where it pressed.
                    const ox = d > 0.0001 ? ax / d : 0;
                    const oz = d > 0.0001 ? az / d : 0;
                    const lx = dx * 0.8 + ox * 0.45;
                    const lz = dz * 0.8 + oz * 0.45;
                    const length = Math.hypot(lx, lz) || 1;
                    const i = (py * TRAIL.mapSize + px) * 2;
                    let nx = trail[i] + (lx / length) * weight;
                    let nz = trail[i + 1] + (lz / length) * weight;
                    const total = Math.hypot(nx, nz);

                    if (total > 1) {
                        nx /= total;
                        nz /= total;
                    }

                    trail[i] = nx;
                    trail[i + 1] = nz;
                }
            }

            trodden = true;
        },
        /**
         * Shows what bends each blade instead of the grass, or the grass again.
         */
        showBend: (on: boolean) => {
            knobs.wind[3] = on ? 1 : 0;
        }
    };
};

export type TGrass = ReturnType<typeof Grass>;
```

`components/ground.ts`:

```ts
import { createMesh, useIcoSphereGeometry, usePlaneGeometry } from 'nacatamalon';
import { MEADOW, ROCKS } from '../settings';

/**
 * The earth under the grass, and the rocks lying in it.
 */
export const Ground = () => {
    // In many pieces: the engine works its distance fog out per vertex.
    createMesh({
        geometry: usePlaneGeometry({
            width: MEADOW.size + 8,
            depth: MEADOW.size + 8,
            widthSegments: 34,
            depthSegments: 34
        }),
        tint: '#2a3a17'
    });

    const rock = useIcoSphereGeometry({
        radius: 1,
        subdivisions: 1
    });

    for (const [x, z, r] of ROCKS) {
        createMesh({
            geometry: rock,
            tint: '#b3ab9c',
            castShadow: true,
            transform: {
                x,
                y: r * 0.35,
                z,
                scaleX: r,
                scaleY: r * 0.7,
                scaleZ: r * 0.9
            }
        });
    }
};
```

`components/orbs.ts`:

```ts
import { createParticles3d, createText, emitParticles, usePointLight, useUpdate, type TMesh, type TParticles3d, type TPointLight } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { createPixels, createPixelTexture, setPixel } from 'nacatamalon/pixels';
import { BALL, MEADOW, ORBS, ROCKS, WIDTH } from '../settings';

// Glowing orbs: a core that shines with rays and a crown of petals spinning round it, a tail of dots
// that fades behind, and a light of their own.
//
// All of them are additive 3D particles, which always face the camera:
// - the core: a few particles that live very briefly, stuck to the orb (not in world space), turned
//   at random, so the star twinkles;
// - the crown: the same, with the petals' picture;
// - the aura: a big soft halo that gives the orb its colour;
// - the tail: particles in world space that stay where they were born and fade, so they draw the
//   way the orb went.

/**
 * A picture painted from how opaque each point is, by where it is from the middle: across, down,
 * how far (0 to 1 at the edge) and at what angle.
 */
const paint = (size: number, alphaAt: (dx: number, dy: number, r: number, a: number) => number) => {
    const pixels = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const dx = (x + 0.5 - size / 2) / (size / 2);
            const dy = (y + 0.5 - size / 2) / (size / 2);
            const alpha = Math.max(0, Math.min(1, alphaAt(dx, dy, Math.hypot(dx, dy), Math.atan2(dy, dx))));

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

    return createPixelTexture(pixels);
};

/**
 * A star: a very bright point, a soft halo, and eight thin rays.
 */
const paintStar = () => paint(48, (_dx, _dy, r, a) => {
    const core = Math.max(0, 1 - r * 3.2);
    const halo = Math.max(0, 1 - r) ** 2.2 * 0.55;
    const rays = Math.pow(Math.abs(Math.cos(a * 4)), 60) * Math.max(0, 1 - r) ** 1.3;
    const thin = Math.pow(Math.abs(Math.cos(a * 4 + Math.PI / 4)), 90) * Math.max(0, 1 - r * 1.4) * 0.6;

    return core + halo + rays + thin;
});

/**
 * A crown: six petals round a ring.
 */
const paintPetals = () => paint(48, (dx, dy, r, a) => {
    const ring = Math.exp(-(((r - 0.5) / 0.07) ** 2)) * 0.8;
    const petalAngle = Math.round(a / (Math.PI / 3)) * (Math.PI / 3);
    const d = Math.hypot(dx - Math.cos(petalAngle) * 0.68, dy - Math.sin(petalAngle) * 0.68);
    const petal = Math.max(0, 1 - d / 0.2) ** 1.5;

    return ring + petal;
});

const paintDot = () => paint(16, (_dx, _dy, r) => Math.max(0, 1 - r) ** 1.6);

type TOrb = {
    x: number;
    y: number;
    z: number;
    homeX: number;
    homeZ: number;
    phase: number;
    fleeX: number;
    fleeZ: number;
    /**
     * Seconds left until a caught orb comes back; 0 while it is out.
     */
    hidden: number;
    emitters: TParticles3d[];
    light: TPointLight;
};

/**
 * The orbs that wander over the meadow. They drift in shifting figures of eight round their place,
 * rise and fall, shy away from the ball, and when it touches one it bursts and comes back somewhere
 * else: roll into the low ones, jump for the high ones. The count of those caught is at the top
 * right.
 */
export const Orbs = ({ ball }: { ball: TMesh; }) => {
    const random = useRandom();
    const star = paintStar();
    const petals = paintPetals();
    const dot = paintDot();

    // A place on the meadow away from the rocks and the edge.
    const spot = (): [number, number] => {
        for (;;) {
            const x = random.rand(-0.5, 0.5) * (MEADOW.size - 8);
            const z = random.rand(-0.5, 0.5) * (MEADOW.size - 8);

            if (!ROCKS.some(([rx, rz, r]) => Math.hypot(x - rx, z - rz) < r + 1.5)) {
                return [x, z];
            }
        }
    };

    const burst = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: star,
            blend: 'additive',
            worldSpace: true,
            max: 400,
            emission: {
                rate: 0,
                burst: 0
            },
            shape: {
                kind: 'sphere',
                radius: 0.1,
                edge: false
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 3.14,
            speed: [1.5, 4],
            gravity: {
                y: -1.5
            },
            damping: 2.5,
            life: [0.4, 0.9],
            size: [0.12, 0.3],
            spin: [-6, 6],
            colorOverLife: [
                {
                    t: 0,
                    color: '#ffffff',
                    alpha: 1
                },
                {
                    t: 0.4,
                    color: ORBS.glow,
                    alpha: 0.9
                },
                {
                    t: 1,
                    color: '#7fd03a',
                    alpha: 0
                }
            ]
        }
    });

    const makeOrb = (phase: number): TOrb => {
        const [x, z] = spot();

        const core = createParticles3d({
            effect: {
                kind: 'particles-3d',
                texture: star,
                blend: 'additive',
                // Stuck to the orb: they move with it instead of staying where they were born.
                worldSpace: false,
                max: 12,
                emission: {
                    rate: 40
                },
                shape: {
                    kind: 'point'
                },
                speed: 0,
                life: [0.1, 0.18],
                size: [0.38, 0.55],
                spin: [-2, 2],
                colorOverLife: [
                    {
                        t: 0,
                        color: '#fbffd8',
                        alpha: 1
                    },
                    {
                        t: 1,
                        color: ORBS.glow,
                        alpha: 0.7
                    }
                ]
            }
        });

        const crown = createParticles3d({
            effect: {
                kind: 'particles-3d',
                texture: petals,
                blend: 'additive',
                worldSpace: false,
                max: 6,
                emission: {
                    rate: 14
                },
                shape: {
                    kind: 'point'
                },
                speed: 0,
                life: [0.3, 0.4],
                size: [0.5, 0.58],
                spin: [1.5, 3],
                colorOverLife: [
                    {
                        t: 0,
                        color: ORBS.glow,
                        alpha: 0
                    },
                    {
                        t: 0.3,
                        color: '#c8f060',
                        alpha: 0.9
                    },
                    {
                        t: 1,
                        color: '#8fd040',
                        alpha: 0
                    }
                ]
            }
        });

        // The aura: a big soft yellow-green halo, which is what gives the orb its colour.
        const aura = createParticles3d({
            effect: {
                kind: 'particles-3d',
                texture: dot,
                blend: 'additive',
                worldSpace: false,
                max: 6,
                emission: {
                    rate: 12
                },
                shape: {
                    kind: 'point'
                },
                speed: 0,
                life: [0.35, 0.5],
                size: [1.1, 1.4],
                colorOverLife: [
                    {
                        t: 0,
                        color: '#b6ec50',
                        alpha: 0
                    },
                    {
                        t: 0.4,
                        color: '#b6ec50',
                        alpha: 0.35
                    },
                    {
                        t: 1,
                        color: '#86c83a',
                        alpha: 0
                    }
                ]
            }
        });

        const tail = createParticles3d({
            effect: {
                kind: 'particles-3d',
                texture: dot,
                blend: 'additive',
                worldSpace: true,
                max: 90,
                emission: {
                    rate: 70
                },
                shape: {
                    kind: 'point'
                },
                speed: 0,
                life: [0.7, 0.9],
                size: [0.09, 0.11],
                sizeOverLife: [
                    {
                        t: 0,
                        scale: 1
                    },
                    {
                        t: 1,
                        scale: 0.35
                    }
                ],
                colorOverLife: [
                    {
                        t: 0,
                        color: '#f4ffc0',
                        alpha: 0.9
                    },
                    {
                        t: 0.5,
                        color: '#c8f060',
                        alpha: 0.6
                    },
                    {
                        t: 1,
                        color: '#9bd84c',
                        alpha: 0
                    }
                ]
            }
        });

        const light = usePointLight({
            color: '#d8ff8a',
            intensity: 1.4,
            range: 3.2
        });

        return {
            x,
            y: 1.2,
            z,
            homeX: x,
            homeZ: z,
            phase,
            fleeX: 0,
            fleeZ: 0,
            hidden: 0,
            emitters: [core, crown, aura, tail],
            light
        };
    };

    const orbs = Array.from({
        length: ORBS.count
    }, (_, i) => makeOrb(i * 1.7));

    const place = (orb: TOrb) => {
        for (const emitter of orb.emitters) {
            emitter.transform.x = orb.x;
            emitter.transform.y = orb.y;
            emitter.transform.z = orb.z;
        }

        orb.light.transform.x = orb.x;
        orb.light.transform.y = orb.y;
        orb.light.transform.z = orb.z;
    };

    const show = (orb: TOrb, visible: boolean) => {
        for (const emitter of orb.emitters) {
            emitter.visible = visible;
        }

        orb.light.intensity = visible ? 1.4 : 0;
    };

    for (const orb of orbs) {
        place(orb);
    }

    let caught = 0;

    const counter = createText({
        text: 'ORBS 0',
        tint: '#4a6a1a',
        anchor: {
            x: 1,
            y: 0
        },
        zIndex: 100,
        transform: {
            x: WIDTH - 8,
            y: 28
        }
    });

    useUpdate((delta, time) => {
        const at = ball.transform;

        for (const orb of orbs) {
            if (orb.hidden > 0) {
                orb.hidden -= delta;

                if (orb.hidden <= 0) {
                    const [x, z] = spot();

                    orb.homeX = x;
                    orb.homeZ = z;
                    orb.x = x;
                    orb.z = z;
                    orb.fleeX = 0;
                    orb.fleeZ = 0;
                    show(orb, true);
                }

                continue;
            }

            // Figures of eight that shift with time, so the tail comes out curled.
            const t = time * 0.9 + orb.phase;
            const wx = orb.homeX + Math.sin(t) * 1.6 + Math.sin(t * 2.3 + 1) * 0.6;
            const wz = orb.homeZ + Math.sin(t * 1.4 + 2) * 1.3 + Math.cos(t * 3.1) * 0.4;
            const wy = 1.1 + Math.sin(t * 1.9) * 0.35 + Math.sin(t * 4.7) * 0.08;

            // They shy away a little when the ball comes near.
            const dx = wx + orb.fleeX - at.x;
            const dz = wz + orb.fleeZ - at.z;
            const d = Math.hypot(dx, dz);

            if (d < 2.2 && d > 0.001) {
                const push = (2.2 - d) * 1.6 * delta;

                orb.fleeX += (dx / d) * push;
                orb.fleeZ += (dz / d) * push;
            }

            const settle = Math.exp(-0.5 * delta);
            const follow = 1 - Math.exp(-6 * delta);

            orb.fleeX *= settle;
            orb.fleeZ *= settle;
            orb.x += (wx + orb.fleeX - orb.x) * follow;
            orb.y += (wy - orb.y) * follow;
            orb.z += (wz + orb.fleeZ - orb.z) * follow;
            orb.light.intensity = 1.3 + Math.sin(time * 9 + orb.phase) * 0.2;
            place(orb);

            if (Math.hypot(orb.x - at.x, orb.y - at.y, orb.z - at.z) < BALL.radius + ORBS.reach) {
                burst.transform.x = orb.x;
                burst.transform.y = orb.y;
                burst.transform.z = orb.z;
                emitParticles(burst, 40);
                orb.hidden = ORBS.hidden;
                show(orb, false);
                caught++;
                counter.text = `ORBS ${caught}`;
            }
        }
    });
};
```

`components/pollen.ts`:

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

/**
 * A small soft dot.
 */
const paintMote = () => {
    const size = 8;
    const mote = 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);

            setPixel(mote, x, y, `rgba(255, 255, 255, ${Math.max(0, 1 - d).toFixed(3)})`);
        }
    }

    return createPixelTexture(mote);
};

/**
 * What floats over the meadow: pollen drifting against the sun round what the camera sees, and bits
 * of grass thrown up where the ball lands.
 */
export const Pollen = () => {
    const mote = paintMote();

    const pollen = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: mote,
            blend: 'additive',
            worldSpace: true,
            max: 300,
            emission: {
                rate: 30
            },
            shape: {
                kind: 'box',
                size: [18, 2, 18]
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 3.1,
            speed: [0.05, 0.2],
            gravity: {
                x: 0.08,
                y: 0.02,
                z: 0.03
            },
            life: [6, 10],
            size: [0.03, 0.06],
            colorOverLife: [
                {
                    t: 0,
                    color: '#fff2c0',
                    alpha: 0
                },
                {
                    t: 0.2,
                    color: '#fff2c0',
                    alpha: 0.7
                },
                {
                    t: 0.8,
                    color: '#fff2c0',
                    alpha: 0.7
                },
                {
                    t: 1,
                    color: '#fff2c0',
                    alpha: 0
                }
            ]
        },
        transform: {
            x: 0,
            y: 1.2,
            z: 0
        }
    });

    const bits = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: mote,
            worldSpace: true,
            max: 300,
            emission: {
                rate: 0,
                burst: 0
            },
            shape: {
                kind: 'sphere',
                radius: 0.4,
                edge: true
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 1.2,
            speed: [1.5, 3.5],
            gravity: {
                y: -7
            },
            damping: 0.6,
            life: [0.5, 1.2],
            size: [0.04, 0.08],
            colorOverLife: [
                {
                    t: 0,
                    color: '#9acd4a',
                    alpha: 1
                },
                {
                    t: 1,
                    color: '#5b7f2a',
                    alpha: 0
                }
            ]
        }
    });

    return {
        /**
         * Throws up `count` bits of grass at a place on the ground.
         */
        kick: (x: number, z: number, count: number) => {
            bits.transform.x = x;
            bits.transform.y = 0.2;
            bits.transform.z = z;
            emitParticles(bits, count);
        },
        /**
         * Keeps the pollen over what the camera sees.
         */
        follow: (x: number, z: number) => {
            pollen.transform.x = x;
            pollen.transform.z = z;
        }
    };
};

export type TPollen = ReturnType<typeof Pollen>;
```

`components/views.ts`:

```ts
import { createSprite, createText, listen, useAction, useUpdate } from 'nacatamalon';
import { VIEWS, WIDTH } from '../settings';
import type { TGrass } from './grass';

/**
 * The two ways to look at the meadow, switched with V or the button at the top right: GRASS as it
 * is, and BEND, what bends each blade, red for the ball and its trail, blue for the wind.
 */
export const Views = ({ grass }: { grass: TGrass; }) => {
    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 show = () => {
        label.text = `[V] VIEW: ${VIEWS[view]}`;
        grass.showBend(VIEWS[view] === 'BEND');
    };

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

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

    const switchView = useAction('view');

    useUpdate(() => {
        if (switchView.justPressed()) {
            next();
        }
    });
};
```

`geometry/blades.ts`:

```ts
import { createGeometry, type TGeometry, type TMeshInstancePlacement } from 'nacatamalon';

// The meadow's blades. Every blade is the same shape, made once: three segments (7 vertices, 5
// triangles a side), one unit tall, one unit to each side at the root and one unit of lean at the
// tip. Each blade of the meadow is an instance of it (`createMeshInstances`), which sizes it into its own:
// how wide, how tall, and how far it leans by itself.
//
// What the shape's vertices carry for the shader:
// - position: across (x), up the blade (y, 0 at the root and 1 at the tip), and the curve it leans
//   in (z).
// - uv.y: how much of the blade is below (0 at the root, 1 at the tip). It is what bends.
// - colour: from a dark root to white at the tip, which the instance's own colour multiplies.
//
// What each instance carries:
// - its place, its turn, and its size: width, height and lean.
// - its colour: the tip's, which on a few is a flower's.
// - data[0]: the blade's seed (0 to 1): its phase as it sways, and how stiff it is.

/**
 * How dark the root is against the tip, each channel: the tip's colour times this is the root's.
 */
const ROOT = [0.21, 0.31, 0.28];

const TIPS = [[0.55, 0.78, 0.25], [0.62, 0.82, 0.3], [0.72, 0.8, 0.32]];

const FLOWERS = [[1.0, 0.92, 0.45], [1.0, 1.0, 1.0], [0.78, 0.6, 1.0], [1.0, 0.55, 0.65]];

/**
 * How far up the blade each pair of vertices is; the last is the tip, one vertex.
 */
const LEVELS = [0, 0.35, 0.7, 1];

/**
 * The one blade every instance draws.
 */
export const bladeShape = (): TGeometry => {
    const positions: number[] = [];
    const uvs: number[] = [];
    const colors: number[] = [];
    const normals: number[] = [];
    const indices: number[] = [];

    for (const t of LEVELS) {
        const w = 1 - t * 0.55;
        // The colour grows towards the tip faster than the height does, as the lean does.
        const k = t * t;

        for (const side of t === 1 ? [0] : [-1, 1]) {
            positions.push(w * side, t, k);
            uvs.push(0, t);
            normals.push(0, 1, 0);
            colors.push(ROOT[0] + (1 - ROOT[0]) * k, ROOT[1] + (1 - ROOT[1]) * k, ROOT[2] + (1 - ROOT[2]) * k, 1);
        }
    }

    // Two segments of two triangles, and the tip: once for each side, the second the other way
    // round. Each side is its own triangles, so each is lit as the material says, facing up, where
    // one set drawn on both sides (`cull: 'none'`) would light its far side facing down.
    const front: number[] = [];

    for (let s = 0; s < 3; s++) {
        const a = s * 2;

        if (s < 2) {
            front.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
        } else {
            front.push(a, a + 1, a + 2);
        }
    }

    for (let i = 0; i < front.length; i += 3) {
        indices.push(front[i], front[i + 1], front[i + 2]);
        indices.push(front[i], front[i + 2], front[i + 1]);
    }

    return createGeometry({
        positions,
        uvs,
        colors,
        normals,
        indices
    });
};

export type TBladesOptions = {
    /**
     * World units across, round the middle.
     */
    size: number;
    chunks: number;
    perSquareMetre: number;
    /**
     * True where no grass grows.
     */
    avoid: (x: number, z: number) => boolean;
};

/**
 * Plants the meadow, the same every time, and returns where each blade goes, chunk by chunk: the
 * blades of a chunk are drawn together, so the engine can leave out the chunks out of view.
 */
export const plantBlades = ({ size, chunks, perSquareMetre, avoid }: TBladesOptions): TMeshInstancePlacement[][] => {
    let seed = 1234567;

    const random = () => {
        seed = (seed * 16807) % 2147483647;

        return seed / 2147483647;
    };

    const chunkSize = size / chunks;
    const perChunk = Math.round(chunkSize * chunkSize * perSquareMetre);
    const planted: TMeshInstancePlacement[][] = [];

    for (let cz = 0; cz < chunks; cz++) {
        for (let cx = 0; cx < chunks; cx++) {
            const blades: TMeshInstancePlacement[] = [];

            for (let b = 0; b < perChunk; b++) {
                const x = -size / 2 + (cx + random()) * chunkSize;
                const z = -size / 2 + (cz + random()) * chunkSize;

                if (avoid(x, z)) {
                    continue;
                }

                const height = 0.32 + random() * 0.3;
                const width = 0.045 + random() * 0.035;
                const yaw = random() * Math.PI * 2;
                const lean = (random() - 0.5) * 0.5;
                const bladeSeed = random();
                const flower = random() < 0.025;
                const tip = flower ? FLOWERS[Math.floor(random() * FLOWERS.length)] : TIPS[Math.floor(random() * TIPS.length)];
                // Some blades darker or lighter, so the meadow is not flat.
                const shade = 0.85 + random() * 0.3;

                blades.push({
                    x,
                    z,
                    rotationY: yaw,
                    scaleX: width,
                    scaleY: height,
                    scaleZ: lean * height,
                    tint: {
                        r: tip[0] * shade,
                        g: tip[1] * shade,
                        b: tip[2] * shade,
                        a: 1
                    },
                    data: [bladeSeed]
                });
            }

            planted.push(blades);
        }
    }

    return planted;
};
```

`scenes/meadow.ts`:

```ts
import { cameraLookAt, createScene, createText, useAmbientLight, useCamera3d, useDirectionalLight, useFog, useSpawn, useUpdate } from 'nacatamalon';
import { Ball } from '../components/ball';
import { Grass } from '../components/grass';
import { Ground } from '../components/ground';
import { Orbs } from '../components/orbs';
import { Pollen } from '../components/pollen';
import { Views } from '../components/views';
import { HEIGHT, SKY, SUN } from '../settings';

/**
 * A meadow in the evening, with a few rocks and orbs wandering over it. The grass and the pollen are
 * made before the ball, which is handed what they return so it can tread one and kick up the other;
 * the orbs come after it, to watch where it is.
 */
export const Meadow = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            x: 0,
            y: 4.2,
            z: 7
        }
    });

    useFog({
        color: SKY,
        near: 16,
        far: 34
    });
    useAmbientLight({
        color: '#a7b4cc',
        intensity: 0.8
    });
    useDirectionalLight({
        color: '#ffe0b0',
        intensity: 1.1,
        castShadow: true,
        shadowArea: 30,
        transform: {
            rotationX: SUN.rotationX,
            rotationY: SUN.rotationY
        }
    });

    useSpawn(Ground)();

    const grass = useSpawn(Grass)();
    const pollen = useSpawn(Pollen)();

    const ball = useSpawn(Ball)({
        grass: grass.api,
        pollen: pollen.api
    });

    useSpawn(Orbs)({
        ball: ball.api.mesh
    });
    useSpawn(Views)({
        grass: grass.api
    });

    createText({
        text: 'WASD / ARROWS: MOVE   SPACE: JUMP',
        tint: '#3a3226',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });
    createText({
        text: 'GRASS · NACATAMALON',
        tint: '#3a3226',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    // The camera follows the ball from above, a little late, and the pollen floats 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 + 6.5 - camera.transform.z) * follow;
        cameraLookAt(camera, {
            x: at.x * 0.7,
            y: 0.4,
            z: at.z * 0.7
        });
        pollen.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 hazy evening sky, and the distance fog that fades the far end into it.
 */
export const SKY = '#e7dcc8';

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

/**
 * What V and the button at the top right show: the grass as it is, and what bends each blade, red
 * for the ball and its trail, blue for the wind.
 */
export const VIEWS = ['GRASS', 'BEND'] as const;

/**
 * The meadow: `size` by `size` world units (metres) round the middle, cut into `chunks` by `chunks`
 * pieces the engine can leave out when they are out of view, with `perSquareMetre` blades in each
 * square metre: about 37,000 in all.
 */
export const MEADOW = {
    size: 26,
    chunks: 10,
    perSquareMetre: 55
};

/**
 * The low sun, in front of the camera, so the tips of the grass glow against it: turned down
 * (rotationX) and round (rotationY).
 */
export const SUN = {
    rotationX: -0.42,
    rotationY: 2.75
};

/**
 * The white ball, in world units and seconds. It never goes nearer the edge than `edge`.
 */
export const BALL = {
    radius: 0.5,
    start: {
        x: 0,
        z: 2
    },
    accel: 18,
    gravity: 20,
    jump: 7.5,
    edge: 3,
    /**
     * Rolling through grass slows it: gently while it is steered, faster when let go.
     */
    drag: 2.8,
    stopDrag: 5
};

/**
 * The grass remembers where the ball went, in a picture of the whole meadow `mapSize` pixels across:
 * it is laid down there every `spacing` world units, and fades by `recover` a second, so the grass
 * stands back up. A landing harder than `landing` lays the grass round it down outward.
 */
export const TRAIL = {
    /**
     * How many pixels across the picture the trail is kept in, over the whole meadow.
     */
    mapSize: 128,
    spacing: 0.45,
    recover: 0.32,
    landing: 3
};

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

/**
 * The rocks, where they lie (x, z) and how big. No grass grows in them and the ball bumps into them.
 */
export const ROCKS: readonly (readonly [number, number, number])[] = [[-4.5, -3.0, 0.9], [5.0, -4.5, 1.2], [3.5, 3.8, 0.7], [-5.5, 4.5, 1.0], [0.5, -7.0, 0.8], [-7.5, -1.0, 0.6]];

/**
 * The glowing orbs: how many wander over the meadow, how near the ball has to come to catch one
 * (beyond its own radius), and how long a caught one takes to come back somewhere else.
 */
export const ORBS = {
    count: 6,
    reach: 0.35,
    hidden: 4,
    glow: '#e9ff9a'
};
```

`shaders/grass.ts`:

```ts
// The grass bends whole in the vertex hook: nothing changes on the CPU.
//
// Every blade is an instance of one shape. The hook runs after the instance has placed the corner, so
// `pos` is where the corner stands in the meadow, `ctx.origin` where its blade is planted and
// `ctx.instance.x` the blade's seed.
//
// Each blade curves in an arc towards a direction (`bend`) that adds up three things:
// - the wind: gusts that travel across the meadow (a noise that scrolls) and a flutter of its own;
// - the ball now: it pushes the grass outward and flattens it underneath; in the air, nothing;
// - the trail: grass the ball already went over, standing back up little by little. It is a picture
//   over the whole meadow, the material's `trail` map, that says at each place which way the grass
//   lies and how far: the game paints it where the ball goes and fades it as the grass stands up,
//   and the hook reads it at the root of each blade.

export type TGrassKnobs = {
    /**
     * x, y, z, radius.
     */
    ball: number[];
    /**
     * Direction x, z, strength, and the BEND view (0 or 1).
     */
    wind: number[];
    /**
     * Towards the sun.
     */
    sun: number[];
    /**
     * The sun's colour, for the tips glowing against it.
     */
    sunColor: number[];
    /**
     * How much brighter the grass is than the light that reaches it.
     */
    exposure: number;
    /**
     * How far across the meadow is, which the trail map covers.
     */
    meadow: number;
};

export const GRASS_VERTEX_WGSL = /* wgsl */ `
fn grassHash(p: vec2<f32>) -> f32 {
    return fract(sin(dot(p, vec2<f32>(127.1, 311.7))) * 43758.5453);
}

fn grassNoise(p: vec2<f32>) -> f32 {
    let i = floor(p);
    let f = fract(p);
    let u = f * f * (3.0 - 2.0 * f);
    let a = grassHash(i);
    let b = grassHash(i + vec2<f32>(1.0, 0.0));
    let c = grassHash(i + vec2<f32>(0.0, 1.0));
    let d = grassHash(i + vec2<f32>(1.0, 1.0));
    return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

// Which way the grass lies at a place in the meadow, and how far: the trail map, read at it. Its
// two numbers are 0 to 1 with the middle for none, turned back into -1 to 1 each way.
fn trampled(root: vec2<f32>) -> vec2<f32> {
    let s = sampleMap_trail(root / mu.meadow + vec2<f32>(0.5));
    return (s.rg * 255.0 - vec2<f32>(128.0)) / 127.0;
}

fn vertex(pos: vec3<f32>, ctx: VertContext) -> vec3<f32> {
    let t = ctx.uv.y;
    let seed = ctx.instance.x;
    // Where the blade is planted: the same for every corner of it.
    let root = ctx.origin.xz;

    // The wind: gusts crossing the meadow, and each blade's flutter.
    let windDir = normalize(mu.wind.xy + vec2<f32>(0.0001));
    let gust = grassNoise(root * 0.22 - mu.wind.xy * mu.time * 0.9);
    let flutter = sin(mu.time * (2.4 + seed * 1.6) + seed * 40.0 + root.x * 0.8) * 0.08;
    var bend = windDir * ((0.1 + gust * gust * 0.9) * mu.wind.z + flutter);

    // The ball now: it pushes outward and flattens underneath, only when it is near the ground.
    let fromBall = root - mu.ball.xz;
    let d = length(fromBall);
    let near = 1.0 - smoothstep(mu.ball.w * 0.5, mu.ball.w * 2.0, d);
    let low = 1.0 - smoothstep(mu.ball.w * 1.05, mu.ball.w * 1.05 + 0.6, mu.ball.y);
    let push = near * low;
    bend = bend + fromBall / max(d, 0.0001) * push * 1.5;

    // The trail: grass already trodden, standing back up.
    let trail = trampled(root);
    let trailAmount = min(length(trail), 1.0);
    bend = bend + normalize(trail + vec2<f32>(0.00001)) * trailAmount * 1.3;

    // Each blade has its own stiffness; the angle grows towards the tip, so it curves in an arc.
    let amount = min(length(bend), 1.45) * (0.8 + grassHash(vec2<f32>(seed, 7.0)) * 0.4);
    let dir = bend / max(length(bend), 0.0001);
    let angle = amount * t;
    let shift = sin(angle) * pos.y;
    carry = vec4<f32>(t, clamp(push + trailAmount, 0.0, 1.0), gust, 0.0);
    // Lit as if it faced up, whichever way it is turned or bent.
    surfaceNormal = vec3<f32>(0.0, 1.0, 0.0);
    return vec3<f32>(pos.x + dir.x * shift, cos(angle) * pos.y, pos.z + dir.y * shift);
}
`;

export const GRASS_VERTEX_GLSL = /* glsl */ `
float grassHash(vec2 p) {
    return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}

float grassNoise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    float a = grassHash(i);
    float b = grassHash(i + vec2(1.0, 0.0));
    float c = grassHash(i + vec2(0.0, 1.0));
    float d = grassHash(i + vec2(1.0, 1.0));
    return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

vec2 trampled(vec2 root) {
    vec4 s = sampleMap_trail(root / mu.meadow + vec2(0.5));
    return (s.rg * 255.0 - vec2(128.0)) / 127.0;
}

vec3 vertex(vec3 pos, VertContext ctx) {
    float t = ctx.uv.y;
    float seed = ctx.instance.x;
    vec2 root = ctx.origin.xz;

    vec2 windDir = normalize(mu.wind.xy + vec2(0.0001));
    float gust = grassNoise(root * 0.22 - mu.wind.xy * mu.time * 0.9);
    float flutter = sin(mu.time * (2.4 + seed * 1.6) + seed * 40.0 + root.x * 0.8) * 0.08;
    vec2 bend = windDir * ((0.1 + gust * gust * 0.9) * mu.wind.z + flutter);

    vec2 fromBall = root - mu.ball.xz;
    float d = length(fromBall);
    float near = 1.0 - smoothstep(mu.ball.w * 0.5, mu.ball.w * 2.0, d);
    float low = 1.0 - smoothstep(mu.ball.w * 1.05, mu.ball.w * 1.05 + 0.6, mu.ball.y);
    float push = near * low;
    bend += fromBall / max(d, 0.0001) * push * 1.5;

    vec2 trail = trampled(root);
    float trailAmount = min(length(trail), 1.0);
    bend += normalize(trail + vec2(0.00001)) * trailAmount * 1.3;

    float amount = min(length(bend), 1.45) * (0.8 + grassHash(vec2(seed, 7.0)) * 0.4);
    vec2 dir = bend / max(length(bend), 0.0001);
    float angle = amount * t;
    float shift = sin(angle) * pos.y;
    carry = vec4(t, clamp(push + trailAmount, 0.0, 1.0), gust, 0.0);
    surfaceNormal = vec3(0.0, 1.0, 0.0);
    return vec3(pos.x + dir.x * shift, cos(angle) * pos.y, pos.z + dir.y * shift);
}
`;

// The engine's own light (the sun, the orbs' lamps, the ambient and the shadows, the ball's
// included), which the vertex hook asks for as if every blade faced up: a real blade is thin and has
// no dark side. A touch more exposure, since the engine's ambient is a floor under the sun and not
// added to it, and the meadow is the brightest thing in the scene. Darker at the root, and the tips
// glow against the sun, less in the shade.
export const GRASS_FRAGMENT_WGSL = /* wgsl */ `
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let t = ctx.carry.x;
    let toSun = normalize(mu.sun.xyz);
    let root = mix(0.32, 1.0, t);
    let sunlit = min(dot(ctx.light, vec3<f32>(0.3333)), 1.0);
    let backlit = pow(max(dot(-ctx.viewDir, toSun), 0.0), 3.0) * t * 0.7 * sunlit;
    let color = surface.rgb * ctx.light * mu.exposure * root + surface.rgb * mu.sunColor.rgb * backlit;
    // The BEND view: red what the ball bends, blue the gusts.
    let shown = mix(color, vec3<f32>(ctx.carry.y, 0.15 + t * 0.2, ctx.carry.z * 0.8), mu.wind.w);
    return vec4<f32>(shown, 1.0);
}
`;

export const GRASS_FRAGMENT_GLSL = /* glsl */ `
vec4 effect(vec4 surface, FragContext ctx) {
    float t = ctx.carry.x;
    vec3 toSun = normalize(mu.sun.xyz);
    float root = mix(0.32, 1.0, t);
    float sunlit = min(dot(ctx.light, vec3(0.3333)), 1.0);
    float backlit = pow(max(dot(-ctx.viewDir, toSun), 0.0), 3.0) * t * 0.7 * sunlit;
    vec3 color = surface.rgb * ctx.light * mu.exposure * root + surface.rgb * mu.sunColor.rgb * backlit;
    vec3 shown = mix(color, vec3(ctx.carry.y, 0.15 + t * 0.2, ctx.carry.z * 0.8), mu.wind.w);
    return vec4(shown, 1.0);
}
`;
```
