Prompt specification
Build or customize the Three.js 3D scene "Kitchen tool handle evaluation bench" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Kitchen tool handle evaluation bench
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/kitchen-tool-handle-evaluation-bench-x0987
Scene Description Prompt:
Compare voxel utensil handles against an articulated hand, showing geometric contact without claiming universal comfort. Three.js from cdnjs, one HTML file.
Working Three.js Starter (kitchen-tool-handle-evaluation-bench-x0987):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Voxel Utensil Handles vs an Articulated Hand — Geometric Contact</title>
<style>
:root{
--bg:#080b10; --panel:rgba(13,17,24,.88); --edge:rgba(255,255,255,.11);
--fg:#e8eef6; --dim:#8ea0b8; --acc:#5fb3ff; --ok:#57d98a; --warn:#ffbe55; --bad:#ff6b6b;
--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--fg);overflow:hidden;
font:13px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
#view{position:fixed;inset:0;display:block;width:100%;height:100%;touch-action:none}
.panel{position:fixed;background:var(--panel);border:1px solid var(--edge);border-radius:13px;
backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);box-shadow:0 20px 44px rgba(0,0,0,.5)}
h1{font-size:15px;margin:0 0 2px;letter-spacing:.2px}
h2{font-size:10.5px;margin:0 0 8px;text-transform:uppercase;letter-spacing:.13em;color:var(--dim);font-weight:600}
.sub{color:var(--dim);font-size:11.5px;margin:0}
#head{left:16px;top:14px;padding:13px 16px;max-width:min(600px,54vw)}
#ctl{left:16px;bottom:16px;padding:13px 15px;width:290px}
#out{right:16px;top:14px;padding:13px 15px;width:330px}
#sl{right:16px;bottom:16px;padding:11px 13px;width:330px}
#note{left:50%;transform:translateX(-50%);bottom:16px;padding:9px 15px;max-width:min(560px,44vw);
font-size:11px;color:var(--dim);border-left:3px solid var(--warn)}
.row{display:flex;gap:6px;margin-bottom:9px;flex-wrap:wrap}
button{font:inherit;color:var(--fg);background:rgba(255,255,255,.05);border:1px solid var(--edge);
border-radius:8px;padding:6px 9px;cursor:pointer;transition:.14s}
button:hover{background:rgba(95,179,255,.16);border-color:rgba(95,179,255,.5)}
button.on{background:rgba(95,179,255,.22);border-color:var(--acc);color:#dff0ff}
.grp{display:flex;gap:5px;flex-wrap:wrap}
.grp button{flex:1 1 auto;text-align:center;font-size:12px}
label.lb{display:flex;justify-content:space-between;align-items:center;margin:11px 0 4px;color:var(--dim);font-size:11.5px}
label.lb b{color:var(--fg);font-family:var(--mono);font-weight:500}
input[type=range]{width:100%;accent-color:var(--acc);height:18px}
table{width:100%;border-collapse:collapse;font-size:11.5px;font-family:var(--mono)}
th{color:var(--dim);font-weight:600;text-align:right;padding:3px 4px;border-bottom:1px solid var(--edge);font-size:10.5px}
th:first-child{text-align:left}
td{padding:3px 4px;text-align:right;border-bottom:1px solid rgba(255,255,255,.05)}
td:first-child{text-align:left;font-family:system-ui,sans-serif}
tr.sel td{background:rgba(95,179,255,.13)}
dl{display:grid;grid-template-columns:1fr auto;gap:2px 10px;margin:0;font-size:12px}
dt{color:var(--dim)}
dd{margin:0;font-family:var(--mono);text-align:right}
.legend{display:flex;align-items:center;gap:8px;margin-top:9px;font-size:10.5px;color:var(--dim)}
.bar{height:8px;flex:1;border-radius:4px;background:linear-gradient(90deg,#5fb3ff,#57d98a,#ffbe55,#ff5d5d)}
#sliceCv{border-radius:8px;background:rgba(255,255,255,.03);display:block;margin:0 auto}
.fine{font-size:10.5px;color:var(--dim);margin:9px 0 0;line-height:1.5}
.warnb{color:var(--warn)}
@media (max-width:1080px){#sl{display:none}#note{left:16px;transform:none;max-width:290px}}
@media (max-width:760px){#out{display:none}#ctl{width:250px}#head{max-width:70vw}}
</style>
</head>
<body>
<canvas id="view"></canvas>
<div class="panel" id="head">
<h1>Voxel utensil handles × articulated hand</h1>
<p class="sub">Geometric contact only — a rigid-pad kinematic proxy, not a comfort verdict.</p>
</div>
<div class="panel" id="ctl">
<h2>Handle geometry</h2>
<div class="grp" id="variantGrp">
<button data-v="voxelFine" class="on">Voxel 4×4</button>
<button data-v="voxelCoarse">Voxel 2×2</button>
<button data-v="smooth">Smooth ref.</button>
</div>
<p class="fine">All three share the same 36 × 36 mm envelope; only the surface decomposition differs.</p>
<h2 style="margin-top:14px">Gripping model</h2>
<div class="grp" id="modeGrp">
<button data-m="fit" class="on">Fit each handle</button>
<button data-m="fixed">One fixed hand pose</button>
</div>
<p class="fine" id="modeNote">Each handle is fitted independently to the same press-in target.</p>
<label class="lb">Press-in target <b><span id="pressV">1.5</span> mm</b></label>
<input type="range" id="press" min="0" max="4" step="0.1" value="1.5">
<label class="lb">Slice height Y <b><span id="sliceV">10</span> mm</b></label>
<input type="range" id="slice" min="-40" max="40" step="1" value="10">
<h2 style="margin-top:14px">Display</h2>
<div class="grp">
<button id="btnMarkers" class="on">Contacts</button>
<button id="btnCut">Cutaway</button>
<button id="btnSpin">Spin</button>
<button id="btnReset">Reset view</button>
</div>
<p class="fine">Drag = orbit · wheel = zoom · shift-drag / right-drag = pan.</p>
</div>
<div class="panel" id="out">
<h2>Active handle — measured contact</h2>
<dl id="detail"></dl>
<div class="legend"><span>shallow</span><div class="bar"></div><span>deep</span></div>
<h2 style="margin-top:14px">Comparison (same hand, same target)</h2>
<table id="cmp">
<thead><tr>
<th>Handle</th><th>Arc mm</th><th>Patches</th><th>Max mm</th><th>Gaps</th><th>Sharp %</th>
</tr></thead>
<tbody></tbody>
</table>
<p class="fine">
<b>Arc</b> = finger-surface length in contact · <b>Patches</b> = separate contact runs ·
<b>Max</b> = deepest press-in of the rigid pad · <b>Gaps</b> = contact breaks where a pad bridges a
corner · <b>Sharp</b> = share of contact samples whose nearest handle feature is a sharp corner.
</p>
<p class="fine warnb">
A rigid pad under-reports what a compliant finger would do: a sharp corner can dig into a soft pad and
concentrate local pressure far beyond what these numbers show.
</p>
</div>
<div class="panel" id="sl">
<h2>Horizontal section</h2>
<canvas id="sliceCv" width="304" height="236"></canvas>
<p class="fine">Handle cross-section (grey) with the finger pads (amber) at the selected height.</p>
</div>
<div class="panel" id="note">
<b>Scope:</b> this is a geometric contact demonstration using a simplified jointed hand model, a rigid
pad approximation and a uniform press-in target. It does not measure comfort, fit, safety or pressure.
Comfort depends on anatomy, material, temperature, task and personal preference — no geometry alone
establishes universal comfort.
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ============================================================ utilities */
const clamp=(v,a,b)=>v<a?a:(v>b?b:v);
const lerp=(a,b,t)=>a+(b-a)*t;
const wrapA=a=>{while(a>Math.PI)a-=2*Math.PI;while(a<-Math.PI)a+=2*Math.PI;return a;};
const $=id=>document.getElementById(id);
/* ====================================================== cross-sections */
/* A handle cross-section is a closed CCW polygon in the XZ plane with
per-edge tags ('flat' | 'round') and per-vertex tags ('sharp' | 'round'). */
function polyArea(p){let a=0;for(let i=0;i<p.length;i++){const q=p[i],r=p[(i+1)%p.length];a+=q.x*r.z-r.x*q.z;}return a/2;}
function makeSection(kind,pts,eTag,vTag){
const n=pts.length;
function inside(x,z){let c=false;for(let i=0,j=n-1;i<n;j=i++){
const a=pts[i],b=pts[j];
if((a.z>z)!==(b.z>z) && x < (b.x-a.x)*(z-a.z)/(b.z-a.z)+a.x) c=!c;} return c;}
function nearest(x,z){
let best={d:Infinity,px:0,pz:0,i:0,t:0};
for(let i=0;i<n;i++){
const a=pts[i],b=pts[(i+1)%n];
const dx=b.x-a.x,dz=b.z-a.z,L2=dx*dx+dz*dz;
let t=((x-a.x)*dx+(z-a.z)*dz)/L2; t=clamp(t,0,1);
const qx=a.x+dx*t,qz=a.z+dz*t,d=Math.hypot(x-qx,z-qz);
if(d<best.d) best={d,px:qx,pz:qz,i,t};
}
return best;
}
return {
kind,pts,eTag,vTag,
inside,nearest,
sdf(x,z){const q=nearest(x,z);q.s=inside(x,z)?-q.d:q.d;return q;},
feature(q){
const endpoint=q.t<1e-3||q.t>1-1e-3;
if(endpoint){const vi=(q.t>0.5?q.i+1:q.i)%n;return vTag[vi];}
return eTag[q.i];
}
};
}
/* rounded rectangle reference */
function roundedSection(hw,hh,r,arc=7){
const pts=[],ids=[],cx=hw-r,cz=hh-r;
const corners=[{cx,cz,a0:0},{cx:-cx,cz,a0:Math.PI/2},{cx:-cx,cz:-cz,a0:Math.PI},{cx,cz:-cz,a0:3*Math.PI/2}];
corners.forEach((c,ci)=>{for(let i=0;i<=arc;i++){const a=c.a0+i/arc*Math.PI/2;
pts.push({x:c.cx+r*Math.cos(a),z:c.cz+r*Math.sin(a)});ids.push(ci);}});
const eTag=[],vTag=[];
for(let i=0;i<pts.length;i++){const j=(i+1)%pts.length;
eTag.push(ids[i]===ids[j]?'round':'flat');vTag.push('round');}
return makeSection('smooth',pts,eTag,vTag);
}
/* voxel sections: staircase loops, flat faces, sharp corners */
const FINE_PTS=[{x:-9,z:-18},{x:9,z:-18},{x:9,z:-9},{x:18,z:-9},{x:18,z:9},{x:9,z:9},
{x:9,z:18},{x:-9,z:18},{x:-9,z:9},{x:-18,z:9},{x:-18,z:-9},{x:-9,z:-9}];
const COARSE_PTS=[{x:-18,z:-18},{x:18,z:-18},{x:18,z:18},{x:-18,z:18}];
function voxelSection(pts){const n=pts.length;
return makeSection('voxel',pts,Array(n).fill('flat'),Array(n).fill('sharp'));}
const VARIANTS={
voxelFine:{label:'Voxel 4×4 (9 mm cells)',short:'Voxel 4×4',section:voxelSection(FINE_PTS),
grid:4,cell:9,chamfer:true},
voxelCoarse:{label:'Voxel 2×2 (18 mm cells)',short:'Voxel 2×2',section:voxelSection(COARSE_PTS),
grid:2,cell:18,chamfer:false},
smooth:{label:'Smooth reference (R9)',short:'Smooth ref',section:roundedSection(18,18,9),
grid:0,cell:0}
};
/* ============================================== offset contour (pad path) */
function buildOffset(sec,off){
const p=sec.pts,n=p.length,out=[];
const outN=(d)=>({x:d.z,z:-d.x});
const dir=(a,b)=>{const dx=b.x-a.x,dz=b.z-a.z,L=Math.hypot(dx,dz);return{x:dx/L,z:dz/L};};
for(let i=0;i<n;i++){
const prev=p[(i-1+n)%n],v=p[i],next=p[(i+1)%n];
const d1=dir(prev,v),d2=dir(v,next),n1=outN(d1),n2=outN(d2);
const P1={x:v.x+n1.x*off,z:v.z+n1.z*off},P2={x:v.x+n2.x*off,z:v.z+n2.z*off};
const Ax=d1.x,Az=d1.z,Bx=-d2.x,Bz=-d2.z,Cx=P2.x-P1.x,Cz=P2.z-P1.z;
const den=Ax*Bz-Az*Bx;
if(Math.abs(den)<1e-9){out.push({x:v.x+(n1.x+n2.x)*.5*off,z:v.z+(n1.z+n2.z)*.5*off});continue;}
const s=(Cx*Bz-Cz*Bx)/den,t=(Ax*Cz-Az*Cx)/den;
if(s<-1e-6||t<-1e-6){out.push({x:P1.x,z:P1.z});out.push({x:P2.x,z:P2.z});continue;}
const P={x:P1.x+s*Ax,z:P1.z+s*Az};
if(Math.hypot(P.x-v.x,P.z-v.z)>3*off){out.push({x:P1.x,z:P1.z});out.push({x:P2.x,z:P2.z});continue;}
out.push(P);
}
return out;
}
function makePolyline(pts){
const segs=[];let total=0;
for(let i=0;i<pts.length;i++){
const a=pts[i],b=pts[(i+1)%pts.length],len=Math.hypot(b.x-a.x,b.z-a.z);
if(len<1e-6)continue;
segs.push({a,b,len,s0:total,tx:(b.x-a.x)/len,tz:(b.z-a.z)/len});total+=len;
}
return {segs,total};
}
function sampleAt(pl,s){
s=((s%pl.total)+pl.total)%pl.total;
let seg=pl.segs[0];
for(let i=0;i<pl.segs.length;i++){const g=pl.segs[i];if(s>=g.s0&&s<g.s0+g.len){seg=g;break;}
if(i===pl.segs.length-1)seg=g;}
const t=(s-seg.s0)/seg.len;
return {x:lerp(seg.a.x,seg.b.x,t),z:lerp(seg.a.z,seg.b.z,t),tx:seg.tx,tz:seg.tz};
}
/* ================================================== hand: joints & digits */
const GRIP_Y0=-45, GRIP_Y1=45;
const DIGITS=[
{name:'Index', base:{x:-52,y:30,z:-30}, lens:[34,22,17], r:7.0, preferN:{x:0,z:-1}},
{name:'Middle',base:{x:-52,y:10,z:-30}, lens:[38,26,19], r:7.2, preferN:{x:0,z:-1}},
{name:'Ring', base:{x:-52,y:-8,z:-30}, lens:[36,25,18], r:6.8, preferN:{x:0,z:-1}},
{name:'Pinky', base:{x:-52,y:-26,z:-30},lens:[30,20,15], r:6.0, preferN:{x:0,z:-1}},
{name:'Thumb', base:{x:-56,y:-40,z:-8}, lens:[34,22,16], r:8.0, preferN:{x:-1,z:0}}
];
function anglesFromPath(P){
const a1=Math.atan2(P[1].z-P[0].z,P[1].x-P[0].x);
const a2=Math.atan2(P[2].z-P[1].z,P[2].x-P[1].x);
const a3=Math.atan2(P[3].z-P[2].z,P[3].x-P[2].x);
return [wrapA(a1),wrapA(a2-a1),wrapA(a3-a2)];
}
function fkDigit(digit,ang){
const P=[{x:digit.base.x,z:digit.base.z}];let a=0;
for(let i=0;i<3;i++){a+=ang[i];const q=P[i];
P.push({x:q.x+Math.cos(a)*digit.lens[i],z:q.z+Math.sin(a)*digit.lens[i]});}
return {P,angles:ang};
}
/* fit one digit: place the proximal tip on the pad-offset contour, then let
the middle + distal phalanges wrap the contour. Joint angles come out of
the resulting path, which is what makes the hand "articulated". */
function fitDigit(sec,digit,press){
const off=Math.max(.6,digit.r-press);
const pl=makePolyline(buildOffset(sec,off));
const B={x:digit.base.x,z:digit.base.z},L1=digit.lens[0];
const S=360,SAMP=[];
for(let i=0;i<S;i++){const p=sampleAt(pl,i*pl.total/S);
SAMP.push({p,d:Math.hypot(p.x-B.x,p.z-B.z)});}
let best=null;
for(let i=0;i<S;i++){
const a=SAMP[(i-1+S)%S].d,b=SAMP[i].d,c=SAMP[(i+1)%S].d;
if(!((b<=a&&b<c)||(b>=a&&b>=c)))continue;
const cand={s:i*pl.total/S,d:b,p:SAMP[i].p};
const lenErr=Math.abs(cand.d-L1); if(lenErr>0.35*L1)continue;
for(const dir of [1,-1]){
const p1=sampleAt(pl,cand.s);
const P=[{x:B.x,z:B.z},{x:p1.x,z:p1.z},
sampleAt(pl,cand.s+dir*digit.lens[1]),
sampleAt(pl,cand.s+dir*(digit.lens[1]+digit.lens[2]))];
const ang=anglesFromPath(P);
const dg=r=>r*180/Math.PI;
const anat=Math.max(0,-dg(ang[1]))+Math.max(0,-dg(ang[2]))+.5*Math.max(0,-dg(ang[0]));
const nrm={x:p1.tz,z:-p1.tx};
const dot=clamp(nrm.x*digit.preferN.x+nrm.z*digit.preferN.z,-1,1);
const inc=Math.atan2(p1.z-B.z,p1.x-B.x);
let da=Math.abs(wrapA(Math.atan2(p1.tz,p1.tx)-inc));
if(dir<0)da=Math.abs(wrapA(Math.atan2(p1.tz,p1.tx)+Math.PI-inc));
const score=60*lenErr/L1+1.2*anat+22*(1-dot)+6*dg(da);
if(!best||score<best.score)best={score,ang,P};
}
}
if(!best){const P=[{x:B.x,z:B.z},{x:B.x+30,z:B.z},{x:B.x+50,z:B.z+8},{x:B.x+64,z:B.z+22}];
best={ang:anglesFromPath(P),P};}
return {P:best.P,angles:best.ang};
}
/* ================================================ contact measurement */
const TOL=0.15;
function measure(sec,poses){
const res={contactLen:0,patches:0,maxPress:0,meanPress:0,sharp:0,flat:0,round:0,gaps:0,markers:[]};
let pSum=0,pN=0;
for(let di=0;di<poses.length;di++){
const d=DIGITS[di],pose=poses[di],pts=[];
for(let s=0;s<3;s++){
const A=pose.P[s],B=pose.P[s+1],N=16;
for(let i=(s===0?0:1);i<=N;i++){
const t=i/N;
pts.push({x:lerp(A.x,B.x,t),z:lerp(A.z,B.z,t),y:d.base.y});
}
}
for(const p of pts){const q=sec.sdf(p.x,p.z);p.q=q;p.cl=q.s-d.r;}
let run=false,start=0;
const len=(i0,i1)=>{let L=0;for(let i=i0+1;i<=i1;i++)L+=Math.hypot(pts[i].x-pts[i-1].x,pts[i].z-pts[i-1].z);return L;};
for(let i=0;i<pts.length;i++){
const c=pts[i].cl<TOL;
if(c&&!run){run=true;start=i;res.patches++;}
else if(!c&&run){run=false;res.contactLen+=len(start,i-1);}
}
if(run)res.contactLen+=len(start,pts.length-1);
for(let i=1;i<pts.length;i++)if(pts[i-1].cl<TOL&&pts[i].cl>=TOL)res.gaps++;
for(let i=0;i<pts.length;i++){
const p=pts[i]; if(p.cl>=TOL)continue;
const press=Math.max(0,-p.cl);pSum+=press;pN++;
res.maxPress=Math.max(res.maxPress,press);
const f=sec.feature(p.q);
if(f==='sharp')res.sharp++;else if(f==='flat')res.flat++;else res.round++;
if(i%2===0&&res.markers.length<420){
const nx=p.x-p.q.px,nz=p.z-p.q.pz,L=Math.hypot(nx,nz)||1;
res.markers.push({x:p.q.px,y:p.y,z:p.q.pz,nx:nx/L,nz:nz/L,press,feature:f});
}
}
}
res.meanPress=pN?pSum/pN:0;
res.sharpPct=pN?100*res.sharp/pN:0;
res.flatPct=pN?100*res.flat/pN:0;
res.roundPct=pN?100*res.round/pN:0;
return res;
}
/* ============================================================ scene setup */
const canvas=$('view');
const renderer=new THREE.WebGLRenderer({canvas,antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio,2));
renderer.setSize(innerWidth,innerHeight);
renderer.shadowMap.enabled=true;
renderer.shadowMap.type=THREE.PCFSoftShadowMap;
renderer.localClippingEnabled=true;
renderer.toneMapping=THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure=1.05;
const scene=new THREE.Scene();
scene.background=new THREE.Color(0x080b10);
scene.fog=new THREE.Fog(0x080b10,700,1600);
const camera=new THREE.PerspectiveCamera(38,innerWidth/innerHeight,.5,4000);
const cam={az:-0.95,pol:1.16,dist:330,tx:-12,ty:6,tz:-14};
scene.add(new THREE.HemisphereLight(0x9fb6d8,0x141a22,.55));
const key=new THREE.DirectionalLight(0xffffff,1.15);key.position.set(150,230,170);
key.castShadow=true;key.shadow.mapSize.set(1024,1024);
key.shadow.camera.left=-230;key.shadow.camera.right=230;
key.shadow.camera.top=260;key.shadow.camera.bottom=-160;key.shadow.bias=-0.0012;
scene.add(key);
const rim=new THREE.DirectionalLight(0x6f9dff,.42);rim.position.set(-190,60,-140);scene.add(rim);
const grid=new THREE.GridHelper(900,45,0x2c394d,0x18202c);
grid.position.y=-78;grid.material.transparent=true;grid.material.opacity=.5;scene.add(grid);
/* ---------- utensils (shared shaft + bowl) ---------- */
const metal=new THREE.MeshStandardMaterial({color:0xb9c2cc,metalness:.85,roughness:.28});
const shaft=new THREE.Mesh(new THREE.CylinderGeometry(5.5,6.8,160,24),metal);
shaft.position.set(0,125,0);shaft.castShadow=true;scene.add(shaft);
const bowl=new THREE.Mesh(new THREE.SphereGeometry(1,40,28),metal);
bowl.scale.set(27,12,20);bowl.position.set(0,219,0);bowl.castShadow=true;scene.add(bowl);
/* ---------- handle (rebuilt per variant) ---------- */
const handleGroup=new THREE.Group();scene.add(handleGroup);
const clipPlane=new THREE.Plane(new THREE.Vector3(0,-1,0),10);
let handleMats=[];
function buildHandle(key){
while(handleGroup.children.length){const c=handleGroup.children.pop();c.geometry?.dispose();}
handleMats=[];
const v=VARIANTS[key];
if(v.grid>0){
const cells=[],cs=v.cell,half=v.grid*cs/2;
for(let i=0;i<v.grid;i++)for(let j=0;j<v.grid;j++){
if(v.chamfer&&((i===0||i===v.grid-1)&&(j===0||j===v.grid-1)))continue;
cells.push([i,j]);
}
const ny=Math.round((GRIP_Y1-GRIP_Y0)/cs);
const geo=new THREE.BoxGeometry(cs*.97,cs*.97,cs*.97);
const mat=new THREE.MeshStandardMaterial({color:0xd8a468,roughness:.62,metalness:.03});
const im=new THREE.InstancedMesh(geo,mat,cells.length*ny);
im.castShadow=true;im.receiveShadow=true;
const dummy=new THREE.Object3D();let n=0;
for(const [i,j] of cells)for(let k=0;k<ny;k++){
dummy.position.set(-half+(i+.5)*cs,GRIP_Y0+(k+.5)*cs,-half+(j+.5)*cs);
dummy.updateMatrix();im.setMatrixAt(n,dummy.matrix);
const tint=.86+((i*7+j*13+k*5)%9)/34;
im.setColorAt(n,new THREE.Color(0xd8a468).multiplyScalar(tint));n++;
}
im.instanceMatrix.needsUpdate=true;if(im.instanceColor)im.instanceColor.needsUpdate=true;
handleGroup.add(im);handleMats.push(mat);
}else{
const geo=prismGeo(v.section.pts,GRIP_Y0,GRIP_Y1);
const mat=new THREE.MeshStandardMaterial({color:0x7fc4d8,roughness:.45,metalness:.08,side:THREE.DoubleSide});
const m=new THREE.Mesh(geo,mat);m.castShadow=true;m.receiveShadow=true;handleGroup.add(m);handleMats.push(mat);
}
}
function prismGeo(pts,y0,y1){
const n=pts.length,pos=[],idx=[];
let cx=0,cz=0;pts.forEach(p=>{cx+=p.x;cz+=p.z;});cx/=n;cz/=n;
for(let i=0;i<n;i++){
const a=pts[i],b=pts[(i+1)%n],base=pos.length/3;
pos.push(a.x,y0,a.z,b.x,y0,b.z,b.x,y1,b.z,a.x,y1,a.z);
idx.push(base,base+1,base+2,base,base+2,base+3);
}
for(const y of [y0,y1]){
const c=pos.length/3;pos.push(cx,y,cz);
for(let i=0;i<n;i++)pos.push(pts[i].x,y,pts[i].z);
for(let i=0;i<n;i++){
const a=c+1+i,b=c+1+(i+1)%n;
if(y===y0)idx.push(c,a,b);else idx.push(c,b,a);
}
}
const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));
g.setIndex(idx);g.computeVertexNormals();return g;
}
/* ---------- articulated hand meshes ---------- */
const handGroup=new THREE.Group();scene.add(handGroup);
const handMat=new THREE.MeshStandardMaterial({color:0xc6ccd6,roughness:.82,metalness:.03});
const jointMat=new THREE.MeshStandardMaterial({color:0x7f8896,roughness:.62});
const palm=new THREE.Mesh(new THREE.BoxGeometry(44,92,26),handMat);
palm.position.set(-74,0,-43);palm.castShadow=true;palm.receiveShadow=true;handGroup.add(palm);
const wrist=new THREE.Mesh(new THREE.CylinderGeometry(17,20,34,24),handMat);
wrist.rotation.z=Math.PI/2;wrist.position.set(-113,0,-43);wrist.castShadow=true;handGroup.add(wrist);
const knuckle=new THREE.Mesh(new THREE.SphereGeometry(11,20,14),handMat);
knuckle.position.set(-54,0,-34);knuckle.castShadow=true;handGroup.add(knuckle);
const fingerMeshes=[],jointMeshes=[];
DIGITS.forEach((d,di)=>{
const arr=[];
for(let s=0;s<3;s++){
const m=new THREE.Mesh(new THREE.CapsuleGeometry(d.r,1,6,18),handMat);
m.castShadow=true;handGroup.add(m);arr.push(m);
}
fingerMeshes.push(arr);
for(let s=1;s<3;s++){
const j=new THREE.Mesh(new THREE.SphereGeometry(d.r*.95,20,14),jointMat);
j.castShadow=true;handGroup.add(j);jointMeshes.push({di,s,mesh:j});
}
});
/* ---------- contact markers ---------- */
const MAXM=440;
const markMesh=new THREE.InstancedMesh(new THREE.SphereGeometry(1.9,14,10),
new THREE.MeshBasicMaterial({toneMapped:false}),MAXM);
markMesh.count=0;markMesh.frustumCulled=false;scene.add(markMesh);
const lineGeo=new THREE.BufferGeometry();
lineGeo.setAttribute('position',new THREE.Float32BufferAttribute(new Float32Array(MAXM*6),3));
lineGeo.setAttribute('color',new THREE.Float32BufferAttribute(new Float32Array(MAXM*6),3));
const lines=new THREE.LineSegments(lineGeo,new THREE.LineBasicMaterial({vertexColors:true,toneMapped:false}));
lines.frustumCulled=false;scene.add(lines);
function pressColor(p){
const stops=[[0,.373,.702,.999],[1,.341,.851,.541],[2.2,1,.745,.333],[3.6,1,.365,.365]];
let i=0;while(i<stops.length-2&&p>stops[i+1][0])i++;
const a=stops[i],b=stops[i+1],t=clamp((p-a[0])/(b[0]-a[0]),0,1);
return new THREE.Color(lerp(a[1],b[1],t),lerp(a[2],b[2],t),lerp(a[3],b[3],t));
}
/* ============================================================== state */
const state={variant:'voxelFine',mode:'fit',press:1.5,sliceY:10,markers:true,cut:false,spin:false};
let poses={},metrics={},activeMarkers=[];
function recompute(){
const fit=k=>DIGITS.map(d=>fitDigit(VARIANTS[k].section,d,state.press));
if(state.mode==='fit'){
for(const k of Object.keys(VARIANTS))poses[k]=fit(k);
}else{
const ref=fit('smooth').map((f,i)=>fkDigit(DIGITS[i],f.angles));
for(const k of Object.keys(VARIANTS))poses[k]=ref.map((f,i)=>fkDigit(DIGITS[i],f.angles));
}
for(const k of Object.keys(VARIANTS))metrics[k]=measure(VARIANTS[k].section,poses[k]);
activeMarkers=metrics[state.variant].markers;
refreshHand();refreshMarkers();updateReadout();drawSlice();
}
function refreshHand(){
const pose=poses[state.variant];
for(let di=0;di<pose.length;di++){
const d=DIGITS[di],p=pose[di];
for(let s=0;s<3;s++){
const A=p.P[s],B=p.P[s+1];
const len=Math.hypot(B.x-A.x,B.z-A.z);
const mesh=fingerMeshes[di][s];
mesh.geometry.dispose();
mesh.geometry=new THREE.CapsuleGeometry(d.r,Math.max(2,len),6,18);
mesh.position.set((A.x+B.x)/2,d.base.y,(A.z+B.z)/2);
const dir=new THREE.Vector3(B.x-A.x,0,B.z-A.z).normalize();
mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),dir);
}
for(let s=1;s<3;s++){
const j=jointMeshes.find(o=>o.di===di&&o.s===s);
j.mesh.position.set(p.P[s].x,d.base.y,p.P[s].z);
}
}
}
function refreshMarkers(){
const pos=lineGeo.attributes.position.array,col=lineGeo.attributes.color.array;
const dummy=new THREE.Object3D();let n=0;
if(state.markers){
for(const m of activeMarkers){
dummy.position.set(m.x,m.y,m.z);
dummy.scale.setScalar(1+m.press*.28);dummy.updateMatrix();
markMesh.setMatrixAt(n,dummy.matrix);
markMesh.setColorAt(n,pressColor(m.press));
const o=n*6;
pos[o]=m.x;pos[o+1]=m.y;pos[o+2]=m.z;
pos[o+3]=m.x+m.nx*(m.press+3);pos[o+4]=m.y;pos[o+5]=m.z+m.nz*(m.press+3);
const c=pressColor(m.press);
col[o]=c.r;col[o+1]=c.g;col[o+2]=c.b;col[o+3]=c.r;col[o+4]=c.g;col[o+5]=c.b;
n++;if(n>=MAXM)break;
}
}
markMesh.count=n;markMesh.instanceMatrix.needsUpdate=true;
if(markMesh.instanceColor)markMesh.instanceColor.needsUpdate=true;
lineGeo.attributes.position.needsUpdate=true;lineGeo.attributes.color.needsUpdate=true;
lines.visible=state.markers;
}
/* ============================================================= readout */
function updateReadout(){
const m=metrics[state.variant];
const rows=[
['Contact arc length',m.contactLen.toFixed(0)+' mm'],
['Contact patches',String(m.patches)],
['Max press-in (rigid pad)',m.maxPress.toFixed(2)+' mm'],
['Mean press-in',m.meanPress.toFixed(2)+' mm'],
['Corner bridge gaps',String(m.gaps)],
['Sharp-corner contact',m.sharpPct.toFixed(0)+' %'],
['Flat-face contact',m.flatPct.toFixed(0)+' %'],
['Rounded-surface contact',m.roundPct.toFixed(0)+' %']
];
$('detail').innerHTML=rows.map(r=>`<dt>${r[0]}</dt><dd>${r[1]}</dd>`).join('');
const tb=$('cmp').querySelector('tbody');
tb.innerHTML=Object.keys(VARIANTS).map(k=>{
const q=metrics[k];
return `<tr class="${k===state.variant?'sel':''}"><td>${VARIANTS[k].short}</td>
<td>${q.contactLen.toFixed(0)}</td><td>${q.patches}</td><td>${q.maxPress.toFixed(2)}</td>
<td>${q.gaps}</td><td>${q.sharpPct.toFixed(0)}</td></tr>`;
}).join('');
$('modeNote').textContent=state.mode==='fit'
?'Each handle is fitted independently to the same press-in target.'
:'One pose (fitted on the smooth reference) is applied to all three handles.';
}
/* ======================================================== 2-D section */
const sliceCv=$('sliceCv'),sctx=sliceCv.getContext('2d');
function drawSlice(){
const W=sliceCv.width,H=sliceCv.height,R=44;
const map=(x,z)=>[W/2+x/R*(W/2-14),H/2+z/R*(H/2-14)];
sctx.clearRect(0,0,W,H);
sctx.fillStyle='rgba(255,255,255,.02)';sctx.fillRect(0,0,W,H);
const sec=VARIANTS[state.variant].section;
sctx.beginPath();sec.pts.forEach((p,i)=>{const q=map(p.x,p.z);i?sctx.lineTo(q[0],q[1]):sctx.moveTo(q[0],q[1]);});
sctx.closePath();sctx.fillStyle='rgba(130,150,180,.20)';sctx.fill();
sctx.strokeStyle='rgba(205,220,240,.75)';sctx.lineWidth=1.3;sctx.stroke();
const pose=poses[state.variant];
for(let di=0;di<DIGITS.length;di++){
const d=DIGITS[di];if(Math.abs(d.base.y-state.sliceY)>7)continue;
const p=pose[di];
sctx.beginPath();p.P.forEach((q,i)=>{const m=map(q.x,q.z);i?sctx.lineTo(m[0],m[1]):sctx.moveTo(m[0],m[1]);});
sctx.strokeStyle='rgba(255,190,85,.85)';sctx.lineWidth=2;sctx.stroke();
for(const q of p.P){const m=map(q.x,q.z);
sctx.beginPath();sctx.arc(m[0],m[1],d.r/R*(W/2-14),0,Math.PI*2);
sctx.strokeStyle='rgba(255,190,85,.35)';sctx.lineWidth=1;sctx.stroke();}
}
for(const m of activeMarkers){
if(Math.abs(m.y-state.sliceY)>7)continue;
const q=map(m.x,m.z),c=pressColor(m.press);
sctx.beginPath();sctx.arc(q[0],q[1],3.1,0,Math.PI*2);
sctx.fillStyle='#'+c.getHexString();sctx.fill();
}
sctx.fillStyle='rgba(140,158,182,.9)';sctx.font='10px ui-monospace,monospace';
sctx.fillText('y = '+state.sliceY+' mm',10,H-8);
}
/* ============================================================== controls */
$('variantGrp').addEventListener('click',e=>{
const b=e.target.closest('button');if(!b)return;
state.variant=b.dataset.v;
[...$('variantGrp').children].forEach(c=>c.classList.toggle('on',c===b));
buildHandle(state.variant);applyClip();recompute();
});
$('modeGrp').addEventListener('click',e=>{
const b=e.target.closest('button');if(!b)return;
state.mode=b.dataset.m;
[...$('modeGrp').children].forEach(c=>c.classList.toggle('on',c===b));
recompute();
});
$('press').addEventListener('input',e=>{state.press=+e.target.value;$('pressV').textContent=state.press.toFixed(1);recompute();});
$('slice').addEventListener('input',e=>{state.sliceY=+e.target.value;$('sliceV').textContent=state.sliceY;applyClip();drawSlice();});
$('btnMarkers').addEventListener('click',e=>{state.markers=!state.markers;e.target.classList.toggle('on',state.markers);refreshMarkers();});
$('btnCut').addEventListener('click',e=>{state.cut=!state.cut;e.target.classList.toggle('on',state.cut);applyClip();});
$('btnSpin').addEventListener('click',e=>{state.spin=!state.spin;e.target.classList.toggle('on',state.spin);});
$('btnReset').addEventListener('click',()=>{cam.az=-.95;cam.pol=1.16;cam.dist=330;cam.tx=-12;cam.ty=6;cam.tz=-14;});
function applyClip(){
clipPlane.constant=state.sliceY;
const all=[...handleMats,handMat,jointMat];
all.forEach(m=>{m.clippingPlanes=state.cut?[clipPlane]:null;m.needsUpdate=true;});
}
/* camera: implemented directly (no addons) */
let drag=null;
canvas.addEventListener('contextmenu',e=>e.preventDefault());
canvas.addEventListener('pointerdown',e=>{
drag={x:e.clientX,y:e.clientY,pan:e.button===2||e.shiftKey};canvas.setPointerCapture(e.pointerId);});
canvas.addEventListener('pointerup',e=>{drag=null;});
canvas.addEventListener('pointercancel',()=>{drag=null;});
canvas.addEventListener('pointermove',e=>{
if(!drag)return;
const dx=e.clientX-drag.x,dy=e.clientY-drag.y;drag.x=e.clientX;drag.y=e.clientY;
if(drag.pan){
const right=new THREE.Vector3().setFromMatrixColumn(camera.matrix,0);
const up=new THREE.Vector3().setFromMatrixColumn(camera.matrix,1);
const k=cam.dist*0.0016;
cam.tx-=right.x*dx*k+up.x*dy*k;cam.ty-=right.y*dx*k+up.y*dy*k;cam.tz-=right.z*dx*k+up.z*dy*k;
}else{
cam.az-=dx*0.0062;
cam.pol=clamp(cam.pol-dy*0.0062,0.16,2.92);
}
});
canvas.addEventListener('wheel',e=>{e.preventDefault();cam.dist=clamp(cam.dist*Math.exp(e.deltaY*0.0011),90,1100);},{passive:false});
addEventListener('resize',()=>{
camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();
renderer.setSize(innerWidth,innerHeight);});
/* ================================================================ loop */
const clock=new THREE.Clock();
function animate(){
requestAnimationFrame(animate);
const dt=clock.getDelta();
if(state.spin&&!drag)cam.az+=dt*0.16;
const target=new THREE.Vector3(cam.tx,cam.ty,cam.tz);
camera.position.set(
target.x+cam.dist*Math.sin(cam.pol)*Math.cos(cam.az),
target.y+cam.dist*Math.cos(cam.pol),
target.z+cam.dist*Math.sin(cam.pol)*Math.sin(cam.az));
camera.lookAt(target);
renderer.render(scene,camera);
}
buildHandle(state.variant);
applyClip();
recompute();
animate();
</script>
</body>
</html>
```