Skip to content

Instantly share code, notes, and snippets.

@senko
Created November 9, 2026 21:44
Show Gist options
  • Select an option

  • Save senko/afbc29324f082fdb6c3dbf35540b08e6 to your computer and use it in GitHub Desktop.

Select an option

Save senko/afbc29324f082fdb6c3dbf35540b08e6 to your computer and use it in GitHub Desktop.
Flying simulator by Fable 5.2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Canvas &amp; Wire — biplane dogfight</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root { --cream:#efe6cf; --ink:#11161b; --amber:#e8b04a; --red:#d9482f; }
html, body { margin:0; height:100%; overflow:hidden; background:var(--ink); color:var(--cream);
font-family:"Courier New", ui-monospace, Menlo, monospace; }
canvas#gl, canvas#hud { position:fixed; inset:0; width:100%; height:100%; display:block; }
canvas#hud { pointer-events:none; }
#vignette { position:fixed; inset:0; pointer-events:none; opacity:0;
background:radial-gradient(ellipse at center, rgba(180,20,10,0) 45%, rgba(180,20,10,.75) 100%); }
#msg { position:fixed; top:14%; left:0; right:0; text-align:center; pointer-events:none;
font:700 22px Georgia, "Times New Roman", serif; letter-spacing:.14em; text-transform:uppercase;
text-shadow:0 2px 6px rgba(0,0,0,.75); opacity:0; transition:opacity .4s; }
#msg.on { opacity:1; }
#msg small { display:block; margin-top:6px; font:400 14px "Courier New", monospace; letter-spacing:.05em; text-transform:none; }
.overlay { position:fixed; inset:0; display:flex; align-items:center; justify-content:center; text-align:center;
background:linear-gradient(180deg, rgba(10,14,18,.25), rgba(10,14,18,.7)); }
.hidden { display:none !important; }
.card { max-width:660px; padding:26px 34px 22px; background:rgba(14,18,22,.74); border:1px solid rgba(239,230,207,.28);
box-shadow:0 20px 60px rgba(0,0,0,.5); }
h1 { margin:0; font:700 46px Georgia, "Times New Roman", serif; letter-spacing:.2em; text-transform:uppercase; }
h2 { margin:0 0 10px; font:700 32px Georgia, serif; letter-spacing:.2em; text-transform:uppercase; }
.sub { margin:6px 0 20px; color:var(--amber); letter-spacing:.3em; text-transform:uppercase; font-size:13px; }
.keys { display:grid; grid-template-columns:auto auto; gap:6px 18px; justify-content:center; text-align:left; font-size:14px; margin:0 0 18px; }
.keys div:nth-child(odd) { text-align:right; }
kbd { display:inline-block; min-width:14px; padding:1px 6px; margin:0 1px; text-align:center; border:1px solid rgba(239,230,207,.55);
border-bottom-width:2px; border-radius:3px; font:700 12px "Courier New", monospace; background:rgba(239,230,207,.08); }
.go { display:inline-block; margin-top:4px; padding:10px 22px; cursor:pointer; color:var(--ink); background:var(--amber);
border:0; font:700 15px "Courier New", monospace; letter-spacing:.14em; text-transform:uppercase; }
.go:hover { background:#f4c468; }
.note { margin-top:12px; font-size:12px; opacity:.7; }
#err { color:#ff9a86; }
</style>
</head>
<body>
<canvas id="gl"></canvas>
<canvas id="hud"></canvas>
<div id="vignette"></div>
<div id="msg"></div>
<div id="menu" class="overlay">
<div class="card">
<h1>Canvas &amp; Wire</h1>
<div class="sub">a biplane dogfight</div>
<div class="keys">
<div><kbd>S</kbd>/<kbd>&darr;</kbd> &nbsp;<kbd>W</kbd>/<kbd>&uarr;</kbd></div><div>stick back (nose up) / forward</div>
<div><kbd>A</kbd>/<kbd>&larr;</kbd> &nbsp;<kbd>D</kbd>/<kbd>&rarr;</kbd></div><div>roll left / right</div>
<div><kbd>Q</kbd> <kbd>E</kbd></div><div>rudder left / right</div>
<div><kbd>R</kbd> <kbd>F</kbd></div><div>throttle up / down</div>
<div><kbd>Space</kbd> / mouse</div><div>fire guns</div>
<div><kbd>C</kbd> <kbd>I</kbd> <kbd>M</kbd> <kbd>P</kbd></div><div>camera / invert pitch / mute / pause</div>
</div>
<button class="go" id="startBtn">Take off &mdash; Enter</button>
<div class="note" id="note">Roll, then pull, to turn. Put the gunsight on the small lead circle to hit a turning target.</div>
<div class="note" id="err"></div>
</div>
</div>
<div id="over" class="overlay hidden">
<div class="card">
<h2 id="overTitle">Shot down</h2>
<div id="overStats" style="margin:0 0 16px;font-size:15px;line-height:1.7"></div>
<button class="go" id="againBtn">Fly again &mdash; Enter</button>
</div>
</div>
<div id="pause" class="overlay hidden"><div class="card"><h2>Paused</h2><div>Press <kbd>P</kbd> to resume</div></div></div>
<script>
// Shows a message if the module below fails to load (no network / CDN blocked).
window.__booted = false;
setTimeout(function () {
if (!window.__booted) document.getElementById('err').textContent =
'three.js did not load from the CDN. Check the network connection and reload.';
}, 8000);
</script>
<script type="importmap">
{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js" } }
</script>
<script type="module">
import * as THREE from 'three';
// =====================================================================================
// Utilities
// =====================================================================================
const V3 = THREE.Vector3, Q4 = THREE.Quaternion;
const clamp = (x, a, b) => x < a ? a : x > b ? b : x;
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
const wrapPi = a => { a = (a + Math.PI) % (2 * Math.PI); if (a < 0) a += 2 * Math.PI; return a - Math.PI; };
const rand = (a = 1, b) => b === undefined ? Math.random() * a : a + Math.random() * (b - a);
const $ = id => document.getElementById(id);
const params = new URLSearchParams(location.search);
const SEED = parseInt(params.get('seed')) || 1917;
function mulberry32(a) {
return () => { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
}
const srnd = mulberry32(SEED); // seeded: world generation only
// --- 2D gradient noise -----------------------------------------------------------------
const perm = new Uint8Array(512);
{ const p = [...Array(256).keys()];
for (let i = 255; i > 0; i--) { const j = (srnd() * (i + 1)) | 0; [p[i], p[j]] = [p[j], p[i]]; }
for (let i = 0; i < 512; i++) perm[i] = p[i & 255]; }
const GX = [1, -1, 0, 0, .7071, -.7071, .7071, -.7071], GY = [0, 0, 1, -1, .7071, .7071, -.7071, -.7071];
function noise2(x, y) {
const X = Math.floor(x), Y = Math.floor(y); x -= X; y -= Y;
const xi = X & 255, yi = Y & 255;
const u = x * x * x * (x * (x * 6 - 15) + 10), v = y * y * y * (y * (y * 6 - 15) + 10);
const a = perm[perm[xi] + yi] & 7, b = perm[perm[xi + 1] + yi] & 7,
c = perm[perm[xi] + yi + 1] & 7, d = perm[perm[xi + 1] + yi + 1] & 7;
const n00 = GX[a] * x + GY[a] * y, n10 = GX[b] * (x - 1) + GY[b] * y,
n01 = GX[c] * x + GY[c] * (y - 1), n11 = GX[d] * (x - 1) + GY[d] * (y - 1);
return lerp(lerp(n00, n10, u), lerp(n01, n11, u), v) * 1.4;
}
function fbm(x, y, oct) {
let s = 0, a = 1, n = 0;
for (let i = 0; i < oct; i++) { s += a * noise2(x, y); n += a; a *= 0.5; x = x * 2 + 17.3; y = y * 2 - 9.1; }
return s / n;
}
function ridged(x, y, oct) {
let s = 0, a = 1, n = 0;
for (let i = 0; i < oct; i++) { const r = 1 - Math.abs(noise2(x, y)); s += a * r * r; n += a; a *= 0.5; x = x * 2 + 5.7; y = y * 2 + 3.1; }
return s / n;
}
const hash2 = (i, j) => perm[(perm[i & 255] + j) & 255] / 256; // [0, 1)
// =====================================================================================
// Renderer, scene, sky, lights
// =====================================================================================
const glCanvas = $('gl'), hudCanvas = $('hud'), g2 = hudCanvas.getContext('2d');
const renderer = new THREE.WebGLRenderer({ canvas: glCanvas, antialias: true, powerPreference: 'high-performance' });
const scene = new THREE.Scene();
const HORIZON = 0xd3dcdc;
scene.fog = new THREE.Fog(HORIZON, 500, 10500);
const camera = new THREE.PerspectiveCamera(58, 1, 0.4, 24000);
const SUN = new V3(0.52, 0.62, 0.42).normalize();
scene.add(new THREE.HemisphereLight(0xcfe2f5, 0x7a7355, 1.5));
const sunLight = new THREE.DirectionalLight(0xfff1d6, 2.6);
sunLight.position.copy(SUN);
scene.add(sunLight);
const srgb = hex => new V3((hex >> 16 & 255) / 255, (hex >> 8 & 255) / 255, (hex & 255) / 255);
const sky = new THREE.Mesh(
new THREE.SphereGeometry(15000, 24, 12),
new THREE.ShaderMaterial({
side: THREE.BackSide, depthWrite: false, depthTest: false, fog: false,
uniforms: { uTop: { value: srgb(0x3f79b8) }, uHor: { value: srgb(HORIZON) }, uSun: { value: srgb(0xfff0c8) }, uSunDir: { value: SUN } },
vertexShader: `varying vec3 vDir; void main(){ vDir = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
fragmentShader: `uniform vec3 uTop, uHor, uSun, uSunDir; varying vec3 vDir;
void main(){ vec3 d = normalize(vDir); float h = max(d.y, 0.0);
vec3 c = mix(uHor, uTop, pow(h, 0.5));
float s = max(dot(d, uSunDir), 0.0);
c += uSun * (pow(s, 600.0) * 2.0 + pow(s, 14.0) * 0.22);
gl_FragColor = vec4(c, 1.0); }`
}));
sky.renderOrder = -10; sky.frustumCulled = false;
scene.add(sky);
// =====================================================================================
// Terrain: island height field, per-face colours, water, trees, villages, clouds
// =====================================================================================
const WORLD = 12000, SEG = 300, CELL = WORLD / SEG, HALF = WORLD / 2, SEA_FLOOR = -90;
const H = new Float32Array((SEG + 1) * (SEG + 1));
function terrainFn(x, z) {
const d = Math.hypot(x, z) / HALF;
const fall = smooth(0.52, 0.98, d);
const base = fbm(x / 2400, z / 2400, 5);
const mm = smooth(0.0, 0.42, fbm(x / 3600 + 31.7, z / 3600 - 12.3, 3));
const rid = ridged(x / 1700 + 7.1, z / 1700 + 3.3, 4);
let h = 28 + base * 300 + mm * rid * rid * 620;
h = h * (1 - fall) + SEA_FLOOR * fall;
if (h > 0 && h < 80) h = 80 * Math.pow(h / 80, 1.6); // flatten the lowlands
return h;
}
for (let iz = 0; iz <= SEG; iz++) for (let ix = 0; ix <= SEG; ix++)
H[iz * (SEG + 1) + ix] = terrainFn(-HALF + ix * CELL, -HALF + iz * CELL);
// Height lookup that matches the rendered triangles exactly.
function groundHeight(x, z) {
const fx = (x + HALF) / CELL, fz = (z + HALF) / CELL;
if (!(fx >= 0 && fz >= 0 && fx < SEG && fz < SEG)) return SEA_FLOOR;
const ix = fx | 0, iz = fz | 0, tx = fx - ix, tz = fz - iz, i = iz * (SEG + 1) + ix;
const a = H[i], b = H[i + 1], c = H[i + SEG + 1], d = H[i + SEG + 2];
return tx + tz <= 1 ? a + (b - a) * tx + (c - a) * tz : d + (c - d) * (1 - tx) + (b - d) * (1 - tz);
}
function groundNormal(x, z, out) {
const e = 12;
const sx = (groundHeight(x + e, z) - groundHeight(x - e, z)) / (2 * e);
const sz = (groundHeight(x, z + e) - groundHeight(x, z - e)) / (2 * e);
return out.set(-sx, 1, -sz).normalize();
}
const lin = hex => new THREE.Color(hex); // hex (sRGB) -> linear working colour
const PAL = {
deep: lin(0x1d4a63), shallow: lin(0xbfc48e), sand: lin(0xd9cc98),
grassA: lin(0x6f9440), grassB: lin(0x86a04a), forest: lin(0x3f6a34), alpine: lin(0x7c8455),
rockA: lin(0x7d766b), rockB: lin(0x928a7c), snow: lin(0xf2f4f6),
fields: [lin(0xcdb65c), lin(0x7fa23f), lin(0x56803a), lin(0x96704a), lin(0xb7c26a), lin(0xa98f52)]
};
const forestNoise = (x, z) => fbm(x / 1100 + 50, z / 1100 + 50, 3);
const isField = (h, ny, f) => h > 4 && h < 110 && ny > 0.985 && f < 0.06;
{
const nTri = SEG * SEG * 2;
const pos = new Float32Array(nTri * 9), nor = new Float32Array(nTri * 9), col = new Float32Array(nTri * 9);
const c = new THREE.Color(), e1 = new V3(), e2 = new V3(), n1 = new V3(), n2 = new V3();
let o = 0;
const tri = (x0, y0, z0, x1, y1, z1, x2, y2, z2, n, cc) => {
pos[o] = x0; pos[o + 1] = y0; pos[o + 2] = z0; pos[o + 3] = x1; pos[o + 4] = y1; pos[o + 5] = z1; pos[o + 6] = x2; pos[o + 7] = y2; pos[o + 8] = z2;
for (let k = 0; k < 9; k += 3) { nor[o + k] = n.x; nor[o + k + 1] = n.y; nor[o + k + 2] = n.z; col[o + k] = cc.r; col[o + k + 1] = cc.g; col[o + k + 2] = cc.b; }
o += 9;
};
const shade = (h, ny, f, field, fid, jit) => {
if (h < 0) c.copy(PAL.shallow).lerp(PAL.deep, smooth(2, -38, h));
else if (h < 4) c.copy(PAL.sand);
else if (ny < 0.8) c.copy(PAL.rockA).lerp(PAL.rockB, jit);
else if (h > 455) c.copy(PAL.snow);
else if (h > 330) c.copy(PAL.rockB).lerp(PAL.rockA, jit);
else if (field) c.copy(PAL.fields[fid]);
else if (f > 0.1) c.copy(PAL.forest).lerp(PAL.alpine, smooth(200, 330, h));
else c.copy(PAL.grassA).lerp(PAL.grassB, jit).lerp(PAL.alpine, smooth(180, 330, h));
c.multiplyScalar(0.94 + jit * 0.12);
return c;
};
for (let iz = 0; iz < SEG; iz++) for (let ix = 0; ix < SEG; ix++) {
const x0 = -HALF + ix * CELL, z0 = -HALF + iz * CELL, x1 = x0 + CELL, z1 = z0 + CELL, i = iz * (SEG + 1) + ix;
const a = H[i], b = H[i + 1], cH = H[i + SEG + 1], d = H[i + SEG + 2];
n1.crossVectors(e1.set(0, cH - a, CELL), e2.set(CELL, b - a, 0)).normalize();
n2.crossVectors(e1.set(-CELL, cH - b, CELL), e2.set(0, d - b, CELL)).normalize();
const cx = x0 + CELL / 2, cz = z0 + CELL / 2, hq = (a + b + cH + d) / 4;
const f = forestNoise(cx, cz);
const field = isField(Math.min(a, b, cH, d), Math.min(n1.y, n2.y), f) && isField(hq, 1, f);
const fx = Math.floor(cx / 160), fz = Math.floor(cz / 240 + (fx & 1) * 0.5);
const fid = (hash2(fx, fz) * PAL.fields.length) | 0;
const j1 = hash2(ix * 3 + 1, iz * 5 + 2), j2 = hash2(ix * 7 + 3, iz * 3 + 5);
tri(x0, a, z0, x0, cH, z1, x1, b, z0, n1, shade((a + cH + b) / 3, n1.y, f, field, fid, field ? 0.5 : j1));
tri(x1, b, z0, x0, cH, z1, x1, d, z1, n2, shade((b + cH + d) / 3, n2.y, f, field, fid, field ? 0.5 : j2));
}
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
geo.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
const terrain = new THREE.Mesh(geo, new THREE.MeshLambertMaterial({ vertexColors: true }));
terrain.frustumCulled = false;
scene.add(terrain);
}
const water = new THREE.Mesh(
new THREE.PlaneGeometry(48000, 48000).rotateX(-Math.PI / 2),
new THREE.MeshPhongMaterial({ color: 0x2b6c8c, transparent: true, opacity: 0.84, shininess: 90, specular: 0x8a8a7a }));
water.renderOrder = 1;
scene.add(water);
// --- trees ----------------------------------------------------------------------------
{
const MAXT = 11000, tmpN = new V3(), m = new THREE.Matrix4(), q = new Q4(), s = new V3(), p = new V3(), yAxis = new V3(0, 1, 0);
const geo = new THREE.ConeGeometry(1, 3, 5, 1, true).translate(0, 1.5, 0);
const trees = new THREE.InstancedMesh(geo, new THREE.MeshLambertMaterial({ flatShading: true }), MAXT);
const tc = new THREE.Color(), tA = lin(0x2c5a2a), tB = lin(0x4a7a36);
let n = 0;
for (let tries = 0; tries < 90000 && n < MAXT; tries++) {
const x = (srnd() - 0.5) * WORLD * 0.95, z = (srnd() - 0.5) * WORLD * 0.95, h = groundHeight(x, z);
if (h < 5 || h > 300) continue;
const ny = groundNormal(x, z, tmpN).y;
if (ny < 0.82) continue;
const f = forestNoise(x, z);
if (isField(h, ny, f)) { if (srnd() > 0.012) continue; }
else if (f < 0.1 && srnd() > 0.07) continue;
const sc = 3.2 + srnd() * 2.2;
m.compose(p.set(x, h - 0.3, z), q.setFromAxisAngle(yAxis, srnd() * 6.28), s.set(sc, sc * (0.9 + srnd() * 0.5), sc));
trees.setMatrixAt(n, m);
trees.setColorAt(n, tc.copy(tA).lerp(tB, srnd()));
n++;
}
trees.count = n; trees.frustumCulled = false;
scene.add(trees);
}
// --- villages -------------------------------------------------------------------------
{
const spots = [], tmpN = new V3();
for (let tries = 0; tries < 6000 && spots.length < 10; tries++) {
const x = (srnd() - 0.5) * WORLD * 0.8, z = (srnd() - 0.5) * WORLD * 0.8, h = groundHeight(x, z);
if (!isField(h, groundNormal(x, z, tmpN).y, forestNoise(x, z))) continue;
if (spots.some(sp => Math.hypot(sp.x - x, sp.z - z) < 1100)) continue;
spots.push({ x, z });
}
const MAXH = spots.length * 24 + 1;
const walls = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0), new THREE.MeshLambertMaterial({ flatShading: true }), MAXH);
const roofs = new THREE.InstancedMesh(new THREE.ConeGeometry(0.75, 1, 4).rotateY(Math.PI / 4).translate(0, 0.5, 0), new THREE.MeshLambertMaterial({ flatShading: true }), MAXH);
const m = new THREE.Matrix4(), q = new Q4(), s = new V3(), p = new V3(), yAxis = new V3(0, 1, 0), c = new THREE.Color();
const wallC = [lin(0xe2d6b8), lin(0xcfc3a4), lin(0xd9c4a0)], roofC = [lin(0xa5503a), lin(0x8a4634), lin(0x6e5a4c)];
let n = 0;
const house = (x, z, w, hgt, d, roofH, rot, wc, rc) => {
const y = groundHeight(x, z) - 0.4;
q.setFromAxisAngle(yAxis, rot);
walls.setMatrixAt(n, m.compose(p.set(x, y, z), q, s.set(w, hgt, d))); walls.setColorAt(n, wc);
roofs.setMatrixAt(n, m.compose(p.set(x, y + hgt, z), q, s.set(w * 1.08, roofH, d * 1.08))); roofs.setColorAt(n, rc);
n++;
};
for (const sp of spots) {
house(sp.x, sp.z, 6, 20, 6, 9, 0.3, c.copy(wallC[1]).clone(), roofC[2]); // church tower
const count = 10 + (srnd() * 12 | 0);
for (let i = 0; i < count; i++) {
const a = srnd() * 6.28, r = 25 + srnd() * 130, x = sp.x + Math.cos(a) * r, z = sp.z + Math.sin(a) * r;
if (groundHeight(x, z) < 3) continue;
house(x, z, 8 + srnd() * 4, 4.5 + srnd() * 2, 9 + srnd() * 5, 3.5, srnd() * 3.14, wallC[srnd() * 3 | 0], roofC[srnd() * 3 | 0]);
}
}
walls.count = roofs.count = n; walls.frustumCulled = roofs.frustumCulled = false;
scene.add(walls, roofs);
}
// --- clouds ---------------------------------------------------------------------------
{
const MAXC = 420;
const clouds = new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1, 1),
new THREE.MeshLambertMaterial({ color: 0xffffff, flatShading: true, emissive: 0x556070 }), MAXC);
const m = new THREE.Matrix4(), q = new Q4(), s = new V3(), p = new V3();
let n = 0;
for (let i = 0; i < 46 && n < MAXC - 10; i++) {
const a = srnd() * 6.28, r = Math.sqrt(srnd()) * 9000;
const cx = Math.cos(a) * r, cz = Math.sin(a) * r, cy = 620 + srnd() * 520, puffs = 5 + (srnd() * 5 | 0), size = 60 + srnd() * 70;
for (let k = 0; k < puffs; k++) {
const rr = size * (0.55 + srnd() * 0.6);
p.set(cx + (srnd() - 0.5) * size * 3.2, cy + (srnd() - 0.3) * size * 0.5, cz + (srnd() - 0.5) * size * 2.2);
clouds.setMatrixAt(n++, m.compose(p, q.set(srnd(), srnd(), srnd(), srnd()).normalize(), s.set(rr, rr * 0.62, rr)));
}
}
clouds.count = n; clouds.frustumCulled = false;
scene.add(clouds);
}
// =====================================================================================
// Aircraft model (merged primitives, vertex colours; one draw call per aircraft)
// =====================================================================================
function mergeParts(parts) {
let n = 0;
const gs = parts.map(pt => { const g = pt.g.index ? pt.g.toNonIndexed() : pt.g; g.applyMatrix4(pt.m); n += g.attributes.position.count; return g; });
const pos = new Float32Array(n * 3), nor = new Float32Array(n * 3), col = new Float32Array(n * 3);
let o = 0;
gs.forEach((g, i) => {
const cnt = g.attributes.position.count, c = parts[i].c;
pos.set(g.attributes.position.array, o * 3); nor.set(g.attributes.normal.array, o * 3);
for (let k = 0; k < cnt; k++) { col[(o + k) * 3] = c.r; col[(o + k) * 3 + 1] = c.g; col[(o + k) * 3 + 2] = c.b; }
o += cnt;
});
const out = new THREE.BufferGeometry();
out.setAttribute('position', new THREE.BufferAttribute(pos, 3));
out.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
out.setAttribute('color', new THREE.BufferAttribute(col, 3));
return out;
}
// Local axes: nose = -Z, up = +Y, right wing = +X. Units: metres.
function buildPlaneGeo(pal) {
const L = [], HP = Math.PI / 2;
const add = (g, c, x = 0, y = 0, z = 0, rx = 0, ry = 0, rz = 0) =>
L.push({ g, c, m: new THREE.Matrix4().compose(new V3(x, y, z), new Q4().setFromEuler(new THREE.Euler(rx, ry, rz)), new V3(1, 1, 1)) });
const box = (w, h, d) => new THREE.BoxGeometry(w, h, d);
const cyl = (a, b, h, n) => new THREE.CylinderGeometry(a, b, h, n);
const dark = lin(0x26221f), wood = lin(0x6b4a2c), white = lin(0xf1ede2), black = lin(0x16161a);
add(cyl(0.2, 0.55, 5.2, 8).scale(0.86, 1, 1), pal.body, 0, 0, 0.2, HP); // fuselage, tapers to the tail
add(cyl(0.6, 0.6, 0.7, 10), pal.cowl, 0, 0, -2.65, HP); // engine cowl
add(cyl(0.48, 0.48, 0.06, 10), dark, 0, 0, -3.01, HP);
add(box(9.2, 0.12, 1.5), pal.wing, 0, 1.25, -1.25); // upper wing
add(box(8.4, 0.12, 1.35), pal.wing, 0, -0.38, -0.75); // lower wing
for (const sx of [-1, 1]) {
add(box(0.08, 1.75, 0.1), wood, 3.0 * sx, 0.435, -1.42, -0.326); // interplane struts
add(box(0.08, 1.75, 0.1), wood, 3.0 * sx, 0.435, -0.62, -0.326);
add(box(0.07, 0.85, 0.07), wood, 0.42 * sx, 0.83, -1.55); // cabane struts
add(box(0.07, 0.85, 0.07), wood, 0.42 * sx, 0.83, -0.95);
add(cyl(0.38, 0.38, 0.12, 10), dark, 0.9 * sx, -1.35, -1.55, 0, 0, HP); // wheels
add(box(0.07, 1.08, 0.07), wood, 0.625 * sx, -0.885, -1.55, 0, 0, 0.535 * sx); // gear legs
add(box(0.07, 0.09, 0.9), dark, 0.16 * sx, 0.5, -0.95); // guns
if (pal.mark === 'roundel') {
for (const [y, flip] of [[1.32, 1], [-0.45, -1]]) {
const z = flip > 0 ? -1.25 : -0.75, x = 3.3 * sx;
add(cyl(0.6, 0.6, 0.02, 18), pal.m1, x, y, z);
add(cyl(0.38, 0.38, 0.03, 18), white, x, y + 0.004 * flip, z);
add(cyl(0.16, 0.16, 0.04, 12), pal.m2, x, y + 0.008 * flip, z);
}
} else {
for (const [y, flip] of [[1.32, 1], [-0.45, -1]]) {
const z = flip > 0 ? -1.25 : -0.75, x = 3.3 * sx;
add(box(1.25, 0.02, 1.25), white, x, y, z);
add(box(1.05, 0.03, 0.3), black, x, y + 0.004 * flip, z);
add(box(0.3, 0.03, 1.05), black, x, y + 0.004 * flip, z);
}
}
}
add(box(1.9, 0.07, 0.07), wood, 0, -1.35, -1.55); // axle
add(box(3.1, 0.07, 1.05), pal.tail, 0, 0.15, 2.45); // tailplane
add(box(0.07, 1.0, 0.95), pal.tail, 0, 0.68, 2.5); // fin
add(box(0.06, 0.45, 0.06), wood, 0, -0.33, 2.55, 0.5); // tail skid
add(box(0.44, 0.06, 0.7), dark, 0, 0.36, 0.45); // cockpit opening
add(new THREE.SphereGeometry(0.2, 6, 5), wood, 0, 0.6, 0.5); // pilot
return mergeParts(L);
}
const PLANE_PALS = [
{ body: lin(0x6d7040), wing: lin(0x7b7f49), tail: lin(0x7b7f49), cowl: lin(0x9a9da0), mark: 'roundel', m1: lin(0x24418f), m2: lin(0xb8232b) }, // 0: friendly
{ body: lin(0xb02a22), wing: lin(0xb02a22), tail: lin(0xf1ede2), cowl: lin(0xb02a22), mark: 'cross' }, // 1: red
{ body: lin(0x2f4372), wing: lin(0xd2ab3c), tail: lin(0xd2ab3c), cowl: lin(0x2f4372), mark: 'cross' }, // 2: blue / yellow
{ body: lin(0x4c6b4c), wing: lin(0x80609a), tail: lin(0x4c6b4c), cowl: lin(0xd8d2c0), mark: 'cross' }, // 3: green / mauve
{ body: lin(0x232326), wing: lin(0x232326), tail: lin(0xb02a22), cowl: lin(0xd8d2c0), mark: 'cross' } // 4: black (ace)
];
const planeGeos = PLANE_PALS.map(buildPlaneGeo);
const planeMat = new THREE.MeshLambertMaterial({ vertexColors: true, flatShading: true });
const propGeo = new THREE.BoxGeometry(0.18, 2.5, 0.06);
const propMat = new THREE.MeshLambertMaterial({ color: 0x5a3d22 });
const discGeo = new THREE.CircleGeometry(1.28, 20);
const discMat = new THREE.MeshBasicMaterial({ color: 0x2a2520, transparent: true, opacity: 0.16, side: THREE.DoubleSide, depthWrite: false });
const shadowGeo = mergeParts([
{ g: new THREE.PlaneGeometry(9.2, 1.6).rotateX(-Math.PI / 2), m: new THREE.Matrix4().makeTranslation(0, 0, -1), c: lin(0) },
{ g: new THREE.PlaneGeometry(1.1, 6).rotateX(-Math.PI / 2), m: new THREE.Matrix4(), c: lin(0) },
{ g: new THREE.PlaneGeometry(3.1, 1.0).rotateX(-Math.PI / 2), m: new THREE.Matrix4().makeTranslation(0, 0, 2.45), c: lin(0) }]);
// =====================================================================================
// Flight model
// =====================================================================================
const G = 9.81, RHO = 1.225, MASS = 650, S_WING = 21;
const CD0 = 0.040, K_IND = 0.10, CL_A = 4.5, INCID = 0.05, A_STALL = 0.27, CY_B = 0.9;
const T_STATIC = 2700, P_PROP = 76000; // static thrust [N], propulsive power [W]
const A_CMD = 0.30, A_TRIM = 0.012; // full-stick AoA command, hands-off trim AoA [rad]
const KS = 22, DP = 3.5, KY = 3, KB = 12, DY = 3.5, KR = 14, KD = 2.5, DR = 5;
const BSPEED = 520, BLIFE = 1.25, FIRE_RATE = 11;
let time = 0;
const _qi = new Q4(), _dq = new Q4(), _vl = new V3(), _acc = new V3(), _vd = new V3(), _ld = new V3(), _ax = new V3();
function stepPlane(p, dt) {
const c = p.ctrl, q = p.quat;
p.fwd.set(0, 0, -1).applyQuaternion(q); p.up.set(0, 1, 0).applyQuaternion(q); p.right.set(1, 0, 0).applyQuaternion(q);
const V = p.vel.length();
_vl.copy(p.vel).applyQuaternion(_qi.copy(q).invert()); // velocity in body axes
const alpha = V > 0.5 ? Math.atan2(-_vl.y, -_vl.z) : 0; // angle of attack
const beta = V > 0.5 ? Math.asin(clamp(_vl.x / V, -1, 1)) : 0; // sideslip
const a = alpha + INCID;
const st = smooth(A_STALL, A_STALL + 0.14, Math.abs(a)); // 0 = attached flow, 1 = fully stalled
const clLin = CL_A * a, clFlat = 1.05 * Math.sin(2 * a);
let cl = clLin + (clFlat - clLin) * st;
const sa = Math.sin(a), sb = Math.sin(beta);
let cd = CD0 + K_IND * cl * cl * (1 - st) + st * 1.25 * sa * sa + 0.6 * sb * sb;
if (p.dying) { cl *= 0.45; cd += 0.06; } else cd += (1 - p.hp / p.maxHp) * 0.015;
const qS = 0.5 * RHO * V * V * S_WING;
const power = c.throttle * p.engine * clamp(1 - (p.pos.y - 1500) / 1000, 0.15, 1);
const thrust = power * Math.min(T_STATIC, P_PROP / Math.max(V, 1));
_acc.set(0, -G, 0).addScaledVector(p.fwd, thrust / MASS);
if (V > 0.5) {
_vd.copy(p.vel).multiplyScalar(1 / V);
_acc.addScaledVector(_vd, -qS * cd / MASS);
_ld.crossVectors(p.right, _vd); // lift acts normal to the airflow
const ll = _ld.length();
if (ll > 1e-4) _acc.addScaledVector(_ld, qS * cl / MASS / ll);
_acc.addScaledVector(p.right, -qS * CY_B * beta / MASS);
}
p.vel.addScaledVector(_acc, dt);
p.pos.addScaledVector(p.vel, dt);
// Rotation: angular accelerations in body axes (x: pitch up, y: yaw left, z: roll left).
const vn = clamp(V / 40, 0.25, 1.8), qn = Math.min(V * V / 1600, 2.2), qc = Math.min((V * V + power * 260) / 1600, 2.2);
const aLim = 6.5 * MASS * G / (Math.max(qS, 1) * CL_A); // limits the commanded load to about 6.5 g
const aCmd = clamp(c.pitch * A_CMD, -aLim, aLim);
const w = p.omega;
let wzd = -qn * KR * c.roll + qn * KD * beta - DR * vn * w.z;
if (st > 0.05 && !p.dying) wzd += st * 1.4 * Math.sin(time * 2.3 + p.seed); // wing drop in the stall
w.x += (qc * KS * aCmd + qn * KS * (A_TRIM - clamp(alpha, -0.7, 0.7)) - DP * vn * w.x) * dt;
w.y += (-qc * KY * c.yaw - qn * KB * beta - DY * vn * w.y) * dt;
w.z += wzd * dt;
const wl = w.length();
if (wl > 1e-6) q.multiply(_dq.setFromAxisAngle(_ax.copy(w).multiplyScalar(1 / wl), wl * dt)).normalize();
p.speed = V; p.alpha = alpha; p.stall = st; p.gload = qS * cl / (MASS * G);
}
// =====================================================================================
// Aircraft entity
// =====================================================================================
let planes = [], player = null;
const Y_AXIS = new V3(0, 1, 0);
class Plane {
constructor(team, pal, isPlayer, skill) {
this.team = team; this.isPlayer = isPlayer;
this.pos = new V3(); this.vel = new V3(); this.quat = new Q4(); this.omega = new V3();
this.fwd = new V3(0, 0, -1); this.up = new V3(0, 1, 0); this.right = new V3(1, 0, 0);
this.ctrl = { pitch: 0, roll: 0, yaw: 0, throttle: 1, fire: false };
this.maxHp = isPlayer ? 100 : 55; this.hp = this.maxHp; this.engine = 1;
this.alive = true; this.dying = false; this.gone = false;
this.speed = 0; this.alpha = 0; this.stall = 0; this.gload = 1;
this.gunCd = 0; this.gunSide = 1; this.smokeT = 0; this.seed = Math.random() * 100;
this.lastHitBy = null; this.lastHitT = -99; this.deathSpin = 0; this.dieT = 0;
this.ai = { skill, target: null, retarget: 0, evade: 0, evadeSide: 1, evadeV: 0, avoid: 0, aimErr: new V3(), maxPull: 0.72 + 0.28 * skill, burst: 0 };
this.mesh = new THREE.Mesh(planeGeos[pal], planeMat);
this.prop = new THREE.Group(); this.prop.position.set(0, 0, -3.08);
this.prop.add(new THREE.Mesh(propGeo, propMat), new THREE.Mesh(discGeo, discMat));
this.mesh.add(this.prop);
this.shadow = new THREE.Mesh(shadowGeo, new THREE.MeshBasicMaterial({ color: 0x0a0f08, transparent: true, opacity: 0.3, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 }));
this.shadow.renderOrder = 2;
scene.add(this.mesh, this.shadow);
}
place(x, y, z, heading, speed) {
this.pos.set(x, y, z);
this.quat.setFromAxisAngle(Y_AXIS, -heading);
this.fwd.set(0, 0, -1).applyQuaternion(this.quat); this.up.set(0, 1, 0); this.right.set(1, 0, 0).applyQuaternion(this.quat);
this.vel.copy(this.fwd).multiplyScalar(speed); this.speed = speed;
this.omega.set(0, 0, 0);
return this;
}
remove() { this.gone = true; this.alive = false; scene.remove(this.mesh, this.shadow); this.shadow.material.dispose(); }
}
function spawnPlane(team, pal, x, y, z, heading, speed, skill = 0.5, isPlayer = false) {
const p = new Plane(team, pal, isPlayer, skill).place(x, y, z, heading, speed);
planes.push(p);
return p;
}
// =====================================================================================
// Particles (smoke, fire, sparks, splashes)
// =====================================================================================
const PMAX = 3200;
const P = {
pos: new Float32Array(PMAX * 3), vel: new Float32Array(PMAX * 3), life: new Float32Array(PMAX), max: new Float32Array(PMAX),
s0: new Float32Array(PMAX), s1: new Float32Array(PMAX), c0: new Float32Array(PMAX * 3), c1: new Float32Array(PMAX * 3),
a0: new Float32Array(PMAX), grav: new Float32Array(PMAX), drag: new Float32Array(PMAX), next: 0,
col: new Float32Array(PMAX * 4), size: new Float32Array(PMAX)
};
const pGeo = new THREE.BufferGeometry();
pGeo.setAttribute('position', new THREE.BufferAttribute(P.pos, 3).setUsage(THREE.DynamicDrawUsage));
pGeo.setAttribute('aColor', new THREE.BufferAttribute(P.col, 4).setUsage(THREE.DynamicDrawUsage));
pGeo.setAttribute('aSize', new THREE.BufferAttribute(P.size, 1).setUsage(THREE.DynamicDrawUsage));
const pMat = new THREE.ShaderMaterial({
transparent: true, depthWrite: false, uniforms: { uScale: { value: 500 } },
vertexShader: `attribute float aSize; attribute vec4 aColor; varying vec4 vColor; uniform float uScale;
void main(){ vColor = aColor; vec4 mv = modelViewMatrix * vec4(position, 1.0); gl_Position = projectionMatrix * mv;
gl_PointSize = aSize * uScale / max(-mv.z, 0.5); }`,
fragmentShader: `varying vec4 vColor;
void main(){ float d = length(gl_PointCoord - 0.5); float a = smoothstep(0.5, 0.22, d) * vColor.a; if (a < 0.01) discard; gl_FragColor = vec4(vColor.rgb, a); }`
});
const pPoints = new THREE.Points(pGeo, pMat);
pPoints.frustumCulled = false; pPoints.renderOrder = 5;
scene.add(pPoints);
function emit(x, y, z, vx, vy, vz, life, s0, s1, c0, c1, a0, grav = 0, drag = 0) {
const i = P.next; P.next = (P.next + 1) % PMAX;
const i3 = i * 3;
P.pos[i3] = x; P.pos[i3 + 1] = y; P.pos[i3 + 2] = z; P.vel[i3] = vx; P.vel[i3 + 1] = vy; P.vel[i3 + 2] = vz;
P.life[i] = P.max[i] = life; P.s0[i] = s0; P.s1[i] = s1; P.a0[i] = a0; P.grav[i] = grav; P.drag[i] = drag;
P.c0[i3] = c0[0]; P.c0[i3 + 1] = c0[1]; P.c0[i3 + 2] = c0[2]; P.c1[i3] = c1[0]; P.c1[i3 + 1] = c1[1]; P.c1[i3 + 2] = c1[2];
}
function updateParticles(dt) {
for (let i = 0; i < PMAX; i++) {
const i3 = i * 3, i4 = i * 4;
if (P.life[i] <= 0) { P.size[i] = 0; P.col[i4 + 3] = 0; continue; }
P.life[i] -= dt;
const t = 1 - Math.max(P.life[i], 0) / P.max[i], dr = Math.exp(-P.drag[i] * dt);
P.vel[i3] *= dr; P.vel[i3 + 1] = P.vel[i3 + 1] * dr - P.grav[i] * dt; P.vel[i3 + 2] *= dr;
P.pos[i3] += P.vel[i3] * dt; P.pos[i3 + 1] += P.vel[i3 + 1] * dt; P.pos[i3 + 2] += P.vel[i3 + 2] * dt;
P.size[i] = lerp(P.s0[i], P.s1[i], Math.sqrt(t));
P.col[i4] = lerp(P.c0[i3], P.c1[i3], t); P.col[i4 + 1] = lerp(P.c0[i3 + 1], P.c1[i3 + 1], t); P.col[i4 + 2] = lerp(P.c0[i3 + 2], P.c1[i3 + 2], t);
P.col[i4 + 3] = P.a0[i] * (1 - t * t);
}
pGeo.attributes.position.needsUpdate = pGeo.attributes.aColor.needsUpdate = pGeo.attributes.aSize.needsUpdate = true;
}
const C_FIRE0 = [1, 0.9, 0.5], C_FIRE1 = [0.85, 0.25, 0.05], C_SMOKE0 = [0.16, 0.15, 0.14], C_SMOKE1 = [0.32, 0.31, 0.3],
C_GREY0 = [0.6, 0.6, 0.6], C_GREY1 = [0.8, 0.8, 0.8], C_DUST0 = [0.62, 0.55, 0.4], C_DUST1 = [0.72, 0.67, 0.55],
C_WHITE = [0.95, 0.97, 1], C_SPARK0 = [1, 0.95, 0.7], C_SPARK1 = [1, 0.5, 0.1], C_DEBRIS = [0.1, 0.09, 0.08];
function explosion(pos, vel, scale = 1) {
for (let i = 0; i < 34 * scale; i++) {
const sp = rand(4, 22) * scale;
const dx = rand(-1, 1), dy = rand(-0.6, 1), dz = rand(-1, 1), l = Math.hypot(dx, dy, dz) || 1;
emit(pos.x, pos.y, pos.z, vel.x * 0.4 + dx / l * sp, vel.y * 0.4 + dy / l * sp, vel.z * 0.4 + dz / l * sp, rand(0.4, 1.0), 3 * scale, 11 * scale, C_FIRE0, C_FIRE1, 0.95, -2, 2.5);
}
for (let i = 0; i < 22 * scale; i++)
emit(pos.x + rand(-2, 2), pos.y + rand(-1, 2), pos.z + rand(-2, 2), vel.x * 0.25 + rand(-7, 7), vel.y * 0.25 + rand(0, 9), vel.z * 0.25 + rand(-7, 7), rand(2, 4.5), 6 * scale, 26 * scale, C_SMOKE0, C_SMOKE1, 0.75, -1.2, 1.2);
for (let i = 0; i < 14 * scale; i++)
emit(pos.x, pos.y, pos.z, vel.x * 0.6 + rand(-18, 18), vel.y * 0.6 + rand(-4, 22), vel.z * 0.6 + rand(-18, 18), rand(1.2, 2.6), 0.9, 0.5, C_DEBRIS, C_DEBRIS, 1, 9.8, 0.2);
sfxBoom(camera.position.distanceTo(pos));
}
function puff(x, y, z, waterHit) {
const c0 = waterHit ? C_WHITE : C_DUST0, c1 = waterHit ? C_WHITE : C_DUST1;
for (let i = 0; i < 3; i++) emit(x, y + 0.5, z, rand(-2, 2), rand(3, waterHit ? 11 : 7), rand(-2, 2), rand(0.5, 1.0), 1.2, waterHit ? 3 : 5, c0, c1, 0.7, 9, 1);
}
function sparks(pos) {
for (let i = 0; i < 5; i++) emit(pos.x, pos.y, pos.z, rand(-9, 9), rand(-9, 9), rand(-9, 9), rand(0.15, 0.4), 0.9, 0.3, C_SPARK0, C_SPARK1, 1, 5, 1);
emit(pos.x, pos.y, pos.z, 0, 0, 0, 0.6, 1.5, 5, C_GREY0, C_GREY1, 0.4, 0, 0);
}
// =====================================================================================
// Guns and bullets
// =====================================================================================
const BMAX = 500;
const bullets = [];
const bulletPool = [];
const bulletMesh = new THREE.InstancedMesh(new THREE.BoxGeometry(0.22, 0.22, 9), new THREE.MeshBasicMaterial({ color: 0xffffff, fog: false }), BMAX);
bulletMesh.frustumCulled = false; bulletMesh.count = 0;
bulletMesh.setColorAt(0, new THREE.Color(1, 1, 1));
scene.add(bulletMesh);
const TRACER = [new THREE.Color(0xfff0a0), new THREE.Color(0xff9a50)];
const _bm = new THREE.Matrix4(), _bs = new V3(1, 1, 1), _bd = new V3(), _bo = new V3(), _seg = new V3(), _rel = new V3(), _hit = new V3(), NEG_Z = new V3(0, 0, -1);
function fireGun(p) {
if (bullets.length >= BMAX) return;
const b = bulletPool.pop() || { p: new V3(), v: new V3(), q: new Q4(), life: 0, owner: null };
p.gunSide = -p.gunSide;
const spread = p.isPlayer ? 0.004 : 0.011;
_bd.copy(p.fwd).addScaledVector(p.up, rand(-spread, spread)).addScaledVector(p.right, rand(-spread, spread)).normalize();
b.p.copy(p.pos).addScaledVector(p.fwd, 2.2).addScaledVector(p.up, 0.5).addScaledVector(p.right, 0.16 * p.gunSide);
b.v.copy(p.vel).addScaledVector(_bd, BSPEED);
b.q.setFromUnitVectors(NEG_Z, _bd);
b.life = BLIFE; b.owner = p;
b.p.addScaledVector(b.v, Math.random() * 0.01);
bullets.push(b);
_bo.copy(p.pos).addScaledVector(p.fwd, 2.6).addScaledVector(p.up, 0.5).addScaledVector(p.right, 0.16 * p.gunSide);
emit(_bo.x, _bo.y, _bo.z, p.vel.x, p.vel.y, p.vel.z, 0.05, 1.3, 0.6, C_SPARK0, C_SPARK1, 0.9);
const d = p.isPlayer ? 0 : camera.position.distanceTo(p.pos);
if (d < 700) sfxGun(p.isPlayer ? 1 : 0.6 / (1 + d / 60));
}
function updateBullets(dt) {
for (let i = bullets.length - 1; i >= 0; i--) {
const b = bullets[i];
let dead = false;
_seg.copy(b.v).multiplyScalar(dt); // this frame's travel
const segLen2 = _seg.lengthSq();
for (const pl of planes) {
if (pl.gone || pl.team === b.owner.team) continue;
_rel.copy(pl.pos).sub(b.p);
const t = clamp(_rel.dot(_seg) / segLen2, 0, 1);
_hit.copy(b.p).addScaledVector(_seg, t);
const R = pl.isPlayer ? 2.4 : 3.1;
if (_hit.distanceToSquared(pl.pos) < R * R) {
sparks(_hit);
damage(pl, rand(8, 11), b.owner);
dead = true; break;
}
}
if (!dead) {
b.p.add(_seg); b.life -= dt;
const gh = groundHeight(b.p.x, b.p.z);
if (b.p.y < Math.max(gh, 0)) { puff(b.p.x, Math.max(gh, 0), b.p.z, gh < 0); dead = true; }
else if (b.life <= 0) dead = true;
}
if (dead) { bulletPool.push(b); bullets[i] = bullets[bullets.length - 1]; bullets.pop(); }
}
for (let i = 0; i < bullets.length; i++) {
const b = bullets[i];
bulletMesh.setMatrixAt(i, _bm.compose(b.p, b.q, _bs));
bulletMesh.setColorAt(i, TRACER[b.owner.team]);
}
bulletMesh.count = bullets.length;
bulletMesh.instanceMatrix.needsUpdate = true;
if (bulletMesh.instanceColor) bulletMesh.instanceColor.needsUpdate = true;
}
// =====================================================================================
// Damage, kills, crashes
// =====================================================================================
let state = 'menu'; // menu | playing | dead | paused
let score = 0, kills = 0, wave = 0, waveTimer = 0, hitFlash = 0, hitMarker = 0, shake = 0, deadT = 0, deathCause = '';
let best = 0;
try { best = +localStorage.getItem('canvaswire.best') || 0; } catch (e) { /* storage not available */ }
function damage(pl, amt, by) {
if (pl.gone) return;
if (pl.isPlayer) { if (state !== 'playing') return; amt *= 0.55; hitFlash = 1; shake = Math.max(shake, 0.5); sfxHit(); }
if (by && by.isPlayer) { hitMarker = 0.18; sfxTick(); }
pl.hp -= amt;
if (by) { pl.lastHitBy = by; pl.lastHitT = time; }
if (pl.hp <= 0 && !pl.dying) kill(pl, by, 'Shot down');
}
function kill(pl, by, cause) {
window.__sim.log.push({ t: +time.toFixed(1), team: pl.team, player: pl.isPlayer, cause, by: by ? (by.isPlayer ? 'player' : 'team' + by.team) : null });
pl.hp = 0; pl.dying = true; pl.alive = false; pl.ctrl.fire = false; pl.engine = 0; pl.dieT = 0;
pl.deathSpin = (Math.random() < 0.5 ? -1 : 1) * rand(0.5, 1);
if (!by && time - pl.lastHitT < 15) by = pl.lastHitBy;
if (pl.isPlayer) {
state = 'dead'; deadT = 0; deathCause = cause;
} else if (pl.team === 1) {
if (by && by.isPlayer) { kills++; score += 100; msg('Enemy down', '+100'); }
else if (state === 'playing') msg('', by ? 'Your wingman shot one down' : 'An enemy crashed');
} else if (state === 'playing') msg('', 'A wingman is down');
if (!pl.isPlayer && cause === 'Shot down' && Math.random() < 0.3) crash(pl); // blows up in the air
}
function crash(pl) {
if (pl.gone) return;
if (!pl.dying) kill(pl, null, 'Crashed');
explosion(pl.pos, pl.vel, 1.3);
if (pl.isPlayer) shake = 1.5;
pl.remove();
if (pl.isPlayer) pl.mesh.visible = false;
}
// =====================================================================================
// AI pilot
// =====================================================================================
const _des = new V3(), _d = new V3(), _to = new V3(), _lead = new V3(), _r = new V3();
function pickTarget(p) {
let bestT = null, bestC = Infinity;
for (const e of planes) {
if (!e.alive || e.team === p.team) continue;
let attackers = 0;
for (const o of planes) if (o !== p && o.alive && o.team === p.team && o.ai.target === e && !o.isPlayer) attackers++;
const cost = p.pos.distanceTo(e.pos) * (1 + 0.7 * attackers);
if (cost < bestC) { bestC = cost; bestT = e; }
}
return bestT;
}
function aiControl(p, dt) {
const a = p.ai, c = p.ctrl;
a.retarget -= dt;
if (!a.target || !a.target.alive || a.retarget <= 0) { a.target = pickTarget(p); a.retarget = rand(2, 4); }
const T = a.target, V = p.speed;
// Horizontal direction of travel.
let vdx = p.vel.x, vdz = p.vel.z, vl = Math.hypot(vdx, vdz);
if (vl < 3) { vdx = p.fwd.x; vdz = p.fwd.z; vl = Math.hypot(vdx, vdz) || 1; }
vdx /= vl; vdz /= vl;
// --- terrain avoidance has priority ---
let gmax = groundHeight(p.pos.x, p.pos.z);
for (const d of [150, 300, 450]) gmax = Math.max(gmax, groundHeight(p.pos.x + vdx * d, p.pos.z + vdz * d));
gmax = Math.max(gmax, 0);
const clearance = p.pos.y + Math.min(p.vel.y, 0) * 3 - gmax;
a.avoid -= dt;
let wantFire = false, pullCap = a.maxPull;
if (clearance < 75 || (a.avoid > 0 && p.pos.y - gmax < 150)) {
if (clearance < 75) a.avoid = 1.2;
let bx = vdx, bz = vdz, bestCost = Infinity;
for (const ang of [0, -0.7, 0.7, -1.4, 1.4]) {
const cs = Math.cos(ang), sn = Math.sin(ang), dx = vdx * cs - vdz * sn, dz = vdx * sn + vdz * cs;
const cost = Math.max(groundHeight(p.pos.x + dx * 250, p.pos.z + dz * 250), groundHeight(p.pos.x + dx * 500, p.pos.z + dz * 500), 0) + Math.abs(ang) * 45;
if (cost < bestCost) { bestCost = cost; bx = dx; bz = dz; }
}
_des.set(bx, clamp((V - 22) / 20, 0.08, 0.6), bz).normalize();
pullCap = 1;
} else if (T) {
_to.copy(T.pos).sub(p.pos);
const dist = _to.length();
// Wandering aim error: less skilled pilots aim worse.
a.aimErr.x += rand(-1, 1) * dt * 14; a.aimErr.y += rand(-1, 1) * dt * 14; a.aimErr.z += rand(-1, 1) * dt * 14;
a.aimErr.clampLength(0, (1 - a.skill) * 9);
_lead.copy(T.vel).sub(p.vel).multiplyScalar(dist / BSPEED).add(T.pos).add(a.aimErr);
_des.copy(_lead).sub(p.pos).normalize();
const off = Math.acos(clamp(p.fwd.dot(_des), -1, 1));
if (dist < 400 && off < 0.035 + 2 / Math.max(dist, 30)) wantFire = true;
const closing = -_r.copy(T.vel).sub(p.vel).dot(_to) / Math.max(dist, 1);
if (p.fwd.dot(_to) > 0 && (dist < 60 || (closing > 25 && dist < closing * 1.6))) { // do not ram the target
_des.addScaledVector(p.up, 1.4).normalize(); wantFire = wantFire && dist > 45;
}
// Break when an opponent sits on the tail.
if (a.evade <= 0) {
for (const e of planes) {
if (!e.alive || e.team === p.team) continue;
_r.copy(p.pos).sub(e.pos);
const d = _r.length();
if (d < 300 && e.fwd.dot(_r) / d > 0.94 && p.fwd.dot(_r) / d > -0.2) {
if (Math.random() < (0.5 + a.skill) * dt * 1.2) { a.evade = rand(1.8, 3.6); a.evadeSide = Math.random() < 0.5 ? -1 : 1; a.evadeV = rand(-0.4, 0.3); }
break;
}
}
}
if (a.evade > 0) {
a.evade -= dt; wantFire = false; pullCap = 1;
_des.set(-vdz * a.evadeSide * 0.9 + vdx * 0.25, a.evadeV, vdx * a.evadeSide * 0.9 + vdz * 0.25).normalize();
}
if (V < 27) { _des.y -= 0.35; _des.normalize(); } // regain airspeed
if (dist > 600 && p.pos.y < gmax + 220) { _des.y = Math.max(_des.y, 0.15); _des.normalize(); }
if (p.pos.y > 1400) { _des.y = Math.min(_des.y, -0.1); _des.normalize(); }
} else {
// Nothing to fight: orbit the island.
const th = Math.atan2(p.pos.z, p.pos.x) + 0.35, R = 1700;
_des.set(Math.cos(th) * R - p.pos.x, (Math.max(gmax + 260, 420) - p.pos.y) * 1.5, Math.sin(th) * R - p.pos.z).normalize();
_des.y = clamp(_des.y, -0.25, 0.3);
pullCap = 0.6;
}
// --- steer the nose toward _des ---
_d.copy(_des).applyQuaternion(_qi.copy(p.quat).invert());
const ang = Math.acos(clamp(-_d.z, -1, 1));
let rollErr, pitch, yaw = 0;
if (ang > 0.6) { // far off the nose: roll the lift vector onto it, then pull
rollErr = Math.atan2(_d.x, _d.y);
pitch = Math.abs(rollErr) < 0.9 ? 1 : 0.15;
} else { // close: bank-to-turn with rudder for fine aim
const hdgErr = wrapPi(Math.atan2(_des.x, -_des.z) - Math.atan2(p.fwd.x, -p.fwd.z));
const bank = Math.atan2(-p.right.y, p.up.y);
rollErr = wrapPi(clamp(hdgErr * 2.6, -1.35, 1.35) - bank);
pitch = clamp(Math.atan2(_d.y, -_d.z) * 3.5, -0.5, 1);
yaw = clamp(_d.x * 3, -1, 1) * (ang < 0.25 ? 1 : 0.3);
}
pitch = Math.min(pitch, pullCap);
if (p.alpha > 0.17) pitch = Math.min(pitch, (0.25 - p.alpha) * 12); // stay out of the stall
const k = Math.min(1, dt * 8);
c.roll += (clamp(rollErr * 2.2, -1, 1) - c.roll) * k;
c.pitch += (pitch - c.pitch) * k;
c.yaw += (yaw - c.yaw) * k;
c.throttle = V > 62 ? 0.4 : 1;
c.fire = wantFire;
}
// =====================================================================================
// Input
// =====================================================================================
const keys = Object.create(null);
let mouseFire = false, invertPitch = false, camMode = 0, mute = false;
const GAME_KEYS = new Set(['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'KeyW', 'KeyA', 'KeyS', 'KeyD', 'KeyQ', 'KeyE', 'KeyR', 'KeyF']);
addEventListener('keydown', e => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (GAME_KEYS.has(e.code)) e.preventDefault();
if (e.repeat) return;
keys[e.code] = true;
if (e.code === 'Enter' || e.code === 'NumpadEnter') { if (state === 'menu' || (state === 'dead' && deadT > 1.5)) startGame(); }
else if (e.code === 'KeyC') camMode = (camMode + 1) % 2;
else if (e.code === 'KeyI') { invertPitch = !invertPitch; msg('', invertPitch ? 'Pitch inverted: W / Up = nose up' : 'Pitch normal: S / Down = nose up'); }
else if (e.code === 'KeyM') { mute = !mute; if (aud.master) aud.master.gain.value = mute ? 0 : 0.6; msg('', mute ? 'Sound off' : 'Sound on'); }
else if (e.code === 'KeyP' || e.code === 'Escape') togglePause();
});
addEventListener('keyup', e => { keys[e.code] = false; });
addEventListener('blur', () => { for (const k in keys) keys[k] = false; mouseFire = false; });
document.addEventListener('visibilitychange', () => { if (document.hidden && state === 'playing') togglePause(); });
glCanvas.addEventListener('mousedown', e => { if (e.button === 0) mouseFire = true; });
addEventListener('mouseup', () => { mouseFire = false; });
glCanvas.addEventListener('contextmenu', e => e.preventDefault());
$('startBtn').addEventListener('click', () => startGame());
$('againBtn').addEventListener('click', () => startGame());
function togglePause() {
if (state === 'playing') { state = 'paused'; $('pause').classList.remove('hidden'); if (AC) AC.suspend(); }
else if (state === 'paused') { state = 'playing'; $('pause').classList.add('hidden'); if (AC) AC.resume(); }
}
const approach = (v, target, rate) => v < target ? Math.min(v + rate, target) : Math.max(v - rate, target);
function playerControl(p, dt) {
const c = p.ctrl;
let tp = ((keys.KeyS || keys.ArrowDown) ? 1 : 0) - ((keys.KeyW || keys.ArrowUp) ? 1 : 0);
if (invertPitch) tp = -tp;
if (tp < 0) tp = -0.6;
const tr = ((keys.KeyD || keys.ArrowRight) ? 1 : 0) - ((keys.KeyA || keys.ArrowLeft) ? 1 : 0);
const ty = (keys.KeyE ? 1 : 0) - (keys.KeyQ ? 1 : 0);
c.pitch = approach(c.pitch, tp, dt * (tp ? 3.2 : 5));
c.roll = approach(c.roll, tr, dt * (tr ? 4.5 : 7));
c.yaw = approach(c.yaw, ty, dt * (ty ? 4 : 6));
c.throttle = clamp(c.throttle + ((keys.KeyR ? 1 : 0) - (keys.KeyF ? 1 : 0)) * dt * 0.7, 0, 1);
c.fire = !!(keys.Space || mouseFire);
}
// =====================================================================================
// Audio (synthesised: engine, wind, guns, explosions)
// =====================================================================================
let AC = null;
const aud = {};
function initAudio() {
if (AC) { AC.resume(); return; }
try { AC = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { return; }
const m = aud.master = AC.createGain(); m.gain.value = mute ? 0 : 0.6; m.connect(AC.destination);
const len = AC.sampleRate * 2, buf = AC.createBuffer(1, len, AC.sampleRate), d = buf.getChannelData(0);
for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;
aud.noise = buf;
aud.eg = AC.createGain(); aud.eg.gain.value = 0;
aud.elp = AC.createBiquadFilter(); aud.elp.type = 'lowpass'; aud.elp.frequency.value = 500;
aud.o1 = AC.createOscillator(); aud.o1.type = 'sawtooth';
aud.o2 = AC.createOscillator(); aud.o2.type = 'square';
const og = AC.createGain(); og.gain.value = 0.5;
aud.o1.connect(aud.elp); aud.o2.connect(og); og.connect(aud.elp); aud.elp.connect(aud.eg); aud.eg.connect(m);
aud.o1.start(); aud.o2.start();
const ws = AC.createBufferSource(); ws.buffer = buf; ws.loop = true;
const wf = AC.createBiquadFilter(); wf.type = 'bandpass'; wf.frequency.value = 650; wf.Q.value = 0.5;
aud.wg = AC.createGain(); aud.wg.gain.value = 0;
ws.connect(wf); wf.connect(aud.wg); aud.wg.connect(m); ws.start();
}
function noiseBurst(dur, freq, type, vol, q = 1) {
if (!AC || mute || AC.state !== 'running') return;
const s = AC.createBufferSource(); s.buffer = aud.noise;
const f = AC.createBiquadFilter(); f.type = type; f.frequency.value = freq; f.Q.value = q;
const g = AC.createGain(), t = AC.currentTime;
g.gain.setValueAtTime(vol, t); g.gain.exponentialRampToValueAtTime(0.001, t + dur);
s.connect(f); f.connect(g); g.connect(aud.master);
s.start(t, Math.random() * 1.5, dur + 0.05);
}
function sfxGun(v) { noiseBurst(0.08, 1500, 'bandpass', 0.45 * v, 0.8); noiseBurst(0.11, 200, 'lowpass', 0.7 * v); }
function sfxBoom(dist) { const v = 1.3 / (1 + dist / 250); if (v > 0.03) noiseBurst(1.5, 240, 'lowpass', v); }
function sfxHit() { noiseBurst(0.07, 2400, 'bandpass', 0.6, 3); noiseBurst(0.1, 300, 'lowpass', 0.6); }
function sfxTick() { noiseBurst(0.04, 3800, 'highpass', 0.22); }
function updateAudio() {
if (!AC || !player) return;
const t = AC.currentTime, on = state === 'playing' || (state === 'dead' && !player.gone);
const thr = player.ctrl.throttle * player.engine, f = 34 + 46 * thr + player.speed * 0.35;
aud.o1.frequency.setTargetAtTime(f, t, 0.08); aud.o2.frequency.setTargetAtTime(f * 0.502, t, 0.08);
aud.elp.frequency.setTargetAtTime(280 + 800 * thr, t, 0.1);
aud.eg.gain.setTargetAtTime(on ? 0.09 + 0.13 * thr : 0, t, 0.15);
aud.wg.gain.setTargetAtTime(on ? clamp(player.speed / 90, 0, 1) ** 2 * 0.5 : 0, t, 0.2);
}
// =====================================================================================
// Game flow: start, waves
// =====================================================================================
let msgTimer = 0;
function msg(title, sub = '', secs = 3) {
const el = $('msg');
el.textContent = title;
if (sub) { const s = document.createElement('small'); s.textContent = sub; el.appendChild(s); }
el.classList.add('on'); msgTimer = secs;
}
const COMPASS = ['north', 'north-east', 'east', 'south-east', 'south', 'south-west', 'west', 'north-west'];
function clearWorld() {
for (const p of planes) if (!p.gone) p.remove();
planes = []; bulletPool.push(...bullets); bullets.length = 0;
}
function safeAlt(x, z, y) { return Math.max(y, groundHeight(x, z) + 260, 300); }
function setupFlight(asPlayer) {
clearWorld();
const x = 300, z = 2900;
player = spawnPlane(0, 0, x, safeAlt(x, z, 480), z, 0, 42, 0.6, true);
player.ctrl.throttle = 0.9;
spawnWingmen();
camQ.copy(player.quat);
if (!asPlayer) player.ai.skill = 0.5;
}
function spawnWingmen() {
const have = planes.filter(p => p.team === 0 && !p.isPlayer && p.alive).length;
const hdg = Math.atan2(player.fwd.x, -player.fwd.z);
for (let i = have; i < 2; i++) {
const side = i === 0 ? -1 : 1;
const x = player.pos.x - Math.sin(hdg) * 45 + Math.cos(hdg) * 45 * side, z = player.pos.z + Math.cos(hdg) * 45 + Math.sin(hdg) * 45 * side;
spawnPlane(0, 0, x, safeAlt(x, z, player.pos.y + 8), z, hdg, Math.max(player.speed, 36), 0.45);
}
}
function startGame() {
initAudio();
if (document.activeElement && document.activeElement.blur) document.activeElement.blur(); // Space must not re-trigger a button
score = 0; kills = 0; wave = 0; hitFlash = 0; shake = 0;
setupFlight(true);
state = 'playing';
$('menu').classList.add('hidden'); $('over').classList.add('hidden'); $('pause').classList.add('hidden');
waveTimer = 2.5;
msg('Patrol', 'Enemy aircraft reported over the island');
}
function startWave() {
wave++;
const n = Math.min(1 + wave, 6);
const phi = wave === 1 ? Math.atan2(player.fwd.x, -player.fwd.z) + rand(-0.4, 0.4) : rand(0, Math.PI * 2);
const dist = 1900, dx = Math.sin(phi), dz = -Math.cos(phi);
const baseY = clamp(player.pos.y + rand(-60, 220), 350, 950);
for (let i = 0; i < n; i++) {
const lat = (i - (n - 1) / 2) * 70;
const x = player.pos.x + dx * (dist + Math.abs(lat) * 0.6) - dz * lat, z = player.pos.z + dz * (dist + Math.abs(lat) * 0.6) + dx * lat;
const ace = wave >= 3 && i === 0;
const skill = ace ? 1 : clamp(0.2 + wave * 0.09 + rand(0, 0.2), 0, 0.9);
const e = spawnPlane(1, ace ? 4 : 1 + ((wave + i) % 3), x, safeAlt(x, z, baseY + rand(-30, 30)), z, phi + Math.PI, 40, skill);
if (ace) { e.maxHp = e.hp = 80; }
}
if (wave > 1) {
player.hp = Math.min(player.maxHp, player.hp + 40);
spawnWingmen();
score += 50 * (wave - 1);
}
const brg = COMPASS[Math.round(((phi % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI) / (Math.PI / 4)) % 8];
msg('Wave ' + wave, n + ' enemy aircraft to the ' + brg + (wave > 1 ? ' — repairs made' : ''), 4);
}
function endGame() {
if (score > best) { best = score; try { localStorage.setItem('canvaswire.best', String(best)); } catch (e) { /* ignore */ } }
$('overTitle').textContent = deathCause;
$('overStats').innerHTML = 'Victories: <b>' + kills + '</b> &nbsp;·&nbsp; Wave: <b>' + wave + '</b><br>Score: <b>' + score + '</b> &nbsp;·&nbsp; Best: <b>' + best + '</b>';
$('over').classList.remove('hidden');
}
// =====================================================================================
// Simulation update
// =====================================================================================
const _sn = new V3(), _sq = new Q4(), _sq2 = new Q4(), _tmp = new V3();
let overShown = false, autopilot = false; // autopilot: test hook, the AI flies the player's aircraft
function update(dt) {
time += dt;
const sub = Math.max(1, Math.ceil(dt / 0.011)), h = dt / sub;
for (const p of planes) {
if (p.gone) continue;
if (p.dying) {
p.dieT += dt;
p.ctrl.roll = p.deathSpin; p.ctrl.pitch = 0.15; p.ctrl.yaw = p.deathSpin * 0.5; p.ctrl.throttle = 0; p.ctrl.fire = false;
} else if (p.isPlayer && state === 'playing' && !autopilot) playerControl(p, dt);
else aiControl(p, dt);
p.engine = p.dying ? 0 : 0.55 + 0.45 * smooth(0, 0.5, p.hp / p.maxHp);
for (let i = 0; i < sub; i++) stepPlane(p, h);
// ground and water
const gh = groundHeight(p.pos.x, p.pos.z);
if (p.pos.y < Math.max(gh, 0) + 1.3) {
p.pos.y = Math.max(gh, 0) + 1.3;
if (gh < 0) for (let i = 0; i < 14; i++) emit(p.pos.x + rand(-4, 4), 0.5, p.pos.z + rand(-4, 4), rand(-6, 6), rand(8, 22), rand(-6, 6), rand(0.8, 1.6), 3, 9, C_WHITE, C_WHITE, 0.8, 12, 0.6);
crash(p);
continue;
}
if (p.dying && p.dieT > 14) { crash(p); continue; }
// guns
p.gunCd -= dt;
if (p.ctrl.fire && p.gunCd <= 0) { fireGun(p); p.gunCd = 1 / FIRE_RATE; if (p.isPlayer) shake = Math.max(shake, 0.12); }
// damage smoke and fire
const frac = p.hp / p.maxHp;
if (frac < 0.6) {
p.smokeT -= dt;
if (p.smokeT <= 0) {
p.smokeT = p.dying ? 0.03 : 0.07;
_tmp.copy(p.pos).addScaledVector(p.fwd, -1.5);
if (p.dying) {
emit(_tmp.x, _tmp.y, _tmp.z, p.vel.x * 0.5 + rand(-2, 2), p.vel.y * 0.5 + rand(-2, 2), p.vel.z * 0.5 + rand(-2, 2), rand(0.25, 0.5), 2.5, 4.5, C_FIRE0, C_FIRE1, 0.9, 0, 3);
emit(_tmp.x, _tmp.y, _tmp.z, p.vel.x * 0.2 + rand(-1, 1), p.vel.y * 0.2 + rand(0, 2), p.vel.z * 0.2 + rand(-1, 1), rand(1.8, 3), 2.5, 8, C_SMOKE0, C_SMOKE1, 0.5, -1, 1.5);
} else {
const c0 = frac < 0.3 ? C_SMOKE0 : C_GREY0, c1 = frac < 0.3 ? C_SMOKE1 : C_GREY1;
emit(_tmp.x, _tmp.y, _tmp.z, p.vel.x * 0.2 + rand(-1, 1), p.vel.y * 0.2 + rand(0, 1.5), p.vel.z * 0.2 + rand(-1, 1), rand(1.2, 2.2), 1.8, 6, c0, c1, 0.4 * (1 - frac) + 0.12, -0.8, 1.5);
}
}
}
// visuals
p.mesh.position.copy(p.pos); p.mesh.quaternion.copy(p.quat);
p.prop.rotation.z -= dt * (p.engine > 0 ? 14 + 26 * p.ctrl.throttle : 3);
p.prop.children[1].visible = p.engine > 0;
const agl = p.pos.y - Math.max(gh, 0);
if (agl < 500) {
const k = agl / SUN.y, sx = p.pos.x - SUN.x * k, sz = p.pos.z - SUN.z * k, sgh = groundHeight(sx, sz);
p.shadow.visible = true;
p.shadow.position.set(sx, Math.max(sgh, 0) + 0.25, sz);
if (sgh > 0) _sq.setFromUnitVectors(Y_AXIS, groundNormal(sx, sz, _sn)); else _sq.identity();
p.shadow.quaternion.copy(_sq).multiply(_sq2.setFromAxisAngle(Y_AXIS, -Math.atan2(p.fwd.x, -p.fwd.z)));
p.shadow.material.opacity = 0.38 * (1 - agl / 500);
} else p.shadow.visible = false;
}
// player collides with other aircraft
if (player && player.alive && state === 'playing') {
for (const o of planes) {
if (o.team === 0 || !o.alive) continue;
if (o.pos.distanceToSquared(player.pos) < 22) {
kill(o, player, 'Collision'); crash(o);
kill(player, null, 'Collision'); crash(player);
break;
}
}
}
updateBullets(dt);
updateParticles(dt);
// waves
if (state === 'playing') {
const enemies = planes.some(p => p.team === 1 && !p.gone);
if (!enemies) {
if (waveTimer <= 0) { waveTimer = 5; if (wave > 0) msg('Sky clear', 'Wave ' + wave + ' defeated', 3); }
waveTimer -= dt;
if (waveTimer <= 0) startWave();
}
if (Math.hypot(player.pos.x, player.pos.z) > 9000 && msgTimer <= 0) msg('', 'You are leaving the patrol area — turn back', 2);
} else if (state === 'dead') {
deadT += dt;
if (deadT > 1.5 && player.gone && !overShown) { overShown = true; endGame(); }
if (deadT > 9 && !overShown) { overShown = true; endGame(); }
}
if (state !== 'dead') overShown = false;
planes = planes.filter(p => !p.gone || p.isPlayer);
hitFlash = Math.max(0, hitFlash - dt * 1.8); hitMarker = Math.max(0, hitMarker - dt); shake = Math.max(0, shake - dt * 2.5);
if (msgTimer > 0) { msgTimer -= dt; if (msgTimer <= 0) $('msg').classList.remove('on'); }
}
// =====================================================================================
// Camera
// =====================================================================================
const camQ = new Q4(), _off = new V3(), _look = new V3(), _camT = new V3(), _tilt = new Q4().setFromAxisAngle(new V3(1, 0, 0), -0.07);
function updateCamera(dt) {
const p = player;
if (!p) return;
if (state === 'menu') {
const t = performance.now() / 1000 * 0.17;
_camT.set(p.pos.x + Math.cos(t) * 17, p.pos.y + 4.5, p.pos.z + Math.sin(t) * 17);
camera.position.copy(_camT); camera.up.set(0, 1, 0); camera.lookAt(_look.copy(p.pos).setY(p.pos.y + 6.5));
} else if (state === 'dead') {
_off.copy(camera.position).sub(p.pos).setY(0);
if (_off.lengthSq() < 1) _off.set(1, 0, 0);
_off.normalize().applyAxisAngle(Y_AXIS, dt * 0.12);
_camT.copy(p.pos).addScaledVector(_off, 58); _camT.y += 24;
camera.position.lerp(_camT, Math.min(1, dt * 1.6));
camera.up.set(0, 1, 0); camera.lookAt(p.pos);
} else if (camMode === 0) {
camQ.slerp(p.quat, 1 - Math.exp(-dt * 5.5));
camera.position.copy(p.pos).add(_off.set(0, 3.3, 14).applyQuaternion(camQ));
camera.quaternion.copy(camQ).multiply(_tilt);
} else {
camQ.copy(p.quat);
camera.position.copy(p.pos).add(_off.set(0, 0.78, 0.62).applyQuaternion(p.quat));
camera.quaternion.copy(p.quat);
}
const s = shake + (state === 'playing' ? p.stall * 0.25 : 0);
if (s > 0) camera.position.add(_off.set(rand(-1, 1), rand(-1, 1), rand(-1, 1)).multiplyScalar(s * 0.12));
const minY = Math.max(groundHeight(camera.position.x, camera.position.z), 0) + (state === 'dead' ? 9 : 1.2);
if (camera.position.y < minY) { camera.position.y = minY; if (state === 'dead') camera.lookAt(p.pos); }
const fov = 58 + clamp((p.speed - 35) * 0.22, 0, 9);
if (Math.abs(fov - camera.fov) > 0.05) { camera.fov = lerp(camera.fov, fov, Math.min(1, dt * 3)); camera.updateProjectionMatrix(); }
camera.updateMatrixWorld();
sky.position.copy(camera.position);
water.position.set(Math.round(camera.position.x / 500) * 500, 0, Math.round(camera.position.z / 500) * 500);
}
// =====================================================================================
// HUD (2D canvas)
// =====================================================================================
let W = 1, Hh = 1, dpr = 1;
const _pv = new V3(), CREAM = '#efe6cf', AMBER = '#e8b04a', REDC = '#ff5a3c', BLUEC = '#8fc6ff';
function project(v) { // world -> screen px; also returns camera-space coords
_pv.copy(v).applyMatrix4(camera.matrixWorldInverse);
const cx = _pv.x, cy = _pv.y, cz = _pv.z;
_pv.applyMatrix4(camera.projectionMatrix);
return { x: (_pv.x * 0.5 + 0.5) * W, y: (-_pv.y * 0.5 + 0.5) * Hh, front: cz < 0, cx, cy, cz };
}
function panel(x, y, w, h) { g2.fillStyle = 'rgba(12,16,20,.5)'; g2.fillRect(x, y, w, h); g2.strokeStyle = 'rgba(239,230,207,.25)'; g2.lineWidth = 1; g2.strokeRect(x + .5, y + .5, w - 1, h - 1); }
function bar(x, y, w, h, frac, colr) { g2.fillStyle = 'rgba(239,230,207,.16)'; g2.fillRect(x, y, w, h); g2.fillStyle = colr; g2.fillRect(x, y, w * clamp(frac, 0, 1), h); }
function drawHUD() {
g2.setTransform(dpr, 0, 0, dpr, 0, 0);
g2.clearRect(0, 0, W, Hh);
$('vignette').style.opacity = state === 'playing' ? (hitFlash * 0.8 + (player.hp < 30 ? 0.25 : 0)).toFixed(2) : state === 'dead' ? '0.5' : '0';
if (state !== 'playing' && state !== 'paused') return;
const p = player;
g2.lineWidth = 1.5; g2.textBaseline = 'middle';
// nearest living enemy
let near = null, nd = Infinity;
for (const e of planes) if (e.team === 1 && e.alive) { const d = e.pos.distanceTo(p.pos); if (d < nd) { nd = d; near = e; } }
// markers on other aircraft
g2.font = '700 12px "Courier New", monospace'; g2.textAlign = 'center';
for (const e of planes) {
if (e === p || e.gone || e.dying) continue;
const s = project(e.pos), d = e.pos.distanceTo(p.pos), enemy = e.team === 1;
const on = s.front && s.x > 20 && s.x < W - 20 && s.y > 20 && s.y < Hh - 20;
g2.strokeStyle = g2.fillStyle = enemy ? REDC : BLUEC;
if (on) {
const r = clamp(2400 / d, 9, 34);
if (enemy) {
g2.beginPath();
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { g2.moveTo(s.x + sx * r, s.y + sy * r * 0.5); g2.lineTo(s.x + sx * r, s.y + sy * r); g2.lineTo(s.x + sx * r * 0.5, s.y + sy * r); }
g2.stroke();
g2.fillText(Math.round(d) + ' m', s.x, s.y + r + 10);
if (e.hp < e.maxHp) bar(s.x - r, s.y - r - 7, r * 2, 3, e.hp / e.maxHp, REDC);
} else {
g2.beginPath(); g2.moveTo(s.x - 6, s.y - r - 2); g2.lineTo(s.x, s.y - r + 5); g2.lineTo(s.x + 6, s.y - r - 2); g2.stroke();
}
} else if (enemy) {
let ax = s.cx, ay = -s.cy; const l = Math.hypot(ax, ay) || 1; ax /= l; ay /= l;
const R = Math.min(W, Hh) * 0.42, x = W / 2 + ax * R, y = Hh / 2 + ay * R, an = Math.atan2(ay, ax);
g2.save(); g2.translate(x, y); g2.rotate(an);
g2.globalAlpha = e === near ? 1 : 0.6;
g2.beginPath(); g2.moveTo(12, 0); g2.lineTo(-7, -8); g2.lineTo(-3, 0); g2.lineTo(-7, 8); g2.closePath(); g2.fill();
g2.restore();
if (e === near) g2.fillText(Math.round(d) + ' m', x - ax * 26, y - ay * 26);
}
}
// gunsight (where the guns point at the range of the nearest target) and lead pip
const range = near && nd < 700 ? nd : 250;
const gs = project(_tmp.copy(p.pos).addScaledVector(p.fwd, range).addScaledVector(p.up, 0.5));
if (gs.front) {
g2.strokeStyle = hitMarker > 0 ? '#fff' : AMBER; g2.lineWidth = 1.6;
g2.beginPath(); g2.arc(gs.x, gs.y, 15, 0, 6.283);
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { g2.moveTo(gs.x + dx * 15, gs.y + dy * 15); g2.lineTo(gs.x + dx * 24, gs.y + dy * 24); }
g2.moveTo(gs.x + 1.5, gs.y); g2.arc(gs.x, gs.y, 1.5, 0, 6.283);
g2.stroke();
if (hitMarker > 0) { g2.beginPath(); for (const [dx, dy] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) { g2.moveTo(gs.x + dx * 6, gs.y + dy * 6); g2.lineTo(gs.x + dx * 12, gs.y + dy * 12); } g2.stroke(); }
}
if (near && nd < 650) {
_tmp.copy(near.vel).sub(p.vel).multiplyScalar(nd / BSPEED).add(near.pos);
const ls = project(_tmp), es = project(near.pos);
if (ls.front && es.front) {
g2.strokeStyle = nd < 400 ? '#fff' : 'rgba(255,255,255,.5)'; g2.lineWidth = 1.3;
g2.beginPath(); g2.arc(ls.x, ls.y, 5, 0, 6.283); g2.stroke();
g2.globalAlpha = 0.35; g2.beginPath(); g2.moveTo(es.x, es.y); g2.lineTo(ls.x, ls.y); g2.stroke(); g2.globalAlpha = 1;
}
}
// instruments, bottom left
const hdg = (Math.atan2(p.fwd.x, -p.fwd.z) * 180 / Math.PI + 360) % 360;
const agl = p.pos.y - Math.max(groundHeight(p.pos.x, p.pos.z), 0);
const px = 18, py = Hh - 150;
panel(px, py, 214, 132);
g2.textAlign = 'left'; g2.font = '700 15px "Courier New", monospace';
const row = (i, label, val, colr = CREAM) => { g2.fillStyle = 'rgba(239,230,207,.6)'; g2.fillText(label, px + 12, py + 20 + i * 21); g2.fillStyle = colr; g2.fillText(val, px + 62, py + 20 + i * 21); };
row(0, 'SPD', String(Math.round(p.speed * 3.6)).padStart(3) + ' km/h', p.speed < 24 ? REDC : CREAM);
row(1, 'ALT', String(Math.round(p.pos.y)).padStart(4) + ' m', agl < 60 ? REDC : CREAM);
row(2, 'HDG', String(Math.round(hdg) % 360).padStart(3, '0') + '° ' + p.gload.toFixed(1) + ' g');
row(3, 'THR', ''); bar(px + 62, py + 78, 138, 9, p.ctrl.throttle, AMBER);
row(4, 'HULL', ''); bar(px + 62, py + 99, 138, 9, p.hp / p.maxHp, p.hp < 35 ? REDC : '#9fcf6a');
g2.font = '11px "Courier New", monospace'; g2.fillStyle = 'rgba(239,230,207,.5)';
g2.fillText(camMode ? 'cockpit view' : 'chase view', px + 12, py + 122);
// score, top left
panel(18, 16, 214, 56);
g2.font = '700 15px "Courier New", monospace'; g2.fillStyle = CREAM;
g2.fillText('WAVE ' + Math.max(wave, 1) + ' SCORE ' + score, 30, 34);
g2.fillStyle = 'rgba(239,230,207,.75)'; g2.font = '13px "Courier New", monospace';
g2.fillText('victories ' + kills + ' bandits ' + planes.filter(e => e.team === 1 && e.alive).length, 30, 55);
// warnings
g2.textAlign = 'center'; g2.font = '700 20px Georgia, serif';
if (p.stall > 0.35 && Math.floor(time * 5) % 2) { g2.fillStyle = REDC; g2.fillText('STALL', W / 2, Hh * 0.7); }
else if (agl < 70 && p.vel.y < -3 && Math.floor(time * 5) % 2) { g2.fillStyle = REDC; g2.fillText('PULL UP', W / 2, Hh * 0.7); }
// radar, bottom right: heading-up, 2.5 km radius
const R = 68, rx = W - R - 22, ry = Hh - R - 22, RANGE = 2500;
g2.fillStyle = 'rgba(12,16,20,.5)'; g2.beginPath(); g2.arc(rx, ry, R, 0, 6.283); g2.fill();
g2.strokeStyle = 'rgba(239,230,207,.3)'; g2.lineWidth = 1;
g2.beginPath(); g2.arc(rx, ry, R, 0, 6.283); g2.moveTo(rx + R * 0.5, ry); g2.arc(rx, ry, R * 0.5, 0, 6.283);
g2.moveTo(rx, ry - R); g2.lineTo(rx, ry + R); g2.moveTo(rx - R, ry); g2.lineTo(rx + R, ry); g2.stroke();
const hr = hdg * Math.PI / 180, sh = Math.sin(hr), ch = Math.cos(hr);
for (const e of planes) {
if (e === p || e.gone || e.dying) continue;
const dx = e.pos.x - p.pos.x, dz = e.pos.z - p.pos.z;
let xr = (dx * ch + dz * sh) / RANGE, yr = (dx * sh - dz * ch) / RANGE;
const l = Math.hypot(xr, yr); if (l > 0.94) { xr *= 0.94 / l; yr *= 0.94 / l; }
g2.fillStyle = e.team === 1 ? REDC : BLUEC;
g2.beginPath(); g2.arc(rx + xr * R, ry - yr * R, e.team === 1 ? 3.2 : 2.4, 0, 6.283); g2.fill();
}
g2.fillStyle = CREAM; g2.beginPath(); g2.moveTo(rx, ry - 6); g2.lineTo(rx - 4, ry + 4); g2.lineTo(rx + 4, ry + 4); g2.closePath(); g2.fill();
g2.font = '11px "Courier New", monospace'; g2.fillStyle = 'rgba(239,230,207,.6)'; g2.textAlign = 'center';
const nAng = -hr; // north marker on the rim
g2.fillText('N', rx + Math.sin(nAng) * (R + 9), ry - Math.cos(nAng) * (R + 9));
}
// =====================================================================================
// Main loop
// =====================================================================================
function resize() {
W = innerWidth; Hh = innerHeight; dpr = Math.min(devicePixelRatio || 1, 2);
renderer.setPixelRatio(dpr); renderer.setSize(W, Hh, false);
hudCanvas.width = Math.round(W * dpr); hudCanvas.height = Math.round(Hh * dpr);
camera.aspect = W / Hh; camera.updateProjectionMatrix();
pMat.uniforms.uScale.value = Hh * dpr / (2 * Math.tan(camera.fov * Math.PI / 360));
}
addEventListener('resize', resize);
resize();
setupFlight(false);
let last = performance.now();
function frame(now) {
requestAnimationFrame(frame);
const dt = Math.min((now - last) / 1000, 0.05); last = now;
if (state !== 'paused') update(dt);
updateCamera(dt);
updateAudio();
drawHUD();
renderer.render(scene, camera);
}
requestAnimationFrame(frame);
window.__booted = true;
// Debug / test hook (used for automated checks from the browser console).
window.__sim = {
THREE, camera, renderer, groundHeight, update, startGame, startWave, stepPlane, damage,
get planes() { return planes; }, get player() { return player; }, get state() { return state; },
set autopilot(v) { autopilot = v; }, log: [],
get stats() { return { state, wave, score, kills, time, bullets: bullets.length }; }
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment