Game_world / gameworld2.html
Afredbilli's picture
Update gameworld2.html
4f5bda4 verified
Raw History Blame Contribute Delete
22.2 kB
<!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">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#9fd0ff">
<title>Terminal Walk</title>
<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
html,body{margin:0;height:100%;overflow:hidden;background:#9fd0ff;touch-action:none;overscroll-behavior:none;font-family:-apple-system,system-ui,sans-serif}
canvas{position:fixed;inset:0;width:100%;height:100%;display:block}
#ui{position:fixed;inset:0;pointer-events:none;padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)}
#joy{position:absolute;left:28px;bottom:36px;width:140px;height:140px;border-radius:50%;pointer-events:auto;touch-action:none;background:rgba(255,255,255,.14);border:2px solid rgba(255,255,255,.45);backdrop-filter:blur(3px)}
#knob{position:absolute;left:50%;top:50%;width:62px;height:62px;margin:-31px 0 0 -31px;border-radius:50%;background:rgba(255,255,255,.4);border:2px solid rgba(255,255,255,.8);box-shadow:0 2px 10px rgba(0,0,0,.2)}
.btn{position:absolute;pointer-events:auto;touch-action:none;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:12px;letter-spacing:.06em;text-shadow:0 1px 3px rgba(0,0,0,.5);background:rgba(255,255,255,.14);border:2px solid rgba(255,255,255,.5);backdrop-filter:blur(3px);transition:transform .08s,background .08s}
.btn.on{transform:scale(.92);background:rgba(255,255,255,.38)}
/* thumb cluster (matches the approved layout): SPRINT corner, JUMP beside it, extras on a clear second row */
#sprint{right:36px;bottom:44px;width:84px;height:84px}
#jump{right:132px;bottom:30px;width:66px;height:66px}
#sit{right:140px;bottom:130px;width:62px;height:62px;opacity:0;pointer-events:none!important;transform:scale(.7);transition:opacity .2s,transform .2s,background .08s}
#sit.show{opacity:1;pointer-events:auto!important;transform:scale(1)}
#emote{right:44px;bottom:162px;width:56px;height:56px}
@media (max-height:480px){#joy{bottom:16px}#sprint{bottom:20px}#jump{bottom:8px}#sit{bottom:100px}#emote{bottom:128px}}
#hud{position:absolute;top:12px;left:14px;color:#fff;font-size:13px;font-weight:600;text-shadow:0 1px 4px rgba(0,0,0,.5);opacity:.9}
#load{position:fixed;inset:0;display:flex;flex-direction:column;gap:14px;align-items:center;justify-content:center;background:linear-gradient(#bfe0ff,#ffe8c2);color:#33415c;text-align:center;padding:24px;z-index:9}
#load button,#load label{background:#33415c;color:#fff;border:0;border-radius:14px;padding:13px 22px;font-size:15px;font-weight:600}
#load input{display:none}
#msg{font-size:14px;max-width:320px;line-height:1.4}
</style></head><body>
<div id="ui">
<div id="hud">Terminal Walk</div>
<div id="joy"><div id="knob"></div></div>
<div class="btn" id="emote">WAVE</div>
<div class="btn" id="sit">SIT</div>
<div class="btn" id="jump">JUMP</div>
<div class="btn" id="sprint">SPRINT</div>
</div>
<div id="load"><div style="font-size:22px;font-weight:800">Terminal Walk</div><div id="msg">Loading character_rigged.glb…</div>
<label id="pick" style="display:none">Choose character_rigged.glb<input type="file" id="file" accept=".glb,.gltf"></label></div>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/GLTFLoader.js"></script>
<script>
const $=id=>document.getElementById(id);
const renderer=new THREE.WebGLRenderer({antialias:true,powerPreference:'high-performance'});
renderer.setPixelRatio(Math.min(devicePixelRatio,2));
renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;
renderer.outputEncoding=THREE.sRGBEncoding;
document.body.prepend(renderer.domElement);
const scene=new THREE.Scene();
const SKY=0xa9d6ff;scene.background=new THREE.Color(SKY);scene.fog=new THREE.Fog(0xcfe6f7,25,95);
const camera=new THREE.PerspectiveCamera(60,1,.1,200);
function resize(){const w=innerWidth,h=innerHeight;renderer.setSize(w,h);camera.aspect=w/h;camera.updateProjectionMatrix()}
addEventListener('resize',resize);resize();
// ---------- light ----------
scene.add(new THREE.HemisphereLight(0xdff1ff,0xf3d9b0,.75));
const sun=new THREE.DirectionalLight(0xfff0cc,1.15);
sun.position.set(-18,22,10);sun.castShadow=true;
sun.shadow.mapSize.set(2048,2048);
Object.assign(sun.shadow.camera,{left:-22,right:22,top:22,bottom:-22,near:1,far:70});
sun.shadow.bias=-.0006;
scene.add(sun,sun.target);
// ---------- low poly airport terminal ----------
const L=140,W=26,H=9,colliders=[],seats=[],benchSpots=[];
const mat=(c,o={})=>new THREE.MeshLambertMaterial(Object.assign({color:c,flatShading:true},o));
function box(w,h,d,c,x,y,z,o){const m=new THREE.Mesh(new THREE.BoxGeometry(w,h,d),o&&o.m||mat(c));m.position.set(x,y,z);m.castShadow=!(o&&o.noCast);m.receiveShadow=true;scene.add(m);return m}
function solid(w,h,d,c,x,y,z){box(w,h,d,c,x,y,z);colliders.push({x,z,hx:w/2+.1,hz:d/2+.1})}
// floor with tile stripes
box(W,.4,L,0xeee6d8,0,-.2,-L/2+8);
for(let i=0;i<14;i++)box(W,.02,.12,0xd8cdb8,0,.01,8-i*10);
box(4,.03,L,0xc9553d,0,.02,-L/2+8); // carpet runner
// ceiling + beams
box(W,.4,L,0xf6f3ee,0,H,-L/2+8,{noCast:true});
for(let z=8;z>-L+8;z-=10)box(W,.5,.6,0xffffff,0,H-.4,z);
// left glass wall (sun side), right shop wall
const glass=mat(0x9fd8ff,{transparent:true,opacity:.28,flatShading:false});
box(.2,H,L,0,-W/2,H/2,-L/2+8,{m:glass,noCast:true});
for(let z=8;z>-L+8;z-=10)box(.4,H,.4,0xffffff,-W/2,H/2,z);
box(.3,H,L,0xf0e4cf,W/2,H/2,-L/2+8);
box(.3,1.2,L,0x33415c,W/2-.2,.6,-L/2+8);
box(W,H,.3,0xf0e4cf,0,H/2,-L+8); // end wall
box(W,H,.3,0xf0e4cf,0,H/2,9); // start wall
// pillars
for(let z=-2;z>-L+8;z-=14){solid(1,H,1,0xffffff,-6,H/2,z);solid(1,H,1,0xffffff,6,H/2,z-7)}
// check-in desks, benches, plants, signs
const pal=[0xe86a4a,0x3fa7a0,0xf2b84b,0x5b7fd6];
for(let i=0;i<6;i++){const z=-8-i*20,c=pal[i%4];
solid(6,1.2,1.4,0x33415c,9,.6,z);box(6,.15,1.6,c,9,1.28,z);
box(.2,3,.2,0x33415c,9,2.7,z);box(5,.9,.15,c,9,4.2,z-.6);
benchSpots.push([-10.3,z],[-10.3,z-11]);
const p=new THREE.Group();p.position.set(-10.5,0,z-6);
const pot=new THREE.Mesh(new THREE.CylinderGeometry(.5,.4,.8,6),mat(0xb86f50));pot.position.y=.4;
const lf=new THREE.Mesh(new THREE.IcosahedronGeometry(.9,0),mat(0x4caf6a));lf.position.y=1.5;lf.castShadow=true;
p.add(pot,lf);scene.add(p);colliders.push({x:-10.5,z:z-6,hx:.8,hz:.8});}
// luggage carts / trolleys as scatter
for(let i=0;i<8;i++){solid(.9,1,.6,pal[i%4],-3+(i%2)*6,.5,-14-i*15)}
// sunlight shafts through windows
const shaftM=new THREE.MeshBasicMaterial({color:0xfff2c4,transparent:true,opacity:.1,depthWrite:false,blending:THREE.AdditiveBlending,side:THREE.DoubleSide});
for(let z=3;z>-L+8;z-=10){const s=new THREE.Mesh(new THREE.PlaneGeometry(3.6,16),shaftM);
s.position.set(-8.5,H/2-.5,z-5);s.rotation.set(0,Math.PI/2,0);s.rotation.z=.6;scene.add(s)}
// outside: apron, planes, hills
box(200,.2,260,0x8d949c,-120,-.3,-50);
for(let i=0;i<3;i++){const g=new THREE.Group();g.position.set(-38,0,-20-i*40);
const b=new THREE.Mesh(new THREE.CylinderGeometry(2.2,2.2,22,7),mat(0xffffff));b.rotation.x=Math.PI/2;b.position.y=3.6;b.castShadow=true;
const n=new THREE.Mesh(new THREE.ConeGeometry(2.2,5,7),mat(0xffffff));n.rotation.x=-Math.PI/2;n.position.set(0,3.6,-13.5);
const w=new THREE.Mesh(new THREE.BoxGeometry(26,.4,4),mat(0xdfe6ee));w.position.set(0,3,1);
const t=new THREE.Mesh(new THREE.BoxGeometry(.4,5,3.5),mat(pal[i]));t.position.set(0,7,9);
g.add(b,n,w,t);scene.add(g)}
for(let i=0;i<7;i++){const h=new THREE.Mesh(new THREE.ConeGeometry(30+i*3,18+i*4,5),mat(i%2?0x7fb5a0:0x6fa58f));h.position.set(-120+i*5,8,-140+i*40-100);scene.add(h)}
// sun disc
const sd=new THREE.Mesh(new THREE.CircleGeometry(7,16),new THREE.MeshBasicMaterial({color:0xfff6d8,fog:false}));
sd.position.set(-110,70,-60);sd.lookAt(0,0,0);scene.add(sd);
// ---------- input ----------
const inp={x:0,y:0,sprint:false,jump:false,emote:false,keys:{}};
const joy=$('joy'),knob=$('knob');let jid=null,R=70;
function jmove(e){const r=joy.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;
let dx=e.clientX-cx,dy=e.clientY-cy;const d=Math.hypot(dx,dy),m=Math.min(d,R);
if(d>0){dx=dx/d*m;dy=dy/d*m}
knob.style.transform=`translate(${dx}px,${dy}px)`;inp.x=dx/R;inp.y=dy/R}
joy.addEventListener('pointerdown',e=>{jid=e.pointerId;joy.setPointerCapture(jid);jmove(e);e.preventDefault()});
joy.addEventListener('pointermove',e=>{if(e.pointerId===jid)jmove(e)});
const jend=e=>{if(e.pointerId===jid){jid=null;inp.x=inp.y=0;knob.style.transform=''}};
joy.addEventListener('pointerup',jend);joy.addEventListener('pointercancel',jend);
function hold(id,k){const b=$(id);
b.addEventListener('pointerdown',e=>{b.setPointerCapture(e.pointerId);inp[k]=true;b.classList.add('on');if(navigator.vibrate)navigator.vibrate(8);e.preventDefault()});
const up=()=>{inp[k]=false;b.classList.remove('on')};
b.addEventListener('pointerup',up);b.addEventListener('pointercancel',up)}
hold('sprint','sprint');hold('jump','jump');hold('emote','emote');
$('sit').addEventListener('pointerdown',e=>{e.preventDefault();toggleSit();if(navigator.vibrate)navigator.vibrate(8)});
addEventListener('keydown',e=>{inp.keys[e.code]=1;if(e.code==='Space')inp.jump=true;if(e.code==='KeyE')inp.emote=true;if(e.code==='KeyC'&&!e.repeat)toggleSit()});
addEventListener('keyup',e=>{inp.keys[e.code]=0;if(e.code==='Space')inp.jump=false;if(e.code==='KeyE')inp.emote=false});
// camera orbit: drag anywhere that isn't a control
let yaw=0,pitch=.28,lid=null,lx=0,ly=0;
const cv=renderer.domElement;
cv.addEventListener('pointerdown',e=>{lid=e.pointerId;lx=e.clientX;ly=e.clientY;cv.setPointerCapture(lid)});
cv.addEventListener('pointermove',e=>{if(e.pointerId!==lid)return;
yaw-=(e.clientX-lx)*.006;pitch=Math.max(-.1,Math.min(.9,pitch+(e.clientY-ly)*.005));lx=e.clientX;ly=e.clientY});
cv.addEventListener('pointerup',()=>lid=null);cv.addEventListener('pointercancel',()=>lid=null);
document.addEventListener('touchmove',e=>e.preventDefault(),{passive:false});
// ---------- character ----------
const player=new THREE.Group();player.position.set(0,0,4);scene.add(player);
let mixer=null,acts={},cur=null,model=null,hop=0,hopV=0,emoting=0;
const find=re=>{for(const k in clipMap)if(re.test(k))return clipMap[k]};let clipMap={};
function setup(gltf){
model=gltf.scene;
model.traverse(o=>{if(o.isMesh||o.isSkinnedMesh){o.castShadow=true;o.receiveShadow=true;o.frustumCulled=false;
[].concat(o.material).forEach(m=>{if(m.map)m.map.encoding=THREE.sRGBEncoding})}});
const bb=new THREE.Box3().setFromObject(model),h=bb.max.y-bb.min.y;
model.scale.setScalar(1.8/h);model.position.y=-bb.min.y*1.8/h;baseY=model.position.y;RG=findRig(model);
player.add(model);
mixer=new THREE.AnimationMixer(model);
gltf.animations.forEach(c=>clipMap[c.name.toLowerCase()]=c);
const mk=(name,clip,ts=1)=>{if(!clip)return;const a=mixer.clipAction(clip);a.timeScale=ts;acts[name]=a};
const walk=find(/walk/),run=find(/run|jog/),spr=find(/sprint|fast/);
mk('idle',find(/idle|stand|breath/)||walk);
mk('walk',walk||run,walk?1:.6);
mk('run',run||walk,run?1:1.5);
mk('sprint',spr||run||walk,spr?1:(run?1.35:2));
if(acts.walk)acts.walk._b=acts.walk.timeScale;
mk('emote',find(/wave|emote|dance|action|hello/));
if(!find(/idle|stand|breath/)&&acts.idle)acts.idle.timeScale=0; // freeze pose if no idle clip
['emote'].forEach(n=>{if(acts[n]){acts[n].setLoop(THREE.LoopOnce);acts[n].clampWhenFinished=true}});
mixer.addEventListener('finished',()=>{emoting=0;cur=null});
if(!acts.emote)$('emote').style.display='none';
play('idle');
$('load').style.display='none';
$('hud').textContent='Clips: '+gltf.animations.map(a=>a.name).join(', ')+' | Rig: '+Object.keys(RG).join(',');
setTimeout(()=>$('hud').textContent='Terminal Walk',7000);
}
function play(n,f=.25){if(n===cur||!acts[n])return;const a=acts[n],p=acts[cur];
a.reset().setEffectiveWeight(1).fadeIn(f).play();if(p)p.fadeOut(f);cur=n}
// load: try sibling file first, then picker
const loader=new THREE.GLTFLoader();
function fail(){ $('msg').textContent='Pick your character_rigged.glb to start.';$('pick').style.display='inline-block'}
loader.load('character_rigged.glb',setup,e=>{if(e.total)$('msg').textContent='Loading… '+Math.round(e.loaded/e.total*100)+'%'},fail);
$('file').addEventListener('change',e=>{const f=e.target.files[0];if(!f)return;$('msg').textContent='Loading…';
const u=URL.createObjectURL(f);loader.load(u,setup,undefined,()=>$('msg').textContent='Could not read that file.')});
// ---------- procedural rig pose (experimental) ----------
// Bends bones around the character's lateral axis in WORLD space, converted to each bone's local space,
// so it works whatever the rig's local bone axes are. Hip flex = -angle, knee bend = +angle (about +X).
let baseY=0,RG={},sit=null,jp=null,jt=0,gb=1,pose={h:0,k:0,s:0},rigList=[],rigBase=[];
const AX=new THREE.Vector3(),QQ=new THREE.Quaternion(),PQ=new THREE.Quaternion(),DQ=new THREE.Quaternion();
function findRig(root){
const r={},set=(k,b)=>{if(!r[k])r[k]=b},bones=[];
root.traverse(o=>{if(o.isBone)bones.push(o)});
for(const b of bones){
const n=b.name.toLowerCase().replace('mixamorig','');
const s=/left|[._:\-]l$|^l[._:\-]|_l_/.test(n)?'L':/right|[._:\-]r$|^r[._:\-]|_r_/.test(n)?'R':'';
if(/hips|pelvis/.test(n))set('hips',b);
else if(/spine/.test(n))set('spine',b);
else if(s&&/upleg|upperleg|upper_leg|up_leg|thigh/.test(n))set('up'+s,b);
else if(s&&/lowerleg|lower_leg|calf|shin/.test(n))set('lo'+s,b);
else if(s&&/foot|ankle/.test(n)&&!/toe/.test(n))set('ft'+s,b);
else if(s&&/leg/.test(n)&&!/toe|foot/.test(n))set('lo'+s,b);
}
rigList=[r.spine,r.upL,r.upR,r.loL,r.loR,r.ftL,r.ftR].filter(Boolean);
rigBase=rigList.map(b=>b.quaternion.clone());
return r;
}
function rot(b,ang){if(!b||!ang||!b.parent)return;
b.parent.updateWorldMatrix(true,false);b.parent.getWorldQuaternion(PQ);
DQ.setFromAxisAngle(AX,ang);QQ.copy(PQ).invert().multiply(DQ).multiply(PQ);
b.quaternion.premultiply(QQ)}
function restoreRig(){rigList.forEach((b,i)=>b.quaternion.copy(rigBase[i]))}
function poseUpdate(dt){
if(!model)return;
let T=[0,0,0],rate=10;
if(sit==='bench'){T=[1.45,1.45,-.05];rate=7}
else if(sit){T=[1.25,2.35,.3];rate=7}
else if(jp==='pre'){T=[.8,1.6,.28];rate=16}
else if(jp==='air'){T=[.55,1.25,.1];rate=9}
else if(jp==='land'){T=[.75,1.5,.25];rate=18}
const f=Math.min(1,dt*rate);
pose.h+=(T[0]-pose.h)*f;pose.k+=(T[1]-pose.k)*f;pose.s+=(T[2]-pose.s)*f;
gb+=((hop>0?0:1)-gb)*Math.min(1,dt*14);
rigList.forEach((b,i)=>rigBase[i].copy(b.quaternion)); // snapshot of the clip pose
if(Math.abs(pose.h)+Math.abs(pose.k)+Math.abs(pose.s)>.003){
const ry=player.rotation.y;AX.set(Math.cos(ry),0,-Math.sin(ry));
rot(RG.spine,pose.s);
rot(RG.upL,-pose.h);rot(RG.upR,-pose.h);
rot(RG.loL,pose.k);rot(RG.loR,pose.k);
rot(RG.ftL,pose.h-pose.k);rot(RG.ftR,pose.h-pose.k); // keep feet flat
}
// lower the body so the feet stay planted (thigh/shin ~0.47m each)
const drop=Math.max(0,.94-.47*Math.cos(pose.h)-.47*Math.cos(pose.h-pose.k));
model.position.y=baseY-drop*gb;
}
let lift=0,sitSeat=null,nearSeat=null,sitShown=false;
function toggleSit(){
if(sit){standUp();return}
if(!model||!nearSeat||emoting||jp||hop>0)return;
sit='bench';sitSeat=nearSeat;
player.position.set(sitSeat.x,0,sitSeat.z);faceY=sitSeat.face;player.rotation.y=sitSeat.face;
$('sit').textContent='STAND';
}
function standUp(){
if(sitSeat){player.position.x+=Math.sin(sitSeat.face)*.9;player.position.z+=Math.cos(sitSeat.face)*.9}
sit=null;sitSeat=null;$('sit').textContent='SIT';
}
// ---------- airport bench: one GLB, cloned, low-quality on purpose ----------
const CHAIR_FILE='airport_chair.glb',CHAIR_LEN=2.6,MAX_TEX=128,SEAT_FRAC=.5,CHAIR_YAW=0; // CHAIR_YAW=Math.PI if it faces backwards
function lowQ(root){root.traverse(o=>{if(!o.isMesh)return;o.castShadow=o.receiveShadow=true;
const old=o.material,arr=[].concat(old).map(m=>{
const n=new THREE.MeshLambertMaterial({color:m.color?m.color.clone():0xdddddd,flatShading:true,vertexColors:!!o.geometry.attributes.color});
if(m.map&&m.map.image){const im=m.map.image,c=document.createElement('canvas'),k=Math.min(1,MAX_TEX/Math.max(im.width||MAX_TEX,im.height||MAX_TEX));
c.width=Math.max(8,(im.width*k)|0);c.height=Math.max(8,(im.height*k)|0);c.getContext('2d').drawImage(im,0,0,c.width,c.height);
const t=new THREE.CanvasTexture(c);t.flipY=m.map.flipY;t.encoding=THREE.sRGBEncoding;t.magFilter=t.minFilter=THREE.NearestFilter;t.wrapS=m.map.wrapS;t.wrapT=m.map.wrapT;n.map=t}
if(m.transparent){n.transparent=true;n.opacity=m.opacity}
return n});
o.material=Array.isArray(old)?arr:arr[0]})}
function prepChair(gltf){
const raw=gltf.scene;lowQ(raw);
const inner=new THREE.Group(),root=new THREE.Group();inner.add(raw);root.add(inner);
const bb=new THREE.Box3(),sz=new THREE.Vector3();
root.updateMatrixWorld(true);bb.setFromObject(root).getSize(sz);
inner.rotation.y=CHAIR_YAW+(sz.z>sz.x*1.2?Math.PI/2:0); // long side along X, seats face +Z
root.updateMatrixWorld(true);bb.setFromObject(root).getSize(sz);
inner.scale.setScalar(CHAIR_LEN/sz.x);
root.updateMatrixWorld(true);bb.setFromObject(root);const c=bb.getCenter(new THREE.Vector3());bb.getSize(sz);
inner.position.set(-c.x,-bb.min.y,-c.z);
return {root,spec:{len:sz.x,depth:sz.z,seatH:sz.y*SEAT_FRAC}};
}
function fallbackBench(){
const g=new THREE.Group(),m=mat(0x8a94a6);
[[2.6,.1,.6,0,.45,0],[2.6,.5,.1,0,.8,-.3],[.08,.4,.5,-1.1,.2,0],[.08,.4,.5,1.1,.2,0]].forEach(a=>{
const b=new THREE.Mesh(new THREE.BoxGeometry(a[0],a[1],a[2]),m);b.position.set(a[3],a[4],a[5]);b.castShadow=true;g.add(b)});
return {root:g,spec:{len:2.6,depth:.6,seatH:.45}};
}
function placeBenches(o){
const {root,spec}=o,th=-Math.PI/2,c=Math.cos(th),sn=Math.sin(th); // benches face the glass wall (-X)
for(const [bx,bz] of benchSpots){
const b=root.clone(true);b.position.set(bx,0,bz);b.rotation.y=th;scene.add(b);
colliders.push({x:bx,z:bz,hx:spec.depth/2+.1,hz:spec.len/2+.1});
for(let i=0;i<4;i++){const lx=(i-1.5)*spec.len/4,lz=-spec.depth*.1;
seats.push({x:bx+lx*c+lz*sn,z:bz-lx*sn+lz*c,face:th,lift:Math.max(-.1,Math.min(.15,spec.seatH-.45))})}}
}
loader.load(CHAIR_FILE,g=>placeBenches(prepChair(g)),undefined,()=>placeBenches(fallbackBench()));
// ---------- loop ----------
const clock=new THREE.Clock(),SPEED={walk:1.9,run:4.2,sprint:7},v=new THREE.Vector3();let faceY=0,spd=0;
function collide(p){
p.x=Math.max(-W/2+.8,Math.min(W/2-.8,p.x));p.z=Math.max(-L+10,Math.min(7.5,p.z));
for(const c of colliders){const dx=p.x-c.x,dz=p.z-c.z,ox=c.hx+.35-Math.abs(dx),oz=c.hz+.35-Math.abs(dz);
if(ox>0&&oz>0){if(ox<oz)p.x+=Math.sign(dx)*ox;else p.z+=Math.sign(dz)*oz}}}
function tick(){
const dt=Math.min(clock.getDelta(),.05);
let ix=inp.x,iy=inp.y;const k=inp.keys;
if(k.KeyA||k.ArrowLeft)ix-=1;if(k.KeyD||k.ArrowRight)ix+=1;if(k.KeyW||k.ArrowUp)iy-=1;if(k.KeyS||k.ArrowDown)iy+=1;
let mag=Math.min(1,Math.hypot(ix,iy));if(mag<.12)mag=0;
const sprint=inp.sprint||k.ShiftLeft||k.ShiftRight;
let gait='idle';
if(sit&&(mag>.3||inp.jump))standUp();
if(emoting||sit){mag=0}
if(mag>0){gait=sprint?'sprint':(mag>.62?'run':'walk')}
// analog walk: tiny stick push = slow stroll, up to full walk at ~62%
let target=0;
if(mag){if(gait==='walk'){const t=Math.min(1,mag/.62);target=.25+(SPEED.walk-.25)*Math.pow(t,1.3)}else target=SPEED[gait]}
if(jp==='pre')target*=.4;
spd+=(target-spd)*Math.min(1,dt*9);
if(mag){
// camera-relative: joystick up = away from camera
const sy=Math.sin(yaw),cy=Math.cos(yaw);
v.set(ix*cy+iy*sy,0,-ix*sy+iy*cy).normalize();
faceY=Math.atan2(v.x,v.z);
player.position.addScaledVector(v,spd*dt);collide(player.position);
}
// smooth turn
let d=faceY-player.rotation.y;d=Math.atan2(Math.sin(d),Math.cos(d));player.rotation.y+=d*Math.min(1,dt*12);
// jump
if(inp.jump&&!jp&&hop===0&&!emoting&&!sit){jp='pre';jt=0} // 1) crouch with both legs
if(jp==='pre'){jt+=dt;if(jt>.2){jp='air';hopV=5.4;hop=.001}} // 2) launch
if(hop>0){hopV-=15*dt;hop+=hopV*dt;if(hop<=0){hop=0;hopV=0;jp='land';jt=0}} // 3) land
if(jp==='land'){jt+=dt;if(jt>.16)jp=null}
lift+=((sit&&sitSeat?sitSeat.lift:0)-lift)*Math.min(1,dt*8);
player.position.y=hop+lift;
if(inp.emote&&!emoting&&hop===0&&!sit&&!jp&&acts.emote){emoting=1;play('emote',.2)}
if(!emoting)play((sit||jp)?'idle':gait);
const wa=acts.walk;if(wa&&cur==='walk')wa.timeScale=(wa._b||1)*Math.max(.3,Math.min(1.15,spd/SPEED.walk));
if(mixer){restoreRig();mixer.update(dt)}
poseUpdate(dt);
// SIT button only exists near a bench seat
nearSeat=null;
if(!sit&&hop===0&&!jp&&!emoting){let bd=1.7;for(const q of seats){const d=Math.hypot(q.x-player.position.x,q.z-player.position.z);if(d<bd){bd=d;nearSeat=q}}}
const showSit=!!(nearSeat||sit);if(showSit!==sitShown){sitShown=showSit;$('sit').classList.toggle('show',showSit)}
// sun + camera follow
sun.position.set(player.position.x-18,22,player.position.z+10);sun.target.position.copy(player.position);
const dist=4.6-Math.min(1,spd/7)*-.8,cp=Math.cos(pitch);
const tx=player.position.x,ty=player.position.y+1.5,tz=player.position.z;
const want=new THREE.Vector3(tx+Math.sin(yaw)*cp*dist,ty+Math.sin(pitch)*dist+.3,tz+Math.cos(yaw)*cp*dist);
want.y=Math.max(.4,want.y);want.x=Math.max(-W/2+.4,Math.min(W/2-.4,want.x));want.z=Math.min(8.5,want.z);
camera.position.lerp(want,Math.min(1,dt*10));
camera.lookAt(tx,ty,tz);
camera.fov+=((60+Math.min(1,spd/7)*10)-camera.fov)*Math.min(1,dt*4);camera.updateProjectionMatrix();
renderer.render(scene,camera);requestAnimationFrame(tick);
}
tick();
</script></body></html>