• 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 FLY 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 — Fly</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 ──
        const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('animationCanvas'), antialias: true, alpha: true });
        let scene, camera, insect, body, head, proboscis;
        const antennae = [], wings = [], legs = [], abdomen = [], cerci = [];
        let membraneMat, ghostMats = [];

        // 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);
        }

        // ═════════════════════════ HEAD ═════════════════════════
        const R_HEAD = V(0.17, 0.18, 0.15);
        const R_EYE  = V(0.13, 0.165, 0.145);

        // Compound eye: a hexagonal facet (ommatidium) at every point of a
        // Fibonacci lattice over the outward-facing cap of the eye ellipsoid.
        function compoundEye(side) {
            const g = new THREE.Group();
            g.add(ellipsoid(R_EYE, colors.mid, 18, 14));

            const out = V(side * 0.92, 0.12, 0.38).normalize();
            const N = 1100, 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);
                const 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.004);
                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.155, 0.02, 0.03);
            return g;
        }

        function buildAntenna(side) {
            const defs = [
                { len: .07, r0: .024, rm: .027, r1: .02, color: colors.mid, angle: .95 },              // scape
                { len: .05, r0: .02,  rm: .023, r1: .017, color: colors.light, angle: -.25, bands: [.5] }, // pedicel
            ];
            for (let i = 0; i < 16; i++) {                                                             // flagellum
                const r = 0.012 - i * 0.0004;
                defs.push({ len: .034, r0: r, rm: r * 1.25, r1: r * 0.9, color: colors.primary,
                            angle: i === 0 ? -0.2 : -0.03, radial: 6,
                            hairs: 3 });
            }
            const ch = buildChain(defs);
            ch.root.position.set(side * 0.06, 0.13, 0.12);
            ch.root.rotation.y = yawFor(side, 0.5);
            antennae.push({ side, root: ch.root, joints: ch.joints, rest: defs.map(d => d.angle) });
            return ch.root;
        }

        function buildProboscis() {
            const ch = buildChain([
                { len: .09, r0: .034, rm: .038, r1: .026, color: colors.mid, angle: -1.25, hairs: 10 },  // rostrum
                { len: .11, r0: .022, rm: .02,  r1: .018, color: colors.primary, angle: 0.45, bands: [.3, .7] }, // haustellum
                { len: .03, r0: .018, rm: .02,  r1: .018, color: colors.light, angle: -0.3,
                  extra: (j, d) => {
                      // Labellum: two sponge lobes ribbed with pseudotracheae
                      [-1, 1].forEach(s => {
                          const lobe = ball(0.045, colors.light, d.len + 0.02, -0.005, s * 0.03, 0.75, 0.45, 1, 12, 8);
                          j.add(lobe);
                          const rib = [];
                          for (let k = 0; k < 9; k++) {
                              const a = (k / 8 - 0.5) * 2.4;
                              rib.push(d.len + 0.005, -0.02, s * 0.006,
                                       d.len + 0.02 + Math.cos(a) * 0.03, -0.024, s * (0.03 + Math.sin(a) * 0.03 + 0.012));
                          }
                          j.add(lineSegs(rib, lmat(colors.primary, 0.9)));
                      });
                  } },
            ]);
            ch.root.position.set(0, -0.12, 0.06);
            ch.root.rotation.y = -Math.PI / 2;   // +X → +Z (forward), then pitched down
            proboscis = { joints: ch.joints, rest: [-1.25, 0.45, -0.3] };
            return ch.root;
        }

        function buildHead() {
            head = new THREE.Group();
            head.position.set(0, 0.08, 1.2);    // pivot at the neck
            const h = new THREE.Group();
            h.position.set(0, 0, 0.15);
            head.add(h);

            h.add(ellipsoid(R_HEAD, colors.primary, 22, 16));
            h.add(compoundEye(-1));
            h.add(compoundEye(1));

            // Face: frontal suture, ptilinal arc, clypeus outline
            const face = [], arc = [], clyp = [];
            for (let k = 0; k <= 12; k++) face.push(V(0, 0.9 - k * 0.12, 1));
            for (let k = 0; k <= 16; k++) { const a = (k / 16 - .5) * 1.6; arc.push(V(Math.sin(a) * 0.7, 0.35 + Math.cos(a) * 0.15, 1)); }
            for (let k = 0; k <= 16; k++) { const a = k / 16 * Math.PI * 2; clyp.push(V(Math.sin(a) * 0.32, -0.45 + Math.cos(a) * 0.18, 1)); }
            h.add(ellLine(R_HEAD, face, colors.light, 0.55));
            h.add(ellLine(R_HEAD, arc,  colors.light, 0.7));
            h.add(ellLine(R_HEAD, clyp, colors.light, 0.6));

            // Ocelli: triangle of simple eyes on the vertex
            [[0, 0.98, 0.25, 0.02], [-0.22, 0.97, -0.05, 0.016], [0.22, 0.97, -0.05, 0.016]].forEach(([x, y, z, r]) => {
                const p = ellRay(R_HEAD, V(x, y, z).normalize());
                const n = ellNormal(R_HEAD, p);
                const o = ball(r, colors.light, p.x, p.y, p.z, 1, 1, 1, 8, 6);
                h.add(o);
                h.add(surfaceRing(r * 1.4, colors.mid, p, n));
            });
            // Vertical bristles and head hair
            const vb = [];
            for (let i = 0; i < 10; i++) {
                const d = V((i - 4.5) * 0.14, 0.95, -0.1 + (i % 3) * 0.1).normalize();
                const p = ellRay(R_HEAD, d);
                const L = 0.08 + rand() * 0.07;
                const dir = ellNormal(R_HEAD, p).add(V(0, 0.2, -0.9)).normalize();
                vb.push(p.x, p.y, p.z, p.x + dir.x * L, p.y + dir.y * L, p.z + dir.z * L);
            }
            h.add(lineSegs(vb, lmat(colors.light, 0.85)));
            h.add(hairField(R_HEAD, 160, 0.015, 0.035, V(0, 0, -0.5), colors.primary, 0.45, n => n.z < 0.5));

            h.add(buildAntenna(-1));
            h.add(buildAntenna(1));
            h.add(buildProboscis());

            // Maxillary palps beside the proboscis
            [-1, 1].forEach(s => {
                const ch = buildChain([
                    { len: .05, r0: .01, rm: .012, r1: .01, color: colors.primary, angle: -0.9 },
                    { len: .055, r0: .012, rm: .02, r1: .006, color: colors.light, angle: 0.4, hairs: 8 },
                ]);
                ch.root.position.set(s * 0.05, -0.1, 0.1);
                ch.root.rotation.y = yawFor(s, 0.35);
                h.add(ch.root);
            });

            // Neck membrane
            const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.09, 0.12, 12, 2, true).rotateX(Math.PI / 2), mat(colors.mid));
            neck.position.z = -0.02;
            head.add(neck);
            return head;
        }

        // ═════════════════════════ THORAX ═════════════════════════
        function buildThorax(g) {
            // Prothorax collar
            const C_PRO = V(0, 0.1, 1.04), R_PRO = V(0.15, 0.14, 0.11);
            const pro = new THREE.Group(); pro.position.copy(C_PRO);
            pro.add(ellipsoid(R_PRO, colors.mid, 18, 12));
            pro.add(hairField(R_PRO, 60, 0.02, 0.04, V(0, 0.2, -0.6), colors.primary, 0.45));
            g.add(pro);

            // Mesothorax — the big flight-muscle box
            const C_MESO = V(0, 0.14, 0.74), R_MESO = V(0.28, 0.3, 0.34);
            const meso = new THREE.Group(); meso.position.copy(C_MESO);
            meso.add(ellipsoid(R_MESO, colors.primary, 30, 22));
            // Sutures: median, transverse, and notopleural lines either side
            const med = [], tra = [];
            for (let k = 0; k <= 16; k++) med.push(V(0, Math.sin(k / 16 * Math.PI), Math.cos(k / 16 * Math.PI)));
            for (let k = 0; k <= 16; k++) { const a = (k / 16 - .5) * 2.2; tra.push(V(Math.sin(a), Math.cos(a), -0.05)); }
            meso.add(ellLine(R_MESO, med, colors.light, 0.55));
            meso.add(ellLine(R_MESO, tra, colors.light, 0.75));
            [-1, 1].forEach(s => {
                const np = [];
                for (let k = 0; k <= 14; k++) np.push(V(s, 0.25 + 0.15 * Math.sin(k / 14 * Math.PI), 0.9 - k * 0.13));
                meso.add(ellLine(R_MESO, np, colors.light, 0.6));
                // Dorsal stripes (vittae)
                const st = [];
                for (let k = 0; k <= 14; k++) { const a = Math.PI * (0.15 + k / 14 * 0.7); st.push(V(s * 0.28, Math.sin(a), Math.cos(a))); }
                meso.add(ellLine(R_MESO, st, colors.light, 0.4));
            });
            // Macrochaetae: rows of stout bristles, swept back
            const mc = [];
            [-0.55, -0.25, 0.25, 0.55].forEach(x => {
                for (let z = -0.7; z <= 0.7; z += 0.35) {
                    const p = ellRay(R_MESO, V(x, 0.9, z).normalize());
                    const d = ellNormal(R_MESO, p).add(V(0, 0.1, -1.1)).normalize();
                    const L = 0.1 + rand() * 0.07;
                    mc.push(p.x, p.y, p.z, p.x + d.x * L, p.y + d.y * L, p.z + d.z * L);
                }
            });
            meso.add(lineSegs(mc, lmat(colors.light, 0.9)));
            meso.add(hairField(R_MESO, 420, 0.018, 0.04, V(0, 0.15, -0.7), colors.primary, 0.4));
            // Thoracic spiracle
            [-1, 1].forEach(s => {
                const p = ellRay(R_MESO, V(s, -0.1, 0.35).normalize()).multiplyScalar(1.01);
                meso.add(surfaceRing(0.026, colors.light, p, ellNormal(R_MESO, p)));
            });
            g.add(meso);

            // Scutellum shield
            const scu = new THREE.Group(); scu.position.set(0, 0.34, 0.45);
            const R_SCU = V(0.15, 0.08, 0.11);
            scu.add(ellipsoid(R_SCU, colors.primary, 16, 10));
            const sb = [];
            [-0.7, -0.3, 0.3, 0.7].forEach(x => {
                const p = ellRay(R_SCU, V(x, 0.4, -0.8).normalize());
                sb.push(p.x, p.y, p.z, p.x + x * 0.05, p.y + 0.06, p.z - 0.12);
            });
            scu.add(lineSegs(sb, lmat(colors.light, 0.9)));
            g.add(scu);

            // Metathorax
            const C_META = V(0, 0.1, 0.36), R_META = V(0.23, 0.23, 0.16);
            const meta = new THREE.Group(); meta.position.copy(C_META);
            meta.add(ellipsoid(R_META, colors.mid, 20, 14));
            meta.add(hairField(R_META, 90, 0.015, 0.035, V(0, 0, -0.6), colors.primary, 0.4));
            g.add(meta);

            // Sternal plates on the underside
            g.add(ball(1, colors.mid, 0, -0.11, 0.78, 0.16, 0.04, 0.26, 14, 8));
        }

        // ═════════════════════════ ABDOMEN ═════════════════════════
        // A chain of 10 segments so it can curl and telescope as it breathes.
        function buildAbdomen(g) {
            const N = 10, defs = [];
            for (let i = 0; i < N; i++) {
                const t = i / (N - 1);
                const r = 0.165 * (1 - t * 0.7);
                defs.push({
                    len: 0.27, r0: r * 0.94, rm: r * 1.06, r1: r * 0.9,
                    color: i % 2 ? colors.mid : colors.primary,
                    angle: i === 0 ? -0.05 : -0.035, radial: 14, knuckle: false,
                    hairs: Math.round(46 - i * 3),
                    extra: (j, d) => {
                        // Intersegmental membrane ring and posterior setae fringe
                        j.add(ring(d.r0 * 1.04, colors.light, 0.06));
                        j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                            count: 16, ordered: false, l0: d.r1 * 0.35, l1: d.r1 * 0.6, distal: 2.5,
                            color: colors.light, opacity: 0.5 }));
                        // Dorsal tergite marking: median line + paired spots
                        const top = [];
                        for (let k = 0; k <= 8; k++) {
                            const u = 0.08 + k / 8 * 0.84;
                            top.push(V(u * d.len, qb(d.r0, d.rm, d.r1, u) * 1.02, 0));
                        }
                        j.add(polyline(top, lmat(colors.light, 0.65)));
                        [-1, 1].forEach(s => {
                            const u = 0.5, r = qb(d.r0, d.rm, d.r1, u) * 1.01;
                            const p = V(u * d.len, r * Math.cos(0.6), s * r * Math.sin(0.6));
                            const n = V(0, Math.cos(0.6), s * Math.sin(0.6));
                            j.add(surfaceRing(d.r0 * 0.18, colors.light, p, n));
                            // Spiracle on each flank
                            if (i < 8) j.add(surfaceRing(0.018, colors.light, V(0.35 * d.len, -r * 0.15, s * r), V(0, -0.15, s).normalize()));
                        });
                        // Pleural fold along the flanks
                        [-1, 1].forEach(s => {
                            const pl = [];
                            for (let k = 0; k <= 6; k++) {
                                const u = k / 6, r = qb(d.r0, d.rm, d.r1, u) * 1.01;
                                pl.push(V(u * d.len, -r * 0.45, s * r * 0.89));
                            }
                            j.add(polyline(pl, lmat(colors.light, 0.4)));
                        });
                    }
                });
            }
            const ch = buildChain(defs);
            ch.root.position.set(0, 0.07, 0.24);
            ch.root.rotation.y = Math.PI / 2;      // chain +X → body -Z (backward)
            g.add(ch.root);
            ch.joints.forEach((j, i) => abdomen.push({ joint: j, mesh: ch.meshes[i], rest: defs[i].angle, i }));

            // Cerci: segmented, bead-jointed, hairy filaments off the last segment
            const last = ch.joints[N - 1];
            [-1, 1].forEach(s => {
                const cd = [];
                for (let k = 0; k < 12; k++) {
                    const r = 0.016 - k * 0.0009;
                    cd.push({ len: 0.05, r0: r, rm: r * 1.15, r1: r * 0.85, color: k % 2 ? colors.light : colors.primary,
                              angle: k === 0 ? -0.3 : -0.03, radial: 6, hairs: 5 });
                }
                const c = buildChain(cd);
                c.root.position.set(defs[N - 1].len, 0, s * 0.015);
                c.root.rotation.y = s * 0.32;
                last.add(c.root);
                cerci.push({ side: s, joints: c.joints, rest: cd.map(d => d.angle) });
            });
        }

        // ═════════════════════════ LEGS ═════════════════════════
        // coxa · trochanter · femur · tibia · 5 tarsomeres
        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.006, s * 0.014), V(L + 0.036, -0.026, s * 0.02));
                j.add(new THREE.Mesh(new THREE.TubeGeometry(c, 6, 0.004, 4, false), mat(colors.light)));
                // Pulvilli: adhesive pads under the claws
                j.add(ball(0.016, colors.primary, L + 0.012, -0.012, s * 0.012, 1.2, 0.45, 0.8, 8, 6));
            });
            // Empodium bristle
            j.add(lineSegs([L, -0.005, 0, L + 0.03, -0.022, 0], lmat(colors.light, 0.9)));
        }
        function addSpurs(j, d) {
            const L = d.len, pos = [];
            [-1, 1].forEach(s => pos.push(L * 0.96, -d.r1 * 0.6, s * d.r1 * 0.6, L + 0.05, -d.r1 * 1.8, s * d.r1 * 1.4));
            j.add(lineSegs(pos, lmat(colors.light, 0.95)));
        }
        function legDefs(sc) {
            const rs = Math.sqrt(sc);
            const tars = [[.09, -.35], [.06, -.12], [.05, -.1], [.045, -.08], [.05, -.1]];
            const defs = [
                { len: .14*sc, r0: .032*rs, rm: .036*rs, r1: .028*rs, color: colors.mid,     angle: -.35 },
                { len: .06*sc, r0: .026*rs, rm: .027*rs, r1: .025*rs, color: colors.light,   angle: .10 },
                { len: .40*sc, r0: .026*rs, rm: .033*rs, r1: .022*rs, color: colors.primary, angle: .75,
                  hairs: 34, spines: 5, dspines: 3 },
                { len: .36*sc, r0: .018*rs, rm: .02*rs,  r1: .016*rs, color: colors.primary, angle: -1.75,
                  hairs: 28, spines: 5, bands: [.15], extra: addSpurs },
            ];
            tars.forEach(([len, angle], i) => {
                const r = (0.012 - i * 0.0012) * rs;
                defs.push({ len: len * sc, r0: r, rm: r * 1.1, r1: r * 0.9, color: i % 2 ? colors.light : colors.mid,
                            angle, radial: 6, hairs: 6, spines: 2, extra: i === 4 ? addFoot : null });
            });
            return defs;
        }
        function buildLegs(g) {
            const pairs = [
                { attachZ: 0.98, fanAngle: Math.PI * 0.22, scale: 0.85 }, // fore — sweeps forward
                { attachZ: 0.74, fanAngle: Math.PI * 0.50, scale: 1.00 }, // mid — straight out
                { attachZ: 0.50, fanAngle: Math.PI * 0.75, scale: 1.30 }, // hind — sweeps back, longest
            ];
            pairs.forEach((pair, pi) => {
                [-1, 1].forEach(side => {
                    const defs = legDefs(pair.scale);
                    const ch = buildChain(defs);
                    ch.root.position.set(side * 0.2, -0.06, pair.attachZ);
                    ch.root.rotation.y = yawFor(side, pair.fanAngle);
                    ch.joints[0].add(ring(defs[0].r0 * 1.3, colors.light, 0.15));
                    g.add(ch.root);
                    // Alternating tripod: L1 R2 L3 vs R1 L2 R3
                    const phase = ((pi + (side > 0 ? 0 : 1)) % 2) * Math.PI + pi * 0.3;
                    legs.push({ root: ch.root, joints: ch.joints, side, pair: pi, phase,
                                fa: pair.fanAngle, rest: defs.map(d => d.angle) });
                });
            });
        }

        // ═════════════════════════ WINGS ═════════════════════════
        // Wings are generated procedurally: an outline, longitudinal veins
        // that branch (radial sector, media), and a mosaic of crossveins that
        // closes them into cells. Built in the wing's own frame: span along
        // ±X (outward), chord along Z (leading edge +Z).
        function wingOutline(len, wid, fore) {
            return u => {
                const k = 0.32 + 0.68 * smooth(0, 0.22, u);
                const e = Math.sqrt(Math.max(0, 1 - Math.pow(u, 3.2)));
                const le = wid * 0.26 * k * Math.pow(e, 0.6);
                const bump = fore ? 0 : 0.4 * Math.exp(-(((u - 0.22) / 0.16) ** 2));   // hindwing anal lobe
                const te = -wid * 0.74 * k * e * (1 + bump);
                return [le, te];
            };
        }
        function makeWing(len, wid, fore, side, membrane, veinMat, full) {
            const g = new THREE.Group();
            const outline = wingOutline(len, wid, fore);
            const P = (u, f) => { const [le, te] = outline(u); return V(side * u * len, 0, le + (te - le) * f); };

            // Membrane: a fine grid across the wing
            const NU = 30, NF = 7, 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, membrane));

            // Outline
            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, veinMat, true));
            if (!full) return g;

            // Longitudinal veins as functions f(u) over [u0,u1]
            const s = (u, a) => smooth(a, a + 0.28, u);
            const R1 = u => 0.15 - 0.1 * u * u;
            const veins = [
                { u0: 0,    u1: 0.58, f: u => 0.07 * (1 - Math.pow(u / 0.58, 3)) },   // subcosta
                { u0: 0,    u1: 0.99, f: R1 },                                           // radius
                { u0: 0.26, u1: 1,    f: u => R1(u) + 0.12 * s(u, 0.26) },              // radial sector
                { u0: 0.42, u1: 1,    f: u => R1(u) + 0.25 * s(u, 0.42) },
                { u0: 0,    u1: 1,    f: u => 0.48 + 0.04 * u },                         // media
                { u0: 0.5,  u1: 1,    f: u => 0.52 + 0.16 * s(u, 0.5) },
                { u0: 0,    u1: 0.96, f: u => 0.74 - 0.02 * u },                         // cubitus
                { u0: 0.08, u1: 0.8,  f: u => 0.74 + 0.2 * s(u, 0.08) },
                { u0: 0,    u1: fore ? 0.42 : 0.5, f: u => 0.86 + 0.14 * Math.pow(u / (fore ? 0.42 : 0.5), 1.5) }, // anal
            ];
            const vp = [];
            veins.forEach(v => {
                let prev = null;
                for (let k = 0; k <= 24; k++) {
                    const u = v.u0 + (v.u1 - v.u0) * k / 24;
                    const p = P(u, v.f(u));
                    if (prev) vp.push(prev.x, prev.y, prev.z, p.x, p.y, p.z);
                    prev = p;
                }
            });
            // Crossveins between neighbouring longitudinal veins
            const tracks = [{ u0: 0, u1: 1, f: () => 0 }, ...veins, { u0: 0, u1: 1, f: () => 1 }];
            for (let u = 0.06; u < 0.97; u += 0.032) {
                const here = tracks.filter(v => u >= v.u0 && u <= v.u1).map(v => v.f(u)).sort((a, b) => a - b);
                for (let k = 0; k < here.length - 1; k++) {
                    if (here[k + 1] - here[k] < 0.03 || rand() > 0.5) continue;
                    const uj = u + (rand() - 0.5) * 0.02;
                    const a = P(uj, here[k]), b = P(uj + (rand() - 0.5) * 0.015, here[k + 1]);
                    vp.push(a.x, a.y, a.z, b.x, b.y, b.z);
                }
            }
            // Pterostigma: a hatched cell near the leading-edge tip
            for (let k = 0; k <= 7; k++) {
                const u = 0.74 + k * 0.016;
                const a = P(u, 0), b = P(u + 0.01, R1(u));
                vp.push(a.x, a.y, a.z, b.x, b.y, b.z);
            }
            g.add(lineSegs(vp, veinMat));

            // Costa: a thick leading-edge spar
            const cpts = [];
            for (let k = 0; k <= 20; k++) cpts.push(P(k / 20 * 0.98, 0));
            g.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(cpts), 30, 0.007, 4, false), mat(colors.primary)));
            return g;
        }

        function buildWings(g) {
            membraneMat = new THREE.MeshBasicMaterial({ color: colors.light, wireframe: true, transparent: true, opacity: 0.14 });
            const veinMat = new THREE.LineBasicMaterial({ color: colors.primary, transparent: true, opacity: 0.95 });
            ghostMats = [1, 2].map(() => ({
                membrane: new THREE.MeshBasicMaterial({ color: colors.light, wireframe: true, transparent: true, opacity: 0 }),
                vein: new THREE.LineBasicMaterial({ color: colors.light, transparent: true, opacity: 0 }),
            }));

            const defs = [
                { fore: true,  pos: [0.24, 0.32, 0.76], len: 1.85, wid: 0.5,  sweep: 0.52, dihedral: 0.1  },
                { fore: false, pos: [0.22, 0.27, 0.46], len: 1.55, wid: 0.52, sweep: 0.72, dihedral: 0.04 },
            ];
            defs.forEach(d => {
                [-1, 1].forEach(side => {
                    const root = new THREE.Group();
                    root.position.set(side * d.pos[0], d.pos[1], d.pos[2]);
                    // Tegula / wing-base sclerite
                    root.add(ball(0.035, colors.light, 0, 0, 0.02, 1, 0.6, 1.3, 10, 8));
                    const yaw = new THREE.Group();
                    root.add(yaw);
                    const strokes = [], pitches = [];
                    for (let k = 0; k < 3; k++) {
                        const st = new THREE.Group(), pt = new THREE.Group();
                        st.add(pt);
                        yaw.add(st);
                        const m = k === 0 ? { membrane: membraneMat, vein: veinMat } : ghostMats[k - 1];
                        pt.add(makeWing(d.len, d.wid, d.fore, side, m.membrane, m.vein, k === 0));
                        strokes.push(st); pitches.push(pt);
                    }
                    g.add(root);
                    wings.push({ side, fore: d.fore, yaw, strokes, pitches, sweep: d.sweep, dihedral: d.dihedral });
                });
            });
        }

        function createInsect() {
            const root = new THREE.Group();
            body = new THREE.Group();
            body.position.z = 0.55;     // spin about the middle of the body, not the thorax
            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.4, 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);

        // ── Camera: distance chosen so the whole insect fits any aspect ratio ──
        let camDist = 5, camEl = 0.38;
        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(10, Math.max(4.8, 2.9 / (tf * aspect), 1.9 / 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();

            insect = createInsect();
            scene.add(insect);

            animate();
        }

        const _col = new THREE.Color(), _c1 = new THREE.Color(colors.light), _c2 = new THREE.Color(colors.primary);

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

            if (!dragging) {
                userSpin += spinVel;
                spinVel *= 0.95;
                pitch *= 0.97;
            }
            const el = camEl + pitch;
            camera.position.set(0, Math.sin(el) * camDist, Math.cos(el) * camDist);
            camera.lookAt(0, -0.05, 0);

            // Behaviour cycle (20 s): idle → grooming → idle → wing-buzz warm-up
            const cyc = (t / 1000) % 20;
            const groom = smooth(7, 8, cyc) * (1 - smooth(11, 12, cyc));
            const buzz  = smooth(14, 14.6, cyc) * (1 - smooth(18, 18.8, cyc));
            const idle  = 1 - Math.max(groom, buzz);

            insect.rotation.y = userSpin + t * 0.0003;
            insect.position.y = Math.sin(t * 0.0015) * 0.08 + buzz * 0.14;
            insect.rotation.x = Math.sin(t * 0.001) * 0.04 - buzz * 0.07 + groom * 0.05;
            insect.rotation.z = Math.sin(t * 0.0018) * 0.015 + buzz * Math.sin(t * 0.03) * 0.006;

            // Head looks around; dips while grooming
            head.rotation.y = Math.sin(t * 0.0005) * 0.22 * idle + Math.sin(t * 0.0013) * 0.05;
            head.rotation.x = groom * 0.28 + Math.sin(t * 0.0009) * 0.04;
            head.rotation.z = Math.sin(t * 0.0007) * 0.06 * idle;

            // Proboscis dabs now and then, and during grooming
            const dab = Math.pow(Math.max(0, Math.sin(t * 0.0011)), 10) * 0.5 + groom * 0.35 * (0.5 + 0.5 * Math.sin(t * 0.012));
            proboscis.joints[0].rotation.z = proboscis.rest[0] + dab * 0.5 - buzz * 0.3;
            proboscis.joints[1].rotation.z = proboscis.rest[1] - dab * 0.6 + buzz * 0.5;

            // Antennae feeling the air, waves running down the flagellum
            for (const A of antennae) {
                A.root.rotation.y = yawFor(A.side, 0.5 + Math.sin(t * 0.0026 + A.side) * 0.12 + groom * 0.25);
                A.joints[0].rotation.z = A.rest[0] + Math.sin(t * 0.0031 + A.side * 0.5) * 0.1 - buzz * 0.35;
                for (let i = 2; i < A.joints.length; i++)
                    A.joints[i].rotation.z = A.rest[i] + Math.sin(t * 0.004 - i * 0.45 + A.side) * 0.035;
            }

            // Abdomen: travelling curl + telescoping breath, tail lifts in flight
            for (const S of abdomen) {
                S.joint.rotation.z = S.rest + Math.sin(t * 0.0016 - S.i * 0.4) * 0.012 + buzz * 0.022 + groom * 0.01;
                const br = 1 + Math.sin(t * 0.0042 - S.i * 0.5) * 0.03 * (S.i > 0 && S.i < 8 ? 1 : 0.3);
                S.mesh.scale.set(1, br, br);
            }
            for (const C of cerci) {
                C.joints.forEach((j, i) => {
                    j.rotation.z = C.rest[i] + Math.sin(t * 0.003 - i * 0.5) * 0.04;
                    j.rotation.y = Math.sin(t * 0.0023 - i * 0.4 + C.side) * 0.05;
                });
            }

            // Legs: tripod tread at rest; front legs rub while grooming; all tuck for the buzz
            for (const L of legs) {
                const j = L.joints, x = t * 0.0035 + L.phase;
                let fa = L.fa + Math.cos(x) * 0.05 * idle;
                const a = L.rest.slice();
                a[2] += Math.sin(x) * 0.07 * idle;
                a[3] -= Math.max(0, Math.sin(x)) * 0.12 * idle;

                if (L.pair === 0 && groom > 0) {
                    const rub = Math.sin(t * 0.018 + (L.side > 0 ? 0 : Math.PI));
                    fa += groom * (-0.45 + rub * 0.12);
                    a[2] += groom * 0.4;
                    a[3] += groom * (0.55 + rub * 0.22);
                    a[4] -= groom * 0.3;
                }
                if (buzz > 0) {
                    a[2] += buzz * 0.45;
                    a[3] -= buzz * 0.45;
                    for (let k = 4; k < a.length; k++) a[k] -= buzz * 0.12;
                    if (L.pair === 2) fa += buzz * 0.3;
                }
                for (let k = 0; k < a.length; k++) j[k].rotation.z = a[k];
                L.root.rotation.y = yawFor(L.side, fa);
            }

            // Wings: rest tremor, then sweep forward and beat with motion-blur ghosts
            for (const W of wings) {
                const tremor = Math.sin(t * 0.005 + (W.fore ? 0 : 0.9)) * 0.03 + Math.sin(t * 0.021) * 0.008;
                W.yaw.rotation.y = W.side * (W.sweep * (1 - buzz * 0.85) + tremor * 0.3);
                for (let k = 0; k < 3; k++) {
                    const ph = (t - k * 14) * 0.055 + (W.fore ? 0 : 0.7);
                    const stroke = W.dihedral + tremor + buzz * (0.35 + 0.7 * Math.sin(ph));
                    W.strokes[k].rotation.z = W.side * stroke;
                    W.pitches[k].rotation.x = buzz * 0.45 * Math.cos(ph) + Math.sin(t * 0.005 + (W.fore ? 0.4 : 1.3)) * 0.02;
                    W.strokes[k].visible = k === 0 || buzz > 0.02;
                }
            }
            ghostMats[0].membrane.opacity = buzz * 0.08; ghostMats[0].vein.opacity = buzz * 0.35;
            ghostMats[1].membrane.opacity = buzz * 0.04; ghostMats[1].vein.opacity = buzz * 0.18;

            // Faint iridescent shimmer across the membranes
            _col.copy(_c1).lerp(_c2, 0.5 + 0.5 * Math.sin(t * 0.0013));
            membraneMat.color.copy(_col);

            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.