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.)60.9 KB · 446 lines · loads cdn.jsdelivr.net/npm/three@0.160.0/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="#073e49">
<title>Stillwater — The Kelp Garden</title>
<style>
:root{color-scheme:dark;--cream:#eee9d0;--gold:#d9c38a;--muted:#b3c8bf;--glass:rgba(8,45,51,.40)}
*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#075465}body{font-family:Arial,Helvetica,sans-serif;color:var(--cream);-webkit-font-smoothing:antialiased}button{font:inherit;color:inherit;-webkit-tap-highlight-color:transparent}button:focus-visible{outline:2px solid var(--gold);outline-offset:5px}button{cursor:pointer}#ocean{position:fixed;inset:0;touch-action:none}#ocean canvas{display:block;width:100%;height:100%;touch-action:none;outline:none;cursor:grab}body.gliding #ocean canvas{cursor:grabbing}.atmosphere{position:fixed;inset:0;pointer-events:none;background:linear-gradient(180deg,rgba(0,28,40,.19),transparent 27%,transparent 66%,rgba(0,24,33,.39));box-shadow:inset 0 0 15vw rgba(0,25,36,.20);z-index:2}#chrome{position:fixed;inset:0;z-index:5;pointer-events:none;opacity:1;transition:opacity 1.2s}body:not(.ready) #chrome{opacity:0}.header{position:absolute;top:0;left:0;right:0;display:flex;align-items:center;justify-content:space-between;padding:33px 43px}.brand{display:flex;align-items:center;gap:12px;user-select:none}.brand svg{width:29px;height:39px;stroke:var(--gold);fill:none;stroke-width:1.3;stroke-linecap:round}.brand-name{font-family:Georgia,'Times New Roman',serif;font-size:29px;letter-spacing:-1px}.brand-sub{display:block;margin-top:5px;font-family:Arial,Helvetica,sans-serif;font-size:8px;letter-spacing:3.1px;color:var(--muted)}#mood{position:absolute;left:50%;transform:translateX(-50%);font-size:9px;letter-spacing:2.5px;color:#d0dfce;white-space:nowrap;opacity:.75;display:flex;align-items:center;gap:10px}.live-dot{display:inline-block;width:4px;height:4px;flex-shrink:0;border-radius:50%;background:var(--gold);box-shadow:0 0 9px #dfc37855}.header-actions{display:flex;gap:11px;align-items:center;pointer-events:auto}.glass-button{border:1px solid rgba(217,228,206,.24);background:rgba(8,49,55,.29);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);transition:background .25s,border-color .25s;display:flex;align-items:center;justify-content:center;gap:10px;min-height:46px}.glass-button:active{background:rgba(215,217,174,.17);border-color:rgba(236,232,205,.60)}.glass-button svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round;stroke-linejoin:round}#soundButton{padding:0 18px;border-radius:25px;font-size:11px;letter-spacing:.2px;min-width:127px}#helpButton{width:46px;min-width:46px;border-radius:50%;font-family:Georgia,serif;font-style:italic;font-size:20px}.sound-waves{display:none}#soundButton.on .sound-waves{display:block}#soundButton.on .sound-slash{display:none}#intro{position:absolute;left:49px;top:22.5%;transition:opacity 1.8s,transform 1.8s;max-width:490px;text-shadow:0 2px 25px #0a384747}.eyebrow{display:flex;align-items:center;gap:11px;font-size:9px;letter-spacing:2.8px;color:var(--gold);margin-bottom:22px}.eyebrow:before{content:'';display:inline-block;width:28px;height:1px;background:var(--gold);opacity:.75}h1{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:clamp(56px,5.5vw,85px);line-height:1.04;letter-spacing:-2.8px;margin:0 0 23px;color:#f1ecd5}#intro p{margin:0;font-size:12px;line-height:1.85;letter-spacing:.35px;color:#d0dfcf}#intro.gone{opacity:0;transform:translateY(-12px)}#depthPanel{position:absolute;left:46px;bottom:41px;display:flex;gap:18px;align-items:center;user-select:none}.depth-lines{width:11px;height:53px;display:flex;flex-direction:column;justify-content:space-between;opacity:.7}.depth-lines i{display:block;background:#c5d6bd99;height:1px;width:5px}.depth-lines i:nth-child(3n+1){width:10px}.depth-overline{font-size:8px;letter-spacing:2.5px;opacity:.65;margin-bottom:5px}.depth-value{font-family:Georgia,serif;font-size:34px;font-weight:400;line-height:1;letter-spacing:-1px}.depth-unit{font-family:Arial,sans-serif;font-size:10px;letter-spacing:1px;margin-left:5px;opacity:.7}.location{font-size:8px;letter-spacing:1.9px;color:#c6d7c7;margin-top:10px;text-transform:uppercase;display:flex;align-items:center;gap:6px}.location svg{width:10px;height:10px;fill:none;stroke:currentColor;stroke-width:1.4}#movement{position:absolute;bottom:35px;left:50%;transform:translateX(-50%);text-align:center;pointer-events:auto}#swimButton{width:221px;min-height:59px;border:1px solid rgba(227,227,194,.43);border-radius:40px;background:rgba(222,229,202,.10);box-shadow:0 4px 28px #062f3d26,inset 0 1px 0 #ffffff0b;backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);display:flex;align-items:center;justify-content:center;gap:13px;font-size:12px;letter-spacing:.65px;touch-action:none;transition:background .3s,box-shadow .3s;user-select:none}#swimButton svg{width:23px;height:24px;fill:none;stroke:var(--gold);stroke-width:1.3;stroke-linecap:round;stroke-linejoin:round}body.gliding #swimButton{background:rgba(220,220,175,.22);box-shadow:0 0 28px #c4dfbc14,inset 0 1px 0 #fff2}#movement small{display:block;font-size:9px;color:#c0d3c4;letter-spacing:.4px;margin-top:12px;opacity:.78;white-space:nowrap}#tourButton{position:absolute;right:43px;bottom:55px;pointer-events:auto;border-radius:28px;min-height:49px;min-width:158px;padding:0 20px;font-size:11px;letter-spacing:.5px;overflow:hidden}#tourButton svg{width:13px;height:13px;fill:var(--gold);stroke:none}.stop-icon{display:none}body.tour-active .play-icon{display:none}body.tour-active .stop-icon{display:block}.tour-track{display:none;position:absolute;bottom:0;left:18px;right:18px;height:1px;background:#d9c38a1a}body.tour-active .tour-track{display:block}#tourFill{display:block;width:0;height:100%;background:var(--gold)}#reticle{position:fixed;left:50%;top:50%;width:28px;height:28px;margin:-14px 0 0 -14px;border:1px solid #eee9d055;border-radius:50%;opacity:0;z-index:4;pointer-events:none;transition:opacity .5s,transform .8s;transform:scale(.7)}#reticle:after{content:'';position:absolute;left:12px;top:12px;width:2px;height:2px;background:#f1e4bd;border-radius:50%}body.gliding #reticle{opacity:.7;transform:scale(1)}#helpPanel{position:absolute;top:101px;right:43px;width:320px;padding:26px 26px 23px;pointer-events:auto;border:1px solid #d1dfc82b;background:rgba(7,41,49,.91);backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border-radius:18px;box-shadow:0 15px 70px #001d342e;display:none}#helpPanel.open{display:block}#helpPanel h2{font-family:Georgia,serif;font-size:26px;font-weight:400;letter-spacing:-.5px;line-height:1.2;margin:0 26px 17px 0}#helpPanel p{font-size:11px;line-height:1.9;color:#c3d4c6;margin:15px 0 0}#helpPanel dl{margin:20px 0;padding:15px 0;border-top:1px solid #cad8b926;border-bottom:1px solid #cad8b926;font-size:11px}#helpPanel dl div{display:flex;justify-content:space-between;padding:7px 0;gap:20px}#helpPanel dt{color:#e6dec0}#helpPanel dd{margin:0;color:#a9c6be}#helpClose{position:absolute;right:10px;top:9px;width:44px;height:44px;background:none;border:0;color:#cad9c6;font-size:24px;font-weight:200}#toast{position:absolute;left:50%;bottom:144px;transform:translate(-50%,8px);border:1px solid #e1e3c52b;border-radius:25px;background:rgba(7,43,49,.76);backdrop-filter:blur(12px);padding:12px 21px;font-size:11px;letter-spacing:.25px;white-space:nowrap;opacity:0;transition:opacity .35s,transform .35s;pointer-events:none}#toast.show{opacity:1;transform:translate(-50%,0)}#loader{position:fixed;inset:0;z-index:20;display:flex;align-items:center;justify-content:center;text-align:center;background:radial-gradient(ellipse at 42% 23%,#1a6d70,#073d50 75%);transition:opacity 1.1s;pointer-events:auto}#loader.leaving{opacity:0;pointer-events:none}.loading-mark{margin:0 auto 30px;width:68px;height:68px;border:1px solid #d5dfbd3b;border-radius:50%;display:flex;align-items:center;justify-content:center;animation:breathe 3s ease-in-out infinite}.loading-mark svg{width:28px;height:40px;fill:none;stroke:#d7c58e;stroke-width:1.3;stroke-linecap:round}#loader h2{font-family:Georgia,serif;font-size:36px;font-weight:400;letter-spacing:-1px;margin:0 0 13px}#loader p{font-size:10px;line-height:1.9;letter-spacing:1px;color:#aecbc1;margin:0 20px;max-width:380px}#loadingDetail{transition:opacity .3s}@keyframes breathe{50%{transform:translateY(-5px);box-shadow:0 0 0 12px #d2ddbc03}}@media(max-width:760px){.header{padding:23px 22px}.brand{gap:9px}.brand svg{width:23px;height:34px}.brand-name{font-size:26px}.brand-sub{font-size:7px;letter-spacing:2.2px;margin-top:4px}#mood{display:none}.header-actions{gap:8px}#soundButton{width:44px;min-width:44px;padding:0;min-height:44px}#soundText{display:none}#helpButton{width:44px;min-width:44px;min-height:44px}#intro{left:25px;top:21%;max-width:330px}.eyebrow{font-size:8px;letter-spacing:2px;margin-bottom:19px}h1{font-size:57px;letter-spacing:-2px;margin-bottom:19px}#intro p{font-size:11px;max-width:265px}#depthPanel{left:25px;bottom:135px;gap:12px}.depth-value{font-size:30px}.depth-lines{height:47px}.depth-overline{font-size:7px}.location{font-size:7px;letter-spacing:1.4px;margin-top:8px}#tourButton{right:22px;bottom:144px;min-width:139px;padding:0 16px;font-size:10px;min-height:45px}#movement{bottom:max(29px,env(safe-area-inset-bottom))}#swimButton{width:217px;min-height:57px}#movement small{font-size:8px;margin-top:11px}#helpPanel{right:20px;left:20px;width:auto;top:87px}#toast{bottom:214px;font-size:10px;max-width:90vw;text-align:center;white-space:normal;width:max-content}}@media(max-height:580px) and (min-width:600px){.header{padding:19px 28px}#intro{top:26%;left:32px}h1{font-size:53px}#intro p{font-size:10px}.eyebrow{margin-bottom:12px}#depthPanel{bottom:25px;left:28px}#movement{bottom:19px}#tourButton{right:28px;bottom:39px}#helpPanel{top:76px;max-height:calc(100vh - 94px);overflow:auto}}@media(prefers-reduced-motion:reduce){.loading-mark{animation:none}*{scroll-behavior:auto}}
</style>
</head>
<body>
<div id="ocean" aria-label="An underwater kelp garden. Hold and drag to swim and turn."></div>
<div class="atmosphere"></div>
<div id="reticle" aria-hidden="true"></div>
<div id="chrome">
  <header class="header">
    <div class="brand" aria-label="Stillwater, the kelp garden">
      <svg viewBox="0 0 30 42" aria-hidden="true"><path d="M15 39C9 29 22 22 15 3M14 30C4 30 4 22 7 18C8 24 13 23 15 25M17 21C26 21 27 11 23 8C23 15 19 13 17 17M15 13C9 12 8 7 10 3M9 39Q15 35 22 39"/></svg>
      <div class="brand-name">stillwater<span class="brand-sub">THE KELP GARDEN</span></div>
    </div>
    <div id="mood"><span class="live-dot"></span><span id="moodText">NOWHERE TO BE. JUST HERE.</span></div>
    <div class="header-actions">
      <button id="soundButton" class="glass-button" type="button" aria-label="Turn underwater sound on" aria-pressed="false"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M10 5L5 9H2v6h3l5 4z"/><g class="sound-waves"><path d="M14 8a6 6 0 010 8M17 5a10 10 0 010 14"/></g><path class="sound-slash" d="M15 9l6 6m0-6l-6 6"/></svg><span id="soundText">Sound off</span></button>
      <button id="helpButton" class="glass-button" type="button" aria-label="How to explore" aria-expanded="false">i</button>
    </div>
  </header>
  <section id="intro"><div class="eyebrow">A LITTLE ESCAPE, BELOW THE SURFACE</div><h1>A world<br>in no hurry.</h1><p>Follow the light. Wander through the kelp.<br>Stay a little longer than you meant to.</p></section>
  <div id="depthPanel" aria-label="Current depth and location"><div class="depth-lines" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div><div class="depth-overline">BELOW THE SURFACE</div><div class="depth-value"><span id="depthValue">15.5</span><span class="depth-unit">m</span></div><div class="location"><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M7 1L12 11 7 9 2 11z"/></svg><span id="locationName">THE KELP SHALLOWS</span></div></div></div>
  <div id="movement"><button id="swimButton" type="button" aria-label="Press and hold to swim. Drag to turn."><svg viewBox="0 0 25 26" aria-hidden="true"><path d="M12.5 18V4m-4 4l4-4 4 4M3 18q4-4 9.5 0t9.5 0M3 23q4-4 9.5 0t9.5 0"/></svg><span id="swimText">Hold to swim</span></button><small>drag to turn &nbsp;·&nbsp; release to float</small></div>
  <button id="tourButton" class="glass-button" type="button" aria-label="Start a guided underwater tour" aria-pressed="false"><svg class="play-icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 2l10 6-10 6z"/></svg><svg class="stop-icon" viewBox="0 0 16 16" aria-hidden="true"><rect x="3" y="3" width="10" height="10" rx="1"/></svg><span id="tourText">Explore for me</span><span class="tour-track" aria-hidden="true"><i id="tourFill"></i></span></button>
  <aside id="helpPanel" aria-label="Exploring the garden"><button id="helpClose" type="button" aria-label="Close instructions">×</button><div class="eyebrow" style="margin-bottom:14px">GO AT YOUR OWN PACE</div><h2>A slower kind<br>of exploring.</h2><dl><div><dt>Press &amp; hold anywhere</dt><dd>Glide ahead</dd></div><div><dt>Drag while holding</dt><dd>Look &amp; turn</dd></div><div><dt>Lift your finger</dt><dd>Drift to a stop</dd></div></dl><p>Swim beneath the stone arch. Find the <em>Solace</em> resting in the sand. Or simply follow a school of fish.</p><p>Choose “Explore for me” for a gentle, repeating tour. Touch the water to take the lead.</p></aside>
  <div id="toast" role="status" aria-live="polite"></div>
</div>
<div id="loader"><div><div class="loading-mark"><svg viewBox="0 0 30 42" aria-hidden="true"><path d="M15 39C9 29 22 22 15 3M14 30C4 30 4 22 7 18C8 24 13 23 15 25M17 21C26 21 27 11 23 8C23 15 19 13 17 17M15 13C9 12 8 7 10 3"/></svg></div><h2>A little further from everything.</h2><p id="loadingDetail">Letting the light in…</p></div></div>
<noscript><div style="position:fixed;inset:0;z-index:50;display:grid;place-items:center;background:#073e49;padding:30px;text-align:center">Please enable JavaScript to explore the kelp garden.</div></noscript>
<script type="module">
async function createGarden(){
  const THREE = await import('https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js');
  const $=id=>document.getElementById(id);
  const clamp=THREE.MathUtils.clamp;
  const mobile=innerWidth<760;
  const reduced=matchMedia('(prefers-reduced-motion: reduce)').matches;
  let seed=731428;
  function random(a=0,b=1){seed|=0;seed=seed+0x6D2B79F5|0;let q=Math.imul(seed^seed>>>15,1|seed);q=q+Math.imul(q^q>>>7,61|q)^q;return a+((q^q>>>14)>>>0)/4294967296*(b-a)}
  const scene=new THREE.Scene();
  const waterColor=new THREE.Color(0x0b586f);
  scene.background=waterColor;
  scene.fog=new THREE.FogExp2(waterColor,0.0168);
  const camera=new THREE.PerspectiveCamera(mobile?74:62,innerWidth/innerHeight,.12,165);
  const renderer=new THREE.WebGLRenderer({antialias:true,alpha:false,powerPreference:'high-performance'});
  let pixelRatio=Math.min(devicePixelRatio||1,mobile?1.5:1.8);
  renderer.setPixelRatio(pixelRatio);
  renderer.setSize(innerWidth,innerHeight);
  renderer.outputColorSpace=THREE.SRGBColorSpace;
  renderer.toneMapping=THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure=1.04;
  renderer.shadowMap.enabled=true;
  renderer.shadowMap.type=THREE.PCFSoftShadowMap;
  renderer.shadowMap.autoUpdate=false;
  renderer.domElement.setAttribute('aria-label','The underwater garden. Press and hold to swim; drag to turn.');
  $('ocean').appendChild(renderer.domElement);
  const time={value:0};
  const UP=new THREE.Vector3(0,1,0),FORWARD=new THREE.Vector3(0,0,1);
  const tempVector=new THREE.Vector3(),tempMatrix=new THREE.Matrix4();
  scene.add(new THREE.HemisphereLight(0x9cdace,0x184859,1.95));
  scene.add(new THREE.AmbientLight(0x237785,.28));
  const sun=new THREE.DirectionalLight(0xffe3a6,3.15);
  sun.position.set(-24,37,12);sun.target.position.set(-2,0,-25);scene.add(sun,sun.target);
  sun.castShadow=true;sun.shadow.mapSize.set(mobile?1024:2048,mobile?1024:2048);
  Object.assign(sun.shadow.camera,{left:-53,right:53,top:48,bottom:-48,near:1,far:110});
  sun.shadow.bias=-.0007;sun.shadow.normalBias=.12;sun.shadow.radius=3;
  const fill=new THREE.DirectionalLight(0x54c2d0,.55);fill.position.set(15,10,-35);scene.add(fill);
  const colliders=[];
  function floorHeight(x,z){return -1.25+.38*Math.sin(x*.075+z*.045)+.33*Math.cos(z*.095)+.17*Math.sin(x*.22+Math.cos(z*.07))}
  function newBucket(){return{p:[],c:[]}}
  const vertex=new THREE.Vector3();
  function appendGeometry(bucket,geometry,matrix,color){
    const p=geometry.getAttribute('position'),index=geometry.index;
    const c=color instanceof THREE.Color?color:new THREE.Color(color);
    const count=index?index.count:p.count;
    for(let i=0;i<count;i++){const j=index?index.getX(i):i;vertex.fromBufferAttribute(p,j).applyMatrix4(matrix);bucket.p.push(vertex.x,vertex.y,vertex.z);bucket.c.push(c.r,c.g,c.b)}
  }
  function triangle(bucket,a,b,c,color){for(const p of[a,b,c]){bucket.p.push(p.x,p.y,p.z);bucket.c.push(color.r,color.g,color.b)}}
  function geometryFrom(bucket){const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(bucket.p,3));g.setAttribute('color',new THREE.Float32BufferAttribute(bucket.c,3));g.computeVertexNormals();g.computeBoundingSphere();return g}
  function boxTo(bucket,x,y,z,sx,sy,sz,color,rotation=0){
    const g=new THREE.BoxGeometry(sx,sy,sz);tempMatrix.makeRotationY(rotation);tempMatrix.setPosition(x,y,z);appendGeometry(bucket,g,tempMatrix,color);g.dispose();
  }
  function cylinderTo(bucket,a,b,r0,r1,color,sides=7){
    const d=new THREE.Vector3().subVectors(b,a);const length=d.length();if(length<.001)return;
    const g=new THREE.CylinderGeometry(r1,r0,length,sides,1);
    const q=new THREE.Quaternion().setFromUnitVectors(UP,d.normalize());
    const m=new THREE.Matrix4().compose(new THREE.Vector3().addVectors(a,b).multiplyScalar(.5),q,new THREE.Vector3(1,1,1));
    appendGeometry(bucket,g,m,color);g.dispose();
  }
  function causticMaterial(material,strength=1,sand=false){
    material.onBeforeCompile=shader=>{
      shader.uniforms.uGardenTime=time;
      shader.vertexShader='varying vec3 vGardenWorld;\n'+shader.vertexShader;
      shader.vertexShader=shader.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\nvGardenWorld=(modelMatrix*vec4(transformed,1.0)).xyz;');
      shader.fragmentShader='uniform float uGardenTime;\nvarying vec3 vGardenWorld;\n'+shader.fragmentShader;
      shader.fragmentShader=shader.fragmentShader.replace('#include <color_fragment>',`#include <color_fragment>
        vec2 gardenQ=vGardenWorld.xz*0.78;
        gardenQ+=vec2(sin(gardenQ.y*.83+uGardenTime*.21),cos(gardenQ.x*.72-uGardenTime*.17))*.67;
        float gardenN=sin(gardenQ.x+sin(gardenQ.y*1.38))*cos(gardenQ.y+cos(gardenQ.x*1.23));
        float gardenC=pow(1.0-abs(gardenN),15.0);
        diffuseColor.rgb*=0.94+gardenC*${(strength*.46).toFixed(3)};
        diffuseColor.rgb+=vec3(.047,.067,.025)*gardenC*${strength.toFixed(2)};
        ${sand?'diffuseColor.rgb*=.97+.03*sin(vGardenWorld.x*8.5+vGardenWorld.z*1.4+sin(vGardenWorld.z*.52)*2.3);':''}
      `);
    };
    material.customProgramCacheKey=()=>`garden-caustic-${strength}-${sand}`;
    return material;
  }
  // A rippled sand floor. Every texture in the garden is drawn here.
  const sandCanvas=document.createElement('canvas');sandCanvas.width=sandCanvas.height=256;
  const sandContext=sandCanvas.getContext('2d');const sandImage=sandContext.createImageData(256,256);
  for(let y=0;y<256;y++)for(let x=0;x<256;x++){const i=(y*256+x)*4;const v=clamp(146+random(-28,28)+Math.sin(x*.18+Math.sin(y*.035)*2)*17,0,255);sandImage.data[i]=sandImage.data[i+1]=sandImage.data[i+2]=v;sandImage.data[i+3]=255}
  sandContext.putImageData(sandImage,0,0);
  const sandBump=new THREE.CanvasTexture(sandCanvas);sandBump.wrapS=sandBump.wrapT=THREE.RepeatWrapping;sandBump.repeat.set(38,38);
  const floorGeometry=new THREE.PlaneGeometry(180,180,128,128);floorGeometry.rotateX(-Math.PI/2);
  const floorPositions=floorGeometry.getAttribute('position');
  for(let i=0;i<floorPositions.count;i++){const x=floorPositions.getX(i),z=floorPositions.getZ(i);floorPositions.setY(i,floorHeight(x,z))}
  floorGeometry.computeVertexNormals();
  const sandMaterial=causticMaterial(new THREE.MeshStandardMaterial({color:0xb9bd91,roughness:.96,bumpMap:sandBump,bumpScale:.08}),1.3,true);
  const floor=new THREE.Mesh(floorGeometry,sandMaterial);floor.receiveShadow=true;scene.add(floor);
  // A bright, slowly rippling ceiling of water.
  const surfaceMaterial=new THREE.ShaderMaterial({
    side:THREE.DoubleSide,transparent:true,depthWrite:false,
    uniforms:{uTime:time,uFog:{value:waterColor}},
    vertexShader:`uniform float uTime;varying vec3 vWorld;void main(){vec3 p=position;p.y+=sin(p.x*.23+uTime*.47)*.20+cos(p.z*.18+uTime*.32)*.17;vWorld=(modelMatrix*vec4(p,1.)).xyz;gl_Position=projectionMatrix*viewMatrix*vec4(vWorld,1.);}`,
    fragmentShader:`uniform float uTime;uniform vec3 uFog;varying vec3 vWorld;void main(){vec2 q=vWorld.xz;float w=sin(q.x*.45+sin(q.y*.36+uTime*.18)*2.+uTime*.25)*cos(q.y*.51+sin(q.x*.27-uTime*.22));float fleck=pow(1.-abs(w),9.);vec2 sunD=q-vec2(-20.,-12.);float glow=exp(-dot(sunD,sunD)*.0028);vec3 col=mix(vec3(.055,.29,.34),vec3(.27,.58,.53),.4+w*.16);col+=vec3(.28,.29,.13)*fleck*.26+vec3(.29,.27,.13)*glow;float d=length(cameraPosition-vWorld);col=mix(col,uFog,1.-exp(-d*d*.00022));gl_FragColor=vec4(col,.91);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`
  });
  const surfaceGeometry=new THREE.PlaneGeometry(185,185,64,64);surfaceGeometry.rotateX(-Math.PI/2);
  const surface=new THREE.Mesh(surfaceGeometry,surfaceMaterial);surface.position.y=22;surface.renderOrder=1;scene.add(surface);
  function radialTexture(){const c=document.createElement('canvas');c.width=c.height=128;const ctx=c.getContext('2d');const g=ctx.createRadialGradient(64,64,1,64,64,63);g.addColorStop(0,'rgba(255,245,197,1)');g.addColorStop(.2,'rgba(232,241,190,.40)');g.addColorStop(1,'rgba(180,235,199,0)');ctx.fillStyle=g;ctx.fillRect(0,0,128,128);return new THREE.CanvasTexture(c)}
  const glowMap=radialTexture();
  const sunGlow=new THREE.Sprite(new THREE.SpriteMaterial({map:glowMap,color:0xefd7a2,transparent:true,opacity:.3,blending:THREE.AdditiveBlending,depthWrite:false,fog:false}));sunGlow.position.set(-20,21.6,-12);sunGlow.scale.set(34,23,1);sunGlow.renderOrder=2;scene.add(sunGlow);
  function beam(start,end,width,phase){
    const axis=new THREE.Vector3().subVectors(end,start).normalize();
    const side=new THREE.Vector3(1,0,0).addScaledVector(axis,-axis.x).normalize();
    const other=new THREE.Vector3().crossVectors(axis,side).normalize();
    const material=new THREE.ShaderMaterial({transparent:true,depthWrite:false,side:THREE.DoubleSide,blending:THREE.AdditiveBlending,uniforms:{uTime:time,uPhase:{value:phase}},vertexShader:`varying vec2 vUv;varying float vDepth;void main(){vUv=uv;vec4 p=modelViewMatrix*vec4(position,1.);vDepth=-p.z;gl_Position=projectionMatrix*p;}`,fragmentShader:`uniform float uTime;uniform float uPhase;varying vec2 vUv;varying float vDepth;void main(){float edge=pow(max(0.,1.-abs(vUv.x*2.-1.)),2.5);float a=edge*sin(vUv.y*3.14159)*.075; a*=.82+.18*sin(uTime*.35+uPhase+vUv.y*8.);a*=exp(-vDepth*.008);gl_FragColor=vec4(.62,.78,.51,a);}`});
    for(const s of[side,other]){
      const top=width*.21,bottom=width;
      const a=start.clone().addScaledVector(s,-top),b=start.clone().addScaledVector(s,top),c=end.clone().addScaledVector(s,-bottom),d=end.clone().addScaledVector(s,bottom);
      const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute([...a,...c,...b,...b,...c,...d],3));g.setAttribute('uv',new THREE.Float32BufferAttribute([0,1,0,0,1,1,1,1,0,0,1,0],2));
      const m=new THREE.Mesh(g,material);m.renderOrder=4;scene.add(m);
    }
  }
  for(let i=0;i<12;i++){const x=-28+i*3.2+random(-1,1),z=random(-44,4);beam(new THREE.Vector3(x,21.8,z),new THREE.Vector3(x+12,-.3,z-8),random(.8,2.7),random(0,6))}
  // Rounded weathered rocks, with individual solid collision volumes.
  const rockGeometries=[];
  for(let n=0;n<4;n++){
    const g=new THREE.IcosahedronGeometry(1,2),p=g.getAttribute('position'),colors=[];
    for(let i=0;i<p.count;i++){
      let x=p.getX(i),y=p.getY(i),z=p.getZ(i);const f=1+.075*Math.sin(x*9+y*5+n)*Math.sin(z*11-x*3)+.035*Math.cos(y*14+z*5+n*2);p.setXYZ(i,x*f,y*f,z*f);
      const c=new THREE.Color().lerpColors(new THREE.Color(0x31565a),new THREE.Color(0x819078),clamp((y+.9)*.46+Math.sin(x*7+z*9)*.10,0,1));colors.push(c.r,c.g,c.b);
    }
    g.setAttribute('color',new THREE.Float32BufferAttribute(colors,3));g.computeVertexNormals();rockGeometries.push(g);
  }
  const rockMaterial=causticMaterial(new THREE.MeshStandardMaterial({vertexColors:true,roughness:.94}),.8);
  function rock(x,y,z,sx,sy,sz,rotation=0){
    const m=new THREE.Mesh(rockGeometries[Math.floor(random(0,4))],rockMaterial);m.position.set(x,y,z);m.scale.set(sx,sy,sz);m.rotation.set(random(-.15,.15),random(-.35,.35),rotation);m.castShadow=true;m.receiveShadow=true;scene.add(m);
    colliders.push({type:'ellipsoid',center:m.position.clone(),inverse:m.quaternion.clone().invert(),quaternion:m.quaternion.clone(),radii:new THREE.Vector3(sx*1.13+.57,sy*1.13+.57,sz*1.13+.57)});return m;
  }
  function arch(cx,cz,rx,ry,scale=1){
    const base=floorHeight(cx,cz);
    for(let i=0;i<=12;i++){const t=i/12*Math.PI;rock(cx+Math.cos(t)*rx,base+Math.sin(t)*ry,cz+Math.sin(t*2)*.35,2.0*scale,1.45*scale,1.75*scale,t+Math.PI/2)}
    for(const side of[-1,1]){rock(cx+side*(rx+.65),base-.15,cz+1.0,2.8*scale,1.35*scale,2.7*scale);rock(cx+side*(rx+2),base-.2,cz-1.3,2.2*scale,1.6*scale,2.4*scale)}
  }
  arch(-11,-25,6.2,8.3,1);
  arch(30,-61,4.5,6.3,.83);
  const rockSites=[[-24,-18,4.5,4,3.4],[-26,-27,3.8,5,4],[-28,-36,5,6,4],[-22,-40,3.2,3.6,3.8],[25,-26,4,3.8,4.3],[28,-36,5,6.5,4],[25,-46,3.7,4,3.4],[-15,7,3.4,2.3,3.1],[15,5,3.2,2.4,3.2],[-19,-7,3,2.3,2.5],[19,-6,2.4,1.5,2.8],[-38,-57,6,10,6],[-32,-65,4,8,4],[41,-71,6,12,6],[6,-77,8,9,6],[-43,-20,5,5,5]];
  for(const[x,z,sx,sy,sz]of rockSites)rock(x,floorHeight(x,z)+sy*.27,z,sx,sy,sz);
  for(let i=0;i<17;i++){let x=random(-34,35),z=random(-64,17);if(Math.abs(x)<6&&z>-18)x+=x<0?-9:9;const s=random(.45,1.45);rock(x,floorHeight(x,z)+.02,z,s*1.25,s*.65,s)}
  const pebbleMaterial=new THREE.MeshStandardMaterial({color:0x718576,roughness:1});
  const pebbles=new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1,0),pebbleMaterial,210);
  const dummy=new THREE.Object3D();
  for(let i=0;i<210;i++){const x=random(-44,44),z=random(-70,28),s=random(.06,.32);dummy.position.set(x,floorHeight(x,z)-.05,z);dummy.scale.set(s*1.4,s*.6,s);dummy.rotation.set(random(0,3),random(0,6),random(0,3));dummy.updateMatrix();pebbles.setMatrixAt(i,dummy.matrix)}scene.add(pebbles);
  // Flexible kelp ribbons, all batched into one animated mesh.
  const kelp={p:[],c:[],flex:[],phase:[]};
  const kelpColors=[0x708b32,0x899e42,0x577e32,0xa4a44a,0x456c36,0x6c943e].map(c=>new THREE.Color(c));
  function plant(rootX,rootZ,height,small=false){
    const rootY=floorHeight(rootX,rootZ)-.08,phase=random(0,Math.PI*2),azimuth=random(0,Math.PI*2),baseColor=kelpColors[Math.floor(random(0,kelpColors.length))];
    const stem=t=>new THREE.Vector3(rootX+Math.sin(t*3.7+phase)*t*.48,rootY+t*height,rootZ+Math.cos(t*3.2+phase)*t*.43);
    function put(p,c){kelp.p.push(p.x,p.y,p.z);kelp.c.push(c.r,c.g,c.b);kelp.flex.push(clamp((p.y-rootY)/height,0,1.18));kelp.phase.push(phase)}
    function quad(a,b,c,d,color){put(a,color);put(b,color);put(c,color);put(b,color);put(d,color);put(c,color)}
    const stemColor=baseColor.clone().multiplyScalar(.65);
    for(let j=0;j<15;j++){
      const t0=j/15,t1=(j+1)/15,c0=stem(t0),c1=stem(t1),r0=(small?.024:.065)*(1-t0*.7),r1=(small?.024:.065)*(1-t1*.7);
      for(let k=0;k<5;k++){const a=k/5*Math.PI*2,b=(k+1)/5*Math.PI*2;quad(c0.clone().add(new THREE.Vector3(Math.cos(a)*r0,0,Math.sin(a)*r0)),c0.clone().add(new THREE.Vector3(Math.cos(b)*r0,0,Math.sin(b)*r0)),c1.clone().add(new THREE.Vector3(Math.cos(a)*r1,0,Math.sin(a)*r1)),c1.clone().add(new THREE.Vector3(Math.cos(b)*r1,0,Math.sin(b)*r1)),stemColor)}
    }
    const count=small?5:10;
    for(let j=0;j<count;j++){
      const node=.11+j/count*.81,origin=stem(node),angle=azimuth+(j%2?Math.PI:0)+random(-.32,.32),dir=new THREE.Vector3(Math.cos(angle),0,Math.sin(angle)),side=new THREE.Vector3(-Math.sin(angle),.08,Math.cos(angle)).normalize();
      const length=height*random(.16,.25)*(1-node*.28),width=(small?.16:random(.25,.52))*(.85+height*.015);
      function edge(t,sign){const c=origin.clone().addScaledVector(dir,length*(.74*t+.08*Math.sin(t*Math.PI)));c.y+=length*(1.05*t-.23*t*t);c.z+=Math.sin(t*5+phase)*.08*t;const w=Math.pow(Math.max(0,Math.sin(t*Math.PI)),.72)*width*(1+.09*Math.sin(t*26+phase));c.addScaledVector(side,w*sign);c.y+=.08*Math.sin(t*19+phase)*Math.sin(t*Math.PI);return c}
      for(let k=0;k<13;k++){const t0=k/13,t1=(k+1)/13;const color=baseColor.clone().lerp(new THREE.Color(0xb2ad52),t0*.24);quad(edge(t0,-1),edge(t0,1),edge(t1,-1),edge(t1,1),color)}
    }
    const side=new THREE.Vector3(Math.cos(azimuth),0,Math.sin(azimuth));
    for(let j=0;j<22;j++){const t=j/22,u=(j+1)/22,a=stem(t),b=stem(u),wa=Math.sin(t*Math.PI)*.17,wb=Math.sin(u*Math.PI)*.17;quad(a.clone().addScaledVector(side,-wa),a.clone().addScaledVector(side,wa),b.clone().addScaledVector(side,-wb),b.clone().addScaledVector(side,wb),baseColor)}
  }
  const groves=[[-12,9,5],[13,7,5],[-6,-5,3],[9,-9,3],[-20,-3,5],[21,-13,6],[-23,-21,7],[-4,-39,6],[23,-39,7],[-25,-49,7],[10,-65,7],[-35,-43,6],[-30,-68,6],[34,-68,7],[-39,1,5],[33,9,4]];
  for(const[x,z,count]of groves)for(let j=0;j<count;j++)plant(x+random(-3.3,3.3),z+random(-4,4),random(11,20.2));
  for(let i=0;i<47;i++){let x=random(-29,29),z=random(-54,18);if(Math.abs(x)<3)x+=5;plant(x,z,random(.7,2.1),true)}
  const kelpGeometry=new THREE.BufferGeometry();kelpGeometry.setAttribute('position',new THREE.Float32BufferAttribute(kelp.p,3));kelpGeometry.setAttribute('color',new THREE.Float32BufferAttribute(kelp.c,3));kelpGeometry.setAttribute('aFlex',new THREE.Float32BufferAttribute(kelp.flex,1));kelpGeometry.setAttribute('aPhase',new THREE.Float32BufferAttribute(kelp.phase,1));kelpGeometry.computeVertexNormals();
  const kelpMaterial=new THREE.MeshStandardMaterial({vertexColors:true,side:THREE.DoubleSide,roughness:.74,metalness:.04});
  kelpMaterial.onBeforeCompile=shader=>{shader.uniforms.uGardenTime=time;shader.vertexShader='uniform float uGardenTime;attribute float aFlex;attribute float aPhase;\n'+shader.vertexShader;shader.vertexShader=shader.vertexShader.replace('#include <begin_vertex>',`#include <begin_vertex>
    float kf=pow(max(0.,aFlex),1.5);transformed.x+=sin(uGardenTime*.63+position.y*.31+aPhase)*.85*kf;transformed.z+=cos(uGardenTime*.48+position.y*.27+aPhase)*.61*kf;
  `);shader.fragmentShader=shader.fragmentShader.replace('#include <color_fragment>','#include <color_fragment>\nif(!gl_FrontFacing)diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.34,.39,.12),.19);')};
  const kelpMesh=new THREE.Mesh(kelpGeometry,kelpMaterial);kelpMesh.frustumCulled=false;scene.add(kelpMesh);
  // Ochre, warm orange and olive coral. No imported assets or models.
  const coralBucket=newBucket(),spongeBucket=newBucket(),spongeHoles=newBucket();
  const coralColors=[0xd28b43,0xd8ab58,0xbe723d,0x9b9a4b,0xe1b567].map(c=>new THREE.Color(c));
  function seaFan(x,z,size,angle,color){
    const base=new THREE.Vector3(x,floorHeight(x,z),z),q=new THREE.Quaternion().setFromAxisAngle(UP,angle);
    function world(p){return p.clone().applyQuaternion(q).add(base)}
    function branch(start,theta,length,radius,depth){
      const end=start.clone().add(new THREE.Vector3(Math.sin(theta)*length,Math.cos(theta)*length,random(-.06,.06)*size));
      cylinderTo(coralBucket,world(start),world(end),radius,radius*.68,color,6);
      if(depth>0){branch(end,theta-random(.30,.63),length*.70,radius*.68,depth-1);branch(end,theta+random(.30,.63),length*.70,radius*.68,depth-1)}
    }
    branch(new THREE.Vector3(),0,size*.88,size*.085,3);
  }
  const coralSites=[[-7,7,1.2],[7,3,1.3],[-15,-10,1.1],[19,-17,1.5],[-20,-29,1.1],[22,-39,1.2],[-3,-42,.9],[12,-51,1.1],[-19,5,1],[17,-1,.8]];
  for(const[x,z,size]of coralSites){
    for(let j=0;j<3;j++)seaFan(x+random(-.9,.9),z+random(-.8,.8),size*random(.65,1.25),random(-1,1),coralColors[Math.floor(random(0,5))]);
    for(let j=0;j<6;j++){
      const sx=x+random(-1.4,1.4),sz=z+random(-1.2,1.2),sy=floorHeight(sx,sz),h=random(.4,1.25)*size,r=random(.14,.27);
      const points=[new THREE.Vector2(r*.7,0),new THREE.Vector2(r,.2*h),new THREE.Vector2(r*.74,.65*h),new THREE.Vector2(r*1.08,h),new THREE.Vector2(r*.72,h-.035),new THREE.Vector2(r*.6,h*.69)];
      const g=new THREE.LatheGeometry(points,9);const m=new THREE.Matrix4().makeTranslation(sx,sy,sz);appendGeometry(spongeBucket,g,m,coralColors[Math.floor(random(0,3))]);g.dispose();
      const hole=new THREE.CircleGeometry(r*.67,9);hole.rotateX(-Math.PI/2);tempMatrix.makeTranslation(sx,sy+h*.73,sz);appendGeometry(spongeHoles,hole,tempMatrix,0x253e34);hole.dispose();
    }
  }
  const coralMaterial=causticMaterial(new THREE.MeshStandardMaterial({vertexColors:true,roughness:.87}),.7);
  for(const b of[coralBucket,spongeBucket]){const m=new THREE.Mesh(geometryFrom(b),coralMaterial);m.receiveShadow=true;scene.add(m)}
  scene.add(new THREE.Mesh(geometryFrom(spongeHoles),new THREE.MeshStandardMaterial({vertexColors:true,roughness:1,side:THREE.DoubleSide})));
  // The Solace: individually laid planks, exposed ribs, a broken mast and a torn sail.
  const ship=new THREE.Group();ship.position.set(14,floorHeight(14,-35)-.25,-35);ship.rotation.set(.025,.68,-.095);scene.add(ship);
  const timber=newBucket(),ribs=newBucket(),ropeBucket=newBucket();
  const woods=[0x795237,0x8b633d,0x9d7648,0x6c513a,0xa28150,0x6e5940].map(c=>new THREE.Color(c));
  const woodColor=()=>woods[Math.floor(random(0,woods.length))];
  function hullWidth(z){return 3.25*Math.pow(Math.max(.01,1-Math.pow((z-.3)/9.2,2)),.52)}
  for(const sign of[-1,1])for(let row=0;row<9;row++)for(let section=0;section<17;section++){
    if(row>6&&((section>5&&section<9&&sign===1)||(section<3&&row===8)))continue;
    const z0=-7.8+section*.98,z1=z0+.935,th0=.15+row*.151,th1=th0+.135;
    const point=(z,th)=>new THREE.Vector3(sign*hullWidth(z)*Math.sin(th),.18+(1-Math.cos(th))*3.65,z);
    const a=point(z0,th0),b=point(z1,th0),c=point(z0,th1),d=point(z1,th1),color=woodColor();
    triangle(timber,a,b,c,color);triangle(timber,b,d,c,color);
  }
  for(let i=0;i<13;i++){
    const z=-7.4+i*1.25,w=hullWidth(z),points=[];
    for(let j=0;j<=18;j++){const theta=-Math.PI/2+j/18*Math.PI;points.push(new THREE.Vector3(Math.sin(theta)*w,.26+(1-Math.cos(theta))*3.65,z))}
    const curve=new THREE.CatmullRomCurve3(points);const g=new THREE.TubeGeometry(curve,22,.105,5,false);appendGeometry(ribs,g,new THREE.Matrix4(),0x5e4a33);g.dispose();
  }
  for(let i=0;i<18;i++){
    const x=-2.65+i*.30;let length=13.8-Math.abs(x)*1.15;
    const z=-.5+random(-.5,.5);
    if(i>5&&i<11){boxTo(timber,x,2.94,z-length*.29,.265,.12,length*.36,woodColor());boxTo(timber,x,2.94,z+length*.29,.265,.12,length*.27,woodColor())}
    else boxTo(timber,x,2.94,z,.265,.12,length,woodColor());
  }
  boxTo(ribs,0,.3,0,.38,.48,16.6,0x574935);
  for(const sign of[-1,1])for(let j=0;j<6;j++){const z=-6.9+j*2.5,x=sign*hullWidth(z)*.98;cylinderTo(ribs,new THREE.Vector3(x,3.25,z),new THREE.Vector3(x,4.0+random(-.2,.2),z),.09,.07,0x634f32);if(j<5)cylinderTo(ribs,new THREE.Vector3(x,3.9,z),new THREE.Vector3(sign*hullWidth(z+2.5),3.9,z+2.5),.07,.065,0x6c5838)}
  const mastBase=new THREE.Vector3(.25,2.75,-.8),mastTop=new THREE.Vector3(.15,10.65,-1.1);
  cylinderTo(ribs,mastBase,mastTop,.20,.105,0x6b5033,9);
  cylinderTo(ribs,new THREE.Vector3(-2.55,8.65,-1.05),new THREE.Vector3(2.75,8.35,-1.05),.105,.075,0x705438,7);
  cylinderTo(ribs,new THREE.Vector3(-.3,2.8,-5.4),new THREE.Vector3(-2.2,5.2,-6.1),.19,.13,0x624c33,8);
  for(let j=0;j<5;j++)boxTo(timber,random(-1.9,1.8),3.04,random(-6.4,5.4),random(.3,.5),.12,random(1.2,3.4),woodColor(),random(-.9,.9));
  const woodMaterial=causticMaterial(new THREE.MeshStandardMaterial({vertexColors:true,roughness:.94,side:THREE.DoubleSide}),.5);
  const hullMesh=new THREE.Mesh(geometryFrom(timber),woodMaterial);hullMesh.castShadow=true;hullMesh.receiveShadow=true;ship.add(hullMesh);
  const ribMesh=new THREE.Mesh(geometryFrom(ribs),woodMaterial);ribMesh.castShadow=true;ribMesh.receiveShadow=true;ship.add(ribMesh);
  const cloth=newBucket();
  function sailPoint(u,v){return new THREE.Vector3(-2.4+u*4.8,8.45-v*3.1-.17*u,-1.08+Math.sin(u*Math.PI)*Math.sin(v*Math.PI)*.7)}
  for(let y=0;y<13;y++)for(let x=0;x<20;x++){
    const u=x/20,v=y/13;
    if((y>8&&Math.sin(x*2.9)*2.5<y-10)||(x>12&&x<16&&y>4&&y<8)||(x<2&&y>5))continue;
    const color=new THREE.Color(0xb2a46c).multiplyScalar(random(.74,1.08));const a=sailPoint(u,v),b=sailPoint(u+.05,v),c=sailPoint(u,v+1/13),d=sailPoint(u+.05,v+1/13);triangle(cloth,a,c,b,color);triangle(cloth,b,c,d,color);
  }
  const sailMesh=new THREE.Mesh(geometryFrom(cloth),new THREE.MeshStandardMaterial({vertexColors:true,roughness:1,side:THREE.DoubleSide}));sailMesh.castShadow=true;ship.add(sailMesh);
  const rigging=[ [mastTop,new THREE.Vector3(0,3.5,8.1)], [mastTop,new THREE.Vector3(0,3.55,-7.65)], [new THREE.Vector3(-2.5,8.6,-1),new THREE.Vector3(-2.8,3.3,2.9)], [new THREE.Vector3(2.7,8.4,-1),new THREE.Vector3(2.8,3.3,3.1)] ];
  const ropeSegments=[];
  for(const[a,b]of rigging){const mid=new THREE.Vector3().addVectors(a,b).multiplyScalar(.5);mid.y-=.35;const curve=new THREE.QuadraticBezierCurve3(a,mid,b);const g=new THREE.TubeGeometry(curve,12,.025,4,false);appendGeometry(ropeBucket,g,new THREE.Matrix4(),0x4a5740);g.dispose();const points=curve.getPoints(6);for(let j=0;j<points.length-1;j++)ropeSegments.push([points[j],points[j+1]])}
  ship.add(new THREE.Mesh(geometryFrom(ropeBucket),new THREE.MeshStandardMaterial({vertexColors:true,roughness:1})));
  const nameCanvas=document.createElement('canvas');nameCanvas.width=512;nameCanvas.height=112;const nameContext=nameCanvas.getContext('2d');nameContext.fillStyle='#5b533a';nameContext.fillRect(0,0,512,112);nameContext.fillStyle='#c5b57b';nameContext.font='38px Georgia';nameContext.textAlign='center';nameContext.fillText('S  O  L  A  C  E',256,70);const nameTexture=new THREE.CanvasTexture(nameCanvas);nameTexture.colorSpace=THREE.SRGBColorSpace;
  const nameplate=new THREE.Mesh(new THREE.PlaneGeometry(2.8,.61),new THREE.MeshStandardMaterial({map:nameTexture,roughness:1}));nameplate.position.set(-3.03,2.52,-1.8);nameplate.rotation.y=-Math.PI/2;ship.add(nameplate);
  ship.updateMatrixWorld(true);
  const shipQuaternion=ship.quaternion.clone(),shipInverse=shipQuaternion.clone().invert();
  function shipBox(center,half){colliders.push({type:'box',center:ship.localToWorld(center.clone()),half:half.clone().addScalar(.57),quaternion:shipQuaternion.clone(),inverse:shipInverse.clone()})}
  function shipCapsule(a,b,r){colliders.push({type:'capsule',a:ship.localToWorld(a.clone()),b:ship.localToWorld(b.clone()),radius:r+.57})}
  shipBox(new THREE.Vector3(0,1.95,.3),new THREE.Vector3(3.47,2.1,9.0));
  shipBox(new THREE.Vector3(0,6.95,-.8),new THREE.Vector3(2.55,1.7,.55));
  shipCapsule(mastBase,mastTop,.24);shipCapsule(new THREE.Vector3(-2.55,8.65,-1.05),new THREE.Vector3(2.75,8.35,-1.05),.13);
  shipCapsule(new THREE.Vector3(-.3,2.8,-5.4),new THREE.Vector3(-2.2,5.2,-6.1),.2);
  for(const[a,b]of ropeSegments)shipCapsule(a,b,.025);
  const debris=newBucket();
  for(let i=0;i<12;i++){const x=14+random(-8,10),z=-35+random(-12,13);boxTo(debris,x,floorHeight(x,z)+.09,z,random(.2,.45),.12,random(1.1,3.8),woodColor(),random(-3,3))}
  const debrisMesh=new THREE.Mesh(geometryFrom(debris),woodMaterial);debrisMesh.receiveShadow=true;scene.add(debrisMesh);
  // Fish share a single body mesh. School direction turns as one; tails move independently.
  const fishBucket=newBucket();
  const fishBody=new THREE.SphereGeometry(1,10,7);fishBody.scale(.17,.285,.63);tempMatrix.makeTranslation(0,0,.06);appendGeometry(fishBucket,fishBody,tempMatrix,0xf0ca78);fishBody.dispose();
  const gold=new THREE.Color(0xe2a34e),darkGold=new THREE.Color(0xa97d3c);
  const tailTop=new THREE.Vector3(0,.36,-1.05),tailBottom=new THREE.Vector3(0,-.36,-1.05),tailBase=new THREE.Vector3(0,0,-.43);
  triangle(fishBucket,tailBase,tailTop,tailBottom,gold);triangle(fishBucket,new THREE.Vector3(0,.2,.1),new THREE.Vector3(0,.52,-.15),new THREE.Vector3(0,.22,-.44),darkGold);
  for(const sign of[-1,1]){triangle(fishBucket,new THREE.Vector3(sign*.11,-.02,.1),new THREE.Vector3(sign*.40,-.19,-.18),new THREE.Vector3(sign*.12,-.13,-.32),gold);const eye=new THREE.SphereGeometry(.038,6,4);tempMatrix.makeTranslation(sign*.135,.075,.45);appendGeometry(fishBucket,eye,tempMatrix,0x173f42);eye.dispose()}
  const fishGeometry=geometryFrom(fishBucket);const phases=new Float32Array(80);for(let i=0;i<80;i++)phases[i]=random(0,Math.PI*2);fishGeometry.setAttribute('iPhase',new THREE.InstancedBufferAttribute(phases,1));
  const fishMaterial=new THREE.MeshStandardMaterial({vertexColors:true,metalness:.24,roughness:.45,side:THREE.DoubleSide});
  fishMaterial.onBeforeCompile=shader=>{shader.uniforms.uGardenTime=time;shader.vertexShader='uniform float uGardenTime;attribute float iPhase;\n'+shader.vertexShader;shader.vertexShader=shader.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\ntransformed.x+=sin(uGardenTime*7.5+iPhase+position.z*3.)*max(0.,-position.z-.25)*.18;')};
  const schoolDefinitions=[{n:49,x:-1,y:9.8,z:-22,rx:8,rz:5,speed:.135,phase:.25,size:.74,color:0xffe3a2},{n:55,x:14,y:11.7,z:-43,rx:12,rz:8,speed:.10,phase:2.1,size:.82,color:0xf6bc75},{n:29,x:1,y:4.4,z:-5,rx:5,rz:4,speed:.18,phase:3.3,size:.43,color:0xffbe74},{n:72,x:-3,y:14,z:-65,rx:20,rz:8,speed:.075,phase:1.5,size:.6,color:0xadc9b3}];
  const schools=schoolDefinitions.map(def=>{
    const mesh=new THREE.InstancedMesh(fishGeometry,fishMaterial,def.n);mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);mesh.frustumCulled=false;scene.add(mesh);
    const fish=[];for(let i=0;i<def.n;i++){fish.push({offset:new THREE.Vector3(random(-2.2,2.2),random(-1.25,1.25),random(-5,5)),phase:random(0,6.28),size:random(.72,1.2)*def.size});mesh.setColorAt(i,new THREE.Color(def.color).multiplyScalar(random(.84,1.08)))}
    return{...def,mesh,fish};
  });
  const schoolCenter=new THREE.Vector3(),schoolDirection=new THREE.Vector3(),schoolQuaternion=new THREE.Quaternion(),fishPosition=new THREE.Vector3(),fishDirection=new THREE.Vector3();
  function animateFish(t){
    for(const s of schools){const a=t*s.speed+s.phase;schoolCenter.set(s.x+Math.sin(a)*s.rx,s.y+Math.sin(a*.8)*.8,s.z+Math.cos(a)*s.rz);schoolDirection.set(Math.cos(a)*s.rx,.64*Math.cos(a*.8),-Math.sin(a)*s.rz).normalize();schoolQuaternion.setFromUnitVectors(FORWARD,schoolDirection);
      for(let i=0;i<s.fish.length;i++){const f=s.fish[i];fishPosition.copy(f.offset);fishPosition.x+=Math.sin(t*1.4+f.phase)*.14;fishPosition.y+=Math.sin(t*1.8+f.phase)*.11;fishPosition.applyQuaternion(schoolQuaternion).add(schoolCenter);fishDirection.copy(schoolDirection);fishDirection.x+=Math.sin(t*1.1+f.phase)*.055;fishDirection.y+=Math.cos(t*.8+f.phase)*.035;fishDirection.normalize();dummy.position.copy(fishPosition);dummy.quaternion.setFromUnitVectors(FORWARD,fishDirection);dummy.scale.setScalar(f.size);dummy.updateMatrix();s.mesh.setMatrixAt(i,dummy.matrix)}s.mesh.instanceMatrix.needsUpdate=true;
    }
  }
  // Mantas: broad, curved wings with a slow travelling wing beat.
  function makeManta(phase,scale){
    const group=new THREE.Group(),b=newBucket();
    function point(u,v){const a=Math.abs(u);return new THREE.Vector3(u*3.25,.07*Math.sin(v*Math.PI)-a*.14,(1.06-.78*Math.pow(a,1.35))*(1-v)+(-1.30+1.05*Math.pow(a,1.4))*v)}
    for(let x=0;x<30;x++)for(let y=0;y<10;y++){const u=-1+x/15,v=y/10,a=point(u,v),bb=point(u+1/15,v),c=point(u,v+.1),d=point(u+1/15,v+.1),col=new THREE.Color().lerpColors(new THREE.Color(0x174f59),new THREE.Color(0x628a72),Math.pow(Math.abs(u),3)*.75);triangle(b,a,bb,c,col);triangle(b,bb,d,c,col)}
    const mat=new THREE.MeshStandardMaterial({vertexColors:true,side:THREE.DoubleSide,roughness:.68,metalness:.09});
    mat.onBeforeCompile=shader=>{shader.uniforms.uGardenTime=time;shader.uniforms.uMantaPhase={value:phase};shader.vertexShader='uniform float uGardenTime;uniform float uMantaPhase;\n'+shader.vertexShader;shader.vertexShader=shader.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\ntransformed.y+=sin(uGardenTime*.92+uMantaPhase-abs(position.x)*.58)*pow(abs(position.x)/3.25,1.5)*.74;');shader.fragmentShader=shader.fragmentShader.replace('#include <color_fragment>','#include <color_fragment>\nif(!gl_FrontFacing)diffuseColor.rgb=vec3(.44,.59,.46);')};
    const wings=new THREE.Mesh(geometryFrom(b),mat);wings.frustumCulled=false;group.add(wings);
    const bodyMat=new THREE.MeshStandardMaterial({color:0x275d60,roughness:.8});
    const body=new THREE.Mesh(new THREE.SphereGeometry(1,16,10),bodyMat);body.scale.set(.49,.21,1.25);group.add(body);
    const tailCurve=new THREE.CatmullRomCurve3([new THREE.Vector3(0,-.02,-1),new THREE.Vector3(.02,-.12,-2),new THREE.Vector3(.18,-.05,-3.1),new THREE.Vector3(.13,.08,-4.5)]);
    const tail=new THREE.Mesh(new THREE.TubeGeometry(tailCurve,20,.032,5,false),bodyMat);group.add(tail);
    for(const sign of[-1,1]){const hornCurve=new THREE.CatmullRomCurve3([new THREE.Vector3(sign*.32,-.03,.77),new THREE.Vector3(sign*.39,-.03,1.24),new THREE.Vector3(sign*.25,.02,1.43)]);group.add(new THREE.Mesh(new THREE.TubeGeometry(hornCurve,10,.09,6,false),bodyMat))}
    group.scale.setScalar(scale);scene.add(group);return{group,tail,phase};
  }
  const mantas=[{...makeManta(.4,.94),x:-2,y:14,z:-23,rx:14,rz:8,speed:.075,a:1.4},{...makeManta(2.2,.78),x:-18,y:15.7,z:-48,rx:13,rz:9,speed:.065,a:3.9},{...makeManta(4.1,.66),x:23,y:17,z:-62,rx:16,rz:10,speed:.057,a:1.8}];
  function animateMantas(t){for(const m of mantas){const a=t*m.speed+m.a;m.group.position.set(m.x+Math.sin(a)*m.rx,m.y+Math.sin(t*.21+m.phase)*.5,m.z+Math.cos(a)*m.rz);tempVector.set(Math.cos(a)*m.rx,.15*Math.cos(t*.21+m.phase),-Math.sin(a)*m.rz).normalize();m.group.quaternion.setFromUnitVectors(FORWARD,tempVector);m.group.rotateZ(Math.sin(t*.26+m.phase)*.035);m.tail.rotation.y=Math.sin(t*.7+m.phase)*.035}}
  // Suspended particles and rising bubbles catch little pieces of the light.
  const dustPositions=[];for(let i=0;i<(mobile?600:1000);i++)dustPositions.push(random(-58,58),random(.3,22),random(-79,35));
  const dustGeometry=new THREE.BufferGeometry();dustGeometry.setAttribute('position',new THREE.Float32BufferAttribute(dustPositions,3));
  const dust=new THREE.Points(dustGeometry,new THREE.PointsMaterial({color:0xd6e9c4,size:.047,map:glowMap,transparent:true,opacity:.38,depthWrite:false,blending:THREE.AdditiveBlending,sizeAttenuation:true}));scene.add(dust);
  const bubblePositions=[],bubbleSizes=[],bubbleSpeeds=[],bubbleSeeds=[];
  for(let i=0;i<105;i++){const column=i%4;let x,z;if(column===0){x=random(-5,6);z=random(1,20)}else if(column===1){x=random(10,18);z=random(-39,-28)}else if(column===2){x=random(-18,-8);z=random(-30,-18)}else{x=random(-32,32);z=random(-65,6)}bubblePositions.push(x,random(0,22),z);bubbleSizes.push(random(.055,.17));bubbleSpeeds.push(random(.38,.85));bubbleSeeds.push(random(0,6.28))}
  const bubbleGeometry=new THREE.BufferGeometry();bubbleGeometry.setAttribute('position',new THREE.Float32BufferAttribute(bubblePositions,3));bubbleGeometry.setAttribute('aSize',new THREE.Float32BufferAttribute(bubbleSizes,1));bubbleGeometry.setAttribute('aSpeed',new THREE.Float32BufferAttribute(bubbleSpeeds,1));bubbleGeometry.setAttribute('aSeed',new THREE.Float32BufferAttribute(bubbleSeeds,1));
  const bubbleMaterial=new THREE.ShaderMaterial({transparent:true,depthWrite:false,uniforms:{uTime:time,uRatio:{value:pixelRatio}},vertexShader:`uniform float uTime;uniform float uRatio;attribute float aSize;attribute float aSpeed;attribute float aSeed;varying float vDepth;void main(){vec3 p=position;p.y=mod(position.y+uTime*aSpeed,22.);p.x+=sin(p.y*.7+uTime*.4+aSeed)*.18;p.z+=cos(p.y*.5+uTime*.3+aSeed)*.13;vec4 mv=modelViewMatrix*vec4(p,1.);vDepth=-mv.z;gl_Position=projectionMatrix*mv;gl_PointSize=clamp(aSize*uRatio*660./max(1.,-mv.z),1.5,38.);}`,fragmentShader:`varying float vDepth;void main(){vec2 p=gl_PointCoord-.5;float r=length(p)*2.;if(r>1.)discard;float rim=pow(r,9.)*.45;float shine=exp(-dot(p-vec2(-.18,.19),p-vec2(-.18,.19))*95.)*.65;float a=(rim+shine)*.6*exp(-vDepth*.009);gl_FragColor=vec4(.69,.86,.75,a);}`});
  const bubbles=new THREE.Points(bubbleGeometry,bubbleMaterial);bubbles.frustumCulled=false;bubbles.renderOrder=5;scene.add(bubbles);
  // Collision is applied in short steps so even a fast guided drift cannot cross a solid object.
  const collisionLocal=new THREE.Vector3(),segment=new THREE.Vector3(),closest=new THREE.Vector3(),difference=new THREE.Vector3();
  function resolveAt(p){
    for(let pass=0;pass<4;pass++){
      p.x=clamp(p.x,-77,77);p.z=clamp(p.z,-78,51);p.y=clamp(p.y,floorHeight(p.x,p.z)+1.08,20.8);
      for(const c of colliders){
        if(c.type==='capsule'){
          segment.subVectors(c.b,c.a);const t=clamp(difference.subVectors(p,c.a).dot(segment)/segment.lengthSq(),0,1);closest.copy(c.a).addScaledVector(segment,t);difference.subVectors(p,closest);const d=difference.length();if(d<c.radius){if(d<.0001)difference.set(1,0,0);else difference.divideScalar(d);p.copy(closest).addScaledVector(difference,c.radius+.003)}
        }else{
          collisionLocal.copy(p).sub(c.center).applyQuaternion(c.inverse);
          if(c.type==='ellipsoid'){
            const r=c.radii;const d=collisionLocal.x*collisionLocal.x/(r.x*r.x)+collisionLocal.y*collisionLocal.y/(r.y*r.y)+collisionLocal.z*collisionLocal.z/(r.z*r.z);
            if(d<1){if(d<.000001)collisionLocal.set(0,r.y+.001,0);else collisionLocal.multiplyScalar(1.002/Math.sqrt(d));p.copy(collisionLocal.applyQuaternion(c.quaternion)).add(c.center)}
          }else{
            const h=c.half;if(Math.abs(collisionLocal.x)<h.x&&Math.abs(collisionLocal.y)<h.y&&Math.abs(collisionLocal.z)<h.z){const dx=h.x-Math.abs(collisionLocal.x),dy=h.y-Math.abs(collisionLocal.y),dz=h.z-Math.abs(collisionLocal.z);if(dx<=dy&&dx<=dz)collisionLocal.x=(collisionLocal.x<0?-1:1)*(h.x+.002);else if(dy<=dz)collisionLocal.y=(collisionLocal.y<0?-1:1)*(h.y+.002);else collisionLocal.z=(collisionLocal.z<0?-1:1)*(h.z+.002);p.copy(collisionLocal.applyQuaternion(c.quaternion)).add(c.center)}
          }
        }
      }
    }
    p.y=clamp(p.y,floorHeight(p.x,p.z)+1.08,20.8);return p;
  }
  const moveDelta=new THREE.Vector3();
  function moveSafely(p,destination){moveDelta.subVectors(destination,p);const steps=Math.max(1,Math.ceil(moveDelta.length()/.28));moveDelta.divideScalar(steps);for(let i=0;i<steps;i++){p.add(moveDelta);resolveAt(p)}return p}
  const playerPosition=new THREE.Vector3(0,6.5,19);
  let yaw=-.025,pitch=-.055,targetYaw=yaw,targetPitch=pitch,speed=0,holding=false,activePointer=null,lastX=0,lastY=0;
  camera.position.copy(playerPosition);camera.rotation.set(pitch,yaw,0,'YXZ');
  const desiredPosition=new THREE.Vector3(),moveDirection=new THREE.Vector3(),lookDirection=new THREE.Vector3();
  let demo=false,demoStarted=0,demoLead=0,demoFrom=new THREE.Vector3(),stoppedTourByPointer=false;
  const demoRoute=new THREE.CatmullRomCurve3([new THREE.Vector3(0,6.5,19),new THREE.Vector3(-3,5.8,5),new THREE.Vector3(-7,4.9,-9),new THREE.Vector3(-11,4.0,-18),new THREE.Vector3(-3,6.3,-25),new THREE.Vector3(7,7,-21),new THREE.Vector3(9,8.3,-6),new THREE.Vector3(4,7,11)],true,'catmullrom',.34);
  const demoLook=new THREE.CatmullRomCurve3([new THREE.Vector3(-5,6,-23),new THREE.Vector3(-11,5,-26),new THREE.Vector3(-11,4.4,-29),new THREE.Vector3(-10,4.5,-32),new THREE.Vector3(14,4.2,-35),new THREE.Vector3(15,6,-35),new THREE.Vector3(6,13,-25),new THREE.Vector3(-4,7,-23)],true,'catmullrom',.35);
  function hideIntro(){$('intro').classList.add('gone')}
  function stopDemo(){if(!demo)return;demo=false;speed=0;camera.getWorldDirection(lookDirection);pitch=targetPitch=Math.asin(clamp(lookDirection.y,-1,1));yaw=targetYaw=Math.atan2(-lookDirection.x,-lookDirection.z);document.body.classList.remove('tour-active');$('tourText').textContent='Explore for me';$('tourButton').setAttribute('aria-pressed','false');$('tourButton').setAttribute('aria-label','Start a guided underwater tour');$('moodText').textContent='NOWHERE TO BE. JUST HERE.'}
  function startDemo(initial=false){holding=false;speed=0;demo=true;demoStarted=performance.now();demoLead=initial?0:2.5;demoFrom.copy(playerPosition);document.body.classList.add('tour-active');document.body.classList.remove('gliding');$('swimText').textContent='Hold to swim';$('tourText').textContent='End the drift';$('tourButton').setAttribute('aria-pressed','true');$('tourButton').setAttribute('aria-label','Stop the guided tour');if(!initial)hideIntro()}
  let toastTimeout;
  function toast(message){$('toast').textContent=message;$('toast').classList.add('show');clearTimeout(toastTimeout);toastTimeout=setTimeout(()=>$('toast').classList.remove('show'),3500)}
  window.addEventListener('pointerdown',e=>{stoppedTourByPointer=false;if(demo&&e.isTrusted){stoppedTourByPointer=!!e.target.closest?.('#tourButton');stopDemo();hideIntro()}},{capture:true});
  function pointerDown(e){if(activePointer!==null||e.button>0)return;e.preventDefault();stopDemo();holding=true;activePointer=e.pointerId;lastX=e.clientX;lastY=e.clientY;e.currentTarget.setPointerCapture?.(e.pointerId);document.body.classList.add('gliding');$('swimText').textContent='Gliding…';hideIntro();$('helpPanel').classList.remove('open');$('helpButton').setAttribute('aria-expanded','false')}
  function pointerMove(e){if(e.pointerId!==activePointer)return;e.preventDefault();const dx=e.clientX-lastX,dy=e.clientY-lastY;targetYaw-=dx*.0035;targetPitch=clamp(targetPitch-dy*.003,-.95,.98);lastX=e.clientX;lastY=e.clientY}
  function pointerUp(e){if(activePointer!==e.pointerId)return;holding=false;activePointer=null;document.body.classList.remove('gliding');$('swimText').textContent='Hold to swim'}
  for(const surface of[renderer.domElement,$('swimButton')]){surface.addEventListener('pointerdown',pointerDown);surface.addEventListener('pointermove',pointerMove);surface.addEventListener('pointerup',pointerUp);surface.addEventListener('pointercancel',pointerUp);surface.addEventListener('lostpointercapture',pointerUp);surface.addEventListener('contextmenu',e=>e.preventDefault())}
  window.addEventListener('blur',()=>{holding=false;activePointer=null;document.body.classList.remove('gliding');$('swimText').textContent='Hold to swim'});
  $('tourButton').addEventListener('click',()=>{if(stoppedTourByPointer){stoppedTourByPointer=false;return}if(demo)stopDemo();else startDemo()});
  $('helpButton').addEventListener('click',()=>{const open=$('helpPanel').classList.toggle('open');$('helpButton').setAttribute('aria-expanded',String(open))});
  $('helpClose').addEventListener('click',()=>{$('helpPanel').classList.remove('open');$('helpButton').setAttribute('aria-expanded','false')});
  // Quiet ocean audio, synthesized locally after an explicit sound-button tap.
  let audioContext,masterGain,soundOn=false,soundInterval,suspendTimeout;
  function buildAudio(){
    const Audio=window.AudioContext||window.webkitAudioContext;if(!Audio)throw new Error('Audio unavailable');audioContext=new Audio();masterGain=audioContext.createGain();masterGain.gain.value=0;masterGain.connect(audioContext.destination);
    const length=audioContext.sampleRate*4,buffer=audioContext.createBuffer(1,length,audioContext.sampleRate),data=buffer.getChannelData(0);let previous=0;
    for(let i=0;i<length;i++){previous=(previous+Math.random()*.045-.0225)/1.025;data[i]=previous*3}
    const noise=audioContext.createBufferSource();noise.buffer=buffer;noise.loop=true;
    const low=audioContext.createBiquadFilter();low.type='lowpass';low.frequency.value=520;
    const noiseGain=audioContext.createGain();noiseGain.gain.value=.24;noise.connect(low);low.connect(noiseGain);noiseGain.connect(masterGain);noise.start();
    const lfo=audioContext.createOscillator();lfo.frequency.value=.09;const lfoGain=audioContext.createGain();lfoGain.gain.value=.055;lfo.connect(lfoGain);lfoGain.connect(noiseGain.gain);lfo.start();
    for(const frequency of[52,78]){const o=audioContext.createOscillator(),g=audioContext.createGain();o.type='sine';o.frequency.value=frequency;g.gain.value=.011;o.connect(g);g.connect(masterGain);o.start()}
    soundInterval=setInterval(()=>{if(!soundOn||audioContext.state!=='running')return;const now=audioContext.currentTime,o=audioContext.createOscillator(),g=audioContext.createGain();o.type='sine';o.frequency.setValueAtTime(240+Math.random()*180,now);o.frequency.exponentialRampToValueAtTime(150+Math.random()*80,now+.65);g.gain.setValueAtTime(0,now);g.gain.linearRampToValueAtTime(.006,now+.04);g.gain.exponentialRampToValueAtTime(.0001,now+1.2);o.connect(g);g.connect(masterGain);o.start(now);o.stop(now+1.25);o.onended=()=>{o.disconnect();g.disconnect()}},3400);
  }
  $('soundButton').addEventListener('click',async()=>{
    try{clearTimeout(suspendTimeout);if(!audioContext)buildAudio();soundOn=!soundOn;if(soundOn)await audioContext.resume();const now=audioContext.currentTime;masterGain.gain.cancelScheduledValues(now);masterGain.gain.setTargetAtTime(soundOn?.7:0,now,.35);if(!soundOn)suspendTimeout=setTimeout(()=>audioContext.suspend().catch(()=>{}),1300);$('soundButton').classList.toggle('on',soundOn);$('soundButton').setAttribute('aria-pressed',String(soundOn));$('soundButton').setAttribute('aria-label',soundOn?'Turn underwater sound off':'Turn underwater sound on');$('soundText').textContent=soundOn?'Sound on':'Sound off';if(soundOn)toast('A little ocean, in your headphones.')}catch(error){soundOn=false;toast('Sound is unavailable in this browser.')}
  });
  document.addEventListener('visibilitychange',()=>{holding=false;activePointer=null;document.body.classList.remove('gliding');$('swimText').textContent='Hold to swim';if(audioContext){if(document.hidden)audioContext.suspend().catch(()=>{});else if(soundOn)audioContext.resume().catch(()=>{})}});
  window.addEventListener('resize',()=>{camera.aspect=innerWidth/innerHeight;camera.fov=innerWidth<760?74:62;camera.updateProjectionMatrix();renderer.setSize(innerWidth,innerHeight)});
  // The guided view uses the same live world, lighting and collision as free swimming.
  animateFish(0);animateMantas(0);resolveAt(playerPosition);camera.position.copy(playerPosition);renderer.shadowMap.needsUpdate=true;
  document.body.classList.add('ready');$('loader').classList.add('leaving');setTimeout(()=>$('loader').remove(),1250);
  if(location.hash.toLowerCase()==='#demo'){startDemo(true);setTimeout(hideIntro,5500)}
  const clock=new THREE.Clock();let elapsed=0,uiTimer=0,slowFrames=0,lastFrame=performance.now();
  const landmarks=[{x:0,z:5,name:'THE KELP SHALLOWS'},{x:-11,z:-25,name:'THE STONE ARCH'},{x:14,z:-35,name:'THE SOLACE WRECK'},{x:0,z:-66,name:'THE BLUE GARDEN'}];
  function frame(now){
    requestAnimationFrame(frame);
    const rawDelta=clock.getDelta();if(document.hidden)return;const dt=Math.min(rawDelta,.045);elapsed+=dt;time.value=elapsed*(reduced?.58:1);
    animateFish(time.value);animateMantas(time.value);dust.rotation.y=Math.sin(time.value*.035)*.012;
    if(demo){
      const passed=(now-demoStarted)/1000;const u=((Math.max(0,passed-demoLead)/20)%1+1)%1;
      demoRoute.getPointAt(u,desiredPosition);
      if(demoLead>0&&passed<demoLead){const k=clamp(passed/demoLead,0,1),e=k*k*(3-2*k);desiredPosition.lerpVectors(demoFrom,desiredPosition,e)}
      moveSafely(playerPosition,desiredPosition);camera.position.copy(playerPosition);demoLook.getPoint(u,lookDirection);camera.lookAt(lookDirection);$('tourFill').style.width=(u*100).toFixed(1)+'%';
    }else{
      const smooth=1-Math.exp(-dt*9);yaw+=(targetYaw-yaw)*smooth;pitch+=(targetPitch-pitch)*smooth;speed+=((holding?3.15:0)-speed)*(1-Math.exp(-dt*(holding?2.0:3.6)));
      camera.rotation.set(pitch,yaw,Math.sin(elapsed*.6)*.0014,'YXZ');moveDirection.set(0,0,-1).applyQuaternion(camera.quaternion);desiredPosition.copy(playerPosition).addScaledVector(moveDirection,speed*dt);moveSafely(playerPosition,desiredPosition);camera.position.copy(playerPosition);camera.position.y+=Math.sin(elapsed*.73)*.018;
    }
    uiTimer+=dt;
    if(uiTimer>.16){uiTimer=0;$('depthValue').textContent=(22-camera.position.y).toFixed(1);let best=Infinity,place=landmarks[0];for(const l of landmarks){const distance=(playerPosition.x-l.x)**2+(playerPosition.z-l.z)**2;if(distance<best){best=distance;place=l}}$('locationName').textContent=place.name;if(demo){const remain=20-Math.floor(Math.max(0,(now-demoStarted)/1000-demoLead)%20);$('moodText').textContent='A GUIDED DRIFT  ·  0:'+String(remain).padStart(2,'0')}}
    renderer.render(scene,camera);
    const frameTime=now-lastFrame;lastFrame=now;if(frameTime>36&&frameTime<180)slowFrames++;else slowFrames=Math.max(0,slowFrames-1);
    if(slowFrames>95&&pixelRatio>1){pixelRatio=Math.max(1,pixelRatio-.25);renderer.setPixelRatio(pixelRatio);renderer.setSize(innerWidth,innerHeight);bubbleMaterial.uniforms.uRatio.value=pixelRatio;slowFrames=0}
  }
  requestAnimationFrame(frame);
}
createGarden().catch(error=>{
  console.error('The garden could not start:',error);
  const loader=document.getElementById('loader');if(loader){loader.classList.remove('leaving');const heading=loader.querySelector('h2');if(heading)heading.textContent='The ocean is just out of reach.';const detail=document.getElementById('loadingDetail');if(detail)detail.textContent='This garden needs WebGL and a connection to load Three.js. Please enable graphics acceleration and reload.'}
});
</script>
</body>
</html>