Back to the app
The code
Night Courier by Claude Opus 5.5
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Sunset Fish Courier</title>
<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent;user-select:none;-webkit-user-select:none}
html,body{margin:0;height:100%;overflow:hidden;background:#1d1030;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#fff;touch-action:none}
canvas{display:block;touch-action:none}
#hud{position:fixed;inset:0;pointer-events:none}
.pill{position:absolute;top:calc(env(safe-area-inset-top) + 10px);background:rgba(35,16,45,.55);border:1px solid rgba(255,214,160,.4);border-radius:16px;padding:8px 14px;font-weight:800;font-size:18px;text-shadow:0 1px 2px #0009;backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);white-space:nowrap}
.pill b{color:#ffd77a}
#score{left:10px}#left{right:10px}
#clock{left:50%;transform:translateX(-50%);width:min(44vw,300px);text-align:center;font-size:13px;padding:6px 14px 10px}
#bar{height:8px;border-radius:4px;margin-top:6px;position:relative;background:linear-gradient(90deg,#ffd27a,#ff8a4a,#b0508a,#202a70)}
#knob{position:absolute;top:-6px;left:0;width:20px;height:20px;margin-left:-10px;border-radius:50%;background:#fff0b0;box-shadow:0 0 12px #ffcf6a}
#clock.late #ct{color:#ffb09a}
#snd{position:absolute;right:10px;top:calc(env(safe-area-inset-top) + 64px);width:50px;height:50px;border-radius:50%;border:1px solid rgba(255,214,160,.4);background:rgba(35,16,45,.55);font-size:22px;pointer-events:auto;color:#fff}
#arrow{position:absolute;width:54px;height:54px;margin:-27px 0 0 -27px;display:none;text-align:center}
#arw{width:54px;height:54px;filter:drop-shadow(0 2px 3px #0008)}
#dist{display:block;font-size:13px;font-weight:800;text-shadow:0 1px 3px #000;white-space:nowrap;margin-left:-20px;width:94px}
#toast{position:absolute;top:24%;left:50%;transform:translate(-50%,0);font-size:clamp(22px,6vw,34px);font-weight:900;color:#ffe27a;text-shadow:0 3px 8px #000b;opacity:0;transition:opacity .3s,transform .3s;white-space:nowrap}
#demo{position:absolute;left:50%;bottom:calc(env(safe-area-inset-bottom) + 92px);transform:translateX(-50%);background:rgba(0,0,0,.55);padding:8px 16px;border-radius:12px;font-weight:800;display:none;white-space:nowrap}
#cams{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom) + 14px);display:flex;gap:10px}
button{font:inherit;cursor:pointer}
#cams button,.big{font-weight:900;color:#3b1d06;background:linear-gradient(#ffe590,#ffb347);border:0;border-radius:18px;box-shadow:0 4px 0 #b4661c,0 8px 18px #0006}
#cams button{min-width:86px;min-height:60px;font-size:15px;padding:6px 10px;opacity:.72}
#cams button span{display:block;font-size:21px;line-height:1.1}
#cams button.on{opacity:1;outline:3px solid #fff;outline-offset:2px}
.ov{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;padding:16px;background:radial-gradient(ellipse at center,rgba(40,14,50,.25),rgba(18,6,28,.7))}
.card{max-width:460px;width:100%;text-align:center;padding:26px 22px;border-radius:26px;background:rgba(42,18,50,.72);border:1px solid rgba(255,210,150,.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
.card h1{margin:0 0 8px;font-size:clamp(28px,8vw,44px);line-height:1.05;color:#ffd27a;text-shadow:0 3px 0 #a3461a}
.card p{margin:8px 0;line-height:1.45;font-size:16px;color:#ffeedd}
.big{font-size:24px;padding:16px 44px;margin-top:12px;min-height:64px}
.hide{display:none!important}
#joy{position:fixed;width:124px;height:124px;margin:-62px 0 0 -62px;border:3px solid rgba(255,255,255,.45);border-radius:50%;pointer-events:none;display:none}
#joy i{position:absolute;left:50%;top:50%;width:48px;height:48px;margin:-24px;border-radius:50%;background:rgba(255,210,140,.65)}
@media(max-width:560px){.pill{font-size:15px;padding:6px 11px}#clock{top:calc(env(safe-area-inset-top) + 54px);width:min(62vw,260px)}#snd{top:calc(env(safe-area-inset-top) + 54px);width:44px;height:44px;font-size:19px}}
</style>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"}}</script>
</head>
<body>
<div id="hud" class="hide">
<div class="pill" id="score">Score <b id="sc">0</b></div>
<div class="pill" id="clock"><span id="ct">Sunset</span><div id="bar"><div id="knob"></div></div></div>
<div class="pill" id="left">🐟 Crates <b id="cl">8</b></div>
<button id="snd" aria-label="Sound on or off">🔊</button>
<div id="arrow"><svg id="arw" viewBox="0 0 54 54"><polygon points="8,11 49,27 8,43 17,27" fill="#ffe27a" stroke="#7a3a10" stroke-width="3" stroke-linejoin="round"/></svg><span id="dist"></span></div>
<div id="toast"></div>
<div id="demo">DEMO · touch anywhere to play</div>
</div>
<div id="joy"><i></i></div>
<div id="cams" class="hide"><button data-c="0"><span>✈️</span>Behind</button><button data-c="1"><span>🐱</span>Cockpit</button><button data-c="2"><span>🗺️</span>Above</button></div>
<div class="ov" id="title"><div class="card"><h1>Sunset Fish Courier</h1><p>Captain Marmalade has 8 crates of fresh fish for the cats of the lake town. Fly through each glowing ring to drop a crate by parachute, and deliver them all before night falls!</p><p style="font-size:14px;opacity:.85">Phone: drag one finger to steer · Mouse: the plane follows your pointer</p><button class="big" id="go">Take off!</button><p id="best" style="font-size:14px"></p></div></div>
<div class="ov hide" id="end"><div class="card"><h1 id="endT"></h1><p id="endP"></p><button class="big" id="again">Play again</button></div></div>
<script type="module">
import * as THREE from 'three';
import {Reflector} from 'three/addons/objects/Reflector.js';
const $=id=>document.getElementById(id);
const clamp=(v,a,b)=>v<a?a:v>b?b:v,sstep=(a,b,x)=>{const t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t)};
const TAU=Math.PI*2,wrap=a=>{a=(a+Math.PI)%TAU;if(a<0)a+=TAU;return a-Math.PI};
let seed=11;const rnd=()=>(seed=seed*16807%2147483647)/2147483647,pick=a=>a[Math.floor(rnd()*a.length)],C=s=>new THREE.Color(s);
const KEY='sunsetFishCourierBest';
/* ---------- renderer ---------- */
const renderer=new THREE.WebGLRenderer({antialias:true});
const PR=Math.min(window.devicePixelRatio||1,2);renderer.setPixelRatio(PR);renderer.setSize(innerWidth,innerHeight);
renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;
renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const scene=new THREE.Scene();scene.fog=new THREE.Fog(0xffa070,200,980);
const camera=new THREE.PerspectiveCamera(62,innerWidth/innerHeight,.08,2600);
/* ---------- terrain ---------- */
const hash=(x,y)=>{const s=Math.sin(x*127.1+y*311.7)*43758.5453;return s-Math.floor(s)};
function vn(x,y){const i=Math.floor(x),j=Math.floor(y),u=x-i,v=y-j,a=hash(i,j),b=hash(i+1,j),c=hash(i,j+1),d=hash(i+1,j+1),U=u*u*(3-2*u),W=v*v*(3-2*v);return a+(b-a)*U+(c-a)*W+(a-b-c+d)*U*W}
const fbm=(x,y)=>vn(x,y)*.5+vn(x*2.1+5,y*2.1)*.3+vn(x*4.3,y*4.3+9)*.2;
const shoreR=a=>172+22*Math.sin(3*a+.6)+12*Math.sin(5*a+2.1)+5*Math.sin(9*a);
const IS={x:35,z:-25};
function H(x,z){const d=Math.hypot(x,z)-shoreR(Math.atan2(z,x));let h;
if(d<0)h=Math.max(-9,d*.3);
else h=Math.max(d*.05,d*.09+Math.pow(Math.max(0,d-50)/100,1.5)*34+(fbm(x*.012,z*.012)-.4)*Math.min(1,d/90)*60);
const i=Math.hypot(x-IS.x,z-IS.z);return Math.min(Math.max(h,9.5*(1-i*i/1300)-1.5),190)}
function shoreAt(a){let r=shoreR(a)-40;while(r<shoreR(a)+40&&H(Math.cos(a)*r,Math.sin(a)*r)<.3)r+=.5;return r}
{const tg=new THREE.PlaneGeometry(1600,1600,220,220);tg.rotateX(-Math.PI/2);
const p=tg.attributes.position,cols=new Float32Array(p.count*3),c=new THREE.Color(),sand=C('#d8bf8a'),wet=C('#7d6a4a'),g1=C('#6c9a3a'),g2=C('#3e6a2c'),rock=C('#8f7f6c'),pale=C('#c9b9a8');
for(let i=0;i<p.count;i++){const x=p.getX(i),z=p.getZ(i),h=H(x,z);p.setY(i,h);const n=hash(x*.31,z*.17);
if(h<-.5)c.copy(wet).lerp(sand,sstep(-6,-.5,h));else if(h<1.3)c.copy(sand);
else if(h<70)c.copy(g1).lerp(g2,clamp(n*.6+h/90,0,1));else c.copy(g2).lerp(rock,sstep(70,120,h)).lerp(pale,sstep(150,185,h));
c.multiplyScalar(.9+n*.2);cols[i*3]=c.r;cols[i*3+1]=c.g;cols[i*3+2]=c.b}
tg.setAttribute('color',new THREE.BufferAttribute(cols,3));tg.computeVertexNormals();
const terrain=new THREE.Mesh(tg,new THREE.MeshLambertMaterial({vertexColors:true}));terrain.receiveShadow=true;scene.add(terrain)}
/* ---------- water with real reflections ---------- */
const WaterShader={uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null},time:{value:0}},
vertexShader:`uniform mat4 textureMatrix;varying vec4 vUv;varying vec3 vW;void main(){vUv=textureMatrix*vec4(position,1.);vW=(modelMatrix*vec4(position,1.)).xyz;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}`,
fragmentShader:`uniform vec3 color;uniform sampler2D tDiffuse;uniform float time;varying vec4 vUv;varying vec3 vW;
void main(){vec2 d=vec2(sin(vW.x*.21+time*1.3)+sin(vW.z*.13-time*.9+vW.x*.05),cos(vW.z*.19+time*1.1)+sin(vW.x*.09+vW.z*.07+time*.7));
vec4 uv=vUv;uv.xy+=d*.0065*uv.w;vec3 r=texture2DProj(tDiffuse,uv).rgb;
float f=clamp(length(cameraPosition-vW)/500.,0.,1.);
float sp=pow(max(0.,sin(vW.x*.7+time*2.)*sin(vW.z*.6-time*1.7)),12.)*.3*(1.-f);
vec3 c=mix(color,r,.68+.27*f)+sp*r;
gl_FragColor=vec4(c,1.);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`};
const wres=()=>[Math.min(1024,innerWidth*PR*.5)|0,Math.min(1024,innerHeight*PR*.5)|0];
const water=new Reflector(new THREE.PlaneGeometry(1600,1600),{textureWidth:wres()[0],textureHeight:wres()[1],color:0x7a8aa0,shader:WaterShader,clipBias:.003});
water.rotation.x=-Math.PI/2;water.position.y=.02;scene.add(water);
/* ---------- sky ---------- */
const skyU={top:{value:C('#3b6db3')},hor:{value:C('#ffc27c')},sunC:{value:C('#ffd49a')},sunD:{value:new THREE.Vector3(0,.2,-1)},night:{value:0},time:{value:0}};
const sky=new THREE.Mesh(new THREE.SphereGeometry(1000,32,16),new THREE.ShaderMaterial({uniforms:skyU,side:THREE.BackSide,depthWrite:false,
vertexShader:`varying vec3 vD;void main(){vD=position;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}`,
fragmentShader:`uniform vec3 top,hor,sunC,sunD;uniform float night,time;varying vec3 vD;
float hs(vec3 p){return fract(sin(dot(p,vec3(12.9898,78.233,37.719)))*43758.5453);}
void main(){vec3 d=normalize(vD);float y=d.y;
vec3 c=mix(hor,top,pow(clamp(y,0.,1.),.55));c=mix(c,hor*.6,smoothstep(0.,-.2,y));
float s=max(dot(d,sunD),0.);float az=max(dot(normalize(d.xz+1e-4),normalize(sunD.xz+1e-4)),0.);
c+=sunC*(pow(s,6.)*.35+pow(s,40.)*.5)*(1.-night*.6);
c+=sunC*smoothstep(.9985,.9992,s)*4.;
c+=sunC*.3*pow(az,4.)*exp(-abs(y)*9.)*(1.-night*.5);
vec3 cell=floor(d*320.);float st=step(.9975,hs(cell))*smoothstep(.02,.25,y)*night*(.6+.4*sin(time*3.+hs(cell+1.)*30.));c+=vec3(st);
vec3 md=normalize(vec3(-.5,.35,.6));float m=dot(d,md);c+=vec3(.95,.95,1.)*smoothstep(.9990,.9994,m)*night*1.6+vec3(.3,.35,.6)*pow(max(m,0.),30.)*night*.4;
gl_FragColor=vec4(c,1.);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`}));sky.renderOrder=-1;scene.add(sky);
/* ---------- lights ---------- */
const hemi=new THREE.HemisphereLight(0xcbdcff,0x5a4030,1);scene.add(hemi);
const sun=new THREE.DirectionalLight(0xffc58a,2.8);sun.castShadow=true;sun.shadow.mapSize.set(2048,2048);
{const s=sun.shadow.camera;s.left=-260;s.right=260;s.top=260;s.bottom=-260;s.near=10;s.far=900}
sun.shadow.bias=-.0004;sun.shadow.normalBias=.6;scene.add(sun);
/* ---------- materials ---------- */
function ctex(w,h,f){const c=document.createElement('canvas');c.width=w;c.height=h;f(c.getContext('2d'),w,h);const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;t.anisotropy=4;return t}
const WIN=[[10,10],[38,10],[10,38],[38,38]];
const wallT=ctex(64,64,x=>{x.fillStyle='#fff';x.fillRect(0,0,64,64);x.fillStyle='#5b6478';WIN.forEach(([a,b])=>x.fillRect(a,b,16,16));x.fillStyle='#fff';WIN.forEach(([a,b])=>x.fillRect(a+7,b,2,16))});
const winT=ctex(64,64,x=>{x.fillStyle='#000';x.fillRect(0,0,64,64);x.fillStyle='#ffd590';WIN.forEach(([a,b])=>x.fillRect(a,b,16,16))});
const L=(c,o)=>new THREE.MeshLambertMaterial(Object.assign({color:c},o||{}));
const wallMats=['#f6dcb4','#eaa57e','#bcd5e2','#f3efe0','#dcbad9','#c9dc9e'].map(c=>L(c,{map:wallT,emissive:'#ffb860',emissiveMap:winT,emissiveIntensity:.1}));
const roofMats=['#b5452f','#7a3b2a','#3f5f8a','#8a4a6a','#a8572d'].map(c=>L(c));
const lampM=L('#ffe0a0',{emissive:'#ffb050',emissiveIntensity:1}),woodM=L('#8b5a33'),postM=L('#5a3a22'),slabM=L('#8a6f5a');
const red=L('#d9443a'),cream=L('#f6ead0'),dark=L('#2c2c34');
const boxG=new THREE.BoxGeometry(1,1,1),roofG=new THREE.ConeGeometry(.75,1,4);roofG.rotateY(Math.PI/4);roofG.translate(0,.5,0);
const postG=new THREE.CylinderGeometry(.18,.18,4.6,6),lampG=new THREE.SphereGeometry(.45,10,8);
const plane=new THREE.Group();scene.add(plane);
const add=(geo,mat,x,y,z,rx=0,ry=0,rz=0,par=plane)=>{const m=new THREE.Mesh(geo,mat);m.position.set(x,y,z);m.rotation.set(rx,ry,rz);m.castShadow=true;par.add(m);return m};
/* ---------- town ---------- */
const occ=[],free=(x,z,r)=>occ.every(o=>Math.hypot(o.x-x,o.z-z)>o.r+r);
function house(x,z,w,d,h,rot,flat){const y=H(x,z),g=new THREE.Group();g.position.set(x,y-.6,z);g.rotation.y=rot;
const b=new THREE.Mesh(boxG,pick(wallMats));b.scale.set(w,h+.6,d);b.position.y=(h+.6)/2;g.add(b);let top=y+h;
if(flat){const s=new THREE.Mesh(boxG,slabM);s.scale.set(w+.5,.35,d+.5);s.position.y=h+.6+.17;g.add(s);top+=.35}
else{const r=new THREE.Mesh(roofG,pick(roofMats));r.scale.set(w*1.12,h*.5+1.5,d*1.12);r.position.y=h+.6;g.add(r)}
g.traverse(m=>{if(m.isMesh)m.castShadow=m.receiveShadow=true});scene.add(g);return top}
function makeDock(a){const r0=shoreAt(a),ux=Math.cos(a),uz=Math.sin(a),len=26,mid=r0+4-len/2;
const g=new THREE.Group();g.position.set(ux*mid,0,uz*mid);g.rotation.y=Math.atan2(ux,uz);scene.add(g);
const deck=add(new THREE.BoxGeometry(3.6,.35,len),woodM,0,1.3,0,0,0,0,g);deck.receiveShadow=true;
for(let z=-len/2+1;z<len/2;z+=6.5)for(const s of[-1.6,1.6])add(postG,postM,s,-1,z,0,0,0,g);
add(postG,postM,1.6,2.6,-len/2+1,0,0,0,g).scale.set(.6,.5,.6);add(lampG,lampM,1.6,4,-len/2+1,0,0,0,g);
occ.push({x:ux*(r0+3),z:uz*(r0+3),r:7});const cr=r0+4-len+2.2;
return{pos:new THREE.Vector3(ux*cr,1.48,uz*cr),drop:new THREE.Vector3(ux*(cr+3.4),1.48,uz*(cr+3.4))}}
function roofTarget(x,z,h){const top=house(x,z,8,8,h,Math.atan2(x,z),true);occ.push({x,z,r:9});return{pos:new THREE.Vector3(x,top,z),drop:new THREE.Vector3(x+2.6,top,z+1)}}
/* ---------- cats ---------- */
const sph=new THREE.SphereGeometry(1,16,12),earG=new THREE.ConeGeometry(1,1,4),tailG=new THREE.CylinderGeometry(.05,.08,.9,6),armG=new THREE.CylinderGeometry(.07,.07,.5,6);
tailG.translate(0,.45,0);armG.translate(0,-.25,0);
const mats={},cm=c=>mats[c]||(mats[c]=L(c));
function catHead(c,g){const m=cm(c);const hs=new THREE.Mesh(sph,m);hs.scale.set(.42,.38,.38);g.add(hs);
for(const s of[-1,1]){const e=new THREE.Mesh(earG,m);e.scale.set(.15,.3,.12);e.position.set(s*.24,.4,0);e.rotation.z=-s*.3;g.add(e);
const ey=new THREE.Mesh(sph,cm('#1b1510'));ey.scale.setScalar(.06);ey.position.set(s*.15,.06,.34);g.add(ey)}
const mz=new THREE.Mesh(sph,cm('#fff6ea'));mz.scale.set(.18,.12,.1);mz.position.set(0,-.1,.32);g.add(mz);
const ns=new THREE.Mesh(sph,cm('#ff8fa0'));ns.scale.setScalar(.045);ns.position.set(0,-.03,.42);g.add(ns)}
function makeCat(c){const g=new THREE.Group(),m=cm(c);
const b=new THREE.Mesh(sph,m);b.scale.set(.5,.62,.45);b.position.y=.6;b.castShadow=true;g.add(b);
const hd=new THREE.Group();hd.position.y=1.38;catHead(c,hd);g.add(hd);
const t=new THREE.Mesh(tailG,m);t.position.set(0,.3,-.38);t.rotation.x=-.8;g.add(t);
const a=new THREE.Mesh(armG,m);a.position.set(.4,1,.08);g.add(a);
g.userData={hd,t,a};g.scale.setScalar(2.2);return g}
/* ---------- rings & targets ---------- */
const ringG=new THREE.TorusGeometry(6.5,.45,10,48),haloG=new THREE.TorusGeometry(6.5,1.5,8,48);
const ringM=new THREE.MeshBasicMaterial({color:'#ffe27a',toneMapped:false});
const haloM=new THREE.MeshBasicMaterial({color:'#ffae40',transparent:true,opacity:.3,blending:THREE.AdditiveBlending,depthWrite:false,toneMapped:false});
const beamM=haloM.clone();beamM.opacity=.12;beamM.side=THREE.DoubleSide;
const beamG=new THREE.CylinderGeometry(3,1.2,1,14,1,true);beamG.translate(0,.5,0);
const markG=new THREE.RingGeometry(2.2,3,32);markG.rotateX(-Math.PI/2);
const N=8,targets=[],defs=[];
for(const a of[.35,2,3.6,5.2])defs.push(makeDock(a));
for(const a of[1.2,2.8,4.4]){const r=shoreAt(a)+15;defs.push(roofTarget(Math.cos(a)*r,Math.sin(a)*r,8+rnd()*3))}
defs.push(roofTarget(IS.x,IS.z,5));
const catCols=['#ee8a35','#8d8d96','#2b2a2f','#f4efe6','#c9773a','#d9a066','#6b5a4a','#f2b36a'];
defs.forEach((d,i)=>{const cat=makeCat(catCols[i]);cat.position.copy(d.pos);scene.add(cat);
const rp=d.pos.clone();rp.y+=24+(i*7%3)*5;
const ring=new THREE.Group();ring.add(new THREE.Mesh(ringG,ringM),new THREE.Mesh(haloG,haloM));ring.position.copy(rp);scene.add(ring);
const beam=new THREE.Mesh(beamG,beamM);beam.position.copy(d.pos);beam.scale.set(1,rp.y-d.pos.y-6.5,1);scene.add(beam);
const mark=new THREE.Mesh(markG,haloM);mark.position.copy(d.pos);mark.position.y+=.06;scene.add(mark);
targets.push({pos:d.pos,drop:d.drop,cat,ring,beam,mark,rp,state:0,jump:0,fade:0,box:null,i})});
for(let i=0,n=0;i<500&&n<48;i++){const a=rnd()*TAU,r=shoreR(a)+5+rnd()*45,x=Math.cos(a)*r,z=Math.sin(a)*r;
if(H(x,z)<.8||!free(x,z,5))continue;house(x,z,4+rnd()*3,4+rnd()*3,3+rnd()*4,Math.atan2(x,z)+(rnd()-.5)*.4,false);occ.push({x,z,r:5});n++}
for(const a of[.6,2.3,3.9]){const x=IS.x+Math.cos(a)*13,z=IS.z+Math.sin(a)*13;house(x,z,3.5,3.5,3,a,false);occ.push({x,z,r:4})}
/* lighthouse */
const lhx=IS.x+21,lhz=IS.z-9,lhy=H(lhx,lhz);occ.push({x:lhx,z:lhz,r:3});
add(new THREE.CylinderGeometry(1.3,1.8,12,16),L('#f4f0e8'),lhx,lhy+5.5,lhz,0,0,0,scene);
add(new THREE.CylinderGeometry(1.64,1.72,1.4,16),L('#c8392f'),lhx,lhy+3,lhz,0,0,0,scene);
add(new THREE.CylinderGeometry(1.42,1.5,1.4,16),L('#c8392f'),lhx,lhy+8,lhz,0,0,0,scene);
add(new THREE.CylinderGeometry(1,1,1.6,12),lampM,lhx,lhy+12.3,lhz,0,0,0,scene);
add(new THREE.ConeGeometry(1.4,1.4,12),L('#c8392f'),lhx,lhy+13.8,lhz,0,0,0,scene);
const lhBeam=new THREE.Group();lhBeam.position.set(lhx,lhy+12.3,lhz);scene.add(lhBeam);
{const g=new THREE.ConeGeometry(4,60,16,1,true);g.translate(0,-30,0);g.rotateZ(Math.PI/2);
lhBeam.add(new THREE.Mesh(g,new THREE.MeshBasicMaterial({color:'#ffe9a8',transparent:true,opacity:0,blending:THREE.AdditiveBlending,depthWrite:false,side:THREE.DoubleSide})))}
const lhMat=lhBeam.children[0].material;
/* ---------- trees ---------- */
const treeG=new THREE.ConeGeometry(2,7,7);treeG.translate(0,3.2,0);
const trees=new THREE.InstancedMesh(treeG,L('#ffffff'),700);let tn=0;
const M1=new THREE.Matrix4(),Q1=new THREE.Quaternion(),V1=new THREE.Vector3(),S1=new THREE.Vector3();
const treeCols=['#2f5a2a','#3d6b2f','#4b7a36','#2a4d33','#567f3a'].map(C);
const plant=(x,z,s)=>{const h=H(x,z);if(h<1.2||h>125||tn>=700||!free(x,z,2))return;M1.compose(V1.set(x,h-.4,z),Q1,S1.set(s,s*(.8+rnd()*.5),s));trees.setMatrixAt(tn,M1);trees.setColorAt(tn,pick(treeCols));tn++};
for(let i=0;i<60;i++){const a=rnd()*TAU,r=8+rnd()*22;plant(IS.x+Math.cos(a)*r,IS.z+Math.sin(a)*r,.5+rnd()*.5)}
for(let i=0;i<6000;i++){const a=rnd()*TAU,r=shoreR(a)+10+Math.pow(rnd(),1.3)*330;plant(Math.cos(a)*r,Math.sin(a)*r,.7+rnd()*.9)}
trees.count=tn;trees.castShadow=trees.receiveShadow=true;scene.add(trees);
/* ---------- boats ---------- */
const boats=[];
{const sh=new THREE.Shape();sh.moveTo(0,0);sh.lineTo(0,5.2);sh.lineTo(2.6,0);const sailG=new THREE.ShapeGeometry(sh),sailM=L('#fff4e0',{side:THREE.DoubleSide});
[[1.6,95,'#2f6fa8'],[4,120,'#c8492f'],[5.6,110,'#3a8a5a']].forEach(([a,r,c])=>{const g=new THREE.Group();g.position.set(Math.cos(a)*r,0,Math.sin(a)*r);g.rotation.y=a;scene.add(g);
add(new THREE.BoxGeometry(2,1,5),L('#fbf3e4'),0,.3,0,0,0,0,g);add(new THREE.BoxGeometry(2.1,.3,5.1),L(c),0,.75,0,0,0,0,g);
add(new THREE.CylinderGeometry(.08,.08,6,6),dark,0,3.8,0,0,0,0,g);add(sailG,sailM,0,1.1,.1,0,-Math.PI/2,0,g);boats.push(g)})}
/* ---------- clouds ---------- */
const CL=[],puffs=[];
for(let i=0;i<26;i++){const a=rnd()*TAU,r=40+rnd()*460;CL.push({x:Math.cos(a)*r,y:58+rnd()*50,z:Math.sin(a)*r,s:.7+rnd()*.9});
for(let j=0;j<6;j++)puffs.push({c:i,dx:(rnd()-.5)*22,dy:(rnd()-.4)*4,dz:(rnd()-.5)*10,s:4.5+rnd()*5.5})}
const cloudM=L('#ffffff',{emissive:'#ff9a70',emissiveIntensity:1});
const clouds=new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1,2),cloudM,puffs.length);clouds.frustumCulled=false;scene.add(clouds);
function updClouds(dt){for(const c of CL){c.x+=dt*2;if(c.x>520)c.x=-520}
puffs.forEach((p,i)=>{const c=CL[p.c],s=p.s*c.s;M1.compose(V1.set(c.x+p.dx*c.s,c.y+p.dy*c.s,c.z+p.dz*c.s),Q1,S1.set(s,s*.62,s));clouds.setMatrixAt(i,M1)});
clouds.instanceMatrix.needsUpdate=true}
/* ---------- the plane & its pilot ---------- */
add(new THREE.CylinderGeometry(.3,.62,5,14),red,0,0,.1,Math.PI/2);
add(new THREE.CylinderGeometry(.64,.62,.6,14),dark,0,0,-2.55,Math.PI/2);
add(new THREE.ConeGeometry(.24,.55,12),cream,0,0,-3.1,-Math.PI/2);
const prop=new THREE.Group();prop.position.z=-2.95;plane.add(prop);
{const bg=new THREE.BoxGeometry(.2,1.25,.05);bg.translate(0,.62,0);add(bg,dark,0,0,0,0,0,0,prop);add(bg,dark,0,0,0,0,0,Math.PI,prop)}
{const disc=new THREE.Mesh(new THREE.CircleGeometry(1.3,24),new THREE.MeshBasicMaterial({color:'#fff',transparent:true,opacity:.1,depthWrite:false,side:THREE.DoubleSide}));disc.position.z=-2.98;plane.add(disc)}
add(new THREE.BoxGeometry(7.4,.16,1.35),cream,0,-.2,-.7);
add(new THREE.BoxGeometry(.9,.17,1.37),red,3.3,-.2,-.7);add(new THREE.BoxGeometry(.9,.17,1.37),red,-3.3,-.2,-.7);
add(new THREE.BoxGeometry(2.6,.1,.75),cream,0,.1,2.35);add(new THREE.BoxGeometry(.1,1.1,.85),red,0,.62,2.3);
add(new THREE.BoxGeometry(1,.32,.25),dark,0,.55,-.25);
{const gm=new THREE.MeshBasicMaterial({color:'#9ff0c0',toneMapped:false}),cg=new THREE.CircleGeometry(.09,14);for(const x of[-.25,0,.25])add(cg,gm,x,.58,-.12)}
add(new THREE.PlaneGeometry(1,.5),new THREE.MeshLambertMaterial({color:'#bfe6ff',transparent:true,opacity:.35,side:THREE.DoubleSide,depthWrite:false}),0,.85,-.45,.6).castShadow=false;
for(const s of[-1,1]){add(new THREE.BoxGeometry(.05,.55,.05),dark,s*.5,.85,-.45,.6);
add(new THREE.CylinderGeometry(.28,.28,.18,12),dark,s*.75,-1,-1.2,0,0,Math.PI/2);add(new THREE.BoxGeometry(.08,.8,.08),dark,s*.58,-.62,-1.2,0,0,s*.45)}
const pilot=new THREE.Group();pilot.position.set(0,.98,.45);pilot.rotation.y=Math.PI;plane.add(pilot);catHead('#ee8a35',pilot);
for(const s of[-1,1])add(new THREE.TorusGeometry(.12,.035,6,14),L('#6b4a2a'),s*.14,.2,.3,-.3,0,0,pilot);
const scarfG=new THREE.BoxGeometry(.16,.04,1.1);scarfG.translate(0,0,-.55);
const scarf=add(scarfG,L('#3f7fd0'),.12,-.3,-.25,.25,0,0,pilot);
/* ---------- crates, parachutes, sparkles ---------- */
const crateT=ctex(128,128,(x,w,h)=>{x.fillStyle='#b9824a';x.fillRect(0,0,w,h);x.fillStyle='#8f5f30';for(let i=1;i<4;i++)x.fillRect(0,i*32-2,w,4);x.strokeStyle='#5e3c1c';x.lineWidth=10;x.strokeRect(5,5,w-10,h-10);
x.fillStyle='#3f9bd6';x.beginPath();x.ellipse(56,64,30,17,0,0,7);x.fill();x.beginPath();x.moveTo(80,64);x.lineTo(108,44);x.lineTo(108,84);x.fill();
x.fillStyle='#fff';x.beginPath();x.arc(38,60,5,0,7);x.fill();x.fillStyle='#000';x.beginPath();x.arc(38,60,2.5,0,7);x.fill()});
const crateG=new THREE.BoxGeometry(1.8,1.8,1.8),crateM=L('#fff',{map:crateT});
const chuteT=ctex(256,8,x=>{for(let i=0;i<8;i++){x.fillStyle=i%2?'#fff4dc':'#ff5a48';x.fillRect(i*32,0,32,8)}});
const chuteG=new THREE.SphereGeometry(2.8,16,6,0,TAU,0,Math.PI/2);chuteG.scale(1,.55,1);
const chuteM=L('#fff',{map:chuteT,side:THREE.DoubleSide}),lineM=new THREE.LineBasicMaterial({color:'#5a4030'});
const strG=new THREE.BufferGeometry();{const p=[];for(let i=0;i<4;i++){const a=i*Math.PI/2+Math.PI/4;p.push(Math.cos(a)*2.7,0,Math.sin(a)*2.7,Math.cos(a)*1.1,-3.5,Math.sin(a)*1.1)}strG.setAttribute('position',new THREE.Float32BufferAttribute(p,3))}
function makeCrate(){const g=new THREE.Group(),b=new THREE.Mesh(crateG,crateM);b.castShadow=true;g.add(b);
const ch=new THREE.Group();ch.position.y=4.4;ch.add(new THREE.Mesh(chuteG,chuteM),new THREE.LineSegments(strG,lineM));g.add(ch);g.userData.ch=ch;scene.add(g);return g}
const dotT=ctex(32,32,x=>{const g=x.createRadialGradient(16,16,0,16,16,16);g.addColorStop(0,'#fff');g.addColorStop(.4,'#ffd870');g.addColorStop(1,'rgba(255,160,60,0)');x.fillStyle=g;x.fillRect(0,0,32,32)});
const PN=400,pP=new Float32Array(PN*3).fill(-999),pV=new Float32Array(PN*3),pL=new Float32Array(PN);
const pG=new THREE.BufferGeometry();pG.setAttribute('position',new THREE.BufferAttribute(pP,3));
const parts=new THREE.Points(pG,new THREE.PointsMaterial({map:dotT,size:1.6,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,toneMapped:false}));parts.frustumCulled=false;scene.add(parts);
let pI=0;
function burst(p,n,s){for(let k=0;k<n;k++){const j=(pI++)%PN,a=rnd()*TAU,b=rnd()*2-1,q=Math.sqrt(1-b*b),v=s*(.4+rnd()*.6);
pP[j*3]=p.x;pP[j*3+1]=p.y;pP[j*3+2]=p.z;pV[j*3]=Math.cos(a)*q*v;pV[j*3+1]=b*v+s*.4;pV[j*3+2]=Math.sin(a)*q*v;pL[j]=1}}
function updParts(dt){for(let j=0;j<PN;j++){if(pL[j]<=0)continue;pL[j]-=dt*.7;if(pL[j]<=0){pP[j*3+1]=-999;continue}
pV[j*3+1]-=6*dt;for(let k=0;k<3;k++){pV[j*3+k]*=.985;pP[j*3+k]+=pV[j*3+k]*dt}}pG.attributes.position.needsUpdate=true}
/* ---------- time of day ---------- */
const KF=[[0,'#3b6db3','#ffc27c','#ffd49a','#ffc58a',2.9,'#cbdcff',1.05,'#7d93ae'],[.45,'#2d4a8e','#ff9354','#ffa25c','#ffa364',2.3,'#dcb4d2',.85,'#6f7d9c'],
[.75,'#1b2559','#cf5c7b','#ff7444','#e27c72',1,'#8c7aba',.6,'#3e4870'],[1,'#060b22','#28284f','#ff5232','#7c90d0',.4,'#3c4c84',.45,'#151b36']]
.map(k=>({t:k[0],top:C(k[1]),hor:C(k[2]),sun:C(k[3]),lc:C(k[4]),li:k[5],hs:C(k[6]),hi:k[7],wc:C(k[8])}));
function skyF(f){let i=0;while(i<KF.length-2&&f>KF[i+1].t)i++;const a=KF[i],b=KF[i+1],u=clamp((f-a.t)/(b.t-a.t),0,1);
skyU.top.value.lerpColors(a.top,b.top,u);skyU.hor.value.lerpColors(a.hor,b.hor,u);skyU.sunC.value.lerpColors(a.sun,b.sun,u);
sun.color.lerpColors(a.lc,b.lc,u);sun.intensity=a.li+(b.li-a.li)*u;hemi.color.lerpColors(a.hs,b.hs,u);hemi.intensity=a.hi+(b.hi-a.hi)*u;
water.material.uniforms.color.value.lerpColors(a.wc,b.wc,u);scene.fog.color.copy(skyU.hor.value);
const el=.21-.35*f,az=.55,ce=Math.cos(el);skyU.sunD.value.set(Math.sin(az)*ce,Math.sin(el),-Math.cos(az)*ce);
const le=Math.max(el,.16),cl=Math.cos(le);sun.position.set(Math.sin(az)*cl,Math.sin(le),-Math.cos(az)*cl).multiplyScalar(400);
const n=sstep(.55,1,f);skyU.night.value=n;const g=.08+2.6*sstep(.3,.85,f);wallMats.forEach(m=>m.emissiveIntensity=g);
lampM.emissiveIntensity=.6+3*sstep(.2,.8,f);cloudM.emissive.copy(skyU.hor.value).multiplyScalar(.5);lhMat.opacity=.25*n}
/* ---------- game state ---------- */
const S={mode:'title',t:0,T:150,score:0,cam:0,done:0,dropped:0,demoT:0,snap:true};
const P={pos:new THREE.Vector3(),yaw:0,pitch:0,roll:0,speed:28},inp={sx:0,sy:0},crates=[];
const FV=new THREE.Vector3(),fwd=()=>FV.set(-Math.sin(P.yaw)*Math.cos(P.pitch),Math.sin(P.pitch),-Math.cos(P.yaw)*Math.cos(P.pitch));
function reset(){S.t=0;S.score=0;S.done=0;S.dropped=0;P.pos.set(0,40,170);P.yaw=0;P.pitch=0;P.roll=0;inp.sx=inp.sy=0;
crates.forEach(c=>scene.remove(c.g));crates.length=0;
for(const t of targets){t.state=0;t.fade=0;t.jump=0;t.ring.visible=t.beam.visible=t.mark.visible=true;t.ring.scale.setScalar(1);if(t.box){scene.remove(t.box);t.box=null}t.cat.position.copy(t.pos)}
hud()}
function nearest(){let b=null,bd=1e9;for(const t of targets)if(t.state===0){const d=t.rp.distanceTo(P.pos);if(d<bd){bd=d;b=t}}return[b,bd]}
function hud(){$('sc').textContent=S.score;$('cl').textContent=N-S.dropped}
let toastT=0;function toast(s){const e=$('toast');e.textContent=s;e.style.opacity=1;e.style.transform='translate(-50%,-12px)';clearTimeout(toastT);toastT=setTimeout(()=>{e.style.opacity=0;e.style.transform='translate(-50%,0)'},1400)}
function drop(t){t.state=1;t.fade=1;S.dropped++;const g=makeCrate();g.position.copy(P.pos);g.position.y-=1.2;const f=fwd();
crates.push({g,t,vx:f.x*P.speed*.5,vz:f.z*P.speed*.5,a:0});burst(t.rp,40,14);sfx.ring();toast('Crate away!');hud()}
function land(t,g){t.state=2;t.box=g;t.jump=1.6;t.beam.visible=t.mark.visible=false;S.done++;
const pts=100+Math.round(Math.max(0,S.T-S.t));S.score+=pts;burst(V1.copy(t.pos).setY(t.pos.y+3),60,10);sfx.meow();toast(`+${pts} Delivered!`);hud();
if(S.done===N&&S.mode==='play')setTimeout(()=>endGame(true),1500)}
function updCrates(dt){for(let i=crates.length-1;i>=0;i--){const c=crates[i],g=c.g,tp=c.t.drop,ch=g.userData.ch;c.a+=dt;
const k=1-Math.exp(-dt*1.3),d=Math.exp(-dt*2);c.vx*=d;c.vz*=d;
g.position.x+=(tp.x-g.position.x)*k+c.vx*dt;g.position.z+=(tp.z-g.position.z)*k+c.vz*dt;
const o=Math.min(1,c.a*2.2);ch.scale.setScalar(.15+.85*o);
g.position.y-=(16-10.5*o)*dt;g.rotation.z=Math.sin(c.a*2.3)*.12;g.rotation.x=Math.cos(c.a*1.9)*.1;
if(g.position.y<=tp.y+.9){g.position.set(tp.x,tp.y+.9,tp.z);g.rotation.set(0,c.a,0);ch.visible=false;crates.splice(i,1);land(c.t,g)}}}
function updTargets(dt,tm){for(const t of targets){const r=t.ring,cat=t.cat,u=cat.userData;
if(t.state===0){r.lookAt(P.pos.x,r.position.y,P.pos.z);r.scale.setScalar(1+Math.sin(tm*3+t.i)*.05)}
else if(t.fade>0){t.fade-=dt*2.5;r.scale.setScalar(1+(1-t.fade)*.8);if(t.fade<=0)r.visible=false}
cat.rotation.y+=wrap(Math.atan2(P.pos.x-cat.position.x,P.pos.z-cat.position.z)-cat.rotation.y)*Math.min(1,dt*2);
u.t.rotation.z=Math.sin(tm*3+t.i)*.5;
const near=t.state===0&&P.pos.distanceTo(t.pos)<110;
u.a.rotation.z=near?2.5+Math.sin(tm*12)*.45:u.a.rotation.z+(.15-u.a.rotation.z)*Math.min(1,dt*4);
if(t.jump>0){t.jump-=dt*.55;cat.position.y=t.pos.y+Math.abs(Math.sin(t.jump*12))*1.4*Math.max(0,t.jump);u.a.rotation.z=2.6+Math.sin(tm*14)*.5;if(t.jump<=0)cat.position.y=t.pos.y}
t.mark.scale.setScalar(1+Math.sin(tm*4+t.i)*.12)}}
/* ---------- flying ---------- */
function auto(){const[t]=nearest(),tx=t?t.rp.x:0,ty=t?t.rp.y:45,tz=t?t.rp.z:0,dx=tx-P.pos.x,dz=tz-P.pos.z,dist=Math.hypot(dx,dz);
const err=wrap(Math.atan2(-dx,-dz)-P.yaw);inp.sx=clamp(-err*2.2,-1,1);if(dist<38&&Math.abs(err)>1)inp.sx=0;
inp.sy=clamp(Math.atan2(ty-P.pos.y,Math.max(dist,8))/.5*1.3,-1,1)}
function cruise(){inp.sx=.28;inp.sy=clamp((48-P.pos.y)*.05,-.6,.6)}
function fly(dt){let sx=inp.sx;const sy=inp.sy,r=Math.hypot(P.pos.x,P.pos.z);
if(r>300){const e=wrap(Math.atan2(P.pos.x,P.pos.z)-P.yaw);sx+=(clamp(-e*2,-1,1)-sx)*clamp((r-300)/50,0,1)}
P.roll+=(-sx*.85-P.roll)*(1-Math.exp(-dt*3));P.pitch+=(sy*.5-P.pitch)*(1-Math.exp(-dt*2.2));
if(P.pos.y>112&&P.pitch>0)P.pitch*=.9;
P.yaw+=P.roll*1.35*dt;P.pos.addScaledVector(fwd(),P.speed*dt);
const g=Math.max(H(P.pos.x,P.pos.z),0)+3.4;if(P.pos.y<g){P.pos.y=g;if(P.pitch<.15)P.pitch=.15}
plane.position.copy(P.pos);plane.rotation.set(P.pitch,P.yaw,P.roll,'YXZ');prop.rotation.z+=dt*45}
/* ---------- cameras ---------- */
const cT=new THREE.Vector3(),cLk=new THREE.Vector3(),UP=new THREE.Vector3(0,1,0),tilt=new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0),-.12);
function setCam(i){S.cam=i;camera.fov=[62,72,55][i];camera.updateProjectionMatrix();document.querySelectorAll('#cams button').forEach((b,k)=>b.classList.toggle('on',k===i))}
function updCam(dt){plane.updateMatrixWorld();const fx=-Math.sin(P.yaw),fz=-Math.cos(P.yaw);pilot.visible=S.cam!==1;
if(S.cam===1){camera.position.copy(plane.localToWorld(cT.set(0,1.02,.75)));camera.quaternion.copy(plane.quaternion).multiply(tilt);camera.up.copy(UP);return}
if(S.cam===0){cT.set(P.pos.x-fx*13,P.pos.y+4.2,P.pos.z-fz*13);cLk.set(P.pos.x+fx*8,P.pos.y+1.2,P.pos.z+fz*8);camera.up.copy(UP)}
else{cT.set(P.pos.x-fx*8,P.pos.y+70,P.pos.z-fz*8);cLk.set(P.pos.x+fx*14,P.pos.y,P.pos.z+fz*14);camera.up.set(fx,0,fz)}
camera.position.lerp(cT,S.snap?1:1-Math.exp(-dt*(S.cam?2.5:5)));S.snap=false;
const g=Math.max(H(camera.position.x,camera.position.z),0)+1.5;if(camera.position.y<g)camera.position.y=g;
camera.lookAt(cLk)}
const AV=new THREE.Vector3();
function updArrow(){const el=$('arrow'),[t,d]=nearest();if(!t||!(S.mode==='play'||S.mode==='demo')){el.style.display='none';return}
AV.copy(t.rp).project(camera);let x=AV.x,y=AV.y,ang;const behind=AV.z>1;if(behind){x=-x;y=-y;if(Math.abs(y)<.3&&Math.abs(x)<.3)y=-.8}
if(!behind&&Math.abs(x)<.9&&Math.abs(y)<.8){ang=90;el.style.left=((x+1)/2*innerWidth)+'px';el.style.top=((1-y)/2*innerHeight-70)+'px'}
else{const m=Math.max(Math.abs(x)/.86,Math.abs(y)/.72,1e-3);x/=m;y/=m;ang=-Math.atan2(y,x)*180/Math.PI;el.style.left=((x+1)/2*innerWidth)+'px';el.style.top=((1-y)/2*innerHeight)+'px'}
el.style.display='block';$('arw').style.transform=`rotate(${ang}deg)`;$('dist').textContent=Math.round(d)+' m'}
let lastS=-1;
function hudClock(){$('knob').style.left=(S.t/S.T*100)+'%';const s=Math.max(0,Math.ceil(S.T-S.t));if(s===lastS)return;lastS=s;
$('ct').textContent=s>0?`Night falls in ${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`:'Night!';$('clock').classList.toggle('late',s<=20)}
/* ---------- sound (synthesized) ---------- */
let AC=null,eng=null,master=null,muted=false;
function initAudio(){try{if(!AC){AC=new(window.AudioContext||window.webkitAudioContext)();master=AC.createGain();master.gain.value=.5;master.connect(AC.destination);
const o1=AC.createOscillator(),o2=AC.createOscillator(),f=AC.createBiquadFilter(),g=AC.createGain(),g2=AC.createGain(),lfo=AC.createOscillator(),lg=AC.createGain();
o1.type='sawtooth';o2.type='square';o1.frequency.value=62;o2.frequency.value=93;f.type='lowpass';f.frequency.value=520;g.gain.value=0;
lfo.frequency.value=22;lg.gain.value=.3;lfo.connect(lg);lg.connect(g2.gain);
o1.connect(f);o2.connect(f);f.connect(g);g.connect(g2);g2.connect(master);o1.start();o2.start();lfo.start();eng={o1,o2,g}}
AC.resume&&AC.resume()}catch(e){}}
function tone(fr,dur,type='sine',vol=.2,slide=0,delay=0){if(!AC||muted)return;try{const t=AC.currentTime+delay,o=AC.createOscillator(),g=AC.createGain();o.type=type;o.frequency.setValueAtTime(fr,t);
if(slide)o.frequency.exponentialRampToValueAtTime(slide,t+dur);g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(vol,t+.02);g.gain.exponentialRampToValueAtTime(.0001,t+dur);
o.connect(g);g.connect(master);o.start(t);o.stop(t+dur+.05)}catch(e){}}
const sfx={ring(){tone(880,.25,'sine',.18);tone(1320,.3,'sine',.14,0,.07);tone(1760,.45,'sine',.1,0,.14)},
meow(){tone(620,.32,'triangle',.22,980);tone(980,.38,'triangle',.18,520,.18)},
win(){[523,659,784,1047].forEach((f,i)=>tone(f,.45,'triangle',.18,0,i*.13))},
lose(){[392,330,262].forEach((f,i)=>tone(f,.55,'sine',.15,0,i*.2))}};
function engine(){if(!eng)return;const t=AC.currentTime,f=60+P.pitch*25+Math.abs(P.roll)*8;
eng.g.gain.setTargetAtTime(S.mode==='play'&&!muted?.05:0,t,.1);eng.o1.frequency.setTargetAtTime(f,t,.1);eng.o2.frequency.setTargetAtTime(f*1.5,t,.1)}
/* ---------- flow ---------- */
function ui(){const m=S.mode;$('title').classList.toggle('hide',m!=='title');$('end').classList.toggle('hide',m!=='end');
$('cams').classList.toggle('hide',!(m==='play'||m==='demo'));$('hud').classList.toggle('hide',m==='title');$('demo').style.display=m==='demo'?'block':'none';
if(m!=='play')$('joy').style.display='none'}
function bestScore(){try{return+localStorage.getItem(KEY)||0}catch(e){return 0}}
function showBest(){const b=bestScore();$('best').textContent=b?'Best score: '+b:''}
function startGame(){initAudio();reset();S.mode='play';S.snap=true;ui()}
function startDemo(){reset();S.mode='demo';S.demoT=0;setCam(0);S.snap=true;const[t]=nearest();if(t)P.yaw=Math.atan2(-(t.rp.x-P.pos.x),-(t.rp.z-P.pos.z));ui()}
function exitDemo(){reset();S.mode='title';setCam(0);S.snap=true;showBest();ui()}
function endGame(win){if(S.mode!=='play')return;S.mode='end';let bonus=0;if(win){bonus=Math.round((S.T-S.t)*10);S.score+=bonus}
let best=bestScore();if(S.score>best){best=S.score;try{localStorage.setItem(KEY,String(best))}catch(e){}}
$('endT').textContent=win?'Every cat got its fish!':'Night has fallen…';
$('endP').innerHTML=`Delivered <b>${S.done} of ${N}</b> crates<br>${win?`Time bonus +${bonus}<br>`:''}Score <b>${S.score}</b> · Best ${best}`;
win?sfx.win():sfx.lose();hud();ui()}
$('go').onclick=startGame;$('again').onclick=startGame;
document.querySelectorAll('#cams button').forEach(b=>b.addEventListener('click',()=>setCam(+b.dataset.c)));
$('snd').addEventListener('click',()=>{muted=!muted;$('snd').textContent=muted?'🔇':'🔊';initAudio()});
/* ---------- input ---------- */
const cv=renderer.domElement,joy=$('joy'),knob=joy.firstElementChild;let tid=null,tx=0,ty=0;
function mouseSteer(e){if(S.mode!=='play')return;const s=Math.min(innerWidth,innerHeight)*.38,dz=v=>Math.abs(v)<.05?0:clamp(v,-1,1);
inp.sx=dz((e.clientX-innerWidth/2)/s);inp.sy=dz((innerHeight/2-e.clientY)/s)}
addEventListener('pointerdown',e=>{if(S.mode==='demo'&&e.isTrusted)exitDemo()},true);
cv.addEventListener('pointerdown',e=>{if(e.pointerType==='mouse'){mouseSteer(e);return}
tid=e.pointerId;tx=e.clientX;ty=e.clientY;joy.style.left=tx+'px';joy.style.top=ty+'px';knob.style.transform='';joy.style.display=S.mode==='play'?'block':'none'});
addEventListener('pointermove',e=>{if(e.pointerType==='mouse'){if(e.target===cv)mouseSteer(e);return}if(e.pointerId!==tid)return;
let dx=e.clientX-tx,dy=e.clientY-ty;const l=Math.hypot(dx,dy),mx=60;if(l>mx){dx*=mx/l;dy*=mx/l}
if(S.mode==='play'){inp.sx=dx/mx;inp.sy=-dy/mx}knob.style.transform=`translate(${dx}px,${dy}px)`});
const up=e=>{if(e.pointerId===tid){tid=null;if(S.mode==='play')inp.sx=inp.sy=0;joy.style.display='none'}};
addEventListener('pointerup',up);addEventListener('pointercancel',up);
addEventListener('contextmenu',e=>e.preventDefault());
addEventListener('resize',()=>{camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();renderer.setSize(innerWidth,innerHeight);const r=wres();water.getRenderTarget().setSize(r[0],r[1])});
addEventListener('hashchange',()=>{if(location.hash==='#demo')startDemo()});
/* ---------- main loop ---------- */
let last=performance.now(),clk=0;
function loop(now){requestAnimationFrame(loop);const dt=Math.min(.05,Math.max(0,(now-last)/1000));last=now;clk+=dt;
const m=S.mode,active=m==='play'||m==='demo';
if(m==='demo'){S.demoT+=dt;auto();const k=Math.min(2,Math.floor(S.demoT/(20/3)));if(k!==S.cam)setCam(k);S.t=Math.min(S.T*.9,S.t+dt*S.T*.6/20);if(S.demoT>=20)startDemo()}
else if(m==='play'){S.t+=dt;if(S.t>=S.T){S.t=S.T;if(!(S.dropped===N&&S.done<N))endGame(false)}}
else cruise();
fly(dt);
if(active){for(const t of targets)if(t.state===0&&P.pos.distanceTo(t.rp)<7.4)drop(t);updCrates(dt)}
updTargets(dt,clk);updParts(dt);updClouds(dt);
boats.forEach((b,i)=>{b.position.y=Math.sin(clk*1.3+i*2)*.15;b.rotation.z=Math.sin(clk+i)*.06});
lhBeam.rotation.y+=dt*.9;scarf.rotation.y=Math.sin(clk*20)*.25;
skyF(S.t/S.T);updCam(dt);sky.position.copy(camera.position);
water.material.uniforms.time.value=clk;skyU.time.value=clk;
engine();hudClock();updArrow();
renderer.render(scene,camera)}
reset();setCam(0);showBest();
if(location.hash==='#demo')startDemo();else ui();
requestAnimationFrame(loop);
</script>
</body>
</html>
