artificial_muscle_sim

Live ↗ZIP (lokal ausführbar)
Beschreibung

Web-based prototype for designing and simulating a flexible lattice structure with a muscle-like shape. The form is built from capsule and sphere blobs that are blended into one surface with a smooth union, and the surface is generated with Surface Nets. The lattice inside the body is defined by three parameters per point: cell type, cell size and strut thickness, which set relative stiffness, density and densification behaviour. These parameters are stored in a voxel field and can be painted onto the surface or into the interior with a brush, so stiffness can vary across the body. The simulation converts the voxel field into a tetrahedral mesh and solves it with XPBD, with pinned areas, drag forces, gravity and strain colouring. A section plane shows the inside, and a small inspector shows a unit cell and its estimated stiffness for the current material. The prototype is meant for design exploration of graded lattice parts, for teaching the relation between cell geometry and stiffness, and as a starting point for further tools or 3D printing tests.

  • Version: v0.1
  • Blob-based body from capsules and spheres with adjustable blend radius
  • Lattice parameters cell type, cell size and strut thickness per blob and per painted region
  • Voxel paint field with three channels, brush depth and erase mode
  • Section plane with painted cross-section view
  • Tetrahedral XPBD simulation with pins, drag force, gravity and damping
  • Strain, structure and stiffness colour modes with legend
  • Unit cell inspector with estimated effective stiffness per material
  • Tech: Three.js r160, WebGL, JavaScript modules, import map, CDN
  • Requires: WebGL-capable browser, internet connection for Three.js from a CDN
index.html
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>FLEX:LATTICE v0.1</title>
<style>
  :root{--line:#e6e6e6;--txt:#1a1a1a;--mute:#8a8a8a;--acc:#1a1a1a;}
  *{box-sizing:border-box;margin:0;padding:0}
  html,body{height:100%;background:#fff;color:var(--txt);font:12px/1.35 system-ui,-apple-system,"Segoe UI",Helvetica,Arial,sans-serif;overflow:hidden}
  #view{position:fixed;inset:0}
  #view canvas{display:block;width:100%;height:100%;touch-action:none}
  header{position:fixed;top:0;left:0;right:0;height:48px;display:flex;align-items:center;gap:24px;padding:0 18px;border-bottom:1px solid var(--line);background:rgba(255,255,255,.92);backdrop-filter:blur(6px);z-index:5}
  .brand{font-weight:600;letter-spacing:.14em;font-size:12px}
  .brand span{color:var(--mute);font-weight:400;margin-left:6px;letter-spacing:.05em}
  nav{display:flex;gap:2px;margin-left:auto;margin-right:auto}
  nav button{border:0;background:none;padding:8px 14px;font:inherit;letter-spacing:.12em;text-transform:uppercase;font-size:11px;color:var(--mute);cursor:pointer;border-bottom:1.5px solid transparent}
  nav button.on{color:var(--txt);border-bottom-color:var(--txt)}
  .mat{display:flex;align-items:center;gap:8px}
  .mat label{color:var(--mute);font-size:10px;letter-spacing:.12em;text-transform:uppercase}
  select{font:inherit;border:1px solid var(--line);background:#fff;padding:5px 8px;border-radius:3px;color:var(--txt)}
  aside{position:fixed;top:48px;right:0;bottom:0;width:286px;border-left:1px solid var(--line);background:rgba(255,255,255,.94);backdrop-filter:blur(6px);overflow-y:auto;z-index:4;padding:6px 0 30px}
  aside section{display:none}
  aside section.on{display:block}
  .grp{padding:12px 18px;border-bottom:1px solid var(--line)}
  .grp h3{font-size:10px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;margin-bottom:10px;color:var(--txt)}
  .row{display:flex;align-items:center;gap:8px;margin:7px 0}
  .row .lab{width:78px;color:var(--mute);flex:none}
  .row .val{width:62px;text-align:right;flex:none;font-variant-numeric:tabular-nums}
  input[type=range]{-webkit-appearance:none;appearance:none;flex:1;height:18px;background:transparent;min-width:0}
  input[type=range]::-webkit-slider-runnable-track{height:1px;background:#cfcfcf}
  input[type=range]::-moz-range-track{height:1px;background:#cfcfcf}
  input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:11px;height:11px;border-radius:50%;background:#111;margin-top:-5px;border:0}
  input[type=range]::-moz-range-thumb{width:11px;height:11px;border-radius:50%;background:#111;border:0}
  .btns{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
  .b{border:1px solid var(--line);background:#fff;padding:6px 10px;border-radius:3px;font:inherit;cursor:pointer;color:var(--txt)}
  .b:hover{border-color:#bbb}
  .b.on{background:#111;color:#fff;border-color:#111}
  .seg{display:flex;border:1px solid var(--line);border-radius:3px;overflow:hidden;flex:1}
  .seg button{flex:1;border:0;background:#fff;padding:6px 4px;font:inherit;cursor:pointer;color:var(--mute);border-right:1px solid var(--line)}
  .seg button:last-child{border-right:0}
  .seg button.on{background:#111;color:#fff}
  .chip{width:26px;height:26px;border-radius:50%;border:1px solid var(--line);background:#fff;cursor:pointer;font:inherit;font-weight:600;color:#bbb}
  .chip.on.r{background:#e8505b;border-color:#e8505b;color:#fff}
  .chip.on.g{background:#3bb273;border-color:#3bb273;color:#fff}
  .chip.on.bl{background:#3d7be0;border-color:#3d7be0;color:#fff}
  .note{color:var(--mute);font-size:11px;margin-top:6px}
  #insp{position:fixed;left:16px;bottom:16px;width:236px;background:rgba(255,255,255,.94);border:1px solid var(--line);border-radius:4px;z-index:4}
  #cellCanvas{display:block;width:236px;height:150px;border-bottom:1px solid var(--line)}
  #inspText{padding:10px 12px;font-variant-numeric:tabular-nums}
  #inspText .r{display:flex;justify-content:space-between;margin:2px 0}
  #inspText .k{color:var(--mute);letter-spacing:.08em;font-size:10px;text-transform:uppercase}
  #inspText .t{font-size:10px;letter-spacing:.14em;text-transform:uppercase;font-weight:600;margin-bottom:6px}
  #hud{position:fixed;left:268px;bottom:18px;color:var(--mute);z-index:4;font-variant-numeric:tabular-nums;white-space:pre}
  #hint{position:fixed;left:50%;transform:translateX(-50%);top:58px;color:var(--mute);z-index:3;font-size:11px;background:rgba(255,255,255,.85);padding:3px 10px;border-radius:3px;pointer-events:none}
  #legend{position:fixed;left:268px;bottom:58px;z-index:4;display:none;align-items:center;gap:8px;color:var(--mute);font-size:10px}
  #legend .bar{width:140px;height:6px;border-radius:3px}
</style>
</head>
<body>
<div id="view"><canvas id="c"></canvas></div>
<header>
  <div class="brand">FLEX:LATTICE<span>v0.1</span></div>
  <nav id="tabs">
    <button data-mode="form" class="on">Form</button>
    <button data-mode="struct">Struktur</button>
    <button data-mode="sim">Simulation</button>
  </nav>
  <div class="mat"><label>Material</label><select id="matSel"></select></div>
</header>
<aside id="panel">
  <section data-panel="form" class="on"></section>
  <section data-panel="struct"></section>
  <section data-panel="sim"></section>
</aside>
<div id="insp"><canvas id="cellCanvas" width="472" height="300"></canvas><div id="inspText"></div></div>
<div id="legend"><span id="legL"></span><div class="bar" id="legBar"></div><span id="legR"></span></div>
<div id="hud"></div>
<div id="hint"></div>

<script type="importmap">
{"imports":{
  "three":"https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
  "three/addons/":"https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
}}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { TransformControls } from 'three/addons/controls/TransformControls.js';

/*CORE_BEGIN*/
// =====================================================================
//  KERN — reine Logik, kein DOM, kein THREE
//  Einheiten: mm, g, s  →  Kraft in µN, Steifigkeit E in µN/mm² (= MPa·1e6)
// =====================================================================

// --- Gittertypen (R-Kanal 0→1: weich → steif) ------------------------------
// E_rel = A · (p/x)^n   — BCC kalibriert an Yoshimura et al. 2026:
//   (x=15, p=2) → ~0.015 MPa · (x≈7) → ~0.8 MPa · p 1.5→3 mm ≈ ×28–37
// Andere Typen: heuristisch (biegedominiert ↔ streckdominiert).
const TYPES = [
  { name:'Diamant',     A:20,  n:5.6, rho:5.44, volF:0.05, dens:1.00 },
  { name:'BCC · Paper', A:60,  n:5.2, rho:5.44, volF:0.10, dens:1.00 },
  { name:'Kubisch',     A:1.0, n:2.6, rho:2.36, volF:0.15, dens:0.95 },
  { name:'Oktett',      A:1.5, n:2.2, rho:10.0, volF:0.30, dens:0.90 },
];
// --- FDM-druckbare Flex-Materialien (E Festkörper, Richtwerte) -------------
const MATERIALS = [
  { name:'TPU 98A', E:20,  damp:0.7, note:'sehr fest' },
  { name:'TPU 95A', E:8.6, damp:0.8, note:'Referenz Paper (7.4–9.8 MPa gemessen)' },
  { name:'TPU 90A', E:5.5, damp:1.0, note:'' },
  { name:'TPU 85A', E:3.5, damp:1.3, note:'' },
  { name:'TPE 80A', E:2.4, damp:1.6, note:'' },
  { name:'TPE 70A', E:1.5, damp:2.0, note:'' },
  { name:'TPE 60A', E:0.9, damp:2.6, note:'Ultra-Soft, schwer druckbar' },
];
const DENS_SOLID = 1.2e-3;            // g/mm³
const ST = { blobs:[], K:12, stepped:false };

function clamp(v,a,b){ return v<a?a:v>b?b:v; }
function cellSize(d){ return 20 - 15*d; }   // G: 20 mm (weich) → 5 mm (dicht)
function strutD(b){ return 1 + 2*b; }       // B: 1 → 3 mm

function lattice(t,d,b,stepped){
  const x = cellSize(d), p = strutD(b), r = Math.min(p/x, 0.7);
  let ft = clamp(t,0,1)*3; if(stepped || Math.abs(ft-Math.round(ft))<0.025) ft = Math.round(ft);
  let i = Math.floor(ft); if(i>2) i=2; const f = ft-i;
  const A = TYPES[i], B = TYPES[i+1];
  const eA = clamp(A.A*Math.pow(r,A.n), 2e-5, 0.6), eB = clamp(B.A*Math.pow(r,B.n), 2e-5, 0.6);
  const Erel = Math.exp(Math.log(eA)*(1-f) + Math.log(eB)*f);
  const rho = Math.min(0.9, (A.rho*(1-f)+B.rho*f)*r*r);
  const volF = A.volF*(1-f)+B.volF*f;
  const epsD = clamp(0.75*(1-2*r)*(A.dens*(1-f)+B.dens*f), 0.04, 0.8);
  return { x, p, r, Erel, rho, volF, epsD, ti:i, tf:f, main: f<0.5?i:i+1 };
}

// --- Blobs: Kapsel-SDF (Kugel = Kapsel mit Länge 0), smooth union ----------
function sdBlob(B,x,y,z){
  const dx=x-B.cx, dy=y-B.cy, dz=z-B.cz;
  let h = dx*B.ax+dy*B.ay+dz*B.az; if(h>B.half) h=B.half; else if(h<-B.half) h=-B.half;
  const qx=dx-B.ax*h, qy=dy-B.ay*h, qz=dz-B.az*h;
  return Math.sqrt(qx*qx+qy*qy+qz*qz) - B.r;
}
function sdf(x,y,z){
  const bl=ST.blobs, K=ST.K; if(!bl.length) return 1e9;
  let d = sdBlob(bl[0],x,y,z);
  for(let i=1;i<bl.length;i++){
    const e = sdBlob(bl[i],x,y,z);
    if(K>1e-6){ const h=Math.max(K-Math.abs(d-e),0)/K; d=Math.min(d,e)-h*h*K*0.25; }
    else d=Math.min(d,e);
  }
  return d;
}
function sdfGrad(x,y,z,o){
  const e=0.4;
  let gx=sdf(x+e,y,z)-sdf(x-e,y,z), gy=sdf(x,y+e,z)-sdf(x,y-e,z), gz=sdf(x,y,z+e)-sdf(x,y,z-e);
  const l=Math.hypot(gx,gy,gz)||1; o[0]=gx/l; o[1]=gy/l; o[2]=gz/l; return o;
}
const _sd = new Float64Array(256);
function blobBlend(x,y,z,o){
  const bl=ST.blobs, n=bl.length; let m=1e9, mi=0;
  for(let i=0;i<n;i++){ const s=sdBlob(bl[i],x,y,z); _sd[i]=s; if(s<m){m=s;mi=i;} }
  const tau=Math.max(ST.K*0.5,2);
  let W=0,t=0,d=0,b=0,s=0;
  for(let i=0;i<n;i++){ const w=Math.exp(-(_sd[i]-m)/tau); W+=w; t+=w*bl[i].t; d+=w*bl[i].d; b+=w*bl[i].b; s+=w*bl[i].s; }
  o.t=t/W; o.d=d/W; o.b=b/W; o.s=s/W;
  o.fx=bl[mi].ax; o.fy=bl[mi].ay; o.fz=bl[mi].az; o.dom=mi;
  return o;
}

// --- Bemalung: Voxelfeld im Weltraum, 3 Kanäle, vormultipliziert ----------
const PG = { min:-160, h:5, n:64 };
const PN = PG.n*PG.n*PG.n;
const PV = new Float32Array(PN*3), PA = new Float32Array(PN*3);
function clearPaint(){ PV.fill(0); PA.fill(0); }
function sampleParams(x,y,z,o){
  blobBlend(x,y,z,o);
  const n=PG.n, gx=(x-PG.min)/PG.h, gy=(y-PG.min)/PG.h, gz=(z-PG.min)/PG.h;
  const i0=Math.floor(gx), j0=Math.floor(gy), k0=Math.floor(gz);
  o.pa0=o.pa1=o.pa2=0;
  if(i0<0||j0<0||k0<0||i0>=n-1||j0>=n-1||k0>=n-1) return o;
  const fx=gx-i0, fy=gy-j0, fz=gz-k0;
  let a0=0,a1=0,a2=0,v0=0,v1=0,v2=0;
  for(let c=0;c<8;c++){
    const di=c&1, dj=(c>>1)&1, dk=c>>2;
    const w=(di?fx:1-fx)*(dj?fy:1-fy)*(dk?fz:1-fz); if(w<=0) continue;
    const id=((i0+di)+n*((j0+dj)+n*(k0+dk)))*3;
    a0+=w*PA[id]; a1+=w*PA[id+1]; a2+=w*PA[id+2];
    v0+=w*PV[id]; v1+=w*PV[id+1]; v2+=w*PV[id+2];
  }
  if(a0>1e-5){ const a=Math.min(a0,1); o.t=o.t*(1-a)+(v0/a0)*a; }
  if(a1>1e-5){ const a=Math.min(a1,1); o.d=o.d*(1-a)+(v1/a1)*a; }
  if(a2>1e-5){ const a=Math.min(a2,1); o.b=o.b*(1-a)+(v2/a2)*a; }
  o.pa0=a0; o.pa1=a1; o.pa2=a2;
  return o;
}
// Pinsel: Oberfläche (nx..nz = Außennormale, Zylinder nach innen bis Tiefe D)
// oder Kugel (nx===null, z.B. auf der Schnittfläche)
function paintDab(px,py,pz,nx,ny,nz,R,D,flow,tgt,mask,erase){
  const n=PG.n, h=PG.h, sphere = nx===null;
  const De = Math.max(D, h*1.2);
  const ext = (sphere?R:Math.max(R,De)) + h;
  const i0=Math.max(0,Math.floor((px-ext-PG.min)/h)), i1=Math.min(n-1,Math.ceil((px+ext-PG.min)/h));
  const j0=Math.max(0,Math.floor((py-ext-PG.min)/h)), j1=Math.min(n-1,Math.ceil((py+ext-PG.min)/h));
  const k0=Math.max(0,Math.floor((pz-ext-PG.min)/h)), k1=Math.min(n-1,Math.ceil((pz+ext-PG.min)/h));
  for(let k=k0;k<=k1;k++) for(let j=j0;j<=j1;j++) for(let i=i0;i<=i1;i++){
    const vx=PG.min+i*h-px, vy=PG.min+j*h-py, vz=PG.min+k*h-pz;
    let f;
    if(sphere){
      const q=Math.sqrt(vx*vx+vy*vy+vz*vz)/R; if(q>=1) continue; f=(1-q*q); f*=f;
    } else {
      const along = -(vx*nx+vy*ny+vz*nz);
      if(along < -R*0.5 || along > De) continue;
      const lx=vx+nx*along, ly=vy+ny*along, lz=vz+nz*along;
      const q=Math.sqrt(lx*lx+ly*ly+lz*lz)/R; if(q>=1) continue;
      f=(1-q*q); f*=f;
      const zz=along/De; if(zz>0.7) f*=Math.max(0,(1-zz)/0.3);
    }
    const s=f*flow; if(s<=0) continue;
    const id=(i+n*(j+n*k))*3;
    for(let c=0;c<3;c++){
      if(!mask[c]) continue;
      if(erase){ PA[id+c]*=1-s; PV[id+c]*=1-s; }
      else { PV[id+c]=PV[id+c]*(1-s)+tgt[c]*s; PA[id+c]=PA[id+c]*(1-s)+s; }
    }
  }
  return ext;
}

// --- Surface Nets ----------------------------------------------------------
function surfaceNets(b0,b1,cell){
  const nx=Math.max(2,Math.ceil((b1[0]-b0[0])/cell)+1), ny=Math.max(2,Math.ceil((b1[1]-b0[1])/cell)+1), nz=Math.max(2,Math.ceil((b1[2]-b0[2])/cell)+1);
  const F=new Float32Array(nx*ny*nz);
  for(let k=0;k<nz;k++) for(let j=0;j<ny;j++) for(let i=0;i<nx;i++)
    F[i+nx*(j+ny*k)] = sdf(b0[0]+i*cell, b0[1]+j*cell, b0[2]+k*cell);
  const cx=nx-1, cy=ny-1, cz=nz-1;
  const CV=new Int32Array(cx*cy*cz).fill(-1);
  const pos=[]; const g=new Float32Array(8);
  const EA=[0,2,4,6,0,1,4,5,0,1,2,3], EB=[1,3,5,7,2,3,6,7,4,5,6,7];
  for(let k=0;k<cz;k++) for(let j=0;j<cy;j++) for(let i=0;i<cx;i++){
    let mask=0;
    for(let c=0;c<8;c++){ const v=F[(i+(c&1))+nx*((j+((c>>1)&1))+ny*(k+(c>>2)))]; g[c]=v; if(v<0) mask|=1<<c; }
    if(mask===0||mask===255) continue;
    let sx=0,sy=0,sz=0,cnt=0;
    for(let e=0;e<12;e++){
      const a=EA[e], b=EB[e];
      if((g[a]<0)!==(g[b]<0)){
        const t=g[a]/(g[a]-g[b]);
        const ax=a&1, ay=(a>>1)&1, az=a>>2, bx=b&1, by=(b>>1)&1, bz=b>>2;
        sx+=ax+(bx-ax)*t; sy+=ay+(by-ay)*t; sz+=az+(bz-az)*t; cnt++;
      }
    }
    CV[i+cx*(j+cy*k)] = pos.length/3;
    pos.push(b0[0]+(i+sx/cnt)*cell, b0[1]+(j+sy/cnt)*cell, b0[2]+(k+sz/cnt)*cell);
  }
  const idx=[];
  const cv=(i,j,k)=>CV[i+cx*(j+cy*k)];
  const quad=(a,b,c,d)=>{ idx.push(a,b,c,a,c,d); };
  for(let k=0;k<nz;k++) for(let j=0;j<ny;j++) for(let i=0;i<nx;i++){
    const in0 = F[i+nx*(j+ny*k)]<0;
    if(i<nx-1 && j>0 && k>0 && j<ny-1 && k<nz-1){
      if((F[(i+1)+nx*(j+ny*k)]<0)!==in0){
        const a=cv(i,j-1,k-1), b=cv(i,j,k-1), c=cv(i,j,k), d=cv(i,j-1,k);
        in0?quad(a,b,c,d):quad(a,d,c,b);
      }
    }
    if(j<ny-1 && i>0 && k>0 && i<nx-1 && k<nz-1){
      if((F[i+nx*((j+1)+ny*k)]<0)!==in0){
        const a=cv(i-1,j,k-1), b=cv(i-1,j,k), c=cv(i,j,k), d=cv(i,j,k-1);
        in0?quad(a,b,c,d):quad(a,d,c,b);
      }
    }
    if(k<nz-1 && i>0 && j>0 && i<nx-1 && j<ny-1){
      if((F[i+nx*(j+ny*(k+1))]<0)!==in0){
        const a=cv(i-1,j-1,k), b=cv(i,j-1,k), c=cv(i,j,k), d=cv(i-1,j,k);
        in0?quad(a,b,c,d):quad(a,d,c,b);
      }
    }
  }
  return { pos:new Float32Array(pos), idx:new Uint32Array(idx) };
}

// --- Simulation: Voxel → Tetraeder (Kuhn), XPBD ---------------------------
const KUHN=[[0,1,3,7],[0,1,5,7],[0,2,3,7],[0,2,6,7],[0,4,5,7],[0,4,6,7]];
const TE=[[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]];
function tetVol(x,a,b,c,d){
  const ax=x[b*3]-x[a*3], ay=x[b*3+1]-x[a*3+1], az=x[b*3+2]-x[a*3+2];
  const bx=x[c*3]-x[a*3], by=x[c*3+1]-x[a*3+1], bz=x[c*3+2]-x[a*3+2];
  const cx=x[d*3]-x[a*3], cy=x[d*3+1]-x[a*3+1], cz=x[d*3+2]-x[a*3+2];
  return ((ay*bz-az*by)*cx + (az*bx-ax*bz)*cy + (ax*by-ay*bx)*cz)/6;
}
function buildSim(b0,b1,h){
  const nx=Math.max(1,Math.ceil((b1[0]-b0[0])/h)), ny=Math.max(1,Math.ceil((b1[1]-b0[1])/h)), nz=Math.max(1,Math.ceil((b1[2]-b0[2])/h));
  const NX=nx+1, NY=ny+1;
  const cellIdx=new Int32Array(nx*ny*nz).fill(-1);
  const nodeOf=new Int32Array(NX*NY*(nz+1)).fill(-1);
  const P=[], tets=[], tetCell=[];
  const cE=[], cS=[], cF=[], cEps=[], cVol=[], cRho=[];
  const o={}; let nc=0;
  for(let k=0;k<nz;k++) for(let j=0;j<ny;j++) for(let i=0;i<nx;i++){
    const x=b0[0]+(i+.5)*h, y=b0[1]+(j+.5)*h, z=b0[2]+(k+.5)*h;
    if(sdf(x,y,z) >= h*0.2) continue;
    const ci=nc++; cellIdx[i+nx*(j+ny*k)]=ci;
    const ids=new Array(8);
    for(let c=0;c<8;c++){
      const ii=i+(c&1), jj=j+((c>>1)&1), kk=k+(c>>2), key=ii+NX*(jj+NY*kk);
      if(nodeOf[key]<0){ nodeOf[key]=P.length/3; P.push(b0[0]+ii*h, b0[1]+jj*h, b0[2]+kk*h); }
      ids[c]=nodeOf[key];
    }
    sampleParams(x,y,z,o);
    const L=lattice(o.t,o.d,o.b,ST.stepped);
    cE.push(L.Erel); cS.push(o.s); cF.push(o.fx,o.fy,o.fz); cEps.push(L.epsD); cVol.push(L.volF); cRho.push(L.rho/Math.max(o.s,1));
    for(const q of KUHN){ tets.push(ids[q[0]],ids[q[1]],ids[q[2]],ids[q[3]]); tetCell.push(ci); }
  }
  const n=P.length/3, x=new Float32Array(P), nt=tetCell.length;
  const T=new Int32Array(tets), V0=new Float32Array(nt);
  for(let t=0;t<nt;t++){
    let v=tetVol(x,T[t*4],T[t*4+1],T[t*4+2],T[t*4+3]);
    if(v<0){ const s=T[t*4+2]; T[t*4+2]=T[t*4+3]; T[t*4+3]=s; v=-v; }
    V0[t]=v;
  }
  // Kanten
  const map=new Map(), eA=[], eB=[], tetEdges=new Int32Array(nt*6);
  for(let t=0;t<nt;t++) for(let q=0;q<6;q++){
    let a=T[t*4+TE[q][0]], b=T[t*4+TE[q][1]]; if(a>b){const s=a;a=b;b=s;}
    const key=a*n+b; let e=map.get(key);
    if(e===undefined){ e=eA.length; map.set(key,e); eA.push(a); eB.push(b); }
    tetEdges[t*6+q]=e;
  }
  const ne=eA.length, EAi=new Int32Array(eA), EBi=new Int32Array(eB), eL0=new Float32Array(ne);
  for(let e=0;e<ne;e++){ const a=EAi[e]*3,b=EBi[e]*3; eL0[e]=Math.hypot(x[a]-x[b],x[a+1]-x[b+1],x[a+2]-x[b+2]); }
  // Knoten → Tets (für Dehnungsanzeige)
  const S={ n, nt, ne, h, b0:b0.slice(), nx,ny,nz, NX,NY, cellIdx, nodeOf,
    rest:new Float32Array(x), x, prev:new Float32Array(x), v:new Float32Array(n*3),
    mass:new Float32Array(n), invM:new Float32Array(n), pinned:new Uint8Array(n), pinT:new Float32Array(n*3),
    T, tetCell, V0, tetEdges, eA:EAi, eB:EBi, eL0, eAlpha:new Float32Array(ne), eAlphaD:new Float32Array(ne), eLd:new Float32Array(ne),
    tAlpha:new Float32Array(nt), tAlphaInv:new Float32Array(nt),
    cE:new Float32Array(cE), cS:new Float32Array(cS), cF:new Float32Array(cF), cEps:new Float32Array(cEps), cVol:new Float32Array(cVol), cRho:new Float32Array(cRho),
    J:new Float32Array(n), Jc:new Float32Array(n), lastF:0, Emin:0, Emax:0 };
  return S;
}
function applyMaterial(S, mat){
  const Es=mat.E*1e6, Ed=Es*0.15, c=0.7;
  const kS=new Float64Array(S.ne), kD=new Float64Array(S.ne), eps=new Float64Array(S.ne), cnt=new Uint16Array(S.ne);
  S.mass.fill(0);
  const x=S.rest; let Emin=1e30, Emax=0;
  for(let t=0;t<S.nt;t++){
    const ci=S.tetCell[t], E=S.cE[ci]*Es, s=S.cS[ci];
    const Epar=E*Math.pow(s,0.5), Eper=E*Math.pow(s,-2);
    const fx=S.cF[ci*3], fy=S.cF[ci*3+1], fz=S.cF[ci*3+2], V=S.V0[t];
    if(E<Emin)Emin=E; if(E>Emax)Emax=E;
    for(let q=0;q<6;q++){
      const e=S.tetEdges[t*6+q], a=S.eA[e]*3, b=S.eB[e]*3, L=S.eL0[e];
      const u=((x[b]-x[a])*fx+(x[b+1]-x[a+1])*fy+(x[b+2]-x[a+2])*fz)/L;
      const Edir=Eper+(Epar-Eper)*u*u;
      kS[e]+=c*Edir*V/(L*L); kD[e]+=c*Ed*V/(L*L); eps[e]+=S.cEps[ci]; cnt[e]++;
    }
    S.tAlpha[t]=V/(E*S.cVol[ci]*3); S.tAlphaInv[t]=V/(Es*0.3);
    const m=V*S.cRho[ci]*DENS_SOLID/4;
    for(let q=0;q<4;q++) S.mass[S.T[t*4+q]]+=m;
  }
  for(let e=0;e<S.ne;e++){
    S.eAlpha[e]=1/kS[e]; S.eAlphaD[e]=1/Math.max(kD[e],kS[e]*3);
    S.eLd[e]=S.eL0[e]*(1-eps[e]/cnt[e]);
  }
  S.Emin=Emin/1e6; S.Emax=Emax/1e6; S.damp=mat.damp;
  updateInvM(S);
}
function updateInvM(S){ for(let i=0;i<S.n;i++) S.invM[i] = S.pinned[i]?0:1/Math.max(S.mass[i],1e-9); }
function resetSim(S){ S.x.set(S.rest); S.prev.set(S.rest); S.v.fill(0); }
function nodesInSphere(S, src, cx,cy,cz, r, minN){
  const out=[], d2=[];
  for(let i=0;i<S.n;i++){ const dx=src[i*3]-cx, dy=src[i*3+1]-cy, dz=src[i*3+2]-cz, q=dx*dx+dy*dy+dz*dz; d2.push(q); if(q<r*r) out.push(i); }
  if(out.length<minN){ const ord=[...d2.keys()].sort((a,b)=>d2[a]-d2[b]); return ord.slice(0,minN); }
  return out;
}
const _vol=[[1,3,2],[0,2,3],[0,3,1],[0,1,2]];
const _g=new Float64Array(12);
function stepSim(S, frameDt, nSub, o){
  const dt=frameDt/nSub, idt2=1/(dt*dt), n=S.n, x=S.x, p=S.prev, v=S.v, w=S.invM;
  const df=Math.exp(-o.damp*dt), VMAX=20000;
  const T=S.T, eA=S.eA, eB=S.eB, eLd=S.eLd, eL0=S.eL0, eAl=S.eAlpha, eAlD=S.eAlphaD, ne=S.ne, nt=S.nt, V0a=S.V0, tAl=S.tAlpha, tAlI=S.tAlphaInv, pinned=S.pinned, pinT=S.pinT;
  S.lastF=0;
  for(let sub=0;sub<nSub;sub++){
    // äußere Kräfte
    for(let i=0;i<n;i++){
      if(w[i]===0) continue; const i3=i*3;
      v[i3]=(v[i3]+o.gx*dt)*df; v[i3+1]=(v[i3+1]+o.gy*dt)*df; v[i3+2]=(v[i3+2]+o.gz*dt)*df;
    }
    const dr=o.drag;
    if(dr){
      let cx=0,cy=0,cz=0;
      for(let k=0;k<dr.ids.length;k++){ const i3=dr.ids[k]*3, ww=dr.w[k]; cx+=x[i3]*ww; cy+=x[i3+1]*ww; cz+=x[i3+2]*ww; }
      const gx=dr.tx-cx, gy=dr.ty-cy, gz=dr.tz-cz, L=Math.hypot(gx,gy,gz);
      if(L>1e-6){
        const F=dr.F*Math.min(L/dr.ramp,1), fx=gx/L*F, fy=gy/L*F, fz=gz/L*F;
        S.lastF=F;
        for(let k=0;k<dr.ids.length;k++){
          const i=dr.ids[k]; if(w[i]===0) continue; const i3=i*3, a=dr.w[k]*w[i]*dt;
          v[i3]+=fx*a; v[i3+1]+=fy*a; v[i3+2]+=fz*a;
        }
      }
    }
    for(let i=0;i<n;i++){
      const i3=i*3; p[i3]=x[i3]; p[i3+1]=x[i3+1]; p[i3+2]=x[i3+2];
      if(w[i]>0){
        let vx=v[i3],vy=v[i3+1],vz=v[i3+2]; const sp=Math.hypot(vx,vy,vz);
        if(sp>VMAX){ const s=VMAX/sp; vx*=s; vy*=s; vz*=s; v[i3]=vx; v[i3+1]=vy; v[i3+2]=vz; }
        x[i3]+=vx*dt; x[i3+1]+=vy*dt; x[i3+2]+=vz*dt;
      } else if(pinned[i]){ x[i3]=pinT[i3]; x[i3+1]=pinT[i3+1]; x[i3+2]=pinT[i3+2]; }
    }
    // Kanten (Gitter-Steifigkeit + Verdichtung)
    for(let e=0;e<ne;e++){
      const a=eA[e], b=eB[e], wa=w[a], wb=w[b], W=wa+wb; if(W===0) continue;
      const a3=a*3, b3=b*3;
      const dx=x[a3]-x[b3], dy=x[a3+1]-x[b3+1], dz=x[a3+2]-x[b3+2];
      const L=Math.sqrt(dx*dx+dy*dy+dz*dz); if(L<1e-9) continue;
      let C, al;
      if(L<eLd[e]){ C=L-eLd[e]; al=eAlD[e]; } else { C=L-eL0[e]; al=eAl[e]; }
      const s=-C/(W+al*idt2)/L;
      x[a3]+=dx*s*wa; x[a3+1]+=dy*s*wa; x[a3+2]+=dz*s*wa;
      x[b3]-=dx*s*wb; x[b3+1]-=dy*s*wb; x[b3+2]-=dz*s*wb;
    }
    // Volumen: schwach, immer aktiv (Gitter-Querdehnung + verhindert Durchfalten)
    for(let t=0;t<nt;t++){
      const t4=t*4, V0=V0a[t];
      const V=tetVol(x,T[t4],T[t4+1],T[t4+2],T[t4+3]);
      let W=0;
      for(let j=0;j<4;j++){
        const i0=T[t4+_vol[j][0]]*3, i1=T[t4+_vol[j][1]]*3, i2=T[t4+_vol[j][2]]*3;
        const ax=x[i1]-x[i0], ay=x[i1+1]-x[i0+1], az=x[i1+2]-x[i0+2];
        const bx=x[i2]-x[i0], by=x[i2+1]-x[i0+1], bz=x[i2+2]-x[i0+2];
        const gx=(ay*bz-az*by)/6, gy=(az*bx-ax*bz)/6, gz=(ax*by-ay*bx)/6;
        _g[j*3]=gx; _g[j*3+1]=gy; _g[j*3+2]=gz;
        W+=w[T[t4+j]]*(gx*gx+gy*gy+gz*gz);
      }
      if(W===0) continue;
      const s=-(V-V0)/(W+tAl[t]*idt2);
      for(let j=0;j<4;j++){
        const id=T[t4+j], wi=w[id]; if(wi===0) continue; const i3=id*3;
        x[i3]+=s*wi*_g[j*3]; x[i3+1]+=s*wi*_g[j*3+1]; x[i3+2]+=s*wi*_g[j*3+2];
      }
    }
    for(let i=0;i<n;i++){
      if(w[i]===0) continue; const i3=i*3;
      v[i3]=(x[i3]-p[i3])/dt; v[i3+1]=(x[i3+1]-p[i3+1])/dt; v[i3+2]=(x[i3+2]-p[i3+2])/dt;
    }
  }
}
function nodeStrain(S){
  // pro Knoten: betragsgrößte Kantendehnung (signiert) → Zug/Druck sichtbar
  const J=S.J, x=S.x; J.fill(0);
  for(let e=0;e<S.ne;e++){
    const a=S.eA[e]*3, b=S.eB[e]*3;
    const eps=Math.hypot(x[a]-x[b],x[a+1]-x[b+1],x[a+2]-x[b+2])/S.eL0[e]-1;
    const ia=S.eA[e], ib=S.eB[e];
    if(Math.abs(eps)>Math.abs(J[ia])) J[ia]=eps;
    if(Math.abs(eps)>Math.abs(J[ib])) J[ib]=eps;
  }
}
// Render-Vertices trilinear in aktive Zellen einbetten
function embed(S,pos){
  const m=pos.length/3, ids=new Int32Array(m*8), wt=new Float32Array(m*8), h=S.h;
  for(let v=0;v<m;v++){
    const gx=(pos[v*3]-S.b0[0])/h, gy=(pos[v*3+1]-S.b0[1])/h, gz=(pos[v*3+2]-S.b0[2])/h;
    let ci=clamp(Math.floor(gx),0,S.nx-1), cj=clamp(Math.floor(gy),0,S.ny-1), ck=clamp(Math.floor(gz),0,S.nz-1);
    if(S.cellIdx[ci+S.nx*(cj+S.ny*ck)]<0){
      let best=1e9, bi=-1,bj=-1,bk=-1;
      for(let r=1;r<=4 && bi<0;r++)
        for(let k=ck-r;k<=ck+r;k++) for(let j=cj-r;j<=cj+r;j++) for(let i=ci-r;i<=ci+r;i++){
          if(i<0||j<0||k<0||i>=S.nx||j>=S.ny||k>=S.nz) continue;
          if(S.cellIdx[i+S.nx*(j+S.ny*k)]<0) continue;
          const d=(i+.5-gx)**2+(j+.5-gy)**2+(k+.5-gz)**2;
          if(d<best){best=d;bi=i;bj=j;bk=k;}
        }
      if(bi<0){ // Notfall: irgendeine aktive Zelle
        for(let c=0;c<S.cellIdx.length;c++) if(S.cellIdx[c]>=0){ bi=c%S.nx; bj=Math.floor(c/S.nx)%S.ny; bk=Math.floor(c/(S.nx*S.ny)); break; }
      }
      ci=bi; cj=bj; ck=bk;
    }
    const u=clamp(gx-ci,-1,2), vv=clamp(gy-cj,-1,2), ww=clamp(gz-ck,-1,2);
    for(let c=0;c<8;c++){
      const di=c&1, dj=(c>>1)&1, dk=c>>2;
      ids[v*8+c]=S.nodeOf[(ci+di)+S.NX*((cj+dj)+S.NY*(ck+dk))];
      wt[v*8+c]=(di?u:1-u)*(dj?vv:1-vv)*(dk?ww:1-ww);
    }
  }
  return { ids, wt, m };
}
function deform(S,E,out){
  const x=S.x, ids=E.ids, wt=E.wt;
  for(let v=0;v<E.m;v++){
    let px=0,py=0,pz=0;
    for(let c=0;c<8;c++){ const i=ids[v*8+c]*3, w=wt[v*8+c]; px+=x[i]*w; py+=x[i+1]*w; pz+=x[i+2]*w; }
    out[v*3]=px; out[v*3+1]=py; out[v*3+2]=pz;
  }
}
/*CORE_END*/

// =====================================================================
//  UI / RENDER
// =====================================================================
const canvas=document.getElementById('c');
const renderer=new THREE.WebGLRenderer({canvas,antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio,2));
renderer.setClearColor(0xffffff,1);
renderer.localClippingEnabled=true;
const scene=new THREE.Scene();
const camera=new THREE.PerspectiveCamera(32,1,1,5000);
camera.position.set(-90,150,420);
const controls=new OrbitControls(camera,canvas);
controls.enableDamping=true; controls.dampingFactor=0.12; controls.target.set(20,0,0);
scene.add(new THREE.HemisphereLight(0xffffff,0xd8d8d8,1.25));
const dl=new THREE.DirectionalLight(0xffffff,1.5); dl.position.set(220,380,260); scene.add(dl);
const dl2=new THREE.DirectionalLight(0xffffff,0.45); dl2.position.set(-300,-80,-200); scene.add(dl2);
const grid=new THREE.GridHelper(600,30,0xececec,0xf3f3f3); grid.position.y=-110; scene.add(grid);

const surfMat=new THREE.MeshStandardMaterial({vertexColors:true,roughness:0.78,metalness:0,side:THREE.DoubleSide});
const surf=new THREE.Mesh(new THREE.BufferGeometry(),surfMat); scene.add(surf);

// ---------------- Zustand ----------------
const state={
  mode:'form', blobs:[], sel:-1, K:12, meshRes:80, mat:1, stepped:false,
  brush:{t:1/3,d:0.8,b:0.6,mask:[1,1,1],R:12,D:10,flow:0.35,erase:false},
  display:'rgb', section:{on:false,axis:2,pos:0.5},
  sim:{running:true,tool:'drag',F:2,grabR:14,pinR:16,grav:false,gF:1,damp:0.4,res:'mid',display:'strain'},
  pins:[]
};
const RES={coarse:10,mid:8,fine:6};
let restPos=null, restNrm=null, restCol=null;
let surfDirty=true, capDirty=true, simDirty=true;
let S=null, EMB=null;
let bounds={b0:[0,0,0],b1:[1,1,1]};

function makeBlob(kind,pos,opt={}){
  const q=opt.quat||new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1),-Math.PI/2);
  return {kind,pos:pos.clone(),quat:q.clone(),r:opt.r??20,len:kind==='sphere'?0:(opt.len??80),
    t:opt.t??1/3,d:opt.d??1/3,b:opt.b??0.5,s:opt.s??1,proxy:null};
}
// Startszene: Muskelbauch + Sehne (weich → dicht)
state.blobs.push(makeBlob('capsule',new THREE.Vector3(-10,0,0),{r:26,len:100,d:0.33,b:0.5,s:1.5}));
state.blobs.push(makeBlob('capsule',new THREE.Vector3(95,0,0),{r:9,len:50,d:0.85,b:0.6,s:1}));
state.blobs.push(makeBlob('sphere',new THREE.Vector3(-82,0,0),{r:20,d:0.6,b:0.5}));

function syncCore(){
  ST.K=state.K; ST.stepped=state.stepped;
  ST.blobs=state.blobs.map(b=>{
    const a=new THREE.Vector3(0,1,0).applyQuaternion(b.quat);
    return {cx:b.pos.x,cy:b.pos.y,cz:b.pos.z,ax:a.x,ay:a.y,az:a.z,half:b.kind==='sphere'?0:b.len/2,r:b.r,t:b.t,d:b.d,b:b.b,s:b.s};
  });
}
function computeBounds(pad){
  const b0=[1e9,1e9,1e9], b1=[-1e9,-1e9,-1e9];
  for(const B of ST.blobs){
    const ex=[Math.abs(B.ax)*B.half+B.r, Math.abs(B.ay)*B.half+B.r, Math.abs(B.az)*B.half+B.r], c=[B.cx,B.cy,B.cz];
    for(let k=0;k<3;k++){ b0[k]=Math.min(b0[k],c[k]-ex[k]-pad); b1[k]=Math.max(b1[k],c[k]+ex[k]+pad); }
  }
  return {b0,b1};
}

// ---------------- Farben ----------------
const _o={};
function hex(h){ return [(h>>16&255)/255,(h>>8&255)/255,(h&255)/255]; }
function ramp(stops,t,out){
  t=clamp(t,0,1)*(stops.length-1); const i=Math.min(stops.length-2,Math.floor(t)), f=t-i;
  out[0]=stops[i][0]+(stops[i+1][0]-stops[i][0])*f; out[1]=stops[i][1]+(stops[i+1][1]-stops[i][1])*f; out[2]=stops[i][2]+(stops[i+1][2]-stops[i][2])*f; return out;
}
const E_STOPS=[0xf4f6f9,0xc9daf2,0x7fa5e4,0x3a64c4,0x1b2f78].map(hex);
const STRAIN_NEG=[0xffffff,0xb7cdf3,0x2f6fdb].map(hex), STRAIN_POS=[0xffffff,0xf8cfa4,0xec7a1c].map(hex);
function E_t(Empa){ return (Math.log10(Math.max(Empa,1e-6))+4)/4.6; }
function paramColor(o,mode,out){
  if(mode==='rgb'){ out[0]=0.12+0.86*o.t; out[1]=0.12+0.86*o.d; out[2]=0.12+0.86*o.b; return out; }
  if(mode==='r'||mode==='g'||mode==='b'){ const v=mode==='r'?o.t:mode==='g'?o.d:o.b; const g=0.1+0.88*v; out[0]=out[1]=out[2]=g; return out; }
  const L=lattice(o.t,o.d,o.b,state.stepped); return ramp(E_STOPS,E_t(L.Erel*MATERIALS[state.mat].E),out);
}
const _c=[0,0,0];
function colorVertex(i,col,mode){
  const x=restPos[i*3]-restNrm[i*3]*1.5, y=restPos[i*3+1]-restNrm[i*3+1]*1.5, z=restPos[i*3+2]-restNrm[i*3+2]*1.5;
  sampleParams(x,y,z,_o); paramColor(_o,mode,_c);
  col[i*3]=_c[0]; col[i*3+1]=_c[1]; col[i*3+2]=_c[2];
}
function recolorAll(){
  if(!restPos) return; const col=surf.geometry.getAttribute('color').array, n=restPos.length/3;
  for(let i=0;i<n;i++) colorVertex(i,col,state.display);
  surf.geometry.getAttribute('color').needsUpdate=true; restCol=new Float32Array(col);
  updateLegend();
}
function recolorNear(px,py,pz,r){
  const col=surf.geometry.getAttribute('color').array, n=restPos.length/3, r2=r*r;
  for(let i=0;i<n;i++){ const dx=restPos[i*3]-px, dy=restPos[i*3+1]-py, dz=restPos[i*3+2]-pz; if(dx*dx+dy*dy+dz*dz<r2) colorVertex(i,col,state.display); }
  surf.geometry.getAttribute('color').needsUpdate=true; restCol=new Float32Array(col);
}

// ---------------- Oberfläche ----------------
function rebuildSurface(){
  syncCore();
  if(!ST.blobs.length){ surf.visible=false; return; }
  surf.visible=true;
  bounds=computeBounds(state.K*0.5+4);
  const ext=Math.max(bounds.b1[0]-bounds.b0[0],bounds.b1[1]-bounds.b0[1],bounds.b1[2]-bounds.b0[2]);
  const cell=Math.max(ext/state.meshRes,1.1);
  const b0=bounds.b0.map(v=>v-cell*2), b1=bounds.b1.map(v=>v+cell*2);
  const {pos,idx}=surfaceNets(b0,b1,cell);
  const n=pos.length/3, nrm=new Float32Array(n*3), g=[0,0,0];
  for(let i=0;i<n;i++){ sdfGrad(pos[i*3],pos[i*3+1],pos[i*3+2],g); nrm[i*3]=g[0]; nrm[i*3+1]=g[1]; nrm[i*3+2]=g[2]; }
  const geo=new THREE.BufferGeometry();
  geo.setAttribute('position',new THREE.BufferAttribute(new Float32Array(pos),3));
  geo.setAttribute('normal',new THREE.BufferAttribute(nrm,3));
  geo.setAttribute('color',new THREE.BufferAttribute(new Float32Array(n*3),3));
  geo.setIndex(new THREE.BufferAttribute(idx,1));
  surf.geometry.dispose(); surf.geometry=geo;
  restPos=pos; restNrm=nrm;
  recolorAll(); capDirty=true; simDirty=true;
}

// ---------------- Blob-Proxies + Gizmo ----------------
const tc=new TransformControls(camera,canvas); tc.setSize(0.7); scene.add(tc);
let tcDragging=false;
tc.addEventListener('dragging-changed',e=>{ controls.enabled=!e.value; tcDragging=e.value; });
tc.addEventListener('objectChange',()=>{
  const b=state.blobs[state.sel]; if(!b) return;
  b.pos.copy(b.proxy.position); b.quat.copy(b.proxy.quaternion); surfDirty=true;
});
const proxyMat=new THREE.LineBasicMaterial({color:0x111111,transparent:true,opacity:0.16,depthTest:false});
function buildProxy(b){
  if(b.proxy){ scene.remove(b.proxy); b.proxy.traverse(o=>o.geometry&&o.geometry.dispose()); }
  const g=new THREE.Group(); g.position.copy(b.pos); g.quaternion.copy(b.quat);
  const geo=b.kind==='sphere'?new THREE.SphereGeometry(b.r,16,10):new THREE.CapsuleGeometry(b.r,b.len,6,16);
  const ln=new THREE.LineSegments(new THREE.WireframeGeometry(geo),proxyMat); ln.renderOrder=10; geo.dispose();
  g.add(ln); g.visible=false; b.proxy=g; scene.add(g);
}
state.blobs.forEach(buildProxy);
function select(i){
  state.sel=i; state.blobs.forEach((b,k)=>{ b.proxy.visible = (k===i && state.mode==='form'); });
  if(i>=0 && state.mode==='form') tc.attach(state.blobs[i].proxy); else tc.detach();
  refreshBlobPanel(); inspectBlob();
}

// ---------------- Schnittebene ----------------
const capTexSize=192;
const capData=new Uint8Array(capTexSize*capTexSize*4);
const capTex=new THREE.DataTexture(capData,capTexSize,capTexSize); capTex.magFilter=THREE.LinearFilter; capTex.minFilter=THREE.LinearFilter;
const capMat=new THREE.MeshBasicMaterial({map:capTex,transparent:true,alphaTest:0.5,side:THREE.DoubleSide});
const cap=new THREE.Mesh(new THREE.BufferGeometry(),capMat); cap.visible=false; scene.add(cap);
const capLine=new THREE.LineLoop(new THREE.BufferGeometry(),new THREE.LineBasicMaterial({color:0x111111,transparent:true,opacity:0.25})); scene.add(capLine); capLine.visible=false;
const clipPlane=new THREE.Plane(new THREE.Vector3(0,0,-1),0);
function secValue(){ const a=state.section.axis; return bounds.b0[a]+(bounds.b1[a]-bounds.b0[a])*state.section.pos; }
function sectionActive(){ return state.section.on && state.mode!=='sim'; }
function updateCap(){
  capDirty=false;
  const on=sectionActive();
  cap.visible=on; capLine.visible=on; surfMat.clippingPlanes=on?[clipPlane]:[]; surfMat.needsUpdate=true;
  if(!on) return;
  const a=state.section.axis, u=(a+1)%3, w=(a+2)%3, v=secValue();
  const n=new THREE.Vector3(); n.setComponent(a,-1); clipPlane.set(n,v);
  const b0=bounds.b0, b1=bounds.b1, P=[0,0,0], col=[0,0,0];
  for(let j=0;j<capTexSize;j++) for(let i=0;i<capTexSize;i++){
    P[a]=v; P[u]=b0[u]+(b1[u]-b0[u])*(i+.5)/capTexSize; P[w]=b0[w]+(b1[w]-b0[w])*(j+.5)/capTexSize;
    const k=(i+j*capTexSize)*4;
    if(sdf(P[0],P[1],P[2])>0){ capData[k+3]=0; continue; }
    sampleParams(P[0],P[1],P[2],_o); paramColor(_o,state.display,col);
    capData[k]=col[0]*255; capData[k+1]=col[1]*255; capData[k+2]=col[2]*255; capData[k+3]=255;
  }
  capTex.needsUpdate=true;
  const C=(uu,ww)=>{ const q=[0,0,0]; q[a]=v; q[u]=uu; q[w]=ww; return q; };
  const c=[C(b0[u],b0[w]),C(b1[u],b0[w]),C(b1[u],b1[w]),C(b0[u],b1[w])];
  const g=new THREE.BufferGeometry();
  g.setAttribute('position',new THREE.Float32BufferAttribute(c.flat(),3));
  g.setAttribute('uv',new THREE.Float32BufferAttribute([0,0,1,0,1,1,0,1],2));
  g.setIndex([0,1,2,0,2,3]); cap.geometry.dispose(); cap.geometry=g;
  capLine.geometry.dispose(); capLine.geometry=new THREE.BufferGeometry().setAttribute('position',new THREE.Float32BufferAttribute(c.flat(),3));
}

// ---------------- Einheitszelle (Inspektor) ----------------
const cellR=new THREE.WebGLRenderer({canvas:document.getElementById('cellCanvas'),antialias:true,alpha:true});
cellR.setPixelRatio(1); cellR.setSize(472,300,false); cellR.setClearColor(0xffffff,0);
const cellScene=new THREE.Scene(), cellCam=new THREE.PerspectiveCamera(30,472/300,0.1,50);
cellCam.position.set(1.9,1.25,2.4); cellCam.lookAt(0,0,0);
cellScene.add(new THREE.HemisphereLight(0xffffff,0xcfcfcf,1.4)); const cdl=new THREE.DirectionalLight(0xffffff,1.2); cdl.position.set(2,3,2); cellScene.add(cdl);
const cellGroup=new THREE.Group(); cellScene.add(cellGroup);
const strutGeo=new THREE.CylinderGeometry(1,1,1,10,1);
const strutMesh=new THREE.InstancedMesh(strutGeo,new THREE.MeshStandardMaterial({color:0x2a2a2a,roughness:0.6}),48*8); cellGroup.add(strutMesh);
const cellBox=new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(1,1,1)),new THREE.LineBasicMaterial({color:0xbbbbbb})); cellGroup.add(cellBox);
function unitStruts(type){
  const S=[]; const P=(a,b)=>S.push([a,b]);
  if(type===0){
    const t=[[.25,.25,.25,[[0,0,0],[.5,.5,0],[.5,0,.5],[0,.5,.5]]],[.75,.75,.25,[[1,1,0],[.5,.5,0],[1,.5,.5],[.5,1,.5]]],[.75,.25,.75,[[1,0,1],[.5,0,.5],[1,.5,.5],[.5,.5,1]]],[.25,.75,.75,[[0,1,1],[0,.5,.5],[.5,1,.5],[.5,.5,1]]]];
    for(const q of t) for(const nb of q[3]) P([q[0],q[1],q[2]],nb);
  } else if(type===1){
    for(let c=0;c<8;c++) P([.5,.5,.5],[c&1,(c>>1)&1,c>>2]);
  } else if(type===2){
    for(let c=0;c<8;c++) for(const bit of [1,2,4]) if(!(c&bit)){ const d=c|bit; P([c&1,(c>>1)&1,c>>2],[d&1,(d>>1)&1,d>>2]); }
  } else {
    const fc=[]; for(let ax=0;ax<3;ax++) for(const s of [0,1]){ const f=[.5,.5,.5]; f[ax]=s; fc.push([f,ax]); }
    for(const [f,ax] of fc){ const u=(ax+1)%3, w=(ax+2)%3; for(const a of [0,1]) for(const b of [0,1]){ const c=f.slice(); c[u]=a; c[w]=b; P(f,c); } }
    for(let i=0;i<6;i++) for(let j=i+1;j<6;j++) if(fc[i][1]!==fc[j][1]) P(fc[i][0],fc[j][0]);
  }
  return S;
}
let lastCellKey='';
const _m=new THREE.Matrix4(), _q=new THREE.Quaternion(), _up=new THREE.Vector3(0,1,0);
function drawCell(type,x,z,p){
  const key=type+'|'+x.toFixed(1)+'|'+z.toFixed(1)+'|'+p.toFixed(2); if(key===lastCellKey) return; lastCellKey=key;
  const md=Math.max(x,z)*2, sx=x/md, sz=z/md, r=p/2/md;   // 2×2×2 Zellen
  const st=unitStruts(type); let k=0;
  for(let ci=0;ci<8;ci++){
    const ox=(ci&1)-1, oy=((ci>>1)&1)-1, oz=(ci>>2)-1;
    for(const [a,b] of st){
      const A=new THREE.Vector3((a[0]+ox)*sx,(a[2]+oz)*sz,(a[1]+oy)*sx), B=new THREE.Vector3((b[0]+ox)*sx,(b[2]+oz)*sz,(b[1]+oy)*sx);
      const d=B.clone().sub(A), L=d.length(); if(L<1e-6) continue; _q.setFromUnitVectors(_up,d.normalize());
      _m.compose(A.add(B).multiplyScalar(.5),_q,new THREE.Vector3(r,L,r)); strutMesh.setMatrixAt(k++,_m);
    }
  }
  strutMesh.count=k; strutMesh.instanceMatrix.needsUpdate=true;
  cellBox.scale.set(sx*2,sz*2,sx*2);
}
const inspText=document.getElementById('inspText');
function inspect(o,title){
  const L=lattice(o.t,o.d,o.b,state.stepped), M=MATERIALS[state.mat], E=L.Erel*M.E, s=o.s??1;
  drawCell(L.main,L.x,L.x*s,L.p);
  const tname = state.stepped||L.tf===0 ? TYPES[L.main].name : `${TYPES[L.ti].name} → ${TYPES[L.ti+1].name} ${Math.round(L.tf*100)}%`;
  const fmtE=v=>v<0.01?(v*1000).toFixed(2)+' kPa':v.toFixed(3)+' MPa';
  let eLine=`<div class="r"><span class="k">E_eff</span><span>${fmtE(E)}</span></div>`;
  if(s>1.02) eLine=`<div class="r"><span class="k">E ∥ Faser</span><span>${fmtE(E*Math.pow(s,0.5))}</span></div><div class="r"><span class="k">E ⊥ Faser</span><span>${fmtE(E*Math.pow(s,-2))}</span></div>`;
  inspText.innerHTML=`<div class="t">${title}</div>
   <div class="r"><span class="k">Typ</span><span>${tname}</span></div>
   <div class="r"><span class="k">Zelle</span><span>${L.x.toFixed(1)} × ${L.x.toFixed(1)} × ${(L.x*s).toFixed(1)} mm</span></div>
   <div class="r"><span class="k">Steg p</span><span>${L.p.toFixed(2)} mm</span></div>
   <div class="r"><span class="k">Rel. Dichte</span><span>${(L.rho/s*100).toFixed(1)} %</span></div>
   ${eLine}
   <div class="r"><span class="k">Verdichtung ab</span><span>ε ≈ ${L.epsD.toFixed(2)}</span></div>`;
}
function inspectBlob(){
  const b=state.blobs[state.sel];
  if(b) inspect({t:b.t,d:b.d,b:b.b,s:b.s},'Blob '+(state.sel+1)+' · '+(b.kind==='sphere'?'Kugel':'Kapsel'));
  else inspect({t:state.brush.t,d:state.brush.d,b:state.brush.b,s:1},'Pinsel');
}

// ---------------- UI-Helfer ----------------
function el(tag,cls,parent,html){ const e=document.createElement(tag); if(cls) e.className=cls; if(html!=null) e.innerHTML=html; if(parent) parent.appendChild(e); return e; }
function grp(parent,title){ const g=el('div','grp',parent); if(title) el('h3','',g,title); return g; }
function slider(parent,label,min,max,step,get,set,fmt){
  const r=el('div','row',parent); el('span','lab',r,label);
  const inp=el('input','',r); inp.type='range'; inp.min=min; inp.max=max; inp.step=step;
  const val=el('span','val',r);
  const upd=()=>{ inp.value=get(); val.textContent=fmt?fmt(+inp.value):(+inp.value).toFixed(2); };
  inp.addEventListener('input',()=>{ set(+inp.value); val.textContent=fmt?fmt(+inp.value):(+inp.value).toFixed(2); });
  upd(); return {upd,inp,row:r};
}
function seg(parent,opts,get,set,label){
  const r=el('div','row',parent); if(label) el('span','lab',r,label);
  const s=el('div','seg',r); const bs=[];
  for(const [v,l] of opts){ const b=el('button','',s,l); b.onclick=()=>{ set(v); upd(); }; bs.push([v,b]); }
  const upd=()=>bs.forEach(([v,b])=>b.classList.toggle('on',get()===v));
  upd(); return {upd};
}
function btn(parent,label,fn){ const b=el('button','b',parent,label); b.onclick=fn; return b; }
const typeLabel=v=>{ const L=lattice(v,0,0,state.stepped); return state.stepped||L.tf===0?TYPES[L.main].name.split(' ')[0]:TYPES[L.main].name.split(' ')[0]+'~'; };

// ---------------- Panel: FORM ----------------
const pForm=document.querySelector('[data-panel=form]');
{
  const g=grp(pForm,'Blobs'); const bb=el('div','btns',g);
  btn(bb,'+ Kugel',()=>addBlob('sphere')); btn(bb,'+ Kapsel',()=>addBlob('capsule'));
  btn(bb,'Duplizieren',()=>{ const b=state.blobs[state.sel]; if(!b) return; const n=makeBlob(b.kind,b.pos.clone().add(new THREE.Vector3(15,15,0)),{quat:b.quat,r:b.r,len:b.len,t:b.t,d:b.d,b:b.b,s:b.s}); state.blobs.push(n); buildProxy(n); select(state.blobs.length-1); surfDirty=true; });
  btn(bb,'Löschen',deleteSel);
  var gizmoSeg=seg(g,[['translate','Verschieben'],['rotate','Drehen']],()=>tc.mode,v=>tc.setMode(v));
}
const pSel=grp(pForm,'Auswahl');
const selCtl=[];
function refreshBlobPanel(){
  pSel.innerHTML=''; el('h3','',pSel,'Auswahl');
  const b=state.blobs[state.sel];
  if(!b){ el('div','note',pSel,'Klick auf den Körper wählt den nächsten Blob.'); return; }
  const dirty=()=>{ surfDirty=true; inspectBlob(); };
  slider(pSel,'Radius',4,70,0.5,()=>b.r,v=>{b.r=v;buildProxy(b);b.proxy.visible=true;tc.attach(b.proxy);dirty();},v=>v.toFixed(1)+' mm');
  if(b.kind==='capsule') slider(pSel,'Länge',0,220,1,()=>b.len,v=>{b.len=v;buildProxy(b);b.proxy.visible=true;tc.attach(b.proxy);dirty();},v=>v.toFixed(0)+' mm');
  el('h3','',pSel,'Gitter dieses Blobs').style.marginTop='14px';
  slider(pSel,'R · Typ',0,1,0.01,()=>b.t,v=>{b.t=v;dirty();},typeLabel);
  slider(pSel,'G · Dichte',0,1,0.01,()=>b.d,v=>{b.d=v;dirty();},v=>cellSize(v).toFixed(1)+' mm');
  slider(pSel,'B · Steg',0,1,0.01,()=>b.b,v=>{b.b=v;dirty();},v=>strutD(v).toFixed(2)+' mm');
  slider(pSel,'Streckung',1,3,0.05,()=>b.s,v=>{b.s=v;dirty();},v=>'z/x '+v.toFixed(2));
  el('div','note',pSel,'Streckung zieht die Zelle entlang der Blob-Achse (Faserrichtung): steifer längs, weicher quer.');
}
{
  const g=grp(pForm,'Global');
  slider(g,'Verschmelzen',0,50,0.5,()=>state.K,v=>{state.K=v;surfDirty=true;},v=>v.toFixed(1)+' mm');
  slider(g,'Mesh-Auflösung',40,120,1,()=>state.meshRes,v=>{state.meshRes=v;surfDirty=true;},v=>v.toFixed(0));
  el('div','note',g,'Die Gitter-Parameter der Blobs mischen sich im Inneren genauso weich wie die Form.');
}
function addBlob(kind){
  const b=makeBlob(kind,controls.target.clone().add(new THREE.Vector3(0,40,0)),{r:kind==='sphere'?22:16,len:70});
  state.blobs.push(b); buildProxy(b); select(state.blobs.length-1); surfDirty=true;
}
function deleteSel(){
  const b=state.blobs[state.sel]; if(!b) return;
  tc.detach(); scene.remove(b.proxy); state.blobs.splice(state.sel,1); select(-1); surfDirty=true;
}

// ---------------- Panel: STRUKTUR ----------------
const pStruct=document.querySelector('[data-panel=struct]');
let legendUpd=()=>{};
{
  const g=grp(pStruct,'Pinsel');
  const r=el('div','row',g); el('span','lab',r,'Kanäle');
  const cls=['r','g','bl'], names=['R','G','B'];
  names.forEach((n,i)=>{ const c=el('button','chip '+cls[i]+(state.brush.mask[i]?' on':''),r,n); c.onclick=()=>{ state.brush.mask[i]^=1; c.classList.toggle('on',!!state.brush.mask[i]); }; });
  slider(g,'R · Typ',0,1,0.01,()=>state.brush.t,v=>{state.brush.t=v;inspectBlob();},typeLabel);
  slider(g,'G · Dichte',0,1,0.01,()=>state.brush.d,v=>{state.brush.d=v;inspectBlob();},v=>cellSize(v).toFixed(1)+' mm');
  slider(g,'B · Steg',0,1,0.01,()=>state.brush.b,v=>{state.brush.b=v;inspectBlob();},v=>strutD(v).toFixed(2)+' mm');
  slider(g,'Radius',3,45,0.5,()=>state.brush.R,v=>state.brush.R=v,v=>v.toFixed(1)+' mm');
  slider(g,'Tiefe',0,80,1,()=>state.brush.D,v=>state.brush.D=v,v=>v.toFixed(0)+' mm');
  slider(g,'Stärke',0.02,1,0.01,()=>state.brush.flow,v=>state.brush.flow=v,v=>(v*100).toFixed(0)+' %');
  seg(g,[[false,'Malen'],[true,'Radieren']],()=>state.brush.erase,v=>state.brush.erase=v,'Modus');
  el('div','note',g,'Tiefe = wie weit der Strich von der Oberfläche nach innen wirkt. Radieren stellt die Blob-Werte wieder her.');
  const bb=el('div','btns',g); btn(bb,'Bemalung löschen',()=>{ clearPaint(); recolorAll(); capDirty=true; simDirty=true; });
}
{
  const g=grp(pStruct,'Gittertyp-Übergang');
  seg(g,[[false,'weich'],[true,'stufig']],()=>state.stepped,v=>{state.stepped=v;ST.stepped=v;recolorAll();capDirty=true;simDirty=true;inspectBlob();});
  el('div','note',g,'R-Kanal: 0 Diamant · ⅓ BCC (Paper) · ⅔ Kubisch · 1 Oktett. Weich = Steifigkeit wird logarithmisch zwischen Typen gemischt.');
}
{
  const g=grp(pStruct,'Anzeige');
  seg(g,[['rgb','RGB'],['r','R'],['g','G'],['b','B'],['E','E']],()=>state.display,v=>{state.display=v;recolorAll();capDirty=true;});
}
{
  const g=grp(pStruct,'Schnitt');
  seg(g,[[false,'aus'],[true,'an']],()=>state.section.on,v=>{state.section.on=v;capDirty=true;});
  seg(g,[[0,'X'],[1,'Y'],[2,'Z']],()=>state.section.axis,v=>{state.section.axis=v;capDirty=true;},'Achse');
  slider(g,'Position',0,1,0.005,()=>state.section.pos,v=>{state.section.pos=v;capDirty=true;},v=>(v*100).toFixed(0)+' %');
  el('div','note',g,'Auf der Schnittfläche malst du direkt im Inneren (kugelförmiger Pinsel).');
}

// ---------------- Panel: SIMULATION ----------------
const pSim=document.querySelector('[data-panel=sim]');
let simStats;
{
  const g=grp(pSim,'Lauf'); const bb=el('div','btns',g);
  const runB=btn(bb,'Pause',()=>{ state.sim.running=!state.sim.running; runB.textContent=state.sim.running?'Pause':'Start'; });
  btn(bb,'Zurücksetzen',()=>{ if(!S) return; resetSim(S); for(const p of state.pins){ p.base=null; p.visBase=null; p.delta.set(0,0,0);} rebuildPins(); });
  window._runB=runB;
}
{
  const g=grp(pSim,'Werkzeug');
  seg(g,[['drag','Ziehen'],['pin','Pin setzen']],()=>state.sim.tool,v=>state.sim.tool=v);
  slider(g,'Griffkraft',0.05,20,0.05,()=>state.sim.F,v=>state.sim.F=v,v=>v.toFixed(2)+' N');
  slider(g,'Griff-Radius',4,40,0.5,()=>state.sim.grabR,v=>state.sim.grabR=v,v=>v.toFixed(1)+' mm');
  slider(g,'Pin-Radius',5,45,0.5,()=>state.sim.pinR,v=>state.sim.pinR=v,v=>v.toFixed(1)+' mm');
  const bb=el('div','btns',g); btn(bb,'Pins löschen',()=>{ for(const p of state.pins) scene.remove(p.mesh); state.pins=[]; rebuildPins(); });
  el('div','note',g,'Pins fixieren alle Knoten im Radius. Pin anklicken und ziehen = verschieben · im Pin-Modus anklicken = entfernen.');
}
{
  const g=grp(pSim,'Umgebung');
  seg(g,[[false,'aus'],[true,'an']],()=>state.sim.grav,v=>state.sim.grav=v,'Schwerkraft');
  slider(g,'Faktor',0.1,20,0.1,()=>state.sim.gF,v=>state.sim.gF=v,v=>v.toFixed(1)+' × g');
  slider(g,'Dämpfung',0,1,0.01,()=>state.sim.damp,v=>state.sim.damp=v,v=>(v*100).toFixed(0)+' %');
  seg(g,[['coarse','grob'],['mid','mittel'],['fine','fein']],()=>state.sim.res,v=>{state.sim.res=v;simDirty=true;ensureSim();},'Auflösung');
}
{
  const g=grp(pSim,'Anzeige');
  seg(g,[['strain','Dehnung'],['struct','Struktur'],['E','Steifigkeit']],()=>state.sim.display,v=>{state.sim.display=v;if(v!=='strain')applySimColors();updateLegend();});
  simStats=el('div','note',g,'');
}

// ---------------- Material ----------------
const matSel=document.getElementById('matSel');
MATERIALS.forEach((m,i)=>{ const o=el('option','',matSel,`${m.name} · ${m.E} MPa`); o.value=i; });
matSel.value=state.mat;
matSel.onchange=()=>{ state.mat=+matSel.value; if(S){ applyMaterial(S,MATERIALS[state.mat]); rebuildPins(); }
  if(state.display==='E'){ recolorAll(); capDirty=true; } if(state.mode==='sim') applySimColors(); inspectBlob(); updateLegend(); };

// ---------------- Legende ----------------
const legend=document.getElementById('legend'), legBar=document.getElementById('legBar'), legL=document.getElementById('legL'), legR=document.getElementById('legR');
const css=a=>`rgb(${a.map(v=>Math.round(v*255)).join(',')})`;
function updateLegend(){
  const simMode=state.mode==='sim';
  const show = simMode ? (state.sim.display!=='struct') : state.display==='E' && state.mode!=='form';
  legend.style.display=show?'flex':'none'; if(!show) return;
  if(simMode && state.sim.display==='strain'){
    legBar.style.background=`linear-gradient(90deg,${css(STRAIN_NEG[2])},#fff,${css(STRAIN_POS[2])})`;
    legL.textContent='Druck −30 %'; legR.textContent='Zug +30 %';
  } else {
    legBar.style.background=`linear-gradient(90deg,${E_STOPS.map(css).join(',')})`;
    legL.textContent='0.1 kPa'; legR.textContent='4 MPa  (E_eff, log)';
  }
}

// ---------------- Modi ----------------
const hint=document.getElementById('hint'), hud=document.getElementById('hud');
const HINTS={
  form:'Klick wählt Blob · Gizmo verschieben/drehen (W/E) · Entf löscht · Rechtsklick-Ziehen = Pan',
  struct:'Auf dem Körper malen = R/G/B ins Innere · daneben ziehen = Kamera · Schnitt an für Innenansicht',
  sim:'Körper ziehen = Kraft · Pins fixieren Bereiche · Leertaste = Pause'
};
document.querySelectorAll('#tabs button').forEach(b=>b.onclick=()=>setMode(b.dataset.mode));
function setMode(m){
  const prev=state.mode; state.mode=m;
  document.querySelectorAll('#tabs button').forEach(b=>b.classList.toggle('on',b.dataset.mode===m));
  document.querySelectorAll('aside section').forEach(s=>s.classList.toggle('on',s.dataset.panel===m));
  hint.textContent=HINTS[m];
  select(m==='form'?state.sel:-1);
  if(m==='form'&&state.sel<0) inspectBlob();
  brushRing.visible=false;
  if(m==='sim'){ if(surfDirty){ rebuildSurface(); surfDirty=false; } ensureSim(); applySimColors(); state.pins.forEach(p=>p.mesh.visible=true); }
  else {
    state.pins.forEach(p=>p.mesh.visible=false); grabLine.visible=false;
    if(prev==='sim' && restPos){ restoreRest(); }
    hud.textContent='';
  }
  if(m!=='form' && prev==='form') inspectBlob();
  if(m==='form' && prev!=='form' && state.display!=='rgb'){ /* Form zeigt aktuelle Anzeige */ }
  capDirty=true; updateLegend();
}
function restoreRest(){
  const g=surf.geometry; g.getAttribute('position').array.set(restPos); g.getAttribute('position').needsUpdate=true;
  g.getAttribute('normal').array.set(restNrm); g.getAttribute('normal').needsUpdate=true;
  if(restCol){ g.getAttribute('color').array.set(restCol); g.getAttribute('color').needsUpdate=true; }
  g.computeBoundingSphere();
}

// ---------------- Simulation glue ----------------
function ensureSim(){
  if(!simDirty && S) return;
  syncCore();
  const h=RES[state.sim.res];
  const bb=computeBounds(h*0.5);
  S=buildSim(bb.b0,bb.b1,h);
  applyMaterial(S,MATERIALS[state.mat]);
  EMB=embed(S,restPos);
  for(const p of state.pins){ p.base=null; p.nodes=null; p.visBase=null; p.delta.set(0,0,0); }
  rebuildPins();
  simDirty=false;
}
function rebuildPins(){
  if(!S) return;
  S.pinned.fill(0);
  for(const p of state.pins){
    if(!p.nodes){ p.nodes=nodesInSphere(S,S.rest,p.c.x,p.c.y,p.c.z,p.r,4); }
    if(!p.base){ p.base=new Float32Array(p.nodes.length*3); p.nodes.forEach((i,k)=>{ p.base[k*3]=S.x[i*3]; p.base[k*3+1]=S.x[i*3+1]; p.base[k*3+2]=S.x[i*3+2]; }); p.visBase=p.visBase||p.c.clone(); }
    p.nodes.forEach((i,k)=>{ S.pinned[i]=1; S.pinT[i*3]=p.base[k*3]+p.delta.x; S.pinT[i*3+1]=p.base[k*3+1]+p.delta.y; S.pinT[i*3+2]=p.base[k*3+2]+p.delta.z; });
    p.mesh.position.copy(p.visBase).add(p.delta);
  }
  updateInvM(S);
}
const pinMat=new THREE.MeshStandardMaterial({color:0x111111,transparent:true,opacity:0.18,depthWrite:false,roughness:0.4});
function addPin(hitPoint){
  // Treffer (verformt) → Ruhelage über nächsten Knoten
  let bi=0,bd=1e18; for(let i=0;i<S.n;i++){ const d=(S.x[i*3]-hitPoint.x)**2+(S.x[i*3+1]-hitPoint.y)**2+(S.x[i*3+2]-hitPoint.z)**2; if(d<bd){bd=d;bi=i;} }
  const c=new THREE.Vector3(S.rest[bi*3]+hitPoint.x-S.x[bi*3], S.rest[bi*3+1]+hitPoint.y-S.x[bi*3+1], S.rest[bi*3+2]+hitPoint.z-S.x[bi*3+2]);
  const r=state.sim.pinR;
  const mesh=new THREE.Mesh(new THREE.SphereGeometry(r,24,16),pinMat); mesh.renderOrder=5; scene.add(mesh);
  const dot=new THREE.Mesh(new THREE.SphereGeometry(2,10,8),new THREE.MeshBasicMaterial({color:0x111111})); mesh.add(dot);
  const p={c,r,delta:new THREE.Vector3(),nodes:null,base:null,visBase:hitPoint.clone(),mesh};
  state.pins.push(p);
  // nur diese Pin-Knoten neu auflösen, andere behalten
  p.nodes=nodesInSphere(S,S.rest,c.x,c.y,c.z,r,4);
  rebuildPins();
}
function removePin(p){ scene.remove(p.mesh); state.pins.splice(state.pins.indexOf(p),1); rebuildPins(); }
function applySimColors(){
  const col=surf.geometry.getAttribute('color').array;
  if(state.sim.display==='struct'){ col.set(restCol); }
  else if(state.sim.display==='E'){ const n=restPos.length/3; for(let i=0;i<n;i++) colorVertex(i,col,'E'); }
  surf.geometry.getAttribute('color').needsUpdate=true;
}
const _cc=[0,0,0];
function strainColors(){
  nodeStrain(S);
  const col=surf.geometry.getAttribute('color').array, J=S.J, ids=EMB.ids, wt=EMB.wt;
  for(let v=0;v<EMB.m;v++){
    let j=0; for(let c=0;c<8;c++) j+=J[ids[v*8+c]]*wt[v*8+c];
    if(j<0) ramp(STRAIN_NEG,-j/0.3,_cc); else ramp(STRAIN_POS,j/0.3,_cc);
    col[v*3]=_cc[0]; col[v*3+1]=_cc[1]; col[v*3+2]=_cc[2];
  }
  surf.geometry.getAttribute('color').needsUpdate=true;
}
let drag=null, simSub=12;
const grabLine=new THREE.Line(new THREE.BufferGeometry().setAttribute('position',new THREE.Float32BufferAttribute([0,0,0,0,0,0],3)),new THREE.LineBasicMaterial({color:0x111111,depthTest:false}));
grabLine.renderOrder=20; grabLine.visible=false; scene.add(grabLine);
function simFrame(){
  if(!S) return;
  if(state.sim.running){
    const M=MATERIALS[state.mat];
    const g=state.sim.grav?-9810*state.sim.gF:0;
    const damp=(0.5+state.sim.damp*state.sim.damp*80)*M.damp;
    const t0=performance.now();
    stepSim(S,1/60,simSub,{gx:0,gy:g,gz:0,damp,drag:drag?drag.core:null});
    const el=performance.now()-t0;   // Substeps adaptiv auf ~8 ms Budget
    simSub=clamp(Math.round(simSub*(8/Math.max(el,0.5))*0.5+simSub*0.5),4,24);
  }
  deform(S,EMB,surf.geometry.getAttribute('position').array);
  surf.geometry.getAttribute('position').needsUpdate=true;
  surf.geometry.computeVertexNormals();
  if(state.sim.display==='strain') strainColors();
  // HUD
  let line=`${S.n} Knoten · ${S.nt} Tets · E_eff ${fmtMPa(S.Emin)} – ${fmtMPa(S.Emax)}`;
  if(drag){
    let cx=0,cy=0,cz=0,rx=0,ry=0,rz=0; const d=drag.core;
    for(let k=0;k<d.ids.length;k++){ const i=d.ids[k]*3,w=d.w[k]; cx+=S.x[i]*w; cy+=S.x[i+1]*w; cz+=S.x[i+2]*w; rx+=S.rest[i]*w; ry+=S.rest[i+1]*w; rz+=S.rest[i+2]*w; }
    const disp=Math.hypot(cx-rx,cy-ry,cz-rz);
    line=`Kraft ${(S.lastF/1e6).toFixed(2)} N · Auslenkung ${disp.toFixed(1)} mm\n`+line;
    const a=grabLine.geometry.getAttribute('position').array; a[0]=cx;a[1]=cy;a[2]=cz;a[3]=d.tx;a[4]=d.ty;a[5]=d.tz; grabLine.geometry.getAttribute('position').needsUpdate=true; grabLine.visible=true;
  } else grabLine.visible=false;
  hud.textContent=line;
  simStats.textContent=`Sim-Zelle ${S.h} mm · ${simSub} Substeps · ${state.pins.length} Pin(s)`;
}
const fmtMPa=v=>v<0.01?(v*1000).toFixed(2)+' kPa':v.toFixed(3)+' MPa';

// ---------------- Picking ----------------
const ray=new THREE.Raycaster(), ndc=new THREE.Vector2();
function setRay(e){ const r=canvas.getBoundingClientRect(); ndc.set(((e.clientX-r.left)/r.width)*2-1,-((e.clientY-r.top)/r.height)*2+1); ray.setFromCamera(ndc,camera); }
function traceSDF(keep){
  const o=ray.ray.origin, d=ray.ray.direction; let t=0;
  for(let i=0;i<400;i++){
    const x=o.x+d.x*t, y=o.y+d.y*t, z=o.z+d.z*t, s=sdf(x,y,z);
    if(s<0.05 && (!keep||keep(x,y,z))) return {t,p:new THREE.Vector3(x,y,z)};
    t+=Math.max(Math.abs(s)*0.9,0.25); if(t>6000) break;
  }
  return null;
}
function pickStruct(){
  // Oberfläche (diesseits des Schnitts) oder Schnittfläche
  const sec=sectionActive(); const a=state.section.axis, v=secValue();
  const keep=sec?(x,y,z)=>([x,y,z][a]<=v+0.01):null;
  const hs=traceSDF(keep);
  let hp=null;
  if(sec){ const P=new THREE.Vector3(); if(ray.ray.intersectPlane(new THREE.Plane(new THREE.Vector3().setComponent(a,-1),v),P) && sdf(P.x,P.y,P.z)<0){ hp={t:P.distanceTo(ray.ray.origin),p:P,onCap:true}; } }
  if(hp && (!hs || hp.t<hs.t)) return hp;
  if(hs){ const g=[0,0,0]; sdfGrad(hs.p.x,hs.p.y,hs.p.z,g); hs.n=new THREE.Vector3(...g); return hs; }
  return null;
}
const brushRing=new THREE.Mesh(new THREE.RingGeometry(0.93,1,48),new THREE.MeshBasicMaterial({color:0x111111,transparent:true,opacity:0.7,depthTest:false,side:THREE.DoubleSide}));
brushRing.renderOrder=30; brushRing.visible=false; scene.add(brushRing);
function placeRing(p,n,R){ brushRing.visible=true; brushRing.position.copy(p).addScaledVector(n,0.5); brushRing.lookAt(p.clone().add(n)); brushRing.scale.setScalar(R); }

// ---------------- Pointer ----------------
const view=document.getElementById('view');
let down=null, painting=false, pinDrag=null;
view.addEventListener('pointerdown',e=>{
  down={x:e.clientX,y:e.clientY,btn:e.button,tcAxis:tc.axis};
  if(e.button!==0) return;
  setRay(e);
  if(state.mode==='struct'){
    const h=pickStruct(); if(h){ painting=true; controls.enabled=false; dab(h); }
  } else if(state.mode==='sim' && S){
    const pm=ray.intersectObjects(state.pins.map(p=>p.mesh),false)[0];
    if(pm){
      const p=state.pins.find(q=>q.mesh===pm.object);
      if(state.sim.tool==='pin'){ removePin(p); controls.enabled=false; down.consumed=true; return; }
      const pl=new THREE.Plane().setFromNormalAndCoplanarPoint(camera.getWorldDirection(new THREE.Vector3()).negate(),pm.point);
      pinDrag={p,pl,start:pm.point.clone(),d0:p.delta.clone()}; controls.enabled=false; return;
    }
    surf.geometry.computeBoundingSphere();
    const hit=ray.intersectObject(surf,false)[0];
    if(!hit) return;
    controls.enabled=false;
    if(state.sim.tool==='pin'){ addPin(hit.point); down.consumed=true; return; }
    const ids=nodesInSphere(S,S.x,hit.point.x,hit.point.y,hit.point.z,state.sim.grabR,3);
    const w=new Float32Array(ids.length); let W=0;
    ids.forEach((i,k)=>{ const d=Math.hypot(S.x[i*3]-hit.point.x,S.x[i*3+1]-hit.point.y,S.x[i*3+2]-hit.point.z)/state.sim.grabR; w[k]=Math.max(0.05,1-d*d); W+=w[k]; });
    for(let k=0;k<w.length;k++) w[k]/=W;
    const pl=new THREE.Plane().setFromNormalAndCoplanarPoint(camera.getWorldDirection(new THREE.Vector3()).negate(),hit.point);
    drag={pl,core:{ids:Int32Array.from(ids),w,tx:hit.point.x,ty:hit.point.y,tz:hit.point.z,F:state.sim.F*1e6,ramp:30}};
  }
},true);
window.addEventListener('pointermove',e=>{
  if(e.target!==canvas && !painting && !drag && !pinDrag) { brushRing.visible=false; return; }
  setRay(e);
  if(state.mode==='struct'){
    const h=pickStruct();
    if(h){ placeRing(h.p,h.onCap?new THREE.Vector3().setComponent(state.section.axis,-1):h.n,state.brush.R);
      const q=h.onCap?h.p:h.p.clone().addScaledVector(h.n,-2); sampleParams(q.x,q.y,q.z,_o); inspect(_o,h.onCap?'Schnitt · Innen':'Oberfläche'); }
    else brushRing.visible=false;
    if(painting && h) dab(h);
  } else if(state.mode==='form'){
    if(!tcDragging){ const h=traceSDF(null); if(h){ const g=[0,0,0]; sdfGrad(h.p.x,h.p.y,h.p.z,g); sampleParams(h.p.x-g[0]*2,h.p.y-g[1]*2,h.p.z-g[2]*2,_o); inspect(_o,'Oberfläche'); } }
  } else if(state.mode==='sim'){
    if(drag){ const P=new THREE.Vector3(); if(ray.ray.intersectPlane(drag.pl,P)){ drag.core.tx=P.x; drag.core.ty=P.y; drag.core.tz=P.z; drag.core.F=state.sim.F*1e6; } }
    if(pinDrag){ const P=new THREE.Vector3(); if(ray.ray.intersectPlane(pinDrag.pl,P)){ pinDrag.p.delta.copy(pinDrag.d0).add(P.sub(pinDrag.start)); rebuildPins(); } }
  }
});
window.addEventListener('pointerup',e=>{
  const moved=down?Math.hypot(e.clientX-down.x,e.clientY-down.y):99;
  if(state.mode==='form' && down && down.btn===0 && moved<4 && down.tcAxis===null && !tcDragging && e.target===canvas){
    setRay(e); const h=traceSDF(null);
    if(h){ let mi=-1,md=1e9; ST.blobs.forEach((B,i)=>{ const s=sdBlob(B,h.p.x,h.p.y,h.p.z); if(s<md){md=s;mi=i;} }); select(mi); }
    else select(-1);
  }
  if(painting){ painting=false; simDirty=true; }
  drag=null; pinDrag=null; down=null;
  if(!tcDragging) controls.enabled=true;
});
function dab(h){
  const B=state.brush, tgt=[B.t,B.d,B.b];
  let r;
  if(h.onCap) r=paintDab(h.p.x,h.p.y,h.p.z,null,0,0,B.R,0,B.flow,tgt,B.mask,B.erase);
  else r=paintDab(h.p.x,h.p.y,h.p.z,h.n.x,h.n.y,h.n.z,B.R,B.D,B.flow,tgt,B.mask,B.erase);
  recolorNear(h.p.x,h.p.y,h.p.z,r+6); capDirty=true;
}
window.addEventListener('keydown',e=>{
  if(e.target.tagName==='INPUT'||e.target.tagName==='SELECT') return;
  if(state.mode==='form'){
    if(e.key==='w'||e.key==='W'){ tc.setMode('translate'); gizmoSeg.upd(); }
    if(e.key==='e'||e.key==='E'){ tc.setMode('rotate'); gizmoSeg.upd(); }
    if(e.key==='Delete'||e.key==='Backspace') deleteSel();
  }
  if(state.mode==='sim' && e.code==='Space'){ e.preventDefault(); state.sim.running=!state.sim.running; window._runB.textContent=state.sim.running?'Pause':'Start'; }
});

// ---------------- Loop ----------------
function resize(){ const w=innerWidth, h=innerHeight; renderer.setSize(w,h,false); camera.aspect=w/h; camera.updateProjectionMatrix(); }
addEventListener('resize',resize); resize();
setMode('form'); select(0);
let lastSurf=0;
function loop(t){
  requestAnimationFrame(loop);
  if(surfDirty && state.mode!=='sim' && t-lastSurf>30){ surfDirty=false; lastSurf=t; rebuildSurface(); }
  if(capDirty) updateCap();
  if(state.mode==='sim') simFrame();
  controls.update();
  renderer.render(scene,camera);
  cellGroup.rotation.y+=0.006; cellR.render(cellScene,cellCam);
}
requestAnimationFrame(loop);
</script>
</body>
</html>