Skip to content
VibeCodeBench
Back to the app

The code

Swim the Kelp Garden by GPT-6.1 Terra

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.)37.6 KB · 588 lines · loads cdnjs.cloudflare.com/ajax/libs/three.js/0.149.0/three.min.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="#073b45">
<title>The Kelp Garden — a little world to drift in</title>
<style>
  :root{color-scheme:dark;--cream:#f3f1dc;--muted:#c0d5c9;--gold:#e8c782;--ink:#062d35}
  *{box-sizing:border-box}
  html,body{margin:0;width:100%;height:100%;overflow:hidden}
  body{font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--cream);background:#073b45;overscroll-behavior:none}
  button{font:inherit}
  button:focus-visible{outline:2px solid #f7d895;outline-offset:4px}
  #stage{position:fixed;inset:0;touch-action:none;cursor:grab;background:radial-gradient(ellipse at 50% 5%,#287c79 0%,#0c5360 45%,#082e3d 100%)}
  #stage:active{cursor:grabbing}
  #stage canvas{display:block;width:100%;height:100%;touch-action:none}
  .shade{position:fixed;inset:0;pointer-events:none;background:linear-gradient(180deg,rgba(0,28,36,.5) 0%,transparent 22%,transparent 62%,rgba(0,24,31,.57) 100%),linear-gradient(90deg,rgba(1,35,40,.26),transparent 54%);z-index:1}
  .topbar{position:fixed;z-index:3;left:0;right:0;top:0;padding:max(25px,env(safe-area-inset-top)) max(35px,env(safe-area-inset-right)) 0 max(35px,env(safe-area-inset-left));display:flex;align-items:center;justify-content:space-between;pointer-events:none}
  .brand{display:flex;align-items:center;gap:12px}
  .brand-mark{width:39px;height:39px;display:grid;place-items:center;border:1px solid rgba(233,233,207,.5);border-radius:50%;color:#eddb9f}
  .brand-title{font-family:Georgia,"Times New Roman",serif;font-size:19px;letter-spacing:.025em;line-height:1}
  .brand-sub{display:block;margin-top:5px;color:#c7d8cd;font-size:8px;letter-spacing:.19em;font-weight:700;text-transform:uppercase}
  .top-actions{display:flex;align-items:center;gap:11px;pointer-events:auto}
  .current{margin-right:15px;display:flex;align-items:center;gap:8px;color:#d2e2d6;font-size:9px;font-weight:700;letter-spacing:.16em;text-transform:uppercase}
  .current i{width:6px;height:6px;background:#dfcf8b;border-radius:50%;box-shadow:0 0 12px #d9c67d}
  .circle-button,.guide-button{height:46px;color:#f4f3e3;background:rgba(5,44,50,.38);border:1px solid rgba(220,238,220,.3);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);cursor:pointer;transition:background .2s,border-color .2s}
  .circle-button:hover,.guide-button:hover{background:rgba(16,83,83,.7);border-color:rgba(234,240,216,.7)}
  .circle-button{width:46px;border-radius:50%;display:grid;place-items:center}
  .guide-button{padding:0 18px;border-radius:30px;font-size:10px;font-weight:750;letter-spacing:.13em;text-transform:uppercase}
  .intro{position:fixed;z-index:2;top:50%;left:clamp(36px,6.4vw,100px);width:min(440px,calc(100% - 60px));transform:translateY(-48%);pointer-events:none;transition:opacity .65s,transform .65s}
  .intro.gone{opacity:0;transform:translateY(-42%);visibility:hidden}
  .eyebrow{display:flex;align-items:center;gap:11px;color:#e7d5a1;font-size:10px;font-weight:800;letter-spacing:.22em;text-transform:uppercase}
  .eyebrow:before{content:"";width:27px;height:1px;background:#e7d5a1}
  h1{font-family:Georgia,"Times New Roman",serif;font-size:clamp(53px,6.3vw,91px);font-weight:400;letter-spacing:-.055em;line-height:.98;margin:25px 0 22px;text-shadow:0 3px 30px rgba(0,35,39,.22)}
  h1 em{font-weight:400;color:#e9d49c}
  .intro p{max-width:310px;color:#e1e8d9;font-size:14px;line-height:1.75;margin:0 0 29px;text-shadow:0 1px 10px rgba(0,20,24,.65)}
  .enter{pointer-events:auto;display:inline-flex;align-items:center;gap:31px;min-height:52px;padding:0 21px 0 23px;border:0;border-radius:3px;background:#e9ce91;color:#183d3b;font-size:10px;font-weight:850;letter-spacing:.15em;text-transform:uppercase;cursor:pointer;box-shadow:0 8px 28px rgba(0,30,30,.15)}
  .enter:hover{background:#f5dda3}
  .enter svg{transition:transform .2s}.enter:hover svg{transform:translateX(4px)}
  .bottom{position:fixed;z-index:3;bottom:0;left:0;right:0;padding:0 max(35px,env(safe-area-inset-right)) max(27px,env(safe-area-inset-bottom)) max(35px,env(safe-area-inset-left));display:flex;justify-content:space-between;align-items:flex-end;gap:20px;pointer-events:none}
  .place{display:flex;align-items:center;gap:14px}
  .place-number{font-family:Georgia,serif;font-size:29px;color:#ead6a2;font-style:italic}
  .place-copy strong,.depth strong{display:block;font-size:10px;letter-spacing:.15em;text-transform:uppercase;color:#f0f0de}
  .place-copy span,.depth span{display:block;color:#b5d0c5;font-size:10px;letter-spacing:.04em;margin-top:6px}
  .bottom-right{display:flex;align-items:center;gap:25px}
  .depth{padding-right:25px;border-right:1px solid rgba(229,236,213,.3)}
  .depth strong{font-size:17px;letter-spacing:.04em;font-family:Georgia,serif;font-weight:400}
  .depth span{font-size:9px;letter-spacing:.15em;text-transform:uppercase}
  .control-hint{display:flex;align-items:center;gap:12px}
  .control-icon{width:46px;height:46px;border:1px solid rgba(230,239,221,.36);border-radius:50%;display:grid;place-items:center;color:#f1e0ad}
  .control-hint strong{display:block;font-size:10px;letter-spacing:.12em;text-transform:uppercase}
  .control-hint span{display:block;font-size:10px;color:#bed4c8;margin-top:6px}
  .demo-badge{position:fixed;z-index:3;top:101px;right:35px;padding:10px 14px;border:1px solid rgba(224,238,218,.28);border-radius:30px;background:rgba(5,44,50,.5);color:#e9e6c9;font-size:10px;letter-spacing:.11em;text-transform:uppercase;backdrop-filter:blur(10px);pointer-events:none}
  [hidden]{display:none!important}
  .help-panel{position:fixed;z-index:5;right:35px;top:93px;width:min(315px,calc(100vw - 40px));padding:26px;background:rgba(6,48,54,.93);border:1px solid rgba(225,238,215,.3);box-shadow:0 16px 45px rgba(0,22,25,.25);backdrop-filter:blur(18px);border-radius:8px}
  .help-panel .small{font-size:9px;letter-spacing:.2em;text-transform:uppercase;color:#e4cc92;font-weight:800}
  .help-panel h2{font-family:Georgia,serif;font-size:28px;font-weight:400;margin:12px 0}
  .help-panel p{font-size:13px;line-height:1.7;color:#d3e1d5;margin:9px 0}
  .help-panel button{min-height:44px;margin-top:10px;border:1px solid rgba(235,236,212,.5);border-radius:3px;background:transparent;color:#f4efdb;padding:0 19px;font-size:10px;font-weight:750;letter-spacing:.12em;text-transform:uppercase;cursor:pointer}
  .error{position:fixed;z-index:7;left:50%;top:50%;transform:translate(-50%,-50%);width:min(390px,calc(100% - 40px));padding:25px;border:1px solid rgba(232,236,211,.3);border-radius:8px;background:#103e45;line-height:1.6;box-shadow:0 15px 40px rgba(0,0,0,.25)}
  .error strong{font-family:Georgia,serif;font-size:25px;font-weight:400;display:block;margin-bottom:8px}
  .error span{font-size:13px;color:#d5e2d3}
  @media(max-width:650px){
    .topbar{padding:20px 20px 0}
    .brand-mark{width:36px;height:36px}.brand-title{font-size:17px}.brand-sub{font-size:7px}
    .top-actions{gap:7px}.current{display:none}.guide-button{padding:0 13px;font-size:9px}.circle-button,.guide-button{height:44px}.circle-button{width:44px}
    .intro{left:25px;top:43%;width:calc(100% - 50px);transform:translateY(-42%)}
    .intro.gone{transform:translateY(-35%)}
    .eyebrow{font-size:9px}h1{font-size:clamp(50px,13vw,70px);margin:20px 0 17px}
    .intro p{font-size:13px;max-width:265px;margin-bottom:22px}.enter{min-height:50px}
    .bottom{padding:0 20px max(23px,env(safe-area-inset-bottom));align-items:flex-end}
    .place-number{font-size:24px}.place{gap:9px}.place-copy strong{font-size:9px}.place-copy span{font-size:9px}
    .bottom-right{gap:0}.depth{display:none}.control-icon{width:41px;height:41px}.control-hint{gap:9px}.control-hint strong{font-size:9px}.control-hint span{font-size:9px;max-width:135px;line-height:1.4}
    .help-panel{right:20px;top:80px}.demo-badge{right:20px;top:79px;font-size:9px}
  }
  @media(max-height:500px){.intro{top:48%}.intro p{margin-bottom:14px}.eyebrow{font-size:8px}h1{font-size:48px;margin:12px 0}.bottom{padding-bottom:15px}.place-copy span{display:none}}
  @media(prefers-reduced-motion:reduce){.intro,.enter svg{transition:none}}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive underwater garden"></div>
<div class="shade"></div>
<header class="topbar">
  <div class="brand">
    <div class="brand-mark" aria-hidden="true">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M5 14.5c2.5 0 2.5-2 5-2s2.5 2 5 2 2.5-2 4-2M5 18c2.5 0 2.5-2 5-2s2.5 2 5 2 2.5-2 4-2M12 3.5c0 3-2.6 3.3-2.6 5.7" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/></svg>
    </div>
    <div><div class="brand-title">Kelp Garden</div><span class="brand-sub">An underwater sanctuary</span></div>
  </div>
  <div class="top-actions">
    <div class="current"><i></i> A little world to drift in</div>
    <button class="circle-button" id="reset" type="button" aria-label="Return to the starting point" title="Return to start">
      <svg width="19" height="19" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5.2 9A7.2 7.2 0 1 1 5 14M5.2 4.8V9h4.3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
    </button>
    <button class="guide-button" id="guide" type="button" aria-expanded="false" aria-controls="help">Swim guide</button>
  </div>
</header>
<main class="intro" id="intro">
  <div class="eyebrow">An invitation to slow down</div>
  <h1>Find your<br>quiet <em>blue.</em></h1>
  <p>Drift through a living underwater garden, where the only hurry is the tide.</p>
  <button class="enter" id="enter" type="button">Enter the garden <svg width="20" height="14" viewBox="0 0 20 14" fill="none" aria-hidden="true"><path d="M1 7h17M13 2l5 5-5 5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
</main>
<div class="demo-badge" id="demoBadge" hidden>Drifting on its own · Touch to explore</div>
<section class="help-panel" id="help" aria-label="Swimming guide" hidden>
  <div class="small">A little guidance</div>
  <h2>Go with the flow.</h2>
  <p>Press and hold anywhere in the water to swim forward.</p>
  <p>While holding, drag to look around. Look up or down to change your depth.</p>
  <p>Use the circular arrow to return to the starting point.</p>
  <button type="button" id="closeHelp">Got it</button>
</section>
<div class="bottom">
  <div class="place"><div class="place-number">01</div><div class="place-copy"><strong>The kelp garden</strong><span>A world beneath the surface</span></div></div>
  <div class="bottom-right">
    <div class="depth"><strong id="depth">18 m</strong><span>Below the surface</span></div>
    <div class="control-hint">
      <div class="control-icon" aria-hidden="true"><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M12 3v9m-3-6 3-3 3 3M6 14v1.2a6 6 0 0 0 12 0V14M8 14v2m8-2v2" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/></svg></div>
      <div><strong>Hold to swim</strong><span>Drag to look around</span></div>
    </div>
  </div>
</div>
<div class="error" id="error" role="status" hidden><strong>The water is a little cloudy.</strong><span>The underwater scene couldn't start. Please check your connection and try a browser with WebGL enabled.</span></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.149.0/three.min.js"></script>
<script>
(function(){
  'use strict';
  const stage=document.getElementById('stage');
  const intro=document.getElementById('intro');
  const help=document.getElementById('help');
  const guide=document.getElementById('guide');
  const badge=document.getElementById('demoBadge');
  const error=document.getElementById('error');
  if(!window.THREE){error.hidden=false;return;}

  let renderer;
  try{
    renderer=new THREE.WebGLRenderer({antialias:true,powerPreference:'high-performance'});
  }catch(e){error.hidden=false;return;}
  renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,window.innerWidth<700?1.25:1.6));
  renderer.setSize(window.innerWidth,window.innerHeight);
  renderer.outputEncoding=THREE.sRGBEncoding;
  renderer.toneMapping=THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure=1.15;
  stage.appendChild(renderer.domElement);
  renderer.domElement.addEventListener('webglcontextlost',function(e){e.preventDefault();error.hidden=false;});

  const scene=new THREE.Scene();
  scene.background=new THREE.Color(0x0a5060);
  scene.fog=new THREE.FogExp2(0x0b5360,0.019);
  const camera=new THREE.PerspectiveCamera(64,window.innerWidth/window.innerHeight,0.12,170);
  camera.rotation.order='YXZ';
  camera.position.set(0,5.5,21);
  scene.add(new THREE.HemisphereLight(0xb7f1db,0x315b51,1.12));
  scene.add(new THREE.AmbientLight(0x4c837a,0.38));
  const sun=new THREE.DirectionalLight(0xffe6af,1.25);
  sun.position.set(-18,32,12);
  scene.add(sun);

  let seed=289271;
  function random(){seed=(seed*1664525+1013904223)>>>0;return seed/4294967296;}
  function rand(a,b){return a+(b-a)*random();}
  function choose(a){return a[Math.floor(random()*a.length)];}
  const tmp=new THREE.Object3D();
  const mat4=new THREE.Matrix4();
  const up=new THREE.Vector3(0,1,0);
  const obstacles=[];
  const playerRadius=0.7;

  // A hand-made, repeating sand texture, with a separate moving caustic layer.
  const sandCanvas=document.createElement('canvas');
  sandCanvas.width=512;sandCanvas.height=512;
  const ctx=sandCanvas.getContext('2d');
  ctx.fillStyle='#b5a67c';ctx.fillRect(0,0,512,512);
  for(let i=0;i<19000;i++){
    const v=Math.floor(rand(115,220));
    ctx.fillStyle='rgba('+v+','+Math.floor(v*.88)+','+Math.floor(v*.65)+','+rand(.08,.26)+')';
    const s=rand(.4,2);ctx.fillRect(rand(0,512),rand(0,512),s,s);
  }
  for(let j=-1;j<19;j++){
    ctx.beginPath();
    for(let x=0;x<=512;x+=8){
      const y=j*31+Math.sin(x*.018+j*.8)*7+Math.sin(x*.045+j)*2;
      if(x===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);
    }
    ctx.lineWidth=rand(1,3);ctx.strokeStyle='rgba(104,105,78,.10)';ctx.stroke();
  }
  const sandTexture=new THREE.CanvasTexture(sandCanvas);
  sandTexture.encoding=THREE.sRGBEncoding;
  sandTexture.wrapS=sandTexture.wrapT=THREE.RepeatWrapping;
  sandTexture.repeat.set(20,20);
  const sand=new THREE.Mesh(new THREE.PlaneGeometry(240,240),new THREE.MeshStandardMaterial({map:sandTexture,color:0xd2c39a,roughness:1}));
  sand.rotation.x=-Math.PI/2;sand.position.y=-.03;scene.add(sand);
  const floorUniforms={uTime:{value:0}};
  const caustics=new THREE.Mesh(new THREE.PlaneGeometry(240,240),new THREE.ShaderMaterial({
    uniforms:floorUniforms,transparent:true,depthWrite:false,blending:THREE.AdditiveBlending,
    vertexShader:'varying vec3 vWorld; void main(){vec4 w=modelMatrix*vec4(position,1.0);vWorld=w.xyz;gl_Position=projectionMatrix*viewMatrix*w;}',
    fragmentShader:'uniform float uTime; varying vec3 vWorld; void main(){vec2 p=vWorld.xz*.52;float a=sin(p.x+sin(p.y*.73+uTime*.32)*1.9);float b=sin(p.y*1.15+cos(p.x*.67-uTime*.27)*1.7);float c=pow(max(0.0,1.0-abs(a+b)),10.0);float fade=1.0-smoothstep(12.0,80.0,distance(cameraPosition,vWorld));gl_FragColor=vec4(1.0,.85,.52,c*.24*fade);}'
  }));
  caustics.rotation.x=-Math.PI/2;caustics.position.y=.008;scene.add(caustics);

  // The underside of the rippling surface is visible from below.
  const waterUniforms={uTime:{value:0}};
  const surface=new THREE.Mesh(new THREE.PlaneGeometry(240,240,55,55),new THREE.ShaderMaterial({
    uniforms:waterUniforms,side:THREE.DoubleSide,
    vertexShader:'uniform float uTime;varying vec3 vWorld;void main(){vec3 p=position;p.z+=sin(p.x*.14+uTime*.65)*.20+cos(p.y*.19-uTime*.47)*.16;vec4 w=modelMatrix*vec4(p,1.0);vWorld=w.xyz;gl_Position=projectionMatrix*viewMatrix*w;}',
    fragmentShader:'uniform float uTime;varying vec3 vWorld;void main(){vec2 p=vWorld.xz;float a=sin(p.x*.22+sin(p.y*.13+uTime*.25)*1.7+uTime*.27);float b=sin(p.y*.24+cos(p.x*.15-uTime*.2)*1.5);float glint=pow(max(0.0,1.0-abs(a+b)),5.0);vec3 c=mix(vec3(.07,.34,.38),vec3(.16,.57,.55),.45+.28*a)+glint*vec3(.14,.18,.12);float fog=smoothstep(20.0,120.0,distance(cameraPosition,vWorld));c=mix(c,vec3(.035,.29,.33),fog);gl_FragColor=vec4(c,1.0);}'
  }));
  surface.rotation.x=-Math.PI/2;surface.position.y=24;scene.add(surface);

  const beamUniforms={uTime:{value:0}};
  const beamMaterial=new THREE.ShaderMaterial({
    uniforms:beamUniforms,transparent:true,depthWrite:false,side:THREE.DoubleSide,blending:THREE.AdditiveBlending,
    vertexShader:'attribute float aFade;varying float vFade;varying vec3 vWorld;void main(){vFade=aFade;vec4 w=modelMatrix*vec4(position,1.0);vWorld=w.xyz;gl_Position=projectionMatrix*viewMatrix*w;}',
    fragmentShader:'uniform float uTime;varying float vFade;varying vec3 vWorld;void main(){float f=1.0-smoothstep(20.0,85.0,distance(cameraPosition,vWorld));float pulse=.85+.15*sin(uTime*.4+vWorld.x*.2);gl_FragColor=vec4(.67,.91,.72,vFade*f*pulse);}'
  });
  function addBeam(x,z,w,angle){
    const g=new THREE.BufferGeometry();
    g.setAttribute('position',new THREE.Float32BufferAttribute([-w*.22,24,0,w*.22,24,0,-w*.85-3,.2,0,w*.85-3,.2,0],3));
    g.setAttribute('aFade',new THREE.Float32BufferAttribute([.025,.025,.055,.055],1));
    g.setIndex([0,2,1,2,3,1]);
    const m=new THREE.Mesh(g,beamMaterial);m.position.set(x,0,z);m.rotation.y=angle;scene.add(m);
    const m2=new THREE.Mesh(g,beamMaterial);m2.position.copy(m.position);m2.rotation.y=angle+1.25;scene.add(m2);
  }
  [[-17,-4,5,.2],[1,-16,7,-.3],[19,-27,6,.5],[-31,-31,7,.2],[27,2,5,-.5],[-9,-46,8,.3],[8,13,4,.2]].forEach(function(b){addBeam(b[0],b[1],b[2],b[3]);});

  // Stones use conservative bounding spheres for solid swimming collision.
  const stoneGeo=new THREE.IcosahedronGeometry(1,1);
  const stoneMats=[0x54736b,0x496a65,0x66796b,0x425f5b,0x728070].map(function(c){return new THREE.MeshStandardMaterial({color:c,roughness:1,flatShading:true});});
  function rock(x,y,z,sx,sy,sz){
    const m=new THREE.Mesh(stoneGeo,choose(stoneMats));
    m.position.set(x,y,z);m.scale.set(sx,sy,sz);m.rotation.set(rand(-.23,.23),rand(0,6.28),rand(-.2,.2));scene.add(m);
    obstacles.push({x:x,y:y,z:z,r:Math.max(sx,sy,sz)*1.03});
    return m;
  }
  const archX=-8.5,archZ=-11;
  for(const side of [-1,1]){
    rock(archX+side*4.25,1.65,archZ,1.85,2.05,1.85);
    rock(archX+side*4.20,4.35,archZ,1.65,1.85,1.7);
  }
  for(let i=0;i<=8;i++){
    const a=Math.PI*i/8;
    rock(archX+4.22*Math.cos(a),5+4.12*Math.sin(a),archZ,1.53,1.55,1.75);
  }
  rock(-14.1,.9,-10,2.2,1.2,1.8);
  rock(-2.9,.9,-12,2.0,1.1,1.7);
  for(let i=0;i<32;i++){
    const x=rand(-55,55),z=rand(-65,28);
    if(Math.hypot(x-archX,z-archZ)<10||Math.hypot(x-10,z+17)<15||Math.hypot(x,z-21)<7)continue;
    const s=rand(.65,2.5);rock(x,s*.46,z,s,s*rand(.45,.8),s*rand(.7,1.1));
  }
  const pebbles=new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1,0),new THREE.MeshStandardMaterial({color:0x6b8174,roughness:1,flatShading:true}),260);
  for(let i=0;i<260;i++){
    const s=rand(.08,.37);tmp.position.set(rand(-56,56),s*.33,rand(-70,30));tmp.rotation.set(rand(0,2),rand(0,6),rand(0,2));tmp.scale.set(s,s*rand(.35,.65),s*rand(.7,1.2));tmp.updateMatrix();pebbles.setMatrixAt(i,tmp.matrix);
  }
  scene.add(pebbles);

  // A wooden wreck made from planks, ribs, a broken mast, and scraps of sail.
  const woodMats=[0x71583e,0x886546,0x604d3b,0x98724a,0x6c5541].map(function(c){return new THREE.MeshStandardMaterial({color:c,roughness:1,side:THREE.DoubleSide});});
  const ship=new THREE.Group();
  const shipX=10,shipZ=-17,shipAngle=-.28;
  ship.position.set(shipX,0,shipZ);ship.rotation.y=shipAngle;scene.add(ship);
  const zs=[-10,-8,-5,0,5,8,10];
  const widths=[.3,1.8,2.9,3.25,3.05,2.1,.45];
  for(const side of [-1,1]){
    for(let row=0;row<5;row++){
      const vertices=[],indices=[];
      for(let k=0;k<zs.length;k++){
        for(let edge=0;edge<2;edge++){
          const f=(row+edge)/5;
          vertices.push(side*widths[k]*(.34+.66*f),.65+f*3.05,zs[k]);
        }
      }
      for(let k=0;k<zs.length-1;k++){
        const n=k*2;indices.push(n,n+1,n+2,n+1,n+3,n+2);
      }
      const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(vertices,3));g.setIndex(indices);g.computeVertexNormals();
      ship.add(new THREE.Mesh(g,woodMats[(row+(side>0?1:0))%woodMats.length]));
    }
  }
  const cube=new THREE.BoxGeometry(1,1,1);
  for(let i=0;i<11;i++){
    const plank=new THREE.Mesh(cube,woodMats[i%woodMats.length]);
    plank.scale.set(.49,.16,12.8-random()*.7);
    plank.position.set((i-5)*.48,2.45,rand(-.2,.2));ship.add(plank);
  }
  const beamGeo=new THREE.CylinderGeometry(1,1,1,7);
  function beam(group,a,b,r,material){
    const v1=new THREE.Vector3(a[0],a[1],a[2]),v2=new THREE.Vector3(b[0],b[1],b[2]);
    const d=new THREE.Vector3().subVectors(v2,v1);
    const m=new THREE.Mesh(beamGeo,material);m.position.copy(v1).add(v2).multiplyScalar(.5);m.quaternion.setFromUnitVectors(up,d.clone().normalize());m.scale.set(r,d.length(),r);group.add(m);return m;
  }
  for(const side of [-1,1]){
    beam(ship,[side*2.9,3.75,-5],[side*3.1,3.75,5],.16,woodMats[2]);
    for(const z of [-6,-3,0,3,6]){
      const w=3.2-Math.abs(z)*.13;
      beam(ship,[side*w*.57,.95,z],[side*w,3.65,z],.13,woodMats[3]);
    }
  }
  beam(ship,[0,2.3,0],[.55,13,-.5],.27,woodMats[2]);
  beam(ship,[-3.7,9.6,-.38],[3.7,10,-.38],.15,woodMats[1]);
  beam(ship,[0,3.1,-7.5],[0,4.7,-11.8],.17,woodMats[1]);
  const ropeMat=new THREE.MeshStandardMaterial({color:0xb4a16e,roughness:1});
  beam(ship,[.5,11.7,-.5],[0,3.5,-9],.035,ropeMat);
  beam(ship,[.5,11.7,-.5],[0,3.4,8.5],.035,ropeMat);
  const sailGeo=new THREE.BufferGeometry();
  sailGeo.setAttribute('position',new THREE.Float32BufferAttribute([
    .15,9.75,-.35, 3.0,9.78,-.35, 2.2,7.3,-.35,
    .15,9.75,-.35, 2.2,7.3,-.35, .2,6.45,-.35,
    .2,6.45,-.35, 2.2,7.3,-.35, 1.4,5.75,-.35,
    -.12,9.75,-.35, -2.8,9.65,-.35, -1.95,8.1,-.35,
    -.12,9.75,-.35, -1.95,8.1,-.35, -.1,7.0,-.35
  ],3));sailGeo.computeVertexNormals();
  ship.add(new THREE.Mesh(sailGeo,new THREE.MeshStandardMaterial({color:0xb7aa78,roughness:1,side:THREE.DoubleSide,transparent:true,opacity:.74})));
  const ringGeo=new THREE.TorusGeometry(.37,.065,6,12);
  const ringMat=new THREE.MeshStandardMaterial({color:0xb9a16b,roughness:.8});
  for(const side of [-1,1])for(const z of [-3,0,3]){
    const ring=new THREE.Mesh(ringGeo,ringMat);ring.position.set(side*3.08,2.85,z);ring.rotation.y=Math.PI/2;ship.add(ring);
  }

  // Seaweed leaves and stems share instanced meshes so the garden stays light on phones.
  const leafGeo=new THREE.BufferGeometry();
  const leafPos=[],leafIndex=[];
  for(let i=0;i<=8;i++){
    const t=i/8,w=Math.sin(Math.PI*t)*.28;
    leafPos.push(-w,t,Math.sin(t*Math.PI)*.035,w,t,Math.sin(t*Math.PI)*.035);
    if(i<8){const k=i*2;leafIndex.push(k,k+1,k+2,k+1,k+3,k+2);}
  }
  leafGeo.setAttribute('position',new THREE.Float32BufferAttribute(leafPos,3));leafGeo.setIndex(leafIndex);leafGeo.computeVertexNormals();
  const plants=[];
  function addPlant(x,z,h){plants.push({x:x,z:z,h:h,phase:rand(0,6.28),turn:rand(0,6.28),color:choose([0x527d42,0x64873d,0x3e7354,0x879546,0xa3964b])});}
  for(let i=0;i<115;i++){
    const x=rand(-48,48),z=rand(-66,28);
    if(Math.abs(x)<4&&z>-5)continue;
    if(Math.hypot(x-shipX,z-shipZ)<9||Math.hypot(x-archX,z-archZ)<7)continue;
    addPlant(x,z,rand(6,13.5));
  }
  for(let i=0;i<26;i++){
    const side=i%2?1:-1;
    addPlant(side*rand(12,24),rand(-5,28),rand(8,15));
  }
  const leavesPerPlant=7;
  const stemMesh=new THREE.InstancedMesh(new THREE.CylinderGeometry(1,1,1,5),new THREE.MeshStandardMaterial({color:0x547653,roughness:1}),plants.length);
  const leafMesh=new THREE.InstancedMesh(leafGeo,new THREE.MeshStandardMaterial({color:0xffffff,side:THREE.DoubleSide,roughness:1}),plants.length*leavesPerPlant);
  stemMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);leafMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
  stemMesh.frustumCulled=false;leafMesh.frustumCulled=false;
  const base=new THREE.Object3D(),part=new THREE.Object3D();
  for(let i=0;i<plants.length;i++)for(let j=0;j<leavesPerPlant;j++){
    const c=new THREE.Color(plants[i].color);c.multiplyScalar(rand(.8,1.2));leafMesh.setColorAt(i*leavesPerPlant+j,c);
  }
  scene.add(stemMesh);scene.add(leafMesh);
  function updateKelp(t){
    let index=0;
    for(let i=0;i<plants.length;i++){
      const p=plants[i],sway=Math.sin(t*.48+p.phase);
      base.position.set(p.x,0,p.z);base.rotation.set(Math.cos(t*.38+p.phase)*.035,0,sway*.075);base.scale.set(1,1,1);base.updateMatrix();
      part.position.set(0,p.h/2,0);part.rotation.set(0,0,0);part.scale.set(.075,p.h,.075);part.updateMatrix();mat4.multiplyMatrices(base.matrix,part.matrix);stemMesh.setMatrixAt(i,mat4);
      for(let j=0;j<leavesPerPlant;j++){
        const side=j%2?1:-1;
        part.position.set(0,p.h*(.16+j*.105),0);
        part.rotation.set(.04,p.turn+j*1.9,side*(.72+.07*Math.sin(t*1.15+p.phase+j)));
        part.scale.set(1.0,2.1+p.h*.105,1);part.updateMatrix();mat4.multiplyMatrices(base.matrix,part.matrix);leafMesh.setMatrixAt(index++,mat4);
      }
    }
    stemMesh.instanceMatrix.needsUpdate=true;leafMesh.instanceMatrix.needsUpdate=true;
  }

  // Branching coral in warm orange and gold.
  const coralSegments=[];
  const coralColors=[0xcc7141,0xe4974c,0xc88e48,0x9c8748,0xd9ad65];
  function coralSegment(a,b,r,color){
    const va=new THREE.Vector3(a[0],a[1],a[2]),vb=new THREE.Vector3(b[0],b[1],b[2]),d=new THREE.Vector3().subVectors(vb,va);
    tmp.position.copy(va).add(vb).multiplyScalar(.5);tmp.quaternion.setFromUnitVectors(up,d.clone().normalize());tmp.scale.set(r,d.length(),r);tmp.updateMatrix();
    coralSegments.push({matrix:tmp.matrix.clone(),color:color});
  }
  const coralPlaces=[[-12,11],[9,10],[17,1],[-17,-2],[-3,-19],[18,-30],[-24,-20]];
  for(let i=0;i<30;i++)coralPlaces.push([rand(-42,42),rand(-58,22)]);
  coralPlaces.forEach(function(p){
    if(Math.hypot(p[0]-shipX,p[1]-shipZ)<7||Math.hypot(p[0],p[1]-21)<5)return;
    const color=choose(coralColors),size=rand(.55,1.25);
    for(let j=0;j<5;j++){
      const a=j*Math.PI*2/5+rand(-.35,.35),h=rand(.8,2)*size;
      const x=p[0]+Math.cos(a)*rand(.1,.45),z=p[1]+Math.sin(a)*rand(.1,.45);
      const tip=[x+Math.cos(a)*.35*size,h,z+Math.sin(a)*.35*size];
      coralSegment([p[0],.05,p[1]],tip,.09*size,color);
      coralSegment([x+Math.cos(a)*.19*size,h*.55,z+Math.sin(a)*.19*size],[tip[0]+Math.cos(a+1)*.38*size,h*.91,tip[2]+Math.sin(a+1)*.38*size],.055*size,color);
    }
  });
  const coral=new THREE.InstancedMesh(new THREE.CylinderGeometry(.6,1,1,5),new THREE.MeshStandardMaterial({color:0xffffff,roughness:1,flatShading:true}),coralSegments.length);
  coralSegments.forEach(function(s,i){coral.setMatrixAt(i,s.matrix);coral.setColorAt(i,new THREE.Color(s.color));});scene.add(coral);

  // Schools use the same heading for all fish, turning together as they circle.
  const fishGeo=new THREE.SphereGeometry(1,8,6);fishGeo.scale(.55,.24,.17);
  const tailGeo=new THREE.BufferGeometry();tailGeo.setAttribute('position',new THREE.Float32BufferAttribute([-.42,0,0,-.91,.34,0,-.91,-.34,0],3));tailGeo.computeVertexNormals();
  const fishMat=new THREE.MeshStandardMaterial({color:0xffffff,roughness:.7,metalness:.08,side:THREE.DoubleSide});
  function school(cx,cz,rx,rz,y,speed,phase,palette){
    const count=28,body=new THREE.InstancedMesh(fishGeo,fishMat,count),tail=new THREE.InstancedMesh(tailGeo,fishMat,count);
    body.instanceMatrix.setUsage(THREE.DynamicDrawUsage);tail.instanceMatrix.setUsage(THREE.DynamicDrawUsage);body.frustumCulled=false;tail.frustumCulled=false;
    const members=[];
    for(let i=0;i<count;i++){
      const c=new THREE.Color(choose(palette));body.setColorAt(i,c);tail.setColorAt(i,c);
      members.push({size:rand(.52,.85),lift:rand(-.3,.3),phase:rand(0,6.28)});
    }
    scene.add(body);scene.add(tail);return{cx:cx,cz:cz,rx:rx,rz:rz,y:y,speed:speed,phase:phase,body:body,tail:tail,members:members};
  }
  const schools=[
    school(-5,-10,8,6,6.7,.20,.4,[0xe5bd65,0xf1c77a,0xd38e4f]),
    school(12,-22,7,8,8,.16,2.1,[0x83b6a1,0xd3c58b,0xb0c9a9]),
    school(1,3,10,6,8.7,.14,4.2,[0xe6ab62,0xf0ca85,0xd88a4b])
  ];
  function updateFish(t){
    schools.forEach(function(s){
      const a=t*s.speed+s.phase,cx=s.cx+Math.cos(a)*s.rx,cz=s.cz+Math.sin(a)*s.rz;
      const heading=Math.atan2(Math.cos(a)*s.rz,-Math.sin(a)*s.rx),co=Math.cos(heading),si=Math.sin(heading);
      s.members.forEach(function(f,i){
        const along=-Math.floor(i/7)*.77,across=(i%7-3)*.66;
        tmp.position.set(cx+co*along-si*across,s.y+f.lift+Math.sin(t*1.4+f.phase)*.12,cz+si*along+co*across);
        tmp.rotation.set(0,-heading+Math.sin(t*6+f.phase)*.06,0);tmp.scale.setScalar(f.size);tmp.updateMatrix();
        s.body.setMatrixAt(i,tmp.matrix);s.tail.setMatrixAt(i,tmp.matrix);
      });
      s.body.instanceMatrix.needsUpdate=true;s.tail.instanceMatrix.needsUpdate=true;
    });
  }

  // Broad triangular wings and a long tail make the passing rays easy to recognize.
  function makeManta(phase,offset){
    const group=new THREE.Group();
    const dark=new THREE.MeshStandardMaterial({color:0x355b59,roughness:.88,side:THREE.DoubleSide,flatShading:true});
    const pale=new THREE.MeshStandardMaterial({color:0x9cb7a0,roughness:1,side:THREE.DoubleSide});
    const body=new THREE.Mesh(new THREE.SphereGeometry(1,12,8),dark);body.scale.set(.8,.27,1.45);group.add(body);
    const belly=new THREE.Mesh(new THREE.SphereGeometry(1,10,6),pale);belly.scale.set(.55,.10,.9);belly.position.y=-.2;group.add(belly);
    function wing(side){
      const g=new THREE.BufferGeometry();
      g.setAttribute('position',new THREE.Float32BufferAttribute([0,0,-1.15,side*1.3,.05,-.95,side*4.2,0,.35,side*1.4,0,1.05,0,0,1.15],3));
      g.setIndex([0,1,2,0,2,4,2,3,4]);g.computeVertexNormals();const m=new THREE.Mesh(g,dark);group.add(m);return m;
    }
    const left=wing(-1),right=wing(1);
    beam(group,[0,0,1.0],[0,-.05,3.3],.055,dark);
    beam(group,[-.5,0,-.8],[-.8,0,-1.5],.09,dark);
    beam(group,[.5,0,-.8],[.8,0,-1.5],.09,dark);
    group.scale.setScalar(.72);scene.add(group);
    return{group:group,left:left,right:right,phase:phase,offset:offset};
  }
  const rays=[makeManta(.15,0),makeManta(3.4,7)];
  function updateRays(t){
    rays.forEach(function(r){
      const a=t*.115+r.phase,dx=Math.cos(a)*18,dz=-Math.sin(a)*13;
      r.group.position.set(Math.sin(a)*18,10.8+r.offset*.24+Math.sin(t*.45+r.phase)*.7,-15+Math.cos(a)*13-r.offset);
      r.group.rotation.y=Math.atan2(-dx,-dz);
      const flap=Math.sin(t*1.3+r.phase)*.16;r.left.rotation.z=flap;r.right.rotation.z=-flap;
    });
  }

  const bubbleData=[];
  for(let i=0;i<85;i++){
    const near=i<45;
    bubbleData.push({x:near?shipX+rand(-4,4):rand(-28,28),z:near?shipZ+rand(-7,7):rand(-42,18),y:rand(0,24),speed:rand(.8,1.7),size:rand(.035,.13),phase:rand(0,6.28)});
  }
  const bubbles=new THREE.InstancedMesh(new THREE.SphereGeometry(1,7,5),new THREE.MeshBasicMaterial({color:0xd2fff0,transparent:true,opacity:.42,depthWrite:false}),bubbleData.length);
  bubbles.instanceMatrix.setUsage(THREE.DynamicDrawUsage);bubbles.frustumCulled=false;scene.add(bubbles);
  function updateBubbles(t){
    bubbleData.forEach(function(b,i){tmp.position.set(b.x+Math.sin(t*.7+b.phase)*.2,(b.y+t*b.speed)%23,b.z+Math.cos(t*.6+b.phase)*.16);tmp.rotation.set(0,0,0);tmp.scale.setScalar(b.size);tmp.updateMatrix();bubbles.setMatrixAt(i,tmp.matrix);});
    bubbles.instanceMatrix.needsUpdate=true;
  }
  const motePositions=[];
  for(let i=0;i<350;i++)motePositions.push(rand(-50,50),rand(.5,23),rand(-65,30));
  const moteGeo=new THREE.BufferGeometry();moteGeo.setAttribute('position',new THREE.Float32BufferAttribute(motePositions,3));
  const motes=new THREE.Points(moteGeo,new THREE.PointsMaterial({color:0xc7e9d8,size:.08,transparent:true,opacity:.55,depthWrite:false,sizeAttenuation:true}));scene.add(motes);

  function resolveCollisions(){
    for(let pass=0;pass<5;pass++){
      camera.position.y=THREE.MathUtils.clamp(camera.position.y,1.3,21);
      camera.position.x=THREE.MathUtils.clamp(camera.position.x,-112,112);
      camera.position.z=THREE.MathUtils.clamp(camera.position.z,-112,112);
      for(let i=0;i<obstacles.length;i++){
        const o=obstacles[i],dx=camera.position.x-o.x,dy=camera.position.y-o.y,dz=camera.position.z-o.z;
        const rr=o.r+playerRadius,d2=dx*dx+dy*dy+dz*dz;
        if(d2<rr*rr){
          const d=Math.sqrt(d2);
          if(d<.0001)camera.position.x+=rr;
          else{const push=(rr-d)/d;camera.position.x+=dx*push;camera.position.y+=dy*push;camera.position.z+=dz*push;}
        }
      }
      // A rotated safety box encloses the entire hull, mast, spar, and bow.
      if(camera.position.y-playerRadius<15&&camera.position.y+playerRadius>0){
        const c=Math.cos(shipAngle),s=Math.sin(shipAngle),wx=camera.position.x-shipX,wz=camera.position.z-shipZ;
        let lx=c*wx-s*wz,lz=s*wx+c*wz;
        const hx=4.45,hz=12.35;
        const qx=THREE.MathUtils.clamp(lx,-hx,hx),qz=THREE.MathUtils.clamp(lz,-hz,hz);
        const dx=lx-qx,dz=lz-qz,dist2=dx*dx+dz*dz;
        if(Math.abs(lx)<=hx&&Math.abs(lz)<=hz){
          if(hx-Math.abs(lx)<hz-Math.abs(lz))lx=(lx<0?-1:1)*(hx+playerRadius);
          else lz=(lz<0?-1:1)*(hz+playerRadius);
        }else if(dist2<playerRadius*playerRadius){
          const d=Math.sqrt(dist2)||1;lx+=dx/d*(playerRadius-d);lz+=dz/d*(playerRadius-d);
        }
        camera.position.x=shipX+c*lx+s*lz;camera.position.z=shipZ-s*lx+c*lz;
      }
    }
    camera.position.y=THREE.MathUtils.clamp(camera.position.y,1.3,21);
  }
  function moveTo(x,y,z){
    const dx=x-camera.position.x,dy=y-camera.position.y,dz=z-camera.position.z;
    const steps=Math.max(1,Math.ceil(Math.sqrt(dx*dx+dy*dy+dz*dz)/.25));
    for(let i=0;i<steps;i++){camera.position.x+=dx/steps;camera.position.y+=dy/steps;camera.position.z+=dz/steps;resolveCollisions();}
  }

  let yaw=0,pitch=.015,holding=false,pointer=null,lastX=0,lastY=0;
  let demo=window.location.hash.toLowerCase()==='#demo';
  if(demo){intro.classList.add('gone');badge.hidden=false;}
  const forward=new THREE.Vector3();
  function stopDemo(){
    if(!demo)return;
    camera.getWorldDirection(forward);
    yaw=Math.atan2(-forward.x,-forward.z);pitch=Math.asin(THREE.MathUtils.clamp(forward.y,-1,1));
    demo=false;badge.hidden=true;
  }
  window.addEventListener('pointerdown',function(e){if(demo&&e.isTrusted&&e.pointerType==='touch')stopDemo();},true);
  stage.addEventListener('pointerdown',function(e){
    if(e.pointerType==='mouse'&&e.button!==0)return;
    e.preventDefault();stopDemo();intro.classList.add('gone');help.hidden=true;guide.setAttribute('aria-expanded','false');
    holding=true;pointer=e.pointerId;lastX=e.clientX;lastY=e.clientY;
    try{stage.setPointerCapture(e.pointerId);}catch(err){}
  });
  stage.addEventListener('pointermove',function(e){
    if(!holding||e.pointerId!==pointer)return;
    yaw-=(e.clientX-lastX)*.0045;pitch=THREE.MathUtils.clamp(pitch-(e.clientY-lastY)*.004,-1.12,1.12);
    lastX=e.clientX;lastY=e.clientY;
  });
  function release(e){if(!e||e.pointerId===pointer){holding=false;pointer=null;}}
  stage.addEventListener('pointerup',release);stage.addEventListener('pointercancel',release);
  stage.addEventListener('lostpointercapture',release);window.addEventListener('blur',function(){release();});
  document.getElementById('enter').addEventListener('click',function(){stopDemo();intro.classList.add('gone');});
  document.getElementById('reset').addEventListener('click',function(){
    stopDemo();holding=false;camera.position.set(0,5.5,21);yaw=0;pitch=.015;camera.rotation.set(pitch,yaw,0,'YXZ');intro.classList.add('gone');help.hidden=true;guide.setAttribute('aria-expanded','false');
  });
  guide.addEventListener('click',function(){
    stopDemo();holding=false;help.hidden=!help.hidden;guide.setAttribute('aria-expanded',String(!help.hidden));
  });
  document.getElementById('closeHelp').addEventListener('click',function(){help.hidden=true;guide.setAttribute('aria-expanded','false');});

  const demoFrames=[
    {t:0,p:[0,5.5,21],look:[0,5,-15]},
    {t:3,p:[-3,5.5,12],look:[-8,5.5,-11]},
    {t:6,p:[-8.5,5.4,1],look:[-8.5,5.8,-17]},
    {t:9,p:[-8.5,5.5,-15],look:[2,6,-22]},
    {t:12,p:[-1,6,-21],look:[10,5,-17]},
    {t:15,p:[1,7,-7],look:[10,6,-17]},
    {t:18,p:[0,10,7],look:[-2,20,-12]},
    {t:20,p:[0,5.5,21],look:[0,5,-15]}
  ];
  const lookTarget=new THREE.Vector3();
  function updateDemo(time){
    const t=time%20;let a=demoFrames[0],b=demoFrames[1];
    for(let i=0;i<demoFrames.length-1;i++)if(t>=demoFrames[i].t&&t<demoFrames[i+1].t){a=demoFrames[i];b=demoFrames[i+1];break;}
    let f=(t-a.t)/(b.t-a.t);f=f*f*(3-2*f);
    moveTo(THREE.MathUtils.lerp(a.p[0],b.p[0],f),THREE.MathUtils.lerp(a.p[1],b.p[1],f),THREE.MathUtils.lerp(a.p[2],b.p[2],f));
    lookTarget.set(THREE.MathUtils.lerp(a.look[0],b.look[0],f),THREE.MathUtils.lerp(a.look[1],b.look[1],f),THREE.MathUtils.lerp(a.look[2],b.look[2],f));camera.lookAt(lookTarget);
  }
  function resize(){
    camera.aspect=window.innerWidth/window.innerHeight;camera.updateProjectionMatrix();
    renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,window.innerWidth<700?1.25:1.6));renderer.setSize(window.innerWidth,window.innerHeight);
  }
  window.addEventListener('resize',resize);
  let previous=performance.now(),elapsed=0,lastDepth=-1;
  function frame(now){
    requestAnimationFrame(frame);
    const dt=Math.min((now-previous)/1000,.05);previous=now;elapsed+=dt;
    floorUniforms.uTime.value=elapsed;waterUniforms.uTime.value=elapsed;beamUniforms.uTime.value=elapsed;
    updateKelp(elapsed);updateFish(elapsed);updateRays(elapsed);updateBubbles(elapsed);
    if(demo)updateDemo(elapsed);
    else{
      camera.rotation.set(pitch,yaw,0,'YXZ');
      if(holding){
        const speed=5.1,cp=Math.cos(pitch);
        moveTo(camera.position.x-Math.sin(yaw)*cp*speed*dt,camera.position.y+Math.sin(pitch)*speed*dt,camera.position.z-Math.cos(yaw)*cp*speed*dt);
      }
    }
    const depth=Math.max(0,Math.round(24-camera.position.y));
    if(depth!==lastDepth){document.getElementById('depth').textContent=depth+' m';lastDepth=depth;}
    renderer.render(scene,camera);
  }
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>