• 01 - Games
  • 02 - Creative Instruments & Explorers
  • 03 - Language, Signals & Text
  • 04 - Developer & Web Utilities
  • 05 - Generators & Data
  • 06 - Colour Theory
  • 07 - Music 26
  • 08 - 3D, Shaders & Visuals
ARCHIVE
  • Wireframe Spider
  • Wireframe Fly
  • Wireframe Scorpion
  • Wireframe Mosquito
  • Wireframe Bee
  • Wireframe Butterfly
  • Wireframe Locust

WIREFRAME LOCUST SOURCE CODE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aether — Locust</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #000; overflow: hidden; height: 100vh; cursor: grab; touch-action: none; }
        body.dragging { cursor: grabbing; }
        #bgCanvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; }
        #animationCanvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; }
    </style>
</head>
<body>
    <canvas id="bgCanvas"></canvas>
    <canvas id="animationCanvas"></canvas>

    <script>
        const colors = {
            primary: 0x4db8d4,
            mid:     0x2a7f99,
            dark1:   0x0d2a3a,
            dark3:   0x000000,
            light:   0xaee8f5
        };

        // ── THEME SYNC ──
        function syncTheme() {
            try {
                let isDark = true;
                if (window.parent && window.parent.document) {
                    isDark = window.parent.document.documentElement.classList.contains('dark');
                }
                if (!isDark) {
                    document.body.style.backgroundColor = '#ffffff';
                    colors.dark3 = 0xffffff;
                    colors.dark1 = 0xcccccc;
                    if (typeof scene !== 'undefined' && scene) {
                        scene.background = new THREE.Color(colors.dark3);
                    }
                } else {
                    document.body.style.backgroundColor = '#000000';
                    colors.dark3 = 0x000000;
                    colors.dark1 = 0x0d2a3a;
                    if (typeof scene !== 'undefined' && scene) {
                        scene.background = new THREE.Color(colors.dark3);
                    }
                }
            } catch (e) {}
        }
        syncTheme();
        if (window.parent && window.parent.document) {
            try {
                var observer = new MutationObserver(syncTheme);
                observer.observe(window.parent.document.documentElement, { attributes: true, attributeFilter: ['class'] });
            } catch(e) {}
        }

        // ── Background ──
        const bgCanvas = document.getElementById('bgCanvas');
        const bgCtx = bgCanvas.getContext('2d');
        const pixelSize = 8;
        let cols, rows, pixels = [];

        const RAMP_STEPS = 48;
        const ramp = Array.from({ length: RAMP_STEPS + 1 }, (_, i) => {
            const b = (i / RAMP_STEPS) * 0.4;
            return `rgb(${Math.floor(b*10)},${Math.floor(b*30)},${Math.floor(b*50)})`;
        });

        function initBackground() {
            bgCanvas.width = window.innerWidth;
            bgCanvas.height = window.innerHeight;
            cols = Math.ceil(bgCanvas.width / pixelSize);
            rows = Math.ceil(bgCanvas.height / pixelSize);
            pixels = [];
            for (let i = 0; i < cols * rows; i++)
                pixels.push({ brightness: Math.random() * 0.3, speed: 0.001 + Math.random() * 0.003 });
        }

        let bgFrame = 0;
        function animateBackground() {
            if ((bgFrame++ & 1) === 0) {
                for (let y = 0; y < rows; y++) {
                    for (let x = 0; x < cols; x++) {
                        const p = pixels[y * cols + x];
                        p.brightness += p.speed * 2;
                        if (p.brightness > 0.4) p.brightness = 0;
                        bgCtx.fillStyle = ramp[Math.min(RAMP_STEPS, (p.brightness * RAMP_STEPS / 0.4) | 0)];
                        bgCtx.fillRect(x * pixelSize, y * pixelSize, pixelSize, pixelSize);
                    }
                }
            }
            requestAnimationFrame(animateBackground);
        }

        // ── Three.js ──
        // Built facing +Z (head forward), like the rest of the family.
        const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('animationCanvas'), antialias: true, alpha: true });
        let scene, camera, locust, body, head;
        const antennae = [], wings = [], fans = [], legs = [], abdomen = [];
        const mouth = { mandibles: [], palps: [] };

        // Seeded RNG so hairs, veins and facets are identical on every load
        function mulberry32(a) {
            return function () {
                a |= 0; a = a + 0x6D2B79F5 | 0;
                let t = Math.imul(a ^ a >>> 15, 1 | a);
                t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
                return ((t ^ t >>> 14) >>> 0) / 4294967296;
            };
        }
        const rand = mulberry32(20261128);
        const V = (x, y, z) => new THREE.Vector3(x, y, z);
        const smooth = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };

        // ── Materials ── wireframe basic materials ignore lights, so share per colour
        const matCache = new Map();
        function mat(color) {
            if (!matCache.has(color))
                matCache.set(color, new THREE.MeshBasicMaterial({ color, wireframe: true }));
            return matCache.get(color);
        }
        const lineCache = new Map();
        function lmat(color, opacity = 1) {
            const key = color + ':' + opacity;
            if (!lineCache.has(key))
                lineCache.set(key, new THREE.LineBasicMaterial({ color, transparent: opacity < 1, opacity }));
            return lineCache.get(key);
        }

        // ── Geometry helpers ──
        function ball(r, color, x, y, z, sx = 1, sy = 1, sz = 1, ws = 16, hs = 12) {
            const m = new THREE.Mesh(new THREE.SphereGeometry(r, ws, hs), mat(color));
            m.position.set(x, y, z);
            m.scale.set(sx, sy, sz);
            return m;
        }

        function lineSegs(arr, material) {
            const g = new THREE.BufferGeometry();
            g.setAttribute('position', new THREE.Float32BufferAttribute(arr, 3));
            return new THREE.LineSegments(g, material);
        }

        function polyline(points, material, loop = false) {
            const g = new THREE.BufferGeometry().setFromPoints(points);
            return new (loop ? THREE.LineLoop : THREE.Line)(g, material);
        }

        function qb(a, m, b, u) { const v = 1 - u; return v * v * a + 2 * u * v * m + u * u * b; }

        // Lathed limb segment along local +X with a tapered, bulging profile
        function limb(len, r0, rm, r1, color, radial = 8) {
            const pts = [];
            for (let i = 0; i <= 8; i++) {
                const u = i / 8;
                pts.push(new THREE.Vector2(Math.max(qb(r0, rm, r1, u), 0.0015), u * len));
            }
            const geo = new THREE.LatheGeometry(pts, radial);
            geo.rotateZ(-Math.PI / 2);
            return new THREE.Mesh(geo, mat(color));
        }

        // Hairs / bristles on a limb segment (local +X axis, +Y dorsal)
        function limbHairs(len, r0, rm, r1, o) {
            const pos = [];
            for (let i = 0; i < o.count; i++) {
                const u = o.ordered ? 0.12 + (i / Math.max(1, o.count - 1)) * 0.76 : 0.04 + rand() * 0.92;
                const r = qb(r0, rm, r1, u);
                let phi;
                if (o.ordered) phi = o.arc[0] + (i % 2 ? 0.5 : -0.5) * o.arc[1];
                else phi = o.arc ? o.arc[0] + (rand() - 0.5) * o.arc[1] : rand() * Math.PI * 2;
                const cy = Math.cos(phi), cz = Math.sin(phi);
                const x = u * len, y = cy * r, z = cz * r;
                const L = o.l0 + rand() * (o.l1 - o.l0);
                const d = V(o.distal + (rand() - 0.5) * 0.3, cy, cz).normalize();
                pos.push(x, y, z, x + d.x * L, y + d.y * L, z + d.z * L);
            }
            return lineSegs(pos, lmat(o.color, o.opacity));
        }

        function ring(radius, color, tubeR = 0.12) {
            const geo = new THREE.TorusGeometry(radius, radius * tubeR, 3, 16);
            geo.rotateY(Math.PI / 2);
            return new THREE.Mesh(geo, mat(color));
        }

        function surfaceRing(r, color, p, n) {
            const m = new THREE.Mesh(new THREE.TorusGeometry(r, r * 0.18, 3, 14), mat(color));
            m.position.copy(p);
            m.quaternion.setFromUnitVectors(V(0, 0, 1), n);
            return m;
        }

        // Ellipsoid helpers (local to the ellipsoid centre)
        function ellRay(R, d) {   // surface point in direction d
            const k = 1 / Math.sqrt((d.x / R.x) ** 2 + (d.y / R.y) ** 2 + (d.z / R.z) ** 2);
            return V(d.x * k, d.y * k, d.z * k);
        }
        function ellNormal(R, p) {
            return V(p.x / (R.x * R.x), p.y / (R.y * R.y), p.z / (R.z * R.z)).normalize();
        }
        function randUnit() {
            const u = rand() * 2 - 1, a = rand() * Math.PI * 2, s = Math.sqrt(1 - u * u);
            return V(s * Math.cos(a), u, s * Math.sin(a));
        }
        // A line drawn across an ellipsoid through a list of directions
        function ellLine(R, dirs, color, opacity, lift = 1.012) {
            return polyline(dirs.map(d => ellRay(R, d.clone().normalize()).multiplyScalar(lift)), lmat(color, opacity));
        }
        function hairField(R, count, l0, l1, sweep, color, opacity, filter) {
            const pos = [];
            let made = 0, guard = 0;
            while (made < count && guard++ < count * 30) {
                const n = randUnit();
                if (filter && !filter(n)) continue;
                const p = ellRay(R, n);
                const d = ellNormal(R, p).add(sweep)
                    .add(V((rand() - .5) * .35, (rand() - .5) * .2, (rand() - .5) * .35)).normalize();
                const L = l0 + rand() * (l1 - l0);
                pos.push(p.x, p.y, p.z, p.x + d.x * L, p.y + d.y * L, p.z + d.z * L);
                made++;
            }
            return lineSegs(pos, lmat(color, opacity));
        }
        function ellipsoid(R, color, ws, hs) {
            const m = new THREE.Mesh(new THREE.SphereGeometry(1, ws, hs).rotateX(Math.PI / 2), mat(color));
            m.scale.copy(R);
            return m;
        }

        // ── Articulated chains ──
        // Each joint is a Group; its segment extends along local +X, the next
        // joint sits at the tip, and bending is rotation about local Z.
        function knuckle(r) {
            return new THREE.Mesh(new THREE.SphereGeometry(r, 8, 6), mat(colors.light));
        }
        function buildChain(defs) {
            const root = new THREE.Group();
            const joints = [], meshes = [];
            let parent = root;
            defs.forEach((d, i) => {
                const j = new THREE.Group();
                if (i > 0) j.position.x = defs[i - 1].len;
                j.rotation.z = d.angle;
                parent.add(j);
                joints.push(j);

                const m = limb(d.len, d.r0, d.rm, d.r1, d.color, d.radial || 8);
                j.add(m); meshes.push(m);
                if (d.knuckle !== false) j.add(knuckle(d.r0 * 1.15));

                if (d.hairs) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.hairs, l0: d.r0 * 0.9, l1: d.r0 * 2.1, distal: 1.2,
                    color: colors.primary, opacity: 0.42 }));
                if (d.spines) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.spines, ordered: true, arc: [Math.PI, 1.6],
                    l0: d.r0 * 1.8, l1: d.r0 * 2.6, distal: 1.7, color: colors.light, opacity: 0.95 }));
                if (d.dspines) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.dspines, ordered: true, arc: [0, 0.6],
                    l0: d.r0 * 1.8, l1: d.r0 * 2.6, distal: 1.6, color: colors.light, opacity: 0.85 }));
                if (d.bands) d.bands.forEach(u => {
                    const b = ring(qb(d.r0, d.rm, d.r1, u) * 1.2, colors.light);
                    b.position.x = u * d.len;
                    j.add(b);
                });
                if (d.extra) d.extra(j, d);
                parent = j;
            });
            return { root, joints, meshes };
        }

        // Yaw pointing a chain's +X along the spoke at fanAngle (from +Z forward)
        function yawFor(side, fa) {
            return side > 0 ? fa - Math.PI / 2 : -(Math.PI / 2 + fa);
        }

        const GROUND_Y = -0.52;
        const JUMP_D = 2.4;                 // ground distance covered per leap

        // Foot height & reach for a joint-angle set, and one-joint IK on the femur
        function footReach(ang, lens) {
            let c = 0, y = 0, h = 0;
            for (let i = 0; i < ang.length; i++) { c += ang[i]; y += lens[i] * Math.sin(c); h += lens[i] * Math.cos(c); }
            return [y, h];
        }
        function solveFemur(leg, targetY) {
            const a = leg.ang;
            let lo = -0.9, hi = 1.5;
            for (let k = 0; k < 16; k++) {
                a[2] = (lo + hi) * 0.5;
                if (footReach(a, leg.lens)[0] < targetY) lo = a[2]; else hi = a[2];
            }
            a[2] = (lo + hi) * 0.5;
            leg.h = footReach(a, leg.lens)[1];
        }

        // ═════════════════════════ GROUND ═════════════════════════
        // Rippled soil with grass blades and grit. It scrolls backward while
        // the locust is airborne, so each leap actually carries it forward.
        const GR = 4.2, TILE = 8.4, RIPPLE = 0.12;
        const groundBits = {};
        function buildGround() {
            const g = new THREE.Group();
            g.position.y = GROUND_Y;
            const fg = new THREE.Color(colors.primary), bg = new THREE.Color(colors.dark3), c = new THREE.Color();
            const fade = r => { c.copy(fg).lerp(bg, Math.min(1, Math.pow(r / GR, 1.6))); return [c.r, c.g, c.b]; };

            // Parallel ripples — identical shape per row, so shifting by one row is seamless
            const rip = new THREE.Group();
            const pos = [], col = [];
            for (let z0 = -GR - RIPPLE; z0 <= GR + RIPPLE; z0 += RIPPLE) {
                let prev = null;
                for (let x = -GR; x <= GR + 0.001; x += 0.08) {
                    const z = z0 + 0.04 * Math.sin(x * 1.9);
                    if (x * x + z * z > GR * GR) { prev = null; continue; }
                    const p = [x, 0.01 * Math.sin(x * 3.3), z];
                    if (prev) { pos.push(...prev, ...p); col.push(...fade(Math.hypot(prev[0], prev[2])), ...fade(Math.hypot(x, z))); }
                    prev = p;
                }
            }
            const rg = new THREE.BufferGeometry();
            rg.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
            rg.setAttribute('color', new THREE.Float32BufferAttribute(col, 3));
            rip.add(new THREE.LineSegments(rg, new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.32 })));
            g.add(rip);
            groundBits.ripples = rip;

            // Grass blades (tile-wrapped, updated per frame)
            const blades = [];
            for (let i = 0; i < 90; i++) {
                const segs = [], h = 0.25 + rand() * 0.45, lean = (rand() - 0.5) * 0.5, dir = rand() * Math.PI * 2;
                for (let k = 0; k <= 6; k++) {
                    const u = k / 6;
                    segs.push([Math.cos(dir) * lean * u * u * h, u * h, Math.sin(dir) * lean * u * u * h]);
                }
                blades.push({ x: (rand() - 0.5) * TILE, z: (rand() - 0.5) * TILE, segs, w: 0.012 + rand() * 0.01 });
            }
            const nb = blades.length * 6 * 2 * 2;   // two edges per blade
            const bg2 = new THREE.BufferGeometry();
            bg2.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(nb * 3), 3));
            bg2.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(nb * 3), 3));
            const bl = new THREE.LineSegments(bg2, new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.8 }));
            bl.frustumCulled = false;
            g.add(bl);
            groundBits.blades = blades; groundBits.bladeGeo = bg2;

            // Grit
            const grit = [];
            for (let i = 0; i < 500; i++) grit.push({ x: (rand() - 0.5) * TILE, z: (rand() - 0.5) * TILE });
            const gg = new THREE.BufferGeometry();
            gg.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(grit.length * 3), 3));
            const gp = new THREE.Points(gg, new THREE.PointsMaterial({ color: colors.light, size: 0.016, transparent: true, opacity: 0.4 }));
            gp.frustumCulled = false;
            g.add(gp);
            groundBits.grit = grit; groundBits.gritGeo = gg;
            groundBits.fade = fade;
            return g;
        }
        const wrap = v => ((v + TILE / 2) % TILE + TILE) % TILE - TILE / 2;
        function updateGround(offset, t) {
            groundBits.ripples.position.z = -(offset % RIPPLE);
            const bp = groundBits.bladeGeo.attributes.position.array, bc = groundBits.bladeGeo.attributes.color.array;
            let k = 0;
            groundBits.blades.forEach((b, i) => {
                const x = b.x, z = wrap(b.z - offset), r = Math.hypot(x, z);
                const [cr, cg, cb] = groundBits.fade(Math.min(r * 1.05, GR));
                const sway = Math.sin(t * 0.0013 + i) * 0.03;
                for (const e of [-1, 1]) for (let s = 0; s < 6; s++) {
                    const a = b.segs[s], c = b.segs[s + 1];
                    const wa = b.w * (1 - s / 6), wc = b.w * (1 - (s + 1) / 6);
                    bp[k * 3] = x + a[0] + e * wa + sway * a[1]; bp[k * 3 + 1] = a[1]; bp[k * 3 + 2] = z + a[2];
                    bc[k * 3] = cr; bc[k * 3 + 1] = cg; bc[k * 3 + 2] = cb; k++;
                    bp[k * 3] = x + c[0] + e * wc + sway * c[1]; bp[k * 3 + 1] = c[1]; bp[k * 3 + 2] = z + c[2];
                    bc[k * 3] = cr; bc[k * 3 + 1] = cg; bc[k * 3 + 2] = cb; k++;
                }
            });
            groundBits.bladeGeo.attributes.position.needsUpdate = true;
            groundBits.bladeGeo.attributes.color.needsUpdate = true;
            const gp = groundBits.gritGeo.attributes.position.array;
            groundBits.grit.forEach((g, i) => {
                const z = wrap(g.z - offset), inside = g.x * g.x + z * z < GR * GR * 0.8;
                gp[i * 3] = g.x; gp[i * 3 + 1] = inside ? 0.01 : -50; gp[i * 3 + 2] = z;
            });
            groundBits.gritGeo.attributes.position.needsUpdate = true;
        }

        // ═════════════════════════ HEAD ═════════════════════════
        const R_HEAD = V(0.2, 0.28, 0.22);
        const R_EYE  = V(0.07, 0.12, 0.1);

        function compoundEye(side) {
            const g = new THREE.Group();
            g.add(ellipsoid(R_EYE, colors.mid, 14, 12));
            const out = V(side * 0.95, 0.1, 0.25).normalize();
            const N = 800, pos = [];
            const avgR = (R_EYE.x + R_EYE.y + R_EYE.z) / 3;
            const hex = Math.sqrt(4 * Math.PI * avgR * avgR / N) * 0.56;
            const golden = Math.PI * (3 - Math.sqrt(5));
            const t1 = V(), t2 = V(), up = V(0, 1, 0);
            for (let i = 0; i < N; i++) {
                const y = 1 - (i + 0.5) / N * 2, r = Math.sqrt(1 - y * y), a = i * golden;
                const n = V(Math.cos(a) * r, y, Math.sin(a) * r);
                if (n.dot(out) < 0.05) continue;
                const p = ellRay(R_EYE, n), nrm = ellNormal(R_EYE, p);
                t1.crossVectors(nrm, Math.abs(nrm.y) > 0.9 ? V(1, 0, 0) : up).normalize();
                t2.crossVectors(nrm, t1);
                p.addScaledVector(nrm, 0.003);
                let prev = null;
                for (let k = 0; k <= 6; k++) {
                    const ang = k / 6 * Math.PI * 2;
                    const v = p.clone().addScaledVector(t1, Math.cos(ang) * hex).addScaledVector(t2, Math.sin(ang) * hex);
                    if (prev) pos.push(prev.x, prev.y, prev.z, v.x, v.y, v.z);
                    prev = v;
                }
            }
            g.add(lineSegs(pos, lmat(colors.light, 0.8)));
            g.position.set(side * 0.16, 0.08, 0.02);
            return g;
        }

        function buildAntenna(side) {
            const defs = [{ len: .06, r0: .022, rm: .025, r1: .02, color: colors.mid, angle: 0.35, radial: 6 }];
            for (let i = 0; i < 20; i++) {
                const r = 0.013 - i * 0.0004;
                defs.push({ len: .032, r0: r, rm: r * 1.1, r1: r * 0.95, color: i % 2 ? colors.light : colors.primary,
                            angle: -0.025, radial: 5, knuckle: false, hairs: 2 });
            }
            const ch = buildChain(defs);
            ch.root.position.set(side * 0.08, 0.16, 0.16);
            ch.root.rotation.y = yawFor(side, 0.3);
            antennae.push({ side, root: ch.root, joints: ch.joints, rest: defs.map(d => d.angle) });
            return ch.root;
        }

        function buildHead() {
            head = new THREE.Group();
            head.position.set(0, 0.06, 1.12);   // pivot at the neck
            const h = new THREE.Group();
            h.position.z = 0.18;
            head.add(h);

            h.add(ellipsoid(R_HEAD, colors.primary, 22, 18));
            h.add(compoundEye(-1));
            h.add(compoundEye(1));
            // Face: frontal ridge, lateral facial keels, clypeal suture, fastigium
            const fr = [], cl = [], fa = [];
            for (let k = 0; k <= 14; k++) fr.push(V(0, 0.8 - k * 0.1, 1));
            for (let k = 0; k <= 14; k++) { const a = (k / 14 - 0.5) * 1.6; cl.push(V(Math.sin(a) * 0.5, -0.5, 1)); }
            for (let k = 0; k <= 12; k++) { const a = (k / 12 - 0.5) * 1.4; fa.push(V(Math.sin(a) * 0.45, 1, 0.35 + Math.cos(a) * 0.2)); }
            h.add(ellLine(R_HEAD, fr, colors.light, 0.85));
            h.add(ellLine(R_HEAD, cl, colors.light, 0.7));
            h.add(ellLine(R_HEAD, fa, colors.light, 0.7));
            [-1, 1].forEach(s => {
                const k = [];
                for (let m = 0; m <= 12; m++) k.push(V(s * (0.32 + m * 0.015), 0.55 - m * 0.1, 1));
                h.add(ellLine(R_HEAD, k, colors.light, 0.55));
            });
            // Ocelli
            [[0, 0.3, 1, 0.018], [-0.3, 0.75, 0.6, 0.016], [0.3, 0.75, 0.6, 0.016]].forEach(([x, y, z, r]) => {
                const p = ellRay(R_HEAD, V(x, y, z).normalize());
                h.add(ball(r, colors.light, p.x, p.y, p.z, 1, 1, 1, 8, 6));
            });
            h.add(hairField(R_HEAD, 90, 0.015, 0.03, V(0, 0, -0.3), colors.light, 0.4, n => n.z < 0.3));

            // Mouthparts: labrum, chewing mandibles, maxillary and labial palps
            h.add(ball(0.07, colors.mid, 0, -0.27, 0.12, 1.1, 0.7, 0.5, 12, 8));
            [-1, 1].forEach(s => {
                const md = buildChain([{ len: .1, r0: .04, rm: .042, r1: .02, color: colors.light, angle: -0.9, radial: 6,
                    extra: (j, d) => { const tt = []; for (let k = 0; k < 4; k++) tt.push(d.len * (0.6 + k * 0.1), 0, -s * 0.01, d.len * (0.6 + k * 0.1) + 0.01, -0.015, -s * 0.03); j.add(lineSegs(tt, lmat(colors.light, 0.9))); } }]);
                md.root.position.set(s * 0.07, -0.24, 0.1);
                md.root.rotation.y = yawFor(s, 0.25);
                h.add(md.root);
                mouth.mandibles.push({ side: s, root: md.root });
                [[0.11, 5, -1.3, 0.1], [0.07, 3, -1.5, 0.04]].forEach(([x, n, a0, zz]) => {
                    const pd = [];
                    for (let k = 0; k < n; k++) pd.push({ len: .045, r0: .012, rm: .013, r1: .011, color: k % 2 ? colors.light : colors.primary,
                                                          angle: k ? 0.15 : a0, radial: 5, hairs: 3 });
                    const ch = buildChain(pd);
                    ch.root.position.set(s * x, -0.26, zz);
                    ch.root.rotation.y = yawFor(s, 0.4);
                    h.add(ch.root);
                    mouth.palps.push({ side: s, joint: ch.joints[0], rest: a0 });
                });
            });
            h.add(buildAntenna(-1));
            h.add(buildAntenna(1));
            return head;
        }

        // ═════════════════════════ THORAX ═════════════════════════
        function buildThorax(g) {
            // Pronotum: the saddle — a deep shield wrapping the prothorax,
            // with median crest, lateral carinae, three transverse sulci and
            // a flared rear lip over the wing bases
            const PZ0 = 1.08, PZ1 = 0.5, rows = 14, colsN = 22;
            const shield = (z, a) => {
                const u = (PZ0 - z) / (PZ0 - PZ1);
                const rx = 0.25 + 0.07 * u + (u > 0.85 ? (u - 0.85) * 0.5 : 0);
                const ry = 0.33 + 0.05 * u;
                const crest = 0.03 * Math.sin(Math.PI * u);
                return V(Math.sin(a) * rx, 0.02 + Math.cos(a) * ry + (Math.cos(a) > 0.97 ? crest : 0), z);
            };
            const sp = [];
            for (let i = 0; i <= rows; i++) {
                const z = PZ0 - (PZ0 - PZ1) * i / rows;
                for (let j = 0; j < colsN; j++) {
                    const a0 = -2.2 + 4.4 * j / colsN, a1 = -2.2 + 4.4 * (j + 1) / colsN;
                    const p = shield(z, a0), q = shield(z, a1);
                    sp.push(p.x, p.y, p.z, q.x, q.y, q.z);
                    if (i < rows) { const r = shield(PZ0 - (PZ0 - PZ1) * (i + 1) / rows, a0); sp.push(p.x, p.y, p.z, r.x, r.y, r.z); }
                }
            }
            g.add(lineSegs(sp, lmat(colors.mid, 0.9)));
            const along = (a, op) => { const pts = []; for (let i = 0; i <= 20; i++) pts.push(shield(PZ0 - (PZ0 - PZ1) * i / 20, a).multiplyScalar(1.0)); return polyline(pts, lmat(colors.light, op)); };
            g.add(along(0, 1));
            g.add(along(0.75, 0.75)); g.add(along(-0.75, 0.75));
            [0.25, 0.45, 0.66].forEach(f => {
                const pts = [];
                for (let j = 0; j <= 24; j++) pts.push(shield(PZ0 - (PZ0 - PZ1) * f, -2.1 + 4.2 * j / 24));
                g.add(polyline(pts, lmat(colors.light, 0.6)));
            });
            const lip = [];
            for (let j = 0; j <= 24; j++) lip.push(shield(PZ1, -2.2 + 4.4 * j / 24));
            g.add(polyline(lip, lmat(colors.light, 1)));
            const crestTube = [];
            for (let i = 0; i <= 12; i++) crestTube.push(shield(PZ0 - (PZ0 - PZ1) * i / 12, 0));
            g.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(crestTube), 20, 0.014, 4, false), mat(colors.light)));

            // Prothorax + pterothorax beneath
            const pro = ellipsoid(V(0.2, 0.24, 0.3), colors.primary, 18, 12); pro.position.set(0, -0.02, 0.8); g.add(pro);
            const pt = ellipsoid(V(0.26, 0.29, 0.38), colors.primary, 24, 16); pt.position.set(0, 0.0, 0.42); g.add(pt);
            // Thoracic spiracles and sternal plates
            [-1, 1].forEach(s => g.add(surfaceRing(0.025, colors.light, V(s * 0.255, 0.02, 0.52), V(s, 0, 0))));
            g.add(ball(1, colors.mid, 0, -0.27, 0.6, 0.14, 0.03, 0.4, 12, 6));
        }

        // ═════════════════════════ ABDOMEN ═════════════════════════
        function buildAbdomen(g) {
            const R = [0.24, 0.25, 0.24, 0.22, 0.19, 0.16, 0.13, 0.1, 0.07];
            const A = [0.0, -0.02, -0.02, 0.0, 0.03, 0.06, 0.09, 0.12, 0.14];   // tip curls up
            const defs = R.map((r, i) => ({
                len: 0.28, r0: r * 0.95, rm: r * 1.03, r1: (R[i + 1] || 0.05) * 0.98,
                color: i % 2 ? colors.mid : colors.primary, angle: A[i], radial: 14, knuckle: false, hairs: 16,
                extra: (j, d) => {
                    j.add(ring(d.r0 * 1.03, colors.light, 0.05));
                    // Dorsal keel and tergite/sternite seam
                    const top = [], seam = [[], []];
                    for (let k = 0; k <= 8; k++) {
                        const u = 0.05 + k / 8 * 0.9, rr = qb(d.r0, d.rm, d.r1, u) * 1.02;
                        top.push(V(u * d.len, rr, 0));
                        seam[0].push(V(u * d.len, -rr * 0.35, rr * 0.94)); seam[1].push(V(u * d.len, -rr * 0.35, -rr * 0.94));
                    }
                    j.add(polyline(top, lmat(colors.light, 0.8)));
                    seam.forEach(sm => j.add(polyline(sm, lmat(colors.light, 0.45))));
                    [-1, 1].forEach(s => {
                        const rr = qb(d.r0, d.rm, d.r1, 0.35) * 1.01;
                        if (i === 0) {
                            // Tympanum: the locust's ear, an oval membrane on the first segment
                            const ty = new THREE.Mesh(new THREE.TorusGeometry(0.06, 0.008, 3, 20), mat(colors.light));
                            ty.position.set(0.45 * d.len, 0.03, s * rr * 0.98);
                            ty.scale.set(1.3, 0.8, 1);
                            j.add(ty);
                            j.add(new THREE.Mesh(new THREE.CircleGeometry(0.05, 12).translate(0, 0, 0), mat(colors.mid)).translateX(0.45 * d.len).translateY(0.03).translateZ(s * rr * 0.99));
                        } else if (i < 8) {
                            j.add(surfaceRing(0.016, colors.light, V(0.35 * d.len, 0.02, s * rr * 0.99), V(0, 0.05, s).normalize()));
                        }
                    });
                }
            }));
            const ch = buildChain(defs);
            ch.root.position.set(0, 0.0, 0.08);
            ch.root.rotation.y = Math.PI / 2;
            g.add(ch.root);
            const last = ch.joints[defs.length - 1], L = defs[defs.length - 1].len;
            // Cerci and the four hooked ovipositor valves
            [-1, 1].forEach(s => {
                const c = buildChain([{ len: .1, r0: .015, rm: .016, r1: .004, color: colors.light, angle: 0.3, radial: 5, hairs: 6 }]);
                c.root.position.set(L, 0.03, s * 0.03); c.root.rotation.y = s * 0.5;
                last.add(c.root);
                [[0.025, 0.25], [-0.02, -0.25]].forEach(([y, a]) => {
                    const v = buildChain([{ len: .07, r0: .014, rm: .014, r1: .005, color: colors.mid, angle: a, radial: 5 },
                                          { len: .03, r0: .006, rm: .005, r1: .002, color: colors.light, angle: -Math.sign(a) * 0.8, radial: 4, knuckle: false }]);
                    v.root.position.set(L, y, s * 0.012);
                    last.add(v.root);
                });
            });
            ch.joints.forEach((j, i) => abdomen.push({ joint: j, mesh: ch.meshes[i], rest: defs[i].angle, i }));
        }

        // ═════════════════════════ LEGS ═════════════════════════
        function addFoot(j, d) {
            const L = d.len;
            [-1, 1].forEach(s => {
                const c = new THREE.QuadraticBezierCurve3(V(L, 0, s * 0.006), V(L + 0.03, 0.005, s * 0.015), V(L + 0.036, -0.026, s * 0.02));
                j.add(new THREE.Mesh(new THREE.TubeGeometry(c, 5, 0.0045, 4, false), mat(colors.light)));
            });
            j.add(ball(0.016, colors.primary, L + 0.012, -0.012, 0, 1.3, 0.5, 1, 8, 6));   // arolium
        }
        // Tarsal pads (euplantulae) on the underside of each tarsomere
        const pads = (j, d) => { j.add(ball(d.len * 0.35, colors.primary, d.len * 0.5, -d.r0 * 0.9, 0, 1, 0.35, 0.8, 8, 6)); };

        const AIR_FRONT = [-0.7, 0.1, 0.95, -2.1, -0.4, -0.15, -0.1];
        const AIR_HIND  = [-0.15, 0.1, 0.15, -0.4, -0.15, -0.05, -0.05];

        function walkDefs(sc) {
            const L = [.12, .05, .36, .34, .07, .045, .085];
            const R = [[.034, .036, .03], [.026, .027, .024], [.028, .034, .024], [.018, .019, .016], [.014, .014, .013], [.012, .012, .011], [.011, .011, .008]];
            const A = [-0.4, 0.1, 0.35, -1.4, -0.35, -0.1, -0.08];
            return L.map((len, i) => ({
                len: len * sc, r0: R[i][0], rm: R[i][1], r1: R[i][2],
                color: i < 2 ? colors.mid : i === 3 ? colors.light : i % 2 ? colors.primary : colors.mid,
                angle: A[i], radial: i < 4 ? 8 : 6, hairs: [0, 0, 18, 14, 4, 3, 3][i],
                spines: i === 3 ? 8 : 0, bands: i === 2 ? [0.95] : null,
                extra: i === 6 ? addFoot : i >= 4 ? pads : null,
            }));
        }
        function hindDefs() {
            const L = [.1, .06, .98, 1.0, .1, .06, .12];
            return [
                { len: L[0], r0: .045, rm: .05, r1: .04, color: colors.mid, angle: -0.2 },
                { len: L[1], r0: .04, rm: .042, r1: .045, color: colors.light, angle: 0.1 },
                // The jumping femur: massive, keeled, with herringbone muscle chevrons
                { len: L[2], r0: .06, rm: .1, r1: .042, color: colors.primary, angle: 0.62, radial: 14, sy: 1.15,
                  extra: (j, d) => {
                      const hb = [];
                      for (let k = 0; k < 14; k++) {
                          const u = 0.1 + k * 0.058, r = qb(d.r0, d.rm, d.r1, u);
                          [-1, 1].forEach(s => {
                              // Chevrons on both faces: ∧ shapes pointing distally
                              hb.push(u * d.len, r * 0.5, s * r * 0.9, (u + 0.045) * d.len, 0, s * r * 1.02);
                              hb.push((u + 0.045) * d.len, 0, s * r * 1.02, u * d.len, -r * 0.5, s * r * 0.9);
                          });
                      }
                      j.add(lineSegs(hb, lmat(colors.light, 0.85)));
                      // Dorsal and ventral keels
                      [1, -1].forEach(sg => {
                          const k = [];
                          for (let m = 0; m <= 12; m++) { const u = 0.04 + m / 12 * 0.92; k.push(V(u * d.len, sg * qb(d.r0, d.rm, d.r1, u) * 1.18, 0)); }
                          j.add(polyline(k, lmat(colors.light, 1)));
                      });
                      // Knee lobes: the dark crescents of the spring
                      [-1, 1].forEach(s => j.add(ball(0.04, colors.mid, d.len * 0.96, 0, s * 0.03, 1.2, 1, 0.5, 10, 8)));
                  } },
                // Tibia: slender, with two rows of spines and apical spurs
                { len: L[3], r0: .024, rm: .026, r1: .022, color: colors.light, angle: -2.42, radial: 8,
                  extra: (j, d) => {
                      const sp = [];
                      for (let k = 0; k < 10; k++) {
                          const u = 0.3 + k * 0.065;
                          [-1, 1].forEach(s => sp.push(u * d.len, d.r1, s * d.r1 * 0.7, u * d.len + 0.035, d.r1 + 0.04, s * (d.r1 + 0.02)));
                      }
                      [-1, 1].forEach(s => sp.push(d.len * 0.97, d.r1 * 0.5, s * d.r1, d.len + 0.06, d.r1 * 0.8, s * d.r1 * 2));
                      j.add(lineSegs(sp, lmat(colors.light, 0.95)));
                  } },
                { len: L[4], r0: .018, rm: .018, r1: .016, color: colors.mid, angle: 1.75, radial: 6, extra: pads },
                { len: L[5], r0: .015, rm: .015, r1: .014, color: colors.primary, angle: -0.05, radial: 6, extra: pads },
                { len: L[6], r0: .013, rm: .013, r1: .01, color: colors.mid, angle: -0.05, radial: 6, extra: addFoot },
            ];
        }
        function buildLegs(g) {
            [{ z: 0.92, fa: Math.PI * 0.3, sc: 0.95 }, { z: 0.58, fa: Math.PI * 0.52, sc: 1.05 }].forEach((p, pi) => {
                [-1, 1].forEach(side => {
                    const defs = walkDefs(p.sc);
                    const ch = buildChain(defs);
                    const attach = V(side * 0.18, -0.2, p.z);
                    ch.root.position.copy(attach);
                    ch.root.rotation.y = yawFor(side, p.fa);
                    g.add(ch.root);
                    legs.push({ root: ch.root, joints: ch.joints, side, pair: pi, hind: false, attach, fa: p.fa,
                                phase: ((pi + (side > 0 ? 0 : 1)) % 2) * Math.PI + pi * 0.4,
                                lens: defs.map(d => d.len), rest: defs.map(d => d.angle), ang: defs.map(d => d.angle), h: 0.6 });
                });
            });
            [-1, 1].forEach(side => {
                const defs = hindDefs();
                const ch = buildChain(defs);
                const attach = V(side * 0.24, -0.06, 0.22);
                ch.root.position.copy(attach);
                ch.root.rotation.y = yawFor(side, Math.PI * 0.9);
                g.add(ch.root);
                legs.push({ root: ch.root, joints: ch.joints, side, pair: 2, hind: true, attach, fa: Math.PI * 0.9, phase: 0,
                            lens: defs.map(d => d.len), rest: defs.map(d => d.angle), ang: defs.map(d => d.angle), h: 0.3 });
            });
        }

        // ═════════════════════════ WINGS ═════════════════════════
        // Tegmina: long, leathery forewings with a dense reticulate vein
        // network and dark spots, laid roof-like along the back at rest.
        function makeTegmen(len, wid, side) {
            const g = new THREE.Group();
            const outline = u => {
                const k = 0.4 + 0.6 * smooth(0, 0.12, u);
                const e = Math.sqrt(Math.max(0, 1 - Math.pow(u, 5)));
                return [wid * 0.3 * k * Math.pow(e, 0.4), -wid * 0.7 * k * e];
            };
            const P = (u, f) => { const [le, te] = outline(u); return V(side * u * len, 0, le + (te - le) * f); };
            const NU = 34, NF = 6, pos = [], idx = [];
            for (let i = 0; i <= NU; i++) for (let j = 0; j <= NF; j++) { const p = P(i / NU, j / NF); pos.push(p.x, p.y, p.z); }
            for (let i = 0; i < NU; i++) for (let j = 0; j < NF; j++) { const a = i * (NF + 1) + j, b = a + NF + 1; idx.push(a, b, a + 1, b, b + 1, a + 1); }
            const mg = new THREE.BufferGeometry();
            mg.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
            mg.setIndex(idx);
            g.add(new THREE.Mesh(mg, new THREE.MeshBasicMaterial({ color: colors.primary, wireframe: true, transparent: true, opacity: 0.35 })));
            const ol = [];
            for (let k = 0; k <= 50; k++) ol.push(P(k / 50, 0));
            for (let k = 50; k >= 0; k--) ol.push(P(k / 50, 1));
            g.add(polyline(ol, lmat(colors.light, 1), true));
            // Longitudinal veins + a mesh of crossveins
            const tracks = [0, 0.1, 0.22, 0.36, 0.5, 0.64, 0.8, 1];
            const vp = [];
            tracks.slice(1, -1).forEach(f => {
                let prev = null;
                for (let k = 0; k <= 30; k++) { const p = P(k / 30 * 0.97, f); if (prev) vp.push(prev.x, prev.y, prev.z, p.x, p.y, p.z); prev = p; }
            });
            for (let u = 0.05; u < 0.96; u += 0.018) for (let k = 0; k < tracks.length - 1; k++) {
                if (rand() > 0.85) continue;
                const uu = u + (rand() - 0.5) * 0.012;
                const a = P(uu, tracks[k]), b = P(uu + (rand() - 0.5) * 0.02, tracks[k + 1]);
                vp.push(a.x, a.y, a.z, b.x, b.y, b.z);
            }
            g.add(lineSegs(vp, lmat(colors.light, 0.55)));
            // Dark spots
            for (let k = 0; k < 9; k++) {
                const u = 0.3 + rand() * 0.6, f = 0.2 + rand() * 0.6, p = P(u, f);
                const sp = new THREE.Mesh(new THREE.TorusGeometry(0.025 + rand() * 0.02, 0.006, 3, 12).rotateX(Math.PI / 2), mat(colors.mid));
                sp.position.set(p.x, 0.004, p.z);
                g.add(sp);
            }
            const cpts = [];
            for (let k = 0; k <= 20; k++) cpts.push(P(k / 20 * 0.96, 0));
            g.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(cpts), 30, 0.01, 4, false), mat(colors.light)));
            return g;
        }

        // Hindwing: a pleated fan of radial ribs. Rebuilt every frame from
        // an "open" amount: folded, the ribs bunch backward in accordion
        // pleats under the tegmen; open, they spread into a broad fan.
        const FAN_N = 16, FAN_S = 10, FAN_ARCS = [0.15, 0.3, 0.45, 0.6, 0.72, 0.84, 0.94];
        function buildFan(side) {
            const nSeg = FAN_N * FAN_S + (FAN_N - 1) * (FAN_ARCS.length + 1) + 3 * 8;
            const geo = new THREE.BufferGeometry();
            geo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(nSeg * 6), 3));
            const col = new Float32Array(nSeg * 6), c = new THREE.Color();
            let k = 0;
            const put = hex => { c.setHex(hex); for (let m = 0; m < 2; m++) { col[k++] = c.r; col[k++] = c.g; col[k++] = c.b; } };
            for (let i = 0; i < FAN_N; i++) for (let s = 0; s < FAN_S; s++) put(i < 4 ? colors.light : colors.primary);
            for (let i = 0; i < FAN_N - 1; i++) {
                FAN_ARCS.forEach(f => put(f === 0.72 || f === 0.84 ? colors.mid : colors.light));
                put(colors.light);
            }
            for (let m = 0; m < 24; m++) put(colors.light);
            geo.setAttribute('color', new THREE.Float32BufferAttribute(col, 3));
            const ls = new THREE.LineSegments(geo, new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.75 }));
            ls.frustumCulled = false;
            const lens = [], rng = [];
            for (let i = 0; i < FAN_N; i++) {
                lens.push(i < 4 ? 1.7 - i * 0.02 : 1.7 * (0.98 - 0.32 * Math.pow((i - 4) / 11, 1.4)));
                rng.push(rand());
            }
            return { mesh: ls, geo, lens, side };
        }
        function updateFan(F, open) {
            const a = F.geo.attributes.position.array, s = F.side;
            let k = 0;
            const pt = (i, f) => {
                const oi = smooth(0, 1, open * 1.25 - i * 0.015);
                const phi = (0.05 + i * 0.006) * (1 - oi) + (1.5 - i * (1.42 / (FAN_N - 1))) * oi;
                const r = F.lens[i] * f;
                const pleat = (i % 2 ? 1 : -1) * (1 - oi) * 0.03 * f + (i % 2 ? 0.004 : 0) * oi;
                return [s * Math.sin(phi) * r, pleat - (1 - oi) * i * 0.004 * f, -Math.cos(phi) * r];
            };
            const seg = (p, q) => { a[k++] = p[0]; a[k++] = p[1]; a[k++] = p[2]; a[k++] = q[0]; a[k++] = q[1]; a[k++] = q[2]; };
            for (let i = 0; i < FAN_N; i++) for (let j = 0; j < FAN_S; j++) seg(pt(i, j / FAN_S), pt(i, (j + 1) / FAN_S));
            for (let i = 0; i < FAN_N - 1; i++) {
                FAN_ARCS.forEach(f => seg(pt(i, f), pt(i + 1, f)));
                seg(pt(i, 1), pt(i + 1, 1));
            }
            for (let i = 0; i < 3; i++) for (let m = 0; m < 8; m++) { const f = 0.12 + m * 0.1; seg(pt(i, f), pt(i + 1, f + 0.03)); }
            F.geo.attributes.position.needsUpdate = true;
        }

        function buildWings(g) {
            [-1, 1].forEach(side => {
                const root = new THREE.Group();
                root.position.set(side * 0.15, 0.12, 0.58);
                const yaw = new THREE.Group(), stroke = new THREE.Group(), pitchG = new THREE.Group();
                root.add(yaw); yaw.add(stroke); stroke.add(pitchG);
                pitchG.add(makeTegmen(1.95, 0.4, side));
                g.add(root);
                wings.push({ side, yaw, stroke, pitchG });

                const hr = new THREE.Group();
                hr.position.set(side * 0.1, 0.2, 0.5);
                const flap = new THREE.Group();
                hr.add(flap);
                const F = buildFan(side);
                flap.add(F.mesh);
                g.add(hr);
                fans.push({ side, flap, F });
            });
        }

        function createLocust() {
            const root = new THREE.Group();
            root.add(buildGround());
            body = new THREE.Group();
            body.position.z = 0.55;
            root.add(body);
            body.add(buildHead());
            buildThorax(body);
            buildAbdomen(body);
            buildLegs(body);
            buildWings(body);
            return root;
        }

        // ── Pointer interaction: drag to spin (with inertia) and tilt ──
        let dragging = false, lastX = 0, lastY = 0, spinVel = 0, userSpin = 0, pitch = 0;

        function onDown(x, y) { dragging = true; lastX = x; lastY = y; document.body.classList.add('dragging'); }
        function onMove(x, y) {
            if (!dragging) return;
            spinVel = (x - lastX) * 0.006;
            userSpin += spinVel;
            pitch = Math.max(-0.35, Math.min(0.6, pitch + (y - lastY) * 0.004));
            lastX = x; lastY = y;
        }
        function onUp() { dragging = false; document.body.classList.remove('dragging'); }

        window.addEventListener('pointerdown', e => onDown(e.clientX, e.clientY));
        window.addEventListener('pointermove', e => onMove(e.clientX, e.clientY));
        window.addEventListener('pointerup', onUp);
        window.addEventListener('pointercancel', onUp);

        let camDist = 5, camEl = 0.4;
        function updateSize() {
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        }
        function updateCamera() {
            const w = window.innerWidth, aspect = w / window.innerHeight;
            camera.fov = w < 480 ? 55 : w < 768 ? 50 : 45;
            const tf = Math.tan(camera.fov * Math.PI / 360);
            camDist = Math.min(11, Math.max(5.2, 2.7 / (tf * aspect), 2.0 / tf));
            camera.aspect = aspect;
            camera.updateProjectionMatrix();
        }

        function init() {
            initBackground();
            animateBackground();
            updateSize();

            scene = new THREE.Scene();
            scene.background = new THREE.Color(colors.dark3);

            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
            updateCamera();

            locust = createLocust();
            scene.add(locust);

            animate();
        }

        const bump = (x, c, w) => Math.exp(-(((x - c) / w) ** 2));

        function animate() {
            requestAnimationFrame(animate);
            const t = performance.now();

            if (!dragging) {
                userSpin += spinVel;
                spinVel *= 0.95;
                pitch *= 0.97;
            }

            // ── Behaviour cycle (16 s) ──
            // idle → stridulate (hind femora rasp) → idle → crouch & cock →
            // launch → airborne arc with wings open → land, fold, settle
            const P = 16, cyc = (t / 1000) % P, leap = Math.floor(t / 1000 / P);
            const strid  = smooth(3.6, 4, cyc) * (1 - smooth(5.6, 6, cyc));
            const crouch = smooth(8.8, 10.3, cyc) * (1 - smooth(10.5, 10.6, cyc));
            const T0 = 10.6, AIR = 1.4;
            const s = Math.min(1, Math.max(0, (cyc - T0) / AIR));
            const airborne = cyc > T0 && cyc < T0 + AIR;
            const extend = smooth(10.48, 10.62, cyc) * (1 - smooth(T0 + AIR + 0.1, T0 + AIR + 1.1, cyc));
            const ab = smooth(10.62, 10.8, cyc) * (1 - smooth(T0 + AIR - 0.2, T0 + AIR + 0.05, cyc));
            const open = smooth(10.66, 10.95, cyc) * (1 - smooth(T0 + AIR + 0.05, T0 + AIR + 0.9, cyc));
            const impact = bump(cyc, T0 + AIR + 0.1, 0.12);
            const h = airborne ? 4 * 1.0 * s * (1 - s) : 0;
            const offset = (leap + (cyc > T0 ? s : 0)) * JUMP_D;

            updateGround(offset, t);

            // Camera follows the leap upward a little
            const el = camEl + pitch;
            camera.position.set(0, Math.sin(el) * camDist + h * 0.4, Math.cos(el) * camDist);
            camera.lookAt(0, 0.05 + h * 0.6, 0);
            locust.rotation.y = userSpin + t * 0.0003;

            const breath = Math.sin(t * 0.0028);
            body.position.y = -0.11 * crouch + h - 0.08 * impact + breath * 0.004;
            body.rotation.x = -0.12 * crouch + (-0.3 * (1 - s) + 0.15 * s) * ab + 0.06 * impact;
            body.rotation.z = Math.sin(t * 0.0014) * 0.008;
            const by = body.position.y, sa = Math.sin(body.rotation.x), ca = Math.cos(body.rotation.x);

            head.rotation.y = Math.sin(t * 0.0006) * 0.12 * (1 - crouch);
            head.rotation.x = Math.sin(t * 0.0009) * 0.04 - crouch * 0.06;

            // Mouthparts chew, palps tap; antennae sweep back in flight
            mouth.mandibles.forEach(M => M.root.rotation.y = yawFor(M.side, 0.25 + Math.max(0, Math.sin(t * 0.006)) * 0.2));
            mouth.palps.forEach(Pp => Pp.joint.rotation.z = Pp.rest + Math.max(0, Math.sin(t * 0.004 + Pp.side * 1.5 + Pp.rest)) * 0.25);
            for (const A of antennae) {
                A.root.rotation.y = yawFor(A.side, 0.3 + Math.sin(t * 0.0024 + A.side) * 0.1 + ab * 0.35);
                A.joints[0].rotation.z = A.rest[0] + Math.sin(t * 0.003 + A.side) * 0.08 - ab * 0.3;
                for (let i = 1; i < A.joints.length; i++)
                    A.joints[i].rotation.z = A.rest[i] + Math.sin(t * 0.004 - i * 0.35 + A.side) * 0.012 + ab * 0.01;
            }

            // Abdomen pumps (locusts visibly ventilate); straightens in flight
            for (const S of abdomen) {
                S.joint.rotation.z = S.rest * (1 - ab * 0.7) + Math.sin(t * 0.0028 - S.i * 0.3) * 0.006 - impact * 0.02;
                const b = 1 + Math.sin(t * 0.0028 - S.i * 0.45) * 0.035;
                S.mesh.scale.set(1, b, 1 + (b - 1) * 0.5);
            }

            // Legs: IK keeps grounded feet planted; blended to flight poses in the air
            for (const L of legs) {
                const a = L.ang;
                for (let i = 0; i < a.length; i++) a[i] = L.rest[i];
                let fa = L.fa;
                if (L.hind) {
                    a[3] += -0.15 * crouch + extend * 1.9;        // cock, then snap the tibia open
                    a[4] -= extend * 1.5;
                } else {
                    const x = t * 0.0014 + L.phase;
                    a[3] += Math.sin(x) * 0.03;
                    fa += Math.cos(x) * 0.03;
                }
                const zb = L.attach.z + L.h * Math.cos(fa);
                const target = (GROUND_Y - by + zb * sa) / ca - L.attach.y;
                solveFemur(L, target);
                const air = L.hind ? AIR_HIND : AIR_FRONT;
                for (let i = 0; i < a.length; i++) {
                    let v = a[i] + (air[i] - a[i]) * ab;
                    if (L.hind && i === 2) v += Math.sin(t * 0.055) * 0.09 * strid;   // stridulation rasp
                    L.joints[i].rotation.z = v;
                }
                L.root.rotation.y = yawFor(L.side, fa);
            }

            // Wings: tegmina roof the back at rest, swing out and beat in flight;
            // the hindwing fans unfold and beat beneath them
            const beat = Math.sin(t * 0.07);
            const flick = bump(cyc, 6.8, 0.15);
            for (const W of wings) {
                W.yaw.rotation.y = W.side * (1.5 * (1 - open) + 0.12 * open - flick * 0.2);
                W.stroke.rotation.z = W.side * ((0.02 + flick * 0.15) * (1 - open) + (0.2 + 0.45 * beat) * open);
                W.pitchG.rotation.x = 1.0 * (1 - open) + 0.3 * Math.cos(t * 0.07) * open + Math.sin(t * 0.02) * 0.006;
            }
            for (const Fn of fans) {
                updateFan(Fn.F, open);
                Fn.flap.rotation.z = Fn.side * ((-0.25) * (1 - open) + (0.15 + 0.6 * Math.sin(t * 0.07 - 0.5)) * open);
                Fn.flap.rotation.x = -0.05 * (1 - open) + 0.15 * Math.cos(t * 0.07) * open;
            }

            renderer.render(scene, camera);
        }

        window.addEventListener('resize', () => {
            updateSize(); initBackground();
            if (camera) updateCamera();
        });

        window.addEventListener('load', init);
    </script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.