• 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 BUTTERFLY 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 — Butterfly</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, butterfly, body, head;
        const antennae = [], wings = [], legs = [], abdomen = [], proboscis = {};

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

        // ═════════════════════════ WINGS ═════════════════════════
        // Your outlines, kept as the wing shapes (+x out, +y toward the head).
        // Everything else is built in shape-space and laid flat in XZ:
        //  • scale rows — concentric contours from the wing root, coloured by
        //    a pattern function so the bands and dark margins are in the scales
        //  • veins from a closed discal cell, snapped to the margin
        //  • marginal lunules between vein ends, eyespots, and a checkered fringe
        function foreOutline(s) {
            const sh = new THREE.Shape();
            sh.moveTo(0, 0);
            sh.bezierCurveTo(s*0.7, 0.55, s*1.5, 0.95, s*2.15, 1.05);
            sh.quadraticCurveTo(s*2.13,  0.83, s*1.95,  0.55);
            sh.quadraticCurveTo(s*1.93,  0.36, s*1.75,  0.12);
            sh.quadraticCurveTo(s*1.73, -0.05, s*1.55, -0.25);
            sh.quadraticCurveTo(s*1.53, -0.42, s*1.35, -0.55);
            sh.bezierCurveTo(s*0.8, -0.5, s*0.3, -0.2, 0, 0);
            return sh.getSpacedPoints(160);
        }
        function hindOutline(s) {
            const sh = new THREE.Shape();
            sh.moveTo(0, 0);
            sh.bezierCurveTo(s*0.6, 0.08, s*1.2, 0.05, s*1.6, -0.15);
            sh.quadraticCurveTo(s*1.72, -0.32, s*1.58, -0.52);
            sh.quadraticCurveTo(s*1.62, -0.70, s*1.42, -0.85);
            sh.quadraticCurveTo(s*1.44, -1.00, s*1.18, -1.05);
            sh.bezierCurveTo(s*1.06, -1.12, s*1.02, -1.30, s*0.92, -1.44);
            sh.quadraticCurveTo(s*0.85, -1.26, s*0.76, -1.10);
            sh.bezierCurveTo(s*0.4, -0.95, s*0.15, -0.5, 0, 0);
            return sh.getSpacedPoints(150);
        }
        const W3 = (x, y, lift = 0) => V(x, lift, y);   // shape-space → wing plane (y → +Z forward)

        function wingPattern(fore, s, x, y) {
            // Returns a colour for a scale at radial fraction s (0 root → 1 margin)
            const C = colors;
            if (s < 0.22) return C.mid;                                   // dark, hairy wing base
            if (fore) {
                if (s > 0.55 && s < 0.66) return C.light;                 // postdiscal pale band
                if (s > 0.78 && s < 0.9)  return C.mid;                   // dark submarginal band
                if (s >= 0.9) return C.primary;
            } else {
                if (s > 0.4 && s < 0.58) return C.light;                  // broad pale hindwing band
                if (s > 0.74 && s < 0.88) return C.mid;
                if (s >= 0.88) return C.primary;
            }
            return C.primary;
        }

        function makeWing(fore, side) {
            const s = side;
            const g = new THREE.Group();
            const out = fore ? foreOutline(s) : hindOutline(s);
            const N = out.length;

            // Scale rows (contours) with per-vertex pattern colour
            const pos = [], col = [], c = new THREE.Color();
            const pushSeg = (a, b, hex) => {
                pos.push(a.x, a.y, a.z, b.x, b.y, b.z);
                c.setHex(hex); col.push(c.r, c.g, c.b, c.r, c.g, c.b);
            };
            for (let k = 1; k <= 30; k++) {
                const f = k / 30;
                for (let i = 0; i < N - 1; i++) {
                    const p = out[i], q = out[i + 1];
                    if (p.lengthSq() < 0.01 || q.lengthSq() < 0.01) continue;
                    const a = W3(p.x * f, p.y * f), b = W3(q.x * f, q.y * f);
                    pushSeg(a, b, wingPattern(fore, s, p.x * f, p.y * f));
                }
            }
            // Faint radial scale lines
            for (let i = 0; i < N; i += 3) {
                const p = out[i];
                if (p.lengthSq() < 0.02) continue;
                for (let k = 0; k < 10; k++) {
                    const f0 = k / 10, f1 = (k + 1) / 10;
                    pushSeg(W3(p.x * f0, p.y * f0), W3(p.x * f1, p.y * f1), wingPattern(fore, s, p.x * f1, p.y * f1));
                }
            }
            const sg = new THREE.BufferGeometry();
            sg.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
            sg.setAttribute('color', new THREE.Float32BufferAttribute(col, 3));
            g.add(new THREE.LineSegments(sg, new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.55 })));

            // Margin
            g.add(polyline(out.map(p => W3(p.x, p.y, 0.002)), lmat(colors.light, 1), true));

            // Snap a target to the nearest margin point
            const snap = (tx, ty) => {
                let best = null, bd = 1e9;
                out.forEach(p => { const d = (p.x - s * tx) ** 2 + (p.y - ty) ** 2; if (d < bd) { bd = d; best = p; } });
                return best;
            };
            // Veins: discal cell + radiating veins, as lines; the costa as a spar
            const vp = [], ends = [];
            const vein = (pts, toMargin) => {
                const v3 = pts.map(([x, y]) => new THREE.Vector3(s * x, y, 0));
                if (toMargin) { const m = snap(pts[pts.length - 1][0], pts[pts.length - 1][1]); v3[v3.length - 1] = V(m.x, m.y, 0); ends.push(m); }
                const cv = new THREE.CatmullRomCurve3(v3);
                const P = cv.getPoints(16);
                for (let i = 0; i < P.length - 1; i++)
                    vp.push(P[i].x, 0.004, P[i].y, P[i + 1].x, 0.004, P[i + 1].y);
            };
            if (fore) {
                vein([[0.12, 0.05], [0.6, 0.3], [1.05, 0.34]]);           // cell, upper edge
                vein([[0.12, -0.02], [0.6, 0.0], [1.0, 0.06]]);           // cell, lower edge
                vein([[1.05, 0.34], [1.03, 0.2], [1.0, 0.06]]);           // discocellular
                vein([[0.45, 0.24], [0.9, 0.5], [1.3, 0.75]], true);      // R1
                vein([[0.85, 0.33], [1.3, 0.64], [1.75, 0.95]], true);    // R2
                vein([[1.0, 0.34], [1.6, 0.8], [2.12, 1.02]], true);      // R3
                vein([[1.05, 0.34], [1.6, 0.66], [2.08, 0.82]], true);    // R4
                vein([[1.05, 0.3], [1.55, 0.5], [2.0, 0.65]], true);      // R5
                vein([[1.04, 0.24], [1.5, 0.36], [1.94, 0.45]], true);    // M1
                vein([[1.03, 0.15], [1.45, 0.16], [1.82, 0.22]], true);   // M2
                vein([[1.0, 0.06], [1.35, 0.0], [1.7, -0.02]], true);     // M3
                vein([[0.86, 0.05], [1.2, -0.1], [1.56, -0.24]], true);   // Cu1
                vein([[0.6, 0.02], [1.0, -0.2], [1.4, -0.48]], true);     // Cu2
                vein([[0.1, -0.04], [0.6, -0.3], [1.1, -0.52]], true);    // 2A
            } else {
                vein([[0.1, -0.05], [0.55, -0.18], [0.85, -0.35]]);       // cell, upper edge
                vein([[0.1, -0.12], [0.45, -0.38], [0.7, -0.56]]);        // cell, lower edge
                vein([[0.85, -0.35], [0.78, -0.46], [0.7, -0.56]]);       // discocellular
                vein([[0.1, 0.0], [0.9, 0.0], [1.55, -0.13]], true);      // Sc+R1
                vein([[0.85, -0.35], [1.25, -0.36], [1.66, -0.38]], true);// Rs
                vein([[0.84, -0.4], [1.2, -0.52], [1.6, -0.62]], true);   // M1
                vein([[0.8, -0.46], [1.1, -0.66], [1.43, -0.88]], true);  // M2
                vein([[0.75, -0.52], [0.86, -0.95], [0.92, -1.44]], true);// M3 into the tail
                vein([[0.7, -0.56], [0.95, -0.8], [1.18, -1.05]], true);  // Cu1
                vein([[0.55, -0.48], [0.68, -0.8], [0.8, -1.1]], true);   // Cu2
                vein([[0.08, -0.15], [0.35, -0.6], [0.62, -0.98]], true); // 2A
            }
            g.add(lineSegs(vp, lmat(colors.light, 0.95)));
            const costa = out.slice(0, fore ? 62 : 52).map(p => V(p.x, 0.004, p.y));
            g.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(costa), 40, 0.012, 4, false), mat(colors.light)));

            // Marginal lunules: pale crescents between adjacent vein ends
            ends.sort((a, b) => out.indexOf(a) - out.indexOf(b));
            const lu = [];
            for (let i = 0; i < ends.length - 1; i++) {
                const a = ends[i], b = ends[i + 1];
                const m = a.clone().add(b).multiplyScalar(0.5);
                const ctr = m.clone().multiplyScalar(0.91);
                const w = a.distanceTo(b) * 0.32;
                if (w < 0.03) continue;
                const tang = b.clone().sub(a).normalize(), nrm = ctr.clone().normalize();
                let prev = null;
                for (let k = 0; k <= 10; k++) {
                    const u = -1 + 2 * k / 10;
                    const p = ctr.clone().addScaledVector(tang, u * w).addScaledVector(nrm, -(1 - u * u) * w * 0.45);
                    const p3 = V(p.x, 0.006, p.y);
                    if (prev) lu.push(prev.x, prev.y, prev.z, p3.x, p3.y, p3.z);
                    prev = p3;
                }
            }
            g.add(lineSegs(lu, lmat(colors.light, 0.95)));

            // Checkered fringe (cilia) along the outer margin
            const fr = [], fc = [];
            for (let i = 1; i < N - 1; i++) {
                const p = out[i];
                if (p.length() < 0.9) continue;
                const tng = out[i + 1].clone().sub(out[i - 1]).normalize();
                let n = V(tng.y, -tng.x, 0);
                if (n.dot(p) < 0) n.negate();
                const L = 0.035 + 0.01 * Math.sin(i);
                fr.push(p.x, 0, p.y, p.x + n.x * L, 0, p.y + n.y * L);
                c.setHex(Math.floor(i / 4) % 2 ? colors.light : colors.mid);
                fc.push(c.r, c.g, c.b, c.r, c.g, c.b);
            }
            const fg = new THREE.BufferGeometry();
            fg.setAttribute('position', new THREE.Float32BufferAttribute(fr, 3));
            fg.setAttribute('color', new THREE.Float32BufferAttribute(fc, 3));
            g.add(new THREE.LineSegments(fg, new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.7 })));

            // Eyespots: concentric rings, pupil, and a crescent highlight
            const eyespot = (x, y, r) => {
                const e = new THREE.Group();
                e.position.set(s * x, 0.008, y);
                [[1.0, colors.mid], [0.78, colors.light], [0.56, colors.primary], [0.34, colors.light]].forEach(([k, cc]) => {
                    const tg = new THREE.TorusGeometry(r * k, r * 0.06, 3, 24).rotateX(Math.PI / 2);
                    e.add(new THREE.Mesh(tg, mat(cc)));
                });
                const pupil = new THREE.Mesh(new THREE.CircleGeometry(r * 0.2, 10).rotateX(-Math.PI / 2), mat(colors.light));
                e.add(pupil);
                const hl = [];
                for (let k = 0; k <= 8; k++) { const a = -0.6 + k / 8 * 1.2 + Math.PI * 0.75; hl.push(V(Math.cos(a) * r * 0.45, 0.002, Math.sin(a) * r * 0.45)); }
                e.add(polyline(hl, lmat(colors.light, 1)));
                g.add(e);
            };
            if (fore) { eyespot(1.62, 0.48, 0.16); eyespot(1.68, 0.02, 0.09); }
            else      { eyespot(1.18, -0.62, 0.13); eyespot(0.85, -0.92, 0.1); }

            // Hair over the wing base
            const hb = [];
            for (let i = 0; i < 90; i++) {
                const a = rand(), f = rand() * 0.22;
                const p = out[Math.floor(a * (N - 1))];
                const x = p.x * f, y = p.y * f, L = 0.04 + rand() * 0.05;
                hb.push(x, 0.004, y, x + s * L * 0.8, 0.02, y - L * 0.4);
            }
            g.add(lineSegs(hb, lmat(colors.light, 0.5)));
            return g;
        }

        function buildWings(g) {
            [[true, 0.2], [false, 0.04]].forEach(([fore, z]) => [-1, 1].forEach(side => {
                const pivot = new THREE.Group();
                pivot.position.set(side * 0.07, 0.1, z);
                const pitchG = new THREE.Group();
                pivot.add(pitchG);
                pitchG.add(makeWing(fore, side));
                g.add(pivot);
                wings.push({ side, fore, pivot, pitchG });
            }));
            // Tegulae: scale tufts over the wing bases
            [-1, 1].forEach(s => {
                const tf = [];
                for (let i = 0; i < 40; i++) {
                    const x = s * (0.06 + rand() * 0.05), z = 0.18 + rand() * 0.12;
                    tf.push(x, 0.15, z, x + s * 0.06, 0.17 + rand() * 0.03, z - 0.08);
                }
                g.add(lineSegs(tf, lmat(colors.light, 0.65)));
            });
        }

        // ═════════════════════════ HEAD ═════════════════════════
        const R_HEAD = V(0.11, 0.11, 0.1);
        const R_EYE  = V(0.075, 0.09, 0.085);

        function compoundEye(side) {
            const g = new THREE.Group();
            g.add(ellipsoid(R_EYE, colors.mid, 14, 12));
            const out = V(side * 0.9, 0.15, 0.4).normalize();
            const N = 700, 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.0) 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.002);
                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.07, 0.01, 0.02);
            return g;
        }

        // Clubbed antenna: slender ringed shaft swelling into a club
        function buildAntenna(side) {
            const defs = [];
            for (let i = 0; i < 24; i++) {
                const club = Math.max(0, (i - 17) / 6);
                const r = 0.008 + club * 0.018 - (i === 23 ? 0.01 : 0);
                defs.push({ len: 0.034, r0: r * 0.95, rm: r * 1.1, r1: r, color: i % 2 ? colors.light : colors.mid,
                            angle: i === 0 ? 0.95 : i > 17 ? -0.05 : -0.012, radial: 6, knuckle: false });
            }
            const ch = buildChain(defs);
            ch.root.position.set(side * 0.03, 0.09, 0.06);
            ch.root.rotation.y = yawFor(side, 0.35);
            antennae.push({ side, root: ch.root, joints: ch.joints, rest: defs.map(d => d.angle) });
            return ch.root;
        }

        // Proboscis: a coiled tube rebuilt each frame from a curvature
        // profile, so it can unroll smoothly when the butterfly feeds
        const PROB_N = 70, PROB_LEN = 0.75;
        function buildProboscis(h) {
            const geo = new THREE.BufferGeometry();
            geo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(PROB_N * 3), 3));
            [-1, 1].forEach(s => {     // two interlocked galeae
                const l = new THREE.Line(geo, lmat(colors.light, 0.95));
                l.position.x = s * 0.004;
                l.frustumCulled = false;
                h.add(l);
            });
            proboscis.geo = geo;
        }
        function updateProboscis(coil, probe, t) {
            const a = proboscis.geo.attributes.position.array;
            let y = -0.09, z = 0.08, th = -1.0 - (1 - coil) * 0.35 + Math.sin(t * 0.004) * 0.08 * probe;
            const ds = PROB_LEN / PROB_N;
            for (let i = 0; i < PROB_N; i++) {
                a[i * 3] = 0; a[i * 3 + 1] = y; a[i * 3 + 2] = z;
                th -= coil * (0.03 + i * 0.0042) + (1 - coil) * Math.sin(i * 0.3 + t * 0.006) * 0.006 * probe;
                y += Math.sin(th) * ds; z += Math.cos(th) * ds;
            }
            proboscis.geo.attributes.position.needsUpdate = true;
        }

        function buildHead() {
            head = new THREE.Group();
            head.position.set(0, 0.05, 0.47);   // pivot at the neck
            const h = new THREE.Group();
            h.position.z = 0.1;
            head.add(h);
            h.add(ellipsoid(R_HEAD, colors.primary, 18, 14));
            h.add(compoundEye(-1));
            h.add(compoundEye(1));
            h.add(hairField(R_HEAD, 140, 0.02, 0.045, V(0, 0.3, -0.4), colors.light, 0.55, n => n.y > 0.1));

            // Labial palps: hairy, scaled, upturned in front of the face
            [-1, 1].forEach(s => {
                const ch = buildChain([
                    { len: .05, r0: .014, rm: .016, r1: .014, color: colors.mid, angle: -0.6, radial: 6, hairs: 14 },
                    { len: .07, r0: .016, rm: .019, r1: .014, color: colors.primary, angle: 1.0, radial: 6, hairs: 20 },
                    { len: .04, r0: .012, rm: .012, r1: .006, color: colors.light, angle: 0.3, radial: 6, hairs: 6 },
                ]);
                ch.root.position.set(s * 0.025, -0.06, 0.08);
                ch.root.rotation.y = yawFor(s, 0.15);
                h.add(ch.root);
            });
            h.add(buildAntenna(-1));
            h.add(buildAntenna(1));
            buildProboscis(h);
            return head;
        }

        // ═════════════════════════ THORAX & ABDOMEN ═════════════════════════
        function buildThorax(g) {
            const C = V(0, 0.04, 0.26), R = V(0.14, 0.14, 0.22);
            const th = new THREE.Group(); th.position.copy(C);
            th.add(ellipsoid(R, colors.primary, 20, 14));
            th.add(hairField(R, 500, 0.04, 0.08, V(0, 0.2, -0.5), colors.light, 0.5, n => n.y > -0.3));
            th.add(hairField(R, 260, 0.03, 0.06, V(0, -0.2, -0.3), colors.primary, 0.45, n => n.y <= -0.3));
            // Patagia: collar lappets behind the head
            [-1, 1].forEach(s => th.add(ball(0.05, colors.light, s * 0.05, 0.08, 0.18, 1, 0.5, 0.8, 10, 8)));
            g.add(th);
        }

        function buildAbdomen(g) {
            const N = 7, defs = [];
            for (let i = 0; i < N; i++) {
                const r = 0.075 - i * 0.005;
                defs.push({ len: 0.16, r0: r * 0.92, rm: r * 1.05, r1: r * 0.9, color: i % 2 ? colors.mid : colors.primary,
                            angle: i === 0 ? -0.1 : -0.05, radial: 10, knuckle: false, hairs: 40,
                            extra: (j, d) => {
                                j.add(ring(d.r0 * 1.04, colors.light, 0.06));
                                // Pale lateral stripe of scales
                                [-1, 1].forEach(sd => {
                                    const st = [];
                                    for (let k = 0; k <= 6; k++) { const u = k / 6, r = qb(d.r0, d.rm, d.r1, u) * 1.03; st.push(V(u * d.len, -r * 0.2, sd * r)); }
                                    j.add(polyline(st, lmat(colors.light, 0.7)));
                                });
                            } });
            }
            const ch = buildChain(defs);
            [-1, 1].forEach(s => ch.joints[N - 1].add(ball(0.018, colors.light, defs[N - 1].len + 0.015, -0.01, s * 0.018, 1.6, 0.6, 0.8, 8, 6)));  // claspers
            ch.root.position.set(0, 0.0, 0.05);
            ch.root.rotation.y = Math.PI / 2;
            g.add(ch.root);
            ch.joints.forEach((j, i) => abdomen.push({ joint: j, rest: defs[i].angle, i }));
        }

        // ═════════════════════════ LEGS ═════════════════════════
        // Tucked up during flight, reaching down to grip while perched
        const LEG_TUCK  = [-0.9, 0.1, 1.15, -2.3, -0.35, -0.1, -0.1, -0.1, -0.1];
        const LEG_PERCH = [-0.55, 0.1, 0.45, -1.25, -0.3, -0.1, -0.08, -0.06, -0.05];
        function addClaws(j, d) {
            [-1, 1].forEach(s => {
                const c = new THREE.QuadraticBezierCurve3(V(d.len, 0, s * 0.003), V(d.len + 0.015, 0.003, s * 0.007), V(d.len + 0.02, -0.014, s * 0.01));
                j.add(new THREE.Mesh(new THREE.TubeGeometry(c, 4, 0.0025, 3, false), mat(colors.light)));
            });
        }
        function buildLegs(g) {
            const pairs = [
                { attachZ: 0.36, fanAngle: Math.PI * 0.3, scale: 0.9 },
                { attachZ: 0.25, fanAngle: Math.PI * 0.5, scale: 1.0 },
                { attachZ: 0.13, fanAngle: Math.PI * 0.7, scale: 1.05 },
            ];
            pairs.forEach((pair, pi) => [-1, 1].forEach(side => {
                const sc = pair.scale;
                const L = [.06, .03, .2, .2, .05, .035, .03, .025, .025];
                const R = [.02, .016, .014, .011, .007, .0065, .006, .0055, .005];
                const defs = L.map((len, i) => ({
                    len: len * sc, r0: R[i], rm: R[i] * 1.1, r1: R[i] * 0.9,
                    color: i < 2 ? colors.mid : i % 2 ? colors.primary : colors.light,
                    angle: LEG_TUCK[i], radial: i < 4 ? 6 : 4, knuckle: i < 4,
                    hairs: i === 2 ? 14 : i === 3 ? 10 : 0, spines: i === 3 ? 4 : i >= 4 ? 2 : 0,
                    extra: i === 8 ? addClaws : null,
                }));
                const ch = buildChain(defs);
                ch.root.position.set(side * 0.07, -0.08, pair.attachZ);
                ch.root.rotation.y = yawFor(side, pair.fanAngle);
                g.add(ch.root);
                legs.push({ root: ch.root, joints: ch.joints, side, pair: pi, fa: pair.fanAngle,
                            phase: ((pi + (side > 0 ? 0 : 1)) % 2) * Math.PI + pi * 0.3 });
            }));
        }

        function createButterfly() {
            const root = new THREE.Group();
            body = new THREE.Group();
            body.position.z = 0.2;
            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.7, 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 full wingspan fits any aspect ratio ──
        let camDist = 5, camEl = 0.42;
        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.5 / (tf * aspect), 2.1 / 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();

            butterfly = createButterfly();
            scene.add(butterfly);

            animate();
        }

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

            if (!dragging) {
                userSpin += spinVel;
                spinVel *= 0.95;
                pitch *= 0.97;
            }
            // Behaviour cycle (20 s): flapping flight → glide → flight → perch
            // (wings close overhead, bask open and shut, proboscis unrolls)
            const cyc = (t / 1000) % 20;
            const perch = smooth(12, 13, cyc) * (1 - smooth(18.6, 19.6, cyc));

            // Camera drifts up and back a little while the wings stand closed overhead
            const el = camEl + pitch;
            const d = camDist * (1 + perch * 0.12);
            camera.position.set(0, Math.sin(el) * d + perch * 0.5, Math.cos(el) * d);
            camera.lookAt(0, 0.25 + perch * 0.75, 0);
            const glide = smooth(6.4, 7, cyc) * (1 - smooth(8.4, 9, cyc)) * (1 - perch);
            const fly = 1 - Math.max(perch, glide);
            const probe = smooth(13.5, 14.5, cyc) * (1 - smooth(17.5, 18.5, cyc));

            // Slow, deep wingbeat
            const beat = t * 0.0055;
            const flap = Math.sin(beat) * 0.85 - 0.1;
            const flapHind = Math.sin(beat - 0.35) * 0.7 - 0.08;
            const bask = Math.pow(Math.max(0, Math.sin(t * 0.0011)), 2);
            for (const W of wings) {
                const flying = W.fore ? flap : flapHind;
                const gl = 0.32 + Math.sin(t * 0.004) * 0.02;
                const closed = (W.fore ? 1.48 : 1.4) - bask * 1.1;
                const a = flying * fly + gl * glide + closed * perch;
                W.pivot.rotation.z = W.side * a;
                // Wings sweep forward a touch on the downstroke, and twist
                W.pivot.rotation.y = W.side * (Math.cos(beat) * 0.06 * fly - (W.fore ? 0 : 0.05));
                W.pitchG.rotation.x = Math.cos(beat + 0.4) * 0.12 * fly;
            }

            // Flight coupled to the wingbeat; perched still
            butterfly.rotation.y = userSpin + t * 0.0003;
            butterfly.position.y = (Math.sin(beat + 1.2) * 0.1 + Math.sin(t * 0.0009) * 0.15) * fly
                                 + Math.sin(t * 0.0012) * 0.04 * glide;
            body.rotation.x = Math.sin(beat + 0.8) * 0.06 * fly - glide * 0.05 + perch * 0.05;
            body.rotation.z = Math.sin(t * 0.0013) * 0.03 * (1 - perch);

            head.rotation.x = probe * 0.15 + Math.sin(t * 0.0011) * 0.03;
            head.rotation.y = Math.sin(t * 0.0007) * 0.1;
            updateProboscis(1 - probe * 0.92, probe, t);

            for (const A of antennae) {
                A.root.rotation.y = yawFor(A.side, 0.35 + Math.sin(t * 0.0026 + A.side) * 0.08);
                A.joints[0].rotation.z = A.rest[0] + Math.sin(t * 0.0031 + A.side) * 0.05 - fly * Math.sin(beat) * 0.03;
                for (let i = 1; i < A.joints.length; i++)
                    A.joints[i].rotation.z = A.rest[i] + Math.sin(t * 0.004 - i * 0.3 + A.side) * 0.006;
            }

            // Abdomen flexes against the beat
            for (const S of abdomen)
                S.joint.rotation.z = S.rest + Math.sin(beat + Math.PI * 0.7 - S.i * 0.3) * 0.025 * fly + perch * 0.02;

            // Legs: tucked in flight, reaching down when perched
            for (const L of legs) {
                const x = t * 0.0016 + L.phase;
                for (let k = 0; k < L.joints.length; k++) {
                    const a = LEG_TUCK[k] + (LEG_PERCH[k] - LEG_TUCK[k]) * perch;
                    L.joints[k].rotation.z = a + (k === 2 ? Math.sin(x) * 0.04 : k === 3 ? Math.sin(x + 1) * 0.04 : 0);
                }
                L.root.rotation.y = yawFor(L.side, L.fa + Math.cos(x) * 0.03);
            }

            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.