<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>PATROL</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; user-select: none; -webkit-user-select: none; }
html, body {
width: 100%; height: 100%; overflow: hidden;
background: #141020;
font-family: 'JetBrains Mono', monospace;
color: #f4e6d2;
touch-action: none;
}
#stage { position: fixed; inset: 0; width: 100vw; height: 100vh; cursor: crosshair; }
canvas {
position: absolute; inset: 0; width: 100%; height: 100%;
image-rendering: pixelated; image-rendering: crisp-edges; display: block;
}
#hud-canvas { pointer-events: none; }
#loader {
position: fixed; inset: 0; z-index: 40; background: #181226;
display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 18px; transition: opacity 0.45s ease;
}
#loader.done { opacity: 0; pointer-events: none; }
#loader .load-title {
font-family: 'Press Start 2P', monospace; font-size: clamp(22px, 4vw, 38px);
letter-spacing: 0.18em; color: #ffd58c;
text-shadow: 0 4px 0 #5b2e4c, 0 0 24px rgba(255, 168, 92, 0.35);
}
#loader .load-sub { font-size: 11px; letter-spacing: 0.2em; color: #bfa4c4; text-transform: uppercase; }
.bar-wrap { width: min(320px, 78vw); height: 14px; border: 2px solid #8a6d94; background: #100c1a; padding: 2px; }
.bar-fill {
height: 100%; width: 0%;
background: repeating-linear-gradient(90deg, #f7b267 0px, #f7b267 8px, #e67e51 8px, #e67e51 10px);
transition: width 0.08s linear;
}
#load-stage { font-size: 11px; color: #9e8aa8; letter-spacing: 0.08em; min-height: 16px; }
#title-card {
position: fixed; inset: 0; z-index: 20;
display: flex; flex-direction: column; align-items: center; justify-content: center;
pointer-events: none; transition: opacity 0.7s ease; padding-bottom: 10vh;
}
#title-card.hidden { opacity: 0; }
#title-card h1 {
font-family: 'Press Start 2P', monospace; font-size: clamp(28px, 6vw, 60px);
letter-spacing: 0.22em; color: #fff0d0;
text-shadow: 3px 3px 0 #3a1f3d, -2px -2px 0 #3a1f3d, 2px -2px 0 #3a1f3d, -2px 2px 0 #3a1f3d, 0 6px 0 #1f1228;
margin-bottom: 14px;
}
#title-card .tagline {
font-size: clamp(10px, 1.5vw, 13px); letter-spacing: 0.24em; color: #ffdcb2;
text-transform: uppercase; background: rgba(24, 16, 36, 0.58);
padding: 6px 14px; border: 1px solid rgba(255, 206, 148, 0.35);
}
#hint-bar {
position: fixed; left: 0; right: 0; bottom: 0; z-index: 30;
display: flex; align-items: center; justify-content: space-between;
gap: 12px; flex-wrap: wrap; padding: 7px 14px;
background: linear-gradient(to top, rgba(16, 12, 26, 0.82), rgba(16, 12, 26, 0.45));
border-top: 1px solid rgba(255, 210, 160, 0.16);
font-size: 11px; letter-spacing: 0.05em; color: rgba(244, 230, 210, 0.84);
}
.hints { display: flex; flex-wrap: wrap; gap: 10px 14px; align-items: center; }
.hint-item b { color: #ffd38c; font-weight: 600; }
.bar-right { display: flex; align-items: center; gap: 14px; }
#view-badge { color: #c8b4d8; font-size: 10px; letter-spacing: 0.12em; text-transform: uppercase; }
#missile-hud { display: flex; align-items: center; gap: 6px; color: #ffd38c; }
.msl-pips { display: inline-flex; gap: 3px; align-items: center; }
.msl-pip { width: 6px; height: 11px; background: #ff9c54; border: 1px solid #fff0d0; transition: opacity 0.15s; }
.msl-pip.empty { background: rgba(255, 156, 84, 0.14); border-color: rgba(255, 210, 160, 0.25); }
#sound-btn {
background: rgba(34, 24, 52, 0.85); border: 1px solid rgba(255, 208, 152, 0.38);
color: #f4e6d2; font-family: 'JetBrains Mono', monospace; font-size: 10px;
letter-spacing: 0.1em; padding: 4px 9px; cursor: pointer; text-transform: uppercase;
}
#sound-btn:hover { background: rgba(62, 42, 86, 0.92); border-color: #ffd38c; }
#sound-btn.on { color: #8dffb0; border-color: #8dffb0; }
#touch-ui { display: none; position: fixed; inset: 0 0 38px 0; z-index: 25; pointer-events: none; }
#touch-ui.active { display: block; }
#touch-pad {
position: absolute; left: 16px; bottom: 16px; width: 124px; height: 124px;
border-radius: 50%; border: 2px solid rgba(255, 212, 160, 0.42);
background: rgba(20, 14, 34, 0.36); pointer-events: auto;
}
#touch-knob {
position: absolute; left: 50%; top: 50%; width: 38px; height: 38px;
margin: -19px 0 0 -19px; border-radius: 50%; border: 2px solid #ffd58c;
background: rgba(255, 178, 102, 0.45);
}
.touch-btns {
position: absolute; right: 14px; bottom: 16px;
display: grid; grid-template-columns: 1fr 1fr; gap: 10px; pointer-events: auto;
}
.t-btn {
width: 64px; height: 50px; border: 2px solid rgba(255, 212, 160, 0.5);
background: rgba(24, 16, 38, 0.65); color: #fff0d0;
font-family: 'JetBrains Mono', monospace; font-size: 11px; font-weight: 600;
letter-spacing: 0.08em; border-radius: 4px;
}
.t-btn:active, .t-btn.pressed { background: rgba(245, 140, 74, 0.65); border-color: #fff0d0; }
@media (pointer: coarse) { #touch-ui { display: block; } }
</style>
</head>
<body>
<div id="stage">
<canvas id="gl-canvas"></canvas>
<canvas id="hud-canvas"></canvas>
</div>
<div id="loader">
<div class="load-title">PATROL</div>
<div class="load-sub">Autumn Lake Country · Last Light</div>
<div class="bar-wrap"><div class="bar-fill" id="bar-fill"></div></div>
<div id="load-stage">Initializing terrain worker...</div>
</div>
<div id="title-card">
<h1>PATROL</h1>
<div class="tagline">Move mouse to fly · Space to change view</div>
</div>
<div id="touch-ui">
<div id="touch-pad"><div id="touch-knob"></div></div>
<div class="touch-btns">
<button class="t-btn" id="btn-view">VIEW</button>
<button class="t-btn" id="btn-roll">ROLL</button>
<button class="t-btn" id="btn-ab">AB</button>
<button class="t-btn" id="btn-fire">FIRE</button>
</div>
</div>
<div id="hint-bar">
<div class="hints">
<span class="hint-item"><b>MOUSE</b> STEER</span>
<span class="hint-item"><b>CLICK</b> ROLL</span>
<span class="hint-item"><b>HOLD</b> AFTERBURNER</span>
<span class="hint-item"><b>RMB / F</b> MISSILE</span>
<span class="hint-item"><b>SPACE</b> VIEW</span>
</div>
<div class="bar-right">
<span id="view-badge">CHASE</span>
<div id="missile-hud">
<span>MSL</span>
<span class="msl-pips" id="msl-pips">
<span class="msl-pip"></span><span class="msl-pip"></span><span class="msl-pip"></span><span class="msl-pip"></span>
</span>
<span id="msl-count">4/4</span>
</div>
<button id="sound-btn" type="button">SOUND: OFF</button>
</div>
</div>
<script>
(() => {
'use strict';
const MAP_SIZE = 512;
const WORLD_SIZE = 2048.0;
const MAX_TERRAIN_H = 126.0;
const SEA_LEVEL = 25.0;
const CLOUD_Y_MIN = 82.0;
const CLOUD_Y_MAX = 104.0;
const CRUISE_ALT = 128.0;
const SUN_DIR = norm3([-0.76, 0.21, -0.61]);
const CAM_CHASE = 0;
const CAM_COCKPIT = 1;
const CAM_TOP = 2;
const CAM_NAMES = ['CHASE', 'COCKPIT', 'TOP-DOWN'];
function norm3(v) {
const l = Math.hypot(v[0], v[1], v[2]) || 1;
return [v[0] / l, v[1] / l, v[2] / l];
}
function cross3(a, b) {
return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]];
}
function dot3(a, b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }
function add3(a, b) { return [a[0]+b[0], a[1]+b[1], a[2]+b[2]]; }
function sub3(a, b) { return [a[0]-b[0], a[1]-b[1], a[2]-b[2]]; }
function scale3(a, s) { return [a[0]*s, a[1]*s, a[2]*s]; }
function lerp(a, b, t) { return a + (b - a) * t; }
function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; }
function smoothstep(t) { t = clamp(t, 0, 1); return t * t * (3 - 2 * t); }
function lerp3(a, b, t) { return [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]; }
function wrapAngle(a) {
while (a > Math.PI) a -= Math.PI * 2;
while (a < -Math.PI) a += Math.PI * 2;
return a;
}
function mat4Perspective(fovY, aspect, near, far) {
const f = 1.0 / Math.tan(fovY * 0.5);
const nf = 1.0 / (near - far);
return new Float32Array([
f / aspect, 0, 0, 0,
0, f, 0, 0,
0, 0, (far + near) * nf, -1,
0, 0, 2 * far * near * nf, 0
]);
}
function mat4LookBasis(pos, right, up, fwd) {
const zx = -fwd[0], zy = -fwd[1], zz = -fwd[2];
return new Float32Array([
right[0], up[0], zx, 0,
right[1], up[1], zy, 0,
right[2], up[2], zz, 0,
-dot3(right, pos), -dot3(up, pos), -dot3([zx, zy, zz], pos), 1
]);
}
function mat4Mul(a, b) {
const out = new Float32Array(16);
for (let c = 0; c < 4; c++) {
for (let r = 0; r < 4; r++) {
out[c*4 + r] =
a[0*4 + r] * b[c*4 + 0] +
a[1*4 + r] * b[c*4 + 1] +
a[2*4 + r] * b[c*4 + 2] +
a[3*4 + r] * b[c*4 + 3];
}
}
return out;
}
function mat4Model(pos, right, up, fwd, scale = 1.0) {
return new Float32Array([
right[0]*scale, right[1]*scale, right[2]*scale, 0,
up[0]*scale, up[1]*scale, up[2]*scale, 0,
-fwd[0]*scale, -fwd[1]*scale, -fwd[2]*scale, 0,
pos[0], pos[1], pos[2], 1
]);
}
// Inline Web Worker: Seamlessly Tiling Autumn Lake Country Heightfield
function createTerrainWorker() {
const src = `
self.onmessage = function(e) {
const N = e.data.size;
const sunDir = e.data.sunDir;
const seaNorm = e.data.seaNorm;
const maxH = e.data.maxH;
const worldSize = e.data.worldSize;
function hash2(ix, iy, seed) {
let n = (ix * 374761393 + iy * 668265263 + seed * 1442695041) | 0;
n = (n ^ (n >>> 13)) * 1274126177;
n = n ^ (n >>> 16);
return (n >>> 0) / 4294967296;
}
function periodicNoise(u, v, period, seed) {
const x = u * period;
const y = v * period;
const x0 = Math.floor(x);
const y0 = Math.floor(y);
const fx = x - x0;
const fy = y - y0;
const sx = fx * fx * (3 - 2 * fx);
const sy = fy * fy * (3 - 2 * fy);
const ix0 = ((x0 % period) + period) % period;
const iy0 = ((y0 % period) + period) % period;
const ix1 = (ix0 + 1) % period;
const iy1 = (iy0 + 1) % period;
const a = hash2(ix0, iy0, seed);
const b = hash2(ix1, iy0, seed);
const c = hash2(ix0, iy1, seed);
const d = hash2(ix1, iy1, seed);
return (a + (b - a) * sx) + ((c + (d - c) * sx) - (a + (b - a) * sx)) * sy;
}
function fbm(u, v, basePeriod, octaves, seed) {
let sum = 0, amp = 0.5, norm = 0, p = basePeriod;
for (let i = 0; i < octaves; i++) {
sum += amp * periodicNoise(u, v, p, seed + i * 31);
norm += amp;
amp *= 0.5;
p *= 2;
}
return sum / norm;
}
function ridged(u, v, basePeriod, octaves, seed) {
let sum = 0, amp = 0.5, norm = 0, p = basePeriod;
for (let i = 0; i < octaves; i++) {
const n = periodicNoise(u, v, p, seed + i * 53);
const r = 1.0 - Math.abs(n * 2.0 - 1.0);
sum += amp * r * r;
norm += amp;
amp *= 0.48;
p *= 2;
}
return sum / norm;
}
const heights = new Float32Array(N * N);
const biome = new Uint8Array(N * N);
const detail = new Uint8Array(N * N);
self.postMessage({ type: 'progress', pct: 8, stage: 'Sculpting lake basins & autumn ridges...' });
for (let y = 0; y < N; y++) {
const v = y / N;
for (let x = 0; x < N; x++) {
const u = x / N;
const wx = (fbm(u, v, 4, 3, 101) - 0.5) * 0.08;
const wy = (fbm(u, v, 4, 3, 202) - 0.5) * 0.08;
const uu = u + wx;
const vv = v + wy;
const lakeField = fbm(uu, vv, 4, 4, 17);
const coves = fbm(u, v, 16, 3, 41);
const hills = fbm(uu, vv, 8, 4, 73);
const ridge = ridged(uu, vv, 4, 5, 131);
let h = lakeField * 0.62 + hills * 0.28 + coves * 0.10;
h = (h - 0.465) * 1.45 + seaNorm;
const landMask = Math.max(0, Math.min(1, (h - seaNorm) / 0.16));
const peakMask = Math.pow(Math.max(0, fbm(u, v, 2, 3, 307) - 0.36) * 1.65, 1.5);
h += landMask * peakMask * ridge * 0.68;
const islandNoise = fbm(u, v, 16, 2, 419);
if (h < seaNorm && h > seaNorm - 0.09 && islandNoise > 0.66) {
h = seaNorm + (islandNoise - 0.66) * 0.24;
}
h = Math.max(0.0, Math.min(1.0, h));
const idx = y * N + x;
heights[idx] = h;
const b1 = fbm(u, v, 8, 4, 509);
const b2 = periodicNoise(u, v, 32, 601);
biome[idx] = Math.max(0, Math.min(255, Math.floor((b1 * 0.78 + b2 * 0.22) * 255)));
const d1 = periodicNoise(u, v, 64, 709);
const d2 = periodicNoise(u, v, 128, 811);
detail[idx] = Math.max(0, Math.min(255, Math.floor((d1 * 0.65 + d2 * 0.35) * 255)));
}
if ((y & 31) === 31) {
self.postMessage({
type: 'progress',
pct: 8 + Math.floor((y / N) * 44),
stage: 'Sculpting lake basins & autumn ridges...'
});
}
}
self.postMessage({ type: 'progress', pct: 54, stage: 'Baking long twilight shadows...' });
const rgba = new Uint8Array(N * N * 4);
const sunLenXZ = Math.hypot(sunDir[0], sunDir[2]) || 1;
const stepX = sunDir[0] / sunLenXZ;
const stepY = sunDir[2] / sunLenXZ;
const worldPerTexel = worldSize / N;
const sunSlope = (sunDir[1] / sunLenXZ) * (worldPerTexel / maxH);
const MAX_STEPS = 56;
for (let y = 0; y < N; y++) {
for (let x = 0; x < N; x++) {
const idx = y * N + x;
const h0 = Math.max(heights[idx], seaNorm);
let shadow = 1.0;
let rx = x;
let ry = y;
let dist = 0;
for (let s = 1; s <= MAX_STEPS; s++) {
const step = s < 16 ? 1.0 : (s < 32 ? 1.6 : 2.6);
rx += stepX * step;
ry += stepY * step;
dist += step;
const ix = ((Math.floor(rx) % N) + N) % N;
const iy = ((Math.floor(ry) % N) + N) % N;
const hSample = heights[iy * N + ix];
const rayH = h0 + dist * sunSlope;
if (hSample > rayH) {
const pen = (hSample - rayH) * 18.0;
shadow = Math.min(shadow, Math.max(0.0, 1.0 - pen));
if (shadow <= 0.02) { shadow = 0.0; break; }
}
}
const o = idx * 4;
rgba[o + 0] = Math.max(0, Math.min(255, Math.round(heights[idx] * 255)));
rgba[o + 1] = biome[idx];
rgba[o + 2] = Math.max(0, Math.min(255, Math.round(shadow * 255)));
rgba[o + 3] = detail[idx];
}
if ((y & 31) === 31) {
self.postMessage({
type: 'progress',
pct: 54 + Math.floor((y / N) * 42),
stage: 'Baking long twilight shadows...'
});
}
}
self.postMessage({ type: 'progress', pct: 98, stage: 'Uploading world to GPU...' });
self.postMessage({ type: 'done', rgba: rgba.buffer }, [rgba.buffer]);
};
`;
const blob = new Blob([src], { type: 'application/javascript' });
return new Worker(URL.createObjectURL(blob));
}
// Synthesised Web Audio Engine (off by default)
class SoundEngine {
constructor() {
this.enabled = false;
this.ctx = null;
this.master = null;
this.noiseBuf = null;
this.jetGain = null;
this.jetFilter = null;
this.whineOsc = null;
this.whineGain = null;
this.abGain = null;
this.abFilter = null;
this.lastWarnTime = 0;
}
init() {
if (this.ctx) return;
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) return;
this.ctx = new AC();
this.master = this.ctx.createGain();
this.master.gain.value = 0.0;
this.master.connect(this.ctx.destination);
const len = this.ctx.sampleRate * 2;
this.noiseBuf = this.ctx.createBuffer(1, len, this.ctx.sampleRate);
const d = this.noiseBuf.getChannelData(0);
let b0 = 0, b1 = 0, b2 = 0;
for (let i = 0; i < len; i++) {
const w = Math.random() * 2 - 1;
b0 = 0.997 * b0 + w * 0.029;
b1 = 0.985 * b1 + w * 0.032;
b2 = 0.950 * b2 + w * 0.048;
d[i] = (b0 + b1 + b2 + w * 0.14) * 0.65;
}
const jetSrc = this.ctx.createBufferSource();
jetSrc.buffer = this.noiseBuf;
jetSrc.loop = true;
this.jetFilter = this.ctx.createBiquadFilter();
this.jetFilter.type = 'bandpass';
this.jetFilter.frequency.value = 340;
this.jetFilter.Q.value = 0.7;
this.jetGain = this.ctx.createGain();
this.jetGain.gain.value = 0.18;
jetSrc.connect(this.jetFilter).connect(this.jetGain).connect(this.master);
jetSrc.start();
this.whineOsc = this.ctx.createOscillator();
this.whineOsc.type = 'triangle';
this.whineOsc.frequency.value = 260;
this.whineGain = this.ctx.createGain();
this.whineGain.gain.value = 0.018;
this.whineOsc.connect(this.whineGain).connect(this.master);
this.whineOsc.start();
const abSrc = this.ctx.createBufferSource();
abSrc.buffer = this.noiseBuf;
abSrc.loop = true;
this.abFilter = this.ctx.createBiquadFilter();
this.abFilter.type = 'lowpass';
this.abFilter.frequency.value = 220;
this.abGain = this.ctx.createGain();
this.abGain.gain.value = 0.0;
abSrc.connect(this.abFilter).connect(this.abGain).connect(this.master);
abSrc.start();
}
toggle() {
this.enabled = !this.enabled;
if (this.enabled) {
this.init();
if (this.ctx && this.ctx.state === 'suspended') this.ctx.resume();
if (this.master) this.master.gain.setTargetAtTime(0.45, this.ctx.currentTime, 0.08);
} else if (this.master && this.ctx) {
this.master.gain.setTargetAtTime(0.0, this.ctx.currentTime, 0.06);
}
return this.enabled;
}
update(speedNorm, abBlend, inCockpit, pullUp) {
if (!this.enabled || !this.ctx) return;
const t = this.ctx.currentTime;
const muffle = inCockpit ? 0.65 : 1.0;
this.jetFilter.frequency.setTargetAtTime((280 + speedNorm * 420) * muffle, t, 0.08);
this.jetGain.gain.setTargetAtTime((0.14 + speedNorm * 0.14) * muffle, t, 0.08);
this.whineOsc.frequency.setTargetAtTime(220 + speedNorm * 240 + abBlend * 90, t, 0.08);
this.whineGain.gain.setTargetAtTime(0.014 + abBlend * 0.02, t, 0.08);
this.abGain.gain.setTargetAtTime(abBlend * 0.42 * muffle, t, 0.06);
this.abFilter.frequency.setTargetAtTime(170 + abBlend * 260, t, 0.06);
if (pullUp && inCockpit && t - this.lastWarnTime > 0.55) {
this.lastWarnTime = t;
this.playBeep(880, 0.07, 0.06);
setTimeout(() => { if (this.enabled) this.playBeep(660, 0.07, 0.05); }, 95);
}
}
playBeep(freq, dur, vol) {
if (!this.enabled || !this.ctx) return;
const t = this.ctx.currentTime;
const o = this.ctx.createOscillator();
const g = this.ctx.createGain();
o.type = 'square';
o.frequency.value = freq;
g.gain.setValueAtTime(vol, t);
g.gain.exponentialRampToValueAtTime(0.001, t + dur);
o.connect(g).connect(this.master);
o.start(t); o.stop(t + dur);
}
playRoll() {
if (!this.enabled || !this.ctx || !this.noiseBuf) return;
const t = this.ctx.currentTime;
const src = this.ctx.createBufferSource();
src.buffer = this.noiseBuf;
const f = this.ctx.createBiquadFilter();
f.type = 'bandpass';
f.frequency.setValueAtTime(320, t);
f.frequency.exponentialRampToValueAtTime(1100, t + 0.18);
f.frequency.exponentialRampToValueAtTime(260, t + 0.48);
const g = this.ctx.createGain();
g.gain.setValueAtTime(0.01, t);
g.gain.linearRampToValueAtTime(0.24, t + 0.16);
g.gain.exponentialRampToValueAtTime(0.001, t + 0.52);
src.connect(f).connect(g).connect(this.master);
src.start(t); src.stop(t + 0.55);
}
playMissile() {
if (!this.enabled || !this.ctx || !this.noiseBuf) return;
const t = this.ctx.currentTime;
const src = this.ctx.createBufferSource();
src.buffer = this.noiseBuf;
const f = this.ctx.createBiquadFilter();
f.type = 'bandpass';
f.frequency.setValueAtTime(1400, t);
f.frequency.exponentialRampToValueAtTime(280, t + 0.55);
f.Q.value = 1.2;
const g = this.ctx.createGain();
g.gain.setValueAtTime(0.38, t);
g.gain.exponentialRampToValueAtTime(0.001, t + 0.6);
src.connect(f).connect(g).connect(this.master);
src.start(t); src.stop(t + 0.62);
}
playExplosion(isWater) {
if (!this.enabled || !this.ctx || !this.noiseBuf) return;
const t = this.ctx.currentTime;
const osc = this.ctx.createOscillator();
const og = this.ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(isWater ? 95 : 130, t);
osc.frequency.exponentialRampToValueAtTime(28, t + 0.45);
og.gain.setValueAtTime(isWater ? 0.32 : 0.48, t);
og.gain.exponentialRampToValueAtTime(0.001, t + 0.55);
osc.connect(og).connect(this.master);
osc.start(t); osc.stop(t + 0.58);
const src = this.ctx.createBufferSource();
src.buffer = this.noiseBuf;
const f = this.ctx.createBiquadFilter();
f.type = isWater ? 'bandpass' : 'lowpass';
f.frequency.setValueAtTime(isWater ? 950 : 620, t);
f.frequency.exponentialRampToValueAtTime(isWater ? 340 : 120, t + 0.9);
const g = this.ctx.createGain();
g.gain.setValueAtTime(isWater ? 0.34 : 0.44, t);
g.gain.exponentialRampToValueAtTime(0.001, t + 0.95);
src.connect(f).connect(g).connect(this.master);
src.start(t); src.stop(t + 1.0);
}
}
// Procedural low-poly twin-engine twin-tail fighter & missile meshes
function buildFighterGeometry() {
const pos = [], norm = [], col = [], flag = [];
function tri(a, b, c, rgb, f = 0) {
const n = norm3(cross3(sub3(b, a), sub3(c, a)));
for (const p of [a, b, c]) {
pos.push(p[0], p[1], p[2]);
norm.push(n[0], n[1], n[2]);
col.push(rgb[0], rgb[1], rgb[2]);
flag.push(f);
}
}
function quad(a, b, c, d, rgb, f = 0) { tri(a, b, c, rgb, f); tri(a, c, d, rgb, f); }
function symTri(a, b, c, rgb, f = 0) {
tri(a, b, c, rgb, f);
tri([-a[0], a[1], a[2]], [-c[0], c[1], c[2]], [-b[0], b[1], b[2]], rgb, f);
}
function symQuad(a, b, c, d, rgb, f = 0) {
quad(a, b, c, d, rgb, f);
quad([-a[0], a[1], a[2]], [-d[0], d[1], d[2]], [-c[0], c[1], c[2]], [-b[0], b[1], b[2]], rgb, f);
}
const C_RADOME = [0.16, 0.17, 0.24];
const C_LIGHT = [0.64, 0.68, 0.75];
const C_MID = [0.43, 0.48, 0.56];
const C_DARK = [0.28, 0.32, 0.40];
const C_BELLY = [0.48, 0.52, 0.60];
const C_CANOPY = [0.86, 0.66, 0.24];
const C_RED = [0.84, 0.22, 0.24];
const C_NOZ = [1.00, 0.56, 0.18];
const nose = [0, -0.05, -7.8], nTop = [0, 0.42, -4.4], nBot = [0, -0.45, -4.4], nSide = [0.68, -0.05, -4.4];
symTri(nose, nSide, nTop, C_RADOME);
symTri(nose, nBot, nSide, C_RADOME);
const fTop = [0, 0.65, -1.6], fBot = [0, -0.58, -1.6], fUpS = [1.05, 0.30, -1.6], fLoS = [1.08, -0.42, -1.6];
symQuad(nTop, nSide, fUpS, fTop, C_LIGHT);
symTri(nSide, fLoS, fUpS, C_DARK);
symQuad(nBot, fBot, fLoS, nSide, C_BELLY);
const cFront = [0, 0.50, -4.0], cMidT = [0, 1.24, -2.5], cBackT = [0, 1.05, -0.5], cRear = [0, 0.68, 0.7];
const cSideF = [0.56, 0.48, -2.5], cSideB = [0.52, 0.54, -0.5];
symTri(cFront, cSideF, cMidT, C_CANOPY, 2);
symQuad(cMidT, cSideF, cSideB, cBackT, C_CANOPY, 2);
symTri(cBackT, cSideB, cRear, C_CANOPY, 2);
const mTop = [0, 0.68, 0.7], aTop = [0, 0.62, 5.2], mBot = [0, -0.56, 0.7], aBot = [0, -0.45, 5.2];
const mUpS = [1.35, 0.28, 0.7], mLoS = [1.35, -0.40, 0.7], aUpS = [1.38, 0.38, 5.2], aLoS = [1.35, -0.34, 5.2];
symTri(fTop, fUpS, mTop, C_MID);
symTri(fUpS, mUpS, mTop, C_DARK);
symTri(mTop, mUpS, aTop, C_LIGHT);
symTri(mUpS, aUpS, aTop, C_MID);
symQuad(fUpS, fLoS, mLoS, mUpS, C_DARK);
symQuad(mUpS, mLoS, aLoS, aUpS, C_MID);
symQuad(fBot, mBot, mLoS, fLoS, C_BELLY);
symQuad(mBot, aBot, aLoS, mLoS, C_BELLY);
const tailTip = [0, 0.12, 6.4];
symTri(aTop, [0.45, 0.25, 5.2], tailTip, C_DARK);
symTri([0.45, 0.25, 5.2], [0.45, -0.22, 5.2], tailTip, C_DARK);
symTri(aBot, tailTip, [0.45, -0.22, 5.2], C_BELLY);
for (const sgn of [-1, 1]) {
const cx = sgn * 0.86, cy = 0.02, z0 = 5.0, z1 = 6.2, r0 = 0.44, r1 = 0.34, segs = 6;
for (let i = 0; i < segs; i++) {
const a0 = (i / segs) * Math.PI * 2, a1 = ((i + 1) / segs) * Math.PI * 2;
const p0 = [cx + Math.cos(a0)*r0, cy + Math.sin(a0)*r0, z0];
const p1 = [cx + Math.cos(a1)*r0, cy + Math.sin(a1)*r0, z0];
const p2 = [cx + Math.cos(a1)*r1, cy + Math.sin(a1)*r1, z1];
const p3 = [cx + Math.cos(a0)*r1, cy + Math.sin(a0)*r1, z1];
quad(p0, p3, p2, p1, C_DARK);
const g0 = [cx + Math.cos(a0)*(r1*0.86), cy + Math.sin(a0)*(r1*0.86), z1 + 0.02];
const g1 = [cx + Math.cos(a1)*(r1*0.86), cy + Math.sin(a1)*(r1*0.86), z1 + 0.02];
tri([cx, cy, z1 + 0.02], g0, g1, C_NOZ, 1);
}
}
const wRF = [1.22, 0.04, -1.5], wRM = [1.30, 0.05, 1.4], wRR = [1.32, 0.04, 3.6];
const wTF = [5.65, -0.06, 1.9], wTR = [5.65, -0.06, 3.35], wMid = [3.4, 0.0, 1.8], thk = 0.14;
symTri(wRF, wTF, wMid, C_LIGHT);
symTri(wRF, wMid, wRM, C_DARK);
symTri(wRM, wMid, wRR, C_MID);
symTri(wMid, wTF, wTR, C_DARK);
symTri(wMid, wTR, wRR, C_LIGHT);
const bRF = [wRF[0], wRF[1]-thk, wRF[2]], bRR = [wRR[0], wRR[1]-thk, wRR[2]];
const bTF = [wTF[0], wTF[1]-thk*0.6, wTF[2]], bTR = [wTR[0], wTR[1]-thk*0.6, wTR[2]];
symTri(bRF, bRR, bTF, C_BELLY);
symTri(bTF, bRR, bTR, C_BELLY);
symQuad(wRF, bRF, bTF, wTF, C_DARK);
symQuad(wTF, bTF, bTR, wTR, C_RED);
symQuad(wTR, bTR, bRR, wRR, C_DARK);
const finBF = [1.18, 0.36, 2.7], finBR = [1.22, 0.36, 5.4];
const finMF = [1.74, 1.85, 4.15], finMR = [1.76, 1.85, 5.55];
const finTF = [1.92, 2.38, 4.65], finTR = [1.92, 2.38, 5.62], ft = 0.09;
symQuad(finBF, finBR, finMR, finMF, C_MID);
symQuad([finBF[0]-ft, finBF[1], finBF[2]], [finMF[0]-ft, finMF[1], finMF[2]], [finMR[0]-ft, finMR[1], finMR[2]], [finBR[0]-ft, finBR[1], finBR[2]], C_DARK);
symQuad(finMF, finMR, finTR, finTF, C_RED);
symQuad([finMF[0]-ft, finMF[1], finMF[2]], [finTF[0]-ft, finTF[1], finTF[2]], [finTR[0]-ft, finTR[1], finTR[2]], [finMR[0]-ft, finMR[1], finMR[2]], C_RED);
symQuad(finTF, finTR, [finTR[0]-ft, finTR[1], finTR[2]], [finTF[0]-ft, finTF[1], finTF[2]], C_RED);
const stRF = [1.30, 0.0, 4.2], stRR = [1.30, 0.0, 5.65], stTF = [3.25, -0.14, 5.35], stTR = [3.25, -0.14, 6.25];
symQuad(stRF, stTF, stTR, stRR, C_DARK);
symQuad([stRF[0], stRF[1]-0.08, stRF[2]], [stRR[0], stRR[1]-0.08, stRR[2]], [stTR[0], stTR[1]-0.08, stTR[2]], [stTF[0], stTF[1]-0.08, stTF[2]], C_BELLY);
return { pos: new Float32Array(pos), norm: new Float32Array(norm), col: new Float32Array(col), flag: new Float32Array(flag), count: pos.length / 3 };
}
function buildMissileGeometry() {
const pos = [], norm = [], col = [], flag = [];
function tri(a, b, c, rgb, f = 0) {
const n = norm3(cross3(sub3(b, a), sub3(c, a)));
for (const p of [a, b, c]) {
pos.push(p[0], p[1], p[2]); norm.push(n[0], n[1], n[2]); col.push(rgb[0], rgb[1], rgb[2]); flag.push(f);
}
}
const C_BODY = [0.92, 0.90, 0.86], C_NOSE = [0.20, 0.22, 0.28], C_RED = [0.88, 0.24, 0.24];
const r = 0.16, zF = -1.35, zN = -1.95, zB = 1.25;
const pts = [[r,0],[0,r],[-r,0],[0,-r]];
for (let i = 0; i < 4; i++) {
const p0 = pts[i], p1 = pts[(i+1)%4];
tri([0,0,zN], [p1[0],p1[1],zF], [p0[0],p0[1],zF], C_NOSE);
tri([p0[0],p0[1],zF], [p1[0],p1[1],zF], [p1[0],p1[1],zB], C_BODY);
tri([p0[0],p0[1],zF], [p1[0],p1[1],zB], [p0[0],p0[1],zB], C_BODY);
tri([0,0,zB], [p0[0],p0[1],zB], [p1[0],p1[1],zB], C_RED);
}
for (let i = 0; i < 4; i++) {
const ang = (i * Math.PI) / 2 + Math.PI / 4, dx = Math.cos(ang), dy = Math.sin(ang);
const a = [dx*r, dy*r, 0.55], b = [dx*0.44, dy*0.44, 1.22], c = [dx*r, dy*r, 1.22];
tri(a, b, c, C_RED); tri(a, c, b, C_RED);
}
return { pos: new Float32Array(pos), norm: new Float32Array(norm), col: new Float32Array(col), flag: new Float32Array(flag), count: pos.length / 3 };
}
// WebGL2 GLSL Shaders
const VS_FULLSCREEN = `#version 300 es
precision highp float;
out vec2 vUv;
void main() {
vec2 p = vec2((gl_VertexID & 1) << 2, (gl_VertexID & 2) << 1) - 1.0;
vUv = p * 0.5 + 0.5;
gl_Position = vec4(p, 0.0, 1.0);
}`;
const FS_WORLD = `#version 300 es
precision highp float;
in vec2 vUv;
out vec4 outColor;
uniform sampler2D uTerrain;
uniform vec2 uRes;
uniform float uTime;
uniform vec3 uCamPos;
uniform vec3 uCamRight;
uniform vec3 uCamUp;
uniform vec3 uCamFwd;
uniform float uTanHalfFov;
uniform float uAspect;
uniform float uNear;
uniform float uFar;
uniform vec3 uSunDir;
uniform vec3 uJetPos;
uniform vec3 uJetFwd;
uniform float uJetAltAboveWater;
uniform vec4 uImpacts[12];
const float WORLD_SIZE = 2048.0;
const float MAX_H = 126.0;
const float SEA_LEVEL = 25.0;
const float CLOUD_Y0 = 82.0;
const float CLOUD_Y1 = 104.0;
float bayer4(ivec2 p) {
int idx = (p.y & 3) * 4 + (p.x & 3);
const int m[16] = int[16](0,8,2,10, 12,4,14,6, 3,11,1,9, 15,7,13,5);
return (float(m[idx]) + 0.5) / 16.0;
}
vec3 ditherMix(vec3 a, vec3 b, float t, float bayer) {
return step(bayer, clamp(t, 0.0, 1.0)) > 0.5 ? b : a;
}
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float vnoise(vec2 p) {
vec2 i = floor(p), f = fract(p);
f = f * f * (3.0 - 2.0 * f);
return mix(mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x),
mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y);
}
float cloudDensity(vec2 xz) {
vec2 p = xz * 0.0024 + vec2(uTime * 0.006, uTime * 0.0025);
float n = vnoise(p * 3.0) * 0.55 + vnoise(p * 6.5 + 11.3) * 0.30 + vnoise(p * 13.0 + 27.1) * 0.15;
return smoothstep(0.54, 0.78, n);
}
vec4 sampleTerrain(vec2 xz) { return texture(uTerrain, xz / WORLD_SIZE); }
float terrainH(vec2 xz) { return sampleTerrain(xz).r * MAX_H; }
vec3 horizonColor(vec3 rd) {
float sunAmt = clamp(dot(normalize(vec3(rd.x, 0.0, rd.z)), normalize(vec3(uSunDir.x, 0.0, uSunDir.z))) * 0.5 + 0.5, 0.0, 1.0);
vec3 lilac = vec3(0.66, 0.52, 0.72);
vec3 rose = vec3(0.86, 0.55, 0.54);
vec3 gold = vec3(0.98, 0.78, 0.44);
return sunAmt < 0.5 ? mix(lilac, rose, sunAmt * 2.0) : mix(rose, gold, (sunAmt - 0.5) * 2.0);
}
vec3 renderSky(vec3 rd, float bayer) {
float sunDot = dot(rd, uSunDir);
float sunSide = clamp(sunDot * 0.5 + 0.5, 0.0, 1.0);
float el = clamp(rd.y, 0.0, 1.0);
vec3 cHoriz = horizonColor(rd);
vec3 cLow = mix(vec3(0.55, 0.38, 0.58), vec3(0.92, 0.54, 0.40), pow(sunSide, 1.3));
vec3 cMid = mix(vec3(0.30, 0.24, 0.44), vec3(0.58, 0.34, 0.48), pow(sunSide, 1.6));
vec3 cTop = vec3(0.15, 0.13, 0.27);
vec3 col = el < 0.14 ? ditherMix(cHoriz, cLow, el / 0.14, bayer)
: el < 0.38 ? ditherMix(cLow, cMid, (el - 0.14) / 0.24, bayer)
: ditherMix(cMid, cTop, clamp((el - 0.38) / 0.45, 0.0, 1.0), bayer);
if (rd.y > 0.04) {
vec2 sp = rd.xz / (rd.y + 0.18);
float streak = vnoise(vec2(sp.x * 0.65 + uTime * 0.008, sp.y * 4.2)) * 0.65
+ vnoise(vec2(sp.x * 1.4 - uTime * 0.005, sp.y * 9.0)) * 0.35;
float sMask = smoothstep(0.64, 0.80, streak) * smoothstep(0.04, 0.16, rd.y) * smoothstep(0.65, 0.18, rd.y);
vec3 streakCol = mix(vec3(0.82, 0.60, 0.72), vec3(0.99, 0.82, 0.56), pow(sunSide, 1.1));
col = ditherMix(col, streakCol, sMask * 0.78, bayer);
}
if (sunDot > 0.965) col = ditherMix(col, vec3(0.99, 0.82, 0.46), smoothstep(0.965, 0.994, sunDot) * 0.85, bayer);
if (sunDot > 0.9958) col = vec3(1.00, 0.96, 0.82);
else if (sunDot > 0.9938) col = ditherMix(vec3(0.99, 0.80, 0.44), vec3(1.00, 0.96, 0.82), (sunDot - 0.9938) / 0.002, bayer);
return col;
}
float jetShadowMask(vec3 worldPos) {
if (uJetPos.y <= worldPos.y + 1.0) return 0.0;
float t = (uJetPos.y - worldPos.y) / max(0.08, uSunDir.y);
vec2 d = (worldPos.xz + uSunDir.xz * t) - uJetPos.xz;
vec2 jf = normalize(uJetFwd.xz + vec2(0.0001));
vec2 jr = vec2(-jf.y, jf.x);
float along = dot(d, jf), across = dot(d, jr);
return max(step(abs(across), 1.6) * step(abs(along), 7.2),
step(abs(across), 5.6) * step(abs(along + 1.2), 2.3));
}
void main() {
float bayer = bayer4(ivec2(gl_FragCoord.xy));
vec2 ndc = (gl_FragCoord.xy / uRes) * 2.0 - 1.0;
vec3 rd = normalize(uCamRight * (ndc.x * uAspect * uTanHalfFov) + uCamUp * (ndc.y * uTanHalfFov) + uCamFwd);
vec3 col = renderSky(rd, bayer);
float hitT = uFar * 0.995;
bool hitTerrain = false;
float maxDist = 1750.0, tStart = 0.5;
if (uCamPos.y > MAX_H + 2.0 && rd.y < -0.001) tStart = max(0.5, (MAX_H + 1.0 - uCamPos.y) / rd.y);
if (tStart < maxDist && (uCamPos.y <= MAX_H + 2.0 || rd.y < -0.001)) {
float t = tStart, prevT = t;
for (int i = 0; i < 96; i++) {
vec3 p = uCamPos + rd * t;
if (p.y > MAX_H + 4.0 && rd.y > 0.0) break;
float h = max(terrainH(p.xz), SEA_LEVEL);
if (p.y <= h) {
float lo = prevT, hi = t;
for (int j = 0; j < 5; j++) {
float mid = 0.5 * (lo + hi);
vec3 pm = uCamPos + rd * mid;
if (pm.y <= max(terrainH(pm.xz), SEA_LEVEL)) hi = mid; else lo = mid;
}
hitT = hi; hitTerrain = true; break;
}
prevT = t;
t += max(1.4, min(max(1.0, p.y - h) * 0.52, t * 0.024 + 1.8));
if (t > maxDist) break;
}
}
if (hitTerrain) {
vec3 p = uCamPos + rd * hitT;
vec4 data = sampleTerrain(p.xz);
float rawH = data.r * MAX_H, biome = data.g, bakedSun = data.b, detail = data.a;
float tC = (CLOUD_Y0 - p.y) / max(0.1, uSunDir.y);
float cShad = tC > 0.0 ? cloudDensity(p.xz + uSunDir.xz * tC) : 0.0;
float sunVis = bakedSun * (1.0 - cShad * 0.65) * (1.0 - jetShadowMask(p) * 0.72);
if (rawH <= SEA_LEVEL + 0.12) {
float depth = max(0.0, SEA_LEVEL - rawH);
vec3 cShal = vec3(0.45, 0.79, 0.76), cTeal = vec3(0.24, 0.58, 0.62);
vec3 cBlue = vec3(0.16, 0.36, 0.49), cNavy = vec3(0.10, 0.20, 0.34);
vec3 wCol = depth < 3.5 ? ditherMix(cShal, cTeal, depth / 3.5, bayer)
: depth < 9.5 ? ditherMix(cTeal, cBlue, (depth - 3.5) / 6.0, bayer)
: ditherMix(cBlue, cNavy, clamp((depth - 9.5) / 10.0, 0.0, 1.0), bayer);
vec3 wShadCol = mix(wCol * vec3(0.56, 0.48, 0.76), vec3(0.14, 0.13, 0.28), 0.32);
wCol = ditherMix(wShadCol, wCol, sunVis, bayer);
float wavePhase = sin(uTime * 2.4 + detail * 10.0 + p.x * 0.15 + p.z * 0.15);
float foamBand = smoothstep(2.1 + wavePhase * 0.55, 0.15, depth);
if (foamBand > 0.25 && depth < 2.8) wCol = ditherMix(wCol, vec3(0.96, 0.93, 0.87), foamBand * 0.9, bayer);
float fres = pow(1.0 - clamp(-rd.y, 0.0, 1.0), 3.2);
wCol = ditherMix(wCol, horizonColor(vec3(rd.x, abs(rd.y), rd.z)), fres * 0.68, bayer);
float glint = step(0.865, vnoise(vec2(p.x * 0.22 + uTime * 1.1, p.z * 0.85 - uTime * 0.6))) * (0.4 + 0.6 * sunVis) * smoothstep(950.0, 120.0, hitT);
if (glint > 0.5) wCol = vec3(0.98, 0.95, 0.88);
float spec = max(0.0, dot(reflect(rd, vec3(0.0, 1.0, 0.0)), uSunDir));
float rip = vnoise(vec2(p.x * 0.35 + uTime * 1.6, p.z * 0.9 - uTime * 0.9));
float glitter = pow(spec, 38.0) * (0.55 + 0.9 * rip) * sunVis;
if (glitter > 0.16) wCol = ditherMix(wCol, vec3(1.00, 0.84, 0.46), clamp(glitter * 2.2, 0.0, 1.0), bayer);
if (glitter > 0.52) wCol = vec3(1.00, 0.97, 0.84);
if (uJetAltAboveWater < 24.0) {
vec2 toP = p.xz - uJetPos.xz, jf = normalize(uJetFwd.xz + vec2(0.0001)), jr = vec2(-jf.y, jf.x);
float back = -dot(toP, jf), side = abs(dot(toP, jr));
if (back > 2.0 && back < 65.0) {
float strength = (1.0 - uJetAltAboveWater / 24.0) * (1.0 - back / 65.0);
if (abs(side - (1.6 + back * 0.24)) < 2.2 && strength > 0.12)
wCol = ditherMix(wCol, vec3(0.95, 0.95, 0.92), strength * 0.95, bayer);
}
}
for (int k = 0; k < 12; k++) {
float age = uImpacts[k].w;
if (age < -0.001) {
float a = -age, d = length(p.xz - uImpacts[k].xz);
float ring = smoothstep(4.5, 0.5, abs(d - (a * 26.0 + 3.0))) * max(0.0, 1.0 - a / 5.5);
float cFoam = smoothstep(11.0, 1.0, d) * max(0.0, 1.0 - a / 8.0);
wCol = ditherMix(wCol, vec3(0.96, 0.95, 0.90), clamp(ring + cFoam * 0.85, 0.0, 1.0), bayer);
}
}
col = wCol;
} else {
float e = WORLD_SIZE / 512.0;
vec3 nrm = normalize(vec3(terrainH(p.xz - vec2(e,0.0)) - terrainH(p.xz + vec2(e,0.0)), 2.0 * e,
terrainH(p.xz - vec2(0.0,e)) - terrainH(p.xz + vec2(0.0,e))));
float slope = 1.0 - nrm.y, alt = rawH - SEA_LEVEL;
vec3 cSand = vec3(0.84, 0.72, 0.54), cMeadow = vec3(0.71, 0.67, 0.44);
vec3 cOrange = vec3(0.85, 0.42, 0.18), cCrimson = vec3(0.69, 0.21, 0.24);
vec3 cGold = vec3(0.88, 0.66, 0.21), cConifer = vec3(0.15, 0.25, 0.22);
vec3 cRock = vec3(0.45, 0.40, 0.50), cSnow = vec3(0.95, 0.91, 0.88);
vec3 albedo;
if (alt < 2.2 && slope < 0.22) albedo = cSand;
else if (alt > 68.0 - slope * 22.0) albedo = cSnow;
else if (slope > 0.26 || alt > 50.0) albedo = ditherMix(cRock, cSnow, smoothstep(54.0, 68.0, alt) * (1.0 - slope * 1.4), bayer);
else if (biome < 0.26 && alt < 16.0) albedo = cMeadow;
else {
albedo = biome < 0.48 ? ditherMix(cGold, cOrange, (biome - 0.26) / 0.22, bayer)
: biome < 0.72 ? ditherMix(cOrange, cCrimson, (biome - 0.48) / 0.24, bayer)
: ditherMix(cCrimson, cGold, (biome - 0.72) / 0.28, bayer);
float pine = vnoise(p.xz * 0.16);
if (pine > 0.70 || (detail > 0.78 && pine > 0.54)) albedo = cConifer;
}
float terraceShade = fract(alt * 0.14) < 0.22 ? 0.88 : 1.0;
float lit = max(0.0, dot(nrm, uSunDir)) * sunVis * terraceShade;
vec3 shT = albedo * vec3(0.44, 0.36, 0.62), mdT = albedo * vec3(0.92, 0.80, 0.74), snT = albedo * vec3(1.16, 1.02, 0.82);
col = lit < 0.26 ? ditherMix(shT, mdT, lit / 0.26, bayer) : ditherMix(mdT, snT, clamp((lit - 0.26) / 0.48, 0.0, 1.0), bayer);
for (int k = 0; k < 12; k++) {
float age = uImpacts[k].w;
if (age > 0.001) {
float d = length(p.xz - uImpacts[k].xz), fade = max(0.0, 1.0 - age / 24.0);
if (d < 13.0 && fade > 0.01) {
col = ditherMix(col, vec3(0.11, 0.08, 0.12), smoothstep(12.0, 3.0, d) * fade * 0.92, bayer);
float emb = vnoise(p.xz * 0.75 + vec2(0.0, uTime * 1.5));
if (d < 7.5 && emb > 0.62 && age < 14.0) {
vec3 eCol = sin(uTime * 11.0 + d * 3.0) > 0.0 ? vec3(1.0, 0.62, 0.18) : vec3(0.92, 0.24, 0.14);
col = ditherMix(col, eCol, (1.0 - age / 14.0) * 0.95, bayer);
}
}
}
}
}
col = ditherMix(col, horizonColor(rd), smoothstep(320.0, 1620.0, hitT), bayer);
}
float tEnter = -1.0, tExit = -1.0;
if (abs(rd.y) > 0.002) {
float t0 = (CLOUD_Y0 - uCamPos.y) / rd.y, t1 = (CLOUD_Y1 - uCamPos.y) / rd.y;
tEnter = min(t0, t1); tExit = max(t0, t1);
} else if (uCamPos.y >= CLOUD_Y0 && uCamPos.y <= CLOUD_Y1) { tEnter = 2.0; tExit = 900.0; }
if (tExit > 0.5 && tEnter < hitT) {
float ts = max(0.5, tEnter), te = min(hitT, min(tExit, 1450.0));
if (te > ts) {
float cloudHitT = -1.0, cloudHFrac = 0.0;
vec3 cloudP = vec3(0.0);
const int CSTEPS = 10;
float dt = (te - ts) / float(CSTEPS);
for (int i = 0; i < CSTEPS; i++) {
float tc = ts + (float(i) + bayer * 0.85) * dt;
vec3 cp = uCamPos + rd * tc;
float hFrac = (cp.y - CLOUD_Y0) / (CLOUD_Y1 - CLOUD_Y0);
float dome = smoothstep(0.0, 0.22, hFrac) * smoothstep(1.0, 0.30, hFrac);
if (cloudDensity(cp.xz) * dome > 0.26) { cloudHitT = tc; cloudHFrac = hFrac; cloudP = cp; break; }
}
if (cloudHitT > 0.0) {
float cLit = clamp(cloudHFrac * 0.95 + (1.0 - cloudDensity(cloudP.xz + uSunDir.xz * 26.0)) * 0.45 - 0.12, 0.0, 1.0);
cLit *= (1.0 - jetShadowMask(cloudP) * 0.65);
vec3 cBase = vec3(0.37, 0.26, 0.44), cRose = vec3(0.70, 0.44, 0.53);
vec3 cPch = vec3(0.95, 0.67, 0.52), cTop = vec3(1.00, 0.90, 0.78);
vec3 cCol = cLit < 0.33 ? ditherMix(cBase, cRose, cLit / 0.33, bayer)
: cLit < 0.66 ? ditherMix(cRose, cPch, (cLit - 0.33) / 0.33, bayer)
: ditherMix(cPch, cTop, (cLit - 0.66) / 0.34, bayer);
col = ditherMix(cCol, horizonColor(rd), smoothstep(380.0, 1450.0, cloudHitT), bayer);
hitT = cloudHitT;
}
}
}
float zView = -hitT * dot(rd, uCamFwd);
float zNdc = (-(uFar + uNear) * zView - 2.0 * uFar * uNear) / ((uFar - uNear) * (-zView));
gl_FragDepth = clamp(zNdc * 0.5 + 0.5, 0.0, 0.99999);
outColor = vec4(col, 1.0);
}`;
const VS_MESH = `#version 300 es
precision highp float;
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNorm;
layout(location = 2) in vec3 aCol;
layout(location = 3) in float aFlag;
uniform mat4 uVP, uModel;
uniform mat3 uNormalMat;
out vec3 vNorm, vCol, vWorldPos;
out float vFlag;
void main() {
vec4 wp = uModel * vec4(aPos, 1.0);
vWorldPos = wp.xyz;
vNorm = normalize(uNormalMat * aNorm);
vCol = aCol; vFlag = aFlag;
gl_Position = uVP * wp;
}`;
const FS_MESH = `#version 300 es
precision highp float;
in vec3 vNorm, vCol, vWorldPos;
in float vFlag;
out vec4 outColor;
uniform vec3 uSunDir, uCamPos;
uniform float uAB;
void main() {
if (vFlag > 0.5 && vFlag < 1.5) {
outColor = vec4(mix(vec3(1.0, 0.52, 0.16), vec3(1.0, 0.95, 0.72), uAB), 1.0);
return;
}
vec3 n = normalize(vNorm);
float ndl = dot(n, uSunDir);
if (vFlag > 1.5) {
float spec = pow(max(0.0, dot(n, normalize(uSunDir + normalize(uCamPos - vWorldPos)))), 14.0);
vec3 c = ndl > 0.25 ? vec3(0.98, 0.80, 0.34) : (ndl > -0.2 ? vec3(0.76, 0.54, 0.22) : vec3(0.42, 0.30, 0.26));
if (spec > 0.38) c = vec3(1.0, 0.96, 0.78);
outColor = vec4(c, 1.0);
return;
}
vec3 col = ndl > 0.32 ? vCol * vec3(1.16, 1.05, 0.90)
: ndl > -0.18 ? vCol * vec3(0.88, 0.84, 0.88)
: vCol * vec3(0.48, 0.42, 0.64);
outColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}`;
const VS_FX = `#version 300 es
precision highp float;
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec4 aCol;
uniform mat4 uVP;
out vec4 vCol;
void main() { vCol = aCol; gl_Position = uVP * vec4(aPos, 1.0); }`;
const FS_FX = `#version 300 es
precision highp float;
in vec4 vCol;
out vec4 outColor;
float bayer4(ivec2 p) {
int idx = (p.y & 3) * 4 + (p.x & 3);
const int m[16] = int[16](0,8,2,10, 12,4,14,6, 3,11,1,9, 15,7,13,5);
return (float(m[idx]) + 0.5) / 16.0;
}
void main() {
if (vCol.a < bayer4(ivec2(gl_FragCoord.xy))) discard;
outColor = vec4(vCol.rgb, 1.0);
}`;
const FS_COMP = `#version 300 es
precision highp float;
in vec2 vUv;
out vec4 outColor;
uniform sampler2D uWorld, uJet, uFx;
uniform vec2 uTexel;
void main() {
vec3 col = texture(uWorld, vUv).rgb;
vec4 jet = texture(uJet, vUv);
if (jet.a > 0.5) {
col = jet.rgb;
} else {
float n = texture(uJet, vUv + vec2(0.0, uTexel.y)).a + texture(uJet, vUv - vec2(0.0, uTexel.y)).a
+ texture(uJet, vUv + vec2(uTexel.x, 0.0)).a + texture(uJet, vUv - vec2(uTexel.x, 0.0)).a;
if (n > 0.5) col = vec3(0.09, 0.07, 0.15);
}
vec4 fx = texture(uFx, vUv);
if (fx.a > 0.5) col = fx.rgb;
outColor = vec4(col, 1.0);
}`;
// ============================================================================
// WEBGL2 PIPELINE, FRAMEBUFFERS & DYNAMIC RESOLUTION SCALER
// ============================================================================
const glCanvas = document.getElementById('gl-canvas');
const hudCanvas = document.getElementById('hud-canvas');
const hudCtx = hudCanvas.getContext('2d', { alpha: true });
const gl = glCanvas.getContext('webgl2', {
antialias: false, alpha: false, depth: true,
preserveDrawingBuffer: true, powerPreference: 'high-performance'
});
if (!gl) {
document.getElementById('load-stage').textContent = 'WebGL2 is required to run Patrol.';
throw new Error('WebGL2 unavailable');
}
function compileShader(type, src) {
const s = gl.createShader(type);
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
const err = gl.getShaderInfoLog(s);
console.error(err);
throw new Error(err);
}
return s;
}
function createProgram(vs, fs) {
const p = gl.createProgram();
gl.attachShader(p, compileShader(gl.VERTEX_SHADER, vs));
gl.attachShader(p, compileShader(gl.FRAGMENT_SHADER, fs));
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
return p;
}
const progWorld = createProgram(VS_FULLSCREEN, FS_WORLD);
const progMesh = createProgram(VS_MESH, FS_MESH);
const progFx = createProgram(VS_FX, FS_FX);
const progComp = createProgram(VS_FULLSCREEN, FS_COMP);
function getUniforms(prog, names) {
const u = {};
for (const n of names) u[n] = gl.getUniformLocation(prog, n);
return u;
}
const uWorld = getUniforms(progWorld, [
'uTerrain','uRes','uTime','uCamPos','uCamRight','uCamUp','uCamFwd',
'uTanHalfFov','uAspect','uNear','uFar','uSunDir','uJetPos','uJetFwd',
'uJetAltAboveWater','uImpacts[0]'
]);
const uMesh = getUniforms(progMesh, ['uVP','uModel','uNormalMat','uSunDir','uCamPos','uAB']);
const uFx = getUniforms(progFx, ['uVP']);
const uComp = getUniforms(progComp, ['uWorld','uJet','uFx','uTexel']);
const vaoEmpty = gl.createVertexArray();
function createMeshVAO(geo) {
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
function buf(data, loc, size) {
const b = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
}
buf(geo.pos, 0, 3); buf(geo.norm, 1, 3); buf(geo.col, 2, 3); buf(geo.flag, 3, 1);
gl.bindVertexArray(null);
return { vao, count: geo.count };
}
const fighterMesh = createMeshVAO(buildFighterGeometry());
const missileMesh = createMeshVAO(buildMissileGeometry());
const MAX_FX_VERTS = 18000;
const fxPosData = new Float32Array(MAX_FX_VERTS * 3);
const fxColData = new Float32Array(MAX_FX_VERTS * 4);
let fxVertCount = 0;
const fxVao = gl.createVertexArray();
gl.bindVertexArray(fxVao);
const fxPosBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, fxPosBuf);
gl.bufferData(gl.ARRAY_BUFFER, fxPosData.byteLength, gl.DYNAMIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
const fxColBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, fxColBuf);
gl.bufferData(gl.ARRAY_BUFFER, fxColData.byteLength, gl.DYNAMIC_DRAW);
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
function fxReset() { fxVertCount = 0; }
function fxTri(a, b, c, rgba) {
if (fxVertCount + 3 > MAX_FX_VERTS) return;
let pi = fxVertCount * 3, ci = fxVertCount * 4;
for (const p of [a, b, c]) {
fxPosData[pi++] = p[0]; fxPosData[pi++] = p[1]; fxPosData[pi++] = p[2];
fxColData[ci++] = rgba[0]; fxColData[ci++] = rgba[1]; fxColData[ci++] = rgba[2]; fxColData[ci++] = rgba[3];
}
fxVertCount += 3;
}
function fxQuad(a, b, c, d, rgba) { fxTri(a, b, c, rgba); fxTri(a, c, d, rgba); }
function fxBillboard(center, size, camR, camU, rgba) {
const rx = camR[0]*size, ry = camR[1]*size, rz = camR[2]*size;
const ux = camU[0]*size, uy = camU[1]*size, uz = camU[2]*size;
fxQuad(
[center[0]-rx-ux, center[1]-ry-uy, center[2]-rz-uz],
[center[0]+rx-ux, center[1]+ry-uy, center[2]+rz-uz],
[center[0]+rx+ux, center[1]+ry+uy, center[2]+rz+uz],
[center[0]-rx+ux, center[1]-ry+uy, center[2]-rz+uz], rgba
);
}
const RES_TIERS = [340, 290, 240, 200];
let resTierIdx = 0, internalW = 604, internalH = 340;
let worldFbo = null, jetFbo = null, fxFbo = null;
let worldTex = null, jetTex = null, fxTex = null, sharedDepth = null;
function makeColorTex(w, h) {
const t = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return t;
}
function resizeBuffers() {
const aspect = Math.max(320, window.innerWidth) / Math.max(200, window.innerHeight);
internalH = RES_TIERS[resTierIdx];
internalW = Math.max(240, Math.min(960, Math.round(internalH * aspect)));
glCanvas.width = internalW; glCanvas.height = internalH;
hudCanvas.width = internalW; hudCanvas.height = internalH;
hudCtx.imageSmoothingEnabled = false;
if (worldFbo) {
gl.deleteFramebuffer(worldFbo); gl.deleteFramebuffer(jetFbo); gl.deleteFramebuffer(fxFbo);
gl.deleteTexture(worldTex); gl.deleteTexture(jetTex); gl.deleteTexture(fxTex);
gl.deleteRenderbuffer(sharedDepth);
}
sharedDepth = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, sharedDepth);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT24, internalW, internalH);
worldTex = makeColorTex(internalW, internalH);
jetTex = makeColorTex(internalW, internalH);
fxTex = makeColorTex(internalW, internalH);
function buildFbo(tex) {
const f = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, f);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, sharedDepth);
return f;
}
worldFbo = buildFbo(worldTex); jetFbo = buildFbo(jetTex); fxFbo = buildFbo(fxTex);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
window.addEventListener('resize', resizeBuffers);
resizeBuffers();
let terrainRGBA = null, terrainTex = null;
function getTerrainHeightJS(wx, wz) {
if (!terrainRGBA) return SEA_LEVEL;
const u = ((wx / WORLD_SIZE) % 1 + 1) % 1, v = ((wz / WORLD_SIZE) % 1 + 1) % 1;
const fx = u * MAP_SIZE, fy = v * MAP_SIZE;
const x0 = Math.floor(fx) & (MAP_SIZE - 1), y0 = Math.floor(fy) & (MAP_SIZE - 1);
const x1 = (x0 + 1) & (MAP_SIZE - 1), y1 = (y0 + 1) & (MAP_SIZE - 1);
const sx = fx - Math.floor(fx), sy = fy - Math.floor(fy);
const h00 = terrainRGBA[(y0 * MAP_SIZE + x0) * 4], h10 = terrainRGBA[(y0 * MAP_SIZE + x1) * 4];
const h01 = terrainRGBA[(y1 * MAP_SIZE + x0) * 4], h11 = terrainRGBA[(y1 * MAP_SIZE + x1) * 4];
return (lerp(lerp(h00, h10, sx), lerp(h01, h11, sx), sy) / 255.0) * MAX_TERRAIN_H;
}
const sound = new SoundEngine();
const jet = {
pos: [320, CRUISE_ALT, 460], yaw: 0.55, pitch: 0.0, bank: 0.0,
rollSpin: 0.0, rollTimer: 0.0, speed: 92.0, ab: 0.0,
gForce: 1.0, turnRate: 0.0, slip: 0.0, vSpeed: 0.0,
pullUp: false, lowAlt: false, waterSkim: false, ralt: 100.0,
fwd: [0, 0, -1], right: [1, 0, 0], up: [0, 1, 0],
rails: [
{ off: [-2.4, -0.34, 1.3], ready: true, rearm: 0 },
{ off: [ 2.4, -0.34, 1.3], ready: true, rearm: 0 },
{ off: [-3.9, -0.32, 2.0], ready: true, rearm: 0 },
{ off: [ 3.9, -0.32, 2.0], ready: true, rearm: 0 }
]
};
const cam = {
mode: CAM_CHASE, prevMode: CAM_CHASE, blend: 1.0,
pos: [320, CRUISE_ALT + 8, 490], right: [1, 0, 0], up: [0, 1, 0], fwd: [0, 0, -1],
fov: 58 * Math.PI / 180
};
const input = {
hasMoved: false, mouseX: 0, mouseY: 0,
leftDown: false, leftDownTime: 0, rightDown: false, abHold: false,
touchActive: false, touchX: 0, touchY: 0, touchAB: false
};
const trailL = [], trailR = [], MAX_TRAIL = 48;
const activeMissiles = [], particles = [], shockRings = [], impacts = [];
const radarAngleRef = { ang: 0 };
const titleCard = document.getElementById('title-card');
const viewBadge = document.getElementById('view-badge');
const mslPipsEl = document.getElementById('msl-pips');
const mslCountEl = document.getElementById('msl-count');
const soundBtn = document.getElementById('sound-btn');
function dismissTitle() {
if (!input.hasMoved) { input.hasMoved = true; titleCard.classList.add('hidden'); }
}
function updateMissileUI() {
let ready = 0;
const pips = mslPipsEl.children;
for (let i = 0; i < 4; i++) {
if (jet.rails[i].ready) { ready++; pips[i].classList.remove('empty'); }
else pips[i].classList.add('empty');
}
mslCountEl.textContent = `${ready}/4`;
}
function cycleCamera() {
cam.prevMode = cam.mode; cam.mode = (cam.mode + 1) % 3; cam.blend = 0.0;
viewBadge.textContent = CAM_NAMES[cam.mode]; dismissTitle();
}
function triggerBarrelRoll() {
if (jet.rollTimer <= 0.0) { jet.rollTimer = 0.68; sound.playRoll(); }
}
function fireMissile() {
dismissTitle();
const railIdx = jet.rails.findIndex(r => r.ready);
if (railIdx === -1) return;
const rail = jet.rails[railIdx];
rail.ready = false; rail.rearm = 4.2;
updateMissileUI(); sound.playMissile();
const wp = add3(jet.pos, add3(scale3(jet.right, rail.off[0]), add3(scale3(jet.up, rail.off[1]), scale3(jet.fwd, -rail.off[2]))));
let dir = [...jet.fwd];
if (dir[1] > -0.10) {
const aheadX = jet.pos[0] + jet.fwd[0] * 240, aheadZ = jet.pos[2] + jet.fwd[2] * 240;
const groundY = Math.max(SEA_LEVEL, getTerrainHeightJS(aheadX, aheadZ));
dir = norm3([aheadX - wp[0], groundY - wp[1], aheadZ - wp[2]]);
}
activeMissiles.push({ pos: wp, vel: scale3(dir, jet.speed + 185.0), dir, age: 0.0, smokeTimer: 0.0 });
}
soundBtn.addEventListener('click', (e) => {
e.stopPropagation();
const on = sound.toggle();
soundBtn.textContent = on ? 'SOUND: ON' : 'SOUND: OFF';
soundBtn.classList.toggle('on', on);
});
window.addEventListener('contextmenu', (e) => e.preventDefault());
window.addEventListener('mousemove', (e) => {
dismissTitle();
input.mouseX = clamp((e.clientX / window.innerWidth) * 2 - 1, -1, 1);
input.mouseY = clamp((e.clientY / window.innerHeight) * 2 - 1, -1, 1);
});
glCanvas.addEventListener('mousedown', (e) => {
dismissTitle();
if (e.button === 0) { input.leftDown = true; input.leftDownTime = performance.now(); }
else if (e.button === 2) { input.rightDown = true; fireMissile(); }
});
window.addEventListener('mouseup', (e) => {
if (e.button === 0 && input.leftDown) {
const held = performance.now() - input.leftDownTime;
input.leftDown = false; input.abHold = false;
if (held < 230) triggerBarrelRoll();
} else if (e.button === 2) input.rightDown = false;
});
window.addEventListener('keydown', (e) => {
if (e.code === 'Space') { e.preventDefault(); cycleCamera(); }
else if (e.code === 'KeyF') { e.preventDefault(); fireMissile(); }
else if (e.code === 'KeyM') soundBtn.click();
});
const touchUI = document.getElementById('touch-ui');
const touchPad = document.getElementById('touch-pad');
const touchKnob = document.getElementById('touch-knob');
let padTouchId = null;
window.addEventListener('touchstart', () => { touchUI.classList.add('active'); dismissTitle(); }, { passive: true });
touchPad.addEventListener('touchstart', (e) => {
e.preventDefault(); const t = e.changedTouches[0];
padTouchId = t.identifier; input.touchActive = true; updateTouchPad(t);
}, { passive: false });
touchPad.addEventListener('touchmove', (e) => {
e.preventDefault(); for (const t of e.changedTouches) if (t.identifier === padTouchId) updateTouchPad(t);
}, { passive: false });
function endTouchPad(e) {
for (const t of e.changedTouches) if (t.identifier === padTouchId) {
padTouchId = null; input.touchActive = false; input.touchX = 0; input.touchY = 0;
touchKnob.style.transform = 'translate(0px, 0px)';
}
}
touchPad.addEventListener('touchend', endTouchPad);
touchPad.addEventListener('touchcancel', endTouchPad);
function updateTouchPad(t) {
const r = touchPad.getBoundingClientRect(), cx = r.left + r.width * 0.5, cy = r.top + r.height * 0.5, maxR = r.width * 0.38;
let dx = t.clientX - cx, dy = t.clientY - cy, dist = Math.hypot(dx, dy);
if (dist > maxR) { dx = (dx / dist) * maxR; dy = (dy / dist) * maxR; }
input.touchX = dx / maxR; input.touchY = dy / maxR;
touchKnob.style.transform = `translate(${dx.toFixed(1)}px, ${dy.toFixed(1)}px)`;
}
const bindTouchBtn = (id, onDown, onUp) => {
const el = document.getElementById(id);
el.addEventListener('touchstart', (e) => { e.preventDefault(); el.classList.add('pressed'); onDown(); }, { passive: false });
const up = (e) => { e.preventDefault(); el.classList.remove('pressed'); if (onUp) onUp(); };
el.addEventListener('touchend', up, { passive: false }); el.addEventListener('touchcancel', up, { passive: false });
};
bindTouchBtn('btn-view', cycleCamera);
bindTouchBtn('btn-roll', triggerBarrelRoll);
bindTouchBtn('btn-ab', () => { input.touchAB = true; }, () => { input.touchAB = false; });
bindTouchBtn('btn-fire', fireMissile);
// ============================================================================
// FLIGHT MODEL, SIMULATION, FX & WEBGL2 RENDER PASSES
// ============================================================================
function updateJetBasis() {
const cy = Math.cos(jet.yaw), sy = Math.sin(jet.yaw);
const cp = Math.cos(jet.pitch), sp = Math.sin(jet.pitch);
const fwd = [sy * cp, sp, -cy * cp];
let right0 = norm3(cross3(fwd, [0, 1, 0]));
let up0 = cross3(right0, fwd);
const totalRoll = jet.bank + jet.rollSpin;
const cr = Math.cos(totalRoll), sr = Math.sin(totalRoll);
jet.fwd = fwd;
jet.right = add3(scale3(right0, cr), scale3(up0, -sr));
jet.up = add3(scale3(up0, cr), scale3(right0, sr));
}
function spawnImpact(pos, isWater) {
sound.playExplosion(isWater);
impacts.unshift({ x: pos[0], y: pos[1], z: pos[2], age: 0.01, isWater });
if (impacts.length > 12) impacts.pop();
shockRings.push({
x: pos[0], y: pos[1] + 0.8, z: pos[2],
age: 0, maxAge: isWater ? 1.8 : 1.1, maxR: isWater ? 42 : 34,
col: isWater ? [0.95, 0.96, 0.94] : [1.0, 0.86, 0.56]
});
particles.push({
pos: [pos[0], pos[1] + 2.5, pos[2]], vel: [0, 2, 0],
size: 11.0, grow: 18.0, age: 0, maxAge: 0.16,
col0: [1.0, 0.98, 0.88], col1: [1.0, 0.80, 0.35], grav: 0
});
if (isWater) {
for (let i = 0; i < 34; i++) {
const ang = Math.random() * Math.PI * 2, spd = 4 + Math.random() * 14, up = 22 + Math.random() * 38;
particles.push({
pos: [pos[0] + Math.cos(ang)*2, pos[1] + 0.5, pos[2] + Math.sin(ang)*2],
vel: [Math.cos(ang)*spd, up, Math.sin(ang)*spd],
size: 1.8 + Math.random() * 2.4, grow: 2.2, age: 0, maxAge: 1.2 + Math.random() * 1.1,
col0: [0.96, 0.96, 0.94], col1: [0.58, 0.82, 0.82], grav: 36.0
});
}
} else {
for (let i = 0; i < 20; i++) {
const ang = Math.random() * Math.PI * 2, spd = 3 + Math.random() * 14;
particles.push({
pos: [pos[0] + Math.cos(ang)*1.5, pos[1] + 1.5, pos[2] + Math.sin(ang)*1.5],
vel: [Math.cos(ang)*spd, 6 + Math.random() * 18, Math.sin(ang)*spd],
size: 3.0 + Math.random() * 3.5, grow: 4.5, age: 0, maxAge: 0.55 + Math.random() * 0.55,
col0: [1.0, 0.92, 0.55], col1: [0.85, 0.24, 0.14], grav: 4.0
});
}
for (let i = 0; i < 24; i++) {
const ang = Math.random() * Math.PI * 2, spd = 2 + Math.random() * 8;
particles.push({
pos: [pos[0] + Math.cos(ang)*3, pos[1] + 2.5 + Math.random()*3, pos[2] + Math.sin(ang)*3],
vel: [Math.cos(ang)*spd, 7 + Math.random() * 12, Math.sin(ang)*spd],
size: 3.5 + Math.random() * 3.0, grow: 4.0, age: 0, maxAge: 2.6 + Math.random() * 2.2,
col0: [0.34, 0.26, 0.38], col1: [0.22, 0.17, 0.28], grav: -1.5
});
}
}
}
function stepSimulation(dt, time) {
if (input.leftDown && performance.now() - input.leftDownTime >= 220) input.abHold = true;
const abTarget = (input.abHold || input.touchAB) ? 1.0 : 0.0;
jet.ab = lerp(jet.ab, abTarget, clamp(dt * 6.5, 0, 1));
jet.speed = lerp(jet.speed, lerp(88.0, 158.0, jet.ab), clamp(dt * 3.2, 0, 1));
let steerX = 0, steerY = 0;
if (!input.hasMoved) {
steerX = Math.sin(time * 0.42) * 0.42;
steerY = Math.sin(time * 0.27) * 0.10 + (CRUISE_ALT - jet.pos[1]) * 0.012;
} else {
const sx = input.touchActive ? input.touchX : input.mouseX;
const sy = input.touchActive ? input.touchY : input.mouseY;
if (cam.mode === CAM_TOP) {
if (Math.hypot(sx, sy) > 0.05) {
const diff = wrapAngle(Math.atan2(sx, -sy) - jet.yaw);
steerX = clamp(diff * 1.45, -1, 1);
}
steerY = clamp((CRUISE_ALT - jet.pos[1]) * 0.018, -0.45, 0.45);
} else {
const dz = 0.04;
steerX = Math.abs(sx) < dz ? 0 : (sx - Math.sign(sx) * dz) / (1 - dz);
steerY = Math.abs(sy) < dz ? 0 : -(sy - Math.sign(sy) * dz) / (1 - dz);
}
}
const desiredTurn = steerX * 1.42;
jet.turnRate = lerp(jet.turnRate, desiredTurn, clamp(dt * 4.8, 0, 1));
jet.yaw = wrapAngle(jet.yaw + jet.turnRate * dt);
jet.bank = lerp(jet.bank, clamp(jet.turnRate * 0.72, -1.08, 1.08), clamp(dt * 5.5, 0, 1));
jet.slip = lerp(jet.slip, (desiredTurn - jet.turnRate) * 0.6, clamp(dt * 6, 0, 1));
let targetPitch = clamp(steerY * 0.68, -0.64, 0.64);
const gHere = Math.max(SEA_LEVEL, getTerrainHeightJS(jet.pos[0], jet.pos[2]));
jet.ralt = Math.max(0, jet.pos[1] - gHere);
let maxAheadFloor = gHere;
let aheadIsWater = getTerrainHeightJS(jet.pos[0], jet.pos[2]) <= SEA_LEVEL + 0.5;
for (const lookT of [0.35, 0.85, 1.55, 2.3]) {
const px = jet.pos[0] + jet.fwd[0] * jet.speed * lookT;
const pz = jet.pos[2] + jet.fwd[2] * jet.speed * lookT;
const rawH = getTerrainHeightJS(px, pz);
const surf = Math.max(SEA_LEVEL, rawH);
const margin = rawH <= SEA_LEVEL + 0.5 ? 6.5 : 16.0;
if (surf + margin > maxAheadFloor) {
maxAheadFloor = surf + margin;
if (rawH > SEA_LEVEL + 0.5) aheadIsWater = false;
}
}
const predY = jet.pos[1] + Math.sin(jet.pitch) * jet.speed * 1.1;
jet.lowAlt = jet.ralt < 24.0;
jet.pullUp = false;
if (predY < maxAheadFloor || jet.pos[1] < gHere + (aheadIsWater ? 5.5 : 13.0)) {
jet.pullUp = true;
const urgency = clamp((maxAheadFloor - predY) / 24.0, 0.25, 1.0);
targetPitch = Math.max(targetPitch, 0.22 + urgency * 0.50);
}
if (jet.pos[1] > 260.0) targetPitch = Math.min(targetPitch, -0.15);
const prevPitch = jet.pitch;
jet.pitch = lerp(jet.pitch, targetPitch, clamp(dt * (jet.pullUp ? 7.5 : 4.2), 0, 1));
if (jet.rollTimer > 0) {
jet.rollTimer = Math.max(0, jet.rollTimer - dt);
jet.rollSpin = smoothstep(1.0 - jet.rollTimer / 0.68) * Math.PI * 2;
if (jet.rollTimer <= 0) jet.rollSpin = 0;
}
updateJetBasis();
const prevY = jet.pos[1];
jet.pos[0] += jet.fwd[0] * jet.speed * dt;
jet.pos[1] += jet.fwd[1] * jet.speed * dt;
jet.pos[2] += jet.fwd[2] * jet.speed * dt;
const hardFloor = Math.max(SEA_LEVEL + 4.2, getTerrainHeightJS(jet.pos[0], jet.pos[2]) + 7.5);
if (jet.pos[1] < hardFloor) {
jet.pos[1] = hardFloor;
if (jet.pitch < 0.08) jet.pitch = 0.08;
updateJetBasis();
}
jet.vSpeed = (jet.pos[1] - prevY) / Math.max(0.001, dt);
const pitchRate = (jet.pitch - prevPitch) / Math.max(0.001, dt);
const rawG = 1.0 + Math.abs(jet.turnRate) * 2.2 + Math.max(-1.2, pitchRate * 3.8) + (jet.rollTimer > 0 ? 1.4 : 0);
jet.gForce = lerp(jet.gForce, clamp(rawG, 0.2, 7.5), clamp(dt * 6, 0, 1));
const rawHere = getTerrainHeightJS(jet.pos[0], jet.pos[2]);
jet.waterSkim = rawHere <= SEA_LEVEL + 0.5 && (jet.pos[1] - SEA_LEVEL) < 22.0;
if (jet.waterSkim && Math.random() < dt * 45) {
const side = (Math.random() < 0.5 ? -1 : 1) * (1.8 + Math.random() * 2.5);
const spPos = add3([jet.pos[0], SEA_LEVEL + 0.6, jet.pos[2]], add3(scale3(jet.right, side), scale3(jet.fwd, -6.0)));
particles.push({
pos: spPos,
vel: [jet.right[0]*side*4.5 - jet.fwd[0]*12, 8 + Math.random()*11, jet.right[2]*side*4.5 - jet.fwd[2]*12],
size: 1.3 + Math.random() * 1.4, grow: 1.8, age: 0, maxAge: 0.45 + Math.random() * 0.35,
col0: [0.96, 0.96, 0.94], col1: [0.62, 0.85, 0.84], grav: 24.0
});
}
const tipL = add3(jet.pos, add3(scale3(jet.right, -5.65), scale3(jet.fwd, -3.2)));
const tipR = add3(jet.pos, add3(scale3(jet.right, 5.65), scale3(jet.fwd, -3.2)));
const trailStr = clamp(0.32 + Math.abs(jet.bank) * 0.55 + jet.ab * 0.35 + (jet.rollTimer > 0 ? 0.5 : 0), 0.3, 1.0);
trailL.unshift({ pos: tipL, str: trailStr });
trailR.unshift({ pos: tipR, str: trailStr });
if (trailL.length > MAX_TRAIL) trailL.pop();
if (trailR.length > MAX_TRAIL) trailR.pop();
let uiDirty = false;
for (const r of jet.rails) {
if (!r.ready) {
r.rearm -= dt;
if (r.rearm <= 0) { r.ready = true; r.rearm = 0; uiDirty = true; }
}
}
if (uiDirty) updateMissileUI();
for (let i = activeMissiles.length - 1; i >= 0; i--) {
const m = activeMissiles[i];
m.age += dt;
m.pos[0] += m.vel[0] * dt; m.pos[1] += m.vel[1] * dt; m.pos[2] += m.vel[2] * dt;
m.smokeTimer += dt;
if (m.smokeTimer > 0.018) {
m.smokeTimer = 0;
particles.push({
pos: sub3(m.pos, scale3(m.dir, 1.5)),
vel: [(Math.random()-0.5)*3, 1.2 + Math.random()*2, (Math.random()-0.5)*3],
size: 1.0, grow: 2.8, age: 0, maxAge: 1.15,
col0: [0.96, 0.90, 0.84], col1: [0.64, 0.56, 0.68], grav: -0.6
});
}
const rawH = getTerrainHeightJS(m.pos[0], m.pos[2]);
const surf = Math.max(SEA_LEVEL, rawH);
if (m.pos[1] <= surf + 0.6) {
m.pos[1] = surf; spawnImpact(m.pos, rawH <= SEA_LEVEL + 0.35); activeMissiles.splice(i, 1);
} else if (m.age > 5.5) activeMissiles.splice(i, 1);
}
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.age += dt;
if (p.age >= p.maxAge) { particles.splice(i, 1); continue; }
p.vel[1] -= p.grav * dt;
p.pos[0] += p.vel[0] * dt; p.pos[1] += p.vel[1] * dt; p.pos[2] += p.vel[2] * dt;
p.size += p.grow * dt;
}
for (let i = shockRings.length - 1; i >= 0; i--) {
shockRings[i].age += dt;
if (shockRings[i].age >= shockRings[i].maxAge) shockRings.splice(i, 1);
}
for (let i = impacts.length - 1; i >= 0; i--) {
impacts[i].age += dt;
if (impacts[i].age > 24.0) impacts.splice(i, 1);
}
if (cam.blend < 1.0) cam.blend = Math.min(1.0, cam.blend + dt * 1.05);
function poseFor(mode) {
if (mode === CAM_CHASE) {
const flatFwd = norm3([Math.sin(jet.yaw), jet.pitch * 0.45, -Math.cos(jet.yaw)]);
const backDist = 23.0 + jet.ab * 4.0;
const pos = [jet.pos[0] - flatFwd[0]*backDist, jet.pos[1] - flatFwd[1]*backDist + 6.2, jet.pos[2] - flatFwd[2]*backDist];
const fwd = norm3(sub3(add3(jet.pos, scale3(jet.fwd, 18.0)), pos));
const right = norm3(cross3(fwd, [0, 1, 0]));
return { pos, fwd, right, up: cross3(right, fwd), fov: (56 + jet.ab * 6) * Math.PI / 180 };
}
if (mode === CAM_COCKPIT) {
return {
pos: add3(jet.pos, add3(scale3(jet.up, 1.05), scale3(jet.fwd, 1.8))),
fwd: [...jet.fwd], right: [...jet.right], up: [...jet.up], fov: 62 * Math.PI / 180
};
}
const pos = [jet.pos[0], jet.pos[1] + 155.0, jet.pos[2] + 16.0];
const fwd = norm3(sub3(jet.pos, pos));
const right = [1, 0, 0];
return { pos, fwd, right, up: norm3(cross3(right, fwd)), fov: 48 * Math.PI / 180 };
}
const pA = poseFor(cam.prevMode), pB = poseFor(cam.mode), t = smoothstep(cam.blend);
cam.pos = lerp3(pA.pos, pB.pos, t);
cam.fwd = norm3(lerp3(pA.fwd, pB.fwd, t));
const rawUp = norm3(lerp3(pA.up, pB.up, t));
cam.right = norm3(cross3(cam.fwd, rawUp));
cam.up = cross3(cam.right, cam.fwd);
cam.fov = lerp(pA.fov, pB.fov, t);
sound.update(clamp((jet.speed - 85) / 75, 0, 1), jet.ab, cam.mode === CAM_COCKPIT && cam.blend > 0.6, jet.pullUp);
}
function buildFrameFX(time) {
fxReset();
const showJet = !(cam.mode === CAM_COCKPIT && cam.blend > 0.72);
if (showJet) {
const pulse = 0.88 + 0.24 * Math.sin(time * 58.0);
const len = (2.6 + jet.ab * 6.8) * pulse, rad = 0.30 + jet.ab * 0.16;
for (const sgn of [-1, 1]) {
const base = add3(jet.pos, add3(scale3(jet.right, sgn * 0.86), scale3(jet.fwd, -6.25)));
const tip = sub3(base, scale3(jet.fwd, len));
const mid = sub3(base, scale3(jet.fwd, len * 0.42));
const coreTip = sub3(base, scale3(jet.fwd, len * 0.56));
const cOuter = jet.ab > 0.2 ? [1.0, 0.52, 0.24, 0.92] : [0.98, 0.54, 0.20, 0.78];
const cCore = [1.0, 0.98, 0.88, 1.0];
for (const axis of [jet.right, jet.up]) {
fxTri(base, add3(mid, scale3(axis, -rad)), tip, cOuter);
fxTri(base, tip, add3(mid, scale3(axis, rad)), cOuter);
const cb = sub3(base, scale3(jet.fwd, len * 0.22));
fxTri(base, add3(cb, scale3(axis, -rad*0.52)), coreTip, cCore);
fxTri(base, coreTip, add3(cb, scale3(axis, rad*0.52)), cCore);
}
}
}
function emitRibbon(pts) {
for (let i = 0; i < pts.length - 1; i++) {
const a = pts[i], b = pts[i + 1], frac = 1.0 - i / pts.length;
const alpha = frac * frac * a.str * 0.82;
if (alpha < 0.08) continue;
const side = norm3(cross3(sub3(a.pos, b.pos), cam.fwd));
const wA = 0.20 * frac, wB = 0.20 * Math.max(0, 1.0 - (i + 1) / pts.length);
fxQuad(add3(a.pos, scale3(side, -wA)), add3(a.pos, scale3(side, wA)),
add3(b.pos, scale3(side, wB)), add3(b.pos, scale3(side, -wB)), [0.98, 0.96, 0.95, alpha]);
}
}
emitRibbon(trailL); emitRibbon(trailR);
for (const m of activeMissiles) {
const base = sub3(m.pos, scale3(m.dir, 1.25));
const tip = sub3(m.pos, scale3(m.dir, 4.4 + Math.sin(time * 70) * 0.6));
const side = norm3(cross3(m.dir, cam.fwd));
fxTri(add3(base, scale3(side, -0.32)), add3(base, scale3(side, 0.32)), tip, [1.0, 0.78, 0.28, 1.0]);
fxBillboard(base, 0.55, cam.right, cam.up, [1.0, 0.98, 0.85, 1.0]);
}
for (const p of particles) {
const t = p.age / p.maxAge;
const a = t < 0.15 ? 1.0 : Math.max(0, 1.0 - (t - 0.15) / 0.85);
fxBillboard(p.pos, p.size * 0.5, cam.right, cam.up, [lerp(p.col0[0], p.col1[0], t), lerp(p.col0[1], p.col1[1], t), lerp(p.col0[2], p.col1[2], t), a]);
}
for (const sr of shockRings) {
const t = sr.age / sr.maxAge, rOut = lerp(3.0, sr.maxR, smoothstep(t));
const rIn = Math.max(0.5, rOut - lerp(3.5, 1.2, t)), a = Math.max(0, (1.0 - t) * 0.92);
for (let i = 0; i < 16; i++) {
const a0 = (i / 16) * Math.PI * 2, a1 = ((i + 1) / 16) * Math.PI * 2;
const c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1);
fxQuad([sr.x+c0*rIn, sr.y, sr.z+s0*rIn], [sr.x+c0*rOut, sr.y, sr.z+s0*rOut],
[sr.x+c1*rOut, sr.y, sr.z+s1*rOut], [sr.x+c1*rIn, sr.y, sr.z+s1*rIn], [sr.col[0], sr.col[1], sr.col[2], a]);
}
}
}
function renderWebGL(time) {
const aspect = internalW / internalH, near = 0.5, far = 2600.0;
const tanHalfFov = Math.tan(cam.fov * 0.5);
const vp = mat4Mul(mat4Perspective(cam.fov, aspect, near, far), mat4LookBasis(cam.pos, cam.right, cam.up, cam.fwd));
gl.viewport(0, 0, internalW, internalH);
gl.bindFramebuffer(gl.FRAMEBUFFER, worldFbo);
gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.ALWAYS); gl.depthMask(true); gl.disable(gl.CULL_FACE);
gl.useProgram(progWorld);
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, terrainTex);
gl.uniform1i(uWorld['uTerrain'], 0);
gl.uniform2f(uWorld['uRes'], internalW, internalH);
gl.uniform1f(uWorld['uTime'], time);
gl.uniform3fv(uWorld['uCamPos'], cam.pos); gl.uniform3fv(uWorld['uCamRight'], cam.right);
gl.uniform3fv(uWorld['uCamUp'], cam.up); gl.uniform3fv(uWorld['uCamFwd'], cam.fwd);
gl.uniform1f(uWorld['uTanHalfFov'], tanHalfFov); gl.uniform1f(uWorld['uAspect'], aspect);
gl.uniform1f(uWorld['uNear'], near); gl.uniform1f(uWorld['uFar'], far);
gl.uniform3fv(uWorld['uSunDir'], SUN_DIR);
gl.uniform3fv(uWorld['uJetPos'], jet.pos); gl.uniform3fv(uWorld['uJetFwd'], jet.fwd);
gl.uniform1f(uWorld['uJetAltAboveWater'], Math.max(0, jet.pos[1] - SEA_LEVEL));
const impArr = new Float32Array(48);
for (let i = 0; i < impacts.length && i < 12; i++) {
const im = impacts[i];
impArr[i*4] = im.x; impArr[i*4+1] = im.y; impArr[i*4+2] = im.z; impArr[i*4+3] = im.isWater ? -im.age : im.age;
}
gl.uniform4fv(uWorld['uImpacts[0]'], impArr);
gl.bindVertexArray(vaoEmpty); gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.bindFramebuffer(gl.FRAMEBUFFER, jetFbo);
gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.depthMask(true);
gl.useProgram(progMesh);
gl.uniformMatrix4fv(uMesh['uVP'], false, vp);
gl.uniform3fv(uMesh['uSunDir'], SUN_DIR); gl.uniform3fv(uMesh['uCamPos'], cam.pos); gl.uniform1f(uMesh['uAB'], jet.ab);
const showJet = !(cam.mode === CAM_COCKPIT && cam.blend > 0.72);
if (showJet) {
const nMat = new Float32Array([jet.right[0],jet.right[1],jet.right[2], jet.up[0],jet.up[1],jet.up[2], -jet.fwd[0],-jet.fwd[1],-jet.fwd[2]]);
gl.uniformMatrix4fv(uMesh['uModel'], false, mat4Model(jet.pos, jet.right, jet.up, jet.fwd, 1.0));
gl.uniformMatrix3fv(uMesh['uNormalMat'], false, nMat);
gl.bindVertexArray(fighterMesh.vao); gl.drawArrays(gl.TRIANGLES, 0, fighterMesh.count);
gl.bindVertexArray(missileMesh.vao);
for (const r of jet.rails) {
if (!r.ready) continue;
const wp = add3(jet.pos, add3(scale3(jet.right, r.off[0]), add3(scale3(jet.up, r.off[1]), scale3(jet.fwd, -r.off[2]))));
gl.uniformMatrix4fv(uMesh['uModel'], false, mat4Model(wp, jet.right, jet.up, jet.fwd, 1.0));
gl.drawArrays(gl.TRIANGLES, 0, missileMesh.count);
}
}
if (activeMissiles.length > 0) {
gl.bindVertexArray(missileMesh.vao);
for (const m of activeMissiles) {
const mr = norm3(cross3(m.dir, [0, 1, 0])), mu = cross3(mr, m.dir);
gl.uniformMatrix4fv(uMesh['uModel'], false, mat4Model(m.pos, mr, mu, m.dir, 1.15));
gl.uniformMatrix3fv(uMesh['uNormalMat'], false, new Float32Array([mr[0],mr[1],mr[2], mu[0],mu[1],mu[2], -m.dir[0],-m.dir[1],-m.dir[2]]));
gl.drawArrays(gl.TRIANGLES, 0, missileMesh.count);
}
}
buildFrameFX(time);
gl.bindFramebuffer(gl.FRAMEBUFFER, fxFbo);
gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
gl.depthMask(false); gl.depthFunc(gl.LEQUAL);
if (fxVertCount > 0) {
gl.useProgram(progFx); gl.uniformMatrix4fv(uFx['uVP'], false, vp);
gl.bindVertexArray(fxVao);
gl.bindBuffer(gl.ARRAY_BUFFER, fxPosBuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, fxPosData.subarray(0, fxVertCount * 3));
gl.bindBuffer(gl.ARRAY_BUFFER, fxColBuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, fxColData.subarray(0, fxVertCount * 4));
gl.drawArrays(gl.TRIANGLES, 0, fxVertCount);
}
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.disable(gl.DEPTH_TEST); gl.depthMask(true);
gl.useProgram(progComp);
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, worldTex);
gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, jetTex);
gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, fxTex);
gl.uniform1i(uComp['uWorld'], 0); gl.uniform1i(uComp['uJet'], 1); gl.uniform1i(uComp['uFx'], 2);
gl.uniform2f(uComp['uTexel'], 1.0 / internalW, 1.0 / internalH);
gl.bindVertexArray(vaoEmpty); gl.drawArrays(gl.TRIANGLES, 0, 3);
}
// ============================================================================
// HAND-PLOTTED PIXEL ART COCKPIT & EXACT-HORIZON HUD (CANVAS 2D)
// ============================================================================
const FONT_3X5 = {
'0':[7,5,5,5,7],'1':[2,6,2,2,7],'2':[7,1,7,4,7],'3':[7,1,7,1,7],'4':[5,5,7,1,1],
'5':[7,4,7,1,7],'6':[7,4,7,5,7],'7':[7,1,2,2,2],'8':[7,5,7,5,7],'9':[7,5,7,1,7],
'A':[2,5,7,5,5],'B':[6,5,6,5,6],'C':[7,4,4,4,7],'D':[6,5,5,5,6],'E':[7,4,6,4,7],
'F':[7,4,6,4,4],'G':[7,4,5,5,7],'H':[5,5,7,5,5],'I':[7,2,2,2,7],'J':[1,1,1,5,7],
'K':[5,5,6,5,5],'L':[4,4,4,4,7],'M':[5,7,7,5,5],'N':[5,7,7,7,5],'O':[7,5,5,5,7],
'P':[7,5,7,4,4],'Q':[7,5,5,7,1],'R':[6,5,6,5,5],'S':[7,4,7,1,7],'T':[7,2,2,2,2],
'U':[5,5,5,5,7],'V':[5,5,5,5,2],'W':[5,5,7,7,5],'X':[5,5,2,5,5],'Y':[5,5,2,2,2],
'Z':[7,1,2,4,7],'-':[0,0,7,0,0],'.':[0,0,0,0,2],':':[0,2,0,2,0],'/':[1,1,2,4,4],
'+':[0,2,7,2,0],' ':[0,0,0,0,0]
};
function pxRect(x, y, w, h, col) {
hudCtx.fillStyle = col;
hudCtx.fillRect(Math.round(x), Math.round(y), Math.round(w), Math.round(h));
}
function pxLine(x0, y0, x1, y1, col) {
x0 = Math.round(x0); y0 = Math.round(y0); x1 = Math.round(x1); y1 = Math.round(y1);
hudCtx.fillStyle = col;
let dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
let dy = -Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
let err = dx + dy, guard = 0;
while (guard++ < 1200) {
hudCtx.fillRect(x0, y0, 1, 1);
if (x0 === x1 && y0 === y1) break;
const e2 = 2 * err;
if (e2 >= dy) { err += dy; x0 += sx; }
if (e2 <= dx) { err += dx; y0 += sy; }
}
}
function pxDashedLine(x0, y0, x1, y1, col) {
x0 = Math.round(x0); y0 = Math.round(y0); x1 = Math.round(x1); y1 = Math.round(y1);
hudCtx.fillStyle = col;
let dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
let dy = -Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
let err = dx + dy, step = 0;
while (step < 1200) {
if ((step % 5) < 3) hudCtx.fillRect(x0, y0, 1, 1);
if (x0 === x1 && y0 === y1) break;
const e2 = 2 * err;
if (e2 >= dy) { err += dy; x0 += sx; }
if (e2 <= dx) { err += dx; y0 += sy; }
step++;
}
}
function pxCircle(cx, cy, r, col, fill = null) {
cx = Math.round(cx); cy = Math.round(cy); r = Math.round(r);
if (fill) {
hudCtx.fillStyle = fill;
for (let dy = -r; dy <= r; dy++) {
const dx = Math.floor(Math.sqrt(r*r - dy*dy));
hudCtx.fillRect(cx - dx, cy + dy, dx * 2 + 1, 1);
}
}
if (col) {
hudCtx.fillStyle = col;
let x = r, y = 0, d = 1 - r;
while (x >= y) {
hudCtx.fillRect(cx+x,cy+y,1,1); hudCtx.fillRect(cx+y,cy+x,1,1);
hudCtx.fillRect(cx-y,cy+x,1,1); hudCtx.fillRect(cx-x,cy+y,1,1);
hudCtx.fillRect(cx-x,cy-y,1,1); hudCtx.fillRect(cx-y,cy-x,1,1);
hudCtx.fillRect(cx+y,cy-x,1,1); hudCtx.fillRect(cx+x,cy-y,1,1);
y++;
if (d <= 0) d += 2 * y + 1;
else { x--; d += 2 * (y - x) + 1; }
}
}
}
function pxText(str, x, y, col, shadow = null, align = 'left') {
str = String(str).toUpperCase();
const totalW = str.length * 4 - 1;
let ox = Math.round(align === 'center' ? x - totalW * 0.5 : align === 'right' ? x - totalW : x);
const oy = Math.round(y);
for (let i = 0; i < str.length; i++) {
const g = FONT_3X5[str[i]] || FONT_3X5[' '];
for (let row = 0; row < 5; row++) {
const bits = g[row];
for (let colIdx = 0; colIdx < 3; colIdx++) {
if ((bits >> (2 - colIdx)) & 1) {
if (shadow) { hudCtx.fillStyle = shadow; hudCtx.fillRect(ox + colIdx + 1, oy + row + 1, 1, 1); }
hudCtx.fillStyle = col; hudCtx.fillRect(ox + colIdx, oy + row, 1, 1);
}
}
}
ox += 4;
}
}
function projectDirToScreen(dir) {
const vx = dot3(dir, cam.right), vy = dot3(dir, cam.up), vz = dot3(dir, cam.fwd);
if (vz <= 0.05) return null;
const aspect = internalW / internalH, tanH = Math.tan(cam.fov * 0.5);
return [((vx / vz) / (aspect * tanH) * 0.5 + 0.5) * internalW, (0.5 - (vy / vz) / tanH * 0.5) * internalH];
}
function renderCockpitAndHUD(dt, time) {
const W = internalW, H = internalH;
hudCtx.clearRect(0, 0, W, H);
let cockpitAmt = 0;
if (cam.mode === CAM_COCKPIT) cockpitAmt = smoothstep(cam.blend);
else if (cam.prevMode === CAM_COCKPIT) cockpitAmt = 1.0 - smoothstep(cam.blend);
if (cockpitAmt < 0.15 && input.hasMoved) {
const sx = Math.round(((input.touchActive ? input.touchX : input.mouseX) * 0.5 + 0.5) * W);
const sy = Math.round(((input.touchActive ? input.touchY : input.mouseY) * 0.5 + 0.5) * H);
const c = 'rgba(255, 232, 184, 0.72)';
pxRect(sx - 5, sy, 3, 1, c); pxRect(sx + 3, sy, 3, 1, c);
pxRect(sx, sy - 5, 1, 3, c); pxRect(sx, sy + 3, 1, 3, c);
}
if (cockpitAmt <= 0.01) return;
const slideY = Math.round((1.0 - cockpitAmt) * (H * 0.52));
const kts = Math.round(jet.speed * 4.9);
const altFt = Math.max(0, Math.round((jet.pos[1] - SEA_LEVEL) * 32));
const raltFt = Math.max(0, Math.round(jet.ralt * 32));
const hdgDeg = ((Math.round(jet.yaw * 180 / Math.PI) % 360) + 360) % 360;
const vsFpm = Math.round(jet.vSpeed * 120);
const readyMsl = jet.rails.filter(r => r.ready).length;
// 1. Conformal HUD (exact real-horizon pitch ladder)
if (cockpitAmt > 0.35) {
const HUD_G = '#7aff92', HUD_S = 'rgba(10, 26, 16, 0.72)', HUD_W = '#ff6b52';
const yaw = jet.yaw;
for (const deg of [-30, -20, -10, 0, 10, 20, 30]) {
const rad = deg * Math.PI / 180, halfSpan = deg === 0 ? 0.24 : 0.11, gap = 0.032;
const cR = Math.cos(rad), sR = Math.sin(rad);
for (const sgn of [-1, 1]) {
const y0 = yaw + sgn * gap, y1 = yaw + sgn * halfSpan;
const p0 = projectDirToScreen([Math.sin(y0)*cR, sR, -Math.cos(y0)*cR]);
const p1 = projectDirToScreen([Math.sin(y1)*cR, sR, -Math.cos(y1)*cR]);
if (!p0 || !p1) continue;
const hudBot = Math.round(H * 0.58) + slideY;
if ((p0[1] > hudBot && p1[1] > hudBot) || (p0[1] < 24 && p1[1] < 24)) continue;
if (deg < 0) pxDashedLine(p0[0], p0[1], p1[0], p1[1], HUD_G);
else pxLine(p0[0], p0[1], p1[0], p1[1], HUD_G);
if (deg !== 0 && sgn === 1) pxText(Math.abs(deg), p1[0] + 3, p1[1] - 2, HUD_G, HUD_S);
}
}
const cx = Math.round(W * 0.5), cy = Math.round(H * 0.36);
pxLine(cx-10, cy, cx-4, cy, HUD_G); pxLine(cx-4, cy, cx-2, cy+2, HUD_G);
pxLine(cx-2, cy+2, cx, cy, HUD_G); pxLine(cx, cy, cx+2, cy+2, HUD_G);
pxLine(cx+2, cy+2, cx+4, cy, HUD_G); pxLine(cx+4, cy, cx+10, cy, HUD_G);
pxRect(cx, cy - 1, 1, 1, HUD_G);
const tapeY = 14, tapeW = 112;
pxLine(cx - tapeW/2, tapeY + 8, cx + tapeW/2, tapeY + 8, HUD_G);
pxLine(cx, tapeY + 9, cx - 2, tapeY + 12, HUD_G);
pxLine(cx, tapeY + 9, cx + 2, tapeY + 12, HUD_G);
const startDeg = Math.floor((hdgDeg - 35) / 5) * 5;
for (let d = startDeg; d <= hdgDeg + 35; d += 5) {
const x = Math.round(cx + (d - hdgDeg) * 1.6);
if (x < cx - tapeW/2 || x > cx + tapeW/2) continue;
const wd = ((d % 360) + 360) % 360;
pxLine(x, tapeY + (wd % 15 === 0 ? 4 : 6), x, tapeY + 8, HUD_G);
if (wd % 30 === 0) {
const lbl = wd === 0 ? 'N' : wd === 90 ? 'E' : wd === 180 ? 'S' : wd === 270 ? 'W' : String(wd / 10).padStart(2, '0');
pxText(lbl, x, tapeY - 2, HUD_G, HUD_S, 'center');
}
}
pxRect(cx - 9, tapeY + 13, 19, 7, 'rgba(12, 24, 16, 0.72)');
pxText(String(hdgDeg).padStart(3, '0'), cx, tapeY + 14, HUD_G, null, 'center');
const lx = Math.round(W * 0.5 - 86);
pxRect(lx - 22, cy - 5, 24, 9, 'rgba(12, 24, 16, 0.55)');
pxLine(lx + 2, cy - 5, lx + 2, cy + 4, HUD_G);
pxText(String(kts).padStart(3, ' '), lx - 20, cy - 3, HUD_G, HUD_S);
pxText('KTS', lx - 20, cy + 7, HUD_G, HUD_S);
pxText(`${jet.gForce.toFixed(1)}G`, lx - 20, cy + 16, HUD_G, HUD_S);
if (jet.ab > 0.35) pxText('AB', lx - 20, cy - 14, '#ffd266', HUD_S);
const rx = Math.round(W * 0.5 + 86);
pxRect(rx - 2, cy - 5, 28, 9, 'rgba(12, 24, 16, 0.55)');
pxLine(rx - 2, cy - 5, rx - 2, cy + 4, HUD_G);
pxText(String(altFt).padStart(4, ' '), rx + 1, cy - 3, HUD_G, HUD_S);
pxText('ALT', rx + 1, cy + 7, HUD_G, HUD_S);
pxText(`R ${String(raltFt).padStart(4, ' ')}`, rx - 4, cy + 16, jet.lowAlt ? HUD_W : HUD_G, HUD_S);
pxText(`MSL ${readyMsl}`, lx - 20, cy + 28, readyMsl > 0 ? HUD_G : HUD_W, HUD_S);
if (jet.pullUp && (Math.floor(time * 7) & 1)) pxText('PULL UP', cx, cy + 22, HUD_W, HUD_S, 'center');
else if (jet.waterSkim) pxText('SKIM', cx, cy + 22, '#7ce8ff', HUD_S, 'center');
else if (jet.lowAlt) pxText('LOW ALT', cx, cy + 22, '#ffbe55', HUD_S, 'center');
}
// 2. Canopy frame & HUD combiner posts
const C_FRAME = '#1e1c2a', C_RIM = '#3e3852';
const panelTop = Math.round(H * 0.59) + slideY;
for (let y = 0; y < panelTop; y++) {
const wSide = Math.round(8 + (y / Math.max(1, panelTop)) * 14);
pxRect(0, y, wSide, 1, C_FRAME); pxRect(wSide, y, 1, 1, C_RIM);
pxRect(W - wSide, y, wSide, 1, C_FRAME); pxRect(W - wSide - 1, y, 1, 1, C_RIM);
}
pxRect(0, 0, W, 6, C_FRAME); pxRect(0, 6, W, 1, C_RIM);
const hcx = Math.round(W * 0.5), hudW = 92;
pxLine(hcx - hudW/2, panelTop, hcx - hudW/2 + 8, panelTop - 52, '#2d2b3c');
pxLine(hcx + hudW/2, panelTop, hcx + hudW/2 - 8, panelTop - 52, '#2d2b3c');
pxLine(hcx - hudW/2 + 8, panelTop - 52, hcx + hudW/2 - 8, panelTop - 52, '#3c4850');
// 3. Hand-plotted pixel instrument panel
const panelH = H - panelTop;
if (panelH <= 4) return;
pxRect(0, panelTop - 3, W, 3, '#171422');
pxRect(0, panelTop - 4, W, 1, '#584862');
pxRect(0, panelTop, W, panelH, '#232230');
pxRect(0, panelTop + 2, W, 2, '#181724');
const midX = Math.round(W * 0.5), row1Y = panelTop + 28, row2Y = panelTop + 78, dialR = 20;
function drawBezel(cx, cy, r) {
pxCircle(cx, cy, r + 2, '#12111a', '#161620');
pxCircle(cx, cy, r + 1, '#3d3c4e');
pxCircle(cx, cy, r, '#0d0e14', '#10121a');
}
// Throttle lever (follows afterburner)
const thX = Math.max(18, midX - 186), thY = panelTop + 14;
pxRect(thX - 10, thY, 22, 82, '#181822'); pxRect(thX - 9, thY + 1, 20, 80, '#2a2a38');
pxRect(thX - 2, thY + 8, 5, 66, '#0d0d14');
pxText('THR', thX + 1, thY - 7, '#a89eb6', null, 'center');
pxText('AB', thX + 1, thY + 3, jet.ab > 0.3 ? '#ff9e42' : '#6a5f78', null, 'center');
for (let i = 0; i < 6; i++) {
pxRect(thX - 7, thY + 12 + i * 11, 3, 1, i === 0 ? '#ff6a3c' : '#6c6a80');
pxRect(thX + 5, thY + 12 + i * 11, 3, 1, i === 0 ? '#ff6a3c' : '#6c6a80');
}
const leverY = Math.round(lerp(thY + 54, thY + 14, jet.ab));
pxRect(thX - 9, leverY - 4, 20, 9, '#12121a');
pxRect(thX - 8, leverY - 3, 18, 7, jet.ab > 0.3 ? '#d86636' : '#606678');
pxRect(thX - 7, leverY - 2, 16, 2, jet.ab > 0.3 ? '#ffb866' : '#9aa0b4');
// Airspeed indicator
const asiX = midX - 122;
drawBezel(asiX, row1Y, dialR);
for (let i = 0; i < 12; i++) {
const a = -Math.PI * 0.75 + (i / 11) * Math.PI * 1.5;
pxLine(asiX + Math.cos(a)*(dialR-4), row1Y + Math.sin(a)*(dialR-4),
asiX + Math.cos(a)*(dialR-1), row1Y + Math.sin(a)*(dialR-1), i > 8 ? '#e85a4a' : '#c8c4d0');
}
pxText('ASI', asiX, row1Y - 10, '#888c9e', null, 'center');
pxText(String(kts), asiX, row1Y + 7, '#e6e2d8', null, 'center');
const asiAng = -Math.PI * 0.75 + clamp((kts - 200) / 700, 0, 1) * Math.PI * 1.5;
pxLine(asiX, row1Y, asiX + Math.cos(asiAng)*(dialR-4), row1Y + Math.sin(asiAng)*(dialR-4), '#ffd266');
pxRect(asiX - 1, row1Y - 1, 3, 3, '#c8c4d0');
// Artificial horizon
const adiX = midX - 72;
drawBezel(adiX, row1Y, dialR);
const sinR = Math.sin(-(jet.bank + jet.rollSpin)), cosR = Math.cos(-(jet.bank + jet.rollSpin));
const pitchOff = clamp(jet.pitch * 24, -14, 14);
for (let dy = -dialR + 1; dy <= dialR - 1; dy++) {
const maxDx = Math.floor(Math.sqrt((dialR - 1)*(dialR - 1) - dy*dy));
for (let dx = -maxDx; dx <= maxDx; dx++) {
const ry = dx * sinR + dy * cosR - pitchOff;
hudCtx.fillStyle = Math.abs(ry) < 0.9 ? '#f2ede0' : (ry < 0 ? '#3b73a8' : '#7c4c2c');
hudCtx.fillRect(adiX + dx, row1Y + dy, 1, 1);
}
}
pxRect(adiX - 10, row1Y, 7, 2, '#ffd248'); pxRect(adiX + 4, row1Y, 7, 2, '#ffd248'); pxRect(adiX - 1, row1Y, 2, 2, '#ffd248');
// Altimeter with digits
const altX = midX - 22;
drawBezel(altX, row1Y, dialR);
for (let i = 0; i < 10; i++) {
const a = -Math.PI * 0.5 + (i / 10) * Math.PI * 2;
pxLine(altX + Math.cos(a)*(dialR-4), row1Y + Math.sin(a)*(dialR-4),
altX + Math.cos(a)*(dialR-1), row1Y + Math.sin(a)*(dialR-1), '#c8c4d0');
}
pxText('ALT', altX, row1Y - 11, '#888c9e', null, 'center');
pxRect(altX - 11, row1Y + 4, 23, 8, '#08090e'); pxRect(altX - 10, row1Y + 5, 21, 6, '#141720');
pxText(String(altFt).padStart(4, '0'), altX, row1Y + 6, '#f4f0e0', null, 'center');
const a1000 = -Math.PI * 0.5 + ((altFt % 10000) / 10000) * Math.PI * 2;
const a100 = -Math.PI * 0.5 + ((altFt % 1000) / 1000) * Math.PI * 2;
pxLine(altX, row1Y, altX + Math.cos(a1000)*9, row1Y + Math.sin(a1000)*9, '#ff9852');
pxLine(altX, row1Y, altX + Math.cos(a100)*(dialR-4), row1Y + Math.sin(a100)*(dialR-4), '#f4f0e0');
pxRect(altX - 1, row1Y - 1, 3, 3, '#c8c4d0');
// Turn & slip
const tsX = midX - 122;
drawBezel(tsX, row2Y, dialR);
pxText('TURN', tsX, row2Y - 12, '#888c9e', null, 'center');
const tAng = clamp(jet.turnRate * 0.45, -0.65, 0.65), tx = Math.cos(tAng) * 11, ty = Math.sin(tAng) * 11;
pxLine(tsX - tx, row2Y - 2 - ty, tsX + tx, row2Y - 2 + ty, '#f4f0e0');
pxLine(tsX, row2Y - 2, tsX + Math.sin(tAng)*5, row2Y - 2 - Math.cos(tAng)*5, '#f4f0e0');
pxRect(tsX - 11, row2Y + 8, 23, 5, '#1c242c');
pxRect(tsX - 2, row2Y + 8, 1, 5, '#8894a4'); pxRect(tsX + 2, row2Y + 8, 1, 5, '#8894a4');
pxRect(Math.round(tsX + clamp(jet.slip * 12, -8, 8)) - 1, row2Y + 9, 3, 3, '#e8e4d8');
// Heading indicator (HSI)
const hsiX = midX - 72;
drawBezel(hsiX, row2Y, dialR);
for (const [lbl, off, col] of [['N',0,'#ff6a4a'],['E',Math.PI*0.5,'#c8c4d0'],['S',Math.PI,'#c8c4d0'],['W',Math.PI*1.5,'#c8c4d0']]) {
const a = -jet.yaw + off - Math.PI * 0.5;
pxText(lbl, hsiX + Math.cos(a)*12, row2Y + Math.sin(a)*12 - 2, col, null, 'center');
}
pxRect(hsiX, row2Y - dialR + 1, 1, 4, '#ffd248');
pxLine(hsiX - 5, row2Y, hsiX + 5, row2Y, '#ffd248'); pxLine(hsiX, row2Y - 5, hsiX, row2Y + 5, '#ffd248');
// Vertical speed indicator (VSI)
const vsiX = midX - 22;
drawBezel(vsiX, row2Y, dialR);
pxText('VSI', vsiX, row2Y - 10, '#888c9e', null, 'center');
pxText('UP', vsiX + 4, row2Y - 4, '#6c7288'); pxText('DN', vsiX + 4, row2Y + 4, '#6c7288');
for (let i = -3; i <= 3; i++) {
const a = Math.PI + i * 0.42;
pxLine(vsiX + Math.cos(a)*(dialR-4), row2Y + Math.sin(a)*(dialR-4),
vsiX + Math.cos(a)*(dialR-1), row2Y + Math.sin(a)*(dialR-1), '#c8c4d0');
}
const vsAng = Math.PI + clamp(vsFpm / 4000, -1, 1) * 1.35;
pxLine(vsiX, row2Y, vsiX + Math.cos(vsAng)*(dialR-4), row2Y + Math.sin(vsAng)*(dialR-4), '#7aff92');
pxRect(vsiX - 1, row2Y - 1, 3, 3, '#c8c4d0');
// Amber ground-mapping radar with real terrain sweep
const radCx = midX + 42, radCy = panelTop + 52, radS = 36;
pxRect(radCx - radS - 3, radCy - radS - 3, radS*2 + 6, radS*2 + 6, '#12111a');
pxRect(radCx - radS - 2, radCy - radS - 2, radS*2 + 4, radS*2 + 4, '#3e3a4c');
pxRect(radCx - radS, radCy - radS, radS*2, radS*2, '#140b04');
radarAngleRef.ang = (radarAngleRef.ang + dt * 2.2) % (Math.PI * 2);
const sweepA = radarAngleRef.ang, sinY = Math.sin(jet.yaw), cosY = Math.cos(jet.yaw);
for (let py = -radS + 2; py <= radS - 2; py += 2) {
for (let px = -radS + 2; px <= radS - 2; px += 2) {
if (Math.hypot(px, py) > radS - 2) continue;
const fDist = (-py / radS) * 520.0, rDist = (px / radS) * 520.0;
const h = getTerrainHeightJS(jet.pos[0] + sinY * fDist + cosY * rDist, jet.pos[2] - cosY * fDist + sinY * rDist);
let angDiff = ((sweepA - Math.atan2(py, px)) % (Math.PI * 2) + Math.PI * 2) % (Math.PI * 2);
const decay = Math.max(0.22, 1.0 - angDiff / (Math.PI * 1.8));
if (h > SEA_LEVEL + 0.6) {
const bright = (0.32 + clamp((h - SEA_LEVEL) / 72.0, 0, 1) * 0.68) * decay;
hudCtx.fillStyle = bright > 0.68 ? '#ffcc55' : (bright > 0.40 ? '#cc761c' : '#64340a');
hudCtx.fillRect(radCx + px, radCy + py, 2, 2);
} else if (angDiff < 0.25) {
hudCtx.fillStyle = '#2a1606'; hudCtx.fillRect(radCx + px, radCy + py, 2, 2);
}
}
}
pxCircle(radCx, radCy, Math.round(radS * 0.5), '#4a280a');
pxCircle(radCx, radCy, radS - 2, '#5c3410');
pxLine(radCx, radCy, radCx + Math.cos(sweepA)*(radS-2), radCy + Math.sin(sweepA)*(radS-2), '#ffe084');
pxRect(radCx - 1, radCy - 1, 3, 3, '#fff0b0');
pxText('GMR', radCx - radS + 2, radCy - radS + 2, '#d48628');
// Engine gauges, local time clock & warning lamps
const engX = midX + 94, engY = panelTop + 14;
pxRect(engX, engY, 38, 48, '#14141e'); pxRect(engX + 1, engY + 1, 36, 46, '#1c1d28');
pxText('ENG L R', engX + 3, engY + 3, '#9a96ac');
const rpmFrac = clamp(0.62 + jet.ab * 0.36 + Math.sin(time * 9) * 0.015, 0.5, 1.0);
const egtFrac = clamp(0.48 + jet.ab * 0.48, 0.4, 1.0);
for (const [bx, frac, col] of [
[engX + 5, rpmFrac, '#7aff92'], [engX + 13, egtFrac, jet.ab > 0.3 ? '#ff643c' : '#ffba48'],
[engX + 22, rpmFrac, '#7aff92'], [engX + 30, egtFrac, jet.ab > 0.3 ? '#ff643c' : '#ffba48']
]) {
pxRect(bx, engY + 12, 4, 28, '#0c0d14');
const bh = Math.round(frac * 28);
pxRect(bx, engY + 12 + (28 - bh), 4, bh, col);
}
pxText('RPM EGT', engX + 3, engY + 41, '#78768c');
const now = new Date();
const clkStr = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`;
const clkY = engY + 52;
pxRect(engX, clkY, 38, 16, '#101018'); pxRect(engX + 1, clkY + 1, 36, 14, '#1a1c26');
pxText('TIME', engX + 19, clkY + 2, '#7e8298', null, 'center');
pxText(clkStr, engX + 19, clkY + 9, '#ffb852', null, 'center');
const lampX = engX + 44;
const lamps = [
{ lbl: 'PULL UP', on: jet.pullUp, col: '#ff4238', dim: '#361618' },
{ lbl: 'LOW ALT', on: jet.lowAlt, col: '#ffae34', dim: '#342414' },
{ lbl: 'A/B ON', on: jet.ab > 0.35, col: '#ff8a34', dim: '#321e14' },
{ lbl: 'MSL RDY', on: readyMsl > 0, col: '#68ff88', dim: '#162c1c' },
{ lbl: 'REARM', on: readyMsl < 4, col: '#6ad8ff', dim: '#162630' }
];
for (let i = 0; i < lamps.length; i++) {
const L = lamps[i], ly = engY + i * 14;
pxRect(lampX, ly, 34, 11, '#0e0e16');
pxRect(lampX + 1, ly + 1, 32, 9, L.on ? L.col : L.dim);
pxText(L.lbl, lampX + 17, ly + 3, L.on ? '#120e18' : '#646276', null, 'center');
}
}
// ============================================================================
// MAIN LOOP, DYNAMIC RESOLUTION SCALER & WORKER BOOTSTRAP
// ============================================================================
let running = false, lastTs = 0, simTime = 0, emaDt = 0.016, slowSec = 0, fastSec = 0;
function frame(ts) {
if (!running) return;
requestAnimationFrame(frame);
if (!lastTs) lastTs = ts;
const rawDt = (ts - lastTs) * 0.001;
lastTs = ts;
const dt = Math.min(0.05, Math.max(0.001, rawDt));
simTime += dt;
emaDt = emaDt * 0.92 + rawDt * 0.08;
if (emaDt > 0.025) {
slowSec += dt; fastSec = 0;
if (slowSec > 1.6 && resTierIdx < RES_TIERS.length - 1) { resTierIdx++; slowSec = 0; resizeBuffers(); }
} else if (emaDt < 0.015) {
fastSec += dt; slowSec = 0;
if (fastSec > 3.5 && resTierIdx > 0) { resTierIdx--; fastSec = 0; resizeBuffers(); }
}
stepSimulation(dt, simTime);
renderWebGL(simTime);
renderCockpitAndHUD(dt, simTime);
}
window.__PATROL__ = {
getState: () => ({
running, simTime, res: [internalW, internalH], camMode: CAM_NAMES[cam.mode], camBlend: cam.blend,
jetPos: [...jet.pos], jetYaw: jet.yaw, jetPitch: jet.pitch, jetSpeed: jet.speed, jetRalt: jet.ralt,
pullUp: jet.pullUp, readyMissiles: jet.rails.filter(r => r.ready).length,
activeMissiles: activeMissiles.length, impacts: impacts.length
}),
setView: (idx) => { cam.prevMode = idx; cam.mode = idx; cam.blend = 1.0; viewBadge.textContent = CAM_NAMES[idx]; dismissTitle(); },
fireMissile, triggerBarrelRoll, cycleCamera,
step: (dt) => { simTime += dt; stepSimulation(dt, simTime); },
renderNow: () => { renderWebGL(simTime); renderCockpitAndHUD(0.016, simTime); },
setInput: (mx, my, ab) => { dismissTitle(); input.mouseX = clamp(mx, -1, 1); input.mouseY = clamp(my, -1, 1); input.abHold = !!ab; },
spawnTestStrike: () => {
const x = jet.pos[0] + jet.fwd[0] * 68, z = jet.pos[2] + jet.fwd[2] * 68;
const rawH = getTerrainHeightJS(x, z);
spawnImpact([x, Math.max(SEA_LEVEL, rawH), z], rawH <= SEA_LEVEL + 0.35);
}
};
const barFill = document.getElementById('bar-fill');
const loadStage = document.getElementById('load-stage');
const loader = document.getElementById('loader');
const worker = createTerrainWorker();
worker.onmessage = (e) => {
const msg = e.data;
if (msg.type === 'progress') {
barFill.style.width = `${msg.pct}%`;
loadStage.textContent = msg.stage;
} else if (msg.type === 'done') {
terrainRGBA = new Uint8Array(msg.rgba);
terrainTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, terrainTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, MAP_SIZE, MAP_SIZE, 0, gl.RGBA, gl.UNSIGNED_BYTE, terrainRGBA);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
worker.terminate();
let bestX = 512, bestZ = 512, bestScore = -1;
for (let i = 0; i < 40; i++) {
const tx = (i * 173 + 120) % WORLD_SIZE, tz = (i * 293 + 240) % WORLD_SIZE;
const hHere = getTerrainHeightJS(tx, tz);
const hAhead = getTerrainHeightJS(tx + SUN_DIR[0] * 340, tz + SUN_DIR[2] * 340);
if (hHere < SEA_LEVEL - 2 && hAhead > SEA_LEVEL + 18) {
const sc = hAhead - hHere;
if (sc > bestScore) { bestScore = sc; bestX = tx; bestZ = tz; }
}
}
jet.pos = [bestX, CRUISE_ALT, bestZ];
jet.yaw = Math.atan2(SUN_DIR[0], -SUN_DIR[2]) + 0.35;
updateJetBasis();
barFill.style.width = '100%';
loadStage.textContent = 'Cleared for patrol.';
setTimeout(() => loader.classList.add('done'), 180);
running = true;
requestAnimationFrame(frame);
}
};
worker.postMessage({
size: MAP_SIZE, sunDir: SUN_DIR, seaNorm: SEA_LEVEL / MAX_TERRAIN_H,
maxH: MAX_TERRAIN_H, worldSize: WORLD_SIZE
});
})();
</script>
</body>
</html>