BUMBLEBEE SOURCE CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ThreeJS: Bumblebee</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; }
html, body { height: 100%; overflow: hidden; background: radial-gradient(ellipse at 50% 42%, #2a1c10 0%, #140d07 55%, #050302 100%); }
#c { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; }
#c:active { cursor: grabbing; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<script>
{
"use strict";
if (typeof THREE === 'undefined') throw new Error('three missing');
const T = THREE, TAU = Math.PI*2;
const V3 = (x=0,y=0,z=0) => new T.Vector3(x,y,z);
const clamp = (x,a,b) => Math.max(a, Math.min(b, x));
const lerp = (a,b,t) => a + (b-a)*t;
const smooth = t => { t = clamp(t,0,1); return t*t*(3-2*t); };
let seed = 2468;
const rnd = () => (seed = (seed*16807) % 2147483647, (seed-1)/2147483646);
const rr = (a,b) => a + (b-a)*rnd();
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const UP = V3(0,1,0), DS = T.DoubleSide;
const lin = h => new T.Color(h).convertSRGBToLinear();
/* =====================================================================
RENDERER / SCENE
===================================================================== */
const canvas = document.getElementById('c');
const renderer = new T.WebGLRenderer({ canvas, antialias:true, alpha:true, powerPreference:'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputEncoding = T.sRGBEncoding;
renderer.toneMapping = T.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = T.PCFSoftShadowMap;
const ANISO = renderer.capabilities.getMaxAnisotropy();
const scene = new T.Scene();
scene.fog = new T.FogExp2(0x120b06, 0.05);
const camera = new T.PerspectiveCamera(42, innerWidth/innerHeight, 0.03, 200);
(function(){
const c=document.createElement('canvas'); c.width=1024; c.height=512; const x=c.getContext('2d');
const g=x.createLinearGradient(0,0,0,512); g.addColorStop(0,'#3a4a70'); g.addColorStop(.35,'#1a2440'); g.addColorStop(.5,'#0c1222'); g.addColorStop(.65,'#20283a'); g.addColorStop(1,'#05070d');
x.fillStyle=g; x.fillRect(0,0,1024,512);
[[200,100,220,'#ffe2a0',.45],[780,90,240,'#9cc8ff',.4],[520,320,260,'#ffb36e',.25],[60,300,200,'#a0ffd0',.15]].forEach(b=>{ const rg=x.createRadialGradient(b[0],b[1],0,b[0],b[1],b[2]); rg.addColorStop(0,b[3]); rg.addColorStop(1,'rgba(0,0,0,0)'); x.globalAlpha=b[4]; x.fillStyle=rg; x.beginPath(); x.arc(b[0],b[1],b[2],0,7); x.fill(); });
const tex=new T.CanvasTexture(c); tex.mapping=T.EquirectangularReflectionMapping; tex.encoding=T.sRGBEncoding;
const pm=new T.PMREMGenerator(renderer); pm.compileEquirectangularShader(); scene.environment=pm.fromEquirectangular(tex).texture; pm.dispose(); tex.dispose();
})();
/* =====================================================================
IRIDESCENT WING MATERIAL (thin-film: hue drifts with time and viewing angle)
Data texture: R = brightness, G = hue offset, B = film strength, A = alpha.
===================================================================== */
const U_TIME = { value: 0 };
const HSL_GLSL = `
vec3 hsl2rgb(vec3 c){ vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.,4.,2.),6.)-3.)-1.,0.,1.);
return c.z + c.y*(rgb-0.5)*(1.0-abs(2.0*c.z-1.0)); }
`;
function wingMat(tex, alpha){
const m = new T.MeshStandardMaterial({ color:0xffffff, map:tex, roughness:.12, metalness:.35, side:DS, transparent:true, depthWrite:false, envMapIntensity:1.8 });
const u = { uTime:U_TIME, uAlpha:{value:alpha} }; m.userData.u=u;
m.onBeforeCompile = sh => { Object.assign(sh.uniforms,u);
sh.fragmentShader = 'uniform float uTime; uniform float uAlpha;\n' + HSL_GLSL + sh.fragmentShader
.replace('#include <map_fragment>', 'vec4 patS = texture2D(map, vUv); diffuseColor.a *= patS.a * uAlpha;')
.replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
{ float ndv = clamp(abs(dot(normal, normalize(vViewPosition))),0.,1.);
float film = patS.b;
float h = fract(uTime*0.03 + 0.55 + patS.g + (1.0-ndv)*0.7*film);
vec3 c = pow(hsl2rgb(vec3(h, 0.75*film, clamp(patS.r*0.85,0.,0.85))), vec3(2.2));
diffuseColor.rgb = c;
totalEmissiveRadiance += c * 0.22 * film * pow(1.0-ndv, 2.0) * uAlpha; }`); };
m.customProgramCacheKey = () => 'wing';
return m;
}
/* =====================================================================
HELPERS
===================================================================== */
function makeCanvas(w,h,draw){ const c=document.createElement('canvas'); c.width=w; c.height=h; draw(c.getContext('2d'),w,h); return c; }
const D = (r,g,b,a=1) => `rgba(${Math.round(clamp(r,0,1)*255)},${Math.round(clamp(g,0,1)*255)},${Math.round(clamp(b,0,1)*255)},${a})`;
function lathe(len,rf,n=12,rs=12){ const p=[]; for(let i=0;i<=rs;i++){ const s=i/rs; p.push(new T.Vector2(Math.max(rf(s),.0005), s*len)); } return new T.LatheGeometry(p,n); }
const alongX = (len,rf,n,rs) => lathe(len,rf,n,rs).rotateZ(-Math.PI/2);
const alongZ = (len,rf,n,rs) => lathe(len,rf,n,rs).rotateX(Math.PI/2);
const SPH = new T.SphereGeometry(1, 28, 20), SPH_LO = new T.SphereGeometry(1, 10, 8);
const HAIR = new T.CylinderGeometry(0, 1, 1, 3, 1).translate(0,.5,0);
const _q = new T.Quaternion();
function mesh(geo,mat,parent,pos,scl){ const m=new T.Mesh(geo,mat); if(pos) m.position.copy(pos); if(scl!==undefined) (typeof scl==='number'?m.scale.setScalar(scl):m.scale.copy(scl)); m.castShadow=true; m.receiveShadow=true; parent&&parent.add(m); return m; }
const randDir = () => V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize();
function gridGeo(NU,NV,fn){ const pos=[],uv=[],idx=[];
for(let i=0;i<=NU;i++) for(let j=0;j<=NV;j++){ const u=i/NU, v=j/NV, p=fn(u,v); pos.push(p[0],p[1],p[2]); uv.push(u,v); }
for(let i=0;i<NU;i++) for(let j=0;j<NV;j++){ const a=i*(NV+1)+j,b=a+NV+1; idx.push(a,b,a+1,b,b+1,a+1); }
const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(pos,3)); g.setAttribute('uv',new T.Float32BufferAttribute(uv,2)); g.setIndex(idx); g.computeVertexNormals(); return g; }
// instanced fur: list of [base, dir, len, rad, colorHex]
const furMat = new T.MeshStandardMaterial({ color:0xffffff, roughness:.82, metalness:0 });
function fur(parent, list, mat=furMat){
const im=new T.InstancedMesh(HAIR,mat,list.length), m4=new T.Matrix4(), c=new T.Color();
list.forEach(([p,d,len,rad,col],i)=>{ _q.setFromUnitVectors(UP,d.clone().normalize()); m4.compose(p,_q,V3(rad,len,rad)); im.setMatrixAt(i,m4); c.set(col).convertSRGBToLinear(); c.multiplyScalar(rr(.75,1.15)); im.setColorAt(i,c); });
im.instanceMatrix.needsUpdate=true; parent.add(im); return im;
}
function ellSample(c,a,b,cz,filter){ let d; do{ d=randDir(); } while(filter&&!filter(d)); return [V3(c.x+d.x*a,c.y+d.y*b,c.z+d.z*cz), V3(d.x/a,d.y/b,d.z/cz).normalize(), d]; }
/* =====================================================================
MATERIALS
===================================================================== */
const eyeBump=(()=>{ const c=makeCanvas(256,256,(g,W,H)=>{ g.fillStyle='#000'; g.fillRect(0,0,W,H); const r=3;
for(let row=0;row*r*1.5<H+r;row++) for(let col=0;col*r*1.75<W+r;col++){ const x=col*r*1.75+(row%2)*r*.87, y=row*r*1.5, gr=g.createRadialGradient(x,y,0,x,y,r); gr.addColorStop(0,'#fff'); gr.addColorStop(1,'#000'); g.fillStyle=gr; g.beginPath(); g.arc(x,y,r,0,7); g.fill(); } });
const t=new T.CanvasTexture(c); t.wrapS=t.wrapT=T.RepeatWrapping; t.repeat.set(3,3); return t; })();
const MAT = {
chitin: new T.MeshPhysicalMaterial({ color:lin(0x0c0907), roughness:.38, metalness:.1, clearcoat:.8, clearcoatRoughness:.25 }),
eye: new T.MeshPhysicalMaterial({ color:lin(0x120d14), roughness:.18, metalness:.2, clearcoat:1, clearcoatRoughness:.05, bumpMap:eyeBump, bumpScale:.002 }),
joint: new T.MeshStandardMaterial({ color:lin(0x2a1a0e), roughness:.5 }),
claw: new T.MeshStandardMaterial({ color:lin(0x3a2312), roughness:.3, metalness:.3 }),
pollen: new T.MeshStandardMaterial({ color:lin(0xe39a1a), roughness:.85, metalness:0 }),
tongue: new T.MeshPhysicalMaterial({ color:lin(0x2a1808), roughness:.4, clearcoat:.6 }),
};
// colour of the pile at a body point (Bombus-style banding)
const BLACK=0x15100b, YEL=0xf0b21a, WHITE=0xf1ebdd, AMB=0x9a621c;
function pileColour(p){ const z=p.z;
if(z>1.05) return BLACK; // head
if(z>.92) return YEL; // collar
if(z>.3) return (p.y<-.15?YEL:BLACK); // thorax disc (pale underneath)
if(z>.15) return YEL; // scutellar fringe
if(z>-.1) return YEL; // T1
if(z>-.42) return BLACK; // T2
if(z>-.62) return YEL; // T3
if(z>-.86) return BLACK; // T4
return WHITE; // white tail
}
/* =====================================================================
THE BEE
===================================================================== */
const bee = new T.Group(); scene.add(bee); // world pose
const body = new T.Group(); bee.add(body); // bob / vibration
bee.scale.setScalar(.55);
const leftSide = new T.Group(); leftSide.scale.x=-1; body.add(leftSide);
const sides=[body,leftSide];
// core shapes (mostly hidden under pile)
const coreMat=c=>new T.MeshStandardMaterial({color:lin(c),roughness:.9,metalness:0});
mesh(SPH, coreMat(0x1a140e), body, V3(0,.04,.66), V3(.4,.38,.42)); // thorax
mesh(SPH, MAT.chitin, body, V3(0,.02,.24), V3(.1,.1,.08)); // petiole
const abdomen=new T.Group(); abdomen.position.set(0,.0,.2); body.add(abdomen);
const tergites=[];
[[.0,.3,.26],[-.24,.42,.36],[-.52,.44,.37],[-.8,.4,.33],[-1.05,.32,.26],[-1.26,.22,.18],[-1.42,.12,.1]].forEach(([z,w,h],i)=>{
const g=new T.Group(); g.position.set(0,-.03-i*.012,z); abdomen.add(g); tergites.push(g);
mesh(SPH, coreMat(pileColour(V3(0,.3,z+.2))), g, null, V3(w,h,.22));
});
mesh(alongZ(.16,u=>.025*(1-u)+.002,6,4), MAT.claw, abdomen, V3(0,-.1,-1.5)).rotation.x=Math.PI-.25; // sting tip
// pile — thousands of instanced hairs, banded by region
(function(){
const list=[];
for(let i=0;i<8000;i++){ const [p,n,d]=ellSample(V3(0,.04,.66),.41,.39,.43); const dir=n.clone().add(V3(rr(-.4,.4),rr(-.1,.35),rr(-.5,.15))); list.push([p,dir,rr(.07,.14),.0062,pileColour(p)]); }
for(let i=0;i<10000;i++){
const zz=rr(-1.48,.14), seg=Math.min(1,Math.abs(zz+.6)/.9), w=lerp(.46,.2,Math.max(0,(-zz-.6)/.9))*(zz>-.05?lerp(1,.75,(zz+.05)/.2):1), h=w*.86;
const a=rnd()*TAU, p=V3(Math.cos(a)*w,-.03+Math.sin(a)*h,zz+.2), n=V3(Math.cos(a),Math.sin(a),-.25).normalize();
list.push([p,n.clone().add(V3(rr(-.2,.2),rr(-.2,.2),-.55)),rr(.04,.08)*(zz<-1.2?.7:1),.0055,pileColour(V3(p.x,p.y,zz))]); }
fur(body,list);
})();
// head
const head=new T.Group(); head.position.set(0,-.02,1.26); head.rotation.x=.25; body.add(head);
mesh(SPH, MAT.chitin, head, null, V3(.25,.27,.18));
mesh(SPH, MAT.chitin, head, V3(0,-.08,.12), V3(.13,.16,.08)); // clypeus
[-1,1].forEach(s=>{ const e=mesh(SPH, MAT.eye, head, V3(s*.19,.04,.02), V3(.075,.16,.12)); e.rotation.y=s*.3;
mesh(SPH_LO, new T.MeshStandardMaterial({color:0xffffff,roughness:.05,envMapIntensity:2}), head, V3(s*.23,.12,.07), .015); });
[[-0.05,.22,.06],[.05,.22,.06],[0,.24,.1]].forEach(p=>mesh(SPH_LO, MAT.eye, head, V3(...p), .018)); // ocelli
fur(head, Array.from({length:700},()=>{ const [p,n]=ellSample(V3(0,0,0),.25,.27,.18,d=>Math.abs(d.x)<.55||d.y>.5); return [p,n.clone().add(V3(0,.3,.2)),rr(.04,.09),.007,BLACK]; }));
const mandibles=[];
[-1,1].forEach(s=>{ const mg=new T.Group(); mg.position.set(s*.07,-.22,.08); head.add(mg); mesh(SPH, MAT.chitin, mg, V3(-s*.02,-.03,.01), V3(.035,.05,.03)); mandibles.push({mg,s}); });
// tongue (glossa): folded under the head, extends to feed
const tongue=new T.Group(); tongue.position.set(0,-.24,.06); head.add(tongue);
const tongueSegs=[]; { let p=tongue; for(let k=0;k<6;k++){ const j=new T.Group(); p.add(j); mesh(alongZ(.07,u=>.016*(1-k*.1)*(.85+.15*Math.sin(u*Math.PI)),6,3), MAT.tongue, j);
if(k>2) fur(j, Array.from({length:10},()=>{ const a=rnd()*TAU; return [V3(Math.cos(a)*.012,Math.sin(a)*.012,rnd()*.07), V3(Math.cos(a),Math.sin(a),.6), .015,.002,AMB]; }));
const n=new T.Group(); n.position.z=.07; j.add(n); p=n; tongueSegs.push(j); } }
// elbowed antennae: long scape, then 10-segment flagellum
const antennae=[];
[-1,1].forEach(s=>{ const r=new T.Group(); r.position.set(s*.06,.08,.15); head.add(r); r.rotation.set(-.9,s*.25,0);
mesh(alongZ(.26,u=>.022*(1-.25*u),8,4), MAT.chitin, r);
const fl=new T.Group(); fl.position.z=.26; r.add(fl); fl.rotation.set(1.35,s*.35,0);
let p=fl; const J=[]; for(let k=0;k<10;k++){ const j=new T.Group(); j.rotation.x=-.04; p.add(j); mesh(alongZ(.05,u=>.017*(.85+.15*Math.sin(u*Math.PI)),6,3), MAT.chitin, j); const n=new T.Group(); n.position.z=.05; j.add(n); p=n; J.push(j); }
antennae.push({r,fl,J,s}); });
// wings: veined membranes with thin-film colour; ghost copies give the motion blur of a 200 Hz beat
const foreC = makeCanvas(512,200,(g,W,H)=>{ g.clearRect(0,0,W,H);
let gr=g.createLinearGradient(0,0,W,0); gr.addColorStop(0,D(.6,.0,.6,.4)); gr.addColorStop(.3,D(.8,.05,1,.2)); gr.addColorStop(1,D(.75,.15,1,.3)); g.fillStyle=gr; g.fillRect(0,0,W,H);
for(let i=0;i<5000;i++){ g.fillStyle=D(.8,rr(0,.2),1,.25); g.fillRect(rnd()*W,rnd()*H,1.2,1.2); }
const X=u=>u*W, Y=v=>(1-v)*H, vein=(pts,w)=>{ g.strokeStyle=D(.12,.05,.3,1); g.lineWidth=w; g.lineJoin=g.lineCap='round'; g.beginPath(); pts.forEach(([u,v],i)=>i?g.lineTo(X(u),Y(v)):g.moveTo(X(u),Y(v))); g.stroke(); };
vein([[0,.62],[.25,.9],[.56,.94]],7); // costa
vein([[0,.55],[.3,.78],[.56,.86],[.7,.82]],4); // radius
g.fillStyle=D(.12,.05,.3,1); g.beginPath(); g.ellipse(X(.58),Y(.9),18,7,-.1,0,7); g.fill(); // pterostigma
vein([[.56,.86],[.72,.84],[.86,.74],[.74,.68],[.6,.72]],3); // marginal cell
vein([[.42,.7],[.6,.72]],3); vein([[.42,.7],[.4,.5]],3); vein([[.52,.72],[.5,.5]],3); vein([[.62,.72],[.62,.5]],3); vein([[.72,.69],[.7,.48]],3); // submarginal cells
vein([[0,.5],[.2,.52],[.4,.5],[.7,.48]],3.5); vein([[0,.42],[.3,.32],[.5,.3],[.62,.26]],3.5); vein([[.3,.32],[.4,.5]],3); vein([[.5,.3],[.5,.5]],3);
vein([[0,.3],[.35,.12]],3); vein([[0,.1],[.6,.04]],2.5);
});
const hindC = makeCanvas(256,128,(g,W,H)=>{ g.clearRect(0,0,W,H); g.fillStyle=D(.8,.1,1,.2); g.fillRect(0,0,W,H);
const vein=(pts,w)=>{ g.strokeStyle=D(.12,.05,.3,1); g.lineWidth=w; g.lineCap='round'; g.beginPath(); pts.forEach(([u,v],i)=>i?g.lineTo(u*W,(1-v)*H):g.moveTo(u*W,(1-v)*H)); g.stroke(); };
vein([[0,.6],[.6,.92]],4); vein([[0,.45],[.35,.5],[.6,.42]],2.5); vein([[0,.3],[.4,.22]],2.5); vein([[.35,.5],[.4,.22]],2);
for(let k=0;k<10;k++){ g.fillStyle=D(.12,.05,.3,1); g.fillRect(W*(.45+k*.015),H*.05,2,5); } // hamuli
});
const foreT=new T.CanvasTexture(foreC), hindT=new T.CanvasTexture(hindC); foreT.anisotropy=hindT.anisotropy=ANISO;
function wingGeo(L,W,c0){ return gridGeo(32,10,(u,v)=>{ const env=Math.pow(Math.sin(Math.PI*clamp(u*1.04+.05,0,1)),.55)*(1-.15*u)*(u<.08?u/.08*.7+.3:1); const hw=.5*W*env, cen=c0*u; return [u*L,0,cen-hw+2*hw*v]; }); }
const FW=wingGeo(1.55,.62,.06), HWg=wingGeo(1.12,.44,.03);
const wingSets=[];
const GHOSTS=[-.85,-.4,.15,.6,.95];
function wingRig(parent, alpha, ghostPhase){
const fp=new T.Group(); fp.position.set(.2,.34,.82); parent.add(fp);
const fm=new T.Mesh(FW, wingMat(foreT,alpha)); fm.renderOrder=3; fp.add(fm);
const hp=new T.Group(); hp.position.set(.22,.3,.6); parent.add(hp);
const hm=new T.Mesh(HWg, wingMat(hindT,alpha)); hm.renderOrder=2; hp.add(hm);
return {fp,hp,fm,hm,alpha,ghostPhase};
}
sides.forEach((p,si)=>{ wingSets.push(wingRig(p,1,null)); GHOSTS.forEach(g=>wingSets.push(wingRig(p,.28,g))); });
// legs: coxa, femur, tibia, basitarsus + 4 tarsomeres, claws; hind tibia carries the pollen basket
const legs=[]; const pollenLoads=[];
const LEGS=[ {pos:[.18,-.28,.88],yaw:-.6,f:.36,t:.32,ts:.28}, {pos:[.24,-.3,.66],yaw:.15,f:.4,t:.36,ts:.3}, {pos:[.24,-.28,.44],yaw:.7,f:.46,t:.46,ts:.34,hind:true} ];
const pollenGeo=(()=>{ const g=new T.IcosahedronGeometry(1,3), p=g.attributes.position, v=V3(); for(let i=0;i<p.count;i++){ v.fromBufferAttribute(p,i); v.multiplyScalar(1+.08*Math.sin(v.x*9)*Math.sin(v.y*11)*Math.sin(v.z*7)+rr(-.03,.03)); p.setXYZ(i,v.x,v.y,v.z); } g.computeVertexNormals(); return g; })();
sides.forEach(ps=>LEGS.forEach((d,li)=>{
const root=new T.Group(); root.position.set(...d.pos); root.rotation.y=d.yaw; ps.add(root);
const segs=[[.1,.05],[d.f,.04],[d.t,d.hind?.05:.03],[d.ts,.025]]; let parent=root; const joints=[];
segs.forEach(([L,r],si)=>{ const j=new T.Group(); parent.add(j); joints.push(j);
if(si<3){ const m=mesh(alongX(L,u=>r*(.85+.25*Math.sin(Math.PI*u))*(1-(si===2&&d.hind?-.4:.2)*u),10,6), MAT.chitin, j); if(si===2&&d.hind) m.scale.z=.55;
const col=si===0?BLACK:(d.hind&&si===2?AMB:BLACK);
fur(j, Array.from({length:si===1?70:si===2?(d.hind?90:55):20},()=>{ const x=rnd()*L, a=rnd()*TAU; if(d.hind&&si===2&&Math.abs(Math.sin(a))<.6&&Math.cos(a)>0) return [V3(x,0,0),V3(1,0,0),.001,.001,BLACK];
return [V3(x,Math.cos(a)*r*.9,Math.sin(a)*r*.9), V3(.5,Math.cos(a),Math.sin(a)), rr(.03,d.hind&&si===2?.11:.07), .005, col]; }));
if(d.hind&&si===2){ const pl=mesh(pollenGeo, MAT.pollen, j, V3(L*.6,.0,.05), V3(.0,.0,.0)); pl.userData.full=V3(L*.42,.1,.09); pollenLoads.push(pl); } }
else { let x=0; [.42,.15,.13,.12,.18].forEach((f,k)=>{ const LL=L*f; mesh(alongX(LL,u=>(k===0&&d.hind?.03:.017)*(1-k*.08),6,3), MAT.chitin, j, V3(x,0,0)); x+=LL; });
fur(j, Array.from({length:30},()=>{ const x2=rnd()*L, a=rnd()*TAU; return [V3(x2,Math.cos(a)*.015,Math.sin(a)*.015), V3(.6,Math.cos(a)-.5,Math.sin(a)), rr(.02,.04),.004,AMB]; }));
[-1,1].forEach(cs=>{ const c=mesh(alongX(.05,u=>.007*(1-u)+.001,5,3), MAT.claw, j, V3(L,0,cs*.008)); c.rotation.set(0,cs*.4,-1.1); }); }
const n=new T.Group(); n.position.x=L; j.add(n); parent=n; });
legs.push({root,joints,li,d});
}));
const POSE={ fly:[[-1.2,-.3,-1.5,.2],[-1.3,-.2,-1.4,.3],[-1.45,.2,-.6,.2]], stand:[[-.85,.55,-1.5,.6],[-.95,.6,-1.45,.6],[-1,.55,-1.4,.55]], yawFly:[.45,.4,.75] };
/* =====================================================================
THE NEST: a mossy hollow with a brood clump of wax-coated cocoons and honey pots
===================================================================== */
const NS=.72; const nest=new T.Group(); nest.position.set(0,-1.4,0); nest.scale.setScalar(NS); scene.add(nest);
const pots=[];
(function(){
// soil floor
const soilC=makeCanvas(1024,1024,(g,W,H)=>{ g.fillStyle='#2a1c12'; g.fillRect(0,0,W,H);
for(let i=0;i<50;i++){ const x=rnd()*W,y=rnd()*H,r=rr(60,220),gr=g.createRadialGradient(x,y,0,x,y,r); gr.addColorStop(0,`rgba(${rnd()<.5?'10,6,3':'70,50,32'},${rr(.2,.35)})`); gr.addColorStop(1,'rgba(0,0,0,0)'); g.fillStyle=gr; g.fillRect(0,0,W,H); }
const cols=['#3a2a1c','#1a120b','#4d3826','#2f2116','#5c4630'];
for(let i=0;i<50000;i++){ g.fillStyle=cols[(rnd()*cols.length)|0]; g.fillRect(rnd()*W,rnd()*H,rr(.8,2.4),rr(.8,2.4)); }
for(let i=0;i<40;i++){ g.strokeStyle=`rgba(${rnd()<.5?'90,64,40':'20,12,6'},.5)`; g.lineWidth=rr(1,3); let x=rnd()*W,y=rnd()*H; g.beginPath(); g.moveTo(x,y); for(let k=0;k<10;k++){ x+=rr(-40,40); y+=rr(-40,40); g.lineTo(x,y);} g.stroke(); } });
const st=new T.CanvasTexture(soilC); st.encoding=T.sRGBEncoding; st.wrapS=st.wrapT=T.RepeatWrapping; st.repeat.set(4,4); st.anisotropy=ANISO;
const ground=new T.Mesh(new T.CircleGeometry(30,64), new T.MeshStandardMaterial({map:st,roughness:.95,bumpMap:st,bumpScale:.03}));
ground.rotation.x=-Math.PI/2; ground.receiveShadow=true; nest.add(ground);
// bedding: dry grass and moss fibres forming a shallow bowl around the comb
const N=6000, fib=new T.InstancedMesh(new T.CylinderGeometry(.012,.018,1,3).rotateZ(Math.PI/2).translate(.5,0,0), new T.MeshStandardMaterial({color:0xffffff,roughness:.85}), N);
const m4=new T.Matrix4(), col=new T.Color(), e=new T.Euler();
for(let i=0;i<N;i++){ const a=rnd()*TAU, r=Math.sqrt(rnd())*6.5+1.6, rim=Math.exp(-((r-4.3)**2)/1.2);
const y=rim*1.3*rr(.4,1)+rr(0,.08); e.set(rr(-.3,.3),a+Math.PI/2+rr(-.7,.7),rr(-.15,.35)+rim*.4); _q.setFromEuler(e);
m4.compose(V3(Math.cos(a)*r,y,Math.sin(a)*r),_q,V3(rr(.6,1.8),1,1)); fib.setMatrixAt(i,m4);
col.set([0x8a7445,0x6b5a35,0xa08a55,0x4f6a2a,0x3d5424][(rnd()*5)|0]).convertSRGBToLinear().multiplyScalar(rr(.6,1.1)); fib.setColorAt(i,col); }
fib.castShadow=fib.receiveShadow=true; nest.add(fib);
const moss=new T.InstancedMesh(new T.IcosahedronGeometry(1,1), new T.MeshStandardMaterial({color:0xffffff,roughness:.95}), 260);
for(let i=0;i<260;i++){ const a=rnd()*TAU, r=rr(3.2,6.5), s=rr(.08,.28); m4.compose(V3(Math.cos(a)*r,s*.4+Math.exp(-((r-4.3)**2)/1.2)*rr(0,.9),Math.sin(a)*r),_q.setFromEuler(e.set(rnd(),rnd(),rnd())),V3(s*1.3,s*.3,s*1.3)); moss.setMatrixAt(i,m4);
col.set(rnd()<.5?0x2a4214:0x3a5418).convertSRGBToLinear(); moss.setColorAt(i,col); }
moss.receiveShadow=true; nest.add(moss);
// brood clump: wax-coated cocoons, some capped with darker wax
const coconGeo=(()=>{ const g=new T.SphereGeometry(1,28,20), p=g.attributes.position, v=V3(); for(let i=0;i<p.count;i++){ v.fromBufferAttribute(p,i); v.multiplyScalar(1+.04*Math.sin(v.x*7+v.y*5)*Math.cos(v.z*6)+rr(-.01,.01)); p.setXYZ(i,v.x,v.y,v.z); } g.computeVertexNormals(); return g; })();
const silk=new T.MeshPhysicalMaterial({color:lin(0xd8b46c),roughness:.45,clearcoat:.4,clearcoatRoughness:.4,emissive:lin(0x2a1604)});
const silkD=new T.MeshPhysicalMaterial({color:lin(0xb48238),roughness:.4,clearcoat:.5,emissive:lin(0x201002)});
const waxD=new T.MeshPhysicalMaterial({color:lin(0x7a4a1a),roughness:.35,clearcoat:.7,emissive:lin(0x1a0a02)});
mesh(coconGeo,waxD,nest,V3(0,.35,0),V3(1.25,.45,1.25));
const place=(n,r,y,tilt)=>{ for(let i=0;i<n;i++){ const a=i/n*TAU+rr(-.1,.1), c=mesh(coconGeo,rnd()<.3?silkD:silk,nest,V3(Math.cos(a)*r,y,Math.sin(a)*r),V3(.42,.56,.42)); c.rotation.set(Math.sin(a)*tilt,0,-Math.cos(a)*tilt); } };
place(7,.85,.7,.35); place(4,.42,1.3,.2);
mesh(coconGeo,silk,nest,V3(0,1.75,0),V3(.42,.5,.42));
for(let i=0;i<14;i++){ const a=rnd()*TAU, r=rr(.2,1.1); mesh(coconGeo,waxD,nest,V3(Math.cos(a)*r,rr(.4,1.5),Math.sin(a)*r),V3(rr(.12,.22),rr(.08,.14),rr(.12,.22))); } // wax patches
// honey pots: thin wax walls, glossy honey surfaces, drips
const wax=new T.MeshPhysicalMaterial({color:lin(0xc4852a),roughness:.3,clearcoat:.8,clearcoatRoughness:.15,emissive:lin(0x3a1a04),side:DS});
const honey=new T.MeshPhysicalMaterial({color:lin(0xe08a12),roughness:.04,metalness:0,clearcoat:1,clearcoatRoughness:.02,emissive:lin(0x6a2c00),emissiveIntensity:.8});
[[.4,.75],[1.5,.9],[2.7,.7],[3.9,.85],[5.1,.78]].forEach(([a,h],k)=>{
const R=rr(.34,.42), pos=V3(Math.cos(a)*2.35,0,Math.sin(a)*2.35);
const prof=[]; for(let i=0;i<=14;i++){ const t=i/14; prof.push(new T.Vector2(R*(t<.08?t/.08*.7+.3:1)*(1+.12*Math.sin(Math.PI*t))*(t>.85?1-.18*(t-.85)/.15:1),t*h)); }
const g=new T.Group(); g.position.copy(pos); nest.add(g);
mesh(new T.LatheGeometry(prof,28),wax,g);
mesh(new T.TorusGeometry(R*.84,.035,8,28),wax,g,V3(0,h,0)).rotation.x=Math.PI/2;
const hs=mesh(new T.CircleGeometry(R*.86,28),honey,g,V3(0,h*.86,0)); hs.rotation.x=-Math.PI/2;
for(let d=0;d<3;d++){ const da=rnd()*TAU; mesh(SPH,honey,g,V3(Math.cos(da)*R*1.08,h*rr(.55,.85),Math.sin(da)*R*1.08),V3(.04,rr(.07,.13),.04)); }
pots.push({g,R,h});
});
})();
// falling pollen grains (unloading into the brood clump)
const puff=(()=>{ const N=260, pos=new Float32Array(N*3), vel=[], life=new Float32Array(N); for(let i=0;i<N;i++){ vel.push(V3()); life[i]=0; pos[i*3+1]=-99; }
const g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(pos,3));
const sp=new T.CanvasTexture(makeCanvas(32,32,(x)=>{ const gr=x.createRadialGradient(16,16,0,16,16,16); gr.addColorStop(0,'rgba(255,200,80,1)'); gr.addColorStop(1,'rgba(255,170,40,0)'); x.fillStyle=gr; x.fillRect(0,0,32,32); }));
const pts=new T.Points(g,new T.PointsMaterial({size:.06,map:sp,transparent:true,depthWrite:false,color:0xffc860})); scene.add(pts);
return {N,pos,vel,life,g,next:0}; })();
function emitPollen(at,n){ for(let k=0;k<n;k++){ const i=puff.next=(puff.next+1)%puff.N; puff.pos[i*3]=at.x+rr(-.15,.15); puff.pos[i*3+1]=at.y; puff.pos[i*3+2]=at.z+rr(-.15,.15); puff.vel[i].set(rr(-.2,.2),rr(-.1,.2),rr(-.2,.2)); puff.life[i]=rr(.8,1.6); } }
/* lights: cool sky from above, warm glow from the comb */
scene.add(new T.HemisphereLight(0xffe6c0,0x1a1008,.55));
const key=new T.DirectionalLight(0xfff0d8,1.5); key.position.set(4,9,5); key.castShadow=true; key.shadow.mapSize.set(2048,2048);
Object.assign(key.shadow.camera,{left:-6,right:6,top:6,bottom:-6,near:1,far:30}); key.shadow.bias=-.0004; key.shadow.normalBias=.02; key.shadow.radius=3; scene.add(key);
const glow=new T.PointLight(0xffa040,1.6,9,2); glow.position.set(0,.6,0); scene.add(glow);
const rim=new T.PointLight(0xffd35c,1.0,60); rim.position.set(-6,3,-2); scene.add(rim);
const rim2=new T.PointLight(0x7fa8ff,.8,60); rim2.position.set(6,1,-5); scene.add(rim2);
const glint=new T.PointLight(0xffffff,.8,40); glint.position.set(2,4,8); scene.add(glint);
/* =====================================================================
BEHAVIOUR: forage away → return laden → unload pollen on the brood →
hop to a honey pot and drink → fan the nest → leave again
===================================================================== */
const NESTC=()=>nest.localToWorld(V3(0,1.2,0));
const BROOD=()=>nest.localToWorld(V3(0,2.25,0));
let tau=0;
function wander(t){ const c=nest.localToWorld(V3(0,0,0)), a=t*.5+.5*Math.sin(t*.31), R=6+2*Math.sin(t*.27);
return V3(c.x+Math.cos(a)*R+.3*Math.sin(t*3.1), c.y+3.2+.9*Math.sin(t*.7)+.2*Math.sin(t*2.6), c.z+Math.sin(a)*R+.3*Math.cos(t*2.3)); }
const st={mode:'forage',t:0,dur:rr(5,7),p0:V3(),p1:V3(),c0:V3(),c1:V3(),yaw:0,pitch:.1,pot:0};
const bez=(a,b,c,d,s)=>{ const u=1-s; return a.clone().multiplyScalar(u*u*u).addScaledVector(b,3*u*u*s).addScaledVector(c,3*u*s*s).addScaledVector(d,s*s*s); };
const eul=new T.Euler(0,0,0,'YXZ');
function broodPerch(){ return BROOD(); }
function potPerch(){ const P=pots[st.pot], c=P.g.getWorldPosition(V3()), toward=BROOD().sub(c); toward.y=0; toward.normalize();
const rim=c.clone().addScaledVector(toward,P.R*.9*NS); rim.y+=P.h*NS; const fwd=toward.clone().negate();
return { p: rim.addScaledVector(fwd,-.2).add(V3(0,.34,0)), yaw: Math.atan2(fwd.x,fwd.z) }; }
let prev=wander(0), vel=V3(), roll=0, fold=0, legStand=0, tongueOut=0, fanT=0, pollenAmt=1;
bee.position.copy(prev);
const PERCHED={unload:1,drink:1,fan:1};
function update(dt,t){
st.t+=dt;
const go=(m,d)=>{ st.mode=m; st.t=0; st.dur=d; };
if(st.mode==='forage'){ tau+=dt; bee.position.copy(wander(tau)); pollenAmt=Math.min(1,pollenAmt+dt*.2);
if(st.t>st.dur && !reduceMotion){ go('approach',2.6); st.p0.copy(bee.position); st.c0.copy(bee.position).addScaledVector(vel,.9); st.yaw=rnd()*TAU; st.pitch=.08; } }
else if(st.mode==='approach'){ const p=broodPerch(); st.p1.copy(p); st.c1.copy(p).add(V3(0,1.4,0)); bee.position.copy(bez(st.p0,st.c0,st.c1,st.p1,smooth(st.t/st.dur))); if(st.t>=st.dur) go('unload',4); }
else if(st.mode==='unload'){ bee.position.copy(broodPerch()); st.yaw+=dt*.25; pollenAmt=Math.max(0,pollenAmt-dt*.32);
if(pollenAmt>.02 && rnd()<dt*25){ const at=bee.localToWorld(V3(0,-.4,.2)); emitPollen(at,2); }
if(st.t>=st.dur){ go('hop',1.3); st.pot=(rnd()*pots.length)|0; st.p0.copy(bee.position); st.c0.copy(bee.position).add(V3(0,1,0)); } }
else if(st.mode==='hop'){ const pp=potPerch(); st.p1.copy(pp.p); st.c1.copy(pp.p).add(V3(0,1,0)); bee.position.copy(bez(st.p0,st.c0,st.c1,st.p1,smooth(st.t/st.dur))); st.yaw=pp.yaw; st.pitch=.32; if(st.t>=st.dur) go('drink',4.5); }
else if(st.mode==='drink'){ bee.position.copy(potPerch().p); if(st.t>=st.dur) go('fan',2.6); }
else if(st.mode==='fan'){ bee.position.copy(potPerch().p); st.pitch=.05; if(st.t>=st.dur){ go('takeoff',1.6); tau+=1.8; st.p0.copy(bee.position); st.c0.copy(bee.position).add(V3(0,1.6,0)); } }
else if(st.mode==='takeoff'){ const w=wander(tau); st.p1.copy(w); st.c1.copy(w).sub(wander(tau+.1)).multiplyScalar(8).add(w); bee.position.copy(bez(st.p0,st.c0,st.c1,st.p1,smooth(st.t/st.dur))); if(st.t>=st.dur) go('forage',rr(5,8)); }
const v=bee.position.clone().sub(prev).divideScalar(Math.max(dt,1e-4)); prev.copy(bee.position); vel.lerp(v,1-Math.exp(-dt*5));
const perched=!!PERCHED[st.mode];
if(!perched){ const hs=Math.hypot(vel.x,vel.z), cur=new T.Euler().setFromQuaternion(bee.quaternion,'YXZ'), yaw=hs>.05?Math.atan2(vel.x,vel.z):cur.y;
let dy=Math.atan2(Math.sin(yaw-cur.y),Math.cos(yaw-cur.y)); roll+=(clamp(-dy*1.2,-.5,.5)-roll)*(1-Math.exp(-dt*3));
let q=new T.Quaternion().setFromEuler(eul.set(-.12-clamp(vel.y*.08,-.3,.3)+clamp(hs*.04,0,.2),yaw,roll));
if(st.mode==='approach'||st.mode==='hop'){ q.slerp(new T.Quaternion().setFromEuler(eul.set(st.pitch,st.yaw,0)),smooth((st.t/st.dur-.5)/.5)); }
bee.quaternion.slerp(q,1-Math.exp(-dt*4)); }
else bee.quaternion.slerp(new T.Quaternion().setFromEuler(eul.set(st.pitch,st.yaw,0)),1-Math.exp(-dt*3));
// part states
const landed = perched || ((st.mode==='approach'||st.mode==='hop')&&st.t/st.dur>.85);
const fanning = st.mode==='fan' && st.t>.3 && st.t<st.dur-.2;
fold+=(((st.mode==='unload'||st.mode==='drink')?1:0)-fold)*(1-Math.exp(-dt*(perched&&!fanning?3:12)));
legStand+=((landed?1:0)-legStand)*(1-Math.exp(-dt*5));
tongueOut+=((st.mode==='drink'&&st.t>.4&&st.t<st.dur-.6?1:0)-tongueOut)*(1-Math.exp(-dt*3));
// wings: ghost copies sample the stroke to mimic motion blur
const flying=1-fold, beat=t*TAU*24;
wingSets.forEach(W=>{
const ph=W.ghostPhase===null?Math.sin(beat):W.ghostPhase;
const sweep=lerp(1.38,ph*.85,flying), elev=lerp(.06,.18+.2*ph,flying), pitch=lerp(0,-.5*Math.cos(beat)*(W.ghostPhase===null?1:0)+(W.ghostPhase??0)*.25,flying);
W.fp.rotation.set(pitch,sweep,elev); W.hp.rotation.set(pitch*.8,sweep*.95+(1-flying)*.04,elev*.9-(1-flying)*.03);
if(W.ghostPhase!==null){ const a=.28*flying*flying; W.fm.material.userData.u.uAlpha.value=a; W.hm.material.userData.u.uAlpha.value=a; W.fp.visible=W.hp.visible=a>.01; }
});
// body: hover bob, fanning shiver, abdomen pumping
const vib=fanning?Math.sin(t*TAU*40)*.012:0;
body.position.set(vib, perched?0:flying*(.03*Math.sin(t*TAU*1.3)+.015*Math.sin(beat*.5)), 0);
body.rotation.z=vib*1.5+(perched?0:flying*.03*Math.sin(t*2));
const pump=Math.sin(t*(perched?3.2:4.5))*(fanning?1.8:1);
tergites.forEach((g,i)=>{ g.scale.y=1+.04*pump*(i/6); g.scale.z=1-.02*pump*(i/6); });
abdomen.rotation.x=.12*(perched?0:flying)+.03*pump+(fanning?.08:0);
// legs
const ls=smooth(legStand), shuffling=st.mode==='unload';
legs.forEach(L=>{ const a=POSE.fly[L.li], b=POSE.stand[L.li]; const walk=shuffling?Math.sin(t*6+L.li*2.1+(L.root.parent===leftSide?Math.PI:0))*.15:0;
const scrape=shuffling&&L.li===1?.25*Math.sin(t*9):0; // mid legs push the pollen off the baskets
L.joints.forEach((j,k)=>j.rotation.z=lerp(a[k],b[k],ls)+(k===1?walk+scrape:0)+(k===2&&!landed?.06*Math.sin(t*3+L.li):0));
L.joints[0].rotation.y=lerp(POSE.yawFly[L.li],0,ls)+walk*.5; });
pollenLoads.forEach(pl=>{ const f=pl.userData.full, s=Math.max(.001,pollenAmt); pl.scale.set(f.x*s,f.y*s,f.z*s); });
// head parts
tongueSegs.forEach((j,k)=>{ j.rotation.x=lerp(k===0?-2.6:.9,k===0?-.7:.12,smooth(tongueOut))+(tongueOut>.5?.05*Math.sin(t*8+k):0); });
mandibles.forEach(({mg,s})=>{ mg.rotation.y=s*.15*Math.max(0,Math.sin(t*4))*(perched?1:.2); });
antennae.forEach(({r,fl,s},i)=>{ r.rotation.x=-.9+.12*Math.sin(t*2.2+i)-(flying*.15); r.rotation.y=s*(.25+.1*Math.sin(t*1.7+i*2)); fl.rotation.x=1.35+.18*Math.sin(t*2.6+i*1.3)+(perched?.25:0); });
head.rotation.x=.25+(st.mode==='drink'?.3:perched?.12:0)+.04*Math.sin(t*1.4);
// pollen grains & nest glow flicker
const P=puff.pos; for(let i=0;i<puff.N;i++){ if(puff.life[i]<=0) continue; puff.life[i]-=dt; const v2=puff.vel[i]; v2.y-=2.5*dt; P[i*3]+=v2.x*dt; P[i*3+1]+=v2.y*dt; P[i*3+2]+=v2.z*dt; if(puff.life[i]<=0) P[i*3+1]=-99; }
puff.g.attributes.position.needsUpdate=true;
glow.intensity=1.5+.15*Math.sin(t*1.7)+.08*Math.sin(t*4.3);
}
/* =====================================================================
CAMERA / INPUT
===================================================================== */
const cam={dist:8.5,yaw:.6,pitch:.32,tYaw:.6,tPitch:.32,tDist:8.5,auto:0}; let dragging=false;
const camTarget=NESTC();
function fitCam(){ const w=innerWidth; camera.fov=w<480?58:w<768?50:42; camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix(); if(w<480) cam.tDist=Math.max(cam.tDist,9); }
fitCam();
const pts=new Map(); let pinch=0,lx=0,ly=0;
canvas.addEventListener('pointerdown',e=>{ pts.set(e.pointerId,[e.clientX,e.clientY]); canvas.setPointerCapture(e.pointerId); dragging=true; lx=e.clientX; ly=e.clientY; pinch=0; });
canvas.addEventListener('pointermove',e=>{ if(!pts.has(e.pointerId)) return; pts.set(e.pointerId,[e.clientX,e.clientY]);
if(pts.size===2){ const [a,b]=[...pts.values()], d=Math.hypot(a[0]-b[0],a[1]-b[1]); if(pinch) cam.tDist=clamp(cam.tDist+(pinch-d)*.015,2,16); pinch=d; return; }
cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.05,1.35); lx=e.clientX; ly=e.clientY; });
const upH=e=>{ pts.delete(e.pointerId); pinch=0; if(!pts.size) dragging=false; else { const [p]=[...pts.values()]; lx=p[0]; ly=p[1]; } };
['pointerup','pointercancel'].forEach(n=>canvas.addEventListener(n,upH));
canvas.addEventListener('wheel',e=>{ e.preventDefault(); cam.tDist=clamp(cam.tDist+e.deltaY*.006,2,16); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });
const clock=new T.Clock(); let time=0;
function frame(){
requestAnimationFrame(frame);
const dt=Math.min(clock.getDelta(),1/30); time+=dt; U_TIME.value=time;
update(dt,time);
camTarget.lerp(NESTC().lerp(bee.position,.5),1-Math.exp(-dt*1.4));
if(!dragging&&!reduceMotion) cam.auto+=dt*.08;
cam.yaw+=(cam.tYaw-cam.yaw)*.08; cam.pitch+=(cam.tPitch-cam.pitch)*.08; cam.dist+=(cam.tDist-cam.dist)*.08;
const y=cam.yaw+cam.auto, p=cam.pitch;
camera.position.set(camTarget.x+Math.sin(y)*Math.cos(p)*cam.dist, camTarget.y+Math.sin(p)*cam.dist, camTarget.z+Math.cos(y)*Math.cos(p)*cam.dist);
camera.lookAt(camTarget);
renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>