Skip to content
VibeCodeBench
Back to the app

The code

Swim the Kelp Garden by GPT-6.2 Sol

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

partly works · auto-checked (Checked by an automated pass. Not hand-played yet.)32.9 KB · 546 lines · loads cdn.jsdelivr.net/npm/three@0.160.0/build/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="#0a2f3c">
<title>Kelp Garden</title>
<style>
:root{color-scheme:dark;--cream:#fcf3dd;--gold:#efd191;--soft:#d3e8e0;--line:#e4f2dd48;font-family:system-ui,sans-serif}
*{box-sizing:border-box}html,body,canvas{margin:0;width:100%;height:100%;overflow:hidden}body{background:#0b3547;color:var(--cream);overscroll-behavior:none}canvas{display:block;touch-action:none;cursor:grab}canvas:active{cursor:grabbing}
.shade,#ui{position:absolute;inset:0;pointer-events:none}.shade{background:linear-gradient(#051f2e91,transparent 24%,transparent 72%,#051d2bbd),radial-gradient(ellipse at 50% 47%,transparent 44%,#06273550 100%)}
#ui{--pad:clamp(20px,4vw,64px)}header{position:absolute;top:max(27px,calc(env(safe-area-inset-top) + 11px));left:var(--pad);display:flex;align-items:center;gap:13px}
.logo,.dial{border:1px solid var(--line);border-radius:50%;display:grid;place-items:center;color:var(--gold);background:#0d303b75}.logo{width:45px;height:45px}.logo svg{width:25px}h1{font:400 clamp(31px,4.1vw,61px)/1 Georgia,serif;letter-spacing:-.055em;margin:0;text-shadow:0 3px 22px #072c33}
.depth{position:absolute;right:var(--pad);top:max(31px,calc(env(safe-area-inset-top) + 14px));display:flex;gap:9px;align-items:center;text-align:right}.depth svg{width:17px;color:var(--gold)}small,.hint,.tag{font-size:10px;letter-spacing:.17em;font-weight:650;text-transform:uppercase}small{color:var(--soft);display:block}.depth output{font-size:19px;font-variant-numeric:tabular-nums}
.aim{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:16px;height:16px;border-radius:50%;border:1px solid #f4edcf8c}.aim::after{content:"";position:absolute;inset:6px;background:var(--cream);border-radius:50%}
.tag{position:absolute;white-space:nowrap;color:#f7eace;background:#102f37a8;border:1px solid #edd5a151;border-radius:4px;padding:7px 9px;opacity:0;transform:translate(-50%,-100%);transition:opacity .3s}.tag::after{content:"";position:absolute;height:12px;left:50%;top:100%;border-left:1px solid #ead6a68f}
footer{position:absolute;bottom:max(22px,calc(env(safe-area-inset-bottom) + 12px));left:var(--pad);right:var(--pad);display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:9px}.heading,.hint,.actions{display:flex;align-items:center;gap:8px}.dial{width:33px;height:33px}.dial svg{width:13px}.heading output{font-size:13px;font-variant-numeric:tabular-nums}.hint{justify-content:center;letter-spacing:.11em;color:var(--soft);text-shadow:0 2px 8px #051e2d}.hint svg{width:17px;color:var(--gold)}.actions{justify-self:end}
button{pointer-events:auto;touch-action:manipulation;min-height:44px;border-radius:24px;border:1px solid var(--line);background:#0a2936ce;color:var(--cream);font:600 12px system-ui;padding:0 14px;display:flex;align-items:center;justify-content:center;gap:7px;white-space:nowrap;cursor:pointer}button svg{width:15px;color:var(--gold)}button:focus-visible{outline:2px solid var(--gold);outline-offset:3px}#reset{width:44px;padding:0}
.touch,#error{display:none}#error{position:absolute;inset:45% 10% auto;text-align:center;line-height:1.5}
@media(pointer:coarse){.touch{display:inline}.mouse{display:none}}
@media(max-width:610px){header{gap:8px}.logo{width:35px;height:35px}.logo svg{width:20px}.depth{gap:5px}.depth output{font-size:15px}.depth small,.tag{font-size:8px}footer{grid-template-columns:1fr 1fr}.hint{grid-column:1/-1;grid-row:1;font-size:9px}.actions{grid-column:2}.heading{grid-column:1;grid-row:2}}
</style>
</head>
<body>
<canvas id="water" aria-label="Underwater garden. Hold to swim forward and drag to turn."></canvas>
<div class="shade"></div>
<div id="ui">
<header><span class="logo" aria-hidden="true"><svg viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"><path d="M14 23c3-6-2-10 2-18M14 20C8 19 6 16 6 13c4 0 7 2 8 5m1-2c5 0 7-3 8-7-4 0-7 3-8 5m0-4c-4-1-5-3-5-5 3 0 5 2 5 4M5 23c3 1 6 1 9 0s6-1 9 0"/></svg></span><h1>Kelp Garden</h1></header>
<div class="depth"><svg viewBox="0 0 20 30" fill="none" stroke="currentColor" aria-hidden="true"><path d="M2 4h16M2 9h8M2 14h12M2 19h8M2 24h16"/></svg><div><small>Depth</small><output id="depth">8.0 m</output></div></div>
<span class="aim" aria-hidden="true"></span><span id="arch" class="tag">Stone arch</span><span id="wreck" class="tag">Sunken ship</span>
<footer>
<div class="heading"><span class="dial" aria-hidden="true"><svg viewBox="0 0 12 20" id="needle"><path d="M6 1 11 16 6 12 1 16Z" fill="currentColor"/></svg></span><div><small>Heading</small><output id="heading">000&deg; N</output></div></div>
<div class="hint"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><circle cx="10" cy="10" r="8"/><path d="M10 5v10M7 8l3-3 3 3"/></svg><span class="mouse">Hold to swim &middot; Drag to look</span><span class="touch">Press to swim &middot; Drag to look</span></div>
<div class="actions"><button id="reset" type="button" aria-label="Return to starting point" title="Return to starting point"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 10a7 7 0 1 1 2 5M3 4v6h6"/></svg></button><button id="tour" type="button" aria-pressed="false"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path id="play" d="m7 4 9 6-9 6z"/></svg><span id="tourText">Guided swim</span></button></div>
</footer></div>
<p id="error" role="status">The garden needs WebGL and the Three.js library to open.</p>
<script src="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"></script>
<script>
(() => {
  'use strict';
  const $=id=>document.getElementById(id);
  const canvas=$('water'), T=window.THREE;
  let renderer;
  try { renderer=new T.WebGLRenderer({canvas,antialias:true}); }
  catch { $('error').style.display='block'; $('ui').style.display='none'; return; }
  const scene=new T.Scene(), tint=new T.Color('#20617b');
  scene.background=tint;
  scene.fog=new T.FogExp2(tint,.036);
  const camera=new T.PerspectiveCamera(60,1,.055,110);
  camera.rotation.order='YXZ';
  function resize(){
    renderer.setPixelRatio(Math.min(devicePixelRatio||1,1.55));
    renderer.setSize(innerWidth,innerHeight,false);
    camera.aspect=innerWidth/innerHeight;
    camera.fov=camera.aspect<.85?78:60;
    camera.updateProjectionMatrix();
  }
  addEventListener('resize',resize);
  resize();
  const sea=14, time={value:0};
  const V=(x,y,z)=>new T.Vector3(x,y,z), up=V(0,1,0), east=V(1,0,0);
  const ground=(x,z)=>.19*Math.sin(.25*x+.27*z)+.12*Math.sin(.53*z-.37*x)+.17*Math.cos(.16*x-.2*z);
  let seed=97293;
  function random(){seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/4294967296;}
  const range=(a,b)=>a+(b-a)*random(), pick=a=>a[Math.floor(random()*a.length)];
  const dummy=new T.Object3D();
  const solid=[];
  scene.add(new T.HemisphereLight('#c5f1df','#786749',2.15));
  const sun=new T.DirectionalLight('#ffe2a1',2.1);
  sun.position.set(-14,24,7);scene.add(sun);
  const fill=new T.DirectionalLight('#56b7c2',.8);
  fill.position.set(9,6,-12);scene.add(fill);
  function geometry(points,indices,colors){
    const g=new T.BufferGeometry();
    g.setAttribute('position',new T.Float32BufferAttribute(points,3));
    if(indices)g.setIndex(indices);
    if(colors)g.setAttribute('color',new T.Float32BufferAttribute(colors,3));
    g.computeVertexNormals();
    return g;
  }
  function mesh(parent,g,m,x=0,y=0,z=0){
    const o=new T.Mesh(g,m);o.position.set(x,y,z);parent.add(o);return o;
  }
  function standard(color,extra={}){
    return new T.MeshStandardMaterial({color,roughness:.86,...extra});
  }
  const plane=new T.PlaneGeometry(152,152,115,115);
  plane.rotateX(-Math.PI/2);
  const fp=plane.attributes.position;
  for(let i=0;i<fp.count;i++)fp.setY(i,ground(fp.getX(i),fp.getZ(i)));
  mesh(scene,plane,new T.ShaderMaterial({
    uniforms:{t:time,fogTint:{value:tint}},
    vertexShader:`varying vec3 p;void main(){p=position;gl_Position=projectionMatrix*modelViewMatrix*vec4(p,1.);}`,
    fragmentShader:`
    uniform float t;uniform vec3 fogTint;varying vec3 p;
    float hash(vec2 x){return fract(sin(dot(x,vec2(127.1,311.7)))*43758.5453);}
    float caustics(vec2 q){
      vec2 cell=floor(q),f=fract(q);float a=9.,b=9.;
      for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++){
        vec2 g=vec2(float(x),float(y));
        vec2 j=.5+.36*sin(t*.52+6.283*vec2(hash(cell+g),hash(cell+g+27.)));
        vec2 r=g+j-f;float d=dot(r,r);
        if(d<a){b=a;a=d;}else{b=min(d,b);}
      }
      return 1.-smoothstep(.022,.125,b-a);
    }
    void main(){
      float d=distance(cameraPosition,p);
      vec2 q=p.xz*vec2(.91,1.15)+.47*vec2(sin(p.z*.22+t*.3),cos(p.x*.31-t*.3));
      float sand=sin(p.z*10.+p.x*2.5+2.3*sin(p.x*.67+p.z*.56)+.65*sin(p.x*1.2-p.z*.48));
      float patch=.5+.5*sin(p.x*.28-p.z*.31+sin(p.x*.43+p.z*.33));
      vec3 c=mix(vec3(.112,.195,.166),vec3(.43,.365,.214),.35+.46*patch+.07*sand+.075*hash(floor(p.xz*100.)));
      c+=vec3(.33,.42,.25)*caustics(q)*(.32+.63*patch)*exp(-d*.021);
      vec2 a=(p.xz-vec2(-7.4,-12.3))/vec2(4.7,2.1),b=(p.xz-vec2(7.3,-15.5))/vec2(5.2,2.25);
      c*=1.-.48*max(exp(-dot(a,a)),exp(-dot(b,b)));
      gl_FragColor=vec4(mix(c,fogTint,1.-exp(-.00129*d*d)),1.);
      #include <colorspace_fragment>
    }`
  }));
  const ceiling=new T.PlaneGeometry(151,151,108,108);
  ceiling.rotateX(-Math.PI/2);
  mesh(scene,ceiling,new T.ShaderMaterial({
    side:T.DoubleSide,uniforms:{t:time,fogTint:{value:tint}},
    vertexShader:`uniform float t;varying vec3 p;void main(){
      vec3 q=position;q.y+=.22*sin(q.x*.65+q.z*.45+t*.85)+.13*cos(q.x*.77-q.z*.83-t*.74);
      p=(modelMatrix*vec4(q,1.)).xyz;gl_Position=projectionMatrix*viewMatrix*vec4(p,1.);
    }`,
    fragmentShader:`uniform float t;uniform vec3 fogTint;varying vec3 p;
    void main(){
      vec2 q=p.xz;
      float w=sin(q.x*1.5+q.y*1.4+t*.7)+.44*sin(q.y*3.1-q.x*1.2-t)+.2*sin(q.x*6.+q.y*5.+t);
      float v=sin(q.x*.56-q.y*2.3+t*.88+.9*w);
      float crest=pow(.5+.5*sin(w*1.78+v*.92),8.);
      float sun=exp(-length((q-vec2(-12.,2.))*vec2(.076,.055)));
      vec3 c=mix(vec3(.028,.229,.278),vec3(.29,.66,.54),sun*.62+.2*(.5+.5*v));
      c+=vec3(.55,.62,.4)*(crest*.37+pow(.5+.5*v,12.)*.13)*(.34+sun*.85);
      float d=distance(cameraPosition,p);
      gl_FragColor=vec4(mix(c,fogTint,1.-exp(-d*d*.00069)),1.);
      #include <colorspace_fragment>
    }`
  }),0,sea,0);
  const beamP=[],beamUV=[],beamIds=[],strength=[];
  for(let i=0;i<33;i++){
    const x=range(-28,13),z=range(-39,19),a=range(.1,.54),b=range(.65,2.55),dx=range(5.3,9),j=i*4;
    beamP.push(x-a,13.83,z,x+a,13.83,z,x+dx+b,.1,z-5,x+dx-b,.1,z-5);
    beamUV.push(0,0,1,0,1,1,0,1);beamIds.push(j,j+1,j+2,j,j+2,j+3);
    const s=range(.045,.145);strength.push(s,s,s,s);
  }
  const shafts=geometry(beamP,beamIds);
  shafts.setAttribute('uv',new T.Float32BufferAttribute(beamUV,2));
  shafts.setAttribute('strength',new T.Float32BufferAttribute(strength,1));
  mesh(scene,shafts,new T.ShaderMaterial({
    side:T.DoubleSide,transparent:true,depthWrite:false,blending:T.AdditiveBlending,uniforms:{t:time},
    vertexShader:`attribute float strength;varying vec2 q;varying float s;void main(){q=uv;s=strength;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}`,
    fragmentShader:`uniform float t;varying vec2 q;varying float s;void main(){
      float a=pow(sin(3.14159*q.x),2.)*smoothstep(0.,.16,q.y)*(1.-smoothstep(.33,1.,q.y));
      gl_FragColor=vec4(.52,.83,.70,s*a*(.75+.25*sin(t*.74+s*33.+q.x*5.)));
    }`
  }));

  const stones=[];
  const slate=['#405954','#536760','#486568','#637567','#4d6061','#6f7660'];
  function addStone(x,y,z,sx,sy,sz,rigid=true){
    stones.push({x,y,z,sx,sy,sz,color:pick(slate),tilt:range(-.35,.35),turn:range(-3,3)});
    if(rigid)solid.push({x,y,z,sx,sy,sz});
  }
  for(const [x,z,s] of [[-7.1,-12.1,1],[-15,-26,.79],[17,-30,.82]]){
    for(let i=0;i<=14;i++){
      const a=Math.PI*i/14;
      addStone(x+4.15*s*Math.cos(a),.65+s*5.55*Math.sin(a),z+.3*Math.sin(a*3),s*range(1,1.34),s*range(1,1.35),s*range(1.02,1.49));
    }
  }
  for(const [x,z,s] of [[-11,-12,1.4],[-17,-24,2.5],[18,-23,2.6],[-14,-5,2.1],[17,-2,1.8],[-7,3,1.11],[7,4,1.15],[-10,12,1.6],[10,13,1.4]]){
    for(let i=0;i<7;i++){
      const a=range(0,6.28),d=range(0,s*1.45),r=s*range(.38,.96);
      addStone(x+d*Math.cos(a),ground(x,z)+r*.35,z+d*Math.sin(a),r*range(.95,1.6),r*range(.71,1.12),r);
    }
  }
  for(let i=0;i<310;i++){
    const x=range(-34,34),z=range(-51,25),s=range(.05,Math.abs(x)<3?.27:.59);
    addStone(x,ground(x,z)+s*.2,z,s*range(.76,1.72),s*.71,s,s>.34);
  }
  const stoneGeo=new T.IcosahedronGeometry(1,2), st=stoneGeo.attributes.position, stoneColors=[];
  for(let i=0;i<st.count;i++){
    const x=st.getX(i),y=st.getY(i),z=st.getZ(i);
    const r=1+.12*Math.sin(7*x+3*y)*Math.sin(8*z-4*y)+.08*Math.cos(10*z+4*x);
    st.setXYZ(i,x*r,y*r,z*r);
    const c=.68+.29*(.5+.5*Math.sin(y*5+z*4+x*3))+.20*Math.max(0,y);
    stoneColors.push(c,c,c*.95);
  }
  stoneGeo.computeVertexNormals();stoneGeo.setAttribute('color',new T.Float32BufferAttribute(stoneColors,3));
  const rockBatch=new T.InstancedMesh(stoneGeo,standard('#ffffff',{vertexColors:true}),stones.length);
  stones.forEach((s,i)=>{
    dummy.position.set(s.x,s.y,s.z);dummy.rotation.set(s.tilt,s.turn,s.tilt*.7);dummy.scale.set(s.sx,s.sy,s.sz);dummy.updateMatrix();
    rockBatch.setMatrixAt(i,dummy.matrix);rockBatch.setColorAt(i,new T.Color(s.color));
  });
  scene.add(rockBatch);

  const ship=new T.Group();
  ship.position.set(7.1,.18,-15.8);ship.rotation.set(0,-.28,-.105);scene.add(ship);
  ship.updateMatrixWorld(true);
  const inverse=ship.matrixWorld.clone().invert();
  const timberCanvas=document.createElement('canvas');
  timberCanvas.width=256;timberCanvas.height=96;
  const ink=timberCanvas.getContext('2d');
  ink.fillStyle='#bc946b';ink.fillRect(0,0,256,96);
  for(let i=0;i<1000;i++){
    const x=range(0,256),y=range(0,96),l=range(5,90);
    ink.strokeStyle=i%4===0?'#f1cd9560':'#48332236';ink.lineWidth=range(.4,1.5);
    ink.beginPath();ink.moveTo(x,y);ink.quadraticCurveTo(x+l*.5,y+range(-2,2),x+l,y+range(-1,1));ink.stroke();
  }
  const wood=new T.CanvasTexture(timberCanvas);
  wood.colorSpace=T.SRGBColorSpace;wood.wrapS=wood.wrapT=T.RepeatWrapping;
  const boards=['#95674b','#95704c','#a48356','#79523e','#a9764c','#81583e','#b28a5e'].map(c=>standard(c,{map:wood,side:T.DoubleSide}));
  const darkWood=standard('#483928'), rope=standard('#a28858');
  const box=new T.BoxGeometry(1,1,1);
  function board(x,y,z,a,b,c,m=pick(boards)){
    const p=mesh(ship,box,m,x,y,z);p.scale.set(a,b,c);return p;
  }
  function spar(a,b,r1,r2,m){
    const mid=a.clone().lerp(b,.5);
    const o=mesh(ship,new T.CylinderGeometry(r2,r1,a.distanceTo(b),9),m,mid.x,mid.y,mid.z);
    o.quaternion.setFromUnitVectors(up,b.clone().sub(a).normalize());
  }
  const hullWidth=x=>Math.pow(Math.max(.002,1-Math.pow(Math.abs(x)/6.15,2.63)),.58);
  const rim=x=>2.36+1.22*Math.pow(Math.abs(x)/6.15,3.7);
  const hull=(x,h,s)=>[x,.27+(rim(x)-.27)*h,s*(.31+1.55*Math.sin(h*1.39))*hullWidth(x)];
  for(const side of [-1,1]){
    for(let row=0;row<9;row++){
      const p=[],uv=[],ids=[];
      for(let i=0;i<=36;i++){
        const x=-6.14+12.28*i/36;
        p.push(...hull(x,row/9+.007,side),...hull(x,(row+1)/9-.009,side));uv.push(i/9,0,i/9,1);
        if(i&&!(row>=6&&((side===1&&i>=8&&i<=row+4)||(side<0&&i>=23&&i<=row+17)))){
          const j=i*2;ids.push(j-2,j-1,j,j-1,j+1,j);
        }
      }
      const g=geometry(p,ids);g.setAttribute('uv',new T.Float32BufferAttribute(uv,2));mesh(ship,g,boards[row%7]);
    }
    const upper=new T.CatmullRomCurve3(Array.from({length:24},(_,i)=>new T.Vector3(...hull(-6.12+i*12.24/23,1,side))));
    mesh(ship,new T.TubeGeometry(upper,46,.1,6,false),boards[4]);
    for(let x=-5;x<=5;x++){
      const rib=new T.CatmullRomCurve3([.3,.5,.72,1.03].map(h=>new T.Vector3(...hull(x,h,side)).multiply(V(1,1,.94))));
      mesh(ship,new T.TubeGeometry(rib,9,.064,5,false),darkWood);
    }
    for(const x of [-4.5,-3.2,-1.1,1.6,3.2,4.8]){
      const z=side*1.78*hullWidth(x);
      spar(V(x,rim(x)-.27,z),V(x+.04,rim(x)+.37,z),.065,.05,darkWood);
    }
  }
  for(let i=0;i<12;i++){
    const x=-5.48+i*.985,w=3.03*hullWidth(x);
    if(i<4||i>6)board(x,1.62+Math.abs(x)*.07,0,.93,.12,w);
    else for(const s of [-1,1])board(x,1.71,s*w*.39,.93,.12,w*.23);
  }
  const mast=V(-.49,8.04,-.29);
  spar(V(.47,1.55,0),mast,.17,.069,boards[4]);
  spar(V(-2.58,6.31,-.18),V(2.28,5.93,.23),.057,.083,boards[4]);
  spar(V(4.35,2.05,.07),V(3.95,4.82,-.19),.113,.047,boards[1]);
  spar(V(5.41,3.03,0),V(7.12,3.81,0),.095,.045,boards[3]);
  for(const x of [-4.87,4.16])for(const z of [-1.05,1.05]){
    const curve=new T.QuadraticBezierCurve3(mast,V(x*.45,4.15,z*.63),V(x,2.6,z));
    mesh(ship,new T.TubeGeometry(curve,15,.018,4,false),rope);
  }
  const sail=[],sailIds=[],sailColors=[];
  for(let j=0;j<=12;j++)for(let i=0;i<=20;i++){
    const u=i/20,v=j/12;
    sail.push(-.37+(u-.5)*4.45*(1-.37*v)+.29*v,6.14-.23*u-2.56*v+(.12+.32*Math.sin(u*21)**2)*v**5,.03+.59*Math.sin(Math.PI*u)*Math.sin(v*2.29)+.08*Math.sin(u*11+v*2));
    const c=new T.Color(i===1||i===19||j===0?'#9b754b':'#ba975f').multiplyScalar(.87+.11*Math.sin(i*.61+j*.36)**2);
    sailColors.push(c.r,c.g,c.b);
    if(i&&j&&!(j>8&&i>7&&i<10+((j-8)>>1))&&!(j>10&&i>16)){
      const k=j*21+i;sailIds.push(k-22,k-21,k,k-22,k,k-1);
    }
  }
  mesh(ship,geometry(sail,sailIds,sailColors),standard('#ffffff',{side:T.DoubleSide,vertexColors:true}));
  for(const [x,z,a] of [[3.5,2.1,.3],[4.4,2.5,-.3],[-3.2,-2.4,.67],[-4.4,2.2,.2]])board(x,.11,z,range(.95,1.9),.12,.24).rotation.y=a;

  const kp=[],ki=[],kc=[],flex=[];
  const greens=['#719d42','#a2aa48','#607e37','#477947','#929738','#416c47','#b0a449'];
  function blade(x,y,z,height,width,angle,lean,col,leaf){
    const start=kp.length/3,segments=leaf?10:15, phase=range(0,6.28),a=Math.cos(angle),b=Math.sin(angle);
    for(let i=0;i<=segments;i++){
      const f=i/segments, w=Math.max(.011,width*Math.sin(Math.PI*f)**.77),curve=lean*f*f+.22*Math.sin(f*4+phase)*f;
      for(let k=-1;k<=1;k++){
        const q=angle+.78*f*Math.sin(phase);
        kp.push(x+a*curve+Math.sin(q)*w*k,y+height*f+(leaf?.5*Math.sin(f*Math.PI):0)+(k===0?.055*Math.sin(f*Math.PI):0),z+b*curve-Math.cos(q)*w*k);
        flex.push(f*height+Math.max(0,y)*.89,phase);
        const v=(.57+.49*f)*(k===0?1.18:.88+.12*Math.sin(i*1.8+k));
        kc.push(col.r*v,col.g*v,col.b*v);
      }
      if(i){const j=start+3*i;ki.push(j-3,j-2,j,j-2,j+1,j,j-2,j-1,j+1,j-1,j+2,j+1);}
    }
  }
  const beds=[[-7,4,2.3],[7.8,4,2.5],[-11,1,2.7],[12,0,2.5],[-12,-5,2.8],[11,-6,2.2],[-14,-13,2.6],[-4,-19,1.8],[13,-16,2.1],[16,-22,3.5],[-14,-23,3.3],[-8,-25,2.6],[1,-26,2.7],[9,-28,3.2],[-20,-9,3.5],[20,-8,3.6],[21,-21,4.1],[-8,14,2.5],[8,14,2.2],[-3,-34,3],[7,-36,4],[-16,-35,4],[17,-37,4]];
  for(const [bx,bz,s] of beds)for(let i=0;i<8;i++){
    const x=bx+range(-s,s),z=bz+range(-s,s),y=ground(x,z)-.05,h=range(3.3,11.6),a=range(0,6.28),c=new T.Color(pick(greens));
    blade(x,y,z,h,range(.16,.39),a,range(.22,1.5),c,false);
    for(let j=0;j<5;j++)blade(x,y+h*(.13+j*.144),z,h*range(.14,.24),range(.17,.32),a+j*2.31,range(.65,1.9),c.clone().multiplyScalar(range(.82,1.22)),true);
  }
  const kelp=geometry(kp,ki,kc);
  kelp.setAttribute('flex',new T.Float32BufferAttribute(flex,2));
  const kelpMat=standard('#ffffff',{side:T.DoubleSide,vertexColors:true,emissive:'#33290d',emissiveIntensity:.19});
  kelpMat.onBeforeCompile=s=>{
    s.uniforms.time=time;
    s.vertexShader='attribute vec2 flex; uniform float time;\n'+s.vertexShader;
    s.vertexShader=s.vertexShader.replace('#include <begin_vertex>',`
      #include <begin_vertex>
      float bend=pow(max(0.,flex.x)/11.,1.6);
      transformed.x+=bend*(.84*sin(time*.84+position.z*.19+position.x*.17)+.15*sin(time*1.65+flex.y));
      transformed.z+=bend*.46*cos(time*.64+position.x*.15+position.z*.13+flex.y*.1);
    `);
  };
  mesh(scene,kelp,kelpMat);

  const coral=[],tubes=[],coralPalette=['#e89243','#d66438','#e5aa55','#b95e3c','#efbb6a','#bf742f'];
  function grow(p,d,l,r,levels,color){
    const tip=p.clone().addScaledVector(d,l);coral.push({p,tip,r,color});
    if(levels)for(let i=0;i<3;i++){
      const angle=i*2.1+range(-.56,.56);
      const dir=d.clone().multiplyScalar(.68).add(V(Math.cos(angle)*.69,range(.25,.58),Math.sin(angle)*.69)).normalize();
      grow(tip.clone().lerp(p,range(.01,.2)),dir,l*range(.54,.75),r*.58,levels-1,color);
    }
  }
  const reefs=[[-5.4,8,1.65],[5.5,7.5,1.58],[-7.8,2,1.28],[7.8,1,1.35],[-8,-5,1.18],[6,-5,1.08],[-4,-10,1.25],[-11,-11,1.3],[12,-13,1.2],[2.5,-13,.82],[11,-20,1.2],[-14,-20,1.45],[3,-23,1],[-6,-25,1.45],[16,-3,1.5],[5,12,1.36],[-5.8,13,1.4]];
  for(const [x,z,s] of reefs)for(let i=0;i<9;i++){
    const a=x+range(-1.5,1.5)*s,b=z+range(-1.25,1.25)*s,p=V(a,ground(a,b)-.015,b),c=new T.Color(pick(coralPalette));
    if(i<6)grow(p,V(range(-.52,.52),1,range(-.52,.52)).normalize(),range(.35,.68)*s,range(.045,.087)*s,i<2?3:2,c);
    else for(let j=0;j<6;j++)tubes.push({p:p.clone().add(V(range(-.31,.31),0,range(-.31,.31))),r:range(.079,.18)*s,h:range(.18,.52)*s,color:c});
  }
  const coralMat=standard('#ffffff',{side:T.DoubleSide,emissive:'#592a13',emissiveIntensity:.19});
  const pipe=new T.LatheGeometry([[.55,0],[.86,.29],[1.03,.9],[1,1],[.75,1],[.64,.83],[.35,.34]].map(([x,y])=>new T.Vector2(x,y)),10);
  const coralBatch=new T.InstancedMesh(new T.CylinderGeometry(.51,1,1,7),coralMat,coral.length);
  const tubeBatch=new T.InstancedMesh(pipe,coralMat,tubes.length);
  coral.forEach(({p,tip,r,color},i)=>{
    dummy.position.copy(p).lerp(tip,.5);dummy.quaternion.setFromUnitVectors(up,tip.clone().sub(p).normalize());
    dummy.scale.set(r,p.distanceTo(tip)*1.065,r);dummy.updateMatrix();coralBatch.setMatrixAt(i,dummy.matrix);coralBatch.setColorAt(i,color);
  });
  tubes.forEach(({p,r,h,color},i)=>{
    dummy.position.copy(p);dummy.rotation.set(range(-.25,.25),0,range(-.25,.25));dummy.scale.set(r,h,r);dummy.updateMatrix();tubeBatch.setMatrixAt(i,dummy.matrix);tubeBatch.setColorAt(i,color);
  });
  scene.add(coralBatch,tubeBatch);

  const fishP=[],fishC=[];
  function fishPart(g,color){
    const p=(g.index?g.toNonIndexed():g).attributes.position,c=new T.Color(color);
    fishP.push(...p.array);
    for(let i=0;i<p.count;i++)fishC.push(c.r,c.g,c.b);
  }
  fishPart(new T.SphereGeometry(1,11,7).scale(.42,.151,.09),'#edbd71');
  fishPart(new T.SphereGeometry(1,9,6).scale(.21,.064,.088).translate(.02,.072,0),'#e18a40');
  fishPart(geometry([-.29,0,0,-.63,.18,0,-.53,0,0,-.62,-.15,0],[0,1,2,0,2,3]),'#bc6435');
  fishPart(geometry([-.22,.091,0,-.14,.232,0,.17,.105,0],[0,1,2]),'#db8641');
  for(const s of [-1,1])fishPart(new T.SphereGeometry(.023,6,4).translate(.285,.061,s*.066),'#173b3d');
  const fishGeo=geometry(fishP,null,fishC),fishMat=standard('#ffffff',{side:T.DoubleSide,vertexColors:true,emissive:'#644418',emissiveIntensity:.19});
  const schools=[
    [-.7,6.55,-5.7,4.6,2.7,1.24,.33,53,'#ffedc6'],
    [-7.8,4.1,-11,3.7,3.6,2.3,.27,36,'#b4e4db'],
    [7.9,6.4,-19,5.7,3.34,.7,-.23,39,'#f3bf7b'],
    [2.8,4.3,-26.5,6.1,3.8,1.1,.23,41,'#95d5cd']
  ].map(([x,y,z,rx,rz,a,s,n,c])=>{
    const batch=new T.InstancedMesh(fishGeo,fishMat,n);batch.frustumCulled=false;scene.add(batch);
    const fish=Array.from({length:n},(_,i)=>{
      batch.setColorAt(i,new T.Color(c).multiplyScalar(range(.71,1.31)));
      const k=range(0,6.28),r=Math.sqrt(random());
      return {x:range(-2.36,2.36),y:Math.sin(k)*r*.97,z:Math.cos(k)*r*1.54,s:range(.43,.82),phase:range(0,6.28)};
    });
    return {x,y,z,rx,rz,a,s,batch,fish};
  });
  const course=V(0,0,0),side=V(0,0,0);
  function swimSchools(t){
    for(const s of schools){
      const a=t*s.s+s.a, cx=s.x+s.rx*Math.cos(a),cy=s.y+.46*Math.sin(a*1.2),cz=s.z+s.rz*Math.sin(a);
      course.set(-s.rx*Math.sin(a)*s.s,.12*Math.cos(a*1.2),s.rz*Math.cos(a)*s.s).normalize();
      side.crossVectors(course,up).normalize();
      s.fish.forEach((f,i)=>{
        const w=Math.sin(t*5+f.phase);
        dummy.position.set(cx,cy+f.y+w*.09,cz);dummy.position.addScaledVector(course,f.x).addScaledVector(side,f.z+w*.1);
        dummy.quaternion.setFromUnitVectors(east,course);dummy.rotateY(w*.13);dummy.scale.setScalar(f.s);dummy.updateMatrix();s.batch.setMatrixAt(i,dummy.matrix);
      });
      s.batch.instanceMatrix.needsUpdate=true;
    }
  }
  const mantas=[];
  for(let i=0;i<3;i++){
    const ray=new T.Group(),p=[],ids=[],colors=[];
    for(let x=0;x<=24;x++)for(let j=0;j<=10;j++){
      const u=(x-12)/12,w=Math.abs(u),v=j/10,front=.72+.72*w-1.13*w*w,back=-.83+.30*w+.81*w*w;
      p.push(2.13*u,Math.sin(v*Math.PI)*(.15-.11*w)-.11*w,front+(back-front)*v);
      const c=new T.Color(w>.88?'#50828b':'#294e61').lerp(new T.Color('#b0a071'),Math.max(0,(.12-v)*1.6));
      colors.push(c.r,c.g,c.b);
      if(x&&j){const k=x*11+j;ids.push(k-12,k,k-11,k-12,k-1,k);}
    }
    const wing=geometry(p,ids,colors);
    mesh(ray,wing,standard('#ffffff',{vertexColors:true,side:T.DoubleSide,emissive:'#13475a',emissiveIntensity:.29}));
    const skin=standard('#3b6b78');
    mesh(ray,new T.SphereGeometry(1,14,8).scale(.44,.16,.79),skin,0,.05,0);
    const tail=new T.CatmullRomCurve3([V(0,0,-.64),V(.04,-.06,-1.04),V(.09,-.12,-1.58),V(.02,-.086,-2.1)]);
    mesh(ray,new T.TubeGeometry(tail,15,.029,5,false),skin);
    for(const s of [-1,1])mesh(ray,new T.SphereGeometry(1,8,6).scale(.071,.079,.32),skin,s*.22,.015,.81).rotation.y=s*.28;
    ray.scale.setScalar([1.15,.83,.98][i]);scene.add(ray);mantas.push({ray,wing,p});
  }
  function glide(t){
    mantas.forEach(({ray,wing,p},i)=>{
      const a=t*(.15+i*.018)+1.37+i*1.68,rx=[7.7,12,9][i],rz=[5.4,6.8,6][i];
      ray.position.set([-1,2,7][i]+rx*Math.cos(a),[9.7,8.1,10.65][i]+.57*Math.sin(a*1.4),[-8.5,-20,-25][i]+rz*Math.sin(a));
      ray.rotation.set(.067*Math.sin(a),Math.atan2(-rx*Math.sin(a),rz*Math.cos(a)),.16+.14*Math.cos(a));
      const attr=wing.attributes.position;
      for(let j=0;j<attr.count;j++){
        const x=p[j*3],z=p[j*3+2],w=Math.abs(x)/2.13;
        attr.setY(j,p[j*3+1]+w*w*.49*Math.sin(t*1.61+i*1.2-w*1.32+z*.38));
      }
      attr.needsUpdate=true;wing.computeVertexNormals();
    });
  }

  const vents=[[-5.3,5.6],[5.5,3.2],[-9,-11],[9,-14],[14,-20]];
  const bubbles=Array.from({length:515},(_,i)=>{
    const pair=i<75?vents[i%vents.length]:[range(-27,27),range(-45,21)];
    return {x:pair[0]+range(-.35,.35),z:pair[1]+range(-.35,.35),y:range(0,13.65),s:i<125?range(.026,.085):range(.009,.023),v:i<125?range(.26,1):range(.035,.081),a:range(0,6.28)};
  });
  const dust=new T.BufferGeometry(), cloud=new Float32Array(bubbles.length*3);
  dust.setAttribute('position',new T.BufferAttribute(cloud,3));
  dust.setAttribute('size',new T.Float32BufferAttribute(bubbles.map(b=>b.s),1));
  const bubbleMat=new T.ShaderMaterial({
    transparent:true,depthWrite:false,blending:T.AdditiveBlending,uniforms:{pixel:{value:1}},
    vertexShader:`uniform float pixel;attribute float size;varying float b;varying float fade;void main(){
      vec4 p=modelViewMatrix*vec4(position,1.);gl_Position=projectionMatrix*p;
      gl_PointSize=clamp(pixel*size/max(.4,-p.z),1.25,26.);
      b=step(.025,size);fade=exp(-.025*length(p.xyz))*smoothstep(.15,1.8,-p.z);
    }`,
    fragmentShader:`varying float b;varying float fade;void main(){
      vec2 p=gl_PointCoord-.5;float r=length(p);
      float rim=smoothstep(.29,.42,r)*(1.-smoothstep(.44,.5,r));
      float glint=1.-smoothstep(.025,.13,length(p-vec2(-.16,-.22)));
      gl_FragColor=vec4(.68,.91,.82,fade*mix((1.-smoothstep(.06,.5,r))*.55,rim*.60+glint*.84,b));
    }`
  });
  const cloudMesh=new T.Points(dust,bubbleMat);cloudMesh.frustumCulled=false;scene.add(cloudMesh);

  const spawn=V(.05,6,13.3), local=V(0,0,0), target=V(0,0,0), motion=V(0,0,0), trial=V(0,0,0);
  const labels=[[$('arch'),V(-7.1,4.45,-12)],[$('wreck'),V(8.7,4.1,-15.55)]];
  let yaw=.016,pitch=-.063,wantYaw=yaw,wantPitch=pitch,speed=0,held=null,x0=0,y0=0,touring=false,start=0;
  function blocked(p){
    if(p.y<ground(p.x,p.z)+.67||p.y>13.29||Math.abs(p.x)>35||p.z< -47||p.z>27)return true;
    for(const s of solid){
      const r=Math.max(s.sx,s.sz)*1.18+.44;
      const x=(p.x-s.x)/r,y=(p.y-s.y)/(s.sy*1.23+.49),z=(p.z-s.z)/r;
      if(x*x+y*y+z*z<1)return true;
    }
    local.copy(p).applyMatrix4(inverse);
    const {x,y,z}=local;
    if(Math.abs(x)<6.59&&y>-.28&&y<rim(x)+.65&&Math.abs(z)<1.99*hullWidth(Math.min(Math.abs(x),5.98))+.46)return true;
    if(y>1.1&&y<8.52&&Math.hypot(x-(.47-(y-1.55)*.96/6.49),z+.12)<.51)return true;
    if(x> -2.94&&x<2.7&&y>3.25&&y<6.76&&Math.abs(z-.16)<.79)return true;
    if(y>1.7&&y<5.16&&Math.hypot(x-4.14,z+.06)<.57)return true;
    if(x>5.0&&x<7.52&&Math.abs(z)<.46&&Math.abs(y-(3.03+(x-5.41)*.46))<.53)return true;
    if(y>2.4&&y<8.32&&Math.abs(z)<1.48){
      const s=(8.04-y)/5.44, zRope=.05+.93*s;
      for(const end of [-4.87,4.16])if(Math.abs(x-(-.49+(end+.49)*s))<.55&&Math.abs(Math.abs(z)-zRope)<.53)return true;
    }
    return false;
  }
  function move(d){
    trial.copy(camera.position).add(d);
    if(!blocked(trial)){camera.position.copy(trial);return;}
    for(const a of ['x','z','y']){
      trial.copy(camera.position);trial[a]+=d[a];
      if(!blocked(trial))camera.position.copy(trial);
    }
  }
  function reset(){
    camera.position.copy(spawn);yaw=wantYaw=.016;pitch=wantPitch=-.063;speed=0;
    camera.rotation.set(pitch,yaw,0);
  }
  const path=new T.CatmullRomCurve3([spawn,V(-1.3,5.1,4.35),V(-6.2,3.7,-5.4),V(-7.1,3.25,-14.1),V(-3.6,5.4,-21.4),V(1.85,6.75,-21),V(4.05,8.5,-13.4),V(5.0,7.65,-5.6),V(3.65,6.15,4.1)],true);
  const look=new T.CatmullRomCurve3([V(-.3,4.5,-10),V(-6.6,4.2,-12),V(-7.1,3.4,-14.6),V(-1.7,5.4,-20.7),V(6,6,-17.5),V(8,5.4,-14.4),V(8.05,5.46,-16),V(.8,8.7,-10.8),V(-.4,4.5,-8.5)],true);
  function tour(on){
    touring=on;speed=0;wantYaw=yaw;wantPitch=pitch;
    if(on){reset();start=performance.now();}
    $('tour').setAttribute('aria-pressed',String(on));
    $('tourText').textContent=on?'End tour':'Guided swim';
    $('play').setAttribute('d',on?'M6 4h8v12H6z':'m7 4 9 6-9 6z');
  }
  reset();tour(location.hash==='#demo');
  $('tour').onclick=()=>tour(!touring);
  $('reset').onclick=()=>{tour(false);reset();};
  document.addEventListener('pointerdown',e=>{if(e.pointerType==='touch'&&touring&&!$('tour').contains(e.target))tour(false);},true);
  canvas.addEventListener('pointerdown',e=>{
    if(held!==null||(e.pointerType==='mouse'&&e.button!==0))return;
    if(touring)tour(false);
    held=e.pointerId;x0=e.clientX;y0=e.clientY;canvas.setPointerCapture(held);
  });
  canvas.addEventListener('pointermove',e=>{
    if(e.pointerId!==held)return;
    const k=e.pointerType==='touch'?.0071:.0053;
    wantYaw-=(e.clientX-x0)*k;
    wantPitch=T.MathUtils.clamp(wantPitch-(e.clientY-y0)*k,-1.25,1.25);
    x0=e.clientX;y0=e.clientY;
  });
  for(const name of ['pointerup','pointercancel','lostpointercapture'])canvas.addEventListener(name,e=>{if(e.pointerId===held)held=null;});
  canvas.addEventListener('contextmenu',e=>e.preventDefault());
  addEventListener('blur',()=>{held=null;});
  addEventListener('hashchange',()=>tour(location.hash==='#demo'));
  const projected=V(0,0,0), aim=V(0,0,0), sectors=['N','NE','E','SE','S','SW','W','NW'];
  const depth=$('depth'),heading=$('heading'),needle=$('needle');
  let last=performance.now(),elapsed=0;
  function frame(now){
    const dt=Math.max(0,Math.min(.045,(now-last)/1000));last=now;elapsed+=dt;time.value=elapsed;
    if(touring){
      const u=Math.max(0,(now-start)/20000)%1;
      path.getPoint(u,target);motion.copy(target).sub(camera.position).clampLength(0,dt*13);move(motion);
      look.getPoint(u,aim).sub(camera.position);
      const turn=Math.atan2(-aim.x,-aim.z)-yaw;
      yaw+=Math.atan2(Math.sin(turn),Math.cos(turn))*(1-Math.exp(-dt*4.1));
      pitch=T.MathUtils.damp(pitch,Math.atan2(aim.y,Math.hypot(aim.x,aim.z)),4.1,dt);
    }else{
      yaw=T.MathUtils.damp(yaw,wantYaw,13,dt);pitch=T.MathUtils.damp(pitch,wantPitch,13,dt);
      speed=T.MathUtils.damp(speed,held===null?0:3.45,held===null?4.8:2.7,dt);
      if(speed>.005)move(motion.set(-Math.sin(yaw)*Math.cos(pitch),Math.sin(pitch),-Math.cos(yaw)*Math.cos(pitch)).multiplyScalar(speed*dt));
    }
    camera.rotation.set(pitch,yaw,0);camera.updateMatrixWorld();
    swimSchools(elapsed);glide(elapsed);
    bubbles.forEach((b,i)=>{
      cloud[i*3]=b.x+.22*Math.sin(elapsed*.67+b.a);
      cloud[i*3+1]=(b.y+elapsed*b.v)%13.65;
      cloud[i*3+2]=b.z+.16*Math.cos(elapsed*.51+b.a);
    });
    dust.attributes.position.needsUpdate=true;bubbleMat.uniforms.pixel.value=innerHeight*renderer.getPixelRatio()*.93;
    const deg=((Math.round(-yaw*180/Math.PI)%360)+360)%360;
    depth.textContent=(sea-camera.position.y).toFixed(1)+' m';
    heading.textContent=String(deg).padStart(3,'0')+'\u00b0 '+sectors[Math.round(deg/45)%8];
    needle.style.transform='rotate('+(-deg)+'deg)';
    for(const [el,p] of labels){
      local.copy(p).applyMatrix4(camera.matrixWorldInverse);
      projected.copy(p).project(camera);
      const on=local.z< -8&&local.z> -41&&Math.abs(projected.x)<.82&&Math.abs(projected.y)<.61;
      el.style.opacity=on?'.95':'0';
      if(on){el.style.left=(50+50*projected.x)+'%';el.style.top=(50-50*projected.y)+'%';}
    }
    renderer.render(scene,camera);requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>