← Flight Simulator results

Flight Simulator

inkling · full

Initial view of Flight Simulator

Reviews & generation details

Reviews

No human review yet. Unreviewed does not mean unsuccessful.

Generation context

Imported historical artifact. Its exact original instructions and lineage are not known.

Generation prompt · exact text unavailable

See the current prompt for reference. It may differ from the instructions used to generate this artifact.

Inspect original source 27,750 bytes · SHA-256 ecabb5d4831a
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apex Aero — Flight Simulator</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Rajdhani:wght@300;500;700&display=swap');

* { margin: 0; padding: 0; box-sizing: border-box; }

body {
  background: #020204;
  color: #e8e8f0;
  font-family: 'Rajdhani', sans-serif;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
}

/* HUD */
#hud {
  position: fixed;
  inset: 0;
  pointer-events: none;
  z-index: 10;
  font-family: 'Orbitron', sans-serif;
}

.hud-top {
  position: absolute; top: 20px; left: 30px; right: 30px;
  display: flex; justify-content: space-between; align-items: flex-start;
}

.hud-left { display: flex; flex-direction: column; gap: 8px; }
.hud-right { display: flex; flex-direction: column; gap: 8px; align-items: flex-end; }

.hud-card {
  background: rgba(10, 15, 30, 0.65);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255,255,255,0.08);
  border-radius: 10px;
  padding: 12px 20px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.5), inset 0 0 20px rgba(0,200,255,0.05);
  min-width: 180px;
}

.hud-card h2 {
  font-size: 10px; letter-spacing: 2px; color: #7a889e; text-transform: uppercase; margin-bottom: 4px;
}
.hud-card .val {
  font-size: 22px; font-weight: 700; color: #00f0ff; text-shadow: 0 0 8px rgba(0,240,255,0.4);
}
.hud-card .sub {
  font-size: 11px; color: #aaa; margin-top: 2px;
}

/* Artificial Horizon in center-top */
#horizon {
  position: absolute; top: 80px; left: 50%; transform: translateX(-50%);
  width: 320px; height: 160px;
  background: rgba(10,15,30,0.6);
  border: 1px solid rgba(255,255,255,0.1);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0,0,0,0.6);
  display: flex; flex-direction: column; align-items: center; justify-content: center;
}

#horizon .line {
  width: 260px; height: 2px; background: rgba(255,255,255,0.3);
  position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
}

#horizon .pitch-marker {
  position: absolute; left: 50%; width: 2px; height: 60px; background: rgba(255,255,255,0.15);
  transform-origin: center 30px;
}

#horizon .roll-marker {
  position: absolute; top: 50%; left: 50%; width: 2px; height: 140px; background: rgba(255,255,255,0.1);
  transform-origin: center 70px;
}

#horizon .pitch-num {
  position: absolute; left: 20px; color: #fff; font-size: 11px; font-family: monospace;
}

/* Mode indicator bottom */
#mode-bar {
  position: absolute; bottom: 30px; left: 50%; transform: translateX(-50%);
  display: flex; gap: 20px; align-items: center;
}

.mode-btn {
  background: rgba(10,15,30,0.7);
  border: 1px solid rgba(255,255,255,0.15);
  border-radius: 8px; padding: 10px 24px; color: #fff;
  font-family: 'Orbitron', sans-serif; font-size: 12px; letter-spacing: 1px;
  cursor: pointer; pointer-events: auto; transition: all .2s;
  text-transform: uppercase;
}
.mode-btn:hover { border-color: #00f0ff; color: #00f0ff; box-shadow: 0 0 15px rgba(0,240,255,0.2); }
.mode-btn.active { background: rgba(0,240,255,0.15); border-color: #00f0ff; color: #00f0ff; }

/* Main overlay/menu */
#overlay {
  position: fixed; inset: 0; z-index: 100;
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  background: linear-gradient(160deg, rgba(2,2,8,0.92) 0%, rgba(10,15,30,0.95) 60%, rgba(0,20,40,0.9) 100%);
  pointer-events: auto;
}

#overlay h1 {
  font-family: 'Orbitron', sans-serif; font-size: 72px; letter-spacing: 12px;
  color: #fff; text-shadow: 0 0 40px rgba(0,240,255,0.3), 0 4px 20px rgba(0,0,0,0.8);
  margin-bottom: 8px;
}
#overlay .subtitle { font-size: 16px; letter-spacing: 6px; color: #7a889e; margin-bottom: 60px; }

#fleet-grid {
  display: grid; grid-template-columns: repeat(3, 1fr); gap: 30px; max-width: 1000px; padding: 0 40px;
}

.fleet-card {
  background: rgba(255,255,255,0.03);
  border: 1px solid rgba(255,255,255,0.08);
  border-radius: 16px; padding: 30px; text-align: center;
  transition: all .3s ease; cursor: pointer; pointer-events: auto;
  position: relative; overflow: hidden;
}
.fleet-card:hover { border-color: rgba(0,240,255,0.4); transform: translateY(-8px); box-shadow: 0 20px 40px rgba(0,240,255,0.08); }
.fleet-card.selected { border-color: #00f0ff; box-shadow: 0 0 30px rgba(0,240,255,0.2); }
.fleet-card h3 { font-family: 'Orbitron', sans-serif; font-size: 20px; margin-bottom: 8px; color: #fff; }
.fleet-card .tag { font-size: 10px; letter-spacing: 2px; color: #00f0ff; text-transform: uppercase; margin-bottom: 16px; }
.fleet-card .stats { display: flex; justify-content: center; gap: 12px; flex-wrap: wrap; }
.fleet-card .stat-pill { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 20px; padding: 4px 12px; font-size: 11px; color: #ccc; }
.fleet-card .stat-pill b { color: #fff; font-family: 'Orbitron'; }

#start-btn {
  margin-top: 40px; padding: 16px 48px; font-family: 'Orbitron', sans-serif; font-size: 16px;
  letter-spacing: 3px; text-transform: uppercase; color: #fff; background: linear-gradient(135deg, #00f0ff 0%, #0066cc 100%);
  border: none; border-radius: 8px; cursor: pointer; pointer-events: auto;
  box-shadow: 0 0 30px rgba(0,240,255,0.3); transition: all .3s;
}
#start-btn:hover { box-shadow: 0 0 50px rgba(0,240,255,0.6); transform: scale(1.05); }
#start-btn:disabled { opacity: 0.3; pointer-events: none; }

/* Flight mode labels */
#mode-label {
  position: absolute; top: 20px; right: 30px; text-align: right; pointer-events: none;
}
#mode-label h2 { font-family: 'Orbitron', sans-serif; font-size: 14px; letter-spacing: 3px; color: #fff; text-shadow: 0 2px 10px rgba(0,0,0,0.8); }
#mode-label .desc { font-size: 12px; color: #aaa; }
</style>
</head>
<body>

<div id="overlay">
  <h1>APEX AERO</h1>
  <div class="subtitle">PHYSICALLY ACCURATE FLIGHT SIMULATION</div>
  <div id="fleet-grid">
    <div class="fleet-card" data-idx="0" onclick="selectAircraft(0)">
      <h3>SKYLARK C152</h3>
      <div class="tag">Light Prop / Training</div>
      <div class="stats">
        <span class="stat-pill">Mass <b>680 kg</b></span>
        <span class="stat-pill">Lift <b>High</b></span>
        <span class="stat-pill">Thrust <b>150 hp</b></span>
        <span class="stat-pill">Turn <b>Smooth</b></span>
      </div>
      <p style="margin-top:14px;font-size:11px;color:#aaa;">Ideal for takeoff/landing practice. Forgiving stall profile.</p>
    </div>
    <div class="fleet-card selected" data-idx="1" onclick="selectAircraft(1)">
      <h3>VIPER F-16</h3>
      <div class="tag">High-Performance Fighter</div>
      <div class="stats">
        <span class="stat-pill">Mass <b>980 kg</b></span>
        <span class="stat-pill">Lift <b>Medium</b></span>
        <span class="stat-pill">Thrust <b>28 kN</b></span>
        <span class="stat-pill">Turn <b>Aggressive</b></span>
      </div>
      <p style="margin-top:14px;font-size:11px;color:#aaa;">Extreme maneuverability. High-speed dogfight specialist.</p>
    </div>
    <div class="fleet-card" data-idx="2" onclick="selectAircraft(2)">
      <h3>COLOSSUS C-47</h3>
      <div class="tag">Heavy Transport</div>
      <div class="stats">
        <span class="stat-pill">Mass <b>4,200 kg</b></span>
        <span class="stat-pill">Lift <b>Low</b></span>
        <span class="stat-pill">Thrust <b>3,000 hp</b></span>
        <span class="stat-pill">Turn <b>Wide</b></span>
      </div>
      <p style="margin-top:14px;font-size:11px;color:#aaa;">Requires long runways. Slow response, massive inertia.</p>
    </div>
  </div>
  <button id="start-btn" onclick="startFlight()">INITIATE FLIGHT</button>
</div>

<div id="hud" style="display:none;">
  <div class="hud-top">
    <div class="hud-left">
      <div class="hud-card">
        <h2>AIRCRAFT</h2>
        <div class="val" id="craft-name">VIPER F-16</div>
        <div class="sub" id="craft-sub">Fighter / Dogfight</div>
      </div>
      <div class="hud-card">
        <h2>ENGINE</h2>
        <div class="val" id="engine-rpm">8,400 RPM</div>
        <div class="sub" id="engine-throttle">THROTTLE 85%</div>
      </div>
    </div>
    <div class="hud-right">
      <div class="hud-card">
        <h2>AIRSPEED</h2>
        <div class="val" id="airspeed">340 KT</div>
        <div class="sub">TRUE AIRSPEED</div>
      </div>
      <div class="hud-card">
        <h2>ALTITUDE</h2>
        <div class="val" id="altitude">2,450 FT</div>
        <div class="sub">AGL / MSL</div>
      </div>
    </div>
  </div>

  <div id="horizon">
    <div class="pitch-marker" id="pitch-marker"></div>
    <div class="roll-marker" id="roll-marker"></div>
    <div class="line"></div>
    <div class="pitch-num" style="top:10px;">+60°</div>
    <div class="pitch-num" style="bottom:10px;top:auto;">-60°</div>
  </div>

  <div id="mode-label">
    <h2 id="mode-title">TAKEOFF / LANDING</h2>
    <div class="desc" id="mode-desc">Maintain runway heading, manage lift-off speed, execute safe descent.</div>
  </div>

  <div id="mode-bar">
    <button class="mode-btn active" onclick="setMode('takeoff')">TAKEOFF / LANDING</button>
    <button class="mode-btn" onclick="setMode('dogfight')">DOGFIGHT</button>
  </div>
</div>

<script>
/* ============================================================
   APEX AERO — PHYSICALLY-ACCURATE FLIGHT SIMULATOR
   ============================================================ */

// --- Constants ---
const G = 9.81; // m/s^2
const AIR_DENSITY_SEA = 1.225; // kg/m^3
const WING_AREA = 18.0; // m^2 (approx reference)

// --- Aircraft Profiles ---
const aircraftProfiles = [
  {
    name: "Skylark C152",
    mass: 680,
    enginePowerHP: 150,
    maxThrustN: 2200,
    liftCoef: 1.4,
    dragCoef: 0.035,
    rollRate: 2.5,
    pitchRate: 1.8,
    yawRate: 1.0,
    stallSpeed: 18,
    color: 0x2288aa
  },
  {
    name: "Viper F-16",
    mass: 980,
    enginePowerHP: 28000,
    maxThrustN: 28000,
    liftCoef: 0.9,
    dragCoef: 0.025,
    rollRate: 5.5,
    pitchRate: 4.2,
    yawRate: 2.8,
    stallSpeed: 55,
    color: 0x444444
  },
  {
    name: "Colossus C-47",
    mass: 4200,
    enginePowerHP: 3000,
    maxThrustN: 12000,
    liftCoef: 1.1,
    dragCoef: 0.055,
    rollRate: 0.6,
    pitchRate: 0.5,
    yawRate: 0.35,
    stallSpeed: 45,
    color: 0xaa6611
  }
];

// --- Scene State ---
let scene, camera, renderer;
let aircraftMesh, propMesh;
let terrainMesh, terrainGeometry, terrainMaterial;
let aircraftProfile = aircraftProfiles[1];
let selectedAircraftIdx = 1;

// Flight state
let pos = new THREE.Vector3(0, 50, 0); // x, y (up), z
let vel = new THREE.Vector3(0, 0, 0);
let quat = new THREE.Quaternion();
let angularVel = new THREE.Vector3(0, 0, 0);

// Controls
let throttle = 0.65;
let pitchInput = 0; // -1..1
let rollInput = 0;
let yawInput = 0;

let mode = 'takeoff'; // 'takeoff' or 'dogfight'
let clock = new THREE.Clock();

// Audio
let audioCtx, engineOsc, engineGain, windGain, windNoise;
let engineFreqTarget = 0;

// --- Initialization ---
function initThree() {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x081220);
  scene.fog = new THREE.FogExp2(0x081220, 0.008);

  // Camera (chase / cockpit)
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 5000);
  camera.position.set(0, 60, -20);

  renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  document.body.appendChild(renderer.domElement);

  // Lights
  const hemi = new THREE.HemisphereLight(0xffffff, 0x334455, 0.9);
  scene.add(hemi);

  const sun = new THREE.DirectionalLight(0xfff5dd, 1.4);
  sun.position.set(100, 300, 50);
  sun.castShadow = true;
  sun.shadow.mapSize.width = 2048;
  sun.shadow.mapSize.height = 2048;
  sun.shadow.camera.left = -200;
  sun.shadow.camera.right = 200;
  sun.shadow.camera.top = 200;
  sun.shadow.camera.bottom = -200;
  sun.shadow.camera.near = 1;
  sun.shadow.camera.far = 1000;
  scene.add(sun);

  // Ambient
  scene.add(new THREE.AmbientLight(0x8899aa, 0.3));

  // Sky dome
  const skyGeo = new THREE.SphereGeometry(1500, 32, 32);
  const skyMat = new THREE.MeshBasicMaterial({ color: 0x0a1025, side: THREE.BackSide });
  scene.add(new THREE.Mesh(skyGeo, skyMat));

  // Procedural Terrain
  generateTerrain();

  // Aircraft
  buildAircraft();

  // Audio setup
  initAudio();

  window.addEventListener('keydown', onKey);
  window.addEventListener('keyup', onKey);
  window.addEventListener('resize', onResize);
  onResize();
}

function generateTerrain() {
  const segments = 256;
  const size = 2000; // large area
  const half = size / 2;

  const geo = new THREE.PlaneGeometry(size, size, segments, segments);
  geo.rotateX(-Math.PI / 2);

  // Procedural heightmap noise (simple multi-octave value noise)
  const posAttr = geo.attributes.position;
  const count = posAttr.count;
  const colors = [];

  for (let i = 0; i < count; i++) {
    const x = posAttr.getX(i);
    const z = posAttr.getZ(i);
    let h = 0;
    // Multi-octave noise approximation
    h += Math.sin(x * 0.005 + Math.sin(z * 0.003) * 20) * 40;
    h += Math.sin(x * 0.015 + Math.cos(z * 0.01) * 10) * 15;
    h += Math.sin(x * 0.04 + z * 0.03) * 5;
    h += Math.abs(Math.sin(x * 0.002) * Math.sin(z * 0.002)) * 80; // broad mountains

    // Coastline / flat area near center for runway
    const distFromCenter = Math.hypot(x, z);
    if (distFromCenter < 120) h *= 0.15; // flat airport zone

    h = Math.max(-20, Math.min(250, h));
    posAttr.setY(i, h);

    // Color based on height
    let c = new THREE.Color();
    if (h < 5) {
      c.setHex(0x556644); // grass low
    } else if (h < 80) {
      c.setHex(0x77aa55);
    } else if (h < 150) {
      c.setHex(0x888877); // rock
    } else {
      c.setHex(0xaaaacc); // snow peaks
    }
    colors.push(c.r, c.g, c.b);
  }

  geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
  geo.computeVertexNormals();

  const mat = new THREE.MeshStandardMaterial({
    vertexColors: true,
    roughness: 0.9,
    metalness: 0.05,
    flatShading: false
  });

  terrainMesh = new THREE.Mesh(geo, mat);
  terrainMesh.receiveShadow = true;
  terrainMesh.castShadow = true;
  scene.add(terrainMesh);
  terrainGeometry = geo; // keep reference for height queries
}

function buildAircraft() {
  // Remove previous
  if (aircraftMesh) scene.remove(aircraftMesh);
  if (propMesh) scene.remove(propMesh);

  const p = aircraftProfile;

  // Fuselage
  const fuselage = new THREE.Mesh(
    new THREE.CylinderGeometry(0.8, 1.0, 7, 12),
    new THREE.MeshStandardMaterial({ color: p.color, roughness: 0.3, metalness: 0.8 })
  );
  fuselage.rotation.z = Math.PI / 2;
  fuselage.castShadow = true;

  // Wings
  const wingGeo = new THREE.BoxGeometry(11, 0.3, 3);
  const wingMat = new THREE.MeshStandardMaterial({ color: p.color, roughness: 0.4, metalness: 0.7 });
  const wings = new THREE.Mesh(wingGeo, wingMat);
  wings.castShadow = true;

  // Tail
  const tailGeo = new THREE.BoxGeometry(2, 2, 0.2);
  const tail = new THREE.Mesh(tailGeo, wingMat);
  tail.position.set(-3, 0, 0);
  tail.castShadow = true;

  // Propeller (visible for prop planes; hidden for fighter visually smaller)
  const propGeo = new THREE.BoxGeometry(3, 0.05, 0.3);
  propMat = new THREE.MeshStandardMaterial({ color: 0x222222, roughness: 0.8 });
  propMesh = new THREE.Mesh(propGeo, propMat);
  propMesh.position.set(3.5, 0, 0);
  propMesh.rotation.z = Math.PI / 8; // tilt slightly

  // Group
  aircraftMesh = new THREE.Group();
  aircraftMesh.add(fuselage);
  aircraftMesh.add(wings);
  aircraftMesh.add(tail);
  aircraftMesh.add(propMesh);
  scene.add(aircraftMesh);

  // Set position
  aircraftMesh.position.copy(pos);
  aircraftMesh.quaternion.copy(quat);
  aircraftMesh.rotation.y = Math.PI; // face forward along +z (we will adjust orientation)
}

function initAudio() {
  try {
    audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    engineOsc = audioCtx.createOscillator();
    engineOsc.type = 'sawtooth';
    engineGain = audioCtx.createGain();
    engineGain.gain.value = 0.05;

    // Low-pass filter for engine
    const filter = audioCtx.createBiquadFilter();
    filter.type = 'lowpass';
    filter.frequency.value = 1200;

    engineOsc.connect(engineGain);
    engineGain.connect(filter);
    filter.connect(audioCtx.destination);
    engineOsc.start();

    // Wind noise (noise source)
    const bufferSize = 2 * audioCtx.sampleRate;
    const noiseBuffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
    const data = noiseBuffer.getChannelData(0);
    for (let i = 0; i < bufferSize; i++) data[i] = Math.random() * 2 - 1;

    const windSource = audioCtx.createBufferSource();
    windSource.buffer = noiseBuffer;
    windSource.loop = true;
    windGain = audioCtx.createGain();
    windGain.gain.value = 0;
    const windFilter = audioCtx.createBiquadFilter();
    windFilter.type = 'highpass';
    windFilter.frequency.value = 400;
    windSource.connect(windFilter);
    windFilter.connect(windGain);
    windGain.connect(audioCtx.destination);
    windSource.start();
    windNoise = windSource;
  } catch (e) {
    console.warn("Audio init failed:", e);
  }
}

function updateAudio(delta) {
  if (!audioCtx) return;
  // Engine frequency mapped to throttle + RPM simulation
  const baseFreq = 60;
  const rpmFactor = throttle * 200 + (vel.length() / 20) * 50;
  const target = baseFreq + rpmFactor * (aircraftProfile.mass > 2000 ? 0.5 : 1.2);
  engineFreqTarget += (target - engineFreqTarget) * 0.1;
  engineOsc.frequency.setTargetAtTime(engineFreqTarget, audioCtx.currentTime, 0.05);

  const engineVol = Math.min(1, throttle + (vel.length() / 120) * 0.5);
  engineGain.gain.setTargetAtTime(0.02 + engineVol * 0.08, audioCtx.currentTime, 0.05);

  // Wind volume increases with speed and altitude
  const altFactor = 1 + (pos.y / 500) * 0.5;
  const windVol = Math.min(1, (vel.length() / 80) * altFactor);
  windGain.gain.setTargetAtTime(windVol * 0.05, audioCtx.currentTime, 0.05);
}

// --- Terrain Height Query ---
function getTerrainHeight(x, z) {
  if (!terrainGeometry) return 0;
  // Approximate by reading nearest vertex attribute data
  // For simplicity, compute noise at point
  let h = 0;
  h += Math.sin(x * 0.005 + Math.sin(z * 0.003) * 20) * 40;
  h += Math.sin(x * 0.015 + Math.cos(z * 0.01) * 10) * 15;
  h += Math.sin(x * 0.04 + z * 0.03) * 5;
  h += Math.abs(Math.sin(x * 0.002) * Math.sin(z * 0.002)) * 80;
  const distFromCenter = Math.hypot(x, z);
  if (distFromCenter < 120) h *= 0.15;
  h = Math.max(-20, Math.min(250, h));
  return h + 2; // small offset for ground clearance
}

// --- Input ---
function onKey(e) {
  const down = e.type === 'keydown';
  switch (e.key.toLowerCase()) {
    case 'arrowup': case 'w': pitchInput = down ? -1 : 0; break; // pitch down to nose down? Actually arrow up = pitch up? Let's define clearly.
    // Let's say Arrow Up = pitch up (nose up), Arrow Down = pitch down (nose down)
    case 'arrowdown': case 's': pitchInput = down ? 1 : 0; break;
    case 'arrowleft': case 'a': rollInput = down ? -1 : 0; break;
    case 'arrowright': case 'd': rollInput = down ? 1 : 0; break;
    case 'q': yawInput = down ? -1 : 0; break;
    case 'e': yawInput = down ? 1 : 0; break;
    case ' ': throttle = Math.min(1, throttle + 0.02); e.preventDefault(); break;
    case 'shift': throttle = Math.max(0, throttle - 0.04); e.preventDefault(); break;
  }
  // Override arrow mapping: ArrowUp/Down for pitch, ArrowLeft/Right for roll
  if (e.key === 'ArrowUp') pitchInput = down ? -1 : 0;
  if (e.key === 'ArrowDown') pitchInput = down ? 1 : 0;
  if (e.key === 'ArrowLeft') rollInput = down ? -1 : 0;
  if (e.key === 'ArrowRight') rollInput = down ? 1 : 0;
}

// --- Physics ---
function physicsStep(delta) {
  const p = aircraftProfile;

  // Air density decreases with altitude
  const airDensity = AIR_DENSITY_SEA * Math.exp(-pos.y / 7000);

  // Current velocity in local space
  // Create local rotation matrix from quaternion
  const rotMat = new THREE.Matrix4();
  rotMat.makeRotationFromQuaternion(quat);
  const forward = new THREE.Vector3(1, 0, 0);
  const up = new THREE.Vector3(0, 1, 0);
  const right = new THREE.Vector3(0, 0, 1);
  forward.applyQuaternion(quat);
  up.applyQuaternion(quat);
  right.applyQuaternion(quat);

  // Velocity magnitude and direction
  const speed = vel.length();

  // Angle of attack approximation (pitch rate vs velocity vector in local frame)
  // Simplified: use velocity component relative to forward
  const localVel = vel.clone().applyQuaternion(quat.clone().invert());
  // Angle of attack: how much velocity points upward vs forward
  const aoa = Math.atan2(localVel.y, localVel.x); // approximate

  // Lift generation: L = 0.5 * rho * v^2 * Cl * A
  const liftMag = 0.5 * airDensity * Math.max(0, speed * speed) * p.liftCoef * WING_AREA;
  const lift = up.clone().multiplyScalar(liftMag);

  // Drag: D = 0.5 * rho * v^2 * Cd * A + induced drag factor
  const dragMag = 0.5 * airDensity * Math.max(0.5, speed * speed) * p.dragCoef * WING_AREA;
  const dragDir = vel.clone().normalize().multiplyScalar(-dragMag);
  const drag = dragDir;

  // Weight
  const weight = new THREE.Vector3(0, -p.mass * G, 0);

  // Thrust
  const thrustForce = Math.max(0, throttle) * p.maxThrustN;
  const thrust = forward.clone().multiplyScalar(thrustForce);

  // Net force
  const netForce = new THREE.Vector3();
  netForce.add(lift);
  netForce.add(drag);
  netForce.add(weight);
  netForce.add(thrust);

  // Inertia: acceleration
  const accel = netForce.clone().divideScalar(p.mass);
  vel.add(accel.multiplyScalar(delta));

  // Angular dynamics
  // Pitch torque from elevator (pitchInput)
  const pitchTorque = pitchInput * p.pitchRate * delta;
  // Roll torque from ailerons (rollInput)
  const rollTorque = rollInput * p.rollRate * delta;
  // Yaw torque from rudder (yawInput)
  const yawTorque = yawInput * p.yawRate * delta;

  // Inertia damping (angular drag)
  angularVel.multiplyScalar(0.92);
  angularVel.x += pitchTorque * delta * 3;
  angularVel.z += rollTorque * delta * 3;
  angularVel.y += yawTorque * delta * 3;

  // Update orientation quaternion from angular velocity
  const angleAxis = angularVel.clone().multiplyScalar(delta);
  if (angleAxis.length() > 0.0001) {
    const ax = angleAxis.normalize();
    const qDelta = new THREE.Quaternion().setFromAxisAngle(ax, angleAxis.length());
    quat.multiply(qDelta); // apply rotation in local body frame
    quat.normalize();
  }

  // Update position
  pos.add(vel.clone().multiplyScalar(delta));

  // Ground collision / landing
  const terrainH = getTerrainHeight(pos.x, pos.z);
  if (pos.y < terrainH + 2) {
    pos.y = terrainH + 2;
    vel.y = Math.max(0, vel.y * -0.2); // bounce with damping
    // Ground friction
    const groundSpeedFactor = Math.abs(vel.x) + Math.abs(vel.z);
    vel.x *= 0.985;
    vel.z *= 0.985;
  }

  // Stall behavior: if speed < stallSpeed, lift reduces sharply
  if (speed < p.stallSpeed) {
    // Apply downward pitch tendency (stall sink)
    angularVel.x += 0.15 * delta;
    vel.y -= 0.05 * delta;
  }

  // Update aircraft mesh
  aircraftMesh.position.copy(pos);
  aircraftMesh.quaternion.copy(quat);

  // Prop rotation (visual only)
  propMesh.rotation.z += delta * 20 * throttle;
}

function setMode(newMode) {
  mode = newMode;
  document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
  document.querySelector('.mode-btn[onclick*="'+newMode+'"]').classList.add('active');

  // Mode setup
  if (mode === 'takeoff') {
    pos.set(0, 3, -600);
    vel.set(0, 0, 80);
    quat.setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI / 2); // face +Z runway
    throttle = 0.7;
    pitchInput = 0; rollInput = 0; yawInput = 0;
  } else {
    // Dogfight mode: start in air over mountains
    pos.set(-200, 300, -300);
    vel.set(40, 0, 140);
    quat.setFromAxisAngle(new THREE.Vector3(0,1,0), Math.PI + 0.2);
    throttle = 0.85;
  }

  document.getElementById('mode-title').textContent = mode === 'takeoff' ? 'TAKEOFF / LANDING' : 'DOGFIGHT';
  document.getElementById('mode-desc').textContent = mode === 'takeoff'
    ? 'Manage airspeed, lift-off, descent. Runway at center.'
    : 'High-G maneuvering over terrain. Maintain speed, avoid stalls.';
}

function selectAircraft(idx) {
  selectedAircraftIdx = idx;
  aircraftProfile = aircraftProfiles[idx];
  document.querySelectorAll('.fleet-card').forEach(c => c.classList.remove('selected'));
  document.querySelector('.fleet-card[data-idx="'+idx+'"]').classList.add('selected');
}

function startFlight() {
  document.getElementById('overlay').style.display = 'none';
  document.getElementById('hud').style.display = 'block';
  initThree();
  // Start loop
  animate();
  // Resume audio context on user interaction
  if (audioCtx && audioCtx.state === 'suspended') audioCtx.resume();
}

function updateHUD() {
  document.getElementById('craft-name').textContent = aircraftProfile.name;
  document.getElementById('craft-sub').textContent = (selectedAircraftIdx === 0 ? 'Prop / Training' : selectedAircraftIdx === 1 ? 'Fighter / Dogfight' : 'Transport / Heavy');
  document.getElementById('engine-rpm').textContent = Math.round(2400 + throttle * 9000) + " RPM";
  document.getElementById('engine-throttle').textContent = "THROTTLE " + Math.round(throttle * 100) + "%";

  const speedKts = (vel.length() * 1.94384).toFixed(0);
  document.getElementById('airspeed').textContent = speedKts + " KT";

  document.getElementById('altitude').textContent = Math.round(pos.y) + " FT";

  // Artificial horizon
  const pitchDeg = Math.asin(Math.max(-1, Math.min(1, vel.y / Math.max(1, vel.length()))) ) * (180 / Math.PI);
  const rollDeg = 0; // We can approximate roll from quaternion
  // Simple roll approximation from quaternion rotation around local forward
  const euler = new THREE.Euler().setFromQuaternion(quat, 'YXZ');
  const rollDegApprox = euler.z * (180 / Math.PI);
  const pitchDegApprox = euler.x * (180 / Math.PI);

  document.getElementById('pitch-marker').style.transform = `rotate(${pitchDegApprox}deg) translateX(-50%)`;
  document.getElementById('roll-marker').style.transform = `rotate(${-rollDegApprox}deg) translateX(-50%)`;
}

function animate() {
  requestAnimationFrame(animate);
  const delta = Math.min(0.033, clock.getDelta());

  if (aircraftMesh) {
    physicsStep(delta);
    updateAudio(delta);
    updateHUD();

    // Camera chase: follow aircraft with smooth interpolation
    // Compute camera position behind aircraft
    const camOffset = new THREE.Vector3(0, 6, -25);
    camOffset.applyQuaternion(quat);
    const camTarget = pos.clone().add(camOffset);
    camera.position.lerp(camTarget, 0.1);
    camera.lookAt(pos);
  }

  renderer.render(scene, camera);
}

function onResize() {
  if (camera && renderer) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  }
}

// Initialize selection
selectAircraft(1);
</script>
</body>
</html>
<!-- agent-meta {"model":"thinkingmachines/inkling","provider":"openrouter","persona":"full","sessionId":"d2be2520-63b6-42cf-ae03-b3ded862c86d","tokensIn":139304,"tokensOut":13465,"tokensTotal":152769,"turns":9,"toolCalls":8,"failedToolCalls":0,"timestamp":"2026-07-18T21:46:43.765Z"} -->