W/S — тангаж вверх/вниз. A/D — поворот курса влево/вправо без крена и вращения вокруг продольной оси. Space — тяга мотора, Shift — снижение тяги. R — перезапуск. P — пауза.
`;
const el=id=>host.querySelector('#flight'+id),canvas=el('Canvas');let render;
try{render=renderer(canvas);}catch(e){el('Overlay').textContent=e.message;return ()=>{};}
// Flying-wing strike drone silhouette: swept wings, pointed nose and rear motor housing.
let droneMesh,canopyMesh,trunkMesh,shadowMesh,roofMesh;
droneMesh=render.makeMesh([
[0,.18,-3.35],[-4.35,0,.72],[4.35,0,.72],[-3.05,-.16,2.35],[3.05,-.16,2.35],[0,.12,2.85],
[0,-.18,-1.2],[-2.55,-.26,1.1],[2.55,-.26,1.1],[0,-.12,2.35]
],[
[0,1,2],[0,3,1],[0,2,4],[1,3,7],[1,7,6],[1,6,0],[2,0,6],[2,6,8],[2,8,4],[3,4,9],[3,9,7],[4,8,9],[7,9,6],[8,6,9]
]);
canopyMesh=render.makeMesh([[0,1.3,0],[-1,-.35,-1],[1,-.35,-1],[1,-.35,1],[-1,-.35,1],[0,-1.1,0]],[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[5,2,1],[5,3,2],[5,4,3],[5,1,4]]);
trunkMesh=render.makeMesh([[0,.9,0],[-.55,-.9,-.55],[.55,-.9,-.55],[.55,-.9,.55],[-.55,-.9,.55],[0,.9,0]],[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,3],[1,3,2]]);
shadowMesh=render.makeMesh([[0,.01,-1],[-.86,.01,-.5],[-.86,.01,.5],[0,.01,1],[.86,.01,.5],[.86,.01,-.5]],[[0,1,2],[0,2,3],[0,3,4],[0,4,5]]);
roofMesh=render.makeMesh([[-1,0,-1],[1,0,-1],[1,0,1],[-1,0,1],[0,1.15,-1],[0,1.15,1]],[[0,1,4],[1,2,5],[2,3,5],[3,0,4],[4,5,2],[4,2,1],[0,3,2],[0,2,1]]);
let progress=load(),selected=0,state='ready',paused=false,raf=0,last=0,acc=0,t=0,prep=0,battery=100,heat=0,yaw=0,pitch=0,throttle=0,camYaw=0,camPitch=.3,eye=[0,9,69],p=[0,3,52],v=[0,0,0],q=[0,0,0,1],omega=[0,0,0],input=[0,0,0],pointer=null,audio=null,osc=null,bodyOsc=null,pulseOsc=null,gain=null,bodyGain=null,pulseGain=null,sound=false,impactCooldown=0,impactMessage=0;
const keys=new Set(),events=new AbortController(),signal=events.signal;let boxes=[],target=[],trail=[],forest=[],clouds=[],buildings=[],hostileTargets=[],explosions=[];
function save(){try{localStorage.setItem('zke-flight-progress',JSON.stringify(progress));}catch{}}
function menu(){el('Mission').innerHTML=missions.map((m,i)=>``).join('');el('Upgrades').innerHTML=`Кредиты: ${progress.credits}`+['Батарея','Тяга','Стабилизация','Сенсоры'].map((n,i)=>``).join('');el('Upgrades').querySelectorAll('button').forEach(b=>b.onclick=()=>{const i=+b.dataset.upgrade,cost=200*(progress.upgrades[i]+1);if(progress.creditsbuildings.push({p:[x,0,z],type,s:[5+(i%2)*2,3+(i%3),4+(i%2)*2]}));
for(let i=0;i<18;i++){const x=(i%6)*18-46,z=Math.floor(i/6)*24-44;const s=missions[selected].biome===0?[2,10,2]:[7,5+(i%4)*3,8];if(Math.hypot(x-missions[selected].target[0],z-missions[selected].target[2])>12)boxes.push({p:[x,s[1]/2,z],s});}
buildings.forEach(building=>boxes.push({p:[building.p[0],building.s[1]*.5,building.p[2]],s:[building.s[0]*2,building.s[1],building.s[2]*2]}));
boxes.push({p:[-89,4,0],s:[2,8,178]},{p:[89,4,0],s:[2,8,178]},{p:[0,4,-89],s:[178,8,2]},{p:[0,4,89],s:[178,8,2]});
hostileTargets=[
{p:[-72,1,-18],type:'bunker',label:'Штабной модуль',destroyed:false},
{p:[58,1,-58],type:'vehicle',label:'Колонна транспорта',destroyed:false},
{p:[82,1,30],type:'artillery',label:'Артиллерийский макет',destroyed:false},
{p:[-34,1,68],type:'bunker',label:'Полевой штаб',destroyed:false}
];
explosions=[];impactCooldown=0;impactMessage=0;target=[...missions[selected].target];
}
function reset(){state='ready';paused=false;t=0;prep=0;battery=100;heat=0;yaw=0;pitch=0;throttle=.38;impactCooldown=0;impactMessage=0;camYaw=0;p=[0,12,62];v=[0,0,-6];q=[0,0,0,1];omega=[0,0,0];input=[0,0,0];eye=[0,18,79];trail=[];keys.clear();world();el('Brief').textContent=`${missions[selected].name}: свободно летите над полигоном и сталкивайтесь с отмеченными учебными объектами. Все объекты разбросаны по карте. Лимит ${missions[selected].time} с. Нажмите R чтобы перезапустить.`;el('Start').textContent='Начать полёт';el('Pause').textContent='Пауза';menu();}
function start(){reset();state='flight';canvas.focus();}
function finish(won,reason){state=won?'won':'lost';keys.clear();if(won){const score=Math.max(10,Math.round(missions[selected].reward+battery*2+(missions[selected].time-t)*4));const old=progress.best[selected]||0;if(!old)progress.credits+=missions[selected].reward;progress.best[selected]=Math.max(old,score);progress.unlocked=Math.max(progress.unlocked,Math.min(12,selected+2));save();onScore(score);menu();reason=`Миссия завершена · ${score} очков`;}el('Overlay').textContent=reason+' · R — повторить';el('Start').textContent='Повторить миссию';}
// Input: held keys, multitouch and gamepad use the same smoothed command vector.
const keymap=['KeyW','KeyA','KeyS','KeyD','Space','ShiftLeft','ShiftRight'];
document.addEventListener('keydown',e=>{if(!host.closest('dialog').open)return;if(keymap.includes(e.code)){e.preventDefault();e.stopImmediatePropagation();keys.add(e.code);}if(e.code==='KeyR'&&!e.repeat){e.preventDefault();start();}if(e.code==='KeyP'&&!e.repeat)togglePause();},{signal,capture:true});
document.addEventListener('keyup',e=>keys.delete(e.code),{signal});
function togglePause(){if(state!=='flight'&&state!=='prep')return;paused=!paused;keys.clear();el('Pause').textContent=paused?'Продолжить':'Пауза';}
window.addEventListener('blur',()=>{keys.clear();if(!paused&&(state==='flight'||state==='prep'))togglePause();},{signal});
document.addEventListener('visibilitychange',()=>{if(document.hidden&&!paused&&(state==='flight'||state==='prep'))togglePause();},{signal});
canvas.addEventListener('pointerdown',e=>{pointer=[e.pointerId,e.clientX,e.clientY];canvas.setPointerCapture(e.pointerId);},{signal});
canvas.addEventListener('pointermove',e=>{if(!pointer||pointer[0]!==e.pointerId)return;const s=Number(el('Sensitivity').value)*.001;camYaw-=(e.clientX-pointer[1])*s;camPitch=clamp(camPitch+(e.clientY-pointer[2])*s,-.3,1.1);pointer=[e.pointerId,e.clientX,e.clientY];},{signal});
canvas.addEventListener('pointerup',()=>pointer=null,{signal});canvas.addEventListener('pointercancel',()=>pointer=null,{signal});
host.querySelectorAll('[data-flight-key]').forEach(b=>{b.onpointerdown=e=>{e.preventDefault();b.setPointerCapture(e.pointerId);keys.add(b.dataset.flightKey);};b.onpointerup=b.onpointercancel=b.onlostpointercapture=()=>keys.delete(b.dataset.flightKey);});
el('Start').onclick=start;el('Pause').onclick=togglePause;el('Mission').onchange=()=>{selected=+el('Mission').value;reset();};
el('Sound').onclick=()=>{sound=!sound;if(sound&&!audio){audio=new (window.AudioContext||window.webkitAudioContext)();osc=audio.createOscillator();bodyOsc=audio.createOscillator();pulseOsc=audio.createOscillator();gain=audio.createGain();bodyGain=audio.createGain();pulseGain=audio.createGain();osc.type='sawtooth';bodyOsc.type='triangle';pulseOsc.type='square';osc.connect(gain);bodyOsc.connect(bodyGain);pulseOsc.connect(pulseGain);gain.connect(audio.destination);bodyGain.connect(audio.destination);pulseGain.connect(audio.destination);gain.gain.value=0;bodyGain.gain.value=0;pulseGain.gain.value=0;osc.start();bodyOsc.start();pulseOsc.start();}if(audio)audio.resume();el('Sound').textContent='Звук: '+(sound?'вкл.':'выкл.');};
el('Fullscreen').onclick=async()=>{const root=host.closest('dialog')||host.closest('.activity-modal')||host;if(!document.fullscreenElement){try{const request=root.requestFullscreen||root.webkitRequestFullscreen;if(!request)throw Error('unsupported');await request.call(root);el('Fullscreen').textContent='Выйти из полного экрана';}catch{el('Overlay').textContent='Полноэкранный режим недоступен в этом браузере';}}else{try{const exit=document.exitFullscreen||document.webkitExitFullscreen;if(exit)await exit.call(document);el('Fullscreen').textContent='Полный экран';}catch{}}};
document.addEventListener('fullscreenchange',()=>{if(!document.fullscreenElement)el('Fullscreen').textContent='Полный экран';},{signal});
// Collision: the drone bounces from terrain; touching a marked training object creates a cinematic impact.
function collision(){const r=CONFIG.radius;if(p[1]{if(p.some((n,i)=>Math.abs(n-b.p[i])>b.s[i]/2+r))return;const closest=p.map((n,i)=>clamp(n,b.p[i]-b.s[i]/2,b.p[i]+b.s[i]/2));let delta=sub(p,closest),distance=Math.hypot(...delta),normal,depth;if(distance>=r)return;if(distance>.0001){normal=scale(delta,1/distance);depth=r-distance;}else{const gaps=p.map((n,i)=>b.s[i]/2-Math.abs(n-b.p[i]));const a=gaps.indexOf(Math.min(...gaps));normal=[0,0,0];normal[a]=Math.sign(p[a]-b.p[a])||1;depth=gaps[a]+r;}p=add(p,scale(normal,depth+.001));const speed=dot(v,normal);if(speed<0)v=sub(v,scale(normal,speed));});
if(impactCooldown>0)return;hostileTargets.forEach(item=>{if(item.destroyed)return;const distance=Math.hypot(p[0]-item.p[0],p[1]-item.p[1],p[2]-item.p[2]);if(distance>3.4)return;item.destroyed=true;impactCooldown=2.4;impactMessage=2;spawnExplosion(item.p);spawnExplosion(p);p=[p[0],Math.max(8,p[1]+4),p[2]+7];v=[0,0,-5];throttle=.34;el('Overlay').textContent=`УДАР · ${item.label} уничтожен`});
}
function spawnExplosion(pos){
const particles=Array.from({length:22},(_,i)=>{const a=i*2.39996,b=(i%7)/7*Math.PI-.35,s=Math.sin(b),c=Math.cos(b);return {p:[...pos],v:[Math.cos(a)*c*(2.5+i%4),s*(2.2+i%3),Math.sin(a)*c*(2.5+i%4)],size:.16+(i%4)*.08,smoke:i%4===0};});
explosions.push({p:[...pos],life:1.35,max:1.35,particles});
}
function updateExplosions(dt){
explosions.forEach(ex=>{ex.life-=dt;ex.particles.forEach(part=>{part.p=add(part.p,scale(part.v,dt));part.v[1]-=3.2*dt;part.v=scale(part.v,.985);});});
explosions=explosions.filter(ex=>ex.life>0);
}
// Physics: rear motor thrust, gravity, drag and pitch/yaw stabilization. There is no roll axis.
function step(dt){
if(paused)return;if(state==='prep'){prep+=dt;if(prep>=2)state='flight';return;}if(state!=='flight')return;
t+=dt;impactCooldown=Math.max(0,impactCooldown-dt);impactMessage=Math.max(0,impactMessage-dt);
const m=missions[selected],pad=Array.from(navigator.getGamepads?.()||[]).find(Boolean),dead=+el('Deadzone').value/100,stick=n=>Math.abs(n||0)n+(clamp(desired[i],-1,1)-n)*(1-Math.exp(-dt*7)));if(pad){camYaw-=stick(pad.axes[2])*dt*2;camPitch=clamp(camPitch+stick(pad.axes[3])*dt,-.3,1.1);}
yaw+=input[0]*dt*(.95+progress.upgrades[2]*.08);
const angle=modes[el('Mode').value].angle,desiredQ=qm(axis([0,1,0],yaw),axis([1,0,0],-input[1]*angle)),error=qm(desiredQ,[-q[0],-q[1],-q[2],q[3]]);
omega[2]=0;omega[0]=clamp(omega[0]+(error[0]*(16+progress.upgrades[2]*3)-omega[0]*6)*dt/CONFIG.inertia[0],-CONFIG.maxOmega,CONFIG.maxOmega);omega[1]=clamp(omega[1]+(error[1]*(16+progress.upgrades[2]*3)-omega[1]*6)*dt/CONFIG.inertia[1],-CONFIG.maxOmega,CONFIG.maxOmega);const dq=qm([...omega,0],q);q=norm(q.map((n,i)=>n+dq[i]*dt*.5));
throttle=clamp(throttle+input[2]*dt*.8,0,1);if(Math.abs(input[2])<.05)throttle=Math.max(0,throttle-dt*.025);
const up=rotate(q,[0,1,0]),forward=rotate(q,[0,0,-1]),speed=Math.hypot(...v),thrust=throttle*(18+progress.upgrades[1]*3)*(heat>90?.65:1),wind=[Math.sin(t*.7+p[2]*.03)*m.wind,0,Math.cos(t*.5)*m.wind],relative=sub(v,wind),drag=scale(relative,-CONFIG.drag*(1+speed*.045));
const force=add(add(scale(forward,thrust),scale(up,thrust*.58)),add([0,-CONFIG.mass*CONFIG.gravity,0],drag));v=add(v,scale(force,dt/CONFIG.mass));p=add(p,scale(v,dt));collision();heat=clamp(heat+(thrust>15?12:-9)*dt,0,100);battery-=dt*(.05+throttle*.18)/(1+progress.upgrades[0]*.22);
if(Math.abs(p[0])>150||Math.abs(p[2])>150||p[1]>120)return finish(false,'Граница полигона');if(battery<=0||t>m.time)return finish(false,battery<=0?'Батарея разряжена':'Время истекло');
if(hostileTargets.length&&hostileTargets.every(item=>item.destroyed))finish(true,'Все учебные объекты разрушены');
updateExplosions(dt);
}
// UI and Render: all mission timers pause when focus is lost; bounded particles/LOD.
function draw(dt){
const m=missions[selected],behind=[Math.sin(camYaw)*14,6+Math.sin(camPitch)*10,Math.cos(camYaw)*14],camera=el('Camera').value;
const desiredEye=camera==='cockpit'?add(p,[0,1,0]):add(p,scale(behind,camera==='free'?2:1));eye=add(eye,scale(sub(desiredEye,eye),1-Math.exp(-dt*7)));
const look=camera==='cockpit'?add(eye,[-Math.sin(camYaw)*20,-Math.sin(camPitch)*15,-Math.cos(camYaw)*20]):add(p,[0,1,0]);
render.begin(eye,look,false);
const sun=[p[0]-55,62,p[2]-105];render.mesh(canopyMesh,sun,[9,9,9],[1,.72,.18],undefined,1);for(let i=0;i<8;i++){const a=i*Math.PI/4;render.box([sun[0]+Math.cos(a)*12,sun[1],sun[2]+Math.sin(a)*12],[.55,.25,5],[1,.62,.12],axis([0,1,0],a),.55);}
render.box([0,-1,0],[182,2,182],[.08,.40,.13]);
// Mown strips and a stream give the landscape visible structure from altitude.
for(let z=-80;z<=80;z+=10)render.box([0,.03,z],[175,.04,.13],[.22,.58,.18]);
render.box([18,.02,-2],[24,.045,7],[.08,.28,.34]);
boxes.forEach(b=>{if(Math.hypot(...sub(b.p,p))<110)render.box(b.p,b.s,[.28,.36,.33]);});
forest.forEach(tree=>{if(Math.hypot(tree.p[0]-p[0],tree.p[2]-p[2])>145)return;const leaf=tree.variant===0?[.10,.38,.14]:tree.variant===1?[.16,.48,.18]:[.08,.31,.22];render.mesh(shadowMesh,[tree.p[0],.02,tree.p[2]],[tree.r*1.8,1,tree.r*1.15],[.035,.09,.045]);render.mesh(trunkMesh,[tree.p[0],tree.h*.42,tree.p[2]],[tree.r*.32,tree.h*.48,tree.r*.32],[.22,.13,.07]);render.mesh(canopyMesh,[tree.p[0],tree.h*.78,tree.p[2]],[tree.r*1.55,tree.h*.58,tree.r*1.55],leaf,undefined,.05);render.mesh(canopyMesh,[tree.p[0]-tree.r*.52,tree.h*.92,tree.p[2]+tree.r*.18],[tree.r*1.08,tree.h*.36,tree.r*1.08],leaf,undefined,.04);});
buildings.forEach(building=>{if(Math.hypot(building.p[0]-p[0],building.p[2]-p[2])>180)return;const roof=building.type==='barn'?[.50,.12,.06]:building.type==='farm'?[.18,.28,.12]:[.42,.20,.12];render.mesh(shadowMesh,[building.p[0],.025,building.p[2]],[building.s[0]*1.15,1,building.s[2]*1.15],[.04,.08,.04]);render.box([building.p[0],building.s[1]*.5,building.p[2]],[building.s[0]*2,building.s[1],building.s[2]*2],building.type==='farm'?[.62,.46,.24]:[.48,.34,.22]);render.mesh(roofMesh,[building.p[0],building.s[1],building.p[2]],[building.s[0]*1.12,building.s[1]*.85,building.s[2]*1.12],roof);if(building.type==='farm')render.box([building.p[0]+building.s[0]*.9,.7,building.p[2]],[1.2,1.4,1.2],[.28,.18,.08]);});
clouds.forEach(cloud=>{if(Math.hypot(cloud.p[0]-p[0],cloud.p[2]-p[2])<150)render.box(cloud.p,cloud.s,[.72,.82,.78],undefined,.04);});
hostileTargets.forEach(item=>{if(item.destroyed||Math.hypot(item.p[0]-p[0],item.p[2]-p[2])>180)return;const c=item.type==='vehicle'?[.72,.26,.08]:item.type==='artillery'?[.86,.34,.06]:[.72,.18,.08];if(item.type==='vehicle'){render.box(item.p,[3.8,.85,1.8],c,undefined,.12);render.box(add(item.p,[0,.62,0]),[1.45,.5,1.2],[.38,.12,.05],undefined,.12);}else if(item.type==='artillery'){render.box(item.p,[2.1,.7,2.1],c,undefined,.12);render.box(add(item.p,[0,1.1,-.2]),[.24,1.5,.24],[.18,.08,.03],axis([1,0,0],-.45),.1);}else{render.box(add(item.p,[0,.75,0]),[4.2,1.5,3],c,undefined,.12);render.box(add(item.p,[0,1.58,-.5]),[2.5,.38,1.7],[.4,.1,.04],undefined,.12);}render.box(add(item.p,[0,3.1,0]),[.18,3.8,.18],[1,.18,.03],undefined,.8);render.box(add(item.p,[0,5.05,0]),[.58,.58,.58],[1,.3,.03],axis([0,1,0],t),1);for(let i=0;i<8;i++){const a=i*Math.PI/4+t*.7;render.box(add(item.p,[Math.cos(a)*3.2,.18,Math.sin(a)*3.2]),[.75,.08,.18],[1,.25,.03],axis([0,1,0],-a),.7);}});
if(camera!=='cockpit'){render.mesh(droneMesh,p,[1,1,1],[.65,.73,.68],q,.08);const exhaust=add(p,rotate(q,[0,.1,2.65])),propQ=qm(q,axis([0,0,1],t*34));render.box(exhaust,[.42,.28,.8],[.32,.65,.72],q,.65);render.box(add(p,rotate(q,[0,.2,2.9])),[.22,.18,.55],[.95,.42,.12],q,.9);render.box(exhaust,[2.2,.08,.12],[.6,.7,.66],propQ,.25);render.box(exhaust,[.08,2.2,.12],[.6,.7,.66],propQ,.25);}
explosions.forEach(ex=>{const a=ex.life/ex.max;ex.particles.forEach(part=>render.box(part.p,[part.size*(1.8-a),part.size*(1.8-a),part.size*(1.8-a)],part.smoke?[.22,.2,.16]:[1,.22+.65*a,.04],undefined,part.smoke?.05:.8*a));render.box(ex.p,[2.4*(1-a),2.4*(1-a),2.4*(1-a)],[1,.22,.03],undefined,.8*a);});
if(state==='flight'&&!paused){trail.push([...p]);if(trail.length>28)trail.shift();}trail.forEach((pos,i)=>{if(i%3===0)render.box(pos,[.1,.1,.1],[.22,.55,.61],undefined,.1);});
const speedNow=Math.hypot(...v),modeName=el('Mode').value.toUpperCase(),destroyed=hostileTargets.filter(item=>item.destroyed).length;el('Capture').max=hostileTargets.length;el('Capture').value=destroyed;el('Telemetry').textContent=`${t.toFixed(1)} / ${m.time} с · высота ${p[1].toFixed(1)} · скорость ${speedNow.toFixed(1)} · тяга ${(throttle*100).toFixed(0)}% · батарея ${Math.max(0,battery).toFixed(0)}% · нагрев ${heat.toFixed(0)}% · учебные цели ${destroyed}/${hostileTargets.length}`;
el('Coords').textContent=`X ${p[0].toFixed(0).padStart(3,'0')} · Z ${p[2].toFixed(0).padStart(3,'0')}`;el('Alt').textContent=p[1].toFixed(0).padStart(3,'0');el('Speed').textContent=speedNow.toFixed(0).padStart(3,'0');el('Battery').textContent=Math.max(0,battery).toFixed(0);el('Heat').textContent=heat.toFixed(0);el('ModeHud').textContent=`MODE ${modeName}`;el('TargetHud').textContent=`TARGET ${hostileTargets.filter(x=>!x.destroyed).length?'TRAINING':'CLEAR'}`;
if(!['won','lost'].includes(state)&&impactMessage<=0)el('Overlay').textContent=paused?'Пауза':`Свободный полёт · учебные объекты: ${destroyed}/${hostileTargets.length}`;
if(gain){const active=sound&&!paused&&state==='flight',rpm=throttle*190+speedNow*3;gain.gain.setTargetAtTime(active?.018:0,audio.currentTime,.08);bodyGain.gain.setTargetAtTime(active?.011:0,audio.currentTime,.08);pulseGain.gain.setTargetAtTime(active?.004:0,audio.currentTime,.08);osc.frequency.setTargetAtTime(72+rpm,audio.currentTime,.08);bodyOsc.frequency.setTargetAtTime(38+rpm*.28,audio.currentTime,.08);pulseOsc.frequency.setTargetAtTime(145+rpm*1.85,audio.currentTime,.08);}
}
function frame(now){const dt=last?Math.min(.05,(now-last)/1000):1/60;last=now;acc+=dt;while(acc>=CONFIG.dt){step(CONFIG.dt);acc-=CONFIG.dt;}draw(dt);raf=requestAnimationFrame(frame);}
start();raf=requestAnimationFrame(frame);
return ()=>{cancelAnimationFrame(raf);events.abort();keys.clear();render.dispose();if(audio){osc?.stop();bodyOsc?.stop();pulseOsc?.stop();audio.close();}};
}
return {mount,missions};
})();