Skip to content
VibeCodeBench
Back to the app

The code

Swim the Kelp Garden 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.)51.5 KB · 321 lines · loads cdn.jsdelivr.net/npm/three@0.164.1/build/three.module.js
Download
<!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="#103e49">
<title>Pelagic — The Kelp Garden</title>
<style>
:root{color-scheme:dark;--ivory:#f0eed9;--muted:#c3d7cc;--line:rgba(226,239,215,.24);--glass:rgba(11,47,54,.38)}
*{box-sizing:border-box}html,body{width:100%;height:100%;margin:0;overflow:hidden;background:#124d60}body{font-family:Inter,"Segoe UI",Arial,sans-serif;color:var(--ivory);-webkit-font-smoothing:antialiased;overscroll-behavior:none}button{font:inherit;color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent}button:focus-visible{outline:2px solid #e8c882;outline-offset:5px}button svg{width:20px;height:20px;flex:none;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}#ocean{position:fixed;inset:0;touch-action:none;cursor:grab}#ocean:active{cursor:grabbing}canvas{display:block;width:100%;height:100%;outline:none}.veil{position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse at 55% 42%,transparent 32%,rgba(3,26,38,.13) 77%,rgba(3,25,35,.4) 115%),linear-gradient(180deg,rgba(4,30,42,.26),transparent 24%,transparent 73%,rgba(4,30,40,.37))}.interface{position:fixed;inset:0;pointer-events:none}.topbar{position:absolute;top:max(30px,env(safe-area-inset-top));left:44px;right:40px;display:flex;align-items:center;justify-content:space-between;gap:20px}.brand{display:flex;align-items:center;gap:13px}.brand-mark{width:40px;height:40px;border:1px solid rgba(232,240,216,.55);border-radius:50%;display:grid;place-items:center}.brand-mark svg{width:26px;height:28px;fill:none;stroke:#e7edce;stroke-width:1.1;stroke-linecap:round}.brand-name{font-size:13px;letter-spacing:5px;font-weight:500}.brand-sub{font-size:8px;letter-spacing:2.5px;color:var(--muted);margin-top:6px}.top-actions{display:flex;gap:9px;pointer-events:auto}.glass-button{border:1px solid var(--line);background:var(--glass);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);min-height:46px;display:flex;align-items:center;justify-content:center;gap:10px;border-radius:30px;padding:0 18px;font-size:11px;letter-spacing:.5px;transition:background .25s,border-color .25s}.glass-button:active{background:rgba(107,153,130,.4);border-color:rgba(240,239,213,.6)}.help-button{width:46px;padding:0;font-family:Georgia,serif;font-size:19px}.hero{position:absolute;left:48px;top:clamp(134px,22vh,215px);transition:opacity 1.5s,transform 1.5s;max-width:450px;text-shadow:0 2px 25px rgba(4,34,40,.17)}.eyebrow{font-size:9px;letter-spacing:2.9px;display:flex;align-items:center;gap:11px;color:#d1dfc8}.eyebrow:before{content:"";width:24px;height:1px;background:#cad9b9}h1{font-family:"Palatino Linotype",Palatino,"Book Antiqua",Georgia,serif;font-size:clamp(48px,5.7vw,78px);font-weight:400;letter-spacing:-2.7px;line-height:1.05;margin:23px 0 19px}h1 em{font-weight:400;color:#e2dcae}.hero p{font-size:12px;line-height:1.9;color:#cfddd1;letter-spacing:.25px;margin:0;max-width:270px}.hero .little-wave{margin-top:27px;width:54px;height:12px;opacity:.65}.exploring .hero,.demo .hero{opacity:0;transform:translateY(-10px)}.depth-block{position:absolute;left:48px;bottom:max(43px,calc(env(safe-area-inset-bottom) + 24px));display:flex;align-items:center;gap:22px}.depth-rule{height:46px;width:13px;border-left:1px solid rgba(226,239,215,.4);position:relative;background:repeating-linear-gradient(0deg,transparent 0,transparent 10px,rgba(226,239,215,.35) 10px,rgba(226,239,215,.35) 11px) left center/5px 100% no-repeat}.depth-rule:after{content:"";position:absolute;left:-3px;top:22px;width:5px;height:5px;background:#dfcf90;border-radius:50%;box-shadow:0 0 9px #d9d69c}.depth-label{font-size:8px;letter-spacing:2.5px;color:#c1d4ca;margin-bottom:6px}.depth-number{font-family:Georgia,serif;font-size:28px;letter-spacing:-.7px;font-variant-numeric:tabular-nums}.depth-number small{font-family:"Segoe UI",sans-serif;font-size:11px;margin-left:5px;color:#c9d7ca;letter-spacing:1px}.compass{width:46px;height:46px;border:1px solid rgba(224,234,214,.23);border-radius:50%;position:relative;margin-left:6px}.compass:before,.compass:after{content:"";position:absolute;background:rgba(224,234,214,.25)}.compass:before{height:1px;width:7px;left:-1px;top:22px}.compass:after{height:1px;width:7px;right:-1px;top:22px}.compass-n{position:absolute;top:5px;left:0;right:0;text-align:center;font-size:7px;letter-spacing:1px}.needle{position:absolute;width:16px;height:24px;left:14px;top:15px;transform-origin:50% 7px}.needle:before{content:"";position:absolute;border-left:3px solid transparent;border-right:3px solid transparent;border-bottom:11px solid #dfc98b;left:5px;top:-5px}.needle:after{content:"";position:absolute;left:7px;top:6px;width:1px;height:10px;background:#b5c9bf}.swim-hint{position:absolute;bottom:max(37px,calc(env(safe-area-inset-bottom) + 18px));left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:14px;border:1px solid var(--line);background:rgba(10,45,51,.34);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);padding:14px 23px 14px 14px;border-radius:50px;white-space:nowrap;transition:opacity .6s}.swim-icon{width:40px;height:40px;border:1px solid rgba(231,235,206,.4);border-radius:50%;display:grid;place-items:center;position:relative}.swim-icon svg{width:20px;height:24px;fill:none;stroke:#e9e7ce;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round}.swimming .swim-icon:after{content:"";position:absolute;inset:-5px;border:1px solid rgba(232,231,204,.4);border-radius:50%;animation:ripple 1.8s infinite}.hint-title{font-size:12px;letter-spacing:.3px;margin-bottom:5px}.hint-sub{font-size:10px;color:#adc9c0;letter-spacing:.3px}.drift-button{position:absolute;right:43px;bottom:max(48px,calc(env(safe-area-inset-bottom) + 28px));pointer-events:auto;padding:0 19px;min-height:50px;background:rgba(194,210,176,.1)}.drift-button svg{width:17px;height:17px}.drift-button .arrow{font-size:19px;font-family:Georgia,serif;margin-left:8px;color:#d9d7b0}.demo-badge{position:absolute;left:50%;top:40px;transform:translateX(-50%) translateY(-8px);display:flex;align-items:center;gap:10px;font-size:9px;letter-spacing:2px;opacity:0;transition:opacity .5s,transform .5s;background:rgba(5,46,54,.3);padding:12px 18px;border:1px solid var(--line);border-radius:25px}.demo-badge:before{content:"";width:5px;height:5px;background:#dfd49e;border-radius:50%;box-shadow:0 0 9px #cabd7a}.demo .demo-badge{opacity:1;transform:translateX(-50%) translateY(0)}.demo .hint-title{color:#e4ddb8}.panel-shade{position:fixed;inset:0;background:rgba(3,26,36,.35);backdrop-filter:blur(7px);display:grid;place-items:center;z-index:10;padding:24px;opacity:0;visibility:hidden;transition:opacity .3s,visibility .3s}.panel-shade.open{opacity:1;visibility:visible}.guide{width:min(100%,400px);padding:34px;background:rgba(15,53,59,.96);border:1px solid rgba(230,232,199,.22);border-radius:22px;box-shadow:0 20px 100px #052b3d66}.guide h2{font-family:Georgia,serif;font-size:32px;font-weight:400;letter-spacing:-.7px;margin:14px 0 18px}.guide p{font-size:13px;line-height:1.9;color:#c2d4c8}.guide .guide-controls{padding:18px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin:22px 0;display:grid;gap:14px}.guide-controls div{display:flex;align-items:center;gap:15px;font-size:12px;color:#dce2cf}.guide-controls span{width:28px;height:28px;display:grid;place-items:center;border:1px solid var(--line);border-radius:50%;font-family:Georgia,serif;color:#d7ce9b}.guide button{width:100%;margin-top:12px;background:#d7d6b0;color:#153f45;border:0;border-radius:30px;min-height:48px;font-size:12px}.loading{position:fixed;inset:0;background:#124d60;display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;transition:opacity 1.2s,visibility 1.2s}.loading.done{opacity:0;visibility:hidden}.loading-mark{width:50px;height:50px;margin-bottom:24px;border:1px solid #b0c6a655;border-radius:50%;display:grid;place-items:center;animation:breathe 3s ease-in-out infinite}.loading-mark svg{width:30px;height:32px;fill:none;stroke:#d9ddba;stroke-width:1.2;stroke-linecap:round}.loading-title{font-family:Georgia,serif;font-size:24px;font-weight:400}.loading-copy{font-size:11px;line-height:1.8;letter-spacing:.4px;color:#b7cfc8;margin:12px 25px;text-align:center;max-width:330px}.loading button{margin-top:18px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@keyframes ripple{0%{opacity:.7;transform:scale(.94)}100%{opacity:0;transform:scale(1.25)}}@keyframes breathe{50%{opacity:.5;transform:translateY(-4px)}}
@media(max-width:760px){.topbar{top:max(22px,env(safe-area-inset-top));left:22px;right:20px}.brand-name{font-size:11px;letter-spacing:3px}.brand-sub{font-size:7px;letter-spacing:1.5px}.brand{gap:10px}.brand-mark{width:35px;height:35px}.top-actions{gap:7px}.sound-label{display:none}#sound{width:44px;padding:0}.help-button{min-height:44px;width:44px}.hero{left:26px;top:145px;max-width:290px}h1{font-size:51px;letter-spacing:-2px;margin-top:20px}.eyebrow{font-size:7px;letter-spacing:2px}.hero p{font-size:11px;max-width:220px}.depth-block{left:25px;bottom:max(25px,calc(env(safe-area-inset-bottom) + 15px));gap:12px}.depth-number{font-size:24px}.depth-label{font-size:7px;letter-spacing:1.7px}.depth-rule{height:38px}.compass{display:none}.drift-button{right:21px;bottom:max(26px,calc(env(safe-area-inset-bottom) + 16px));font-size:10px;min-height:45px;padding:0 15px;gap:8px}.drift-button .arrow{display:none}.swim-hint{bottom:max(100px,calc(env(safe-area-inset-bottom) + 88px));padding:11px 20px 11px 12px;gap:12px}.hint-title{font-size:11px}.hint-sub{font-size:9px}.swim-icon{width:34px;height:34px}.demo-badge{top:88px;font-size:7px;white-space:nowrap}.guide{padding:28px}.hero .little-wave{margin-top:20px}}
@media(max-height:540px) and (min-width:650px){.hero{top:110px}h1{font-size:45px}.hero p,.little-wave{display:none}.swim-hint{bottom:20px;padding:9px 18px 9px 10px}.depth-block{bottom:25px}.drift-button{bottom:26px}.topbar{top:22px}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important}}
</style>
</head>
<body>
<main id="ocean" aria-label="An explorable underwater kelp garden. Hold to swim and drag to turn."></main>
<div class="veil"></div>
<div class="interface">
  <header class="topbar">
    <div class="brand"><div class="brand-mark"><svg viewBox="0 0 32 34" aria-hidden="true"><path d="M16 29C10 21 21 14 15 5M15 23C7 23 5 17 6 13C13 13 14 18 15 23ZM16 16C24 17 27 11 26 7C19 7 17 11 16 16ZM15 10C10 10 9 6 10 3"/></svg></div><div><div class="brand-name">PELAGIC</div><div class="brand-sub">THE KELP GARDEN</div></div></div>
    <div class="top-actions"><button class="glass-button" id="sound" aria-label="Turn on ocean ambience" aria-pressed="false"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5 6 9H3v6h3l5 4V5Z"/><g id="sound-waves" style="display:none"><path d="M15 8c2 2 2 6 0 8M18 5c4 4 4 10 0 14"/></g><path id="sound-mute" d="m16 9 5 6m0-6-5 6"/></svg><span class="sound-label">Sound off</span></button><button class="glass-button help-button" id="help" aria-label="How to explore">?</button></div>
  </header>
  <section class="hero"><div class="eyebrow">A SMALL ESCAPE, BENEATH THE SURFACE</div><h1>Let the world<br><em>slow down.</em></h1><p>Wander a living underwater garden.<br>There’s nowhere you need to be.</p><svg class="little-wave" viewBox="0 0 60 12" fill="none" aria-hidden="true"><path d="M0 6c5-7 10 7 15 0s10 7 15 0 10 7 15 0 10 7 15 0" stroke="#d9d7ae" stroke-width="1"/></svg></section>
  <div class="demo-badge">DRIFTING WITH THE CURRENT</div>
  <div class="depth-block"><div class="depth-rule"></div><div><div class="depth-label">BELOW THE SURFACE</div><div class="depth-number"><span id="depth">17.7</span><small>m</small></div></div><div class="compass" aria-label="Compass"><span class="compass-n">N</span><div class="needle" id="needle"></div></div></div>
  <div class="swim-hint"><div class="swim-icon"><svg viewBox="0 0 24 28" aria-hidden="true"><rect x="5.5" y="2" width="13" height="22" rx="6.5"/><path d="M12 2v8M9.5 7.5H12"/><path d="m8.5 19 3.5 3 3.5-3"/></svg></div><div><div class="hint-title" id="hint-title">Hold to swim forward</div><div class="hint-sub" id="hint-sub">Move your mouse to gently turn</div></div></div>
  <button class="glass-button drift-button" id="drift"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2 8c3-4 6 4 10 0s7 4 10 0M2 15c3-4 6 4 10 0s7 4 10 0"/></svg><span id="drift-label">Drift for a while</span><span class="arrow">↗</span></button>
</div>
<div class="panel-shade" id="guide-shade"><section class="guide" role="dialog" aria-modal="true" aria-labelledby="guide-title"><div class="eyebrow">MAKE YOURSELF AT HOME</div><h2 id="guide-title">A gentler kind of exploring.</h2><p>Follow the light through the kelp. Find the old wooden wreck, slip beneath the stone arch, or simply watch the rays go by.</p><div class="guide-controls"><div><span>1</span>Press and hold anywhere to glide ahead.</div><div><span>2</span>While holding, drag to look and turn.</div><div><span>3</span>Let go to stop and take it all in.</div></div><p>Look up or down as you swim to change depth. The rocks and the wreck are solid. “Drift for a while” takes you on a quiet 20-second loop.</p><button id="close-guide">Back to the garden</button></section></div>
<div class="loading" id="loading"><div class="loading-mark"><svg viewBox="0 0 32 34" aria-hidden="true"><path d="M16 30C10 22 22 14 15 4M15 23C7 23 5 17 6 13C13 13 14 18 15 23ZM16 16C24 17 27 11 26 7C19 7 17 11 16 16Z"/></svg></div><div class="loading-title" id="loading-title">A little further from the everyday.</div><div class="loading-copy" id="loading-copy">Letting the light settle…</div><button class="glass-button" id="retry" hidden style="display:none">Try again</button></div>
<div id="status" class="sr-only" aria-live="polite"></div>
<script type="module">
const loading=document.getElementById('loading');
try {
  const THREE=await import('https://cdn.jsdelivr.net/npm/three@0.164.1/build/three.module.js');
  buildGarden(THREE);
} catch(error) {
  document.getElementById('loading-title').textContent='The garden is just out of reach.';
  document.getElementById('loading-copy').textContent='This garden needs WebGL and a connection to load its 3D library. Please try again when both are available.';
  const retry=document.getElementById('retry');retry.hidden=false;retry.style.display='flex';retry.onclick=()=>location.reload();
  console.error(error);
}
function buildGarden(T){
  const coarse=matchMedia('(pointer: coarse)').matches;
  const reduced=matchMedia('(prefers-reduced-motion: reduce)').matches;
  const host=document.getElementById('ocean');
  const renderer=new T.WebGLRenderer({antialias:true,alpha:false,powerPreference:'high-performance'});
  renderer.setPixelRatio(Math.min(devicePixelRatio,coarse?1.6:1.85));
  renderer.setSize(innerWidth,innerHeight);
  renderer.outputColorSpace=T.SRGBColorSpace;
  renderer.toneMapping=T.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;
  renderer.shadowMap.enabled=!coarse;renderer.shadowMap.type=T.PCFSoftShadowMap;
  host.appendChild(renderer.domElement);
  renderer.domElement.setAttribute('aria-label','Underwater garden. Press and hold to swim; drag to turn.');
  const scene=new T.Scene();scene.background=new T.Color('#10556b');scene.fog=new T.FogExp2('#10556b',.0215);
  const camera=new T.PerspectiveCamera(63,innerWidth/innerHeight,.12,150);camera.rotation.order='YXZ';
  const seaTime={value:0};const UP=new T.Vector3(0,1,0);
  let seed=87123;
  function rand(){seed=(Math.imul(1664525,seed)+1013904223)|0;return(seed>>>0)/4294967296;}
  function between(a,b){return a+(b-a)*rand();}
  function sandY(x,z){return -.35+.32*Math.sin(x*.14+z*.045)*Math.sin(z*.12)+.16*Math.cos(x*.3+z*.12);}
  scene.add(new T.HemisphereLight('#a8e1ca','#1b5465',1.85));
  const sun=new T.DirectionalLight('#ffe3a6',2.7);sun.position.set(-12,36,8);sun.target.position.set(0,0,-20);scene.add(sun,sun.target);
  sun.castShadow=true;sun.shadow.mapSize.set(2048,2048);Object.assign(sun.shadow.camera,{left:-36,right:36,top:30,bottom:-42,near:1,far:85});sun.shadow.bias=-.0005;sun.shadow.normalBias=.05;sun.shadow.radius=3;
  const fill=new T.DirectionalLight('#52b5bb',.7);fill.position.set(20,12,-40);scene.add(fill);
  function seaMaterial(color,grain=false,vertexColors=false){
    const m=new T.MeshStandardMaterial({color,roughness:.89,metalness:0,vertexColors});
    m.onBeforeCompile=s=>{
      s.uniforms.uSeaTime=seaTime;
      s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nvarying vec3 vOceanWorld;');
      s.vertexShader=s.vertexShader.replace('#include <project_vertex>','#include <project_vertex>\nvOceanWorld=(modelMatrix*vec4(transformed,1.0)).xyz;');
      s.fragmentShader=s.fragmentShader.replace('#include <common>','#include <common>\nvarying vec3 vOceanWorld;uniform float uSeaTime;');
      s.fragmentShader=s.fragmentShader.replace('#include <color_fragment>',`#include <color_fragment>
        vec2 q=vOceanWorld.xz*.78+vec2(uSeaTime*.095,-uSeaTime*.075);
        float w=sin(q.x+sin(q.y*1.15+uSeaTime*.13)*1.8)+sin(q.y*1.36+cos(q.x*.83-uSeaTime*.12)*1.6);
        float caustic=pow(max(0.0,1.0-abs(w)*.86),7.0);
        caustic*=.65+.35*sin(q.x*.43+q.y*.51+uSeaTime*.21);
        diffuseColor.rgb*=.93+caustic*.30;
        diffuseColor.rgb+=vec3(.23,.25,.115)*caustic*.30;
        ${grain?'float g=sin(vOceanWorld.x*27.0+sin(vOceanWorld.y*15.0+vOceanWorld.z*3.0)*2.5);diffuseColor.rgb*=.91+.09*g;':''}`);
    };m.customProgramCacheKey=()=>`sea-${grain}-${vertexColors}`;return m;
  }
  function data(){return {p:[],c:[],i:[],flex:[],phase:[]};}
  function vertex(d,x,y,z,c,flex=0,phase=0){const n=d.p.length/3;d.p.push(x,y,z);d.c.push(c.r,c.g,c.b);d.flex.push(flex);d.phase.push(phase);return n;}
  function geometry(d){const g=new T.BufferGeometry();g.setAttribute('position',new T.Float32BufferAttribute(d.p,3));g.setAttribute('color',new T.Float32BufferAttribute(d.c,3));g.setAttribute('aFlex',new T.Float32BufferAttribute(d.flex,1));g.setAttribute('aPhase',new T.Float32BufferAttribute(d.phase,1));g.setIndex(d.i);g.computeVertexNormals();g.computeBoundingSphere();return g;}
  function tube(d,a,b,r0,r1,color,sides=6,sway=null){
    const axis=new T.Vector3().subVectors(b,a).normalize();
    const tangent=new T.Vector3().crossVectors(axis,Math.abs(axis.y)>.93?new T.Vector3(1,0,0):UP).normalize();
    const bitangent=new T.Vector3().crossVectors(axis,tangent).normalize();const base=d.p.length/3;
    for(let j=0;j<2;j++){const p=j?b:a,r=j?r1:r0;for(let k=0;k<=sides;k++){const angle=k/sides*Math.PI*2;const v=p.clone().addScaledVector(tangent,Math.cos(angle)*r).addScaledVector(bitangent,Math.sin(angle)*r);vertex(d,v.x,v.y,v.z,color,sway?Math.max(0,(v.y-sway.base)/sway.height)*sway.amount:0,sway?sway.phase:0);}}
    for(let k=0;k<sides;k++){const a0=base+k,b0=base+sides+1+k;d.i.push(a0,b0,a0+1,a0+1,b0,b0+1);}
  }
  const groundGeo=new T.PlaneGeometry(180,180,115,115);groundGeo.rotateX(-Math.PI/2);
  const groundPos=groundGeo.attributes.position,groundColors=[];
  for(let i=0;i<groundPos.count;i++){const x=groundPos.getX(i),z=groundPos.getZ(i);groundPos.setY(i,sandY(x,z));const shade=.90+.07*Math.sin(x*.41+z*.28)+rand()*.05;const c=new T.Color('#b8b084').multiplyScalar(shade);groundColors.push(c.r,c.g,c.b);}
  groundGeo.setAttribute('color',new T.Float32BufferAttribute(groundColors,3));groundGeo.computeVertexNormals();
  const ground=new T.Mesh(groundGeo,seaMaterial('#ffffff',false,true));ground.receiveShadow=true;scene.add(ground);
  const colliders=[];
  const rockGeos=[];
  for(let n=0;n<4;n++){const g=new T.IcosahedronGeometry(1,2),p=g.attributes.position,c=[];for(let i=0;i<p.count;i++){const x=p.getX(i),y=p.getY(i),z=p.getZ(i);const f=1+.07*Math.sin(x*8+n*3+z*5)*Math.cos(y*7-z*6+n);p.setXYZ(i,x*f,y*f,z*f);const col=new T.Color().lerpColors(new T.Color('#416e70'),new T.Color('#91a487'),T.MathUtils.clamp((y+1)/2,0,1));col.multiplyScalar(.9+.12*Math.sin(x*12+z*9));c.push(col.r,col.g,col.b);}g.setAttribute('color',new T.Float32BufferAttribute(c,3));g.computeVertexNormals();rockGeos.push(g);}
  const rockMat=seaMaterial('#ffffff',false,true);
  function rock(x,y,z,sx,sy,sz,yaw=0,solid=true){const m=new T.Mesh(rockGeos[Math.floor(rand()*4)],rockMat);m.position.set(x,sandY(x,z)+y,z);m.scale.set(sx,sy,sz);m.rotation.y=yaw;m.castShadow=true;m.receiveShadow=true;scene.add(m);if(solid)colliders.push({type:'ellipsoid',center:m.position.clone(),r:new T.Vector3(sx*1.09,sy*1.09,sz*1.09),yaw});return m;}
  rock(-11,1.1,4,4.0,2.0,3.0,.6);rock(-17,1.1,-6,4.7,2.7,4,.2);rock(13,1.1,7,3.7,2.0,3.4,-.3);rock(17,1.7,-5,5,3.1,3.5,.4);
  rock(-21,1.5,-34,4.2,3.3,4,.7);rock(20,1.6,-35,5,3.0,4.8,.2);rock(-26,1,-15,4,2.4,6,.1);
  for(let i=0;i<26;i++){const side=rand()<.5?-1:1,x=side*between(20,46),z=between(-65,20),r=between(1.3,4);rock(x,r*.35,z,r,r*between(.55,1),r*between(.8,1.5),rand()*6);}
  // An open, swim-through arch: each stone has its own solid boundary.
  rock(4.3,1.7,-23,2.1,2.5,2.4,.2);rock(12.8,1.7,-23.8,2.0,2.5,2.5,-.2);
  for(let i=0;i<9;i++){const angle=i/8*Math.PI;const x=8.55+4.3*Math.cos(angle),y=2.5+5.5*Math.sin(angle),z=-23.4+.35*Math.sin(angle*2);rock(x,y,z,1.55+rand()*.25,1.7+rand()*.2,1.9+rand()*.4,between(-.5,.5));}
  rock(3.1,.6,-18.4,2,1.1,1.5,.3);rock(14.6,.8,-20,2.5,1.4,2,.5);
  // Small stones are below the swimmer's clearance.
  const pebble=new T.InstancedMesh(rockGeos[0],rockMat,160);const dummy=new T.Object3D();
  for(let i=0;i<160;i++){const x=between(-36,36),z=between(-52,22),s=between(.07,.38);dummy.position.set(x,sandY(x,z)+s*.35,z);dummy.rotation.set(rand(),rand()*6,rand());dummy.scale.set(s,s*.6,s*.85);dummy.updateMatrix();pebble.setMatrixAt(i,dummy.matrix);}pebble.receiveShadow=true;scene.add(pebble);
  // Long kelp ribbons share one animated mesh; roots stay planted.
  const kelpData=data();
  function kelp(x,z,height,phase){
    const base=sandY(x,z)+.03,leanX=between(-.7,.7),leanZ=between(-.5,.5),shade=rand();
    const stipe=new T.Color('#7e8238');const sway={base,height,amount:height*.13,phase};
    function stemAt(t){return new T.Vector3(x+leanX*t+Math.sin(t*4+phase)*.18*t,base+t*height,z+leanZ*t+Math.sin(t*3+phase)*.17*t);}
    let previous=stemAt(0);
    for(let j=1;j<=15;j++){const next=stemAt(j/15);tube(kelpData,previous,next,.065*(1-(j-1)/20),.065*(1-j/20),stipe,5,sway);previous=next;}
    const count=Math.floor(height*1.35);
    for(let j=0;j<count;j++){
      const t0=.09+j/count*.87,root=stemAt(t0),angle=j*2.399+phase;
      const length=between(1.25,2.6)*(1-.22*t0),width=between(.31,.65),start=kelpData.p.length/3;
      const leafColor=new T.Color().lerpColors(new T.Color('#376b38'),new T.Color('#b0a24b'),.15+shade*.52+rand()*.22);
      for(let s=0;s<=9;s++){const u=s/9;const spread=Math.pow(Math.sin(u*Math.PI),.75)*width;
        for(let k=-1;k<=1;k++){
          const side=k*spread*.5,along=u*length;
          const px=root.x+Math.cos(angle)*along-Math.sin(angle)*side;
          const pz=root.z+Math.sin(angle)*along+Math.cos(angle)*side;
          const py=root.y+Math.sin(u*Math.PI)*.25-u*length*.53+Math.sin(u*16+phase)*.065*Math.abs(k);
          const c=leafColor.clone().multiplyScalar(k===0?1.06:.91);
          vertex(kelpData,px,py,pz,c,Math.max(0,(py-base)/height)*sway.amount+u*.12,phase);
        }
      }
      for(let s=0;s<9;s++)for(let k=0;k<2;k++){const a=start+s*3+k,b=a+3;kelpData.i.push(a,b,a+1,a+1,b,b+1);}
    }
  }
  const plantSpots=[[-8,7,17],[-11,0,19],[-8,-6,14],[-14,8,20],[-16,-9,18],[10,9,19],[12,1,16],[15,-6,20],[18,5,18],[16,-14,15],[-19,-23,17],[3,-27,13],[14,-28,18],[-22,-40,20],[19,-42,19]];
  for(const [x,z,h] of plantSpots)kelp(x,z,h,rand()*6.28);
  const plantCount=coarse?58:87;
  for(let i=0;i<plantCount;i++){const z=between(-64,20),side=rand()<.5?-1:1;let x=side*between(13,35);if(z<-38)x=between(-35,35);kelp(x,z,between(8,20.5),rand()*6.28);}
  // Fine eelgrass follows the same current.
  for(let i=0;i<150;i++){const x=between(-32,32),z=between(-48,18);if(Math.abs(x)<4&&z> -15&&rand()<.85)continue;const base=sandY(x,z);for(let j=0;j<5;j++){const h=between(.4,1.25),a=rand()*6.28,w=.035,idx=kelpData.p.length/3,c=new T.Color('#4e7950');for(let s=0;s<=4;s++){const t=s/4;for(let k=-1;k<=1;k+=2)vertex(kelpData,x+Math.sin(a)*h*t*t*.55+Math.cos(a)*k*w*(1-t),base+h*t,z+Math.cos(a)*h*t*t*.55-Math.sin(a)*k*w*(1-t),c,t*.25,a);}for(let s=0;s<4;s++){const a0=idx+s*2;kelpData.i.push(a0,a0+2,a0+1,a0+1,a0+2,a0+3);}}}
  const kelpMat=new T.MeshStandardMaterial({color:'#ffffff',vertexColors:true,side:T.DoubleSide,roughness:.71,metalness:0});
  kelpMat.onBeforeCompile=s=>{s.uniforms.uSeaTime=seaTime;s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nuniform float uSeaTime;attribute float aFlex;attribute float aPhase;');s.vertexShader=s.vertexShader.replace('#include <begin_vertex>',`#include <begin_vertex>
    transformed.x+=sin(uSeaTime*.62+aPhase+position.y*.20)*aFlex*.67;
    transformed.z+=cos(uSeaTime*.47+aPhase+position.y*.23)*aFlex*.43;`);};
  const kelpMesh=new T.Mesh(geometry(kelpData),kelpMat);kelpMesh.frustumCulled=false;scene.add(kelpMesh);
  // Warm branching coral, assembled into a single geometry.
  const coralData=data();
  function coral(x,z,scale,shade){const root=new T.Vector3(x,sandY(x,z)+.04,z),yaw=rand()*Math.PI,col=new T.Color(shade);
    function grow(p,angle,len,r,depth){const q=p.clone().add(new T.Vector3(Math.sin(angle)*Math.cos(yaw),Math.cos(angle),Math.sin(angle)*Math.sin(yaw)).multiplyScalar(len));tube(coralData,p,q,r,r*.62,col,6);if(depth>0){grow(q,angle-between(.28,.57),len*.72,r*.63,depth-1);grow(q,angle+between(.28,.57),len*.73,r*.63,depth-1);}else{tube(coralData,q,q.clone().add(new T.Vector3(0,.075*scale,0)),r*.85,.006,col.clone().multiplyScalar(1.18),6);}}
    grow(root,between(-.12,.12),scale*.67,scale*.09,3);
    grow(root,between(-.5,.5),scale*.52,scale*.065,2);
  }
  const coralSpots=[[-6,5,1.3],[-7,3,1.7],[-13,5,1.2],[-15,0,1.8],[7,5,1.1],[8,2,1.7],[12,4,1.1],[15,-8,1.7],[-6,-14,1.1],[2,-20,1.2],[14,-20,1.6],[5,-29,1],[-20,-19,1.4]];
  const coralColors=['#d88c48','#c07539','#dfa14d','#b77c38'];
  for(let i=0;i<coralSpots.length;i++){const [x,z,s]=coralSpots[i];coral(x,z,s,coralColors[i%4]);coral(x+.6,z-.45,s*.68,coralColors[(i+1)%4]);}
  const coralMesh=new T.Mesh(geometry(coralData),seaMaterial('#ffffff',false,true));coralMesh.castShadow=true;scene.add(coralMesh);
  const shelfMat=seaMaterial('#b77e3a');
  for(let i=0;i<16;i++){const side=i<9?-1:1,x=side<0?between(-12,-8):between(12,14),z=side<0?between(2,5):between(-25,-22);const y=sandY(x,z)+between(.3,1.4);const shelf=new T.Mesh(new T.SphereGeometry(1,14,8),shelfMat);shelf.scale.set(between(.35,.85),.10,between(.3,.7));shelf.position.set(x,y,z);shelf.rotation.z=between(-.25,.25);scene.add(shelf);}
  // The old wreck: curved planking, open ribs, broken deck, masts and rigging.
  const ship=new T.Group();ship.position.set(-13,sandY(-13,-28)+.15,-28);ship.rotation.y=-.25;scene.add(ship);
  const shipYaw=ship.rotation.y;
  const wood=seaMaterial('#8c6b3c',true),woodDark=seaMaterial('#57472f',true),woodLight=seaMaterial('#a18448',true);
  const plankData=data();
  for(const side of [-1,1])for(let row=0;row<8;row++){
    const c=new T.Color().lerpColors(new T.Color('#695033'),new T.Color('#a68042'),rand());
    for(let j=0;j<32;j++){
      const x0=-8.9+j/32*17.8,x1=-8.9+(j+1)/32*17.8;
      if(side===1&&row<5&&x0>-.9&&x0<1.7)continue;
      if(row===7&&((side===1&&x0>3&&x0<5.4)||(side===-1&&x0< -5)))continue;
      const start=plankData.p.length/3;
      for(const [x,top] of [[x0,0],[x1,0],[x0,1],[x1,1]]){
        const lift=.85*Math.pow(Math.abs(x)/9,3),y=.2+row*.415+top*.37+lift;
        const beam=2.65*Math.pow(Math.max(.01,1-Math.pow(x/9.25,2)),.58)*(.52+.48*((row+top)/8));
        vertex(plankData,x,y,side*beam,c);
      }
      if(side===1)plankData.i.push(start,start+1,start+2,start+2,start+1,start+3);else plankData.i.push(start,start+2,start+1,start+2,start+3,start+1);
    }
  }
  const planks=new T.Mesh(geometry(plankData),seaMaterial('#ffffff',true,true));planks.material.side=T.DoubleSide;planks.castShadow=true;planks.receiveShadow=true;ship.add(planks);
  function worldShip(v){return v.clone().applyAxisAngle(UP,shipYaw).add(ship.position);}
  function shipBeam(a,b,r,material=woodDark,solid=true){const av=new T.Vector3(...a),bv=new T.Vector3(...b),length=av.distanceTo(bv);const m=new T.Mesh(new T.CylinderGeometry(r*.8,r,length,7),material);m.position.copy(av).add(bv).multiplyScalar(.5);m.quaternion.setFromUnitVectors(UP,bv.clone().sub(av).normalize());m.castShadow=true;ship.add(m);if(solid)colliders.push({type:'capsule',a:worldShip(av),b:worldShip(bv),r:r+.04});return m;}
  for(let x=-7.5;x<=7.5;x+=1.3){const width=2.6*Math.pow(1-Math.pow(x/9.4,2),.58);shipBeam([x,.32,0],[x,1.35,width*.76],.10,woodDark,false);shipBeam([x,1.35,width*.76],[x,3.6,width],.095,woodDark,false);shipBeam([x,.32,0],[x,1.35,-width*.76],.10,woodDark,false);shipBeam([x,1.35,-width*.76],[x,3.6,-width],.095,woodDark,false);}
  for(let i=0;i<12;i++){const z=-1.9+i*.34;if(i===4||i===8)continue;const length=between(10.5,14.5);const board=new T.Mesh(new T.BoxGeometry(length,.11,.30),i%3===0?woodLight:wood);board.position.set(between(-.6,.6),3.12+rand()*.06,z);board.rotation.z=between(-.012,.012);board.castShadow=true;board.receiveShadow=true;ship.add(board);}
  shipBeam([-8.8,1.1,0],[-8.8,4.2,0],.18,wood);shipBeam([8.7,1.1,0],[9.4,4.3,0],.17,wood);shipBeam([-8.7,.25,0],[8.6,.25,0],.21,woodDark,false);
  shipBeam([-3.25,2.8,0],[-3.5,12.2,.1],.17,wood);shipBeam([3.1,2.9,0],[3.45,9.0,-.1],.14,wood);
  shipBeam([-3.4,9.3,-2.7],[-3.4,9.3,2.7],.08,woodLight);shipBeam([3.4,7.2,-2.3],[3.4,7.2,2.4],.065,woodLight);
  shipBeam([-.8,3.7,.4],[6.3,5.1,3.4],.13,wood);shipBeam([-7,3.9,1.6],[-2.8,3.8,2.6],.085,wood);
  for(const x of [-7,-5.5,5.6,7.2]){shipBeam([x,3,2.1],[x,4.0,2.1],.055,woodLight,false);}
  const ropeMat=seaMaterial('#77765a');
  function rope(points){const vectors=points.map(p=>new T.Vector3(...p));const curve=new T.CatmullRomCurve3(vectors);const m=new T.Mesh(new T.TubeGeometry(curve,18,.019,4,false),ropeMat);ship.add(m);const p=curve.getPoints(8);for(let i=0;i<p.length-1;i++)colliders.push({type:'capsule',a:worldShip(p[i]),b:worldShip(p[i+1]),r:.025});}
  rope([[-8.6,3.8,0],[-6.4,7.3,.2],[-3.5,12.1,.1]]);rope([[-3.5,12.1,.1],[.1,9.3,.1],[3.45,9,0],[8.8,4.0,0]]);
  rope([[-3.5,11.7,0],[-3.2,7.2,1.5],[-3.0,3.3,2.5]]);
  const sailGeo=new T.BufferGeometry();sailGeo.setAttribute('position',new T.Float32BufferAttribute([-3.45,10.8,.13,-3.3,5.9,.15,-1.9,6.5,.2,-1.6,6.1,.2,-.5,7.0,.18,.2,6.8,.1,1.4,7.5,.08],3));sailGeo.setIndex([0,1,2,0,2,3,0,3,4,0,4,5,0,5,6]);sailGeo.computeVertexNormals();const sailMat=new T.MeshStandardMaterial({color:'#a2aa79',side:T.DoubleSide,roughness:1,transparent:true,opacity:.69});sailMat.onBeforeCompile=s=>{s.uniforms.uSeaTime=seaTime;s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nuniform float uSeaTime;');s.vertexShader=s.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\ntransformed.z+=sin(position.y*1.8+uSeaTime*.65)*.10;');};ship.add(new T.Mesh(sailGeo,sailMat));
  colliders.push({type:'box',center:worldShip(new T.Vector3(0,2.25,0)),half:new T.Vector3(9.45,2.35,2.95),yaw:shipYaw});
  // Fish share a moving formation and heading, including the turn of each school.
  const fishData=data();const fishColor=new T.Color('#ffffff');const rings=[[-.39,.025],[-.27,.115],[-.02,.17],[.22,.14],[.39,.055],[.43,.008]];
  for(let i=0;i<rings.length;i++)for(let j=0;j<=10;j++){const a=j/10*Math.PI*2;vertex(fishData,rings[i][0],Math.cos(a)*rings[i][1],Math.sin(a)*rings[i][1]*.62,fishColor);}
  for(let i=0;i<rings.length-1;i++)for(let j=0;j<10;j++){const a=i*11+j,b=a+11;fishData.i.push(a,b,a+1,a+1,b,b+1);}
  function fishTri(a,b,c){const n=fishData.p.length/3;for(const p of [a,b,c])vertex(fishData,...p,fishColor);fishData.i.push(n,n+1,n+2);}
  fishTri([-.34,0,0],[-.68,.24,0],[-.57,0,0]);fishTri([-.34,0,0],[-.57,0,0],[-.68,-.24,0]);fishTri([-.15,.12,0],[.08,.30,0],[.18,.12,0]);fishTri([0,-.09,.04],[-.1,-.23,.17],[.18,-.08,.03]);
  const fishGeo=geometry(fishData);const fishMat=new T.MeshStandardMaterial({color:'#ffffff',roughness:.43,metalness:.16,side:T.DoubleSide});
  fishMat.onBeforeCompile=s=>{s.uniforms.uSeaTime=seaTime;s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nuniform float uSeaTime;');s.vertexShader=s.vertexShader.replace('#include <begin_vertex>',`#include <begin_vertex>
    transformed.z+=smoothstep(.15,.65,-position.x)*sin(uSeaTime*7.0+instanceMatrix[3].x*.85)*.13;`);};
  const schoolConfigs=[{n:coarse?34:46,x:-1,y:8.2,z:-13,rx:6.5,rz:3.6,speed:.14,phase:0,color:'#d9b75c'},{n:coarse?27:37,x:5,y:5.6,z:-34,rx:7,rz:3,speed:.12,phase:2.5,color:'#79b9ac'},{n:coarse?18:24,x:-14,y:4.6,z:-10,rx:4,rz:3,speed:-.17,phase:1.6,color:'#d78e49'}];
  const totalFish=schoolConfigs.reduce((a,s)=>a+s.n,0),fish=new T.InstancedMesh(fishGeo,fishMat,totalFish);fish.instanceMatrix.setUsage(T.DynamicDrawUsage);fish.frustumCulled=false;scene.add(fish);
  const eyeMat=new T.MeshStandardMaterial({color:'#133f44',roughness:.25});const eyes=new T.InstancedMesh(new T.SphereGeometry(.026,6,4),eyeMat,totalFish*2);eyes.frustumCulled=false;scene.add(eyes);
  const fishStates=[];
  for(const school of schoolConfigs)for(let i=0;i<school.n;i++){const id=fishStates.length;const c=new T.Color(school.color).multiplyScalar(between(.8,1.2));fish.setColorAt(id,c);fishStates.push({school,along:between(-3.8,3.8),side:between(-1.5,1.5),height:between(-1.15,1.15),scale:between(.64,1.1),phase:rand()*6.28});}
  const fishAxis=new T.Vector3(1,0,0),forward=new T.Vector3(),sideVec=new T.Vector3(),fishPos=new T.Vector3(),fishQuat=new T.Quaternion(),eyeOffset=new T.Vector3();
  function animateFish(t){for(let i=0;i<fishStates.length;i++){const f=fishStates[i],s=f.school,a=t*s.speed+s.phase+f.along*.022;
    forward.set(Math.cos(a)*s.rx*s.speed,.04*Math.cos(t*.3+f.phase),-Math.sin(a)*s.rz*s.speed).normalize();sideVec.crossVectors(forward,UP).normalize();
    fishPos.set(s.x+Math.sin(a)*s.rx,s.y+Math.sin(a*.8)*.55+f.height,s.z+Math.cos(a)*s.rz).addScaledVector(forward,f.along).addScaledVector(sideVec,f.side+Math.sin(t*.9+f.phase)*.12);
    fishQuat.setFromUnitVectors(fishAxis,forward);dummy.position.copy(fishPos);dummy.quaternion.copy(fishQuat);dummy.scale.setScalar(f.scale);dummy.updateMatrix();fish.setMatrixAt(i,dummy.matrix);
    for(let j=0;j<2;j++){eyeOffset.set(.285,.052,j?-.081:.081).multiplyScalar(f.scale).applyQuaternion(fishQuat).add(fishPos);dummy.position.copy(eyeOffset);dummy.scale.setScalar(f.scale);dummy.updateMatrix();eyes.setMatrixAt(i*2+j,dummy.matrix);}
  }fish.instanceMatrix.needsUpdate=true;eyes.instanceMatrix.needsUpdate=true;}
  // Sculpted manta wings gently flex in the current.
  const rays=[];
  function makeRay(scale,phase){const group=new T.Group(),d=data(),col=new T.Color('#386a68');const widths=[.13,.61,1,.82,.45,.065];
    for(let row=0;row<widths.length;row++){const v=row/(widths.length-1);for(let j=0;j<=20;j++){const u=j/20*2-1,x=u*2.9*widths[row],z=-1.45+v*2.8,y=.15*(1-u*u)-.12*Math.abs(u);const c=col.clone().multiplyScalar(.82+.3*(1-Math.abs(u)));vertex(d,x,y,z,c,Math.pow(Math.abs(x)/2.9,1.5),phase);}}
    for(let row=0;row<widths.length-1;row++)for(let j=0;j<20;j++){const a=row*21+j,b=a+21;d.i.push(a,a+1,b,a+1,b+1,b);}
    const m=new T.MeshStandardMaterial({color:'#ffffff',vertexColors:true,side:T.DoubleSide,roughness:.6});m.onBeforeCompile=s=>{s.uniforms.uSeaTime=seaTime;s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nuniform float uSeaTime;attribute float aFlex;attribute float aPhase;');s.vertexShader=s.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\ntransformed.y+=sin(uSeaTime*.92+aPhase+abs(position.x)*.5)*aFlex*.72;');s.fragmentShader=s.fragmentShader.replace('#include <color_fragment>','#include <color_fragment>\nif(!gl_FrontFacing)diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.45,.64,.53),.65);');};group.add(new T.Mesh(geometry(d),m));
    const body=new T.Mesh(new T.SphereGeometry(1,16,10),new T.MeshStandardMaterial({color:'#345c59',roughness:.65}));body.scale.set(.36,.20,1.1);group.add(body);
    const tailCurve=new T.CatmullRomCurve3([new T.Vector3(0,.01,.85),new T.Vector3(.05,-.04,1.9),new T.Vector3(.17,-.1,3.4)]);group.add(new T.Mesh(new T.TubeGeometry(tailCurve,14,.032,5,false),new T.MeshStandardMaterial({color:'#325754',roughness:.7})));
    for(const x of [-.26,.26]){const fin=new T.Mesh(new T.ConeGeometry(.12,.56,6),new T.MeshStandardMaterial({color:'#4e7970',roughness:.7}));fin.position.set(x,.03,-1.34);fin.rotation.x=-Math.PI/2;group.add(fin);const eye=new T.Mesh(new T.SphereGeometry(.047,8,6),eyeMat);eye.position.set(x*.95,.16,-.92);group.add(eye);}
    group.scale.setScalar(scale);scene.add(group);rays.push({group,phase,scale});
  }
  makeRay(1.1,.25);makeRay(.78,2.2);makeRay(.63,4.3);
  const rayForward=new T.Vector3(0,0,-1),rayDirection=new T.Vector3();
  function animateRays(t){for(const r of rays){const a=t*.067+r.phase;r.group.position.set(Math.sin(a)*17,13.5+Math.sin(a*.8+r.phase)*2.1,-24+Math.cos(a)*11);rayDirection.set(Math.cos(a)*17,.6*Math.cos(a*.8+r.phase),-Math.sin(a)*11).normalize();r.group.quaternion.setFromUnitVectors(rayForward,rayDirection);r.group.rotateZ(Math.sin(a)*.08);}}
  // A luminous, rippling ceiling, drawn entirely in a shader.
  const surfaceMat=new T.ShaderMaterial({side:T.DoubleSide,transparent:true,opacity:1,depthWrite:false,uniforms:{uSeaTime:seaTime},vertexShader:`varying vec3 vWorld;void main(){vec4 w=modelMatrix*vec4(position,1.);vWorld=w.xyz;gl_Position=projectionMatrix*viewMatrix*w;}`,fragmentShader:`precision highp float;uniform float uSeaTime;varying vec3 vWorld;
    void main(){vec2 p=vWorld.xz;float r=sin(p.x*.6+sin(p.y*.38+uSeaTime*.15)*2.+uSeaTime*.28)*sin(p.y*.53-uSeaTime*.24);float f=pow(max(0.,1.-abs(r)*1.7),5.);float glow=exp(-length(p-vec2(-13.,-13.))*.042);vec3 c=mix(vec3(.045,.32,.36),vec3(.41,.63,.47),glow*.72);c+=f*vec3(.11,.17,.10);gl_FragColor=vec4(c,.7);}`});
  const surface=new T.Mesh(new T.PlaneGeometry(210,210),surfaceMat);surface.rotation.x=Math.PI/2;surface.position.y=23.5;scene.add(surface);
  const beamMat=new T.ShaderMaterial({transparent:true,depthWrite:false,side:T.DoubleSide,blending:T.AdditiveBlending,uniforms:{uSeaTime:seaTime},vertexShader:`varying vec2 vUv;varying float vDistance;void main(){vUv=uv;vec4 v=modelViewMatrix*vec4(position,1.);vDistance=length(v.xyz);gl_Position=projectionMatrix*v;}`,fragmentShader:`precision highp float;uniform float uSeaTime;varying vec2 vUv;varying float vDistance;void main(){float edge=pow(max(0.,sin(vUv.x*3.14159265)),2.5);float ends=smoothstep(0.,.12,vUv.y)*(1.-smoothstep(.8,1.,vUv.y));float wav=.82+.18*sin(vUv.y*12.+uSeaTime*.28);float a=edge*ends*wav*.071*exp(-vDistance*.014);gl_FragColor=vec4(.59,.75,.47,a);}`});
  for(let i=0;i<11;i++){const top=new T.Vector3(4+i*2.7,25,-32+i*2.9),bottom=top.clone().add(new T.Vector3(-15,-27,12));const beam=new T.Mesh(new T.PlaneGeometry(between(1.6,4.7),top.distanceTo(bottom)),beamMat);beam.position.copy(top).add(bottom).multiplyScalar(.5);beam.quaternion.setFromUnitVectors(UP,top.clone().sub(bottom).normalize());beam.rotateY(between(-.18,.18));beam.renderOrder=2;scene.add(beam);}
  // Suspended plankton catches the light.
  const particleCount=coarse?260:460,pg=new T.BufferGeometry(),pp=[],ps=[];
  for(let i=0;i<particleCount;i++){pp.push(between(-48,48),between(.8,23),between(-65,28));ps.push(between(.025,.065));}
  pg.setAttribute('position',new T.Float32BufferAttribute(pp,3));pg.setAttribute('aSize',new T.Float32BufferAttribute(ps,1));
  const particleMat=new T.ShaderMaterial({transparent:true,depthWrite:false,blending:T.AdditiveBlending,uniforms:{uSeaTime:seaTime,uScale:{value:innerHeight*renderer.getPixelRatio()*.7}},vertexShader:`uniform float uSeaTime;uniform float uScale;attribute float aSize;varying float vAlpha;void main(){vec3 p=position;p.x+=sin(uSeaTime*.11+p.z)*.38;p.y+=sin(uSeaTime*.16+p.x)*.25;vec4 mv=modelViewMatrix*vec4(p,1.);gl_Position=projectionMatrix*mv;gl_PointSize=clamp(aSize*uScale/max(1.,-mv.z),1.,6.);vAlpha=exp(-length(mv.xyz)*.025)*.38;}`,fragmentShader:`precision highp float;varying float vAlpha;void main(){float r=length(gl_PointCoord-.5);gl_FragColor=vec4(.75,.85,.61,(1.-smoothstep(.05,.5,r))*vAlpha);}`});scene.add(new T.Points(pg,particleMat));
  // Bubbles have a soft Fresnel rim rather than opaque white bodies.
  const bubbleMat=new T.ShaderMaterial({transparent:true,depthWrite:false,uniforms:{},vertexShader:`varying vec3 vN;varying vec3 vV;void main(){vec4 p=vec4(position,1.);p=instanceMatrix*p;vec4 mv=modelViewMatrix*p;vN=normalize(normalMatrix*normal);vV=-mv.xyz;gl_Position=projectionMatrix*mv;}`,fragmentShader:`precision highp float;varying vec3 vN;varying vec3 vV;void main(){vec3 n=normalize(vN);float rim=pow(1.-abs(dot(n,normalize(vV))),2.5);float glint=pow(max(0.,dot(n,normalize(vec3(-.4,.7,1.)))),24.);float fade=exp(-length(vV)*.025);gl_FragColor=vec4(mix(vec3(.42,.78,.72),vec3(.94,.94,.69),glint),(.025+rim*.36+glint*.47)*fade);}`});
  const bubbleCount=coarse?58:88,bubbles=new T.InstancedMesh(new T.SphereGeometry(1,10,8),bubbleMat,bubbleCount),bubbleStates=[];bubbles.frustumCulled=false;scene.add(bubbles);
  const emitters=[[-5,2],[-13,-25],[12,-18],[7,8],[-20,-6]];
  for(let i=0;i<bubbleCount;i++){const e=emitters[i%emitters.length];bubbleStates.push({x:e[0]+between(-.8,.8),z:e[1]+between(-.7,.7),y:rand()*23,speed:between(.35,.75),r:between(.035,.13),phase:rand()*6});}
  function animateBubbles(t){for(let i=0;i<bubbleCount;i++){const b=bubbleStates[i],y=(b.y+t*b.speed)%23;dummy.position.set(b.x+Math.sin(y*.43+b.phase+t*.15)*.30,y,b.z+Math.cos(y*.3+b.phase)*.23);dummy.quaternion.identity();dummy.scale.setScalar(b.r*(.7+y*.017));dummy.updateMatrix();bubbles.setMatrixAt(i,dummy.matrix);}bubbles.instanceMatrix.needsUpdate=true;}
  // A spherical swimmer, swept in short steps, slides around every solid.
  const swimmer=new T.Vector3(0,5.8,12),radius=.62;
  let yaw=-.035,pitch=-.045,targetYaw=yaw,targetPitch=pitch,speed=0,held=false,pointerId=null,lastX=0,lastY=0;
  const moveDir=new T.Vector3(),candidate=new T.Vector3(),local=new T.Vector3(),delta=new T.Vector3();
  function resolve(p){
    for(let pass=0;pass<4;pass++){
      for(const c of colliders){
        if(c.type==='capsule'){
          const ab=delta.subVectors(c.b,c.a);const l2=ab.lengthSq();const t=T.MathUtils.clamp(local.subVectors(p,c.a).dot(ab)/l2,0,1);local.copy(c.a).addScaledVector(ab,t);delta.subVectors(p,local);const distance=delta.length(),limit=radius+c.r;
          if(distance<limit){if(distance<.00001)delta.set(1,0,0);else delta.divideScalar(distance);p.copy(local).addScaledVector(delta,limit+.002);}continue;
        }
        const cs=Math.cos(c.yaw),sn=Math.sin(c.yaw),dx=p.x-c.center.x,dz=p.z-c.center.z;
        local.set(cs*dx-sn*dz,p.y-c.center.y,sn*dx+cs*dz);
        if(c.type==='ellipsoid'){
          const rx=c.r.x+radius,ry=c.r.y+radius,rz=c.r.z+radius;const q=Math.sqrt((local.x/rx)**2+(local.y/ry)**2+(local.z/rz)**2);
          if(q>=1)continue;if(q<.00001)local.set(rx,0,0);else local.multiplyScalar(1/q+.001);
        }else{
          const hx=c.half.x+radius,hy=c.half.y+radius,hz=c.half.z+radius;
          if(Math.abs(local.x)>=hx||Math.abs(local.y)>=hy||Math.abs(local.z)>=hz)continue;
          const a=hx-Math.abs(local.x),b=hy-Math.abs(local.y),d=hz-Math.abs(local.z);
          if(a<b&&a<d)local.x=(local.x<0?-1:1)*(hx+.002);else if(b<d)local.y=(local.y<0?-1:1)*(hy+.002);else local.z=(local.z<0?-1:1)*(hz+.002);
        }
        p.set(c.center.x+cs*local.x+sn*local.z,c.center.y+local.y,c.center.z-sn*local.x+cs*local.z);
      }
      p.y=T.MathUtils.clamp(p.y,sandY(p.x,p.z)+1.05,22.1);
    }
    const dist=Math.hypot(p.x,p.z+14);if(dist>62){p.x*=62/dist;p.z=-14+(p.z+14)*62/dist;}
    return p;
  }
  function swim(distance){const steps=Math.max(1,Math.ceil(distance/.24));for(let i=0;i<steps;i++){candidate.copy(swimmer).addScaledVector(moveDir,distance/steps);resolve(candidate);swimmer.copy(candidate);}}
  const route=new T.CatmullRomCurve3([new T.Vector3(0,5.8,12),new T.Vector3(-5,5.1,0),new T.Vector3(-6.7,5.9,-13),new T.Vector3(-3,7.5,-26),new T.Vector3(7,8.3,-34),new T.Vector3(18,8.3,-22),new T.Vector3(13.8,8,-6),new T.Vector3(6,6.5,7)],true,'catmullrom',.32);
  const gaze=new T.CatmullRomCurve3([new T.Vector3(-4,7,-15),new T.Vector3(-13,5.3,-26),new T.Vector3(-13,7,-28),new T.Vector3(-2,13,-24),new T.Vector3(8.5,5.5,-23),new T.Vector3(8.5,4.5,-23),new T.Vector3(0,9,-18),new T.Vector3(-1,7,-12)],true,'catmullrom',.4);
  let demo=location.hash.toLowerCase()==='#demo',demoStart=0,elapsed=0,interruptedDrift=false,guideOpen=false;
  const hintTitle=document.getElementById('hint-title'),hintSub=document.getElementById('hint-sub'),driftLabel=document.getElementById('drift-label'),status=document.getElementById('status');
  function updateMode(){document.body.classList.toggle('demo',demo);hintTitle.textContent=demo?'A moment, carried by the current':coarse?'Press & hold to swim forward':'Hold to swim forward';hintSub.textContent=demo?(coarse?'Touch anywhere to take the lead':'Click anywhere to take the lead'):(coarse?'Drag your finger to gently turn':'Move your mouse to gently turn');driftLabel.textContent=demo?'Take the lead':'Drift for a while';}
  function setDemo(value){demo=value;held=false;speed=0;document.body.classList.remove('swimming');if(demo){demoStart=elapsed;document.body.classList.add('exploring');}else{const e=new T.Euler().setFromQuaternion(camera.quaternion,'YXZ');yaw=targetYaw=e.y;pitch=targetPitch=T.MathUtils.clamp(e.x,-.85,.85);swimmer.copy(camera.position);resolve(swimmer);}updateMode();status.textContent=demo?'Drift mode. Touch or click to take control.':'You are in control. Hold to swim and drag to turn.';}
  updateMode();
  window.addEventListener('pointerdown',()=>{interruptedDrift=demo;if(demo)setDemo(false);},{capture:true});
  const canvas=renderer.domElement;
  canvas.addEventListener('pointerdown',e=>{if(guideOpen||pointerId!==null||(e.pointerType==='mouse'&&e.button!==0))return;e.preventDefault();pointerId=e.pointerId;lastX=e.clientX;lastY=e.clientY;held=true;canvas.setPointerCapture(e.pointerId);document.body.classList.add('exploring','swimming');});
  canvas.addEventListener('pointermove',e=>{if(e.pointerId!==pointerId||!held)return;e.preventDefault();const dx=e.clientX-lastX,dy=e.clientY-lastY;lastX=e.clientX;lastY=e.clientY;targetYaw-=dx*(coarse?.0045:.0036);targetPitch=T.MathUtils.clamp(targetPitch-dy*(coarse?.0039:.0032),-.85,.85);});
  function release(e){if(e&&e.pointerId!==pointerId)return;held=false;document.body.classList.remove('swimming');if(pointerId!==null&&canvas.hasPointerCapture(pointerId))canvas.releasePointerCapture(pointerId);pointerId=null;}
  canvas.addEventListener('pointerup',release);canvas.addEventListener('pointercancel',release);canvas.addEventListener('lostpointercapture',()=>{held=false;pointerId=null;document.body.classList.remove('swimming');});canvas.addEventListener('contextmenu',e=>e.preventDefault());window.addEventListener('blur',()=>release());
  document.getElementById('drift').addEventListener('click',()=>{if(interruptedDrift){interruptedDrift=false;return;}setDemo(true);});
  const shade=document.getElementById('guide-shade');
  function closeGuide(){guideOpen=false;shade.classList.remove('open');document.getElementById('help').focus();}
  document.getElementById('help').onclick=()=>{release();guideOpen=true;shade.classList.add('open');document.getElementById('close-guide').focus();};document.getElementById('close-guide').onclick=closeGuide;shade.addEventListener('click',e=>{if(e.target===shade)closeGuide();});
  document.addEventListener('keydown',e=>{if(e.key==='Escape'&&guideOpen)closeGuide();if(guideOpen&&e.key==='Tab'){e.preventDefault();document.getElementById('close-guide').focus();}});
  // Soft ocean ambience is synthesized locally after an explicit gesture.
  let audio=null,soundOn=false;
  function createAmbience(){const Audio=window.AudioContext||window.webkitAudioContext;if(!Audio)return null;const ctx=new Audio(),master=ctx.createGain();master.gain.value=0;master.connect(ctx.destination);const buffer=ctx.createBuffer(1,ctx.sampleRate*5,ctx.sampleRate),samples=buffer.getChannelData(0);let brown=0;for(let i=0;i<samples.length;i++){brown=(brown+(Math.random()*2-1)*.025)/1.025;samples[i]=brown*3;}const noise=ctx.createBufferSource();noise.buffer=buffer;noise.loop=true;const low=ctx.createBiquadFilter();low.type='lowpass';low.frequency.value=260;const high=ctx.createBiquadFilter();high.type='highpass';high.frequency.value=38;noise.connect(low);low.connect(high);high.connect(master);noise.start();for(const [freq,gain] of [[65.4,.045],[98,.021],[130.8,.012]]){const osc=ctx.createOscillator(),vol=ctx.createGain();osc.frequency.value=freq;vol.gain.value=gain;osc.connect(vol);vol.connect(master);osc.start();}return{ctx,master};}
  document.getElementById('sound').onclick=async()=>{try{if(!audio)audio=createAmbience();if(!audio){status.textContent='Ocean ambience is unavailable in this browser.';return;}await audio.ctx.resume();soundOn=!soundOn;audio.master.gain.setTargetAtTime(soundOn?.32:0,audio.ctx.currentTime,.65);const button=document.getElementById('sound');button.setAttribute('aria-pressed',String(soundOn));button.setAttribute('aria-label',soundOn?'Turn off ocean ambience':'Turn on ocean ambience');button.querySelector('.sound-label').textContent=soundOn?'Sound on':'Sound off';document.getElementById('sound-waves').style.display=soundOn?'':'none';document.getElementById('sound-mute').style.display=soundOn?'none':'';}catch{status.textContent='Ocean ambience is unavailable in this browser.';}};
  let last=performance.now(),uiTick=0,first=true;
  const targetGaze=new T.Vector3(),viewBob=new T.Vector3();
  function frame(now){requestAnimationFrame(frame);const dt=Math.min((now-last)/1000,.045);last=now;if(document.hidden)return;elapsed+=dt;seaTime.value=elapsed;
    animateFish(elapsed);animateRays(elapsed);animateBubbles(elapsed);
    if(demo&&!guideOpen){const u=((elapsed-demoStart)/20)%1;route.getPointAt(u,swimmer);resolve(swimmer);camera.position.copy(swimmer);gaze.getPointAt(u,targetGaze);camera.lookAt(targetGaze);}
    else if(!demo){const smoothing=1-Math.exp(-dt*9);yaw+=(targetYaw-yaw)*smoothing;pitch+=(targetPitch-pitch)*smoothing;speed+=((held&&!guideOpen?2.65:0)-speed)*(1-Math.exp(-dt*(held?2.5:7)));moveDir.set(-Math.sin(yaw)*Math.cos(pitch),Math.sin(pitch),-Math.cos(yaw)*Math.cos(pitch));if(speed>.004)swim(speed*dt);viewBob.set(0,reduced?0:Math.sin(elapsed*.7)*.023,0);camera.position.copy(swimmer).add(viewBob);camera.rotation.set(pitch+(reduced?0:Math.sin(elapsed*.31)*.0017),yaw,reduced?0:Math.sin(elapsed*.4)*.0013,'YXZ');}
    renderer.render(scene,camera);
    if(first){first=false;loading.classList.add('done');setTimeout(()=>{if(!held&&!demo)document.body.classList.add('exploring');},12500);}
    uiTick+=dt;if(uiTick>.15){uiTick=0;document.getElementById('depth').textContent=(23.5-camera.position.y).toFixed(1);document.getElementById('needle').style.transform=`rotate(${camera.rotation.y*180/Math.PI}deg)`;}
  }
  window.addEventListener('resize',()=>{camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();renderer.setSize(innerWidth,innerHeight);particleMat.uniforms.uScale.value=innerHeight*renderer.getPixelRatio()*.7;});
  document.addEventListener('visibilitychange',()=>{last=performance.now();if(document.hidden){release();if(audio)audio.master.gain.setTargetAtTime(0,audio.ctx.currentTime,.15);}else if(audio&&soundOn)audio.master.gain.setTargetAtTime(.32,audio.ctx.currentTime,.5);});
  canvas.addEventListener('webglcontextlost',e=>{e.preventDefault();release();document.getElementById('loading-title').textContent='The current paused for a moment.';document.getElementById('loading-copy').textContent='Tap below to return to the garden.';const retry=document.getElementById('retry');retry.hidden=false;retry.style.display='flex';retry.onclick=()=>location.reload();loading.classList.remove('done');});
  camera.position.copy(swimmer);camera.rotation.set(pitch,yaw,0,'YXZ');requestAnimationFrame(frame);
}
</script>
</body>
</html>