Back to the app
The code
Jelly Orange Slice by Claude Opus 5.5
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Orange Jelly Slice</title>
<style>
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#efe5d6;color:#4b2a0c;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none}
#c{position:fixed;inset:0;width:100vw;height:100vh;display:block;touch-action:none;outline:none}
#top{position:fixed;top:0;left:0;right:0;padding:calc(12px + env(safe-area-inset-top)) 16px 0;pointer-events:none;text-align:center}
#top h1{margin:0;font-size:19px;font-weight:800;letter-spacing:.3px}
#top p{margin:4px auto 0;font-size:13.5px;opacity:.72;max-width:520px}
#cap{display:inline-block;margin-top:10px;background:rgba(255,255,255,.86);border-radius:999px;padding:7px 16px;font-weight:800;font-size:15px;opacity:0;transition:opacity .25s;box-shadow:0 4px 14px rgba(120,70,20,.15)}
#badge{position:fixed;top:calc(12px + env(safe-area-inset-top));right:12px;background:#ff8a00;color:#fff;font-weight:800;font-size:12px;padding:6px 10px;border-radius:999px;display:none;pointer-events:none}
#panel{position:fixed;left:50%;bottom:calc(12px + env(safe-area-inset-bottom));transform:translateX(-50%);width:min(560px,calc(100vw - 24px));background:rgba(255,251,245,.86);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);border:1px solid rgba(255,255,255,.9);border-radius:24px;box-shadow:0 10px 30px rgba(120,70,20,.18);padding:10px 14px 14px}
.row{display:flex;gap:12px;align-items:center}
.lab{font-weight:800;font-size:15px}
#fv{font-size:13px;font-weight:700;opacity:.7;min-width:66px;text-align:right}
input[type=range]{-webkit-appearance:none;appearance:none;flex:1;height:48px;background:transparent;margin:0;touch-action:none;cursor:pointer}
input[type=range]::-webkit-slider-runnable-track{height:12px;border-radius:999px;background:linear-gradient(90deg,#ffe2b4,#ff9a1f)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:34px;height:34px;margin-top:-11px;border-radius:50%;background:#fff;border:3px solid #ff8a00;box-shadow:0 3px 8px rgba(0,0,0,.2)}
input[type=range]::-moz-range-track{height:12px;border-radius:999px;background:linear-gradient(90deg,#ffe2b4,#ff9a1f)}
input[type=range]::-moz-range-thumb{width:28px;height:28px;border-radius:50%;background:#fff;border:3px solid #ff8a00}
.btns{display:flex;gap:12px;margin-top:6px}
button{flex:1;min-height:58px;border-radius:18px;border:0;font:inherit;font-size:18px;font-weight:800;cursor:pointer;touch-action:manipulation;transition:transform .12s,opacity .2s}
button:active,button.flash{transform:scale(.94)}
button:disabled{opacity:.6}
#sq{background:linear-gradient(180deg,#ffb238,#ff8400);color:#fff;box-shadow:0 6px 16px rgba(255,130,0,.35)}
#rs{background:#fff;color:#8a4b12;border:2px solid #ffd39a}
.rip{position:fixed;width:56px;height:56px;margin:-28px 0 0 -28px;border-radius:50%;border:3px solid rgba(255,255,255,.95);pointer-events:none;animation:rip .55s ease-out forwards}
@keyframes rip{from{transform:scale(.3);opacity:1}to{transform:scale(1.4);opacity:0}}
#finger{position:fixed;left:0;top:0;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;background:rgba(255,255,255,.55);border:2px solid #fff;box-shadow:0 4px 14px rgba(0,0,0,.25);pointer-events:none;display:none}
#err{position:fixed;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:17px;background:#efe5d6}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="top">
<h1>Orange Jelly Slice</h1>
<p>Poke it · drag it to stretch, then let go · drag the background to turn the view</p>
<div id="cap"></div>
</div>
<div id="badge">DEMO · touch to play</div>
<div id="finger"></div>
<div id="panel">
<div class="row"><span class="lab">Firmness</span><input id="firm" type="range" min="0" max="100" value="40" aria-label="Firmness"><span id="fv">Wobbly</span></div>
<div class="btns"><button id="sq">Squeeze</button><button id="rs">Reset</button></div>
</div>
<div id="err">Sorry, this needs WebGL, which is not available in this browser.</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 { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
const TAU = Math.PI * 2;
const clamp = (x, a, b) => x < a ? a : x > b ? b : x;
const smooth = t => { t = clamp(t, 0, 1); return t * t * (3 - 2 * t); };
const $ = id => document.getElementById(id);
function mulberry32(a){ return function(){ a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
const mk = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h || w; return c; };
/* ---------------- renderer / scene ---------------- */
const canvas = $('c');
let renderer;
try { renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' }); }
catch (e) { $('err').style.display = 'flex'; throw e; }
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.0;
const MAXANI = renderer.capabilities.getMaxAnisotropy();
const scene = new THREE.Scene();
{ const c = mk(4, 256), g = c.getContext('2d'), gr = g.createLinearGradient(0, 0, 0, 256);
gr.addColorStop(0, '#f8f2e9'); gr.addColorStop(1, '#e8d8c2'); g.fillStyle = gr; g.fillRect(0, 0, 4, 256);
const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; scene.background = t; }
scene.fog = new THREE.Fog('#ece0cd', 9, 24);
try { const pm = new THREE.PMREMGenerator(renderer); scene.environment = pm.fromScene(new RoomEnvironment(renderer), 0.04).texture; } catch (e) {}
const camera = new THREE.PerspectiveCamera(36, 1, 0.05, 80);
const camTarget = new THREE.Vector3(0, 0.12, 0);
const cam = { az: 0, el: 0.62, dist: 4.6, taz: 0, tel: 0.62 };
function placeCamera(){
camera.position.set(camTarget.x + cam.dist * Math.cos(cam.el) * Math.sin(cam.az), camTarget.y + cam.dist * Math.sin(cam.el), camTarget.z + cam.dist * Math.cos(cam.el) * Math.cos(cam.az));
camera.lookAt(camTarget); camera.updateMatrixWorld();
}
scene.add(new THREE.HemisphereLight('#fff6ea', '#d8c2a2', 0.55));
const key = new THREE.DirectionalLight('#fff0da', 2.7); key.position.set(-1.0, 3.6, -2.4); scene.add(key);
const fill = new THREE.DirectionalLight('#ffffff', 0.75); fill.position.set(2.4, 2.2, 3.0); scene.add(fill);
const KEYDIR = key.position.clone().normalize();
const CAUS_DIR = new THREE.Vector2(-KEYDIR.x, -KEYDIR.z).normalize();
/* ---------------- procedural textures ---------------- */
function heightToNormal(src, k){
const w = src.width, h = src.height, d = src.getContext('2d').getImageData(0, 0, w, h).data;
const out = mk(w, h), o = out.getContext('2d'), img = o.createImageData(w, h), q = img.data;
for (let y = 0; y < h; y++) {
const yu = ((y - 1 + h) % h) * w, yd = ((y + 1) % h) * w, yc = y * w;
for (let x = 0; x < w; x++) {
const xl = (x - 1 + w) % w, xr = (x + 1) % w;
const nx = (d[(yc + xl) * 4] - d[(yc + xr) * 4]) * k / 255, ny = (d[(yd + x) * 4] - d[(yu + x) * 4]) * k / 255;
const l = 1 / Math.sqrt(nx * nx + ny * ny + 1), i = (yc + x) * 4;
q[i] = (nx * l * 0.5 + 0.5) * 255; q[i + 1] = (ny * l * 0.5 + 0.5) * 255; q[i + 2] = (l * 0.5 + 0.5) * 255; q[i + 3] = 255;
}
}
o.putImageData(img, 0, 0); return out;
}
function faceTextures(){
const S = 1024, C = S / 2, RP = 500, rnd = mulberry32(11);
const cc = mk(S), hc = mk(S), pc = mk(S);
const g = cc.getContext('2d'), h = hc.getContext('2d'), p = pc.getContext('2d');
const disc = (ctx, r, f) => { ctx.fillStyle = f; ctx.beginPath(); ctx.arc(C, C, r, 0, TAU); ctx.fill(); };
const rPI = RP * 0.962, rS = RP * 0.885, rC = RP * 0.07;
g.fillStyle = '#ef7a06'; g.fillRect(0, 0, S, S);
h.fillStyle = '#8c8c8c'; h.fillRect(0, 0, S, S);
p.fillStyle = 'rgb(30,85,0)'; p.fillRect(0, 0, S, S);
let gr = g.createRadialGradient(C, C, rPI, C, C, RP);
gr.addColorStop(0, '#ffab2e'); gr.addColorStop(0.45, '#ff9210'); gr.addColorStop(1, '#f07800'); disc(g, RP, gr);
gr = g.createRadialGradient(C, C, rS, C, C, rPI);
gr.addColorStop(0, '#fff4de'); gr.addColorStop(0.55, '#ffecca'); gr.addColorStop(0.85, '#ffd896'); gr.addColorStop(1, '#ffbd58'); disc(g, rPI, gr);
disc(g, rS, '#fde6c2');
disc(p, RP, 'rgb(45,80,0)'); disc(p, rPI, 'rgb(95,100,0)'); disc(p, rS, 'rgb(140,70,0)');
disc(h, RP, '#969696'); disc(h, rPI, '#8e8e8e'); disc(h, rS, '#7e7e7e');
g.lineWidth = 1.2;
for (let i = 0; i < 560; i++) {
const a = rnd() * TAU, r0 = rS + 2 + rnd() * (rPI - rS) * 0.75, l = 4 + rnd() * 10;
g.strokeStyle = `rgba(255,${200 + rnd() * 40 | 0},${130 + rnd() * 70 | 0},${0.25 + rnd() * 0.35})`;
g.beginPath(); g.moveTo(C + Math.cos(a) * r0, C + Math.sin(a) * r0); g.lineTo(C + Math.cos(a) * (r0 + l), C + Math.sin(a) * (r0 + l)); g.stroke();
}
for (let i = 0; i < 760; i++) {
const a = rnd() * TAU, r = rPI + 3 + rnd() * (RP - rPI - 5), s = 0.8 + rnd() * 1.6, x = C + Math.cos(a) * r, y = C + Math.sin(a) * r;
g.fillStyle = `rgba(${200 + rnd() * 40 | 0},${90 + rnd() * 40 | 0},0,0.45)`; g.beginPath(); g.arc(x, y, s, 0, TAU); g.fill();
h.fillStyle = 'rgba(40,40,40,0.5)'; h.beginPath(); h.arc(x, y, s, 0, TAU); h.fill();
}
const N = 11, ws = []; let sum = 0;
for (let i = 0; i < N; i++) { const w = 1 + (rnd() - 0.5) * 0.22; ws.push(w); sum += w; }
const mkCell = (ctx, stops) => { const q = ctx.createRadialGradient(0.18, 0, 0, 0, 0, 1); for (const s of stops) q.addColorStop(s[0], s[1]); return q; };
const cg = mkCell(g, [[0, 'rgba(255,228,152,0.85)'], [0.45, 'rgba(255,172,52,0.35)'], [0.82, 'rgba(232,108,0,0.38)'], [1, 'rgba(205,80,0,0)']]);
const hg = mkCell(h, [[0, 'rgba(255,255,255,0.95)'], [0.6, 'rgba(190,190,190,0.55)'], [1, 'rgba(90,90,90,0)']]);
const rin = rC + 6, rout = rS - 5;
let a0 = rnd() * TAU;
for (let si = 0; si < N; si++) {
const span = ws[si] / sum * TAU, am = a0 + span / 2, half = span / 2; a0 += span;
const hw = r => Math.max(0.0005, half - (2.6 + r * 0.006) / r) * Math.sqrt(clamp((r - rin) / 34, 0, 1));
const path = ctx => {
ctx.beginPath(); const K = 28;
for (let i = 0; i <= K; i++) { const r = rin + (rout - rin) * i / K, w = hw(r); ctx.lineTo(C + r * Math.cos(am - w), C + r * Math.sin(am - w)); }
ctx.arc(C, C, rout, am - hw(rout), am + hw(rout));
for (let i = K; i >= 0; i--) { const r = rin + (rout - rin) * i / K, w = hw(r); ctx.lineTo(C + r * Math.cos(am + w), C + r * Math.sin(am + w)); }
ctx.closePath();
};
const L = 50 + (rnd() - 0.5) * 6;
gr = g.createRadialGradient(C, C, rin, C, C, rout);
gr.addColorStop(0, `hsl(38,100%,${L + 12}%)`); gr.addColorStop(0.35, `hsl(32,100%,${L + 4}%)`); gr.addColorStop(1, `hsl(27,100%,${L - 2}%)`);
path(g); g.fillStyle = gr; g.fill();
path(p); p.fillStyle = 'rgb(245,20,0)'; p.fill();
path(h); h.fillStyle = '#6e6e6e'; h.fill();
g.save(); path(g); g.clip(); h.save(); path(h); h.clip();
for (let r = rin + 10; r < rout + 4; r += 13 + rnd() * 3) {
const w = hw(Math.min(r, rout)), n = Math.max(1, Math.round(2 * w * r / 10));
for (let k = 0; k < n; k++) {
const an = am - w + (k + 0.5 + (rnd() - 0.5) * 0.55) / n * 2 * w, rr = r + (rnd() - 0.5) * 6;
const x = C + rr * Math.cos(an), y = C + rr * Math.sin(an), len = 11 + rnd() * 8, wid = 3.8 + rnd() * 2.2;
const ca = Math.cos(an), sa = Math.sin(an);
g.setTransform(len * ca, len * sa, -wid * sa, wid * ca, x, y); g.fillStyle = cg; g.beginPath(); g.arc(0, 0, 1, 0, TAU); g.fill();
h.setTransform(len * ca, len * sa, -wid * sa, wid * ca, x, y); h.fillStyle = hg; h.beginPath(); h.arc(0, 0, 1, 0, TAU); h.fill();
}
}
g.setTransform(1, 0, 0, 1, 0, 0); h.setTransform(1, 0, 0, 1, 0, 0); g.restore(); h.restore();
}
gr = g.createRadialGradient(C, C, 0, C, C, rC + 9);
gr.addColorStop(0, '#fffaf0'); gr.addColorStop(0.7, '#fff0d4'); gr.addColorStop(1, 'rgba(255,232,190,0)'); disc(g, rC + 9, gr);
disc(p, rC + 2, 'rgb(90,90,0)'); disc(h, rC + 2, '#8a8a8a');
const col = new THREE.CanvasTexture(cc); col.colorSpace = THREE.SRGBColorSpace; col.anisotropy = MAXANI;
const nrm = new THREE.CanvasTexture(heightToNormal(hc, 3.0)); nrm.anisotropy = MAXANI;
const props = new THREE.CanvasTexture(pc); props.anisotropy = MAXANI;
return { col, nrm, props };
}
function peelTextures(){
const W = 512, H = 128, rnd = mulberry32(5), cc = mk(W, H), hc = mk(W, H), g = cc.getContext('2d'), h = hc.getContext('2d');
const gr = g.createLinearGradient(0, 0, 0, H);
gr.addColorStop(0, '#ffa634'); gr.addColorStop(0.25, '#ff9214'); gr.addColorStop(0.75, '#fb8408'); gr.addColorStop(1, '#f27a00');
g.fillStyle = gr; g.fillRect(0, 0, W, H); h.fillStyle = '#808080'; h.fillRect(0, 0, W, H);
for (let i = 0; i < 2600; i++) {
const x = rnd() * W, y = rnd() * H, r = 0.7 + rnd() * 1.7, dark = rnd() < 0.7;
const cs = dark ? `rgba(214,96,0,${0.25 + rnd() * 0.3})` : `rgba(255,198,112,${0.25 + rnd() * 0.3})`, hs = `rgba(30,30,30,${0.35 + rnd() * 0.35})`;
for (const ox of [0, x < 4 ? W : x > W - 4 ? -W : 0]) {
g.fillStyle = cs; g.beginPath(); g.arc(x + ox, y, r, 0, TAU); g.fill();
h.fillStyle = hs; h.beginPath(); h.arc(x + ox, y, r, 0, TAU); h.fill();
}
}
const col = new THREE.CanvasTexture(cc); col.colorSpace = THREE.SRGBColorSpace; col.wrapS = THREE.RepeatWrapping; col.anisotropy = MAXANI;
const nrm = new THREE.CanvasTexture(heightToNormal(hc, 2.5)); nrm.wrapS = THREE.RepeatWrapping; nrm.anisotropy = MAXANI;
return { col, nrm };
}
/* ---------------- jelly materials (physical + translucent glow) ---------------- */
const glowShared = { uBackDir: { value: new THREE.Vector3(0, 0, -1) } };
const GLOW_GLSL = `
{
vec3 gV = normalize(vViewPosition);
vec3 gN = normalize(normal);
float gM = 0.3;
#ifdef USE_TRANSMISSION
gM = material.transmission;
#endif
vec3 gH = normalize(uBackDir + gN * 0.3);
float gB = pow(clamp(dot(gV, -gH), 0.0, 1.0), 3.0);
float gR = pow(1.0 - clamp(abs(dot(gN, gV)), 0.0, 1.0), 2.0);
vec3 gC = diffuseColor.rgb * vec3(1.0, 0.62, 0.25);
outgoingLight += gC * gM * (gB * 1.5 + gR * 0.45 + 0.22) * uGlowAmt;
}
`;
function addGlow(mat, amt){
mat.onBeforeCompile = sh => {
sh.uniforms.uBackDir = glowShared.uBackDir;
sh.uniforms.uGlowAmt = { value: amt };
sh.fragmentShader = 'uniform vec3 uBackDir;\nuniform float uGlowAmt;\n' + sh.fragmentShader.replace('#include <opaque_fragment>', GLOW_GLSL + '\n#include <opaque_fragment>');
};
}
const FT = faceTextures(), PT = peelTextures();
const fleshMat = new THREE.MeshPhysicalMaterial({
map: FT.col, normalMap: FT.nrm, normalScale: new THREE.Vector2(0.6, 0.6),
roughness: 1, roughnessMap: FT.props, transmission: 1, transmissionMap: FT.props,
thickness: 0.45, ior: 1.36, attenuationColor: new THREE.Color('#ff9c2c'), attenuationDistance: 0.6,
clearcoat: 1, clearcoatRoughness: 0.035, envMapIntensity: 0.95
});
const peelMat = new THREE.MeshPhysicalMaterial({
map: PT.col, normalMap: PT.nrm, normalScale: new THREE.Vector2(0.8, 0.8), roughness: 0.38,
transmission: 0.22, thickness: 0.3, ior: 1.4, attenuationColor: new THREE.Color('#ff8a10'), attenuationDistance: 0.3,
clearcoat: 0.9, clearcoatRoughness: 0.12, envMapIntensity: 0.85
});
addGlow(fleshMat, 0.9); addGlow(peelMat, 0.5);
try { renderer.debug.onShaderError = () => { for (const m of [fleshMat, peelMat]) { m.onBeforeCompile = () => {}; m.needsUpdate = true; } }; } catch (e) {}
/* ---------------- slice mesh ---------------- */
const R = 1.0, T = 0.40, BV = 0.055, RF = R - BV, NA = 120, NR = 22, UVS = 500 / 1024;
const prof = [];
for (let i = 0; i <= 6; i++) { const a = Math.PI / 2 * (1 - i / 6); prof.push([RF + BV * Math.cos(a), T - BV + BV * Math.sin(a)]); }
for (let i = 1; i < 4; i++) prof.push([R, (T - BV) - (T - 2 * BV) * i / 4]);
for (let i = 0; i <= 6; i++) { const a = -Math.PI / 2 * i / 6; prof.push([RF + BV * Math.cos(a), BV + BV * Math.sin(a)]); }
const NP = prof.length, vcum = [0];
for (let i = 1; i < NP; i++) vcum.push(vcum[i - 1] + Math.hypot(prof[i][0] - prof[i - 1][0], prof[i][1] - prof[i - 1][1]));
const vlen = vcum[NP - 1];
const posA = [], uvA = [], idxA = [];
function face(y, top){
const s = posA.length / 3;
posA.push(0, y, 0); uvA.push(0.5, 0.5);
for (let i = 1; i <= NR; i++) { const r = RF * i / NR; for (let a = 0; a < NA; a++) { const th = a / NA * TAU, x = r * Math.cos(th), z = r * Math.sin(th); posA.push(x, y, z); uvA.push(0.5 + x / RF * UVS, 0.5 - z / RF * UVS); } }
const vid = (i, a) => s + 1 + (i - 1) * NA + (a % NA);
for (let a = 0; a < NA; a++) { if (top) idxA.push(s, vid(1, a + 1), vid(1, a)); else idxA.push(s, vid(1, a), vid(1, a + 1)); }
for (let i = 1; i < NR; i++) for (let a = 0; a < NA; a++) {
const a0 = vid(i, a), a1 = vid(i, a + 1), b0 = vid(i + 1, a), b1 = vid(i + 1, a + 1);
if (top) idxA.push(a0, b1, b0, a0, a1, b1); else idxA.push(a0, b0, b1, a0, b1, a1);
}
}
face(T, true); face(0, false);
const FACE_IDX = idxA.length, SIDE0 = posA.length / 3;
for (let a = 0; a <= NA; a++) { const th = a / NA * TAU, c = Math.cos(th), sn = Math.sin(th); for (let p = 0; p < NP; p++) { posA.push(prof[p][0] * c, prof[p][1], prof[p][0] * sn); uvA.push(a / NA * 5, 1 - vcum[p] / vlen); } }
for (let a = 0; a < NA; a++) for (let p = 0; p < NP - 1; p++) { const v00 = SIDE0 + a * NP + p, v01 = v00 + 1, v10 = v00 + NP, v11 = v10 + 1; idxA.push(v00, v10, v01, v10, v11, v01); }
const geo = new THREE.BufferGeometry();
const posAttr = new THREE.Float32BufferAttribute(posA, 3); posAttr.setUsage(THREE.DynamicDrawUsage);
geo.setAttribute('position', posAttr); geo.setAttribute('uv', new THREE.Float32BufferAttribute(uvA, 2));
geo.setIndex(idxA); geo.addGroup(0, FACE_IDX, 0); geo.addGroup(FACE_IDX, idxA.length - FACE_IDX, 1);
geo.computeVertexNormals();
const nrmAttr = geo.getAttribute('normal'); nrmAttr.setUsage(THREE.DynamicDrawUsage);
const NV = posA.length / 3;
const welds = [];
{ const m = new Map();
for (let v = 0; v < NV; v++) { const k = Math.round(posA[v * 3] * 1e4) + ',' + Math.round(posA[v * 3 + 1] * 1e4) + ',' + Math.round(posA[v * 3 + 2] * 1e4); let g = m.get(k); if (!g) m.set(k, g = []); g.push(v); }
for (const g of m.values()) if (g.length > 1) welds.push(g); }
function weldNormals(){
const n = nrmAttr.array;
for (const g of welds) { let x = 0, y = 0, z = 0; for (const v of g) { x += n[v * 3]; y += n[v * 3 + 1]; z += n[v * 3 + 2]; } const l = 1 / (Math.hypot(x, y, z) || 1); for (const v of g) { n[v * 3] = x * l; n[v * 3 + 1] = y * l; n[v * 3 + 2] = z * l; } }
}
const jelly = new THREE.Mesh(geo, [fleshMat, peelMat]);
scene.add(jelly);
/* ---------------- soft body: XPBD lattice + shape matching ---------------- */
const NXC = 12, NYC = 3, HX = 2 * R / NXC, HYC = T / NYC, X0 = -R, NN = NXC + 1;
const nodeId = (i, j, k) => (j * NN + k) * NN + i;
const colKept = new Uint8Array(NXC * NXC);
for (let i = 0; i < NXC; i++) for (let k = 0; k < NXC; k++) {
const cx = X0 + (i + 0.5) * HX, cz = X0 + (k + 0.5) * HX, nx = Math.max(Math.abs(cx) - HX / 2, 0), nz = Math.max(Math.abs(cz) - HX / 2, 0);
colKept[i * NXC + k] = nx * nx + nz * nz < (R + 0.003) * (R + 0.003) ? 1 : 0;
}
const nodeP = new Int32Array(NN * NN * (NYC + 1)).fill(-1), restA = [];
const useNode = (i, j, k) => { const id = nodeId(i, j, k); if (nodeP[id] < 0) { nodeP[id] = restA.length / 3; restA.push(X0 + i * HX, j * HYC, X0 + k * HX); } return nodeP[id]; };
const pairSet = new Set(), ci = [], cj = [];
for (let i = 0; i < NXC; i++) for (let k = 0; k < NXC; k++) {
if (!colKept[i * NXC + k]) continue;
for (let j = 0; j < NYC; j++) {
const c = [];
for (let dj = 0; dj < 2; dj++) for (let dk = 0; dk < 2; dk++) for (let di = 0; di < 2; di++) c.push(useNode(i + di, j + dj, k + dk));
for (let a = 0; a < 8; a++) for (let b = a + 1; b < 8; b++) { const lo = Math.min(c[a], c[b]), hi = Math.max(c[a], c[b]), key = lo * 8192 + hi; if (!pairSet.has(key)) { pairSet.add(key); ci.push(lo); cj.push(hi); } }
}
}
const NPART = restA.length / 3;
const REST = Float64Array.from(restA), P = Float64Array.from(restA), PR = Float64Array.from(restA), V = new Float64Array(NPART * 3), QR = new Float64Array(NPART * 3);
{ let x = 0, y = 0, z = 0; for (let o = 0; o < NPART * 3; o += 3) { x += REST[o]; y += REST[o + 1]; z += REST[o + 2]; } x /= NPART; y /= NPART; z /= NPART;
for (let o = 0; o < NPART * 3; o += 3) { QR[o] = REST[o] - x; QR[o + 1] = REST[o + 1] - y; QR[o + 2] = REST[o + 2] - z; } }
const NC = ci.length, CI = Int32Array.from(ci), CJ = Int32Array.from(cj), CL = new Float64Array(NC);
for (let c = 0; c < NC; c++) { const a = CI[c] * 3, b = CJ[c] * 3; CL[c] = Math.hypot(REST[b] - REST[a], REST[b + 1] - REST[a + 1], REST[b + 2] - REST[a + 2]); }
// embed every render vertex in its lattice cell (trilinear weights)
const EI = new Int32Array(NV * 8), EW = new Float32Array(NV * 8);
for (let v = 0; v < NV; v++) {
const x = posA[v * 3], y = posA[v * 3 + 1], z = posA[v * 3 + 2];
const fi = (x - X0) / HX, fk = (z - X0) / HX, fj = y / HYC;
let i = clamp(Math.floor(fi), 0, NXC - 1), k = clamp(Math.floor(fk), 0, NXC - 1);
const j = clamp(Math.floor(fj), 0, NYC - 1);
if (!colKept[i * NXC + k]) {
let best = 1e9, bi = i, bk = k;
for (let di = -1; di <= 1; di++) for (let dk = -1; dk <= 1; dk++) { const ii = i + di, kk = k + dk; if (ii < 0 || kk < 0 || ii >= NXC || kk >= NXC || !colKept[ii * NXC + kk]) continue; const d = Math.abs(fi - (ii + 0.5)) + Math.abs(fk - (kk + 0.5)); if (d < best) { best = d; bi = ii; bk = kk; } }
i = bi; k = bk;
}
const fx = clamp(fi - i, 0, 1), fy = clamp(fj - j, 0, 1), fz = clamp(fk - k, 0, 1);
let m = 0;
for (let dj = 0; dj < 2; dj++) for (let dk = 0; dk < 2; dk++) for (let di = 0; di < 2; di++) {
const id = nodeP[nodeId(i + di, j + dj, k + dk)];
EI[v * 8 + m] = id < 0 ? 0 : id;
EW[v * 8 + m] = id < 0 ? 0 : (di ? fx : 1 - fx) * (dj ? fy : 1 - fy) * (dk ? fz : 1 - fz);
m++;
}
}
function plateY(r){
if (r < 1.18) return 0;
if (r <= 1.76) { const t = (r - 1.18) / 0.58; return 0.17 * t * t * (1.6 - 0.6 * t); }
if (r <= 1.84) return 0.17;
return -0.088;
}
const prm = { at: 20, sm: 0.0015, damp: 1.7 };
const SUB = 10, FIXED = 1 / 60, MU = 0.45;
let comX = 0, comY = 0, comZ = 0, qx = 0, qy = 0, qz = 0, qw = 1;
const grab = { on: false, ids: [], w: [], off: [], start: new THREE.Vector3(), target: new THREE.Vector3(), plane: new THREE.Plane() };
const press = { phase: 0, t: 0, y: 99, cx: 0, cz: 0, emitted: 0, next: 0 };
function extractRot(a00, a01, a02, a10, a11, a12, a20, a21, a22){
for (let it = 0; it < 3; it++) {
const x = qx, y = qy, z = qz, w = qw;
const r00 = 1 - 2 * (y * y + z * z), r01 = 2 * (x * y - z * w), r02 = 2 * (x * z + y * w);
const r10 = 2 * (x * y + z * w), r11 = 1 - 2 * (x * x + z * z), r12 = 2 * (y * z - x * w);
const r20 = 2 * (x * z - y * w), r21 = 2 * (y * z + x * w), r22 = 1 - 2 * (x * x + y * y);
let ox = (r10 * a20 - r20 * a10) + (r11 * a21 - r21 * a11) + (r12 * a22 - r22 * a12);
let oy = (r20 * a00 - r00 * a20) + (r21 * a01 - r01 * a21) + (r22 * a02 - r02 * a22);
let oz = (r00 * a10 - r10 * a00) + (r01 * a11 - r11 * a01) + (r02 * a12 - r12 * a02);
const den = Math.abs(r00 * a00 + r10 * a10 + r20 * a20 + r01 * a01 + r11 * a11 + r21 * a21 + r02 * a02 + r12 * a12 + r22 * a22) + 1e-9;
ox /= den; oy /= den; oz /= den;
const ang = Math.sqrt(ox * ox + oy * oy + oz * oz);
if (ang < 1e-9) break;
const sh = Math.sin(ang * 0.5) / ang, dw = Math.cos(ang * 0.5), dx = ox * sh, dy = oy * sh, dz = oz * sh;
const nx = dw * x + dx * w + dy * z - dz * y, ny = dw * y - dx * z + dy * w + dz * x, nz = dw * z + dx * y - dy * x + dz * w, nw = dw * w - dx * x - dy * y - dz * z;
const l = 1 / Math.hypot(nx, ny, nz, nw); qx = nx * l; qy = ny * l; qz = nz * l; qw = nw * l;
}
}
function substep(dt){
const n3 = NPART * 3, damp = Math.exp(-prm.damp * dt), gdt = -9.81 * dt;
for (let o = 0; o < n3; o += 3) {
V[o] *= damp; V[o + 1] = (V[o + 1] + gdt) * damp; V[o + 2] *= damp;
PR[o] = P[o]; PR[o + 1] = P[o + 1]; PR[o + 2] = P[o + 2];
P[o] += V[o] * dt; P[o + 1] += V[o + 1] * dt; P[o + 2] += V[o + 2] * dt;
}
// XPBD distance constraints (edges + face & body diagonals of every cell)
const inv = 1 / (2 + prm.at);
for (let c = 0; c < NC; c++) {
const a = CI[c] * 3, b = CJ[c] * 3, dx = P[b] - P[a], dy = P[b + 1] - P[a + 1], dz = P[b + 2] - P[a + 2];
const d = Math.sqrt(dx * dx + dy * dy + dz * dz); if (d < 1e-8) continue;
const s = (d - CL[c]) * inv / d;
P[a] += dx * s; P[a + 1] += dy * s; P[a + 2] += dz * s; P[b] -= dx * s; P[b + 1] -= dy * s; P[b + 2] -= dz * s;
}
// global shape matching (shape memory, allows rotation)
let sx = 0, sy = 0, sz = 0, a00 = 0, a01 = 0, a02 = 0, a10 = 0, a11 = 0, a12 = 0, a20 = 0, a21 = 0, a22 = 0;
for (let o = 0; o < n3; o += 3) {
const x = P[o], y = P[o + 1], z = P[o + 2], X = QR[o], Y = QR[o + 1], Z = QR[o + 2];
sx += x; sy += y; sz += z; a00 += x * X; a01 += x * Y; a02 += x * Z; a10 += y * X; a11 += y * Y; a12 += y * Z; a20 += z * X; a21 += z * Y; a22 += z * Z;
}
comX = sx / NPART; comY = sy / NPART; comZ = sz / NPART;
extractRot(a00, a01, a02, a10, a11, a12, a20, a21, a22);
{ const x = qx, y = qy, z = qz, w = qw;
const r00 = 1 - 2 * (y * y + z * z), r01 = 2 * (x * y - z * w), r02 = 2 * (x * z + y * w);
const r10 = 2 * (x * y + z * w), r11 = 1 - 2 * (x * x + z * z), r12 = 2 * (y * z - x * w);
const r20 = 2 * (x * z - y * w), r21 = 2 * (y * z + x * w), r22 = 1 - 2 * (x * x + y * y);
const gx0 = comX * (1 - 0.0015), gy0 = comY, gz0 = comZ * (1 - 0.0015), k = prm.sm;
for (let o = 0; o < n3; o += 3) {
const X = QR[o], Y = QR[o + 1], Z = QR[o + 2];
P[o] += (r00 * X + r01 * Y + r02 * Z + gx0 - P[o]) * k;
P[o + 1] += (r10 * X + r11 * Y + r12 * Z + gy0 - P[o + 1]) * k;
P[o + 2] += (r20 * X + r21 * Y + r22 * Z + gz0 - P[o + 2]) * k;
} }
if (grab.on) {
const tx = grab.target.x, ty = grab.target.y, tz = grab.target.z;
for (let m = 0; m < grab.ids.length; m++) { const o = grab.ids[m] * 3, w = grab.w[m]; P[o] += (tx + grab.off[m * 3] - P[o]) * w; P[o + 1] += (ty + grab.off[m * 3 + 1] - P[o + 1]) * w; P[o + 2] += (tz + grab.off[m * 3 + 2] - P[o + 2]) * w; }
}
if (press.phase) {
const py = press.y;
for (let o = 0; o < n3; o += 3) if (P[o + 1] > py) { const dx = P[o] - press.cx, dz = P[o + 2] - press.cz; if (dx * dx + dz * dz < 1.69) { P[o + 1] = py; P[o] -= (P[o] - PR[o]) * 0.3; P[o + 2] -= (P[o + 2] - PR[o + 2]) * 0.3; } }
}
// plate contact with friction (applied last: never sinks)
for (let o = 0; o < n3; o += 3) { const f = plateY(Math.hypot(P[o], P[o + 2])); if (P[o + 1] < f) { P[o + 1] = f; P[o] -= (P[o] - PR[o]) * MU; P[o + 2] -= (P[o + 2] - PR[o + 2]) * MU; } }
const id = 1 / dt;
for (let o = 0; o < n3; o += 3) {
let vx = (P[o] - PR[o]) * id, vy = (P[o + 1] - PR[o + 1]) * id, vz = (P[o + 2] - PR[o + 2]) * id;
const s2 = vx * vx + vy * vy + vz * vz; if (s2 > 400) { const s = 20 / Math.sqrt(s2); vx *= s; vy *= s; vz *= s; }
V[o] = vx; V[o + 1] = vy; V[o + 2] = vz;
}
}
function relDamp(){
const kd = 0.015;
for (let c = 0; c < NC; c++) {
const a = CI[c] * 3, b = CJ[c] * 3, dx = P[b] - P[a], dy = P[b + 1] - P[a + 1], dz = P[b + 2] - P[a + 2], d = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (d < 1e-8) continue;
const nx = dx / d, ny = dy / d, nz = dz / d, rv = ((V[b] - V[a]) * nx + (V[b + 1] - V[a + 1]) * ny + (V[b + 2] - V[a + 2]) * nz) * kd;
V[a] += nx * rv; V[a + 1] += ny * rv; V[a + 2] += nz * rv; V[b] -= nx * rv; V[b + 1] -= ny * rv; V[b + 2] -= nz * rv;
}
}
function simStep(){
for (let s = 0; s < SUB; s++) substep(FIXED / SUB);
relDamp();
if (!Number.isFinite(comX + comY + comZ) || !Number.isFinite(P[0])) resetJelly(0.2);
}
function resetJelly(lift){
for (let o = 0; o < NPART * 3; o += 3) { P[o] = REST[o]; P[o + 1] = REST[o + 1] + lift; P[o + 2] = REST[o + 2]; PR[o] = P[o]; PR[o + 1] = P[o + 1]; PR[o + 2] = P[o + 2]; V[o] = V[o + 1] = V[o + 2] = 0; }
qx = qy = qz = 0; qw = 1; comX = 0; comZ = 0; comY = T / 2 + lift;
}
function updateMesh(){
const pa = posAttr.array;
for (let v = 0, o = 0; v < NV; v++, o += 8) {
let x = 0, y = 0, z = 0;
for (let m = 0; m < 8; m++) { const w = EW[o + m]; if (w === 0) continue; const p = EI[o + m] * 3; x += P[p] * w; y += P[p + 1] * w; z += P[p + 2] * w; }
pa[v * 3] = x; pa[v * 3 + 1] = y; pa[v * 3 + 2] = z;
}
posAttr.needsUpdate = true;
geo.computeVertexNormals(); weldNormals(); nrmAttr.needsUpdate = true;
geo.computeBoundingSphere();
}
/* ---------------- interactions on the body ---------------- */
function poke(pt, dir, strength){
const rp = 0.42;
for (let i = 0, o = 0; i < NPART; i++, o += 3) {
const d = Math.hypot(P[o] - pt.x, P[o + 1] - pt.y, P[o + 2] - pt.z);
if (d < rp) { const f = 1 - d / rp, s = strength * 2.6 * f * f; V[o] += dir.x * s; V[o + 1] += dir.y * s; V[o + 2] += dir.z * s; }
}
}
function startGrab(pt){
const rg = 0.4; grab.ids = []; grab.w = []; grab.off = [];
for (let i = 0, o = 0; i < NPART; i++, o += 3) {
const d = Math.hypot(P[o] - pt.x, P[o + 1] - pt.y, P[o + 2] - pt.z);
if (d < rg) { grab.ids.push(i); grab.w.push(0.28 * Math.pow(1 - d / rg, 1.5)); grab.off.push(P[o] - pt.x, P[o + 1] - pt.y, P[o + 2] - pt.z); }
}
grab.start.copy(pt); grab.target.copy(pt);
grab.plane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(new THREE.Vector3()), pt);
grab.on = grab.ids.length > 0;
}
function setGrabTarget(t){
const d = t.clone().sub(grab.start); if (d.length() > 0.85) d.setLength(0.85);
const tt = grab.start.clone().add(d); tt.y = Math.max(tt.y, 0.06);
const r = Math.hypot(tt.x, tt.z); if (r > 1.5) { tt.x *= 1.5 / r; tt.z *= 1.5 / r; }
grab.target.copy(tt);
}
function endGrab(){ grab.on = false; grab.ids = []; }
/* ---------------- plate, table, light pools ---------------- */
const topPts = [];
for (let i = 0; i <= 40; i++) { const r = 1.76 * i / 40; topPts.push(new THREE.Vector2(r, plateY(r))); }
const platePts = topPts.slice();
platePts.push(new THREE.Vector2(1.785, 0.168), new THREE.Vector2(1.8, 0.155), new THREE.Vector2(1.795, 0.138), new THREE.Vector2(1.77, 0.128));
for (let i = 1; i <= 14; i++) { const r = 1.76 - 0.68 * i / 14; platePts.push(new THREE.Vector2(r, plateY(r) - 0.045)); }
platePts.push(new THREE.Vector2(1.02, -0.05), new THREE.Vector2(1.0, -0.085), new THREE.Vector2(0.96, -0.088), new THREE.Vector2(0.92, -0.085), new THREE.Vector2(0.9, -0.055), new THREE.Vector2(0, -0.05));
const plate = new THREE.Mesh(new THREE.LatheGeometry(platePts, 96), new THREE.MeshPhysicalMaterial({ color: '#fbfaf7', roughness: 0.18, clearcoat: 1, clearcoatRoughness: 0.06, envMapIntensity: 0.9, side: THREE.DoubleSide }));
scene.add(plate);
const table = new THREE.Mesh(new THREE.CircleGeometry(40, 64), new THREE.MeshStandardMaterial({ color: '#eadcc6', roughness: 0.92 }));
table.rotation.x = -Math.PI / 2; table.position.y = -0.09; scene.add(table);
{ const c = mk(256), g = c.getContext('2d'), gr = g.createRadialGradient(128, 128, 0, 128, 128, 128);
gr.addColorStop(0, 'rgba(90,55,20,0.42)'); gr.addColorStop(0.7, 'rgba(90,55,20,0.34)'); gr.addColorStop(0.8, 'rgba(90,55,20,0.16)'); gr.addColorStop(1, 'rgba(90,55,20,0)');
g.fillStyle = gr; g.fillRect(0, 0, 256, 256);
const sh = new THREE.Mesh(new THREE.PlaneGeometry(4.6, 4.6), new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(c), transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4 }));
sh.rotation.x = -Math.PI / 2; sh.position.y = -0.0895; scene.add(sh); }
const OV_VS = 'varying vec3 vW; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }';
const topGeo = new THREE.LatheGeometry(topPts, 96);
const shadowMat = new THREE.ShaderMaterial({
uniforms: { uC: { value: new THREE.Vector2() } }, vertexShader: OV_VS,
fragmentShader: 'uniform vec2 uC; varying vec3 vW; void main(){ float d = length(vW.xz - uC); float a = 0.30 * (1.0 - smoothstep(0.88, 1.2, d)) + 0.10 * (1.0 - smoothstep(0.95, 1.6, d)); gl_FragColor = vec4(0.32, 0.16, 0.04, a); }',
transparent: true, depthWrite: false, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4
});
const causMat = new THREE.ShaderMaterial({
uniforms: { uC: { value: new THREE.Vector2() }, uD: { value: CAUS_DIR.clone() }, uAmt: { value: 0.45 } }, vertexShader: OV_VS,
fragmentShader: 'uniform vec2 uC; uniform vec2 uD; uniform float uAmt; varying vec3 vW; void main(){ vec2 p = vW.xz - uC; vec2 q = p - uD * 0.62; float al = dot(q, uD), ac = dot(q, vec2(-uD.y, uD.x)); float e = exp(-(al * al * 3.2 + ac * ac * 2.2)); vec2 s = p - uD * 0.3; float st = 0.84 + 0.16 * cos(atan(s.y, s.x) * 11.0); gl_FragColor = vec4(vec3(1.0, 0.5, 0.1) * e * st * uAmt, 1.0); }',
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -6
});
const shadowMesh = new THREE.Mesh(topGeo, shadowMat); shadowMesh.renderOrder = 1; scene.add(shadowMesh);
const causMesh = new THREE.Mesh(topGeo, causMat); causMesh.renderOrder = 2; scene.add(causMesh);
/* ---------------- squeeze press + juice ---------------- */
const glassMat = new THREE.MeshPhysicalMaterial({ color: '#ffffff', roughness: 0.04, transparent: true, opacity: 0.22, clearcoat: 1, clearcoatRoughness: 0.03, envMapIntensity: 1.6, depthWrite: false });
const knobMat = new THREE.MeshStandardMaterial({ color: '#c8875a', roughness: 0.55 });
const pressGroup = new THREE.Group();
{ const d = new THREE.Mesh(new THREE.CylinderGeometry(1.22, 1.22, 0.06, 72), glassMat); d.position.y = 0.03;
const ring = new THREE.Mesh(new THREE.TorusGeometry(1.22, 0.03, 12, 72), glassMat); ring.rotation.x = Math.PI / 2; ring.position.y = 0.03;
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.09, 0.42, 24), knobMat); stem.position.y = 0.27;
const knob = new THREE.Mesh(new THREE.SphereGeometry(0.17, 24, 16), knobMat); knob.position.y = 0.55;
pressGroup.add(d, ring, stem, knob); }
pressGroup.visible = false; scene.add(pressGroup);
const PRESS_TOP = T + 1.4, PRESS_LOW = T * 0.46;
const sqBtn = $('sq');
const ease = t => t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
function startSqueeze(){
if (press.phase) return;
endGrab();
press.phase = 1; press.t = 0; press.cx = comX; press.cz = comZ; press.emitted = 0; press.next = 0; press.y = PRESS_TOP;
pressGroup.visible = true; sqBtn.disabled = true;
}
function stopPress(){ press.phase = 0; press.y = 99; pressGroup.visible = false; sqBtn.disabled = false; }
function updatePress(dt){
if (!press.phase) return;
press.t += dt;
if (press.phase === 1) { const u = Math.min(1, press.t / 1.0); press.y = PRESS_TOP + (PRESS_LOW - PRESS_TOP) * ease(u); if (u >= 1) { press.phase = 2; press.t = 0; } }
else if (press.phase === 2) { press.y = PRESS_LOW - 0.01 * Math.sin(press.t * 7); if (press.t > 1.9) { press.phase = 3; press.t = 0; } }
else { const u = Math.min(1, press.t / 0.9); press.y = PRESS_LOW + (PRESS_TOP - PRESS_LOW) * u * u; if (u >= 1) { stopPress(); return; } }
if ((press.phase === 1 && press.y < T * 0.64) || press.phase === 2) {
press.next -= dt;
if (press.next <= 0 && press.emitted < 6) { emitDrop(); press.emitted++; press.next = 0.22 + Math.random() * 0.2; }
}
pressGroup.position.set(press.cx, press.y, press.cz);
}
const drops = [], dropGeo = new THREE.SphereGeometry(1, 20, 14);
const dropMat = new THREE.MeshPhysicalMaterial({ color: '#ff9a1e', emissive: '#6b2400', emissiveIntensity: 0.5, roughness: 0.05, clearcoat: 1, clearcoatRoughness: 0.02, transparent: true, opacity: 0.86, envMapIntensity: 1.4 });
function emitDrop(){
if (drops.length > 30) return;
const th = Math.atan2(camera.position.z - comZ, camera.position.x - comX) + (Math.random() * 2 - 1) * 1.15;
const a = Math.round(((th % TAU) + TAU) % TAU / TAU * NA) % NA;
const m = new THREE.Mesh(dropGeo, dropMat.clone()); m.scale.setScalar(0.001); m.renderOrder = 3; scene.add(m);
drops.push({ m, a, s: 2 + Math.random() * 2.5, sp: 0.8, phase: 0, t: 0, size: 0.032 + Math.random() * 0.018, px: 0, pz: 0, ox: 0, oz: 0 });
}
const tP = new THREE.Vector3(), tN = new THREE.Vector3();
function sidePos(a, s){
const p0 = Math.min(NP - 2, Math.floor(s)), f = clamp(s - p0, 0, 1), i0 = (SIDE0 + a * NP + p0) * 3, i1 = i0 + 3, pa = posAttr.array, na = nrmAttr.array;
tP.set(pa[i0] + (pa[i1] - pa[i0]) * f, pa[i0 + 1] + (pa[i1 + 1] - pa[i0 + 1]) * f, pa[i0 + 2] + (pa[i1 + 2] - pa[i0 + 2]) * f);
tN.set(na[i0] + (na[i1] - na[i0]) * f, na[i0 + 1] + (na[i1 + 1] - na[i0 + 1]) * f, na[i0 + 2] + (na[i1 + 2] - na[i0 + 2]) * f).normalize();
}
function updateDrops(dt){
for (let i = drops.length - 1; i >= 0; i--) {
const d = drops[i], m = d.m; d.t += dt;
if (d.phase === 0) {
const k = Math.min(1, d.t / 0.35); sidePos(d.a, d.s);
m.position.copy(tP).addScaledVector(tN, d.size * 0.55); m.scale.set(d.size * k, d.size * 1.1 * k, d.size * k);
if (k >= 1) { d.phase = 1; d.t = 0; }
} else if (d.phase === 1) {
d.sp += 7 * dt; d.s += d.sp * dt;
if (d.s >= NP - 1) {
sidePos(d.a, NP - 1);
let ox = tP.x - comX, oz = tP.z - comZ; const l = Math.hypot(ox, oz) || 1; d.ox = ox / l; d.oz = oz / l;
d.px = tP.x + d.ox * 0.04; d.pz = tP.z + d.oz * 0.04; d.phase = 2; d.t = 0;
} else { sidePos(d.a, d.s); m.position.copy(tP).addScaledVector(tN, d.size * 0.6); m.scale.set(d.size * 0.9, d.size * 1.35, d.size * 0.9); }
}
if (d.phase === 2) {
const e = 1 - Math.pow(1 - Math.min(1, d.t / 1.0), 3), r = d.size * (1 + 1.7 * e);
const x = d.px + d.ox * 0.09 * e, z = d.pz + d.oz * 0.09 * e;
m.position.set(x, plateY(Math.hypot(x, z)) + d.size * (0.3 - 0.12 * e), z);
m.scale.set(r, d.size * (0.75 - 0.5 * e), r);
if (d.t > 5) { m.material.opacity = 0.86 * (1 - (d.t - 5) / 1.5); if (d.t > 6.5) { scene.remove(m); m.material.dispose(); drops.splice(i, 1); } }
}
}
}
function clearDrops(){ for (const d of drops) { scene.remove(d.m); d.m.material.dispose(); } drops.length = 0; }
/* ---------------- UI ---------------- */
const firmEl = $('firm'), fvEl = $('fv'), capEl = $('cap'), fingerEl = $('finger');
function setFirm(v){
v = clamp(v, 0, 100); if (+firmEl.value !== Math.round(v)) firmEl.value = Math.round(v);
const f = v / 100;
prm.at = Math.exp(Math.log(80) + (Math.log(2.5) - Math.log(80)) * f);
prm.sm = Math.exp(Math.log(0.0006) + (Math.log(0.0065) - Math.log(0.0006)) * f);
prm.damp = 1.25 + 1.2 * f;
fvEl.textContent = v < 20 ? 'Very soft' : v < 45 ? 'Wobbly' : v < 72 ? 'Bouncy' : 'Firm';
}
function resetAll(){ endGrab(); stopPress(); clearDrops(); resetJelly(0.22); cam.taz = 0; cam.tel = 0.62; }
firmEl.addEventListener('input', () => setFirm(+firmEl.value));
sqBtn.addEventListener('click', () => startSqueeze());
$('rs').addEventListener('click', () => resetAll());
function ripple(x, y){ const r = document.createElement('div'); r.className = 'rip'; r.style.left = x + 'px'; r.style.top = y + 'px'; document.body.appendChild(r); setTimeout(() => r.remove(), 600); }
function flash(id){ const b = $(id); b.classList.add('flash'); setTimeout(() => b.classList.remove('flash'), 230); }
function caption(t){ capEl.textContent = t; capEl.style.opacity = t ? 1 : 0; }
const tmpV = new THREE.Vector3();
function toScreen(p){ tmpV.copy(p).project(camera); return [(tmpV.x + 1) / 2 * innerWidth, (1 - tmpV.y) / 2 * innerHeight]; }
function showFinger(p){ const [x, y] = toScreen(p); fingerEl.style.display = 'block'; fingerEl.style.transform = `translate(${x}px,${y}px)`; }
function hideFinger(){ fingerEl.style.display = 'none'; }
const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
function setRay(x, y){ ndc.set(x / innerWidth * 2 - 1, -(y / innerHeight) * 2 + 1); ray.setFromCamera(ndc, camera); }
const ptr = { id: null, mode: null, x0: 0, y0: 0, lx: 0, ly: 0, hit: null, moved: false };
canvas.addEventListener('pointerdown', e => {
if (ptr.id !== null) return;
ptr.id = e.pointerId; try { canvas.setPointerCapture(e.pointerId); } catch (_) {}
ptr.x0 = ptr.lx = e.clientX; ptr.y0 = ptr.ly = e.clientY; ptr.moved = false;
setRay(e.clientX, e.clientY);
const hits = ray.intersectObject(jelly, false);
if (hits.length) { ptr.mode = 'jelly'; ptr.hit = hits[0].point.clone(); poke(ptr.hit, ray.ray.direction, 1); ripple(e.clientX, e.clientY); }
else ptr.mode = 'orbit';
e.preventDefault();
});
canvas.addEventListener('pointermove', e => {
if (e.pointerId !== ptr.id) return;
const dx = e.clientX - ptr.lx, dy = e.clientY - ptr.ly; ptr.lx = e.clientX; ptr.ly = e.clientY;
if (!ptr.moved && Math.hypot(e.clientX - ptr.x0, e.clientY - ptr.y0) > 6) { ptr.moved = true; if (ptr.mode === 'jelly' && !press.phase) startGrab(ptr.hit); }
if (ptr.mode === 'jelly' && grab.on) { setRay(e.clientX, e.clientY); const t = new THREE.Vector3(); if (ray.ray.intersectPlane(grab.plane, t)) setGrabTarget(t); }
else if (ptr.mode === 'orbit' && ptr.moved) { cam.taz -= dx * 0.008; cam.tel = clamp(cam.tel + dy * 0.006, 0.22, 1.25); }
});
const endPtr = e => { if (e.pointerId !== ptr.id) return; if (grab.on) endGrab(); ptr.id = null; ptr.mode = null; };
canvas.addEventListener('pointerup', endPtr); canvas.addEventListener('pointercancel', endPtr); canvas.addEventListener('lostpointercapture', endPtr);
/* ---------------- #demo: hands-free 20 s loop ---------------- */
const demo = { on: false, t: 0, fired: 0, from: new THREE.Vector3(), to: new THREE.Vector3() };
function surfacePoint(x, y, z){
const p = new THREE.Vector3(x, y, z), dir = p.clone().sub(camera.position).normalize();
ray.set(camera.position, dir); const h = ray.intersectObject(jelly, false);
return { p: h.length ? h[0].point.clone() : p, dir };
}
function demoPoke(x, z){ const s = surfacePoint(x, T, z); poke(s.p, s.dir, 1.15); showFinger(s.p); const [sx, sy] = toScreen(s.p); ripple(sx, sy); setTimeout(() => { if (demo.on && !grab.on) hideFinger(); }, 450); }
function demoGrab(){
const hx = Math.sin(cam.az), hz = Math.cos(cam.az), s = surfacePoint(comX + hx * R * 0.98, T * 0.55, comZ + hz * R * 0.98);
startGrab(s.p); demo.from.copy(s.p); demo.to.set(s.p.x + hx * 0.55, s.p.y + 0.42, s.p.z + hz * 0.55);
}
const DEMO = [
[0.0, () => { resetAll(); setFirm(40); caption('Real soft-body jelly — Reset drops it in'); flash('rs'); }],
[2.3, () => { caption('Poke it'); demoPoke(0.3, 0.25); }],
[3.5, () => demoPoke(-0.35, -0.1)],
[4.9, () => { caption('Drag to stretch… and let go'); demoGrab(); }],
[6.7, () => { endGrab(); hideFinger(); }],
[8.4, () => caption('Firmness: firm → snappy jiggle')],
[9.3, () => { setFirm(95); demoPoke(0.15, 0.3); }],
[10.6, () => caption('Firmness: soft → slow wobble')],
[11.6, () => { setFirm(8); demoPoke(0.15, 0.3); }],
[13.0, () => { setFirm(40); caption('Squeeze → juice runs out'); flash('sq'); startSqueeze(); }],
[19.3, () => caption('')]
];
function demoUpdate(dt){
demo.t += dt;
if (demo.t >= 20) { demo.t -= 20; demo.fired = 0; }
while (demo.fired < DEMO.length && demo.t >= DEMO[demo.fired][0]) { DEMO[demo.fired][1](); demo.fired++; }
const t = demo.t;
if (t > 8.4 && t < 9.0) setFirm(40 + 55 * smooth((t - 8.4) / 0.6));
if (t > 10.6 && t < 11.2) setFirm(95 - 87 * smooth((t - 10.6) / 0.6));
if (t > 12.4 && t < 12.95) setFirm(8 + 32 * smooth((t - 12.4) / 0.55));
if (grab.on && t >= 4.9 && t < 6.7) { setGrabTarget(demo.from.clone().lerp(demo.to, smooth((t - 5.0) / 1.1))); showFinger(grab.target); }
cam.taz = 0.35 * Math.sin(TAU * t / 20);
}
function startDemo(){ demo.on = true; demo.t = 0; demo.fired = 0; $('badge').style.display = 'block'; }
function stopDemo(){ if (!demo.on) return; demo.on = false; $('badge').style.display = 'none'; caption(''); hideFinger(); endGrab(); }
window.addEventListener('pointerdown', e => { if (demo.on && e.isTrusted) stopDemo(); }, true);
window.addEventListener('touchstart', e => { if (demo.on && e.isTrusted) stopDemo(); }, { capture: true, passive: true });
window.addEventListener('hashchange', () => { if (location.hash === '#demo') startDemo(); });
/* ---------------- resize + loop ---------------- */
function resize(){
const w = innerWidth, h = innerHeight;
renderer.setSize(w, h, false);
camera.aspect = w / h; camera.fov = camera.aspect < 0.8 ? 46 : 36;
const tanH = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));
cam.dist = Math.max(4.4, 1.5 / (tanH * camera.aspect));
const ph = $('panel').offsetHeight + 16;
camera.setViewOffset(w, h, 0, ph * 0.42, w, h);
camera.updateProjectionMatrix();
}
addEventListener('resize', resize);
resize();
setFirm(40);
resetJelly(0.3);
placeCamera();
updateMesh();
if (location.hash === '#demo') startDemo();
let last = performance.now(), acc = 0;
function frame(now){
requestAnimationFrame(frame);
let dt = (now - last) / 1000; last = now; if (!(dt > 0)) dt = 0; if (dt > 0.1) dt = 0.1;
if (demo.on) demoUpdate(dt);
const k = Math.min(1, dt * 8); cam.az += (cam.taz - cam.az) * k; cam.el += (cam.tel - cam.el) * k;
placeCamera();
acc += dt; let steps = 0;
while (acc >= FIXED && steps < 2) { updatePress(FIXED); simStep(); acc -= FIXED; steps++; }
if (steps === 2 && acc > FIXED) acc = 0;
updateMesh(); updateDrops(dt);
shadowMat.uniforms.uC.value.set(comX + CAUS_DIR.x * 0.07, comZ + CAUS_DIR.y * 0.07);
causMat.uniforms.uC.value.set(comX, comZ);
glowShared.uBackDir.value.copy(KEYDIR).transformDirection(camera.matrixWorldInverse);
renderer.render(scene, camera);
}
requestAnimationFrame(frame);
</script>
</body>
</html>
