Back to the app
The code
Jelly Orange Slice by Claude Fable 5.2
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>Jelly Orange Slice</title>
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #06222a; color: #fff;
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; }
#c { position: fixed; left: 0; top: 0; width: 100%; height: 100%; display: block; touch-action: none; outline: none; }
#top { position: fixed; left: 0; right: 0; top: 0; padding: 14px 16px; pointer-events: none;
padding-top: max(14px, env(safe-area-inset-top)); text-align: center; }
#top h1 { margin: 0; font-size: 20px; font-weight: 700; letter-spacing: .3px; color: #ffe2b8;
text-shadow: 0 2px 10px rgba(0,0,0,.5); }
#hint { margin-top: 6px; font-size: 15px; color: rgba(255,255,255,.82); transition: opacity .8s; }
#hint.off { opacity: 0; }
#cap { display: none; margin: 10px auto 0; padding: 8px 18px; border-radius: 999px; font-size: 18px; font-weight: 700;
background: rgba(255,138,0,.92); color: #2a1200; width: max-content; max-width: 90vw; box-shadow: 0 4px 16px rgba(0,0,0,.35); }
#ui { position: fixed; left: 50%; transform: translateX(-50%); bottom: max(10px, env(safe-area-inset-bottom));
width: min(94vw, 640px); box-sizing: border-box; display: flex; flex-wrap: wrap; gap: 10px; align-items: center;
padding: 12px 14px; border-radius: 20px; background: rgba(4,26,33,.74); border: 1px solid rgba(255,255,255,.14);
-webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); box-shadow: 0 8px 30px rgba(0,0,0,.4); }
.srow { flex: 1 1 100%; display: flex; align-items: center; gap: 10px; }
.srow label { font-size: 16px; font-weight: 700; color: #ffe2b8; white-space: nowrap; }
.srow span { font-size: 13px; color: rgba(255,255,255,.7); }
button { flex: 1 1 0; min-height: 56px; border-radius: 16px; font-size: 19px; font-weight: 800; font-family: inherit;
cursor: pointer; touch-action: manipulation; border: 0; padding: 0 16px; }
#squeeze { background: linear-gradient(180deg, #ffb53a, #ff7a00); color: #2a1200; box-shadow: 0 4px 0 #b24e00; }
#squeeze:active { transform: translateY(2px); box-shadow: 0 2px 0 #b24e00; }
#squeeze:disabled { opacity: .55; }
#reset { background: rgba(255,255,255,.1); color: #fff; border: 2px solid rgba(255,255,255,.55); }
#reset:active { background: rgba(255,255,255,.25); }
input[type=range] { -webkit-appearance: none; appearance: none; flex: 1 1 auto; min-width: 0; height: 46px;
background: transparent; margin: 0; touch-action: none; cursor: pointer; }
input[type=range]:focus { outline: none; }
input[type=range]::-webkit-slider-runnable-track { height: 12px; border-radius: 6px; background: linear-gradient(90deg, #ffe0ae, #ff8a00); }
input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 36px; height: 36px; border-radius: 50%;
background: #fff; border: 5px solid #ff8a00; margin-top: -12px; box-shadow: 0 2px 8px rgba(0,0,0,.45); }
input[type=range]::-moz-range-track { height: 12px; border-radius: 6px; background: linear-gradient(90deg, #ffe0ae, #ff8a00); }
input[type=range]::-moz-range-thumb { width: 28px; height: 28px; border-radius: 50%; background: #fff; border: 5px solid #ff8a00; }
@media (min-width: 780px) {
#ui { flex-wrap: nowrap; width: min(94vw, 820px); }
.srow { flex: 1 1 auto; }
button { flex: 0 0 150px; }
}
#cursor { position: fixed; left: 0; top: 0; width: 46px; height: 46px; margin: -23px 0 0 -23px; border-radius: 50%;
border: 3px solid rgba(255,255,255,.95); background: rgba(255,255,255,.22); pointer-events: none; display: none;
transition: transform .12s, background .12s; box-shadow: 0 2px 10px rgba(0,0,0,.4); }
#cursor.down { transform: scale(.72); background: rgba(255,255,255,.55); }
#msg { display: none; position: fixed; left: 50%; top: 45%; transform: translate(-50%,-50%); max-width: 80vw;
padding: 16px 20px; border-radius: 14px; background: rgba(0,0,0,.6); font-size: 17px; text-align: center; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="top">
<h1>Jelly Orange Slice</h1>
<div id="hint">Tap the jelly to poke it · drag it to stretch · drag around it to turn</div>
<div id="cap"></div>
</div>
<div id="ui">
<div class="srow">
<label for="firm">Firmness</label>
<span>soft</span>
<input id="firm" type="range" min="0" max="100" step="1" value="40" aria-label="Firmness">
<span>firm</span>
</div>
<button id="squeeze" type="button">Squeeze</button>
<button id="reset" type="button">Reset</button>
</div>
<div id="cursor"></div>
<div id="msg"></div>
<script src="https://cdn.jsdelivr.net/npm/three@0.152.2/build/three.min.js"></script>
<script>
(function () {
'use strict';
const msgEl = document.getElementById('msg');
function fail(t) { msgEl.textContent = t; msgEl.style.display = 'block'; }
if (!window.THREE) { fail('The 3D library could not be loaded. Please check the connection and reload.'); return; }
const THREE = window.THREE;
const canvas = document.getElementById('c');
const uiEl = document.getElementById('ui');
const hintEl = document.getElementById('hint');
const capEl = document.getElementById('cap');
const cursorEl = document.getElementById('cursor');
const sqBtn = document.getElementById('squeeze');
const resetBtn = document.getElementById('reset');
const firmEl = document.getElementById('firm');
let renderer;
try {
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true, alpha: false, powerPreference: 'high-performance' });
} catch (e) { fail('WebGL is not available on this device.'); return; }
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x06222a, 1);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(35, 1, 0.5, 700);
const KEY = new THREE.Vector3(-0.35, 0.85, -0.55).normalize();
const FILL = new THREE.Vector3(0.5, 0.6, 0.8).normalize();
/* ------------------------------------------------------------------ */
/* Shape definition (shared by JS and GLSL) */
/* ------------------------------------------------------------------ */
const R = 1.0, BEV = 0.07;
function halfT(r) { let t = r / R; t = t < 0 ? 0 : (t > 1 ? 1 : t); return 0.17 + 0.07 * (t * t * (3 - 2 * t)); }
/* ------------------------------------------------------------------ */
/* Soft body: lattice of particles */
/* ------------------------------------------------------------------ */
const NX = 11, NY = 6, NZ = 4, X0 = -1, Y0 = 0, Z0 = -0.27, DX = 0.2, DY = 0.2, DZ = 0.18;
const CX = NX - 1, CY = NY - 1, CZ = NZ - 1;
const cellOn = new Uint8Array(CX * CY * CZ);
const nodeMap = new Int32Array(NX * NY * NZ).fill(-1);
const cIdx = (x, y, z) => x + CX * (y + CY * z);
const nIdx = (x, y, z) => x + NX * (y + NY * z);
const restList = [], baseList = [];
let NP = 0;
for (let iz = 0; iz < CZ; iz++) for (let iy = 0; iy < CY; iy++) for (let ix = 0; ix < CX; ix++) {
const x0 = X0 + ix * DX, x1 = x0 + DX, y0 = Y0 + iy * DY;
const nx = Math.max(x0, Math.min(0, x1));
if (nx * nx + y0 * y0 < 0.999) {
cellOn[cIdx(ix, iy, iz)] = 1;
for (let c = 0; c < 8; c++) {
const jx = ix + (c & 1), jy = iy + ((c >> 1) & 1), jz = iz + ((c >> 2) & 1);
const n = nIdx(jx, jy, jz);
if (nodeMap[n] < 0) {
nodeMap[n] = NP++;
restList.push(X0 + jx * DX, Y0 + jy * DY, Z0 + jz * DZ);
baseList.push(jy === 0 ? 1 : 0);
}
}
}
}
const R0 = new Float64Array(restList);
const P = new Float64Array(R0), Q = new Float64Array(R0), V = new Float64Array(NP * 3);
const isBase = new Uint8Array(baseList);
// distance constraints: every pair of corners of every active cell (edges, face diagonals, body diagonals)
const seen = new Set(), cAl = [], cBl = [], cLl = [];
for (let iz = 0; iz < CZ; iz++) for (let iy = 0; iy < CY; iy++) for (let ix = 0; ix < CX; ix++) {
if (!cellOn[cIdx(ix, iy, iz)]) continue;
const ids = [];
for (let c = 0; c < 8; c++) ids.push(nodeMap[nIdx(ix + (c & 1), iy + ((c >> 1) & 1), iz + ((c >> 2) & 1))]);
for (let a = 0; a < 8; a++) for (let b = a + 1; b < 8; b++) {
const i = ids[a], j = ids[b];
const key = i < j ? i * 4096 + j : j * 4096 + i;
if (seen.has(key)) continue;
seen.add(key);
const dx = R0[i * 3] - R0[j * 3], dy = R0[i * 3 + 1] - R0[j * 3 + 1], dz = R0[i * 3 + 2] - R0[j * 3 + 2];
cAl.push(i); cBl.push(j); cLl.push(Math.sqrt(dx * dx + dy * dy + dz * dz));
}
}
const NC = cAl.length;
const CA = new Uint16Array(cAl), CB = new Uint16Array(cBl), CL = new Float64Array(cLl);
let C0x = 0, C0y = 0, C0z = 0;
for (let i = 0; i < NP; i++) { C0x += R0[i * 3]; C0y += R0[i * 3 + 1]; C0z += R0[i * 3 + 2]; }
C0x /= NP; C0y /= NP; C0z /= NP;
const topNodes = [];
let topMeanY = 0;
for (let i = 0; i < NP; i++) if (R0[i * 3 + 1] > 0.59) { topNodes.push(i); topMeanY += R0[i * 3 + 1]; }
topMeanY /= Math.max(1, topNodes.length);
/* ------------------------------------------------------------------ */
/* Render mesh (half-lathe + bottom cap), embedded in the lattice */
/* ------------------------------------------------------------------ */
const prof = [];
(function () {
const NF = 14, NB = 5, NS = 6, Rf = R - BEV, hR = halfT(Rf);
for (let i = 0; i <= NF; i++) { const r = Rf * Math.pow(i / NF, 0.9); prof.push([r, halfT(r)]); }
for (let i = 1; i <= NB; i++) { const a = (i / NB) * Math.PI / 2; prof.push([Rf + BEV * Math.sin(a), hR - BEV + BEV * Math.cos(a)]); }
for (let i = 1; i <= NS; i++) { prof.push([R, (hR - BEV) * (1 - 2 * i / NS)]); }
for (let i = 1; i <= NB; i++) { const a = (i / NB) * Math.PI / 2; prof.push([Rf + BEV * Math.cos(a), -(hR - BEV) - BEV * Math.sin(a)]); }
for (let i = NF - 1; i >= 0; i--) { const r = Rf * Math.pow(i / NF, 0.9); prof.push([r, -halfT(r)]); }
})();
const M = prof.length, NT = 56, KX = 36, KZ = 6;
const NV_LATHE = (NT + 1) * M, NV = NV_LATHE + (KX + 1) * (KZ + 1);
const RP = new Float32Array(NV * 3);
const idxList = [];
for (let j = 0; j <= NT; j++) {
const th = Math.PI * j / NT, cs = Math.cos(th), sn = Math.max(0, Math.sin(th));
for (let p = 0; p < M; p++) {
const v = (j * M + p) * 3;
RP[v] = prof[p][0] * cs; RP[v + 1] = prof[p][0] * sn; RP[v + 2] = prof[p][1];
}
}
for (let j = 0; j < NT; j++) for (let p = 0; p < M - 1; p++) {
const a = j * M + p, b = (j + 1) * M + p, c = (j + 1) * M + p + 1, d = j * M + p + 1;
idxList.push(a, b, c, a, c, d);
}
const LATHE_IDX_END = idxList.length;
function capHalf(ax) {
const Rf = R - BEV, hR = halfT(Rf);
if (ax <= Rf) return halfT(ax);
const e = Math.min(BEV, ax - Rf);
return hR - BEV + Math.sqrt(Math.max(0, BEV * BEV - e * e));
}
for (let i = 0; i <= KX; i++) {
const x = R * Math.sin(Math.PI / 2 * (-1 + 2 * i / KX));
const hh = capHalf(Math.abs(x));
for (let k = 0; k <= KZ; k++) {
const v = (NV_LATHE + i * (KZ + 1) + k) * 3;
RP[v] = x; RP[v + 1] = 0; RP[v + 2] = hh * (-1 + 2 * k / KZ);
}
}
for (let i = 0; i < KX; i++) for (let k = 0; k < KZ; k++) {
const a = NV_LATHE + i * (KZ + 1) + k, b = a + (KZ + 1), c = b + 1, d = a + 1;
idxList.push(a, b, c, a, c, d);
}
const IDX = new Uint16Array(idxList);
function orient(i0, i1) {
let s = 0;
for (let t = i0; t < i1; t += 3) {
const a = IDX[t] * 3, b = IDX[t + 1] * 3, c = IDX[t + 2] * 3;
const ax = RP[a], ay = RP[a + 1], az = RP[a + 2];
const e1x = RP[b] - ax, e1y = RP[b + 1] - ay, e1z = RP[b + 2] - az;
const e2x = RP[c] - ax, e2y = RP[c + 1] - ay, e2z = RP[c + 2] - az;
const nx = e1y * e2z - e1z * e2y, ny = e1z * e2x - e1x * e2z, nz = e1x * e2y - e1y * e2x;
const cx = (ax + RP[b] + RP[c]) / 3, cy = (ay + RP[b + 1] + RP[c + 1]) / 3 - 0.4, cz = (az + RP[b + 2] + RP[c + 2]) / 3;
s += nx * cx + ny * cy + nz * cz;
}
if (s < 0) for (let t = i0; t < i1; t += 3) { const q = IDX[t + 1]; IDX[t + 1] = IDX[t + 2]; IDX[t + 2] = q; }
}
orient(0, LATHE_IDX_END);
orient(LATHE_IDX_END, IDX.length);
// trilinear embedding of any rest-space point into the lattice
function embed(x, y, z, ids, ws, off) {
const fx = (x - X0) / DX, fy = (y - Y0) / DY, fz = (z - Z0) / DZ;
let ix = Math.min(CX - 1, Math.max(0, Math.floor(fx)));
let iy = Math.min(CY - 1, Math.max(0, Math.floor(fy)));
let iz = Math.min(CZ - 1, Math.max(0, Math.floor(fz)));
if (!cellOn[cIdx(ix, iy, iz)]) {
let best = 1e9, bx = 0, by = 0, bz = 0;
for (let c = 0; c < CZ; c++) for (let b = 0; b < CY; b++) for (let a = 0; a < CX; a++) {
if (!cellOn[cIdx(a, b, c)]) continue;
const d = (a + 0.5 - fx) * (a + 0.5 - fx) + (b + 0.5 - fy) * (b + 0.5 - fy) + (c + 0.5 - fz) * (c + 0.5 - fz);
if (d < best) { best = d; bx = a; by = b; bz = c; }
}
ix = bx; iy = by; iz = bz;
}
const tx = fx - ix, ty = fy - iy, tz = fz - iz;
let ss = 0;
for (let c = 0; c < 8; c++) {
const ax = c & 1, ay = (c >> 1) & 1, az = (c >> 2) & 1;
const w = (ax ? tx : 1 - tx) * (ay ? ty : 1 - ty) * (az ? tz : 1 - tz);
ids[off + c] = nodeMap[nIdx(ix + ax, iy + ay, iz + az)];
ws[off + c] = w; ss += w * w;
}
return ss;
}
const EID = new Uint16Array(NV * 8), EW = new Float32Array(NV * 8), EWS = new Float32Array(NV);
for (let v = 0; v < NV; v++) EWS[v] = embed(RP[v * 3], RP[v * 3 + 1], RP[v * 3 + 2], EID, EW, v * 8);
const pressList = [];
for (let j = 0; j <= NT; j += 2) for (let p = 0; p < M; p++) { const v = j * M + p; if (RP[v * 3 + 1] > 0.2) pressList.push(v); }
const tmpIds = new Uint16Array(8), tmpWs = new Float32Array(8);
function deformPoint(x, y, z, out) {
embed(x, y, z, tmpIds, tmpWs, 0);
let ox = 0, oy = 0, oz = 0;
for (let c = 0; c < 8; c++) { const k = tmpIds[c] * 3, w = tmpWs[c]; ox += w * P[k]; oy += w * P[k + 1]; oz += w * P[k + 2]; }
out[0] = ox; out[1] = oy; out[2] = oz;
}
const posArr = new Float32Array(RP), nrmArr = new Float32Array(NV * 3);
const geo = new THREE.BufferGeometry();
const posAttr = new THREE.BufferAttribute(posArr, 3); posAttr.setUsage(THREE.DynamicDrawUsage);
const nrmAttr = new THREE.BufferAttribute(nrmArr, 3); nrmAttr.setUsage(THREE.DynamicDrawUsage);
geo.setAttribute('position', posAttr);
geo.setAttribute('normal', nrmAttr);
geo.setAttribute('rest', new THREE.BufferAttribute(new Float32Array(RP), 3));
geo.setIndex(new THREE.BufferAttribute(IDX, 1));
geo.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 0.5, 0), 6);
function updateMesh() {
for (let v = 0; v < NV; v++) {
const b = v * 8; let x = 0, y = 0, z = 0;
for (let c = 0; c < 8; c++) { const k = EID[b + c] * 3, w = EW[b + c]; x += w * P[k]; y += w * P[k + 1]; z += w * P[k + 2]; }
posArr[v * 3] = x; posArr[v * 3 + 1] = y; posArr[v * 3 + 2] = z;
}
nrmArr.fill(0);
for (let t = 0; t < IDX.length; t += 3) {
const a = IDX[t] * 3, b = IDX[t + 1] * 3, c = IDX[t + 2] * 3;
const ax = posArr[a], ay = posArr[a + 1], az = posArr[a + 2];
const e1x = posArr[b] - ax, e1y = posArr[b + 1] - ay, e1z = posArr[b + 2] - az;
const e2x = posArr[c] - ax, e2y = posArr[c + 1] - ay, e2z = posArr[c + 2] - az;
const nx = e1y * e2z - e1z * e2y, ny = e1z * e2x - e1x * e2z, nz = e1x * e2y - e1y * e2x;
nrmArr[a] += nx; nrmArr[a + 1] += ny; nrmArr[a + 2] += nz;
nrmArr[b] += nx; nrmArr[b + 1] += ny; nrmArr[b + 2] += nz;
nrmArr[c] += nx; nrmArr[c + 1] += ny; nrmArr[c + 2] += nz;
}
for (let v = 0; v < NV * 3; v += 3) {
const x = nrmArr[v], y = nrmArr[v + 1], z = nrmArr[v + 2];
const l = Math.sqrt(x * x + y * y + z * z);
if (l > 1e-12) { nrmArr[v] = x / l; nrmArr[v + 1] = y / l; nrmArr[v + 2] = z / l; } else { nrmArr[v + 2] = 1; }
}
posAttr.needsUpdate = true; nrmAttr.needsUpdate = true;
}
/* ------------------------------------------------------------------ */
/* Shaders */
/* ------------------------------------------------------------------ */
const GLSL_COMMON = `
#define PI 3.14159265
float hash21(vec2 p){ p = fract(p*vec2(123.34,456.21)); p += dot(p, p+45.32); return fract(p.x*p.y); }
vec3 voro(vec2 x, out vec2 off){
vec2 n = floor(x); vec2 f = fract(x);
float d1 = 8.0; float d2 = 8.0; vec2 bid = vec2(0.0); off = vec2(0.0);
for (int j=-1;j<=1;j++){ for (int i=-1;i<=1;i++){
vec2 g = vec2(float(i), float(j));
vec2 c = n + g;
vec2 o = vec2(hash21(c), hash21(c + vec2(37.7, 11.3)))*0.8 + 0.1;
vec2 rr = g + o - f;
float dd = dot(rr, rr);
if (dd < d1){ d2 = d1; d1 = dd; bid = c; off = rr; } else if (dd < d2){ d2 = dd; }
}}
return vec3(sqrt(d1), sqrt(d2) - sqrt(d1), hash21(bid + vec2(5.1, 9.7)));
}
float halfT(float r){ return 0.17 + 0.07*smoothstep(0.0, 1.0, r); }
void regions(vec2 p, out float flesh, out float peel, out float seg, out float d, out float t){
float r = length(p);
t = clamp(atan(max(p.y, 0.0) + 0.00001, p.x)/PI, 0.0, 1.0);
float w = t + 0.030*sin(6.2832*t) + 0.014*sin(12.5664*t);
float s = clamp(w, 0.0, 0.9999)*5.0;
seg = floor(s);
float fr = s - seg;
float ang = min(fr, 1.0 - fr)*(PI/5.0);
float dSide = r*sin(ang);
float dOut = 0.872 + 0.010*sin(t*37.0 + seg*2.1) - r;
vec2 q = max(vec2(0.085) - vec2(dSide, dOut), vec2(0.0));
d = 0.085 - length(q);
flesh = smoothstep(0.011, 0.024, d)*smoothstep(0.05, 0.09, r);
peel = smoothstep(0.918, 0.940, r);
}
`;
const jellyVS = `
attribute vec3 rest;
varying vec3 vRest; varying vec3 vPos; varying vec3 vNrm;
void main(){
vRest = rest; vPos = position; vNrm = normal;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}`;
const jellyFS = `
uniform vec3 uKey; uniform vec3 uFill; uniform float uSide;
varying vec3 vRest; varying vec3 vPos; varying vec3 vNrm;
` + GLSL_COMMON + `
vec3 studioEnv(vec3 Rd){
float up = smoothstep(-0.25, 0.85, Rd.y);
vec3 c = mix(vec3(0.02,0.06,0.07), vec3(0.50,0.58,0.62), up*up);
float k = max(dot(Rd, uKey), 0.0);
c += vec3(1.0,0.96,0.88)*(pow(k, 90.0)*7.0 + smoothstep(0.93, 0.97, k)*2.2);
float f = max(dot(Rd, uFill), 0.0);
c += vec3(0.85,0.92,1.0)*(pow(f, 40.0)*1.6 + smoothstep(0.95, 0.98, f)*0.9);
float s1 = max(dot(Rd, normalize(vec3(-0.15, 0.05, 1.0))), 0.0);
float s2 = max(dot(Rd, normalize(vec3(0.15, 0.05, -1.0))), 0.0);
float sb = max(s1, s2);
c += vec3(1.0)*(pow(sb, 50.0)*5.0 + smoothstep(0.96, 0.985, sb)*1.5);
c += vec3(1.0)*smoothstep(0.62, 0.80, Rd.y)*smoothstep(0.42, 0.25, abs(Rd.x - 0.15))*0.9;
return c;
}
vec3 encodeOut(vec3 c){
c = max(c, vec3(0.0));
vec3 lo = min(c, vec3(0.7));
vec3 x = max(c - vec3(0.7), vec3(0.0));
vec3 m = lo + 0.3*(vec3(1.0) - exp(-x/0.3));
return pow(m, vec3(0.4545));
}
void main(){
vec3 Vd = normalize(vPos - cameraPosition);
vec3 No = normalize(vNrm);
vec3 dir = Vd*uSide;
vec3 C = vec3(0.0);
float T = 1.0;
float hgt = 0.0;
float dk = dot(No, uKey); float df = dot(No, uFill);
float wrapK = clamp(dk*0.5 + 0.5, 0.0, 1.0); wrapK *= wrapK;
float wrapF = clamp(df*0.5 + 0.5, 0.0, 1.0);
float thruK = clamp(-dk*0.75 + 0.25, 0.0, 1.0);
float thruF = clamp(-df*0.75 + 0.25, 0.0, 1.0);
float fwd = pow(max(dot(Vd, uKey), 0.0), 2.0);
float front = step(0.0, uSide);
for (int k = 0; k < 4; k++){
float fk = float(k);
float s = 0.035*fk + 0.008*fk*fk;
vec3 p = vRest + dir*s;
float r = length(p.xy);
if (k > 0 && (r > 1.0 || abs(p.z) > halfT(r) + 0.003 || p.y < -0.003)) break;
float flesh; float peel; float seg; float d; float t;
regions(p.xy, flesh, peel, seg, d, t);
float white = (1.0 - flesh)*(1.0 - peel);
vec2 off;
vec2 uv = vec2(t*46.0 + seg*5.3, pow(max(r, 0.001), 0.85)*8.5) + fk*vec2(3.1, 1.7) + vec2(0.0, p.z*1.5);
vec3 vc = voro(uv, off);
float wall = smoothstep(0.0, 0.12, vc.y);
float glint = smoothstep(0.17, 0.03, length(off - vec2(0.10, -0.14) - Vd.xy*0.25))*step(0.4, vc.z);
float pore = 0.0;
if (peel > 0.01){
vec2 po;
vec3 pv = voro(vec2(t*75.0, p.z*24.0 + r*34.0), po);
pore = smoothstep(0.32, 0.08, pv.x);
}
vec3 fleshA = mix(vec3(1.0,0.52,0.12), vec3(1.0,0.36,0.015), wall)*(0.78 + 0.44*vc.z);
vec3 peelA = mix(vec3(1.0,0.26,0.0), vec3(0.78,0.16,0.0), pore*0.7);
vec3 whiteA = mix(vec3(1.0,0.86,0.62), vec3(1.0,0.60,0.22), smoothstep(0.87, 0.93, r)*0.55);
vec3 alb = fleshA*flesh + peelA*peel + whiteA*white;
float Tr = exp(-4.0*(2.0*halfT(r) - 0.30));
float trm = (flesh + white*0.5 + peel*0.05)*Tr;
float aDir = mix(1.3, mix(0.55, 1.2, peel), front);
float bThr = mix(0.6, 1.9, front);
vec3 E = vec3(0.26,0.27,0.30)
+ vec3(1.25,1.2,1.1)*(aDir*wrapK + bThr*trm*thruK + 1.4*trm*fwd)
+ vec3(0.44,0.48,0.55)*(aDir*wrapF + 0.5*bThr*trm*thruF);
vec3 col = alb*E*(1.0 - 0.07*fk) + flesh*glint*vec3(1.0,0.82,0.5)*(0.25 + 0.5*thruK);
float a = flesh*0.27 + white*0.62 + peel*0.93;
if (k == 0){
hgt = flesh*(0.012*smoothstep(0.0, 0.085, d) + 0.006*(1.0 - vc.x)) - peel*0.004*pore;
}
C += T*a*col;
T *= 1.0 - a;
}
float aa = 1.0 - T;
vec3 lin = C/max(aa, 0.001);
float aOut = aa;
if (uSide > 0.0){
vec3 dpx = dFdx(vPos)*300.0; vec3 dpy = dFdy(vPos)*300.0;
float hx = dFdx(hgt)*300.0; float hy = dFdy(hgt)*300.0;
vec3 r1 = cross(dpy, No); vec3 r2 = cross(No, dpx);
float det = dot(dpx, r1);
vec3 nb = abs(det)*No - sign(det)*(hx*r1 + hy*r2);
vec3 Nb = (dot(nb, nb) > 1e-16) ? normalize(nb) : No;
vec3 Vv = -Vd;
float nv = clamp(dot(Nb, Vv), 0.0, 1.0);
float fres = 0.06 + 0.94*pow(1.0 - nv, 5.0);
vec3 Rr = reflect(Vd, Nb);
vec3 spec = studioEnv(Rr)*fres;
lin += spec;
aOut = clamp(aa + dot(spec, vec3(0.33))*0.6, 0.0, 1.0);
}
gl_FragColor = vec4(encodeOut(lin), aOut);
}`;
const worldVS = `
varying vec3 vP;
void main(){
vec4 w = modelMatrix * vec4(position, 1.0);
vP = w.xyz;
gl_Position = projectionMatrix * viewMatrix * w;
}`;
const shadowFS = `
uniform vec3 uKey; uniform vec3 uLean;
varying vec3 vP;
` + GLSL_COMMON + `
void main(){
vec3 Pp = vP;
vec3 res = vec3(1.0);
float den = uKey.z - uLean.z*uKey.y/uLean.y;
if (den < -0.05){
float tt = -Pp.z/den;
if (tt > 0.0){
float qy = uKey.y*tt/uLean.y;
float qx = Pp.x + uKey.x*tt - uLean.x*qy;
float r = length(vec2(qx, qy));
float flesh; float peel; float seg; float d; float t;
regions(vec2(qx, qy), flesh, peel, seg, d, t);
float white = (1.0 - flesh)*(1.0 - peel);
float soft = 0.03 + 0.10*qy;
float inside = smoothstep(1.0 + soft*0.5, 1.0 - soft, r)*smoothstep(0.0, 0.03, qy);
vec3 tint = flesh*vec3(1.0,0.70,0.30) + white*vec3(0.80,0.66,0.48) + peel*vec3(0.50,0.27,0.12);
tint = mix(tint, vec3(0.92,0.62,0.30), smoothstep(0.1, 1.0, qy)*0.55);
res = mix(vec3(1.0), tint, inside*0.92);
}
}
float ax = smoothstep(1.15, 0.85, abs(Pp.x));
float az = smoothstep(0.50, 0.10, abs(Pp.z));
res *= 1.0 - 0.30*ax*az;
float edge = smoothstep(1.30, 1.15, length(Pp.xz));
res = mix(vec3(1.0), res, edge);
gl_FragColor = vec4(res, 1.0);
}`;
const tableFS = `
varying vec3 vP;
void main(){
float dist = length(vP.xz);
vec3 c = mix(vec3(0.115,0.40,0.44), vec3(0.0235,0.133,0.165), smoothstep(0.8, 8.5, dist));
float sh = smoothstep(2.6, 1.2, length(vP.xz - vec2(0.22, 0.34)));
c *= 1.0 - 0.5*sh;
gl_FragColor = vec4(c, 1.0);
}`;
const skyFS = `
void main(){ gl_FragColor = vec4(0.0235,0.133,0.165,1.0); }`;
/* ------------------------------------------------------------------ */
/* Scene objects */
/* ------------------------------------------------------------------ */
const sky = new THREE.Mesh(new THREE.SphereGeometry(320, 16, 12),
new THREE.ShaderMaterial({ vertexShader: worldVS, fragmentShader: skyFS, side: THREE.BackSide, depthWrite: false }));
sky.renderOrder = -10; sky.frustumCulled = false; scene.add(sky);
const table = new THREE.Mesh(new THREE.PlaneGeometry(500, 500),
new THREE.ShaderMaterial({ vertexShader: worldVS, fragmentShader: tableFS }));
table.rotation.x = -Math.PI / 2; table.position.y = -0.127; scene.add(table);
const keyLight = new THREE.DirectionalLight(0xfff4e0, 0.58); keyLight.position.copy(KEY).multiplyScalar(10); scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xdfe8ff, 0.28); fillLight.position.copy(FILL).multiplyScalar(10); scene.add(fillLight);
scene.add(new THREE.HemisphereLight(0xffffff, 0x2a5a60, 0.34));
const platePts = [[0, -0.006], [1.22, -0.006], [1.36, 0.012], [1.55, 0.075], [1.70, 0.15], [1.76, 0.168], [1.78, 0.155],
[1.72, 0.10], [1.5, 0.0], [1.25, -0.07], [0.95, -0.085], [0.95, -0.125], [0, -0.125]].map(p => new THREE.Vector2(p[0], p[1]));
const plate = new THREE.Mesh(new THREE.LatheGeometry(platePts, 80),
new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x666666, shininess: 90, side: THREE.DoubleSide }));
scene.add(plate);
const shadowUni = { uKey: { value: KEY }, uLean: { value: new THREE.Vector3(0, 1, 0) } };
const shadowDisc = new THREE.Mesh(new THREE.CircleGeometry(1.3, 64),
new THREE.ShaderMaterial({ uniforms: shadowUni, vertexShader: worldVS, fragmentShader: shadowFS, transparent: true,
depthWrite: false, side: THREE.DoubleSide, blending: THREE.CustomBlending, blendEquation: THREE.AddEquation,
blendSrc: THREE.ZeroFactor, blendDst: THREE.SrcColorFactor }));
shadowDisc.rotation.x = -Math.PI / 2; shadowDisc.position.y = -0.003; shadowDisc.renderOrder = -1; scene.add(shadowDisc);
function jellyMat(side) {
return new THREE.ShaderMaterial({
uniforms: { uKey: { value: KEY }, uFill: { value: FILL }, uSide: { value: side } },
vertexShader: jellyVS, fragmentShader: jellyFS, transparent: true,
side: side > 0 ? THREE.FrontSide : THREE.BackSide, depthWrite: side > 0,
extensions: { derivatives: true }
});
}
const meshBack = new THREE.Mesh(geo, jellyMat(-1)); meshBack.renderOrder = 1; meshBack.frustumCulled = false; scene.add(meshBack);
const meshFront = new THREE.Mesh(geo, jellyMat(1)); meshFront.renderOrder = 2; meshFront.frustumCulled = false; scene.add(meshFront);
// glass presser used by the Squeeze button
const pressG = new THREE.Group();
const glassMat = new THREE.MeshPhongMaterial({ color: 0xcfeeff, specular: 0xffffff, shininess: 140, transparent: true, opacity: 0.38, depthWrite: false });
(function () {
const disc = new THREE.Mesh(new THREE.CylinderGeometry(1.22, 1.22, 0.07, 56), glassMat); disc.position.y = 0.035;
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.08, 0.8, 20), glassMat); stem.position.y = 0.47;
const knob = new THREE.Mesh(new THREE.SphereGeometry(0.16, 20, 14), glassMat); knob.position.y = 0.95;
[disc, stem, knob].forEach(m => { m.renderOrder = 5; pressG.add(m); });
})();
pressG.visible = false; scene.add(pressG);
/* ------------------------------------------------------------------ */
/* Physics */
/* ------------------------------------------------------------------ */
const GRAV = 25, SUB = 12, DT = 1 / 60, H = DT / SUB;
const DAMP = Math.exp(-1.0 * H), RELD = 0.002, ADH = 0.05, PRESS_Y = 0.58, DEF_FIRM = 40;
let stiff = 8000;
function setFirm(v) {
v = Math.max(0, Math.min(100, v));
stiff = 2500 * Math.pow(18, v / 100);
firmEl.value = String(Math.round(v));
}
const grab = { on: false, vert: 0, n: 0, ids: new Uint16Array(NP), w: new Float64Array(NP),
rx: 0, ry: 0, rz: 0, tx: 0, ty: 0, tz: 0, ox: 0, oy: 0, oz: 0, maxD: 0.6 };
const press = { phase: 0, t: 0, y: 1.6, vis: 0, on: false, left: 0, next: 0 };
function floorAt(x, z) {
const rr = Math.sqrt(x * x + z * z);
if (rr < 1.22) return 0;
if (rr < 1.36) return (rr - 1.22) / 0.14 * 0.018;
if (rr < 1.55) return 0.018 + (rr - 1.36) / 0.19 * 0.063;
if (rr < 1.70) return 0.081 + (rr - 1.55) / 0.15 * 0.075;
return 0.17;
}
function setInfluence(vert) {
const gx = RP[vert * 3], gy = RP[vert * 3 + 1], gz = RP[vert * 3 + 2];
let n = 0, mx = 1e-9;
for (let i = 0; i < NP; i++) {
const dx = R0[i * 3] - gx, dy = R0[i * 3 + 1] - gy, dz = R0[i * 3 + 2] - gz;
const w = Math.exp(-(dx * dx + dy * dy + dz * dz) / 0.0676);
if (w > 0.03) { grab.ids[n] = i; grab.w[n] = w; n++; if (w > mx) mx = w; }
}
for (let k = 0; k < n; k++) grab.w[k] /= mx;
grab.n = n; grab.vert = vert; grab.rx = gx; grab.ry = gy; grab.rz = gz;
grab.maxD = 0.35 + 0.5 * gy;
grab.tx = posArr[vert * 3]; grab.ty = posArr[vert * 3 + 1]; grab.tz = posArr[vert * 3 + 2];
grab.ox = 0; grab.oy = 0; grab.oz = 0;
}
function setTarget(x, y, z) {
let dx = x - grab.rx, dy = y - grab.ry, dz = z - grab.rz;
const l = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (l > grab.maxD) { const f = grab.maxD / l; dx *= f; dy *= f; dz *= f; }
grab.tx = grab.rx + dx; grab.ty = Math.max(0.05, grab.ry + dy); grab.tz = grab.rz + dz;
}
function poke(dx, dy, dz, strength) {
for (let k = 0; k < grab.n; k++) {
const i = grab.ids[k] * 3, w = grab.w[k] * strength;
V[i] += dx * w; V[i + 1] += dy * w; V[i + 2] += dz * w;
}
}
function applyGrab() {
const b = grab.vert * 8; let px = 0, py = 0, pz = 0;
for (let c = 0; c < 8; c++) { const k = EID[b + c] * 3, w = EW[b + c]; px += w * P[k]; py += w * P[k + 1]; pz += w * P[k + 2]; }
const dx = (grab.tx - px) * 0.3, dy = (grab.ty - py) * 0.3, dz = (grab.tz - pz) * 0.3;
for (let k = 0; k < grab.n; k++) {
const i = grab.ids[k] * 3, w = grab.w[k];
P[i] += dx * w; P[i + 1] += dy * w; P[i + 2] += dz * w;
}
}
function applyPress() {
const py = press.y;
for (let s = 0; s < pressList.length; s++) {
const v = pressList[s], b = v * 8;
let y = 0;
for (let c = 0; c < 8; c++) y += EW[b + c] * P[EID[b + c] * 3 + 1];
if (y > py) {
const inv = 1 / EWS[v];
let mx = 0, mz = 0;
for (let c = 0; c < 8; c++) { const k = EID[b + c] * 3, w = EW[b + c]; mx += w * (P[k] - Q[k]); mz += w * (P[k + 2] - Q[k + 2]); }
const cy = (py - y) * inv, fx = -mx * 0.8 * inv, fz = -mz * 0.8 * inv;
for (let c = 0; c < 8; c++) { const k = EID[b + c] * 3, w = EW[b + c]; P[k] += fx * w; P[k + 1] += cy * w; P[k + 2] += fz * w; }
}
}
}
let sqx = 0, sqy = 0, sqz = 0, sqw = 1;
function shapeMatch(s) {
let cx = 0, cy = 0, cz = 0;
for (let i = 0; i < NP; i++) { const k = i * 3; cx += P[k]; cy += P[k + 1]; cz += P[k + 2]; }
cx /= NP; cy /= NP; cz /= NP;
let a00 = 0, a01 = 0, a02 = 0, a10 = 0, a11 = 0, a12 = 0, a20 = 0, a21 = 0, a22 = 0;
for (let i = 0; i < NP; i++) {
const k = i * 3;
const px = P[k] - cx, py = P[k + 1] - cy, pz = P[k + 2] - cz;
const rx = R0[k] - C0x, ry = R0[k + 1] - C0y, rz = R0[k + 2] - C0z;
a00 += px * rx; a01 += px * ry; a02 += px * rz;
a10 += py * rx; a11 += py * ry; a12 += py * rz;
a20 += pz * rx; a21 += pz * ry; a22 += pz * rz;
}
if (!(sqw === sqw)) { sqx = 0; sqy = 0; sqz = 0; sqw = 1; }
let r00 = 1, r01 = 0, r02 = 0, r10 = 0, r11 = 1, r12 = 0, r20 = 0, r21 = 0, r22 = 1;
for (let it = 0; it < 3; it++) {
const x = sqx, y = sqy, z = sqz, w = sqw;
r00 = 1 - 2 * (y * y + z * z); r01 = 2 * (x * y - z * w); r02 = 2 * (x * z + y * w);
r10 = 2 * (x * y + z * w); r11 = 1 - 2 * (x * x + z * z); r12 = 2 * (y * z - x * w);
r20 = 2 * (x * z - y * w); r21 = 2 * (y * z + x * w); r22 = 1 - 2 * (x * x + y * y);
if (it === 2) break;
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 wl = Math.sqrt(ox * ox + oy * oy + oz * oz);
if (wl < 1e-9) continue;
const hf = wl * 0.5, sn = Math.sin(hf) / wl, ax = ox * sn, ay = oy * sn, az = oz * sn, aw = Math.cos(hf);
let nx = aw * x + ax * w + ay * z - az * y;
let ny = aw * y - ax * z + ay * w + az * x;
let nz = aw * z + ax * y - ay * x + az * w;
let nw = aw * w - ax * x - ay * y - az * z;
const nl = Math.sqrt(nx * nx + ny * ny + nz * nz + nw * nw) || 1;
sqx = nx / nl; sqy = ny / nl; sqz = nz / nl; sqw = nw / nl;
}
for (let i = 0; i < NP; i++) {
const k = i * 3;
const rx = R0[k] - C0x, ry = R0[k + 1] - C0y, rz = R0[k + 2] - C0z;
P[k] += (cx + r00 * rx + r01 * ry + r02 * rz - P[k]) * s;
P[k + 1] += (cy + r10 * rx + r11 * ry + r12 * rz - P[k + 1]) * s;
P[k + 2] += (cz + r20 * rx + r21 * ry + r22 * rz - P[k + 2]) * s;
}
}
function substep() {
const h = H, at = 1 / (stiff * h * h), soft = 1 / (2 + at);
for (let i = 0; i < NP; i++) {
const k = i * 3;
V[k + 1] -= GRAV * h;
Q[k] = P[k]; Q[k + 1] = P[k + 1]; Q[k + 2] = P[k + 2];
P[k] += V[k] * h; P[k + 1] += V[k + 1] * h; P[k + 2] += V[k + 2] * h;
}
if (grab.on) applyGrab();
for (let c = 0; c < NC; c++) {
const i = CA[c] * 3, j = CB[c] * 3;
const dx = P[i] - P[j], dy = P[i + 1] - P[j + 1], dz = P[i + 2] - P[j + 2];
const len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len < 1e-9) continue;
const L = CL[c];
let s;
if (len > L * 2.2) s = -(len - L * 2.2) * 0.5 / len;
else if (len < L * 0.35) s = -(len - L * 0.35) * 0.5 / len;
else s = -(len - L) * soft / len;
P[i] += dx * s; P[i + 1] += dy * s; P[i + 2] += dz * s;
P[j] -= dx * s; P[j + 1] -= dy * s; P[j + 2] -= dz * s;
}
shapeMatch(Math.min(0.2, stiff * 0.03 * h * h));
for (let i = 0; i < NP; i++) {
const k = i * 3;
if (isBase[i]) {
P[k] += (R0[k] - P[k]) * ADH; P[k + 2] += (R0[k + 2] - P[k + 2]) * ADH;
if (P[k + 1] > 0) P[k + 1] -= P[k + 1] * ADH;
}
const x = P[k], z = P[k + 2];
const fy = (x * x + z * z < 1.4884) ? 0 : floorAt(x, z);
if (P[k + 1] < fy) {
P[k + 1] = fy;
if (!isBase[i]) { P[k] = Q[k] + (x - Q[k]) * 0.5; P[k + 2] = Q[k + 2] + (z - Q[k + 2]) * 0.5; }
}
}
if (press.on) applyPress();
const inv = 1 / h;
for (let i = 0; i < NP; i++) {
const k = i * 3;
let vx = (P[k] - Q[k]) * inv * DAMP, vy = (P[k + 1] - Q[k + 1]) * inv * DAMP, vz = (P[k + 2] - Q[k + 2]) * inv * DAMP;
const s2 = vx * vx + vy * vy + vz * vz;
if (s2 > 900) { const f = 30 / Math.sqrt(s2); vx *= f; vy *= f; vz *= f; }
V[k] = vx; V[k + 1] = vy; V[k + 2] = vz;
}
for (let c = 0; c < NC; c++) {
const i = CA[c] * 3, j = CB[c] * 3;
const ax = (V[i] - V[j]) * RELD, ay = (V[i + 1] - V[j + 1]) * RELD, az = (V[i + 2] - V[j + 2]) * RELD;
V[i] -= ax; V[i + 1] -= ay; V[i + 2] -= az;
V[j] += ax; V[j + 1] += ay; V[j + 2] += az;
}
}
function resetJelly(kick) {
P.set(R0); Q.set(R0); V.fill(0);
sqx = 0; sqy = 0; sqz = 0; sqw = 1;
grab.on = false;
if (kick) for (let i = 0; i < NP; i++) { V[i * 3 + 2] = 1.4 * R0[i * 3 + 1]; V[i * 3] = 0.5 * R0[i * 3 + 1]; }
}
/* ------------------------------------------------------------------ */
/* Juice drops */
/* ------------------------------------------------------------------ */
const dropGeo = new THREE.SphereGeometry(1, 14, 10);
const dropMat = new THREE.MeshPhongMaterial({ color: 0xffa41f, emissive: 0x8a3600, specular: 0xffffff, shininess: 160, transparent: true, opacity: 0.9 });
const drops = [];
const tmp3 = [0, 0, 0];
function spawnDrop() {
const facing = camera.position.z >= 0 ? 1 : -1;
const side = Math.random() < 0.78 ? facing : -facing;
const ang = (0.18 + 0.64 * Math.random()) * Math.PI, r = 0.38 + 0.36 * Math.random();
const m = new THREE.Mesh(dropGeo, dropMat);
m.renderOrder = 4; m.frustumCulled = false; m.scale.set(0.0001, 0.0001, 0.0001);
scene.add(m);
drops.push({ m: m, st: 0, rx: r * Math.cos(ang), ry: r * Math.sin(ang), side: side, sp: 0.02,
size: 0.034 + 0.02 * Math.random(), grow: 0, px: 0, pz: 0 });
if (drops.length > 18) { const d = drops.shift(); scene.remove(d.m); }
}
function clearDrops() { while (drops.length) scene.remove(drops.pop().m); }
function updateDrops(dt) {
for (let i = 0; i < drops.length; i++) {
const d = drops[i];
if (d.st === 0) {
d.grow = Math.min(1, d.grow + dt * 2.2);
if (d.grow > 0.6) { d.sp = Math.min(0.75, d.sp + dt * 0.5); d.ry -= d.sp * dt; }
const ry = Math.max(d.ry, 0), r = Math.min(1, Math.sqrt(d.rx * d.rx + ry * ry));
deformPoint(d.rx, ry, d.side * (halfT(r) + 0.012), tmp3);
const s = d.size * d.grow, st = 1 + Math.min(1.2, d.sp * 2.2);
d.m.position.set(tmp3[0], Math.max(0.01, tmp3[1]), tmp3[2]);
d.m.scale.set(Math.max(1e-4, s * 0.9), Math.max(1e-4, s * st), Math.max(1e-4, s * 0.6));
if (d.ry <= 0.03) { d.st = 1; d.px = tmp3[0]; d.pz = tmp3[2] + d.side * 0.03; d.grow = 0; }
} else {
d.grow = Math.min(1, d.grow + dt * 1.6);
const e = d.grow * (2 - d.grow), s = d.size;
d.m.position.set(d.px, 0.002 + s * 0.14, d.pz + d.side * 0.035 * e);
d.m.scale.set(s * (0.9 + 1.1 * e), s * (0.9 - 0.62 * e), s * (0.9 + 1.1 * e));
}
}
}
/* ------------------------------------------------------------------ */
/* Squeeze */
/* ------------------------------------------------------------------ */
function startSqueeze() {
if (press.phase !== 0) return;
press.phase = 1; press.t = 0; press.y = 1.45; press.vis = 0; press.on = true;
press.left = 5 + Math.floor(Math.random() * 3);
sqBtn.disabled = true;
}
function stopSqueeze() { press.phase = 0; press.on = false; press.vis = 0; sqBtn.disabled = false; }
function updatePress(dt) {
if (press.phase === 0) return;
press.t += dt;
if (press.phase === 1) {
const u = Math.min(1, press.t / 1.4), e = u * u * (3 - 2 * u);
press.y = 1.45 + (PRESS_Y - 1.45) * e;
press.vis = Math.min(1, press.t / 0.3);
if (u >= 1) { press.phase = 2; press.t = 0; press.next = 0.05; }
} else if (press.phase === 2) {
press.y = PRESS_Y + 0.012 * Math.sin(press.t * 7);
if (press.left > 0 && press.t >= press.next) { spawnDrop(); press.left--; press.next = press.t + 0.16 + Math.random() * 0.2; }
if (press.t > 1.7) { press.phase = 3; press.t = 0; }
} else {
const u = Math.min(1, press.t / 0.35), e = u * u * (3 - 2 * u);
press.y = PRESS_Y + (1.8 - PRESS_Y) * e;
press.vis = 1 - u;
if (u >= 1) stopSqueeze();
}
}
/* ------------------------------------------------------------------ */
/* Camera, input */
/* ------------------------------------------------------------------ */
const AZ0 = 0.38, EL0 = 0.36;
const cam = { az: AZ0, el: EL0, dist: 5, zoom: 1 };
const TGT = new THREE.Vector3(0, 0.42, 0);
function updateCamera() {
const d = cam.dist * cam.zoom, ce = Math.cos(cam.el);
camera.position.set(TGT.x + d * Math.sin(cam.az) * ce, TGT.y + d * Math.sin(cam.el), TGT.z + d * Math.cos(cam.az) * ce);
camera.lookAt(TGT);
camera.updateMatrixWorld();
}
function resize() {
const w = Math.max(1, window.innerWidth), h = Math.max(1, window.innerHeight);
renderer.setSize(w, h, false);
const uiH = uiEl.getBoundingClientRect().height || 0;
camera.aspect = w / h;
camera.setViewOffset(w, h, 0, Math.round(uiH * 0.42), w, h);
cam.dist = Math.max(5.0, 1.9 / (Math.tan(35 * Math.PI / 360) * (w / h)));
}
window.addEventListener('resize', resize);
resize(); updateCamera();
const ray = new THREE.Raycaster(), ndc = new THREE.Vector2(), plane = new THREE.Plane();
const tv1 = new THREE.Vector3(), tv2 = new THREE.Vector3();
const ptr = { id: null, mode: null, x: 0, y: 0, sx: 0, sy: 0 };
function setRay(cx, cy) {
const r = canvas.getBoundingClientRect();
ndc.set(((cx - r.left) / Math.max(1, r.width)) * 2 - 1, -((cy - r.top) / Math.max(1, r.height)) * 2 + 1);
ray.setFromCamera(ndc, camera);
}
function hideHint() { hintEl.classList.add('off'); }
canvas.addEventListener('pointerdown', function (e) {
if (ptr.id !== null) return;
ptr.id = e.pointerId;
try { canvas.setPointerCapture(e.pointerId); } catch (_) {}
ptr.x = ptr.sx = e.clientX; ptr.y = ptr.sy = e.clientY;
setRay(e.clientX, e.clientY);
const hits = ray.intersectObject(meshFront, false);
if (hits.length && hits[0].face) {
const hpt = hits[0].point, f = hits[0].face;
let best = f.a, bd = 1e9;
const cand = [f.a, f.b, f.c];
for (let i = 0; i < 3; i++) {
const v = cand[i];
const dx = posArr[v * 3] - hpt.x, dy = posArr[v * 3 + 1] - hpt.y, dz = posArr[v * 3 + 2] - hpt.z;
const d = dx * dx + dy * dy + dz * dz;
if (d < bd) { bd = d; best = v; }
}
grab.on = false;
setInfluence(best);
grab.ox = posArr[best * 3] - hpt.x; grab.oy = posArr[best * 3 + 1] - hpt.y; grab.oz = posArr[best * 3 + 2] - hpt.z;
camera.getWorldDirection(tv1);
plane.setFromNormalAndCoplanarPoint(tv1, hpt);
const rd = ray.ray.direction;
poke(rd.x, rd.y, rd.z, 4.2);
ptr.mode = 'jelly';
} else {
ptr.mode = 'orbit';
}
hideHint();
e.preventDefault();
});
canvas.addEventListener('pointermove', function (e) {
if (e.pointerId !== ptr.id) return;
const dx = e.clientX - ptr.x, dy = e.clientY - ptr.y;
ptr.x = e.clientX; ptr.y = e.clientY;
if (ptr.mode === 'jelly') {
if (!grab.on && Math.hypot(e.clientX - ptr.sx, e.clientY - ptr.sy) > 5) grab.on = true;
if (grab.on) {
setRay(e.clientX, e.clientY);
if (ray.ray.intersectPlane(plane, tv2)) setTarget(tv2.x + grab.ox, tv2.y + grab.oy, tv2.z + grab.oz);
}
} else if (ptr.mode === 'orbit') {
cam.az -= dx * 0.007;
cam.el = Math.max(0.1, Math.min(1.25, cam.el + dy * 0.006));
}
e.preventDefault();
});
function endPointer(e) {
if (e.pointerId !== ptr.id) return;
if (ptr.mode === 'jelly') grab.on = false;
ptr.id = null; ptr.mode = null;
}
canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', endPointer);
canvas.addEventListener('lostpointercapture', endPointer);
canvas.addEventListener('contextmenu', function (e) { e.preventDefault(); });
canvas.addEventListener('wheel', function (e) {
cam.zoom = Math.max(0.6, Math.min(1.6, cam.zoom * Math.exp(e.deltaY * 0.001)));
e.preventDefault();
}, { passive: false });
function resetAll() {
resetJelly(true);
clearDrops();
stopSqueeze();
pressG.visible = false;
cam.az = AZ0; cam.el = EL0; cam.zoom = 1;
setFirm(DEF_FIRM);
}
sqBtn.addEventListener('click', function () { hideHint(); startSqueeze(); });
resetBtn.addEventListener('click', function () { resetAll(); });
firmEl.addEventListener('input', function () { setFirm(parseFloat(firmEl.value) || 0); });
/* ------------------------------------------------------------------ */
/* Hands-free demo (#demo) */
/* ------------------------------------------------------------------ */
const demo = { on: false, t: 0, f: {}, grab: false, gx: 0, gy: 0, gz: 0, hideAt: -1, upAt: -1 };
function isDemoUrl() { return /#demo$/i.test(String(window.location.href)); }
function cap(text) { capEl.textContent = text; capEl.style.display = 'block'; }
function nearestVert(x, y, z) {
let best = 0, bd = 1e9;
for (let v = 0; v < NV_LATHE; v++) {
const dx = RP[v * 3] - x, dy = RP[v * 3 + 1] - y, dz = RP[v * 3 + 2] - z;
const d = dx * dx + dy * dy + dz * dz;
if (d < bd) { bd = d; best = v; }
}
return best;
}
function cursorAt(x, y, z, down) {
tv1.set(x, y, z).project(camera);
const sx = (tv1.x * 0.5 + 0.5) * window.innerWidth, sy = (-tv1.y * 0.5 + 0.5) * window.innerHeight;
cursorEl.style.display = 'block';
cursorEl.style.left = sx + 'px'; cursorEl.style.top = sy + 'px';
if (down) cursorEl.classList.add('down'); else cursorEl.classList.remove('down');
}
function demoPoke(rx, ry) {
const r = Math.min(1, Math.sqrt(rx * rx + ry * ry));
const v = nearestVert(rx, ry, halfT(r));
setInfluence(v);
const px = posArr[v * 3], py = posArr[v * 3 + 1], pz = posArr[v * 3 + 2];
let dx = px - camera.position.x, dy = py - camera.position.y, dz = pz - camera.position.z;
const l = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;
poke(dx / l, dy / l, dz / l, 4.6);
cursorAt(px, py, pz, true);
demo.upAt = demo.t + 0.22; demo.hideAt = demo.t + 0.8;
}
function demoGrab(rx, ry) {
const r = Math.min(1, Math.sqrt(rx * rx + ry * ry));
const v = nearestVert(rx, ry, halfT(r));
setInfluence(v);
demo.gx = posArr[v * 3]; demo.gy = posArr[v * 3 + 1]; demo.gz = posArr[v * 3 + 2];
grab.on = true; demo.grab = true; demo.hideAt = -1; demo.upAt = -1;
}
function lerp(a, b, u) { u = Math.max(0, Math.min(1, u)); return a + (b - a) * u; }
function startDemo() {
resetAll();
demo.on = true; demo.t = 0; demo.f = {}; demo.grab = false;
hideHint();
}
function endDemo() {
if (!demo.on) return;
demo.on = false;
if (demo.grab) { grab.on = false; demo.grab = false; }
cursorEl.style.display = 'none';
capEl.style.display = 'none';
setFirm(DEF_FIRM);
}
function demoStep(dt) {
demo.t += dt;
if (demo.t >= 20.5) { demo.t = 0; demo.f = {}; }
const t = demo.t;
cam.az = AZ0 + 0.32 * Math.sin(t / 20.5 * Math.PI * 2);
cam.el = EL0 + 0.05 * Math.sin(t / 20.5 * Math.PI * 4);
const once = function (k, at, fn) { if (t >= at && !demo.f[k]) { demo.f[k] = 1; fn(); } };
once('c0', 0.0, function () { cap('Poke it'); });
once('p1', 0.8, function () { demoPoke(-0.38, 0.5); });
once('p2', 2.0, function () { demoPoke(0.42, 0.55); });
once('c1', 3.2, function () { cap('Drag to stretch, then let go'); });
once('g1', 3.6, function () { demoGrab(0.05, 0.9); });
if (demo.grab) {
const u = Math.min(1, (t - 3.6) / 1.5), e = u * u * (3 - 2 * u);
const wob = t > 5.1 ? 0.04 * Math.sin((t - 5.1) * 9) : 0;
setTarget(demo.gx + 0.55 * e + wob, demo.gy + 0.42 * e, demo.gz + 0.15 * e);
const v = grab.vert;
cursorAt(posArr[v * 3], posArr[v * 3 + 1], posArr[v * 3 + 2], true);
}
once('g2', 5.8, function () { grab.on = false; demo.grab = false; cursorEl.classList.remove('down'); demo.hideAt = demo.t + 0.5; });
once('c2', 7.4, function () { cap('Squeeze'); });
once('s1', 7.7, function () { startSqueeze(); });
once('c3', 12.0, function () { cap('Firmness: soft'); });
if (t >= 12.0 && t < 13.0) setFirm(lerp(DEF_FIRM, 6, (t - 12.0) / 1.0));
once('p3', 13.3, function () { demoPoke(0.1, 0.7); });
once('c4', 15.0, function () { cap('Firmness: firm'); });
if (t >= 15.0 && t < 15.8) setFirm(lerp(6, 95, (t - 15.0) / 0.8));
once('p4', 16.1, function () { demoPoke(-0.3, 0.6); });
once('p5', 17.0, function () { demoPoke(0.35, 0.45); });
if (t >= 17.8 && t < 18.4) setFirm(lerp(95, DEF_FIRM, (t - 17.8) / 0.6));
once('c5', 18.6, function () { cap('Reset'); });
once('r1', 19.0, function () { resetAll(); });
if (demo.upAt >= 0 && t >= demo.upAt) { cursorEl.classList.remove('down'); demo.upAt = -1; }
if (demo.hideAt >= 0 && t >= demo.hideAt && !demo.grab) { cursorEl.style.display = 'none'; demo.hideAt = -1; }
}
['pointerdown', 'touchstart', 'mousedown', 'keydown', 'wheel'].forEach(function (ev) {
window.addEventListener(ev, endDemo, { capture: true, passive: true });
});
window.addEventListener('hashchange', function () { if (isDemoUrl() && !demo.on) startDemo(); });
/* ------------------------------------------------------------------ */
/* Main loop */
/* ------------------------------------------------------------------ */
setFirm(DEF_FIRM);
resetJelly(true);
updateMesh();
if (isDemoUrl()) 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) demoStep(dt);
acc += dt;
let n = 0;
while (acc >= DT && n < 3) {
updatePress(DT);
for (let s = 0; s < SUB; s++) substep();
acc -= DT; n++;
}
if (acc > DT) acc = 0;
let chk = 0;
for (let i = 0; i < NP * 3; i++) chk += P[i];
if (!isFinite(chk)) resetJelly(false);
updateMesh();
updateDrops(dt);
updateCamera();
// lean / squash estimate for the projected glow-shadow on the plate
let lx = 0, ly = 0, lz = 0;
for (let i = 0; i < topNodes.length; i++) {
const k = topNodes[i] * 3;
lx += P[k] - R0[k]; ly += P[k + 1] - R0[k + 1]; lz += P[k + 2] - R0[k + 2];
}
const tn = Math.max(1, topNodes.length);
shadowUni.uLean.value.set(lx / tn / topMeanY, Math.max(0.3, 1 + ly / tn / topMeanY), lz / tn / topMeanY);
if (press.phase !== 0 && press.vis > 0.01) {
pressG.visible = true; pressG.position.y = press.y; glassMat.opacity = 0.38 * press.vis;
} else {
pressG.visible = false;
}
renderer.render(scene, camera);
}
requestAnimationFrame(frame);
})();
</script>
</body>
</html>
