Back to the app
The code
Jelly Orange Slice by GPT-6.1 Sol
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,viewport-fit=cover">
<meta name="theme-color" content="#f6f2e9">
<title>Softslice — a little squeeze of sunshine</title>
<style>
:root{--paper:#f6f2e9;--ink:#392c22;--muted:#948577;--orange:#ee682b;--line:#ded6c8;--white:#fffdf8}
*{box-sizing:border-box}
html,body{margin:0;min-height:100%;background:var(--paper);color:var(--ink);font-family:Arial,Helvetica,sans-serif}
button,input{-webkit-tap-highlight-color:transparent;font:inherit}
button{cursor:pointer}
button:focus-visible,input:focus-visible{outline:3px solid #a54c24;outline-offset:5px}
button:disabled{cursor:wait;opacity:.55}
.playground{height:100svh;min-height:760px;position:relative;isolation:isolate;overflow:hidden}
.header{position:absolute;left:5.6%;right:5.6%;top:33px;z-index:5;display:flex;align-items:center;justify-content:space-between}
.brand{display:flex;align-items:center;gap:11px;text-decoration:none;color:var(--ink)}
.brand svg{width:35px;height:35px;flex:none}
.brand-name{font-size:27px;font-weight:700;letter-spacing:-1.3px}
.brand-name span{color:var(--orange)}
.brand-divider{width:1px;height:26px;background:var(--line);margin:0 9px}
.brand-caption{font-size:10px;line-height:1.6;letter-spacing:1.3px;text-transform:uppercase;color:#8b7d6e}
.header-tools{display:flex;align-items:center;gap:12px}
.demo-button,.help-button{border:1px solid var(--line);background:rgba(255,253,248,.55);color:var(--ink);display:flex;align-items:center;justify-content:center}
.demo-button{min-height:44px;padding:0 18px;gap:9px;border-radius:24px;font-size:12px}
.demo-button svg{width:13px;height:13px;color:var(--orange)}
.help-button{width:44px;height:44px;border-radius:50%;font-size:17px;font-family:Georgia,serif}
.demo-button:hover,.help-button:hover{background:var(--white);border-color:#bdad97}
.hero{position:absolute;z-index:2;left:5.9%;top:24.5%;width:350px;pointer-events:none}
.eyebrow{display:flex;gap:10px;align-items:center;font-size:10px;font-weight:700;letter-spacing:2.4px;color:#a66a43;margin:0 0 23px}
.eyebrow:before{content:"";display:block;width:22px;height:1px;background:#b07c51}
h1{font-family:Georgia,'Times New Roman',serif;font-size:clamp(63px,5.7vw,91px);font-weight:400;line-height:1.025;letter-spacing:-4.8px;margin:0}
h1 em{color:var(--orange);font-weight:400}
.intro{font-size:13px;color:#8c7c6c;line-height:1.85;letter-spacing:.05px;margin:24px 0 28px}
.gesture-hints{display:flex;gap:19px;align-items:center;font-size:10px;color:#766656}
.gesture-hints span{display:flex;align-items:center;gap:6px}
.gesture-hints svg{width:16px;height:16px;color:#a67a55;stroke-width:1.3}
#stage{position:absolute;left:27%;right:-1.5%;top:99px;bottom:126px;z-index:1;touch-action:none;user-select:none;-webkit-user-select:none}
#stage canvas{display:block;width:100%;height:100%;touch-action:none;cursor:grab;outline:none}
#stage canvas:active{cursor:grabbing}
.stage-top{position:absolute;right:10%;top:34px;text-align:right;pointer-events:none}
.specimen{font-size:10px;letter-spacing:2px;color:#a38f76;display:flex;align-items:center;justify-content:flex-end;gap:9px}
.specimen:before{content:"";width:6px;height:6px;border-radius:50%;background:var(--orange)}
.handwritten{font-family:Georgia,'Times New Roman',serif;font-style:italic;font-size:20px;color:#b69470;transform:rotate(6deg);margin:14px 6px 0 0;line-height:1.25}
.handwritten svg{display:block;width:45px;height:36px;margin:2px 0 0 36px;transform:rotate(-6deg)}
.live-status{position:absolute;bottom:13px;left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:10px;white-space:nowrap;pointer-events:none}
.meter{display:flex;gap:3px;align-items:center;height:16px}
.meter i{display:block;width:2px;height:12px;background:#b2a183;border-radius:2px;transform:scaleY(.25);transition:background .2s}
.meter i:nth-child(2){height:16px}.meter i:nth-child(3){height:10px}
#status-text{font-size:9px;letter-spacing:1.9px;color:#95816b;min-width:155px}
.controls{position:absolute;z-index:4;left:42%;right:6%;bottom:87px;display:flex;align-items:center;gap:25px;padding:16px 18px;background:rgba(255,253,248,.86);border:1px solid #e7dfd2;border-radius:22px;box-shadow:0 8px 35px #64401b06;backdrop-filter:blur(12px)}
.squeeze{min-width:157px;height:61px;display:flex;align-items:center;justify-content:center;gap:11px;padding:0 22px;border:0;border-radius:13px;background:var(--orange);color:white;font-size:13px;font-weight:600;box-shadow:0 4px 0 #c64f1920;transition:background .15s,transform .15s}
.squeeze:hover{background:#dd5a20}.squeeze:active{transform:scale(.96)}
.squeeze.active{background:#d85c25}
.squeeze svg{width:22px;height:22px;flex:none}
.firmness{flex:1;min-width:120px}
.range-heading{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:11px;font-size:11px}
#firmness-name{font-size:10px;color:#b58b64}
input[type=range]{appearance:none;-webkit-appearance:none;display:block;width:100%;height:4px;border-radius:4px;outline:none;background:linear-gradient(to right,var(--orange) 42%,#e6dfd3 42%);cursor:pointer}
input[type=range]::-webkit-slider-thumb{appearance:none;-webkit-appearance:none;width:20px;height:20px;border:5px solid var(--white);border-radius:50%;background:var(--orange);box-shadow:0 0 0 1px #d9cdbd,0 2px 4px #5c301b19}
input[type=range]::-moz-range-thumb{width:10px;height:10px;border:5px solid var(--white);border-radius:50%;background:var(--orange);box-shadow:0 0 0 1px #d9cdbd}
.range-ends{display:flex;justify-content:space-between;font-size:8px;color:#ad9e8b;margin-top:10px;letter-spacing:.5px}
.reset{height:55px;min-width:62px;border:0;border-left:1px solid #e7dfd1;background:transparent;color:#9c8b75;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px;padding-left:18px;font-size:9px;transition:color .15s}
.reset svg{width:19px;height:19px;transition:transform .35s}.reset:hover{color:var(--orange)}.reset:active svg{transform:rotate(-70deg)}
.footer{position:absolute;left:5.9%;right:6%;bottom:27px;display:flex;align-items:center;justify-content:space-between;gap:20px;z-index:3}
.footer-left{font-size:9px;letter-spacing:1.5px;color:#a08e77;display:flex;align-items:center;gap:13px}
.footer-left b{font-size:10px;color:#7c6a55;font-weight:400;letter-spacing:1px}
.footer-left .line{width:30px;height:1px;background:#cebea8}
#note{font-family:Georgia,serif;font-size:12px;font-style:italic;color:#a38a6e;transition:opacity .3s}
.physics-badge{font-size:8px;letter-spacing:1.4px;color:#988976;display:flex;align-items:center;gap:7px;white-space:nowrap}
.physics-badge:before{content:"";width:5px;height:5px;border-radius:50%;background:#92a27c;box-shadow:0 0 0 3px #92a27c0e}
.demo-badge{position:absolute;left:50%;top:105px;transform:translateX(-50%);z-index:5;display:flex;align-items:center;gap:8px;border:1px solid #e6d6bd;border-radius:30px;padding:10px 16px;background:#fffcf3eb;color:#a26e3f;font-size:9px;letter-spacing:1px;white-space:nowrap}
.demo-badge:before{content:"";width:5px;height:5px;border-radius:50%;background:var(--orange)}
[hidden]{display:none!important}
.help-panel{position:absolute;right:5.6%;top:91px;z-index:10;width:290px;border:1px solid var(--line);border-radius:18px;padding:26px;background:#fffdf9;box-shadow:0 12px 50px #57391912}
.help-panel h2{font:400 23px Georgia,serif;letter-spacing:-.6px;margin:0 0 15px}
.help-panel p{font-size:12px;line-height:1.8;color:#8e7c68;margin:9px 0}
.help-panel strong{font-weight:600;color:#674c34}
.help-panel small{display:block;border-top:1px solid #ece3d5;margin-top:17px;padding-top:15px;font-size:10px;color:#b1845a;line-height:1.6}
#loading{position:absolute;inset:20% 10%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:17px;z-index:2;pointer-events:none;color:#ac885f;font:italic 16px Georgia,serif;text-align:center}
.loader{width:31px;height:31px;border:1px solid #e4c9a4;border-top:2px solid var(--orange);border-radius:50%;animation:spin 1s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
@media(min-width:1650px){.hero{top:26%}.controls{left:46%;right:9%;bottom:105px}#stage{left:28%;right:1%;bottom:145px}.footer{bottom:35px}}
@media(max-width:1100px) and (min-width:721px){.brand-caption,.brand-divider{display:none}.hero{left:5%;width:285px;top:25%}h1{font-size:69px;letter-spacing:-3.7px}.intro{font-size:12px}.gesture-hints{gap:12px;font-size:9px}#stage{left:25%;right:-8%;top:115px;bottom:170px}.controls{left:34%;right:4%;gap:16px;bottom:94px}.squeeze{min-width:133px;padding:0 16px}.stage-top{right:15%;top:20px}.handwritten{font-size:17px}.footer-left{font-size:8px;gap:8px}#note{font-size:11px}.physics-badge{font-size:7px}}
@media(max-width:720px){
.playground{min-height:860px;height:100svh;max-height:1100px}
.header{top:22px;left:6%;right:6%}.brand{gap:8px}.brand svg{width:28px;height:28px}.brand-name{font-size:24px}.brand-caption,.brand-divider{display:none}
.header-tools{gap:8px}.demo-button{min-height:40px;padding:0 13px;font-size:10px;gap:7px}.help-button{height:40px;width:40px;font-size:16px}
.hero{left:7%;top:117px;right:7%;width:auto}.eyebrow{font-size:8px;letter-spacing:2px;margin-bottom:16px;gap:8px}.eyebrow:before{width:18px}
h1{font-size:53px;line-height:1.03;letter-spacing:-2.9px}h1 br:nth-of-type(2){display:none}h1 em{padding-left:10px}.intro{font-size:11px;line-height:1.7;margin-top:17px;max-width:220px}.intro br{display:none}
.gesture-hints{position:absolute;left:0;top:223px;font-size:9px;gap:15px}.gesture-hints svg{width:14px;height:14px}
#stage{top:328px;left:-6%;right:-6%;bottom:191px}
.stage-top{top:11px;right:11%}.specimen{font-size:8px;letter-spacing:1.3px}.handwritten{display:none}
.live-status{bottom:1px;gap:8px}#status-text{font-size:8px;min-width:143px;letter-spacing:1.5px}
.controls{left:5.5%;right:5.5%;bottom:85px;padding:13px;gap:16px;border-radius:18px}.squeeze{height:61px;min-width:121px;padding:0 13px;gap:7px;font-size:12px}.squeeze svg{width:20px}.firmness{min-width:80px}.reset{min-width:41px;padding-left:12px;font-size:8px}.range-heading{font-size:10px;gap:5px}#firmness-name{font-size:8px}.range-ends{font-size:7px}
.footer{left:7%;right:7%;bottom:26px;gap:8px;align-items:flex-start}.footer-left{font-size:7px;letter-spacing:1px;gap:8px}.footer-left b{font-size:8px}.footer-left .line{width:16px}.physics-badge{font-size:6px;letter-spacing:.8px;padding-top:2px}#note{position:absolute;top:20px;left:0;font-size:10px}
.demo-badge{top:81px;font-size:8px;padding:8px 12px}.help-panel{right:6%;top:76px;width:280px}
}
@media(max-width:380px){.squeeze{min-width:100px;font-size:11px;padding:0 10px}.controls{gap:12px}.reset{min-width:35px;padding-left:9px}.brand-name{font-size:22px}.demo-button{padding:0 11px}.hero{top:112px}h1{font-size:49px}.gesture-hints{top:214px}}
@media(max-height:760px) and (min-width:721px){.playground{min-height:680px}.hero{top:23%}h1{font-size:68px}.intro{margin:18px 0 20px}#stage{top:83px;bottom:142px}.controls{bottom:76px}.footer{bottom:23px}.stage-top{top:23px}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}.loader{animation-duration:2s}.squeeze,.reset svg{transition:none}}
</style>
<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>
</head>
<body>
<main class="playground">
<header class="header">
<a class="brand" href="#" aria-label="Softslice home">
<svg viewBox="0 0 40 40" fill="none" aria-hidden="true"><path d="M4 20a16 16 0 0 0 32 0H4Z" fill="#ed6d30"/><path d="M7 21a13 13 0 0 0 26 0H7Z" stroke="#fff4d9" stroke-width="1.8"/><path d="m20 22-8 8m8-8v11m0-11 8 8" stroke="#fff4d9" stroke-width="1.6" stroke-linecap="round"/><path d="m23 11 4-5m-8 4-1-5m9 10 6-2" stroke="#ed6d30" stroke-width="1.7" stroke-linecap="round"/></svg>
<span class="brand-name">softslice<span>.</span></span>
<span class="brand-divider"></span>
<span class="brand-caption">A little squeeze<br>of sunshine</span>
</a>
<div class="header-tools">
<button class="demo-button" id="demo-toggle" type="button" disabled><svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M4 2.5v11L13 8Z"/></svg><span id="demo-button-text">Play demo</span></button>
<button class="help-button" id="help-toggle" type="button" aria-label="How to play" aria-expanded="false" aria-controls="help-panel">?</button>
</div>
</header>
<section class="hero" aria-labelledby="title">
<p class="eyebrow">FRESHLY SQUEEZABLE</p>
<h1 id="title">A softer<br>side of<br><em>citrus.</em></h1>
<p class="intro">A small slice of sunshine, just for you.<br>Poke it. Pull it. Let the day wobble away.</p>
<div class="gesture-hints" id="instructions">
<span><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path d="M8 10V5a1.5 1.5 0 0 1 3 0v5l2-1 3 2v3l-3 4H8l-4-6a1 1 0 0 1 1-1l3 2"/><path d="M4 4 2 3m12 1 2-1M9 1v1"/></svg>Tap to jiggle</span>
<span><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path d="m6 3-3 3 3 3m-3-3h14m-3 5 3 3-3 3m3-3H3"/></svg>Drag to stretch</span>
</div>
</section>
<div id="stage">
<div id="loading"><span class="loader"></span><span>Slicing a little sunshine…</span></div>
<div class="stage-top" aria-hidden="true"><div class="specimen">01 — ORANGE JELLY</div><div class="handwritten">100%<br>squishable.<svg viewBox="0 0 50 40" fill="none"><path d="M38 3c4 13-6 23-25 23m0 0 7-7m-7 7 9 4" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg></div></div>
<div class="live-status"><span class="meter" aria-hidden="true"><i></i><i></i><i></i></span><span id="status-text">RESTING HAPPILY</span></div>
</div>
<div class="controls" aria-label="Jelly controls">
<button id="squeeze" class="squeeze" type="button" disabled>
<svg viewBox="0 0 25 25" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12.5h5m-3-3 3 3-3 3m17-3h-5m3-3-3 3 3 3M10 5c2-2 3-2 5 0m-5 15c2 2 3 2 5 0"/><path d="M11 8c-2 3-2 6 0 9m3-9c2 3 2 6 0 9"/></svg>
<span id="squeeze-text">Squeeze</span>
</button>
<div class="firmness">
<div class="range-heading"><label for="firmness">Firmness</label><output id="firmness-name" for="firmness">Juicy</output></div>
<input id="firmness" type="range" min="0" max="100" value="42" step="1" aria-valuetext="Juicy, 42 percent" disabled>
<div class="range-ends"><span>SOFT</span><span>FIRM</span></div>
</div>
<button id="reset" class="reset" type="button" disabled aria-label="Reset jelly, juice, view and firmness"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 9a8 8 0 1 1 0 7M4 4v5h5"/></svg><span>Reset</span></button>
</div>
<footer class="footer">
<div class="footer-left"><b>THE PLAY SERIES</b><span class="line"></span><span>NO. 001</span></div>
<span id="note" aria-live="polite">Good things come with a little give.</span>
<span class="physics-badge">REAL-TIME SOFT BODY</span>
</footer>
<div id="demo-badge" class="demo-badge" hidden>DEMO IN PLAY · TOUCH TO TAKE OVER</div>
<aside class="help-panel" id="help-panel" hidden>
<h2>A little room to play.</h2>
<p><strong>Tap</strong> the orange for a little jiggle.<br><strong>Drag</strong> its flesh, then let go.<br><strong>Squeeze</strong> to press out a few drops.</p>
<p>Try a softer or firmer slice. Drag the empty space around the plate to turn the view.</p>
<small>Every wobble is simulated live. The slice has elastic stretch and volume constraints, so it always finds its way back.</small>
</aside>
</main>
<script type="module">
const $ = function(id){return document.getElementById(id);};
const helpButton = $('help-toggle');
helpButton.addEventListener('click',function(){
const open = $('help-panel').hidden;
$('help-panel').hidden = !open;
helpButton.setAttribute('aria-expanded',String(open));
});
document.addEventListener('keydown',function(e){
if(e.key === 'Escape'){$('help-panel').hidden=true;helpButton.setAttribute('aria-expanded','false');}
});
try {
const THREE = await import('three');
const modules = await Promise.all([
import('three/addons/environments/RoomEnvironment.js'),
import('three/addons/utils/BufferGeometryUtils.js')
]);
const RoomEnvironment = modules[0].RoomEnvironment;
const mergeVertices = modules[1].mergeVertices;
const stage = $('stage');
const slider = $('firmness');
const squeezeButton = $('squeeze');
const resetButton = $('reset');
const demoButton = $('demo-toggle');
const meterBars = Array.from(document.querySelectorAll('.meter i'));
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
const smooth = function(t){t=clamp(t,0,1);return t*t*(3-2*t);};
let seed = 728194;
function random(){seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/4294967296;}
const renderer = new THREE.WebGLRenderer({antialias:true,alpha:false,powerPreference:'high-performance'});
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,window.innerWidth<721?1.7:2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute('role','img');
renderer.domElement.setAttribute('aria-label','Interactive three-dimensional orange jelly on a white plate. Tap to poke or drag to stretch.');
renderer.domElement.setAttribute('aria-describedby','instructions');
renderer.domElement.tabIndex = 0;
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#f6f2e9');
scene.fog = new THREE.Fog('#f6f2e9',15,32);
const camera = new THREE.PerspectiveCamera(35,1,.1,50);
const viewTarget = new THREE.Vector3(0,.75,0);
let viewAngle = .27;
let desiredAngle = .27;
let cameraDistance = 7;
function updateCamera(){
camera.position.set(Math.sin(viewAngle)*cameraDistance*.88,.75+cameraDistance*.475,Math.cos(viewAngle)*cameraDistance*.88);
camera.lookAt(viewTarget);
camera.updateMatrixWorld();
}
function resize(){
const w=stage.clientWidth,h=stage.clientHeight;
renderer.setSize(w,h,false);
camera.aspect=w/Math.max(h,1);
camera.updateProjectionMatrix();
const f=Math.tan(THREE.MathUtils.degToRad(17.5));
cameraDistance=Math.max(3.65/(2*f),5.85/(2*f*camera.aspect));
updateCamera();
}
new ResizeObserver(resize).observe(stage);
resize();
const pmrem = new THREE.PMREMGenerator(renderer);
const room = new RoomEnvironment();
const environment = pmrem.fromScene(room,.035);
scene.environment = environment.texture;
room.dispose();
pmrem.dispose();
scene.add(new THREE.HemisphereLight('#fff9e9','#c6ae8f',1.25));
const key = new THREE.DirectionalLight('#fff5df',3.3);
key.position.set(-3.5,6,4.5);
key.castShadow=true;
key.shadow.mapSize.set(2048,2048);
key.shadow.camera.left=-4.5;key.shadow.camera.right=4.5;
key.shadow.camera.top=4.5;key.shadow.camera.bottom=-4.5;
key.shadow.camera.near=.1;key.shadow.camera.far=15;
key.shadow.normalBias=.014;key.shadow.bias=-.00015;
key.shadow.radius=4;
scene.add(key);
const rim = new THREE.DirectionalLight('#ffd99b',2.7);
rim.position.set(1,3,-4);scene.add(rim);
const fill = new THREE.DirectionalLight('#fffdf5',1.1);
fill.position.set(4,2,3);scene.add(fill);
const ground = new THREE.Mesh(new THREE.PlaneGeometry(100,100),new THREE.MeshStandardMaterial({color:'#f6f2e9',roughness:.93}));
ground.rotation.x=-Math.PI/2;ground.receiveShadow=true;scene.add(ground);
const shadowCanvas=document.createElement('canvas');shadowCanvas.width=256;shadowCanvas.height=256;
const shadowContext=shadowCanvas.getContext('2d');
const shadowGradient=shadowContext.createRadialGradient(128,128,22,128,128,126);
shadowGradient.addColorStop(0,'rgba(82,50,20,0.19)');shadowGradient.addColorStop(.6,'rgba(82,50,20,0.1)');shadowGradient.addColorStop(1,'rgba(82,50,20,0)');
shadowContext.fillStyle=shadowGradient;shadowContext.fillRect(0,0,256,256);
const contactShadow=new THREE.Mesh(new THREE.PlaneGeometry(6.4,6.4),new THREE.MeshBasicMaterial({map:new THREE.CanvasTexture(shadowCanvas),transparent:true,depthWrite:false}));
contactShadow.rotation.x=-Math.PI/2;contactShadow.position.y=.007;scene.add(contactShadow);
const plateProfile=[
[0,.11],[.86,.09],[.91,.044],[1.06,.047],[1.11,.09],[1.64,.10],
[2.15,.14],[2.38,.20],[2.56,.28],[2.62,.33],[2.61,.365],[2.56,.38],
[2.40,.33],[2.20,.25],[1.92,.21],[1.60,.20],[0,.20]
].map(function(p){return new THREE.Vector2(p[0],p[1]);});
const plate = new THREE.Mesh(
new THREE.LatheGeometry(plateProfile,144),
new THREE.MeshPhysicalMaterial({color:'#fffefa',roughness:.18,metalness:0,clearcoat:1,clearcoatRoughness:.1,envMapIntensity:.75,side:THREE.DoubleSide})
);
plate.castShadow=true;plate.receiveShadow=true;scene.add(plate);
const R=1.64,BASE=.224,DEPTH=.57,FLOOR=.216;
const RINGS=5,SECTORS=20,LAYERS=3;
const PER_LAYER=1+RINGS*(SECTORS+1);
const STEP=1/100;
let firmness=.42,edgeCompliance=0,volumeCompliance=0;
let grab=null,gesture=null,squeezeTime=-1,pressure=0;
let juiceQueued=false,juiceClock=-1,juiceIndex=0;
let demoActive=false,demoTime=0,lastDemoTime=-.001;
let energy=0,noteUntil=0,elapsed=0;
// A volumetric XPBD body, not a mesh animation. Triangular prisms are
// subdivided consistently into tetrahedra. Material points in every
// visible layer are embedded in this same deforming volume.
class SoftBody {
constructor(){
const positions=[],triangles=[],tetList=[],edgeList=[],edgeSet=new Set();
this.index=function(k,r,a){return k*PER_LAYER+(r===0?0:1+(r-1)*(SECTORS+1)+a);};
for(let k=0;k<LAYERS;k++){
const z=-DEPTH/2+k*DEPTH/(LAYERS-1);
positions.push(0,BASE,z);
for(let r=1;r<=RINGS;r++){
for(let a=0;a<=SECTORS;a++){
const theta=a*Math.PI/SECTORS,rad=r*R/RINGS;
positions.push(rad*Math.cos(theta),BASE+rad*Math.sin(theta),z);
}
}
}
this.rest=new Float64Array(positions);
this.p=new Float64Array(positions);
this.old=new Float64Array(positions);
this.v=new Float64Array(positions.length);
this.count=positions.length/3;
this.w=new Float64Array(this.count);
for(let i=0;i<this.count;i++)this.w[i]=this.rest[i*3+1]<BASE+.0001?0:1;
for(let a=0;a<SECTORS;a++){
triangles.push([0,this.index(0,1,a),this.index(0,1,a+1)]);
for(let r=2;r<=RINGS;r++){
const A=this.index(0,r-1,a),B=this.index(0,r,a),C=this.index(0,r,a+1),D=this.index(0,r-1,a+1);
triangles.push([A,B,C],[A,C,D]);
}
}
const self=this;
function addEdge(a,b,complianceScale){
if(a>b){const q=a;a=b;b=q;}
const id=a*self.count+b;
if(edgeSet.has(id))return;
edgeSet.add(id);
const ai=a*3,bi=b*3;
const length=Math.hypot(positions[ai]-positions[bi],positions[ai+1]-positions[bi+1],positions[ai+2]-positions[bi+2]);
edgeList.push({a:a,b:b,length:length,scale:complianceScale||1,lambda:0});
}
function addTet(a,b,c,d){
let det=self.detAt(a,b,c,d,self.rest);
if(det<0){const q=b;b=c;c=q;det=-det;}
if(det<1e-9)return;
tetList.push({a:a,b:b,c:c,d:d,rest:det,lambda:0});
addEdge(a,b);addEdge(a,c);addEdge(a,d);addEdge(b,c);addEdge(b,d);addEdge(c,d);
}
for(let k=0;k<LAYERS-1;k++){
for(const tri of triangles){
const t=tri.slice().sort(function(a,b){return a-b;});
const a=t[0]+k*PER_LAYER,b=t[1]+k*PER_LAYER,c=t[2]+k*PER_LAYER;
const A=a+PER_LAYER,B=b+PER_LAYER,C=c+PER_LAYER;
addTet(a,b,c,C);addTet(a,b,B,C);addTet(a,A,B,C);
}
}
// Longer material edges resist folding without fixing the surface.
for(let k=0;k<LAYERS;k++){
for(let r=1;r<=RINGS;r++){
for(let a=0;a<=SECTORS;a++){
if(a+2<=SECTORS)addEdge(this.index(k,r,a),this.index(k,r,a+2),2.5);
if(r+2<=RINGS)addEdge(this.index(k,r,a),this.index(k,r+2,a),2);
if(k===0)addEdge(this.index(0,r,a),this.index(2,r,a),1);
}
}
}
this.edges=edgeList;this.tets=tetList;
}
detAt(a,b,c,d,p){
a*=3;b*=3;c*=3;d*=3;
const ux=p[b]-p[a],uy=p[b+1]-p[a+1],uz=p[b+2]-p[a+2];
const vx=p[c]-p[a],vy=p[c+1]-p[a+1],vz=p[c+2]-p[a+2];
const wx=p[d]-p[a],wy=p[d+1]-p[a+1],wz=p[d+2]-p[a+2];
return ux*(vy*wz-vz*wy)+uy*(vz*wx-vx*wz)+uz*(vx*wy-vy*wx);
}
reset(){this.p.set(this.rest);this.old.set(this.rest);this.v.fill(0);}
solveEdges(h){
const p=this.p,w=this.w;
const alpha=edgeCompliance/(h*h);
for(let i=0;i<this.edges.length;i++){
const e=this.edges[i],a=e.a*3,b=e.b*3,wa=w[e.a],wb=w[e.b];
if(wa+wb===0)continue;
const dx=p[a]-p[b],dy=p[a+1]-p[b+1],dz=p[a+2]-p[b+2];
const len=Math.sqrt(dx*dx+dy*dy+dz*dz);
if(len<1e-8)continue;
const al=alpha*e.scale;
const dl=clamp(-(len-e.length+al*e.lambda)/(wa+wb+al),-.065,.065);
e.lambda+=dl;
const s=dl/len;
p[a]+=wa*s*dx;p[a+1]+=wa*s*dy;p[a+2]+=wa*s*dz;
p[b]-=wb*s*dx;p[b+1]-=wb*s*dy;p[b+2]-=wb*s*dz;
}
}
solveVolumes(h){
const p=this.p,w=this.w,alpha=volumeCompliance/(h*h);
for(let i=0;i<this.tets.length;i++){
const t=this.tets[i],a=t.a*3,b=t.b*3,c=t.c*3,d=t.d*3;
const ux=p[b]-p[a],uy=p[b+1]-p[a+1],uz=p[b+2]-p[a+2];
const vx=p[c]-p[a],vy=p[c+1]-p[a+1],vz=p[c+2]-p[a+2];
const wx=p[d]-p[a],wy=p[d+1]-p[a+1],wz=p[d+2]-p[a+2];
const bx=vy*wz-vz*wy,by=vz*wx-vx*wz,bz=vx*wy-vy*wx;
const cx=wy*uz-wz*uy,cy=wz*ux-wx*uz,cz=wx*uy-wy*ux;
const dx=uy*vz-uz*vy,dy=uz*vx-ux*vz,dz=ux*vy-uy*vx;
const ax=-bx-cx-dx,ay=-by-cy-dy,az=-bz-cz-dz;
const wa=w[t.a],wb=w[t.b],wc=w[t.c],wd=w[t.d];
const denom=wa*(ax*ax+ay*ay+az*az)+wb*(bx*bx+by*by+bz*bz)+wc*(cx*cx+cy*cy+cz*cz)+wd*(dx*dx+dy*dy+dz*dz)+alpha;
if(denom<1e-12)continue;
const det=ux*bx+uy*by+uz*bz;
const dl=clamp(-(det-t.rest+alpha*t.lambda)/denom,-.3,.3);
t.lambda+=dl;
p[a]+=wa*dl*ax;p[a+1]+=wa*dl*ay;p[a+2]+=wa*dl*az;
p[b]+=wb*dl*bx;p[b+1]+=wb*dl*by;p[b+2]+=wb*dl*bz;
p[c]+=wc*dl*cx;p[c+1]+=wc*dl*cy;p[c+2]+=wc*dl*cz;
p[d]+=wd*dl*dx;p[d+1]+=wd*dl*dy;p[d+2]+=wd*dl*dz;
}
}
contacts(){
const p=this.p;
const ceiling=BASE+R-.43*pressure;
for(let i=0;i<this.count;i++){
const j=i*3;
if(this.w[i]===0){p[j]=this.rest[j];p[j+1]=this.rest[j+1];p[j+2]=this.rest[j+2];continue;}
if(p[j+1]<FLOOR)p[j+1]=FLOOR;
if(pressure>.001&&p[j+1]>ceiling)p[j+1]=Math.max(ceiling,p[j+1]-.055);
// A generous strain envelope is a final numerical guard.
const dx=p[j]-this.rest[j],dy=p[j+1]-this.rest[j+1],dz=p[j+2]-this.rest[j+2];
const dist=Math.sqrt(dx*dx+dy*dy+dz*dz);
if(dist>1.1){const s=1.1/dist;p[j]=this.rest[j]+dx*s;p[j+1]=this.rest[j+1]+dy*s;p[j+2]=this.rest[j+2]+dz*s;}
}
}
step(h){
this.old.set(this.p);
const p=this.p,v=this.v,w=this.w;
const damping=Math.exp(-(1.7+firmness*.8)*h);
if(grab)grab.target.lerp(grab.desired,1-Math.exp(-24*h));
for(let i=0;i<this.count;i++){
if(w[i]===0)continue;
const j=i*3;
v[j]*=damping;v[j+1]=(v[j+1]-1.65*h)*damping;v[j+2]*=damping;
p[j]+=v[j]*h;p[j+1]+=v[j+1]*h;p[j+2]+=v[j+2]*h;
}
for(const e of this.edges)e.lambda=0;
for(const t of this.tets)t.lambda=0;
for(let it=0;it<5;it++){
this.solveEdges(h);
this.solveVolumes(h);
if(grab){
const target=grab.target;
for(const g of grab.nodes){
const j=g.i*3;
let dx=target.x+g.x-p[j],dy=target.y+g.y-p[j+1],dz=target.z+g.z-p[j+2];
let amount=.19*g.weight;
const length=Math.sqrt(dx*dx+dy*dy+dz*dz);
if(length*amount>.032)amount=.032/length;
p[j]+=dx*amount;p[j+1]+=dy*amount;p[j+2]+=dz*amount;
}
}
this.contacts();
}
let sum=0,moving=0;
for(let i=0;i<this.count;i++){
const j=i*3;
if(w[i]===0){v[j]=v[j+1]=v[j+2]=0;continue;}
for(let c=0;c<3;c++){
const n=j+c;
if(!Number.isFinite(p[n]))p[n]=this.rest[n];
v[n]=clamp((p[n]-this.old[n])/h,-5,5);
}
if(p[j+1]<=FLOOR+.002){v[j]*=.8;v[j+2]*=.8;v[j+1]=Math.max(0,v[j+1]);}
sum+=v[j]*v[j]+v[j+1]*v[j+1]+v[j+2]*v[j+2];moving++;
}
energy=Math.sqrt(sum/Math.max(moving,1));
}
}
const body=new SoftBody();
function setFirmness(value){
firmness=clamp(Number(value),0,100)/100;
edgeCompliance=.0000025+Math.pow(1-firmness,2)*.00030;
volumeCompliance=3e-10+(1-firmness)*6e-10;
slider.value=String(Math.round(firmness*100));
const name=firmness<.25?'Tender':firmness<.58?'Juicy':firmness<.82?'Bouncy':'Firm';
$('firmness-name').value=name;
$('firmness-name').textContent=name;
slider.style.background='linear-gradient(to right,#ee682b '+(firmness*100)+'%,#e6dfd3 '+(firmness*100)+'%)';
slider.setAttribute('aria-valuetext',name+', '+Math.round(firmness*100)+' percent');
}
setFirmness(42);
// Eight-node polar-volume embedding, with a rest residual to retain
// smoothly curved, beveled render surfaces on a coarser physical mesh.
function bindPoint(x,y,z){
const yy=Math.max(0,y-BASE);
const theta=clamp(Math.atan2(yy,x),0,Math.PI);
const rf=clamp(Math.hypot(x,yy)/R*RINGS,0,RINGS);
const r0=Math.min(RINGS-1,Math.floor(rf)),fr=rf-r0;
const af=theta/Math.PI*SECTORS,a0=Math.min(SECTORS-1,Math.floor(af)),fa=af-a0;
const zf=clamp((z+DEPTH/2)/DEPTH*(LAYERS-1),0,LAYERS-1);
const z0=Math.min(LAYERS-2,Math.floor(zf)),fz=zf-z0;
const ids=new Uint16Array(8),weights=new Float32Array(8);
let n=0,rx=0,ry=0,rz=0;
for(let k=0;k<2;k++)for(let r=0;r<2;r++)for(let a=0;a<2;a++){
const i=body.index(z0+k,r0+r,a0+a);
const weight=(k?fz:1-fz)*(r?fr:1-fr)*(a?fa:1-fa);
ids[n]=i*3;weights[n]=weight;
rx+=body.rest[i*3]*weight;ry+=body.rest[i*3+1]*weight;rz+=body.rest[i*3+2]*weight;n++;
}
return {ids:ids,weights:weights,x:x-rx,y:y-ry,z:z-rz};
}
function evaluate(binding,out){
let x=binding.x,y=binding.y,z=binding.z;
for(let i=0;i<8;i++){
const j=binding.ids[i],w=binding.weights[i];
x+=body.p[j]*w;y+=body.p[j+1]*w;z+=body.p[j+2]*w;
}
out.set(x,y,z);return out;
}
const skins=[],pickMeshes=[];
function addSkin(geometry,material,cast){
const geo=mergeVertices(geometry,1e-5);
geometry.dispose();
const arr=geo.attributes.position.array,bindings=[];
for(let i=0;i<arr.length;i+=3)bindings.push(bindPoint(arr[i],arr[i+1],arr[i+2]));
geo.attributes.position.setUsage(THREE.DynamicDrawUsage);
const mesh=new THREE.Mesh(geo,material);
mesh.castShadow=cast!==false;mesh.receiveShadow=true;mesh.frustumCulled=false;
// This bound deliberately includes the maximum allowed grab strain.
geo.boundingSphere=new THREE.Sphere(new THREE.Vector3(0,BASE+.7,0),3.2);
scene.add(mesh);skins.push({mesh:mesh,geometry:geo,bindings:bindings});
pickMeshes.push(mesh);
return mesh;
}
function sectorShape(inner,outer,a,b){
const shape=new THREE.Shape();
shape.moveTo(inner*Math.cos(a),inner*Math.sin(a));
shape.lineTo(outer*Math.cos(a),outer*Math.sin(a));
shape.absarc(0,0,outer,a,b,false);
shape.lineTo(inner*Math.cos(b),inner*Math.sin(b));
if(inner>.0001)shape.absarc(0,0,inner,b,a,true);
else shape.lineTo(0,0);
shape.closePath();return shape;
}
function sectorGeometry(inner,outer,a,b,depth,bevel,curves){
const geo=new THREE.ExtrudeGeometry(sectorShape(inner,outer,a,b),{
depth:depth,steps:1,bevelEnabled:bevel>0,bevelThickness:bevel,
bevelSize:bevel*.65,bevelSegments:3,curveSegments:curves
});
geo.translate(0,BASE,-depth/2);return geo;
}
function peelTexture(){
const c=document.createElement('canvas');c.width=512;c.height=256;
const ctx=c.getContext('2d'),img=ctx.createImageData(512,256);
for(let i=0;i<img.data.length;i+=4){
const n=random(),q=random();
img.data[i]=239+n*16;img.data[i+1]=99+n*36+q*8;img.data[i+2]=4+n*13;img.data[i+3]=255;
}
ctx.putImageData(img,0,0);
for(let i=0;i<3200;i++){
const x=random()*512,y=random()*256,r=.6+random()*1.7;
ctx.beginPath();ctx.arc(x,y,r,0,Math.PI*2);ctx.fillStyle=random()>.5?'rgba(255,204,70,.22)':'rgba(156,62,0,.13)';ctx.fill();
ctx.beginPath();ctx.arc(x-.4,y-.45,r*.48,0,Math.PI*2);ctx.fillStyle='rgba(255,229,115,.13)';ctx.fill();
}
const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;t.wrapS=t.wrapT=THREE.RepeatWrapping;t.repeat.set(1.5,1.5);t.anisotropy=Math.min(8,renderer.capabilities.getMaxAnisotropy());return t;
}
function pithTexture(){
const c=document.createElement('canvas');c.width=c.height=128;
const ctx=c.getContext('2d');ctx.fillStyle='#fff2d2';ctx.fillRect(0,0,128,128);
for(let i=0;i<2300;i++){ctx.fillStyle=random()>.5?'rgba(190,158,103,.13)':'rgba(255,255,246,.65)';ctx.fillRect(random()*128,random()*128,.5+random(),1+random()*3);}
const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;t.wrapS=t.wrapT=THREE.RepeatWrapping;t.repeat.set(2,2);return t;
}
const peelMap=peelTexture();
const peelMaterial=new THREE.MeshPhysicalMaterial({
color:'#ff9418',map:peelMap,bumpMap:peelMap,bumpScale:.018,roughness:.32,metalness:0,
clearcoat:.5,clearcoatRoughness:.22,envMapIntensity:.8
});
const pithMap=pithTexture();
const pithMaterial=new THREE.MeshStandardMaterial({color:'#fff1d3',map:pithMap,bumpMap:pithMap,bumpScale:.006,roughness:.55});
const fleshMaterials=[];
for(let j=0;j<9;j++){
const mat=new THREE.MeshPhysicalMaterial({
color:new THREE.Color().setHSL(.092+(j%3)*.004,.98,.64),
roughness:.13,metalness:0,transmission:.91,thickness:.47,
ior:1.36,attenuationColor:new THREE.Color('#ffa123'),attenuationDistance:1.05,
clearcoat:1,clearcoatRoughness:.085,envMapIntensity:1.05
});
fleshMaterials.push(mat);
addSkin(sectorGeometry(.12,1.478,j*Math.PI/9+.013,(j+1)*Math.PI/9-.013,.475,.014,12),mat,true);
}
addSkin(sectorGeometry(1.574,1.637,0,Math.PI,.535,.010,56),peelMaterial,true);
addSkin(sectorGeometry(1.482,1.578,.001,Math.PI-.001,.516,.006,56),pithMaterial,true);
for(let j=1;j<9;j++){
const a=j*Math.PI/9;
addSkin(sectorGeometry(.045,1.49,a-.008,a+.008,.506,.002,3),pithMaterial,true);
}
addSkin(sectorGeometry(0,.133,0,Math.PI,.513,.004,16),pithMaterial,true);
// Each juice vesicle is a tiny radial ellipsoid inside the clear flesh.
// Four embedded material points provide both translation and deformation.
const vesicles=[];
function addCell(r,theta,z,length,width){
const x=r*Math.cos(theta),y=BASE+r*Math.sin(theta);
const ux=Math.cos(theta),uy=Math.sin(theta);
vesicles.push({
c:bindPoint(x,y,z),
radial:bindPoint(x+ux*length,y+uy*length,z),
tangent:bindPoint(x-uy*width,y+ux*width,z),
depth:bindPoint(x,y,z+.021+random()*.012),
hue:.075+random()*.028,light:.48+random()*.14
});
}
for(let j=0;j<9;j++){
const a=j*Math.PI/9+.024,b=(j+1)*Math.PI/9-.024;
for(let row=0;row<23;row++){
const r=.20+(row+.5)/23*1.22;
const number=Math.max(1,Math.floor((b-a)*r/.043));
for(let col=0;col<number;col++){
const theta=lerp(a,b,(col+.5+(random()-.5)*.4)/number);
const rad=r+(random()-.5)*.027;
addCell(rad,theta,.177+(random()-.5)*.035,.035+random()*.021,.013+random()*.007);
if(random()<.38)addCell(rad+.012,theta+(random()-.5)*.014,-.113+(random()-.5)*.07,.037+random()*.02,.014+random()*.008);
}
}
}
const cellGeometry=new THREE.SphereGeometry(1,7,5);
const cellMaterial=new THREE.MeshPhysicalMaterial({color:'#ffb935',roughness:.25,metalness:0,clearcoat:.85,clearcoatRoughness:.16,envMapIntensity:.8});
const cells=new THREE.InstancedMesh(cellGeometry,cellMaterial,vesicles.length);
cells.instanceMatrix.setUsage(THREE.DynamicDrawUsage);cells.frustumCulled=false;
const cellColor=new THREE.Color();
for(let i=0;i<vesicles.length;i++){const c=vesicles[i];cellColor.setHSL(c.hue,.93,c.light);cells.setColorAt(i,cellColor);}
cells.instanceColor.needsUpdate=true;scene.add(cells);
// A few translucent radial fibers on the cut surface.
const fiberPositions=[];
for(let j=0;j<9;j++)for(let k=0;k<11;k++){
const theta=(j+(k+1)/12)*Math.PI/9;
const start=.17+random()*.28,end=1.39+random()*.045;
for(let s=0;s<9;s++){
const r1=lerp(start,end,s/9),r2=lerp(start,end,(s+1)/9);
const t1=theta+Math.sin(s*.35)*.005,t2=theta+Math.sin((s+1)*.35)*.005;
fiberPositions.push(r1*Math.cos(t1),BASE+r1*Math.sin(t1),.253,r2*Math.cos(t2),BASE+r2*Math.sin(t2),.253);
}
}
const fiberGeometry=new THREE.BufferGeometry();
fiberGeometry.setAttribute('position',new THREE.Float32BufferAttribute(fiberPositions,3));
fiberGeometry.attributes.position.setUsage(THREE.DynamicDrawUsage);
const fibers=new THREE.LineSegments(fiberGeometry,new THREE.LineBasicMaterial({color:'#fff0bb',transparent:true,opacity:.12,depthWrite:false}));
fibers.frustumCulled=false;scene.add(fibers);
const fiberBindings=[];
for(let i=0;i<fiberPositions.length;i+=3)fiberBindings.push(bindPoint(fiberPositions[i],fiberPositions[i+1],fiberPositions[i+2]));
const ring=new THREE.Mesh(new THREE.TorusGeometry(.095,.005,8,40),new THREE.MeshBasicMaterial({color:'#fff6dc',transparent:true,opacity:.8,depthTest:false,depthWrite:false}));
ring.visible=false;ring.renderOrder=8;scene.add(ring);
let ringLife=0;
const temp=new THREE.Vector3(),ca=new THREE.Vector3(),cb=new THREE.Vector3(),cc=new THREE.Vector3(),cd=new THREE.Vector3();
function updateSkins(){
for(const skin of skins){
const arr=skin.geometry.attributes.position.array;
for(let i=0;i<skin.bindings.length;i++){
evaluate(skin.bindings[i],temp);
const j=i*3;arr[j]=temp.x;arr[j+1]=temp.y;arr[j+2]=temp.z;
}
skin.geometry.attributes.position.needsUpdate=true;
skin.geometry.computeVertexNormals();
}
const arr=fiberGeometry.attributes.position.array;
for(let i=0;i<fiberBindings.length;i++){
evaluate(fiberBindings[i],temp);const j=i*3;
arr[j]=temp.x;arr[j+1]=temp.y;arr[j+2]=temp.z;
}
fiberGeometry.attributes.position.needsUpdate=true;
const matrix=cells.instanceMatrix.array;
for(let i=0;i<vesicles.length;i++){
const cell=vesicles[i];
evaluate(cell.c,ca);evaluate(cell.tangent,cb);evaluate(cell.radial,cc);evaluate(cell.depth,cd);
cb.sub(ca);cc.sub(ca);cd.sub(ca);
const n=i*16;
matrix[n]=cb.x;matrix[n+1]=cb.y;matrix[n+2]=cb.z;matrix[n+3]=0;
matrix[n+4]=cc.x;matrix[n+5]=cc.y;matrix[n+6]=cc.z;matrix[n+7]=0;
matrix[n+8]=cd.x;matrix[n+9]=cd.y;matrix[n+10]=cd.z;matrix[n+11]=0;
matrix[n+12]=ca.x;matrix[n+13]=ca.y;matrix[n+14]=ca.z;matrix[n+15]=1;
}
cells.instanceMatrix.needsUpdate=true;
}
const dropGeometry=new THREE.SphereGeometry(1,14,10);
const dropMaterial=new THREE.MeshPhysicalMaterial({color:'#ffb72d',transmission:.78,thickness:.09,roughness:.09,ior:1.34,clearcoat:1,clearcoatRoughness:.06,attenuationColor:new THREE.Color('#ffac1b'),attenuationDistance:.45});
const drops=[];
for(let i=0;i<30;i++){
const mesh=new THREE.Mesh(dropGeometry,dropMaterial);mesh.visible=false;mesh.castShadow=false;scene.add(mesh);
drops.push({mesh:mesh,active:false,age:0,position:new THREE.Vector3(),velocity:new THREE.Vector3(),radius:.03,landed:false});
}
let nextDrop=0;
function emitDrop(){
const d=drops[nextDrop++%drops.length];
const x=-.74+juiceIndex*.31+(random()-.5)*.14;
const y=BASE+.47+random()*.35;
evaluate(bindPoint(x,y,.267),d.position);
d.position.z+=.027;
d.velocity.set(x*.24+(random()-.5)*.16,-.13-random()*.15,.24+random()*.22);
d.radius=.026+random()*.017;d.age=0;d.active=true;d.landed=false;d.mesh.visible=true;
}
function plateHeight(r){
if(r<1.85)return .204;
if(r<2.6)return .204+smooth((r-1.85)/.75)*.17;
return .008;
}
function updateDrops(dt){
for(const d of drops){
if(!d.active)continue;
d.age+=dt;
if(d.age>14){d.active=false;d.mesh.visible=false;continue;}
const r=d.radius;
if(!d.landed){
d.velocity.y-=5.6*dt;
d.position.addScaledVector(d.velocity,dt);
const h=plateHeight(Math.hypot(d.position.x,d.position.z));
if(d.position.y<h+r*.5){
d.position.y=h+r*.43;d.landed=true;d.velocity.y=0;
d.velocity.x*=.65;d.velocity.z*=.65;
}
}else{
d.position.addScaledVector(d.velocity,dt);
d.velocity.multiplyScalar(Math.exp(-4.8*dt));
d.position.y=plateHeight(Math.hypot(d.position.x,d.position.z))+r*.32;
}
const fade=Math.min(1,(14-d.age)/2);
d.mesh.position.copy(d.position);
if(d.landed)d.mesh.scale.set(r*1.55*fade,r*.36*fade,r*1.8*fade);
else{
const stretch=1+Math.min(1,Math.abs(d.velocity.y)*.35);
d.mesh.scale.set(r*.85*fade,r*stretch*fade,r*.85*fade);
}
}
}
function setNote(message,seconds){
$('note').textContent=message;noteUntil=elapsed+(seconds||3);
}
function squeeze(){
if(squeezeTime>=0)return;
squeezeTime=0;juiceQueued=false;juiceClock=-1;juiceIndex=0;
squeezeButton.classList.add('active');
squeezeButton.setAttribute('aria-pressed','true');
$('squeeze-text').textContent='Squeezing…';
setNote('A little pressure. A little sunshine.',3);
}
function updateSqueeze(dt){
if(squeezeTime>=0){
squeezeTime+=dt;
if(squeezeTime<.85)pressure=smooth(squeezeTime/.85);
else if(squeezeTime<1.35)pressure=1;
else if(squeezeTime<2.2)pressure=1-smooth((squeezeTime-1.35)/.85);
else{
squeezeTime=-1;pressure=0;
squeezeButton.classList.remove('active');squeezeButton.setAttribute('aria-pressed','false');
$('squeeze-text').textContent='Squeeze';
}
if(pressure>.83&&!juiceQueued){
juiceQueued=true;juiceClock=0;juiceIndex=0;
setNote('Five little drops of sunshine.',4);
}
}
if(juiceClock>=0){
juiceClock+=dt;
const times=[0,.11,.22,.34,.49];
while(juiceIndex<5&&juiceClock>=times[juiceIndex]){emitDrop();juiceIndex++;}
if(juiceIndex>=5)juiceClock=-1;
}
}
function poke(point,direction,strength){
for(let i=0;i<body.count;i++){
if(body.w[i]===0)continue;
const j=i*3;
const d2=(body.p[j]-point.x)**2+(body.p[j+1]-point.y)**2+(body.p[j+2]-point.z)**2;
const influence=Math.exp(-d2/.17)*(strength||1.8);
body.v[j]+=direction.x*influence;
body.v[j+1]+=direction.y*influence;
body.v[j+2]+=direction.z*influence;
}
ring.position.copy(point);ring.quaternion.copy(camera.quaternion);ringLife=.55;ring.visible=true;
}
function beginGrab(point,isDemo){
const nodes=[];
for(let i=0;i<body.count;i++){
if(body.w[i]===0)continue;
const j=i*3,dx=body.p[j]-point.x,dy=body.p[j+1]-point.y,dz=body.p[j+2]-point.z;
const weight=Math.exp(-(dx*dx+dy*dy+dz*dz)/.115);
if(weight>.025)nodes.push({i:i,x:dx,y:dy,z:dz,weight:weight});
}
grab={origin:point.clone(),target:point.clone(),desired:point.clone(),nodes:nodes,demo:isDemo||false};
ring.visible=true;ringLife=1;
}
function resetAll(silent){
grab=null;gesture=null;body.reset();energy=0;
squeezeTime=-1;pressure=0;juiceClock=-1;juiceQueued=false;
squeezeButton.classList.remove('active');squeezeButton.setAttribute('aria-pressed','false');$('squeeze-text').textContent='Squeeze';
for(const d of drops){d.active=false;d.mesh.visible=false;}
setFirmness(42);desiredAngle=.27;
ringLife=0;ring.visible=false;
if(!silent)setNote('Fresh as new. Have another go.',3);
}
function stopDemo(){
if(!demoActive)return;
demoActive=false;
if(grab&&grab.demo)grab=null;
$('demo-badge').hidden=true;$('demo-button-text').textContent='Play demo';
}
function startDemo(){
resetAll(true);demoTime=0;lastDemoTime=-.001;demoActive=true;
$('demo-badge').hidden=false;$('demo-button-text').textContent='Stop demo';
setNote('A little taste of what this slice can do.',3);
}
document.addEventListener('pointerdown',function(e){if(e.isTrusted)stopDemo();},{capture:true,passive:true});
slider.addEventListener('input',function(){stopDemo();setFirmness(slider.value);});
squeezeButton.addEventListener('click',function(){stopDemo();squeeze();});
resetButton.addEventListener('click',function(){stopDemo();resetAll(false);});
demoButton.addEventListener('click',function(){
// A pointerdown stops an existing demo before the subsequent click.
if(demoActive)stopDemo();else startDemo();
});
const raycaster=new THREE.Raycaster(),pointer=new THREE.Vector2(),dragPlane=new THREE.Plane();
const rayPoint=new THREE.Vector3(),direction=new THREE.Vector3(),movement=new THREE.Vector3();
function setRay(e){
const rect=renderer.domElement.getBoundingClientRect();
pointer.set((e.clientX-rect.left)/rect.width*2-1,-(e.clientY-rect.top)/rect.height*2+1);
raycaster.setFromCamera(pointer,camera);
}
renderer.domElement.addEventListener('pointerdown',function(e){
if(gesture)return;
e.preventDefault();stopDemo();setRay(e);
const hits=raycaster.intersectObjects(pickMeshes,false);
renderer.domElement.setPointerCapture(e.pointerId);
if(hits.length){
const hit=hits[0];
const point=hit.point.clone();
camera.getWorldDirection(direction);
dragPlane.setFromNormalAndCoplanarPoint(direction,point);
gesture={id:e.pointerId,x:e.clientX,y:e.clientY,point:point,dragging:false,orbit:false};
poke(point,direction,2.15);
setNote('A little wobble looks good on you.',2.5);
}else{
gesture={id:e.pointerId,x:e.clientX,y:e.clientY,angle:desiredAngle,orbit:true};
}
});
renderer.domElement.addEventListener('pointermove',function(e){
if(!gesture||e.pointerId!==gesture.id)return;
e.preventDefault();
if(gesture.orbit){
desiredAngle=clamp(gesture.angle+(e.clientX-gesture.x)*.0055,-.72,.85);
return;
}
const distance=Math.hypot(e.clientX-gesture.x,e.clientY-gesture.y);
if(!gesture.dragging&&distance>5){gesture.dragging=true;beginGrab(gesture.point,false);}
if(gesture.dragging&&grab){
setRay(e);
if(raycaster.ray.intersectPlane(dragPlane,rayPoint)){
movement.copy(rayPoint).sub(grab.origin);
if(movement.length()>.87)movement.setLength(.87);
grab.desired.copy(grab.origin).add(movement);
grab.desired.y=Math.max(BASE+.12,grab.desired.y);
}
}
});
function releasePointer(e){
if(!gesture||e.pointerId!==gesture.id)return;
if(gesture.dragging){grab=null;ringLife=.35;setNote('And… let it find its happy place.',3);}
gesture=null;
if(renderer.domElement.hasPointerCapture(e.pointerId))renderer.domElement.releasePointerCapture(e.pointerId);
}
renderer.domElement.addEventListener('pointerup',releasePointer);
renderer.domElement.addEventListener('pointercancel',releasePointer);
renderer.domElement.addEventListener('lostpointercapture',function(){if(gesture){gesture=null;grab=null;}});
renderer.domElement.addEventListener('keydown',function(e){
if(e.key===' '||e.key==='Enter'){
e.preventDefault();stopDemo();
poke(new THREE.Vector3(.15,BASE+1.2,.27),new THREE.Vector3(0,-.15,-1).normalize(),2);
}
});
// The demo moves only external grab/press constraints. The very same
// solver, contacts and release dynamics handle both demo and real input.
function updateDemo(dt){
if(!demoActive)return;
demoTime+=dt;
if(demoTime>=20){
demoTime-=20;lastDemoTime=-.001;resetAll(true);
}
const t=demoTime;
function crossed(value){return lastDemoTime<value&&t>=value;}
if(crossed(1.3)){
poke(new THREE.Vector3(-.53,BASE+1.08,.27),new THREE.Vector3(.1,-.15,-1).normalize(),2.6);
setNote('First, a friendly little poke.',2.2);
}
if(crossed(3.5)){
beginGrab(new THREE.Vector3(.5,BASE+1.35,.27),true);
setNote('Pull a little. Let it stretch.',3);
}
if(t>=3.5&&t<6.5&&grab&&grab.demo){
const u=(t-3.5)/3;
grab.desired.copy(grab.origin).add(new THREE.Vector3(.43*Math.sin(u*Math.PI*.77),.47*Math.sin(u*Math.PI*.77),.16*Math.sin(u*Math.PI)));
}
if(crossed(6.5)){grab=null;ringLife=.4;setNote('Let go. The wiggle is all its own.',2);}
if(crossed(8.1)){setFirmness(13);setNote('A softer slice, an extra little jiggle.',2.5);}
if(crossed(8.7))poke(new THREE.Vector3(-.4,BASE+1.2,.27),new THREE.Vector3(.1,-.1,-1).normalize(),2.3);
if(crossed(10.5))squeeze();
if(crossed(14.2)){setFirmness(87);setNote('Or a firmer, bouncier bite.',2.5);}
if(crossed(14.8))poke(new THREE.Vector3(.35,BASE+1.22,.27),new THREE.Vector3(0,-.2,-1).normalize(),2.7);
if(crossed(16.5)){
beginGrab(new THREE.Vector3(-.55,BASE+1.2,.27),true);
}
if(t>=16.5&&t<18&&grab&&grab.demo){
const u=(t-16.5)/1.5;
grab.desired.copy(grab.origin).add(new THREE.Vector3(-.28*Math.sin(u*Math.PI*.7),.35*Math.sin(u*Math.PI*.7),.1));
}
if(crossed(18)){grab=null;ringLife=.3;}
if(crossed(19.5)){resetAll(true);setNote('Fresh as new. Again?',2);}
lastDemoTime=t;
}
for(let i=0;i<35;i++)body.step(STEP);
updateSkins();
scene.updateMatrixWorld(true);
renderer.render(scene,camera);
$('loading').hidden=true;
slider.disabled=false;squeezeButton.disabled=false;resetButton.disabled=false;demoButton.disabled=false;
if(location.hash.toLowerCase()==='#demo')startDemo();
window.addEventListener('hashchange',function(){if(location.hash.toLowerCase()==='#demo')startDemo();else stopDemo();});
document.addEventListener('visibilitychange',function(){
if(document.hidden){grab=null;gesture=null;}
});
let last=performance.now(),accumulator=0;
function frame(now){
requestAnimationFrame(frame);
let dt=Math.min((now-last)/1000,.04);last=now;
if(document.hidden)return;
elapsed+=dt;
updateDemo(dt);
updateSqueeze(dt);
accumulator+=dt;
let steps=0;
while(accumulator>=STEP&&steps<4){body.step(STEP);accumulator-=STEP;steps++;}
if(steps===4)accumulator=Math.min(accumulator,STEP);
viewAngle=lerp(viewAngle,desiredAngle,1-Math.exp(-9*dt));
updateCamera();
updateSkins();
updateDrops(dt);
if(grab){
ring.position.copy(grab.target);ring.quaternion.copy(camera.quaternion);
ring.material.opacity=.6;ring.scale.setScalar(.8);ring.visible=true;
}else if(ringLife>0){
ringLife-=dt;ring.visible=true;ring.quaternion.copy(camera.quaternion);
ring.material.opacity=clamp(ringLife*1.2,0,.7);ring.scale.setScalar(1+(1-ringLife/.55)*.6);
}else ring.visible=false;
const level=clamp(energy*2.2,0,1);
for(let i=0;i<meterBars.length;i++){
const amount=.22+level*(.42+.28*Math.sin(elapsed*13+i*2));
meterBars[i].style.transform='scaleY('+amount+')';
meterBars[i].style.background=grab||pressure>.02||energy>.12?'#df8a45':'#b2a183';
}
$('status-text').textContent=grab?'A LITTLE STRETCH':pressure>.02?'FRESHLY SQUEEZING':energy>.12?'HAPPY LITTLE WOBBLES':'RESTING HAPPILY';
if(noteUntil>0&&elapsed>noteUntil){$('note').textContent='Good things come with a little give.';noteUntil=0;}
renderer.render(scene,camera);
}
requestAnimationFrame(frame);
}catch(error){
const loading=$('loading');
loading.hidden=false;
loading.replaceChildren();
const message=document.createElement('span');
message.textContent='This little slice needs WebGL and a connection to load its 3D library. Please reload when both are available.';
message.style.maxWidth='280px';message.style.lineHeight='1.7';
loading.append(message);
$('status-text').textContent='3D COULD NOT START';
console.error('Softslice initialization:',error);
}
</script>
</body>
</html>
