Back to the app
The code
Jelly Cat by Gemini 4 Argon
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.0, maximum-scale=1.0, user-scalable=no">
<title>Orange Jelly Cat</title>
<style>
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
user-select: none;
-webkit-user-select: none;
}
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: radial-gradient(circle at 50% 35%, #fff7ea 0%, #fde5c8 55%, #f3cba5 100%);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
touch-action: none;
}
#canvas-container {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
touch-action: none;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
/* Top status / hint pill */
.top-bar {
position: fixed;
top: 14px;
left: 50%;
transform: translateX(-50%);
z-index: 10;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
pointer-events: none;
width: 92%;
max-width: 520px;
}
.hint-pill {
background: rgba(255, 250, 242, 0.86);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1.5px solid rgba(255, 152, 56, 0.32);
box-shadow: 0 6px 20px rgba(175, 88, 18, 0.12);
color: #7c3a0b;
padding: 9px 18px;
border-radius: 999px;
font-size: 14px;
font-weight: 600;
letter-spacing: 0.01em;
text-align: center;
transition: transform 0.25s ease, background-color 0.25s ease;
}
.status-toast {
background: linear-gradient(135deg, #ff881b, #ff5e00);
color: #fff;
padding: 6px 16px;
border-radius: 999px;
font-size: 13px;
font-weight: 700;
box-shadow: 0 4px 14px rgba(255, 102, 0, 0.32);
opacity: 0;
transform: translateY(-6px) scale(0.95);
transition: opacity 0.2s ease, transform 0.2s ease;
}
.status-toast.visible {
opacity: 1;
transform: translateY(0) scale(1);
}
/* Bottom Control Dock */
.bottom-dock {
position: fixed;
bottom: 18px;
left: 50%;
transform: translateX(-50%);
z-index: 10;
width: 94%;
max-width: 540px;
background: rgba(255, 250, 244, 0.9);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
border: 1.5px solid rgba(255, 155, 65, 0.35);
border-radius: 26px;
padding: 14px 18px;
box-shadow: 0 12px 34px rgba(155, 72, 12, 0.16), inset 0 1px 0 rgba(255, 255, 255, 0.8);
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 14px;
}
.drop-btn {
flex: 0 0 auto;
min-height: 54px;
padding: 0 22px;
border: none;
border-radius: 18px;
background: linear-gradient(180deg, #ff9a2e 0%, #ff6a00 100%);
color: #ffffff;
font-size: 16px;
font-weight: 800;
letter-spacing: 0.02em;
cursor: pointer;
box-shadow: 0 6px 16px rgba(255, 106, 0, 0.35), inset 0 2px 1px rgba(255, 255, 255, 0.45);
display: inline-flex;
align-items: center;
justify-content: center;
gap: 9px;
transition: transform 0.12s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.12s ease;
touch-action: manipulation;
}
.drop-btn:active {
transform: scale(0.94) translateY(2px);
box-shadow: 0 3px 8px rgba(255, 106, 0, 0.28);
}
.drop-btn svg {
width: 20px;
height: 20px;
fill: currentColor;
}
.slider-group {
flex: 1 1 220px;
display: flex;
flex-direction: column;
gap: 6px;
min-width: 200px;
}
.slider-labels {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
font-weight: 700;
color: #824010;
padding: 0 2px;
}
.slider-labels span.end-label {
display: inline-flex;
align-items: center;
gap: 4px;
cursor: pointer;
padding: 2px 4px;
border-radius: 6px;
}
.slider-labels span.mode-badge {
font-size: 11.5px;
font-weight: 800;
color: #d95600;
background: rgba(255, 136, 27, 0.16);
padding: 2px 9px;
border-radius: 999px;
}
.slider-wrap {
position: relative;
height: 36px;
display: flex;
align-items: center;
}
input[type="range"].jelly-slider {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 14px;
border-radius: 999px;
background: linear-gradient(90deg, #ffd180 0%, #ff9124 50%, #e65100 100%);
outline: none;
box-shadow: inset 0 2px 4px rgba(130, 55, 0, 0.25);
margin: 0;
cursor: pointer;
touch-action: pan-x;
}
input[type="range"].jelly-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 32px;
height: 32px;
border-radius: 50%;
background: radial-gradient(circle at 35% 35%, #fffdf9 0%, #ffe0b2 65%, #ffb74d 100%);
border: 3px solid #ff6f00;
box-shadow: 0 3px 10px rgba(180, 70, 0, 0.35);
cursor: pointer;
transition: transform 0.12s ease;
}
input[type="range"].jelly-slider::-webkit-slider-thumb:active {
transform: scale(1.14);
}
input[type="range"].jelly-slider::-moz-range-thumb {
width: 32px;
height: 32px;
border-radius: 50%;
background: radial-gradient(circle at 35% 35%, #fffdf9 0%, #ffe0b2 65%, #ffb74d 100%);
border: 3px solid #ff6f00;
box-shadow: 0 3px 10px rgba(180, 70, 0, 0.35);
cursor: pointer;
}
/* Virtual finger indicator for #demo mode */
#demo-pointer {
position: fixed;
width: 44px;
height: 44px;
margin-left: -22px;
margin-top: -22px;
border-radius: 50%;
background: radial-gradient(circle, rgba(255, 255, 255, 0.92) 0%, rgba(255, 152, 48, 0.65) 60%, rgba(255, 110, 0, 0) 100%);
border: 2.5px solid rgba(255, 255, 255, 0.95);
box-shadow: 0 4px 16px rgba(255, 102, 0, 0.45);
pointer-events: none;
z-index: 25;
display: none;
transition: transform 0.1s ease;
}
#demo-pointer.pressing {
transform: scale(0.82);
background: radial-gradient(circle, rgba(255, 255, 255, 1) 0%, rgba(255, 115, 0, 0.85) 65%, rgba(255, 90, 0, 0) 100%);
}
@media (max-width: 480px) {
.bottom-dock {
padding: 12px 14px;
bottom: 12px;
gap: 10px;
}
.drop-btn {
width: 100%;
min-height: 50px;
}
.hint-pill {
font-size: 12.5px;
padding: 7px 14px;
}
}
</style>
</head>
<body>
<div id="canvas-container"></div>
<div class="top-bar">
<div class="hint-pill" id="hint-pill">Poke, squeeze & pull ears, cheeks or tail • Rub head to purr</div>
<div class="status-toast" id="status-toast">Purring... ♪</div>
</div>
<div id="demo-pointer"></div>
<div class="bottom-dock" id="bottom-dock">
<button class="drop-btn" id="drop-btn" type="button" aria-label="Drop jelly cat from above">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M11 3h2v11.17l3.59-3.58L18 12l-6 6-6-6 1.41-1.41L11 14.17V3zm-6 16h14v2H5v-2z"/>
</svg>
<span>Drop Cat!</span>
</button>
<div class="slider-group">
<div class="slider-labels">
<span class="end-label" id="lbl-pudding">🍮 Soft Pudding</span>
<span class="mode-badge" id="firmness-badge">Silky Jelly</span>
<span class="end-label" id="lbl-gummy">Firm Gummy 🍬</span>
</div>
<div class="slider-wrap">
<input type="range" id="firmness-slider" class="jelly-slider" min="0" max="1" step="0.01" value="0.38" aria-label="Jelly firmness from soft pudding to firm gummy">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function() {
'use strict';
// Safe storage helper per Rule 3
function safeSaveFirmness(val) {
try {
window.localStorage.setItem('jellyCatFirmness', String(val));
} catch (e) {}
}
function safeLoadFirmness(fallback) {
try {
const v = window.localStorage.getItem('jellyCatFirmness');
if (v !== null && !isNaN(parseFloat(v))) {
return Math.max(0, Math.min(1, parseFloat(v)));
}
} catch (e) {}
return fallback;
}
// =========================================================================
// 1. PROCEDURAL WET JELLY & PURR WEB AUDIO SYNTHESIZER
// =========================================================================
class JellySoundEngine {
constructor() {
this.ctx = null;
this.master = null;
this.noiseBuffer = null;
this.purrGain = null;
this.purrOsc1 = null;
this.purrOsc2 = null;
this.purrFilter = null;
this.purrPhase = 0;
this.lastStretchGrainTime = 0;
this.lastBubbleTime = 0;
}
init() {
if (this.ctx) {
if (this.ctx.state === 'suspended') {
this.ctx.resume().catch(() => {});
}
return true;
}
try {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (!AudioCtx) return false;
this.ctx = new AudioCtx();
this.master = this.ctx.createGain();
this.master.gain.value = 0.55;
this.master.connect(this.ctx.destination);
// Precompute pink/wet noise buffer (1.5 sec)
const sr = this.ctx.sampleRate;
const len = Math.floor(sr * 1.5);
this.noiseBuffer = this.ctx.createBuffer(1, len, sr);
const data = this.noiseBuffer.getChannelData(0);
let b0 = 0, b1 = 0, b2 = 0;
for (let i = 0; i < len; i++) {
const white = Math.random() * 2 - 1;
b0 = 0.99 * b0 + white * 0.12;
b1 = 0.96 * b1 + white * 0.18;
b2 = 0.85 * b2 + white * 0.35;
data[i] = (b0 + b1 + b2) * 0.5;
}
// Continuous purr chain (starts muted)
this.purrOsc1 = this.ctx.createOscillator();
this.purrOsc2 = this.ctx.createOscillator();
this.purrOsc1.type = 'sawtooth';
this.purrOsc2.type = 'triangle';
this.purrOsc1.frequency.value = 25.5;
this.purrOsc2.frequency.value = 51.0;
this.purrFilter = this.ctx.createBiquadFilter();
this.purrFilter.type = 'bandpass';
this.purrFilter.frequency.value = 210;
this.purrFilter.Q.value = 3.2;
this.purrGain = this.ctx.createGain();
this.purrGain.gain.value = 0.0001;
this.purrOsc1.connect(this.purrFilter);
this.purrOsc2.connect(this.purrFilter);
this.purrFilter.connect(this.purrGain);
this.purrGain.connect(this.master);
this.purrOsc1.start();
this.purrOsc2.start();
return true;
} catch (e) {
return false;
}
}
// Small wet poke / squish sound
playPoke(intensity, firmness) {
if (!this.init() || !this.ctx) return;
const now = this.ctx.currentTime;
const str = Math.max(0.15, Math.min(1.0, intensity));
const baseFreq = 165 + firmness * 130;
// 1. Wet pitch-swept droplet sine
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(baseFreq * 0.95, now);
osc.frequency.exponentialRampToValueAtTime(baseFreq * (2.2 + str * 0.6), now + 0.045);
osc.frequency.exponentialRampToValueAtTime(baseFreq * 1.15, now + 0.13);
gain.gain.setValueAtTime(0.001, now);
gain.gain.linearRampToValueAtTime(0.22 * str, now + 0.014);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.14);
osc.connect(gain);
gain.connect(this.master);
osc.start(now);
osc.stop(now + 0.15);
// 2. Wet resonant squelch noise burst
if (this.noiseBuffer) {
const noise = this.ctx.createBufferSource();
noise.buffer = this.noiseBuffer;
const bp = this.ctx.createBiquadFilter();
bp.type = 'bandpass';
bp.Q.value = 7.5;
bp.frequency.setValueAtTime(340 + firmness * 180, now);
bp.frequency.exponentialRampToValueAtTime(1150 + firmness * 450, now + 0.055);
bp.frequency.exponentialRampToValueAtTime(420, now + 0.12);
const ng = this.ctx.createGain();
ng.gain.setValueAtTime(0.001, now);
ng.gain.linearRampToValueAtTime(0.28 * str, now + 0.015);
ng.gain.exponentialRampToValueAtTime(0.001, now + 0.125);
noise.connect(bp);
bp.connect(ng);
ng.connect(this.master);
noise.start(now, Math.random() * 0.8, 0.14);
}
// 3. Tiny secondary wet micro-bubble pop
this.playMicroBubble(now + 0.04, 0.11 * str, firmness);
}
playMicroBubble(startTime, vol, firmness) {
if (!this.ctx) return;
const osc = this.ctx.createOscillator();
const g = this.ctx.createGain();
const f0 = 620 + Math.random() * 380 + firmness * 260;
osc.type = 'sine';
osc.frequency.setValueAtTime(f0, startTime);
osc.frequency.exponentialRampToValueAtTime(f0 * 2.15, startTime + 0.032);
g.gain.setValueAtTime(0.0005, startTime);
g.gain.linearRampToValueAtTime(vol, startTime + 0.006);
g.gain.exponentialRampToValueAtTime(0.0005, startTime + 0.036);
osc.connect(g);
g.connect(this.master);
osc.start(startTime);
osc.stop(startTime + 0.04);
}
// Wet elastic stretch sound while pulling ear, cheek, or tail
playStretchGrain(stretchAmount, firmness) {
if (!this.init() || !this.ctx) return;
const now = this.ctx.currentTime;
if (now - this.lastStretchGrainTime < 0.075) return;
this.lastStretchGrainTime = now;
const s = Math.min(1.0, stretchAmount);
const f = 240 + s * 280 + firmness * 170 + (Math.random() - 0.5) * 50;
const osc = this.ctx.createOscillator();
const g = this.ctx.createGain();
osc.type = 'triangle';
osc.frequency.setValueAtTime(f, now);
osc.frequency.exponentialRampToValueAtTime(f * 1.45, now + 0.045);
const lp = this.ctx.createBiquadFilter();
lp.type = 'bandpass';
lp.frequency.value = f * 1.3;
lp.Q.value = 5.0;
g.gain.setValueAtTime(0.001, now);
g.gain.linearRampToValueAtTime(0.095 * (0.4 + 0.6 * s), now + 0.01);
g.gain.exponentialRampToValueAtTime(0.001, now + 0.055);
osc.connect(lp);
lp.connect(g);
g.connect(this.master);
osc.start(now);
osc.stop(now + 0.06);
}
// Damped jelly wobble sound when released from a stretch or squeeze
playWobbleRelease(amplitude, firmness) {
if (!this.init() || !this.ctx) return;
const now = this.ctx.currentTime;
const amp = Math.max(0.15, Math.min(1.0, amplitude));
const dur = 0.45 + (1.0 - firmness) * 0.45;
const wobbleRate = 6.2 + firmness * 6.5;
const carrierBase = 135 + firmness * 105;
const carrier = this.ctx.createOscillator();
const lfo = this.ctx.createOscillator();
const lfoGain = this.ctx.createGain();
const filter = this.ctx.createBiquadFilter();
const env = this.ctx.createGain();
carrier.type = 'triangle';
carrier.frequency.setValueAtTime(carrierBase * 1.25, now);
carrier.frequency.exponentialRampToValueAtTime(carrierBase, now + dur);
lfo.type = 'sine';
lfo.frequency.setValueAtTime(wobbleRate, now);
lfoGain.gain.setValueAtTime(65 * amp, now);
lfoGain.gain.exponentialRampToValueAtTime(4, now + dur);
filter.type = 'lowpass';
filter.Q.value = 6.0;
filter.frequency.setValueAtTime(520 + firmness * 350, now);
filter.frequency.exponentialRampToValueAtTime(190, now + dur);
env.gain.setValueAtTime(0.001, now);
env.gain.linearRampToValueAtTime(0.24 * amp, now + 0.018);
env.gain.exponentialRampToValueAtTime(0.001, now + dur);
lfo.connect(lfoGain);
lfoGain.connect(carrier.frequency);
lfoGain.connect(filter.frequency);
carrier.connect(filter);
filter.connect(env);
env.connect(this.master);
carrier.start(now);
lfo.start(now);
carrier.stop(now + dur + 0.02);
lfo.stop(now + dur + 0.02);
// Add a couple of wet droplet pops
this.playMicroBubble(now + 0.015, 0.14 * amp, firmness);
this.playMicroBubble(now + 0.075, 0.10 * amp, firmness);
}
// Whoosh sound when dropped from above
playDropLaunch() {
if (!this.init() || !this.ctx) return;
const now = this.ctx.currentTime;
const osc = this.ctx.createOscillator();
const g = this.ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(340, now);
osc.frequency.exponentialRampToValueAtTime(155, now + 0.25);
g.gain.setValueAtTime(0.001, now);
g.gain.linearRampToValueAtTime(0.11, now + 0.04);
g.gain.exponentialRampToValueAtTime(0.001, now + 0.26);
osc.connect(g);
g.connect(this.master);
osc.start(now);
osc.stop(now + 0.28);
}
// Juicy wet splat + big wobble on landing from a drop
playDropImpact(firmness) {
if (!this.init() || !this.ctx) return;
const now = this.ctx.currentTime;
// 1. Soft thud + wet bounce body
const sub = this.ctx.createOscillator();
const subG = this.ctx.createGain();
sub.type = 'sine';
sub.frequency.setValueAtTime(125 + firmness * 55, now);
sub.frequency.exponentialRampToValueAtTime(48 + firmness * 25, now + 0.18);
subG.gain.setValueAtTime(0.001, now);
subG.gain.linearRampToValueAtTime(0.38, now + 0.012);
subG.gain.exponentialRampToValueAtTime(0.001, now + 0.21);
sub.connect(subG);
subG.connect(this.master);
sub.start(now);
sub.stop(now + 0.22);
// 2. Wet splat filter sweep
if (this.noiseBuffer) {
const noise = this.ctx.createBufferSource();
noise.buffer = this.noiseBuffer;
const bp = this.ctx.createBiquadFilter();
bp.type = 'bandpass';
bp.Q.value = 6.5;
bp.frequency.setValueAtTime(260, now);
bp.frequency.exponentialRampToValueAtTime(1450 + firmness * 400, now + 0.05);
bp.frequency.exponentialRampToValueAtTime(320, now + 0.22);
const ng = this.ctx.createGain();
ng.gain.setValueAtTime(0.001, now);
ng.gain.linearRampToValueAtTime(0.36, now + 0.015);
ng.gain.exponentialRampToValueAtTime(0.001, now + 0.24);
noise.connect(bp);
bp.connect(ng);
ng.connect(this.master);
noise.start(now, 0.1, 0.25);
}
// 3. Cluster of wet bubble blips
for (let i = 0; i < 4; i++) {
this.playMicroBubble(now + 0.02 + i * 0.038, 0.14 - i * 0.025, firmness);
}
// 4. Long resonant wobble tail
this.playWobbleRelease(1.0, firmness);
}
// Update continuous purr + gentle wet purr bubbles
updatePurr(purrAmount, dt, firmness) {
if (!this.ctx || !this.purrGain) return;
const now = this.ctx.currentTime;
this.purrPhase += dt * 4.5;
const breath = 0.72 + 0.28 * Math.sin(this.purrPhase);
const targetGain = purrAmount > 0.04 ? (purrAmount * 0.26 * breath) : 0.0001;
this.purrGain.gain.setTargetAtTime(targetGain, now, 0.06);
const pitchShift = 24.5 + firmness * 4.0 + 1.8 * Math.sin(this.purrPhase * 0.8);
this.purrOsc1.frequency.setTargetAtTime(pitchShift, now, 0.05);
this.purrOsc2.frequency.setTargetAtTime(pitchShift * 2.02, now, 0.05);
this.purrFilter.frequency.setTargetAtTime(185 + 75 * breath + firmness * 45, now, 0.06);
if (purrAmount > 0.35 && now - this.lastBubbleTime > 0.22) {
this.lastBubbleTime = now;
if (Math.random() < 0.65) {
this.playMicroBubble(now + 0.01, 0.045 * purrAmount, firmness);
}
}
}
}
const sound = new JellySoundEngine();
// =========================================================================
// 2. SMOOTH CHUBBY SITTING CAT SIGNED DISTANCE FIELD (SDF)
// =========================================================================
function smin(a, b, k) {
const h = Math.max(k - Math.abs(a - b), 0.0) / k;
return Math.min(a, b) - h * h * k * 0.25;
}
function smax(a, b, k) {
return -smin(-a, -b, k);
}
function sdSphere(x, y, z, cx, cy, cz, r) {
const dx = x - cx, dy = y - cy, dz = z - cz;
return Math.sqrt(dx * dx + dy * dy + dz * dz) - r;
}
function sdEllipsoid(x, y, z, cx, cy, cz, rx, ry, rz) {
const dx = (x - cx) / rx, dy = (y - cy) / ry, dz = (z - cz) / rz;
const k0 = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (k0 < 1e-6) return -Math.min(rx, ry, rz);
const dx2 = dx / rx, dy2 = dy / ry, dz2 = dz / rz;
const k1 = Math.sqrt(dx2 * dx2 + dy2 * dy2 + dz2 * dz2);
return k0 * (k0 - 1.0) / k1;
}
function sdRoundCone(x, y, z, ax, ay, az, bx, by, bz, r1, r2) {
const bax = bx - ax, bay = by - ay, baz = bz - az;
const l2 = bax * bax + bay * bay + baz * baz;
const pax = x - ax, pay = y - ay, paz = z - az;
let h = (pax * bax + pay * bay + paz * baz) / l2;
if (h < 0.0) h = 0.0;
else if (h > 1.0) h = 1.0;
const dx = pax - bax * h, dy = pay - bay * h, dz = paz - baz * h;
const r = r1 + (r2 - r1) * h;
return Math.sqrt(dx * dx + dy * dy + dz * dz) - r;
}
function evalCatSDF(x, y, z) {
const ax = Math.abs(x);
// 1. Plump sitting lower belly & upper torso
const belly = sdEllipsoid(x, y, z, 0.0, 0.65, -0.02, 0.85, 0.67, 0.78);
const chest = sdEllipsoid(x, y, z, 0.0, 1.12, 0.05, 0.65, 0.50, 0.60);
let d = smin(belly, chest, 0.26);
// 2. Chubby sitting hind haunches & hind paws
const haunch = sdEllipsoid(ax, y, z, 0.56, 0.42, -0.06, 0.40, 0.39, 0.46);
d = smin(d, haunch, 0.20);
const hindPaw = sdEllipsoid(ax, y, z, 0.58, 0.14, 0.36, 0.21, 0.14, 0.25);
d = smin(d, hindPaw, 0.14);
// 3. Chubby front legs & paws resting in front
const frontLeg = sdRoundCone(ax, y, z, 0.32, 0.88, 0.34, 0.35, 0.17, 0.55, 0.22, 0.19);
const frontPaw = sdEllipsoid(ax, y, z, 0.35, 0.13, 0.64, 0.21, 0.13, 0.22);
d = smin(d, smin(frontLeg, frontPaw, 0.12), 0.16);
// 4. Round head, signature chubby cheeks, and cute muzzle pads
const head = sdEllipsoid(x, y, z, 0.0, 1.72, 0.10, 0.73, 0.64, 0.67);
const cheek = sdEllipsoid(ax, y, z, 0.47, 1.54, 0.28, 0.35, 0.29, 0.33);
const headWithCheeks = smin(head, cheek, 0.24);
const muzzle = sdSphere(ax, y, z, 0.13, 1.54, 0.68, 0.16);
const fullHead = smin(headWithCheeks, muzzle, 0.11);
// 5. Pointy cat ears
const ear = sdRoundCone(ax, y, z, 0.36, 2.12, 0.07, 0.63, 2.63, 0.10, 0.26, 0.075);
const headAndEars = smin(fullHead, ear, 0.13);
d = smin(d, headAndEars, 0.20);
// 6. Plump curled tail wrapping around the right side
const tail1 = sdRoundCone(x, y, z, 0.0, 0.24, -0.70, 0.48, 0.28, -0.90, 0.20, 0.18);
const tail2 = sdRoundCone(x, y, z, 0.48, 0.28, -0.90, 0.85, 0.56, -0.70, 0.18, 0.18);
const tail3 = sdRoundCone(x, y, z, 0.85, 0.56, -0.70, 0.96, 0.96, -0.32, 0.18, 0.20);
const tail = smin(smin(tail1, tail2, 0.12), tail3, 0.12);
d = smin(d, tail, 0.16);
// 7. Softly flattened base resting on the plate at y = 0
d = smax(d, -y, 0.09);
return d;
}
function getSDFGradient(x, y, z) {
const e = 0.0025;
const gx = evalCatSDF(x + e, y, z) - evalCatSDF(x - e, y, z);
const gy = evalCatSDF(x, y + e, z) - evalCatSDF(x, y - e, z);
const gz = evalCatSDF(x, y, z + e) - evalCatSDF(x, y, z - e);
const len = Math.sqrt(gx * gx + gy * gy + gz * gz) || 1.0;
return [gx / len, gy / len, gz / len];
}
// Project any 3D point onto the exact SDF = offset surface
function projectToCatSurface(x, y, z, surfaceOffset, iterations) {
let px = x, py = y, pz = z;
for (let i = 0; i < iterations; i++) {
const d = evalCatSDF(px, py, pz) - surfaceOffset;
const g = getSDFGradient(px, py, pz);
px -= d * g[0];
py -= d * g[1];
pz -= d * g[2];
}
return [px, py, pz];
}
// =========================================================================
// 3. WATERTIGHT SURFACE NETS MESH GENERATOR (ZERO INTERNAL SEAMS)
// =========================================================================
function buildJellyCatGeometry() {
const Nx = 52, Ny = 58, Nz = 48;
const minX = -1.30, maxX = 1.40;
const minY = -0.15, maxY = 2.85;
const minZ = -1.25, maxZ = 1.10;
const dx = (maxX - minX) / Nx;
const dy = (maxY - minY) / Ny;
const dz = (maxZ - minZ) / Nz;
const strideY = Nx + 1;
const strideZ = (Nx + 1) * (Ny + 1);
const sdfGrid = new Float32Array((Nx + 1) * (Ny + 1) * (Nz + 1));
for (let k = 0; k <= Nz; k++) {
const z = minZ + k * dz;
for (let j = 0; j <= Ny; j++) {
const y = minY + j * dy;
let idx = k * strideZ + j * strideY;
for (let i = 0; i <= Nx; i++) {
const x = minX + i * dx;
sdfGrid[idx++] = evalCatSDF(x, y, z);
}
}
}
const cellStrideY = Nx;
const cellStrideZ = Nx * Ny;
const cellToVert = new Int32Array(Nx * Ny * Nz);
cellToVert.fill(-1);
const positions = [];
const cubeEdges = [
[0,0,0, 1,0,0], [0,1,0, 1,1,0], [0,0,1, 1,0,1], [0,1,1, 1,1,1],
[0,0,0, 0,1,0], [1,0,0, 1,1,0], [0,0,1, 0,1,1], [1,0,1, 1,1,1],
[0,0,0, 0,0,1], [1,0,0, 1,0,1], [0,1,0, 0,1,1], [1,1,0, 1,1,1]
];
for (let k = 0; k < Nz; k++) {
for (let j = 0; j < Ny; j++) {
for (let i = 0; i < Nx; i++) {
let mask = 0;
for (let dz0 = 0; dz0 < 2; dz0++) {
for (let dy0 = 0; dy0 < 2; dy0++) {
for (let dx0 = 0; dx0 < 2; dx0++) {
const val = sdfGrid[(k + dz0) * strideZ + (j + dy0) * strideY + (i + dx0)];
if (val < 0) mask |= (1 << (dx0 + dy0 * 2 + dz0 * 4));
}
}
}
if (mask === 0 || mask === 255) continue;
let sx = 0, sy = 0, sz = 0, count = 0;
for (let e = 0; e < 12; e++) {
const edge = cubeEdges[e];
const i0 = i + edge[0], j0 = j + edge[1], k0 = k + edge[2];
const i1 = i + edge[3], j1 = j + edge[4], k1 = k + edge[5];
const v0 = sdfGrid[k0 * strideZ + j0 * strideY + i0];
const v1 = sdfGrid[k1 * strideZ + j1 * strideY + i1];
if ((v0 < 0) !== (v1 < 0)) {
const t = v0 / (v0 - v1);
sx += minX + (i0 + (i1 - i0) * t) * dx;
sy += minY + (j0 + (j1 - j0) * t) * dy;
sz += minZ + (k0 + (k1 - k0) * t) * dz;
count++;
}
}
if (count > 0) {
const vIdx = positions.length / 3;
cellToVert[k * cellStrideZ + j * cellStrideY + i] = vIdx;
positions.push(sx / count, sy / count, sz / count);
}
}
}
}
const indices = [];
function emitQuad(c0, c1, c2, c3) {
if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0) return;
indices.push(c0, c1, c2, c0, c2, c3);
}
for (let k = 1; k < Nz; k++) {
for (let j = 1; j < Ny; j++) {
for (let i = 1; i < Nx; i++) {
const v000 = sdfGrid[k * strideZ + j * strideY + i];
// X-axis edge from (i,j,k) to (i+1,j,k)
const v100 = sdfGrid[k * strideZ + j * strideY + (i + 1)];
if ((v000 < 0) !== (v100 < 0)) {
const c0 = cellToVert[(k - 1) * cellStrideZ + (j - 1) * cellStrideY + i];
const c1 = cellToVert[(k - 1) * cellStrideZ + j * cellStrideY + i];
const c2 = cellToVert[k * cellStrideZ + j * cellStrideY + i];
const c3 = cellToVert[k * cellStrideZ + (j - 1) * cellStrideY + i];
emitQuad(c0, c1, c2, c3);
}
// Y-axis edge from (i,j,k) to (i,j+1,k)
const v010 = sdfGrid[k * strideZ + (j + 1) * strideY + i];
if ((v000 < 0) !== (v010 < 0)) {
const c0 = cellToVert[(k - 1) * cellStrideZ + j * cellStrideY + (i - 1)];
const c1 = cellToVert[k * cellStrideZ + j * cellStrideY + (i - 1)];
const c2 = cellToVert[k * cellStrideZ + j * cellStrideY + i];
const c3 = cellToVert[(k - 1) * cellStrideZ + j * cellStrideY + i];
emitQuad(c0, c1, c2, c3);
}
// Z-axis edge from (i,j,k) to (i,j,k+1)
const v001 = sdfGrid[(k + 1) * strideZ + j * strideY + i];
if ((v000 < 0) !== (v001 < 0)) {
const c0 = cellToVert[k * cellStrideZ + (j - 1) * cellStrideY + (i - 1)];
const c1 = cellToVert[k * cellStrideZ + (j - 1) * cellStrideY + i];
const c2 = cellToVert[k * cellStrideZ + j * cellStrideY + i];
const c3 = cellToVert[k * cellStrideZ + j * cellStrideY + (i - 1)];
emitQuad(c0, c1, c2, c3);
}
}
}
}
const numVerts = positions.length / 3;
const neighbors = Array.from({ length: numVerts }, () => []);
for (let t = 0; t < indices.length; t += 3) {
const a = indices[t], b = indices[t + 1], c = indices[t + 2];
neighbors[a].push(b, c);
neighbors[b].push(a, c);
neighbors[c].push(a, b);
}
// 4 passes of Laplacian umbrella smoothing + exact SDF zero-isosurface projection
const tempPos = new Float32Array(positions.length);
for (let iter = 0; iter < 4; iter++) {
for (let v = 0; v < numVerts; v++) {
const nb = neighbors[v];
const i3 = v * 3;
if (nb.length === 0) {
tempPos[i3] = positions[i3];
tempPos[i3 + 1] = positions[i3 + 1];
tempPos[i3 + 2] = positions[i3 + 2];
continue;
}
let ax = 0, ay = 0, az = 0;
for (let n = 0; n < nb.length; n++) {
const n3 = nb[n] * 3;
ax += positions[n3];
ay += positions[n3 + 1];
az += positions[n3 + 2];
}
ax /= nb.length;
ay /= nb.length;
az /= nb.length;
let px = positions[i3] * 0.45 + ax * 0.55;
let py = positions[i3 + 1] * 0.45 + ay * 0.55;
let pz = positions[i3 + 2] * 0.45 + az * 0.55;
const d = evalCatSDF(px, py, pz);
const g = getSDFGradient(px, py, pz);
px -= d * g[0] * 0.85;
py -= d * g[1] * 0.85;
pz -= d * g[2] * 0.85;
if (py < 0.0) py = 0.0;
tempPos[i3] = px;
tempPos[i3 + 1] = py;
tempPos[i3 + 2] = pz;
}
for (let i = 0; i < positions.length; i++) {
positions[i] = tempPos[i];
}
}
// Ensure every triangle winding faces strictly outward against SDF gradient
for (let t = 0; t < indices.length; t += 3) {
const a = indices[t], b = indices[t + 1], c = indices[t + 2];
const ax = positions[a * 3], ay = positions[a * 3 + 1], az = positions[a * 3 + 2];
const bx = positions[b * 3], by = positions[b * 3 + 1], bz = positions[b * 3 + 2];
const cx = positions[c * 3], cy = positions[c * 3 + 1], cz = positions[c * 3 + 2];
const ux = bx - ax, uy = by - ay, uz = bz - az;
const vx = cx - ax, vy = cy - ay, vz = cz - az;
const nx = uy * vz - uz * vy;
const ny = uz * vx - ux * vz;
const nz = ux * vy - uy * vx;
const g = getSDFGradient((ax + bx + cx) / 3, (ay + by + cy) / 3, (az + bz + cz) / 3);
if (nx * g[0] + ny * g[1] + nz * g[2] < 0) {
indices[t + 1] = c;
indices[t + 2] = b;
}
}
const geometry = new THREE.BufferGeometry();
const posArray = new Float32Array(positions);
const restArray = new Float32Array(positions);
geometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return { geometry, posArray, restArray, numVerts };
}
// =========================================================================
// 4. COUPLED SOFT-BODY JELLY PHYSICS & KELVINLET DEFORMATION ENGINE
// =========================================================================
const anatomicalNodes = [
{ name: 'leftEar', label: 'Left Ear', x: -0.55, y: 2.45, z: 0.09, r: 0.62, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.35 },
{ name: 'rightEar', label: 'Right Ear', x: 0.55, y: 2.45, z: 0.09, r: 0.62, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.35 },
{ name: 'leftCheek', label: 'Chubby Cheek', x: -0.52, y: 1.54, z: 0.34, r: 0.62, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.15 },
{ name: 'rightCheek', label: 'Chubby Cheek', x: 0.52, y: 1.54, z: 0.34, r: 0.62, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.15 },
{ name: 'headTop', label: 'Head', x: 0.00, y: 2.18, z: 0.16, r: 0.68, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.05 },
{ name: 'snout', label: 'Nose & Chin', x: 0.00, y: 1.54, z: 0.70, r: 0.54, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.20 },
{ name: 'headCore', label: 'Head', x: 0.00, y: 1.72, z: 0.08, r: 0.98, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 0.92 },
{ name: 'bellyFront', label: 'Chubby Belly', x: 0.00, y: 0.72, z: 0.58, r: 0.85, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 0.88 },
{ name: 'bellyLeft', label: 'Chubby Side', x: -0.66, y: 0.68, z: 0.02, r: 0.80, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 0.90 },
{ name: 'bellyRight', label: 'Chubby Side', x: 0.66, y: 0.68, z: 0.02, r: 0.80, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 0.90 },
{ name: 'backCore', label: 'Back', x: 0.00, y: 0.80, z: -0.58, r: 0.78, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 0.92 },
{ name: 'leftPaw', label: 'Left Paw', x: -0.36, y: 0.24, z: 0.64, r: 0.48, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.25 },
{ name: 'rightPaw', label: 'Right Paw', x: 0.36, y: 0.24, z: 0.64, r: 0.48, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.25 },
{ name: 'tailBase', label: 'Tail', x: 0.22, y: 0.28, z: -0.82, r: 0.55, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.10 },
{ name: 'tailMid', label: 'Tail', x: 0.72, y: 0.46, z: -0.80, r: 0.58, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.22 },
{ name: 'tailTip', label: 'Tail Tip', x: 0.96, y: 0.94, z: -0.34, r: 0.62, dx: 0, dy: 0, dz: 0, vx: 0, vy: 0, vz: 0, freqMul: 1.38 }
];
// Neighbor spring links between anatomical nodes
const nodeLinks = [
[0, 4, 0.35], [0, 6, 0.40], [1, 4, 0.35], [1, 6, 0.40],
[2, 5, 0.35], [2, 6, 0.45], [3, 5, 0.35], [3, 6, 0.45],
[4, 6, 0.55], [5, 6, 0.50], [6, 7, 0.35], [6, 10, 0.35],
[7, 8, 0.40], [7, 9, 0.40], [8, 10, 0.40], [9, 10, 0.40],
[13, 10, 0.45], [13, 14, 0.65], [14, 15, 0.72]
];
// Dynamic surface Kelvinlet node for exact finger grab / poke point
const grabKelvinlet = {
active: false,
x: 0, y: 1.2, z: 0.5,
r: 0.58,
dx: 0, dy: 0, dz: 0,
vx: 0, vy: 0, vz: 0
};
// Global whole-body jelly state
const jellyState = {
firmness: safeLoadFirmness(0.38), // 0 = Soft Pudding, 1 = Firm Gummy
dropY: 0.0,
dropVelY: 0.0,
isDropping: false,
squashY: 0.0,
squashVelY: 0.0,
swayX: 0.0,
swayVelX: 0.0,
swayZ: 0.0,
swayVelZ: 0.0,
twistY: 0.0,
twistVelY: 0.0,
gravitySag: 0.0,
purrAmount: 0.0,
rubEnergy: 0.0,
squintAmount: 0.0,
blinkTimer: 2.8,
blinkValue: 0.0,
lookTargetX: 0.0,
lookTargetY: 0.0,
lookX: 0.0,
lookY: 0.0,
time: 0.0
};
// Evaluate 3D deformed position for any rest point (x0, y0, z0)
const _deformOut = [0, 0, 0];
function evaluateDeformedPoint(x0, y0, z0) {
// 1. Base pudding sag + global squash & stretch (volume preserving: sy * sx * sz = 1)
const sag = jellyState.gravitySag;
const totalSquash = Math.max(-0.48, Math.min(0.65, jellyState.squashY - sag));
const hNorm = Math.max(0.0, Math.min(1.0, y0 / 2.65));
// Belly bulges most horizontally around y = 0.65..1.4
const bulgeProfile = Math.sin(Math.min(1.0, y0 / 2.4) * Math.PI) * 0.85 + 0.25;
const sy = 1.0 + totalSquash * (0.35 + 0.65 * hNorm);
const invSqrtSy = 1.0 / Math.sqrt(Math.max(0.38, sy));
const sxz = 1.0 + (invSqrtSy - 1.0) * bulgeProfile * 1.15;
let x = x0 * sxz;
let y = y0 * sy;
let z = z0 * sxz;
// 2. Subtle breathing + purring micro-vibration
const breath = Math.sin(jellyState.time * 2.4) * 0.012 * Math.sin(hNorm * Math.PI);
const purrVib = jellyState.purrAmount > 0.02
? Math.sin(jellyState.time * 52.0 + y0 * 6.0) * 0.011 * jellyState.purrAmount
: 0.0;
x *= (1.0 + breath + purrVib);
z *= (1.0 + breath + purrVib);
// 3. Global horizontal shear sway + head tilt when looking at finger
const swayProfile = Math.pow(hNorm, 1.25);
const headInfluence = Math.max(0.0, (y0 - 1.05) / 1.5);
const lookShiftX = jellyState.lookX * 0.08 * headInfluence;
const lookShiftY = jellyState.lookY * 0.05 * headInfluence;
x += jellyState.swayX * swayProfile + lookShiftX;
z += jellyState.swayZ * swayProfile;
y += lookShiftY - (jellyState.swayX * x0) * 0.18 * swayProfile;
// 4. Torsional Y-axis twist wobble
const twistAngle = jellyState.twistY * swayProfile;
if (Math.abs(twistAngle) > 1e-4) {
const cosT = Math.cos(twistAngle);
const sinT = Math.sin(twistAngle);
const rx = x * cosT - z * sinT;
const rz = x * sinT + z * cosT;
x = rx;
z = rz;
}
// 5. Anatomical soft-body nodes (incompressible Kelvinlet-like radial basis + necking)
for (let i = 0; i < anatomicalNodes.length; i++) {
const n = anatomicalNodes[i];
const ndx = n.dx, ndy = n.dy, ndz = n.dz;
const magSq = ndx * ndx + ndy * ndy + ndz * ndz;
if (magSq < 1e-7) continue;
const rx = x0 - n.x;
const ry = y0 - n.y;
const rz = z0 - n.z;
const distSq = rx * rx + ry * ry + rz * rz;
const rSq = n.r * n.r;
if (distSq > rSq * 2.6) continue;
// Smooth regularized Wendland/Gaussian kernel
const w = Math.exp(-distSq / (rSq * 0.68));
x += ndx * w;
y += ndy * w;
z += ndz * w;
// Incompressible lateral necking perpendicular to stretch vector
const mag = Math.sqrt(magSq);
const dot = (rx * ndx + ry * ndy + rz * ndz) / mag;
const px = rx - (ndx / mag) * dot;
const py = ry - (ndy / mag) * dot;
const pz = rz - (ndz / mag) * dot;
const neck = -0.18 * Math.min(0.65, mag) * w;
x += px * neck;
y += py * neck;
z += pz * neck;
}
// 6. Exact surface grab / poke Kelvinlet deformer
{
const g = grabKelvinlet;
const gdx = g.dx, gdy = g.dy, gdz = g.dz;
const magSq = gdx * gdx + gdy * gdy + gdz * gdz;
if (magSq > 1e-7) {
const rx = x0 - g.x;
const ry = y0 - g.y;
const rz = z0 - g.z;
const epsSq = g.r * g.r * 0.32;
const rEps = Math.sqrt(rx * rx + ry * ry + rz * rz + epsSq);
const eps = Math.sqrt(epsSq);
// Regularized incompressible Kelvinlet kernel
const w1 = (0.67 / rEps + 0.5 * epsSq / (rEps * rEps * rEps)) * eps;
const rDotF = (rx * gdx + ry * gdy + rz * gdz) / (rEps * rEps * rEps) * 0.33 * eps;
const falloff = Math.exp(-(rx * rx + ry * ry + rz * rz) / (g.r * g.r * 1.1));
x += (gdx * w1 + rx * rDotF) * falloff;
y += (gdy * w1 + ry * rDotF) * falloff;
z += (gdz * w1 + rz * rDotF) * falloff;
}
}
// 7. Plate contact floor clamp + vertical drop height
const minPlateY = y0 < 0.08 ? 0.0 : 0.015;
if (y < minPlateY) {
const pushOut = (minPlateY - y) * 0.42;
y = minPlateY;
const rad = Math.sqrt(x * x + z * z) || 1.0;
x += (x / rad) * pushOut;
z += (z / rad) * pushOut;
}
y += jellyState.dropY;
_deformOut[0] = x;
_deformOut[1] = y;
_deformOut[2] = z;
return _deformOut;
}
// Trigger "Drop from Above"
function triggerJellyDrop() {
jellyState.isDropping = true;
jellyState.dropY = 2.85;
jellyState.dropVelY = -1.2;
// Slight stretch while airborne
jellyState.squashY = 0.22;
jellyState.squashVelY = 0.0;
sound.playDropLaunch();
showStatusToast('Big Wobble Drop!');
}
// Physics time-stepping
function stepJellyPhysics(dt, activeDragNodeIdx) {
const subSteps = 3;
const h = Math.min(0.033, dt) / subSteps;
const f = jellyState.firmness; // 0 (Soft Pudding) -> 1 (Firm Gummy)
// Stiffness & damping curves from Soft Pudding to Firm Gummy
const baseOmega = 13.5 + f * 21.0; // angular frequency
const stiffness = baseOmega * baseOmega; // k = w^2
const damping = 2.6 + f * 2.4; // c
// Target static gravity sag (soft pudding sags lower & wider; firm gummy stands perky)
const targetSag = (1.0 - f) * 0.12;
jellyState.gravitySag += (targetSag - jellyState.gravitySag) * Math.min(1.0, dt * 8.0);
for (let step = 0; step < subSteps; step++) {
// 1. Airborne drop physics
if (jellyState.isDropping) {
jellyState.dropVelY -= 26.0 * h;
jellyState.dropY += jellyState.dropVelY * h;
// Elongate slightly as falling speed increases
jellyState.squashY = Math.min(0.32, Math.abs(jellyState.dropVelY) * 0.032);
if (jellyState.dropY <= 0.0) {
jellyState.dropY = 0.0;
const impactSpeed = Math.abs(jellyState.dropVelY);
jellyState.dropVelY = 0.0;
jellyState.isDropping = false;
// Massive pancake squash & stretch impulse + secondary ripples across ears, cheeks, belly & tail
const squashAmp = 0.85 + (1.0 - f) * 0.45;
jellyState.squashY = -0.34 * squashAmp;
jellyState.squashVelY = -impactSpeed * 1.15 * squashAmp;
jellyState.swayVelX += (Math.random() - 0.5) * 3.2;
jellyState.swayVelZ += (Math.random() - 0.5) * 3.2;
jellyState.twistVelY += (Math.random() - 0.5) * 4.5;
// Excite anatomical nodes radially outward on impact
for (let i = 0; i < anatomicalNodes.length; i++) {
const n = anatomicalNodes[i];
n.vy -= (1.8 + n.y * 1.1) * squashAmp;
n.vx += n.x * 2.8 * squashAmp;
n.vz += n.z * 2.8 * squashAmp;
}
sound.playDropImpact(f);
}
}
// 2. Global squash, sway & twist harmonic oscillators
const sqAcc = -stiffness * 0.92 * jellyState.squashY - damping * 0.88 * jellyState.squashVelY;
jellyState.squashVelY += sqAcc * h;
jellyState.squashY += jellyState.squashVelY * h;
const swAccX = -stiffness * 0.75 * jellyState.swayX - damping * 0.82 * jellyState.swayVelX;
const swAccZ = -stiffness * 0.75 * jellyState.swayZ - damping * 0.82 * jellyState.swayVelZ;
jellyState.swayVelX += swAccX * h;
jellyState.swayVelZ += swAccZ * h;
jellyState.swayX += jellyState.swayVelX * h;
jellyState.swayZ += jellyState.swayVelZ * h;
const twAcc = -stiffness * 0.85 * jellyState.twistY - damping * 0.90 * jellyState.twistVelY;
jellyState.twistVelY += twAcc * h;
jellyState.twistY += jellyState.twistVelY * h;
// 3. Neighbor spring coupling forces between anatomical nodes
for (let l = 0; l < nodeLinks.length; l++) {
const ia = nodeLinks[l][0];
const ib = nodeLinks[l][1];
const couple = nodeLinks[l][2] * stiffness * 0.22;
const na = anatomicalNodes[ia];
const nb = anatomicalNodes[ib];
const fx = (nb.dx - na.dx) * couple;
const fy = (nb.dy - na.dy) * couple;
const fz = (nb.dz - na.dz) * couple;
if (ia !== activeDragNodeIdx) {
na.vx += fx * h;
na.vy += fy * h;
na.vz += fz * h;
}
if (ib !== activeDragNodeIdx) {
nb.vx -= fx * h;
nb.vy -= fy * h;
nb.vz -= fz * h;
}
}
// 4. Integrate each anatomical node
for (let i = 0; i < anatomicalNodes.length; i++) {
const n = anatomicalNodes[i];
if (i === activeDragNodeIdx) continue;
const kNode = stiffness * (n.freqMul * n.freqMul);
const cNode = damping * n.freqMul;
const ax = -kNode * n.dx - cNode * n.vx;
const ay = -kNode * n.dy - cNode * n.vy;
const az = -kNode * n.dz - cNode * n.vz;
n.vx += ax * h;
n.vy += ay * h;
n.vz += az * h;
n.dx += n.vx * h;
n.dy += n.vy * h;
n.dz += n.vz * h;
}
// 5. Integrate grab Kelvinlet when released
if (!grabKelvinlet.active) {
const kG = stiffness * 1.35;
const cG = damping * 1.1;
grabKelvinlet.vx += (-kG * grabKelvinlet.dx - cG * grabKelvinlet.vx) * h;
grabKelvinlet.vy += (-kG * grabKelvinlet.dy - cG * grabKelvinlet.vy) * h;
grabKelvinlet.vz += (-kG * grabKelvinlet.dz - cG * grabKelvinlet.vz) * h;
grabKelvinlet.dx += grabKelvinlet.vx * h;
grabKelvinlet.dy += grabKelvinlet.vy * h;
grabKelvinlet.dz += grabKelvinlet.vz * h;
}
}
}
// =========================================================================
// 5. THREE.JS SCENE, PLATE, INTERNAL BUBBLES, EYES & REFRACTIVE JELLY SHADER
// =========================================================================
const container = document.getElementById('canvas-container');
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.1, 40);
function updateCameraFraming() {
const aspect = window.innerWidth / Math.max(1, window.innerHeight);
camera.aspect = aspect;
// Pull camera back slightly on narrow portrait phone screens so the whole plate & drop fit comfortably
const dist = aspect < 0.85 ? 7.6 / Math.max(0.58, aspect * 0.95) : 6.9;
camera.position.set(0.0, 2.35, Math.min(10.2, dist));
camera.lookAt(0.0, 1.15, 0.0);
camera.updateProjectionMatrix();
}
updateCameraFraming();
// Offscreen render target for screen-space jelly refraction & internal bubbles
let rtWidth = Math.floor(window.innerWidth * renderer.getPixelRatio());
let rtHeight = Math.floor(window.innerHeight * renderer.getPixelRatio());
const refractionRT = new THREE.WebGLRenderTarget(rtWidth, rtHeight, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
format: THREE.RGBAFormat
});
// Warm studio lights
const ambLight = new THREE.AmbientLight(0xfff3e2, 0.85);
scene.add(ambLight);
const keyLight = new THREE.DirectionalLight(0xfffaf0, 1.1);
keyLight.position.set(3.5, 6.5, 4.5);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xffb770, 0.65);
rimLight.position.set(-4.0, 4.0, -3.5);
scene.add(rimLight);
// Cozy sunlit tabletop backdrop dome
const bgGeo = new THREE.SphereGeometry(18, 32, 24);
const bgMat = new THREE.ShaderMaterial({
side: THREE.BackSide,
depthWrite: false,
uniforms: {},
vertexShader: `
varying vec3 vWorldPos;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}
`,
fragmentShader: `
varying vec3 vWorldPos;
void main() {
float h = clamp((vWorldPos.y + 3.0) / 14.0, 0.0, 1.0);
vec3 bot = vec3(0.95, 0.78, 0.62);
vec3 mid = vec3(0.99, 0.91, 0.80);
vec3 top = vec3(1.00, 0.97, 0.92);
vec3 col = mix(bot, mid, smoothstep(0.0, 0.45, h));
col = mix(col, top, smoothstep(0.45, 1.0, h));
gl_FragColor = vec4(col, 1.0);
}
`
});
const bgMesh = new THREE.Mesh(bgGeo, bgMat);
scene.add(bgMesh);
// Wooden / pastel café tabletop plane beneath the plate
const tableGeo = new THREE.CircleGeometry(9.0, 48);
tableGeo.rotateX(-Math.PI / 2);
const tableMat = new THREE.ShaderMaterial({
uniforms: {},
vertexShader: `
varying vec2 vUv;
varying vec3 vPos;
void main() {
vUv = uv;
vPos = position;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
varying vec3 vPos;
void main() {
float r = length(vPos.xz);
vec3 centerCol = vec3(0.98, 0.89, 0.77);
vec3 edgeCol = vec3(0.92, 0.76, 0.60);
vec3 col = mix(centerCol, edgeCol, smoothstep(0.8, 7.5, r));
// Soft shadow under the porcelain plate
float plateShadow = smoothstep(1.62, 2.25, r);
col *= mix(0.76, 1.0, plateShadow);
gl_FragColor = vec4(col, 1.0);
}
`
});
const tableMesh = new THREE.Mesh(tableGeo, tableMat);
tableMesh.position.y = -0.17;
scene.add(tableMesh);
// Small Glossy Porcelain Dessert Plate (with dynamic orange jelly caustic glow)
const plateProfile = [
new THREE.Vector2(0.00, -0.02),
new THREE.Vector2(1.05, -0.02),
new THREE.Vector2(1.25, 0.00),
new THREE.Vector2(1.62, 0.14),
new THREE.Vector2(1.78, 0.21),
new THREE.Vector2(1.84, 0.22),
new THREE.Vector2(1.86, 0.18),
new THREE.Vector2(1.65, 0.04),
new THREE.Vector2(1.22, -0.14),
new THREE.Vector2(1.12, -0.17),
new THREE.Vector2(0.98, -0.14),
new THREE.Vector2(0.00, -0.14)
];
const plateGeo = new THREE.LatheGeometry(plateProfile, 64);
const plateUniforms = {
uSquash: { value: 0.0 },
uDropY: { value: 0.0 },
uSway: { value: new THREE.Vector2(0, 0) },
uPurr: { value: 0.0 }
};
const plateMat = new THREE.ShaderMaterial({
uniforms: plateUniforms,
vertexShader: `
varying vec3 vWorldPos;
varying vec3 vNormal;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
vNormal = normalize(mat3(modelMatrix) * normal);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`,
fragmentShader: `
uniform float uSquash;
uniform float uDropY;
uniform vec2 uSway;
uniform float uPurr;
varying vec3 vWorldPos;
varying vec3 vNormal;
void main() {
vec3 N = normalize(vNormal);
vec3 V = normalize(cameraPosition - vWorldPos);
vec3 L = normalize(vec3(3.5, 6.5, 4.5));
vec3 H = normalize(L + V);
float r = length(vWorldPos.xz);
// Glossy warm porcelain base color
vec3 porcelain = vec3(0.995, 0.982, 0.962);
// Subtle painted apricot-gold rim stripe
float rimBand1 = smoothstep(1.66, 1.70, r) * (1.0 - smoothstep(1.74, 1.78, r));
float rimBand2 = smoothstep(1.26, 1.29, r) * (1.0 - smoothstep(1.31, 1.34, r));
vec3 goldAccent = vec3(0.97, 0.64, 0.24);
porcelain = mix(porcelain, goldAccent, rimBand1 * 0.72 + rimBand2 * 0.35);
float NdotL = max(dot(N, L), 0.0);
vec3 col = porcelain * (0.68 + 0.34 * NdotL);
// Translucent orange caustic light transmitted through the jelly cat onto the plate
vec2 catCenter = uSway * 0.35;
float distCat = length((vWorldPos.xz - catCenter) * vec2(0.88, 0.96));
float radiusScale = (1.0 - uSquash * 0.42) * (1.0 / (1.0 + uDropY * 0.35));
float normDist = distCat / max(0.35, radiusScale);
if (vWorldPos.y > -0.05) {
// Focused bright amber caustic core + warm orange halo + contact occlusion ring
float causticCore = exp(-normDist * normDist * 2.2) * (1.0 / (1.0 + uDropY * 0.6));
float causticRing = smoothstep(1.18, 0.72, normDist) * smoothstep(0.15, 0.78, normDist);
float contactRim = exp(-pow((normDist - 0.86) * 5.5, 2.0)) * (1.0 / (1.0 + uDropY * 2.5));
vec3 amberCaustic = vec3(1.0, 0.48, 0.04) * (1.0 + uPurr * 0.25);
col = mix(col, col * vec3(0.92, 0.56, 0.26), causticCore * 0.62);
col += amberCaustic * (causticRing * 0.28 + causticCore * 0.16);
col *= (1.0 - contactRim * 0.26);
}
// Crisp porcelain specular glaze
float spec = pow(max(dot(N, H), 0.0), 96.0) * 0.55;
float fres = pow(1.0 - max(dot(N, V), 0.0), 4.0) * 0.22;
col += vec3(1.0, 0.98, 0.94) * (spec + fres);
gl_FragColor = vec4(col, 1.0);
}
`
});
const plateMesh = new THREE.Mesh(plateGeo, plateMat);
scene.add(plateMesh);
// =========================================================================
// 6. TINY FLOATING INTERNAL AIR BUBBLES (MOVE WITH JELLY DEFORMATION)
// =========================================================================
const bubbleRestData = [
// Belly & chest bubbles
{ x: -0.28, y: 0.55, z: 0.22, r: 0.038 },
{ x: 0.34, y: 0.62, z: 0.18, r: 0.044 },
{ x: 0.06, y: 0.45, z: 0.34, r: 0.028 },
{ x: -0.42, y: 0.78, z: -0.10, r: 0.034 },
{ x: 0.45, y: 0.48, z: -0.15, r: 0.030 },
{ x: 0.14, y: 0.88, z: 0.26, r: 0.046 },
{ x: -0.18, y: 0.96, z: -0.22, r: 0.032 },
{ x: 0.02, y: 0.72, z: -0.28, r: 0.040 },
{ x: -0.52, y: 0.42, z: 0.14, r: 0.026 },
{ x: 0.24, y: 1.12, z: 0.12, r: 0.033 },
{ x: -0.25, y: 1.18, z: 0.18, r: 0.025 },
{ x: 0.00, y: 0.34, z: 0.05, r: 0.036 },
// Head & chubby cheek bubbles
{ x: -0.34, y: 1.56, z: 0.22, r: 0.035 },
{ x: 0.38, y: 1.54, z: 0.20, r: 0.032 },
{ x: 0.12, y: 1.82, z: 0.14, r: 0.042 },
{ x: -0.18, y: 1.92, z: -0.05, r: 0.030 },
{ x: 0.22, y: 1.68, z: -0.18, r: 0.036 },
{ x: -0.08, y: 1.52, z: 0.36, r: 0.024 },
{ x: 0.05, y: 2.06, z: 0.08, r: 0.028 },
// Ear & tail bubbles
{ x: -0.44, y: 2.24, z: 0.07, r: 0.022 },
{ x: 0.46, y: 2.26, z: 0.07, r: 0.024 },
{ x: 0.66, y: 0.42, z: -0.78, r: 0.026 },
{ x: 0.88, y: 0.72, z: -0.54, r: 0.025 },
{ x: -0.32, y: 0.25, z: 0.52, r: 0.023 }
];
// Ensure every bubble rest position is strictly inside the cat SDF (< -0.12)
for (let i = 0; i < bubbleRestData.length; i++) {
const b = bubbleRestData[i];
for (let iter = 0; iter < 4; iter++) {
const d = evalCatSDF(b.x, b.y, b.z);
if (d < -0.13) break;
const g = getSDFGradient(b.x, b.y, b.z);
b.x -= (d + 0.15) * g[0];
b.y -= (d + 0.15) * g[1];
b.z -= (d + 0.15) * g[2];
}
}
const bubbleGroup = new THREE.Group();
scene.add(bubbleGroup);
const bubbleUnitGeo = new THREE.SphereGeometry(1.0, 14, 12);
const bubbleMat = new THREE.ShaderMaterial({
transparent: true,
uniforms: {},
vertexShader: `
varying vec3 vNormal;
varying vec3 vWorldPos;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
vNormal = normalize(mat3(modelMatrix) * normal);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`,
fragmentShader: `
varying vec3 vNormal;
varying vec3 vWorldPos;
void main() {
vec3 N = normalize(vNormal);
vec3 V = normalize(cameraPosition - vWorldPos);
vec3 L = normalize(vec3(3.0, 6.0, 4.5));
vec3 H = normalize(L + V);
float NdotV = max(dot(N, V), 0.0);
float rim = pow(1.0 - NdotV, 2.0);
float spec1 = pow(max(dot(N, H), 0.0), 70.0);
float spec2 = pow(max(dot(N, normalize(vec3(-2.0, -3.0, 3.0) + V)), 0.0), 35.0) * 0.55;
vec3 col = mix(vec3(1.0, 0.74, 0.32), vec3(1.0, 0.98, 0.92), rim * 0.85 + spec1 + spec2);
float alpha = clamp(0.32 + rim * 0.62 + spec1 * 0.95 + spec2 * 0.5, 0.0, 1.0);
gl_FragColor = vec4(col, alpha);
}
`
});
const bubbleMeshes = bubbleRestData.map((b) => {
const m = new THREE.Mesh(bubbleUnitGeo, bubbleMat);
m.scale.setScalar(b.r);
bubbleGroup.add(m);
return m;
});
// =========================================================================
// 7. BUILD JELLY CAT MESH & CLEAR ORANGE JELLY SHADER
// =========================================================================
const catData = buildJellyCatGeometry();
const jellyUniforms = {
uSceneTex: { value: refractionRT.texture },
uResolution: { value: new THREE.Vector2(rtWidth, rtHeight) },
uHeadCenter: { value: new THREE.Vector3(0, 1.68, 0.1) },
uBellyCenter: { value: new THREE.Vector3(0, 0.72, 0.0) },
uPurrGlow: { value: 0.0 },
uFirmness: { value: jellyState.firmness },
uTime: { value: 0.0 }
};
const jellyCatMat = new THREE.ShaderMaterial({
uniforms: jellyUniforms,
vertexShader: `
varying vec3 vWorldPos;
varying vec3 vWorldNormal;
varying vec3 vViewNormal;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
vWorldNormal = normalize(mat3(modelMatrix) * normal);
vViewNormal = normalize(normalMatrix * normal);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`,
fragmentShader: `
uniform sampler2D uSceneTex;
uniform vec2 uResolution;
uniform vec3 uHeadCenter;
uniform vec3 uBellyCenter;
uniform float uPurrGlow;
uniform float uFirmness;
uniform float uTime;
varying vec3 vWorldPos;
varying vec3 vWorldNormal;
varying vec3 vViewNormal;
// Procedural warm HDR studio reflection environment
vec3 sampleStudioEnv(vec3 R) {
float y = clamp(R.y * 0.5 + 0.5, 0.0, 1.0);
vec3 env = mix(vec3(0.95, 0.52, 0.16), vec3(1.0, 0.96, 0.88), smoothstep(0.15, 0.85, y));
// Overhead & front-left softbox studio windows
float win1 = smoothstep(0.76, 0.92, dot(R, normalize(vec3(0.45, 0.72, 0.52))));
float win2 = smoothstep(0.80, 0.94, dot(R, normalize(vec3(-0.62, 0.55, 0.55))));
env += vec3(1.0, 0.99, 0.95) * (win1 * 0.75 + win2 * 0.45);
return env;
}
void main() {
vec3 N = normalize(vWorldNormal);
vec3 V = normalize(cameraPosition - vWorldPos);
vec3 VN = normalize(vViewNormal);
float NdotV = clamp(dot(N, V), 0.0, 1.0);
// Estimate optical thickness through the cat's head, torso & limbs
float dBelly = length((vWorldPos - uBellyCenter) * vec3(1.0, 0.85, 1.0));
float dHead = length((vWorldPos - uHeadCenter) * vec3(1.05, 1.0, 1.05));
float coreProximity = clamp(1.15 - min(dBelly, dHead * 1.15), 0.15, 1.0);
float thickness = mix(0.28, 1.38, pow(NdotV, 0.62) * 0.65 + coreProximity * 0.35);
// Screen-space refraction with subtle chromatic dispersion
vec2 screenUV = gl_FragCoord.xy / uResolution;
float iorStrength = (0.062 + 0.032 * thickness) * (1.02 - uFirmness * 0.12);
vec2 refractOffset = -VN.xy * iorStrength;
vec2 uvR = clamp(screenUV + refractOffset * 0.94, 0.002, 0.998);
vec2 uvG = clamp(screenUV + refractOffset * 1.00, 0.002, 0.998);
vec2 uvB = clamp(screenUV + refractOffset * 1.06, 0.002, 0.998);
vec3 bgCol;
bgCol.r = texture2D(uSceneTex, uvR).r;
bgCol.g = texture2D(uSceneTex, uvG).g;
bgCol.b = texture2D(uSceneTex, uvB).b;
// Beer-Lambert Clear Orange Jelly absorption
float density = 1.42 + uFirmness * 0.32;
vec3 sigma = vec3(0.07, 0.68, 2.15) * density;
vec3 transmittance = exp(-sigma * thickness);
vec3 jellyBody = bgCol * transmittance;
// Rich internal tangerine-orange scattering
vec3 orangeTint = vec3(1.0, 0.44, 0.04);
jellyBody = mix(orangeTint * 0.88, jellyBody, 0.74);
// Soft glowing light inside the jelly cat (brightens gently when purring or wobbling)
float innerCore = exp(-min(dBelly * dBelly * 1.85, dHead * dHead * 2.15));
float pulse = 1.0 + 0.08 * sin(uTime * 3.2) + uPurrGlow * 0.42;
vec3 innerLight = vec3(1.0, 0.68, 0.16) * innerCore * (0.48 * pulse);
// Back-lit subsurface scatter glow around ears, cheeks & tail rim
vec3 L1 = normalize(vec3(3.5, 6.5, 4.5));
vec3 L2 = normalize(vec3(-3.5, 4.2, -3.5));
float sss = pow(clamp(dot(V, -L2 + N * 0.45), 0.0, 1.0), 2.5) * 0.28;
innerLight += vec3(1.0, 0.54, 0.10) * (sss + (1.0 - NdotV) * 0.22);
vec3 color = jellyBody + innerLight;
// Wet glossy Fresnel coat + dual specular highlights
float fresnel = 0.05 + 0.95 * pow(1.0 - NdotV, 3.8);
vec3 R = reflect(-V, N);
vec3 envRefl = sampleStudioEnv(R);
vec3 H1 = normalize(L1 + V);
vec3 H2 = normalize(vec3(-2.5, 5.0, 3.5) + V);
float specSharp1 = pow(max(dot(N, H1), 0.0), 190.0) * 1.15;
float specBroad1 = pow(max(dot(N, H1), 0.0), 28.0) * 0.22;
float specSharp2 = pow(max(dot(N, H2), 0.0), 140.0) * 0.55;
color = mix(color, envRefl, fresnel * 0.52);
color += vec3(1.0, 0.99, 0.95) * (specSharp1 + specBroad1 + specSharp2);
gl_FragColor = vec4(color, 1.0);
}
`
});
const jellyCatMesh = new THREE.Mesh(catData.geometry, jellyCatMat);
scene.add(jellyCatMesh);
// =========================================================================
// 8. EXPRESSIVE EYES (FOLLOW FINGER + SQUINT ON HEAD RUB) & CUTE NOSE/MOUTH
// =========================================================================
function createProjectedPatchGeometry(cx, cy, cz, rx, ry, segU, segV, surfaceOffset) {
const geo = new THREE.BufferGeometry();
const verts = [];
const restVerts = [];
const uvs = [];
const indices = [];
for (let iy = 0; iy <= segV; iy++) {
const v = iy / segV;
const ly = (v * 2 - 1) * ry;
for (let ix = 0; ix <= segU; ix++) {
const u = ix / segU;
const lx = (u * 2 - 1) * rx;
const proj = projectToCatSurface(cx + lx, cy + ly, cz, surfaceOffset, 5);
verts.push(proj[0], proj[1], proj[2]);
restVerts.push(proj[0], proj[1], proj[2]);
uvs.push(u * 2 - 1, v * 2 - 1);
}
}
for (let iy = 0; iy < segV; iy++) {
for (let ix = 0; ix < segU; ix++) {
const a = iy * (segU + 1) + ix;
const b = a + 1;
const c = a + (segU + 1);
const d = c + 1;
indices.push(a, b, d, a, d, c);
}
}
const posAttr = new THREE.BufferAttribute(new Float32Array(verts), 3);
geo.setAttribute('position', posAttr);
geo.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), 2));
geo.setIndex(indices);
geo.computeVertexNormals();
return { geo, posArray: posAttr.array, restArray: new Float32Array(restVerts) };
}
const eyeUniforms = {
uLook: { value: new THREE.Vector2(0, 0) },
uSquint: { value: 0.0 }
};
function createEyeMaterial(isRightEye) {
return new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -2,
uniforms: {
uLook: eyeUniforms.uLook,
uSquint: eyeUniforms.uSquint,
uMirror: { value: isRightEye ? -1.0 : 1.0 }
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec2 uLook;
uniform float uSquint;
uniform float uMirror;
varying vec2 vUv;
void main() {
vec2 p = vUv;
// Outer soft eye socket mask
float rOuter = length(p * vec2(0.95, 1.02));
float openAlpha = 1.0 - smoothstep(0.76, 0.88, rOuter);
// Iris & pupil shifted by finger tracking
vec2 pLook = p - uLook * 0.34;
float rPupil = length(pLook * vec2(0.96, 0.92));
vec3 darkEspresso = vec3(0.14, 0.04, 0.01);
vec3 warmAmberRim = vec3(0.46, 0.16, 0.03);
vec3 eyeCol = mix(darkEspresso, warmAmberRim, smoothstep(0.32, 0.72, rPupil));
// Glossy wet catchlights (shift subtly with gaze)
vec2 hl1Pos = uLook * 0.22 + vec2(-0.22, 0.25);
vec2 hl2Pos = uLook * 0.18 + vec2(0.20, -0.22);
float hl1 = 1.0 - smoothstep(0.11, 0.16, length(p - hl1Pos));
float hl2 = 1.0 - smoothstep(0.05, 0.09, length(p - hl2Pos));
eyeCol = mix(eyeCol, vec3(1.0, 0.99, 0.96), clamp(hl1 + hl2 * 0.85, 0.0, 1.0));
// Happy curved squint arc (^ ^) when head is rubbed
float arcY = 0.16 - 0.56 * (p.x * p.x);
float arcDist = sqrt(pow((p.y - arcY), 2.0) + max(0.0, abs(p.x) - 0.62) * 2.5);
float squintAlpha = 1.0 - smoothstep(0.11, 0.19, arcDist);
vec3 squintCol = vec3(0.20, 0.06, 0.01);
// Eyelid squeeze transition during intermediate squint
float lidClose = smoothstep(0.0, 0.65, uSquint);
float lidMask = 1.0 - smoothstep(0.85 - lidClose * 0.78, 0.92 - lidClose * 0.78, abs(p.y - arcY * lidClose));
float roundAlpha = openAlpha * lidMask;
float finalBlend = smoothstep(0.45, 0.85, uSquint);
vec3 finalCol = mix(eyeCol, squintCol, finalBlend);
float finalAlpha = mix(roundAlpha, squintAlpha, finalBlend);
if (finalAlpha < 0.02) discard;
gl_FragColor = vec4(finalCol, finalAlpha * 0.94);
}
`
});
}
const leftEyePatch = createProjectedPatchGeometry(-0.26, 1.73, 0.80, 0.145, 0.155, 10, 10, 0.008);
const rightEyePatch = createProjectedPatchGeometry(0.26, 1.73, 0.80, 0.145, 0.155, 10, 10, 0.008);
const leftEyeMesh = new THREE.Mesh(leftEyePatch.geo, createEyeMaterial(false));
const rightEyeMesh = new THREE.Mesh(rightEyePatch.geo, createEyeMaterial(true));
scene.add(leftEyeMesh);
scene.add(rightEyeMesh);
// Cute tiny nose & 'ω' mouth patch projected onto the muzzle
const noseMouthPatch = createProjectedPatchGeometry(0.0, 1.56, 0.88, 0.22, 0.13, 12, 8, 0.008);
const noseMouthMat = new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -2,
uniforms: {},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
void main() {
vec2 p = vUv;
// Rounded inverted triangle nose at top center
vec2 np = p - vec2(0.0, 0.34);
float noseW = 0.18 + np.y * 0.28;
float noseDist = max(abs(np.x) - max(0.02, noseW), abs(np.y) - 0.18);
float noseAlpha = 1.0 - smoothstep(0.0, 0.08, noseDist);
// Cute cat 'w' mouth below the nose
vec2 mp = vec2(abs(p.x) - 0.24, p.y + 0.12);
float wDist = abs(length(mp * vec2(1.0, 1.25)) - 0.24);
float wMask = step(mp.y, 0.06) * (1.0 - smoothstep(0.50, 0.56, abs(p.x)));
float mouthAlpha = (1.0 - smoothstep(0.035, 0.085, wDist)) * wMask;
float a = max(noseAlpha, mouthAlpha * 0.85);
if (a < 0.02) discard;
vec3 col = mix(vec3(0.45, 0.14, 0.02), vec3(0.78, 0.24, 0.08), noseAlpha);
gl_FragColor = vec4(col, a * 0.88);
}
`
});
const noseMouthMesh = new THREE.Mesh(noseMouthPatch.geo, noseMouthMat);
scene.add(noseMouthMesh);
// Sync all vertices of the cat, eyes, nose/mouth, and internal bubbles with the deformed field
function updateAllDeformedGeometries() {
// 1. Main jelly cat mesh
const pos = catData.posArray;
const rest = catData.restArray;
const n = catData.numVerts;
for (let i = 0; i < n; i++) {
const i3 = i * 3;
const d = evaluateDeformedPoint(rest[i3], rest[i3 + 1], rest[i3 + 2]);
pos[i3] = d[0];
pos[i3 + 1] = d[1];
pos[i3 + 2] = d[2];
}
catData.geometry.attributes.position.needsUpdate = true;
catData.geometry.computeVertexNormals();
// 2. Eye & nose/mouth patches
const patches = [leftEyePatch, rightEyePatch, noseMouthPatch];
for (let p = 0; p < patches.length; p++) {
const patch = patches[p];
const pPos = patch.posArray;
const pRest = patch.restArray;
for (let i = 0; i < pPos.length; i += 3) {
const d = evaluateDeformedPoint(pRest[i], pRest[i + 1], pRest[i + 2]);
pPos[i] = d[0];
pPos[i + 1] = d[1];
pPos[i + 2] = d[2];
}
patch.geo.attributes.position.needsUpdate = true;
}
// 3. Internal floating air bubbles
for (let i = 0; i < bubbleRestData.length; i++) {
const b = bubbleRestData[i];
const d = evaluateDeformedPoint(b.x, b.y, b.z);
bubbleMeshes[i].position.set(d[0], d[1], d[2]);
}
// 4. Update shader centers for inner light & plate caustic pool
const hc = evaluateDeformedPoint(0.0, 1.68, 0.10);
jellyUniforms.uHeadCenter.value.set(hc[0], hc[1], hc[2]);
const bc = evaluateDeformedPoint(0.0, 0.72, 0.00);
jellyUniforms.uBellyCenter.value.set(bc[0], bc[1], bc[2]);
plateUniforms.uSquash.value = jellyState.squashY - jellyState.gravitySag;
plateUniforms.uDropY.value = jellyState.dropY;
plateUniforms.uSway.value.set(jellyState.swayX, jellyState.swayZ);
plateUniforms.uPurr.value = jellyState.purrAmount;
}
// =========================================================================
// 9. UNIFIED TOUCH & MOUSE INTERACTION (POKE, SQUEEZE, PULL, HEAD RUB)
// =========================================================================
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2(0, 0);
const dragPlane = new THREE.Plane();
const dragIntersect = new THREE.Vector3();
const interaction = {
isDown: false,
pointerId: null,
mode: 'none', // 'pullNode', 'squeeze', 'rubHead'
nodeIdx: -1,
restHit: new THREE.Vector3(),
worldGrabStart: new THREE.Vector3(),
lastClientX: 0,
lastClientY: 0,
lastMoveDirX: 0,
totalMoveDist: 0,
downTime: 0
};
const statusToast = document.getElementById('status-toast');
let toastTimeout = null;
function showStatusToast(text) {
statusToast.textContent = text;
statusToast.classList.add('visible');
if (toastTimeout) clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => {
statusToast.classList.remove('visible');
}, 1350);
}
function updateEyeLookTargetFromScreen(clientX, clientY) {
const nx = (clientX / Math.max(1, window.innerWidth)) * 2 - 1;
const ny = -(clientY / Math.max(1, window.innerHeight)) * 2 + 1;
pointerNDC.set(nx, ny);
jellyState.lookTargetX = Math.max(-1.0, Math.min(1.0, nx * 1.35));
jellyState.lookTargetY = Math.max(-0.9, Math.min(0.9, ny * 1.25 - 0.12));
}
// Classify which anatomical part was touched from rest-space hit position
function classifyHitPart(rx, ry, rz) {
// 1. Check Ears first
if (ry > 2.02 && Math.abs(rx) > 0.24) {
return { mode: 'pullNode', nodeIdx: rx < 0 ? 0 : 1 };
}
// 2. Check Top of Head / Forehead (between ears) -> Head Rubbing zone!
if (ry > 1.82 && Math.abs(rx) <= 0.44 && rz > -0.45) {
return { mode: 'rubHead', nodeIdx: 4 };
}
// 3. Check Chubby Cheeks
if (ry > 1.25 && ry <= 1.88 && Math.abs(rx) > 0.28 && rz > -0.10) {
return { mode: 'pullNode', nodeIdx: rx < 0 ? 2 : 3 };
}
// 4. Check Curled Tail (back and right side)
if ((rz < -0.58 && ry < 1.15) || (rx > 0.58 && rz < -0.12 && ry < 1.22)) {
let bestIdx = 15;
let bestD = 999;
for (let idx = 13; idx <= 15; idx++) {
const n = anatomicalNodes[idx];
const d = (rx - n.x) ** 2 + (ry - n.y) ** 2 + (rz - n.z) ** 2;
if (d < bestD) {
bestD = d;
bestIdx = idx;
}
}
return { mode: 'pullNode', nodeIdx: bestIdx };
}
// 5. Find closest anatomical node for general body/paws/belly poke, squeeze & pull
let bestIdx = 7;
let bestD = 999;
for (let i = 0; i < anatomicalNodes.length; i++) {
const n = anatomicalNodes[i];
const d = (rx - n.x) ** 2 + (ry - n.y) ** 2 + (rz - n.z) ** 2;
if (d < bestD) {
bestD = d;
bestIdx = i;
}
}
const mode = (bestIdx >= 7 && bestIdx <= 10) ? 'squeezeOrPull' : 'pullNode';
return { mode, nodeIdx: bestIdx };
}
function handlePointerDown(clientX, clientY) {
sound.init();
updateEyeLookTargetFromScreen(clientX, clientY);
raycaster.setFromCamera(pointerNDC, camera);
const hits = raycaster.intersectObject(jellyCatMesh, false);
if (hits.length === 0) return false;
const hit = hits[0];
const face = hit.face;
const rest = catData.restArray;
const iA = face.a * 3;
const rx = rest[iA], ry = rest[iA + 1], rz = rest[iA + 2];
const part = classifyHitPart(rx, ry, rz);
interaction.isDown = true;
interaction.mode = part.mode;
interaction.nodeIdx = part.nodeIdx;
interaction.restHit.set(rx, ry, rz);
interaction.worldGrabStart.copy(hit.point);
interaction.lastClientX = clientX;
interaction.lastClientY = clientY;
interaction.totalMoveDist = 0;
interaction.downTime = performance.now();
// Setup camera-facing drag plane at the hit point
const camDir = new THREE.Vector3();
camera.getWorldDirection(camDir);
dragPlane.setFromNormalAndCoplanarPoint(camDir, hit.point);
// Position the surface Kelvinlet at the exact rest-space touch point
grabKelvinlet.active = true;
grabKelvinlet.x = rx;
grabKelvinlet.y = ry;
grabKelvinlet.z = rz;
// Immediate tactile poke dimple inward along surface normal
const wn = hit.face.normal.clone().normalize();
const pokeDepth = 0.14 * (1.12 - jellyState.firmness * 0.35);
grabKelvinlet.dx = -wn.x * pokeDepth;
grabKelvinlet.dy = -wn.y * pokeDepth;
grabKelvinlet.dz = -wn.z * pokeDepth;
grabKelvinlet.vx = -wn.x * 1.4;
grabKelvinlet.vy = -wn.y * 1.4;
grabKelvinlet.vz = -wn.z * 1.4;
const node = anatomicalNodes[part.nodeIdx];
node.vx -= wn.x * 1.5;
node.vy -= wn.y * 1.5;
node.vz -= wn.z * 1.5;
jellyState.squashVelY -= 0.65;
sound.playPoke(0.65, jellyState.firmness);
if (part.mode === 'rubHead') {
jellyState.rubEnergy = Math.min(1.0, jellyState.rubEnergy + 0.32);
} else {
showStatusToast(node.label);
}
return true;
}
function handlePointerMove(clientX, clientY) {
updateEyeLookTargetFromScreen(clientX, clientY);
if (!interaction.isDown) return;
const movePx = Math.hypot(clientX - interaction.lastClientX, clientY - interaction.lastClientY);
const dxPx = clientX - interaction.lastClientX;
interaction.totalMoveDist += movePx;
interaction.lastClientX = clientX;
interaction.lastClientY = clientY;
raycaster.setFromCamera(pointerNDC, camera);
if (!raycaster.ray.intersectPlane(dragPlane, dragIntersect)) return;
const delta = dragIntersect.clone().sub(interaction.worldGrabStart);
const node = anatomicalNodes[interaction.nodeIdx];
// Check if the user is rubbing back and forth on the head / face
const dirSign = Math.abs(dxPx) > 2 ? Math.sign(dxPx) : interaction.lastMoveDirX;
const isReversing = (dirSign !== 0 && interaction.lastMoveDirX !== 0 && dirSign !== interaction.lastMoveDirX);
if (dirSign !== 0) interaction.lastMoveDirX = dirSign;
if (interaction.mode === 'rubHead' || (interaction.restHit.y > 1.45 && isReversing)) {
interaction.mode = 'rubHead';
// Build up purring and happy squint energy as finger rubs the head
jellyState.rubEnergy = Math.min(1.0, jellyState.rubEnergy + movePx * 0.014);
const rubLimit = 0.22;
const rx = Math.max(-rubLimit, Math.min(rubLimit, delta.x * 0.55));
const ry = Math.max(-0.16, Math.min(0.10, delta.y * 0.45));
const rz = Math.max(-rubLimit, Math.min(rubLimit, delta.z * 0.55));
node.dx = rx;
node.dy = ry;
node.dz = rz;
grabKelvinlet.dx = rx * 0.8;
grabKelvinlet.dy = ry * 0.8 - 0.05;
grabKelvinlet.dz = rz * 0.8;
jellyState.swayX = rx * 0.45;
jellyState.squashY = -0.05 * jellyState.purrAmount;
if (jellyState.rubEnergy > 0.35) {
showStatusToast('Purring... ♪');
}
return;
}
// Smooth elastic saturation curve (Soft Pudding stretches further; Firm Gummy resists more)
const maxStretch = 0.82 - jellyState.firmness * 0.26;
const rawLen = delta.length();
const softLen = maxStretch * Math.tanh(rawLen / Math.max(0.1, maxStretch));
const pullVec = rawLen > 1e-5 ? delta.multiplyScalar(softLen / rawLen) : delta;
// Check if pushing inward/downward on the belly -> Volumetric Squeeze!
if (interaction.mode === 'squeezeOrPull') {
const toCenter = new THREE.Vector3(-interaction.restHit.x, 0, -interaction.restHit.z).normalize();
const inwardDot = pullVec.x * toCenter.x + pullVec.z * toCenter.z;
if (pullVec.y < -0.05 || inwardDot > 0.04) {
const squeezeAmt = Math.min(0.42, Math.max(0, -pullVec.y * 0.55 + Math.max(0, inwardDot) * 0.45));
jellyState.squashY = -squeezeAmt;
jellyState.squashVelY = 0;
}
}
// Apply stretch to the grabbed anatomical node and surface Kelvinlet
node.dx = pullVec.x * 0.85;
node.dy = pullVec.y * 0.85;
node.dz = pullVec.z * 0.85;
node.vx = 0;
node.vy = 0;
node.vz = 0;
grabKelvinlet.dx = pullVec.x * 0.55;
grabKelvinlet.dy = pullVec.y * 0.55;
grabKelvinlet.dz = pullVec.z * 0.55;
// Coupled whole-body lean toward the pulled ear, cheek, or tail
jellyState.swayX = pullVec.x * 0.22;
jellyState.swayZ = pullVec.z * 0.22;
if (movePx > 2.5 && softLen > 0.12) {
sound.playStretchGrain(softLen / maxStretch, jellyState.firmness);
}
}
function handlePointerUp() {
if (!interaction.isDown) return;
const node = anatomicalNodes[interaction.nodeIdx];
const stretchMag = Math.hypot(node.dx, node.dy, node.dz) + Math.abs(jellyState.squashY);
// Quick tap (< 190ms and tiny drag) gives an extra bouncy poke impulse
const elapsedMs = performance.now() - interaction.downTime;
if (elapsedMs < 190 && interaction.totalMoveDist < 14) {
jellyState.squashVelY -= 1.35;
node.vy -= 1.4;
} else if (stretchMag > 0.08 && interaction.mode !== 'rubHead') {
sound.playWobbleRelease(Math.min(1.0, stretchMag * 1.45), jellyState.firmness);
}
interaction.isDown = false;
interaction.nodeIdx = -1;
interaction.mode = 'none';
grabKelvinlet.active = false;
}
// =========================================================================
// 10. HANDS-FREE 20-SECOND #demo MODE LOOP (ENDS ON ANY REAL TOUCH)
// =========================================================================
const demoPointerEl = document.getElementById('demo-pointer');
const hintPillEl = document.getElementById('hint-pill');
const defaultHintText = hintPillEl.textContent;
const demoState = {
active: false,
time: 0,
phaseTriggered: {}
};
function checkDemoHash() {
const h = (window.location.hash || '').toLowerCase();
return h === '#demo' || window.location.href.toLowerCase().endsWith('#demo');
}
function startDemoMode() {
demoState.active = true;
demoState.time = 0;
demoState.phaseTriggered = {};
demoPointerEl.style.display = 'block';
hintPillEl.textContent = 'Demo Mode • Touch or click anywhere to play';
}
function stopDemoMode() {
if (!demoState.active) return;
demoState.active = false;
demoPointerEl.style.display = 'none';
hintPillEl.textContent = defaultHintText;
handlePointerUp();
}
// Project a 3D world point to 2D client screen coordinates for the virtual demo finger
function worldToScreen(wx, wy, wz) {
const v = new THREE.Vector3(wx, wy, wz);
v.project(camera);
return {
x: (v.x * 0.5 + 0.5) * window.innerWidth,
y: (-v.y * 0.5 + 0.5) * window.innerHeight
};
}
function updateDemoChoreography(dt) {
if (!demoState.active) return;
const prevT = demoState.time;
demoState.time = (demoState.time + dt) % 20.0;
const t = demoState.time;
if (t < prevT) {
demoState.phaseTriggered = {};
handlePointerUp();
}
let screenPt = { x: window.innerWidth * 0.5, y: window.innerHeight * 0.5 };
let pressing = false;
if (t < 2.8) {
// Phase 1 (0 - 2.8s): Circle finger in front so eyes follow, then poke belly
const ang = t * 2.8;
const p3 = evaluateDeformedPoint(Math.cos(ang) * 0.85, 1.45 + Math.sin(ang) * 0.45, 0.75);
screenPt = worldToScreen(p3[0], p3[1], p3[2]);
updateEyeLookTargetFromScreen(screenPt.x, screenPt.y);
if (t > 1.8 && !demoState.phaseTriggered.poke1) {
demoState.phaseTriggered.poke1 = true;
const bPt = evaluateDeformedPoint(0.0, 0.78, 0.65);
screenPt = worldToScreen(bPt[0], bPt[1], bPt[2]);
handlePointerDown(screenPt.x, screenPt.y);
setTimeout(() => { if (demoState.active) handlePointerUp(); }, 140);
}
pressing = (t > 1.8 && t < 2.05);
} else if (t < 6.0) {
// Phase 2 (2.8 - 6.0s): Grab and pull the Left Ear up and out, then release to wobble
const earBase = evaluateDeformedPoint(-0.55, 2.45, 0.09);
if (t < 3.1) {
screenPt = worldToScreen(earBase[0], earBase[1], earBase[2]);
} else if (t < 4.7) {
pressing = true;
if (!demoState.phaseTriggered.earDown) {
demoState.phaseTriggered.earDown = true;
const startSc = worldToScreen(earBase[0], earBase[1], earBase[2]);
handlePointerDown(startSc.x, startSc.y);
}
const pullProg = Math.min(1.0, (t - 3.1) / 1.1);
screenPt = worldToScreen(-0.55 - 0.62 * pullProg, 2.45 + 0.48 * pullProg, 0.15);
handlePointerMove(screenPt.x, screenPt.y);
} else {
if (!demoState.phaseTriggered.earUp) {
demoState.phaseTriggered.earUp = true;
handlePointerUp();
}
screenPt = worldToScreen(earBase[0], earBase[1], earBase[2]);
}
} else if (t < 9.2) {
// Phase 3 (6.0 - 9.2s): Pull the Chubby Right Cheek out wide, then release
const cheekBase = evaluateDeformedPoint(0.52, 1.54, 0.34);
if (t < 6.3) {
screenPt = worldToScreen(cheekBase[0], cheekBase[1], cheekBase[2]);
} else if (t < 7.9) {
pressing = true;
if (!demoState.phaseTriggered.cheekDown) {
demoState.phaseTriggered.cheekDown = true;
const startSc = worldToScreen(cheekBase[0], cheekBase[1], cheekBase[2]);
handlePointerDown(startSc.x, startSc.y);
}
const pullProg = Math.min(1.0, (t - 6.3) / 1.1);
screenPt = worldToScreen(0.52 + 0.68 * pullProg, 1.50 - 0.12 * pullProg, 0.40);
handlePointerMove(screenPt.x, screenPt.y);
} else {
if (!demoState.phaseTriggered.cheekUp) {
demoState.phaseTriggered.cheekUp = true;
handlePointerUp();
}
screenPt = worldToScreen(cheekBase[0], cheekBase[1], cheekBase[2]);
}
} else if (t < 12.2) {
// Phase 4 (9.2 - 12.2s): Pull the Curled Tail on the right, then release
const tailBase = evaluateDeformedPoint(0.95, 0.92, -0.34);
if (t < 9.5) {
screenPt = worldToScreen(tailBase[0], tailBase[1], tailBase[2]);
} else if (t < 11.0) {
pressing = true;
if (!demoState.phaseTriggered.tailDown) {
demoState.phaseTriggered.tailDown = true;
const startSc = worldToScreen(tailBase[0], tailBase[1], tailBase[2]);
handlePointerDown(startSc.x, startSc.y);
}
const pullProg = Math.min(1.0, (t - 9.5) / 1.0);
screenPt = worldToScreen(0.95 + 0.65 * pullProg, 0.92 + 0.35 * pullProg, -0.20);
handlePointerMove(screenPt.x, screenPt.y);
} else {
if (!demoState.phaseTriggered.tailUp) {
demoState.phaseTriggered.tailUp = true;
handlePointerUp();
}
screenPt = worldToScreen(tailBase[0], tailBase[1], tailBase[2]);
}
} else if (t < 15.8) {
// Phase 5 (12.2 - 15.8s): Rub the cat's head so it squints (^ ^) and purrs
pressing = t < 15.3;
const rubX = Math.sin((t - 12.2) * 8.5) * 0.32;
const headPt = evaluateDeformedPoint(rubX, 2.15, 0.22);
screenPt = worldToScreen(headPt[0], headPt[1], headPt[2]);
if (!demoState.phaseTriggered.rubStart) {
demoState.phaseTriggered.rubStart = true;
handlePointerDown(screenPt.x, screenPt.y);
}
if (pressing) {
handlePointerMove(screenPt.x, screenPt.y);
} else if (!demoState.phaseTriggered.rubEnd) {
demoState.phaseTriggered.rubEnd = true;
handlePointerUp();
}
} else {
// Phase 6 (15.8 - 20.0s): Showcase consistency slider & Drop from Above!
if (!demoState.phaseTriggered.drop1) {
demoState.phaseTriggered.drop1 = true;
setFirmnessValue(0.12); // Soft Pudding drop
triggerJellyDrop();
}
if (t > 18.0 && !demoState.phaseTriggered.firmSwitch) {
demoState.phaseTriggered.firmSwitch = true;
setFirmnessValue(0.88); // Switch to Firm Gummy & squeeze
jellyState.squashVelY = -3.2;
showStatusToast('Firm Gummy Bounce!');
}
const centerPt = evaluateDeformedPoint(0.0, 1.35, 0.55);
screenPt = worldToScreen(centerPt[0], centerPt[1], centerPt[2]);
}
demoPointerEl.style.left = `${screenPt.x}px`;
demoPointerEl.style.top = `${screenPt.y}px`;
demoPointerEl.classList.toggle('pressing', pressing);
}
// =========================================================================
// 11. UI CONTROLS & EVENT LISTENERS
// =========================================================================
const dropBtn = document.getElementById('drop-btn');
const firmnessSlider = document.getElementById('firmness-slider');
const firmnessBadge = document.getElementById('firmness-badge');
const lblPudding = document.getElementById('lbl-pudding');
const lblGummy = document.getElementById('lbl-gummy');
function updateFirmnessLabel(val) {
if (val < 0.2) firmnessBadge.textContent = 'Soft Pudding';
else if (val < 0.45) firmnessBadge.textContent = 'Silky Jelly';
else if (val < 0.7) firmnessBadge.textContent = 'Bouncy Jell-O';
else if (val < 0.88) firmnessBadge.textContent = 'Chewy Gummy';
else firmnessBadge.textContent = 'Firm Gummy';
}
function setFirmnessValue(val, withFeedbackJiggle) {
const clamped = Math.max(0, Math.min(1, parseFloat(val)));
jellyState.firmness = clamped;
jellyUniforms.uFirmness.value = clamped;
firmnessSlider.value = String(clamped);
updateFirmnessLabel(clamped);
safeSaveFirmness(clamped);
if (withFeedbackJiggle) {
jellyState.squashVelY -= 1.25;
sound.playPoke(0.45, clamped);
}
}
setFirmnessValue(jellyState.firmness, false);
dropBtn.addEventListener('pointerdown', (e) => {
e.stopPropagation();
stopDemoMode();
});
dropBtn.addEventListener('click', (e) => {
e.stopPropagation();
stopDemoMode();
sound.init();
triggerJellyDrop();
});
firmnessSlider.addEventListener('pointerdown', (e) => {
e.stopPropagation();
stopDemoMode();
sound.init();
});
firmnessSlider.addEventListener('input', (e) => {
stopDemoMode();
setFirmnessValue(e.target.value, true);
});
lblPudding.addEventListener('click', () => {
stopDemoMode();
sound.init();
setFirmnessValue(0.05, true);
showStatusToast('Soft Pudding Mode');
});
lblGummy.addEventListener('click', () => {
stopDemoMode();
sound.init();
setFirmnessValue(0.95, true);
showStatusToast('Firm Gummy Mode');
});
// Canvas pointer events (unified mouse + touch)
const canvasEl = renderer.domElement;
canvasEl.addEventListener('pointerdown', (e) => {
if (e.isTrusted) stopDemoMode();
if (interaction.isDown) return;
interaction.pointerId = e.pointerId;
try {
canvasEl.setPointerCapture(e.pointerId);
} catch (err) {}
handlePointerDown(e.clientX, e.clientY);
});
window.addEventListener('pointermove', (e) => {
if (demoState.active && !e.isTrusted) return;
if (interaction.isDown && interaction.pointerId !== null && e.pointerId !== interaction.pointerId) return;
handlePointerMove(e.clientX, e.clientY);
}, { passive: true });
function onEndPointer(e) {
if (interaction.pointerId !== null && e.pointerId !== interaction.pointerId) return;
interaction.pointerId = null;
handlePointerUp();
}
window.addEventListener('pointerup', onEndPointer, { passive: true });
window.addEventListener('pointercancel', onEndPointer, { passive: true });
// Any real touch anywhere ends #demo mode immediately
window.addEventListener('touchstart', (e) => {
if (e.isTrusted && demoState.active) {
stopDemoMode();
}
}, { passive: true });
window.addEventListener('hashchange', () => {
if (checkDemoHash()) startDemoMode();
else stopDemoMode();
});
window.addEventListener('resize', () => {
const w = window.innerWidth;
const h = window.innerHeight;
renderer.setSize(w, h);
updateCameraFraming();
rtWidth = Math.floor(w * renderer.getPixelRatio());
rtHeight = Math.floor(h * renderer.getPixelRatio());
refractionRT.setSize(rtWidth, rtHeight);
jellyUniforms.uResolution.value.set(rtWidth, rtHeight);
});
if (checkDemoHash()) {
startDemoMode();
} else {
// Gentle welcoming entrance wobble
jellyState.squashY = -0.14;
jellyState.squashVelY = 1.6;
}
// =========================================================================
// 12. MAIN ANIMATION & TWO-PASS REFRACTION RENDER LOOP
// =========================================================================
let lastTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min(0.05, Math.max(0.001, (now - lastTime) * 0.001));
lastTime = now;
jellyState.time += dt;
jellyUniforms.uTime.value = jellyState.time;
// 1. Update #demo choreography if active
if (demoState.active) {
updateDemoChoreography(dt);
}
// 2. Decay head-rub energy and smoothly interpolate purring & happy squinting
if (interaction.mode !== 'rubHead') {
jellyState.rubEnergy = Math.max(0.0, jellyState.rubEnergy - dt * 1.15);
}
jellyState.purrAmount += (jellyState.rubEnergy - jellyState.purrAmount) * Math.min(1.0, dt * 8.0);
jellyUniforms.uPurrGlow.value = jellyState.purrAmount;
sound.updatePurr(jellyState.purrAmount, dt, jellyState.firmness);
// 3. Natural eye blink timer + squint blending
jellyState.blinkTimer -= dt;
if (jellyState.blinkTimer <= 0.0) {
jellyState.blinkTimer = 3.2 + Math.random() * 2.8;
}
const blinkWindow = jellyState.blinkTimer < 0.16 ? Math.sin((jellyState.blinkTimer / 0.16) * Math.PI) : 0.0;
const impactWince = Math.min(0.85, Math.max(0.0, -jellyState.squashY * 2.1));
const targetSquint = Math.max(jellyState.purrAmount, blinkWindow * 0.9, impactWince);
jellyState.squintAmount += (targetSquint - jellyState.squintAmount) * Math.min(1.0, dt * 14.0);
eyeUniforms.uSquint.value = jellyState.squintAmount;
// 4. Smoothly track eyes toward finger/cursor position
jellyState.lookX += (jellyState.lookTargetX - jellyState.lookX) * Math.min(1.0, dt * 12.0);
jellyState.lookY += (jellyState.lookTargetY - jellyState.lookY) * Math.min(1.0, dt * 12.0);
eyeUniforms.uLook.value.set(jellyState.lookX, jellyState.lookY);
// 5. Step soft-body jelly physics & deform vertices, eyes, and internal bubbles
stepJellyPhysics(dt, interaction.isDown ? interaction.nodeIdx : -1);
updateAllDeformedGeometries();
// 6. PASS 1: Render backdrop, porcelain plate, and internal air bubbles into refractionRT
jellyCatMesh.visible = false;
leftEyeMesh.visible = false;
rightEyeMesh.visible = false;
noseMouthMesh.visible = false;
bubbleGroup.visible = true;
renderer.setRenderTarget(refractionRT);
renderer.render(scene, camera);
// 7. PASS 2: Render refractive orange jelly cat + eyes & nose/mouth to screen
renderer.setRenderTarget(null);
jellyCatMesh.visible = true;
leftEyeMesh.visible = true;
rightEyeMesh.visible = true;
noseMouthMesh.visible = true;
bubbleGroup.visible = false;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
})();
</script>
</body>
</html>
