🎮ArcadeLab

Arena Shooter HD

by UltraNinja96
1029 lines58.7 KB🛠️ Three.js (3D graphics)
▶ Play
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Arena Shooter HD</title>
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; background: #000; font-family: "Segoe UI", Arial, sans-serif; user-select: none; }
  canvas { display: block; }
  #hud { position: fixed; inset: 0; pointer-events: none; color: #fff; text-shadow: 0 1px 4px #000; z-index: 3; }
  #crosshair { position: absolute; left: 50%; top: 50%; width: 26px; height: 26px; margin: -13px 0 0 -13px; transition: opacity .15s; }
  #crosshair i { position: absolute; background: rgba(255,255,255,.9); box-shadow: 0 0 3px #000; }
  #crosshair i:nth-child(1) { left: 12px; top: 0; width: 2px; height: 8px; }
  #crosshair i:nth-child(2) { left: 12px; bottom: 0; width: 2px; height: 8px; }
  #crosshair i:nth-child(3) { top: 12px; left: 0; height: 2px; width: 8px; }
  #crosshair i:nth-child(4) { top: 12px; right: 0; height: 2px; width: 8px; }
  #hitmarker { position: absolute; left: 50%; top: 50%; width: 30px; height: 30px; margin: -15px 0 0 -15px; opacity: 0; transition: opacity .15s; }
  #hitmarker::before, #hitmarker::after { content: ""; position: absolute; left: 14px; top: -4px; width: 3px; height: 38px; background: #fff; }
  #hitmarker::before { transform: rotate(45deg); } #hitmarker::after { transform: rotate(-45deg); }
  #hitmarker.head::before, #hitmarker.head::after { background: #ff3b3b; }
  #stats { position: absolute; left: 28px; bottom: 28px; font-size: 14px; letter-spacing: 2px; opacity: .95; }
  #healthbar { width: 260px; height: 14px; border: 1px solid rgba(255,255,255,.7); background: rgba(0,0,0,.45); margin-top: 6px; padding: 2px; }
  #healthfill { height: 100%; width: 100%; background: linear-gradient(90deg, #c62828, #e8b923 50%, #43a047); transition: width .2s; }
  #ammo { position: absolute; right: 28px; bottom: 24px; font-size: 52px; font-weight: 700; text-align: right; letter-spacing: 1px; }
  #ammo .res { font-size: 26px; opacity: .7; }
  #ammo small { font-size: 14px; font-weight: 400; display: block; letter-spacing: 3px; opacity: .85; }
  #top { position: absolute; top: 18px; left: 0; right: 0; text-align: center; font-size: 17px; letter-spacing: 3px; }
  #msg { position: absolute; top: 24%; left: 0; right: 0; text-align: center; font-size: 34px; font-weight: 700; letter-spacing: 4px; opacity: 0; transition: opacity .4s; }
  #damage { position: fixed; inset: 0; background: radial-gradient(transparent 35%, rgba(200,0,0,.65)); opacity: 0; transition: opacity .3s; pointer-events: none; z-index: 2; }
  #lowhp { position: fixed; inset: 0; background: radial-gradient(transparent 45%, rgba(120,0,0,.7)); opacity: 0; pointer-events: none; z-index: 2; transition: opacity .5s; }
  #vignette { position: fixed; inset: 0; pointer-events: none; z-index: 1; background: radial-gradient(ellipse at center, rgba(0,0,0,0) 65%, rgba(0,0,0,.3) 100%); }
  #grain { position: fixed; left: -50%; top: -50%; width: 200%; height: 200%; pointer-events: none; z-index: 1; opacity: .08; animation: g .4s steps(4) infinite;
    background-image: url("data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E"); }
  @keyframes g { 0% { transform: translate(0,0) } 25% { transform: translate(-3%,2%) } 50% { transform: translate(2%,-3%) } 75% { transform: translate(-2%,-1%) } 100% { transform: translate(1%,3%) } }
  #overlay { position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(5,8,14,.84); color: #fff; text-align: center; cursor: pointer; z-index: 10; }
  #overlay h1 { font-size: 56px; margin: 0 0 10px; letter-spacing: 6px; }
  #overlay p { font-size: 18px; margin: 6px 0; opacity: .9; }
  #overlay .btn { margin-top: 24px; padding: 14px 40px; font-size: 22px; background: #e8472b; border-radius: 4px; font-weight: 700; letter-spacing: 2px; }
  kbd { background: #333; padding: 2px 8px; border-radius: 4px; border: 1px solid #666; }
</style>
</head>
<body>
<div id="vignette"></div>
<div id="grain"></div>
<div id="damage"></div>
<div id="lowhp"></div>
<div id="hud">
  <div id="top">WAVE <span id="wave">1</span> &nbsp;|&nbsp; SCORE <span id="score">0</span> &nbsp;|&nbsp; HOSTILES <span id="enemies">0</span></div>
  <div id="msg"></div>
  <div id="crosshair"><i></i><i></i><i></i><i></i></div>
  <div id="hitmarker"></div>
  <div id="stats">HEALTH<div id="healthbar"><div id="healthfill"></div></div></div>
  <div id="ammo"><span id="mag">30</span> <span class="res">/ <span id="reserve">120</span></span><small id="reloadtxt"></small></div>
</div>

<div id="overlay">
  <h1 id="title">ARENA SHOOTER HD</h1>
  <p id="sub">Loading...</p>
  <p><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> move &nbsp; <kbd>Mouse</kbd> look &nbsp; <kbd>Left click</kbd> shoot &nbsp; <kbd>Right click</kbd> aim</p>
  <p><kbd>Shift</kbd> sprint &nbsp; <kbd>Space</kbd> jump &nbsp; <kbd>R</kbd> reload &nbsp; <kbd>Esc</kbd> pause</p>
  <div class="btn" id="btn">CLICK TO PLAY</div>
</div>

<script>
const LIBS = {
  three: ["https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js", "https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js", "https://unpkg.com/three@0.128.0/build/three.min.js"],
  gltf: ["https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/GLTFLoader.js", "https://unpkg.com/three@0.128.0/examples/js/loaders/GLTFLoader.js"],
  skel: ["https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/utils/SkeletonUtils.js", "https://unpkg.com/three@0.128.0/examples/js/utils/SkeletonUtils.js"],
  model: ["https://cdn.jsdelivr.net/gh/mrdoob/three.js@r128/examples/models/gltf/Soldier.glb", "https://raw.githubusercontent.com/mrdoob/three.js/r128/examples/models/gltf/Soldier.glb", "https://threejs.org/examples/models/gltf/Soldier.glb"]
};
// If the soldiers walk backwards, change this to Math.PI
const MODEL_FACING = 0;

function loadScript(urls, check) {
  return new Promise(resolve => {
    let i = 0;
    (function next() {
      if (i >= urls.length) return resolve(false);
      const s = document.createElement("script");
      s.src = urls[i++];
      s.onload = () => { if (check()) resolve(true); else next(); };
      s.onerror = () => { s.remove(); next(); };
      document.head.appendChild(s);
    })();
  });
}
function loadSoldier(urls) {
  return new Promise(resolve => {
    let i = 0;
    const loader = new THREE.GLTFLoader();
    (function next() {
      if (i >= urls.length) return resolve(null);
      const url = urls[i++]; let settled = false;
      const t = setTimeout(() => { if (!settled) { settled = true; next(); } }, 15000);
      loader.load(url, g => { if (settled) return; settled = true; clearTimeout(t); resolve(g); },
        undefined, () => { if (settled) return; settled = true; clearTimeout(t); next(); });
    })();
  });
}

function startGame(soldierGLTF) {
  const $ = id => document.getElementById(id);
  const rnd = (a, b) => a + Math.random() * (b - a);
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
  const lerp = (a, b, t) => a + (b - a) * t;

  // ====================== RENDERER / SCENE ======================
  const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
  renderer.setPixelRatio(Math.min(devicePixelRatio, 1.75));
  renderer.setSize(innerWidth, innerHeight);
  renderer.outputEncoding = THREE.sRGBEncoding;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.55;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  document.body.appendChild(renderer.domElement);
  const maxAniso = renderer.capabilities.getMaxAnisotropy();

  const scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(0xb8a49c, 0.006);

  const camera = new THREE.PerspectiveCamera(74, innerWidth / innerHeight, 0.02, 500);
  camera.rotation.order = "YXZ";
  scene.add(camera);

  // ---------- Sky + image based lighting ----------
  const SUN_DIR = new THREE.Vector3(0.7, 0.32, 0.55).normalize();
  const skyMat = new THREE.ShaderMaterial({
    side: THREE.BackSide, depthWrite: false, fog: false,
    uniforms: { sunDir: { value: SUN_DIR.clone() } },
    vertexShader: "varying vec3 vDir; void main(){ vDir = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",
    fragmentShader: [
      "varying vec3 vDir; uniform vec3 sunDir;",
      "void main(){",
      "  vec3 d = normalize(vDir);",
      "  float h = clamp(d.y, 0.0, 1.0);",
      "  vec3 zenith = vec3(0.07, 0.13, 0.30);",
      "  vec3 mid = vec3(0.45, 0.38, 0.52);",
      "  vec3 horizon = vec3(1.0, 0.62, 0.38);",
      "  vec3 col = mix(horizon, mid, smoothstep(0.0, 0.18, h));",
      "  col = mix(col, zenith, smoothstep(0.12, 0.7, h));",
      "  float s = max(dot(d, normalize(sunDir)), 0.0);",
      "  col += vec3(1.0, 0.55, 0.25) * pow(s, 6.0) * 0.6;",
      "  col += vec3(1.0, 0.8, 0.55) * pow(s, 64.0) * 1.2;",
      "  col += vec3(1.0, 0.95, 0.8) * smoothstep(0.9995, 0.9999, s) * 8.0;",
      "  if (d.y < 0.0) { col = mix(horizon * 0.5, vec3(0.15, 0.12, 0.12), clamp(-d.y * 4.0, 0.0, 1.0)); }",
      "  gl_FragColor = vec4(col, 1.0);",
      "}"
    ].join("\n")
  });
  const sky = new THREE.Mesh(new THREE.SphereGeometry(300, 32, 16), skyMat);
  scene.add(sky);
  try {
    const pm = new THREE.PMREMGenerator(renderer);
    const envScene = new THREE.Scene();
    envScene.add(new THREE.Mesh(new THREE.SphereGeometry(50, 32, 16), skyMat));
    scene.environment = pm.fromScene(envScene, 0.04).texture;
    pm.dispose();
  } catch (e) {}

  // ---------- Lights ----------
  const sun = new THREE.DirectionalLight(0xffe0b8, 3.4);
  sun.position.copy(SUN_DIR).multiplyScalar(90);
  sun.castShadow = true;
  sun.shadow.mapSize.set(2048, 2048);
  Object.assign(sun.shadow.camera, { left: -55, right: 55, top: 55, bottom: -55, near: 1, far: 220 });
  sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.04;
  scene.add(sun); scene.add(sun.target);
  scene.add(new THREE.HemisphereLight(0xb5c8f0, 0x6a5a4e, 1.6));
  scene.add(new THREE.AmbientLight(0xffffff, 0.45));

  const ARENA = 40;

  // ====================== PROCEDURAL TEXTURES ======================
  function cv(w, h) { const c = document.createElement("canvas"); c.width = w; c.height = h; return [c, c.getContext("2d")]; }
  function noiseify(g, w, h, amt) {
    const im = g.getImageData(0, 0, w, h), d = im.data;
    for (let i = 0; i < d.length; i += 4) { const n = (Math.random() - 0.5) * amt; d[i] += n; d[i + 1] += n; d[i + 2] += n; }
    g.putImageData(im, 0, 0);
  }
  function tex(c, srgb = true) {
    const t = new THREE.CanvasTexture(c);
    t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = maxAniso;
    if (srgb) t.encoding = THREE.sRGBEncoding;
    return t;
  }
  function concreteCanvas(S, base) {
    const [c, g] = cv(S, S);
    g.fillStyle = "rgb(" + base.join(",") + ")"; g.fillRect(0, 0, S, S);
    for (let i = 0; i < 45; i++) {
      const x = rnd(0, S), y = rnd(0, S), r = rnd(30, 120), gr = g.createRadialGradient(x, y, 0, x, y, r);
      gr.addColorStop(0, Math.random() < 0.5 ? "rgba(0,0,0,0.10)" : "rgba(255,255,255,0.07)"); gr.addColorStop(1, "rgba(0,0,0,0)");
      g.fillStyle = gr; g.fillRect(x - r, y - r, r * 2, r * 2);
    }
    noiseify(g, S, S, 40);
    g.strokeStyle = "rgba(20,20,20,0.5)"; g.lineWidth = 1;
    for (let k = 0; k < 5; k++) {
      let x = rnd(0, S), y = rnd(0, S); g.beginPath(); g.moveTo(x, y);
      for (let s = 0; s < 30; s++) { x += rnd(-12, 12); y += rnd(-12, 12); g.lineTo(x, y); }
      g.stroke();
    }
    g.strokeStyle = "rgba(0,0,0,0.45)"; g.lineWidth = 3; g.strokeRect(0, 0, S, S);
    return c;
  }
  function stainCanvas() {
    const [c, g] = cv(1024, 1024);
    for (let i = 0; i < 70; i++) {
      const x = rnd(0, 1024), y = rnd(0, 1024), r = rnd(40, 200), gr = g.createRadialGradient(x, y, 0, x, y, r), a = rnd(0.03, 0.13);
      gr.addColorStop(0, "rgba(20,16,12," + a + ")"); gr.addColorStop(1, "rgba(20,16,12,0)");
      g.fillStyle = gr; g.fillRect(x - r, y - r, r * 2, r * 2);
    }
    g.strokeStyle = "rgba(220,190,60,0.5)"; g.lineWidth = 10; g.setLineDash([60, 40]);
    g.beginPath(); g.moveTo(0, 512); g.lineTo(1024, 512); g.stroke(); g.setLineDash([]);
    return c;
  }
  function crateCanvas() {
    const S = 256, [c, g] = cv(S, S), boards = 5, bh = S / boards;
    for (let i = 0; i < boards; i++) {
      const s = rnd(-14, 14);
      g.fillStyle = "rgb(" + (118 + s) + "," + (84 + s) + "," + (50 + s) + ")"; g.fillRect(0, i * bh, S, bh);
      for (let j = 0; j < 26; j++) {
        const y = i * bh + rnd(0, bh);
        g.strokeStyle = "rgba(45,28,12," + rnd(0.06, 0.22) + ")"; g.lineWidth = rnd(0.5, 1.6);
        g.beginPath(); g.moveTo(0, y); g.bezierCurveTo(S * 0.3, y + rnd(-4, 4), S * 0.7, y + rnd(-4, 4), S, y + rnd(-3, 3)); g.stroke();
      }
      g.fillStyle = "rgba(20,12,5,0.7)"; g.fillRect(0, i * bh + bh - 2, S, 2);
    }
    const f = S * 0.1;
    g.fillStyle = "rgb(92,64,36)";
    g.fillRect(0, 0, S, f); g.fillRect(0, S - f, S, f); g.fillRect(0, 0, f, S); g.fillRect(S - f, 0, f, S);
    g.save(); g.translate(S / 2, S / 2); g.rotate(Math.PI / 4);
    const L = Math.hypot(S - 2 * f, S - 2 * f); g.fillRect(-L / 2, -f / 2, L, f); g.restore();
    g.strokeStyle = "rgba(25,15,6,0.8)"; g.lineWidth = 2; g.strokeRect(f, f, S - 2 * f, S - 2 * f); g.strokeRect(1, 1, S - 2, S - 2);
    g.fillStyle = "rgba(30,30,32,0.9)";
    [[f / 2, f / 2], [S - f / 2, f / 2], [f / 2, S - f / 2], [S - f / 2, S - f / 2]].forEach(p => { g.beginPath(); g.arc(p[0], p[1], 3, 0, 7); g.fill(); });
    noiseify(g, S, S, 26);
    return c;
  }
  function containerCanvas(hex) {
    const S = 512, [c, g] = cv(S, S), col = new THREE.Color(hex);
    g.fillStyle = "rgb(" + ((col.r * 255) | 0) + "," + ((col.g * 255) | 0) + "," + ((col.b * 255) | 0) + ")"; g.fillRect(0, 0, S, S);
    const rib = S / 32;
    for (let i = 0; i < 32; i++) {
      const gr = g.createLinearGradient(i * rib, 0, (i + 1) * rib, 0);
      gr.addColorStop(0, "rgba(255,255,255,0.18)"); gr.addColorStop(0.5, "rgba(0,0,0,0)"); gr.addColorStop(1, "rgba(0,0,0,0.35)");
      g.fillStyle = gr; g.fillRect(i * rib, 0, rib, S);
    }
    for (let k = 0; k < 26; k++) {
      const x = rnd(0, S), w = rnd(2, 14), h = rnd(60, 300), y = rnd(0, S * 0.6), gr = g.createLinearGradient(0, y, 0, y + h);
      gr.addColorStop(0, "rgba(110,55,20,0.35)"); gr.addColorStop(1, "rgba(110,55,20,0)");
      g.fillStyle = gr; g.fillRect(x, y, w, h);
    }
    const dg = g.createLinearGradient(0, S * 0.75, 0, S);
    dg.addColorStop(0, "rgba(30,22,14,0)"); dg.addColorStop(1, "rgba(30,22,14,0.55)");
    g.fillStyle = dg; g.fillRect(0, S * 0.75, S, S * 0.25);
    g.fillStyle = "rgba(0,0,0,0.35)"; g.fillRect(0, 0, S, 22); g.fillRect(0, S - 22, S, 22);
    noiseify(g, S, S, 30);
    return c;
  }
  function barrelCanvas(hex) {
    const W = 256, H = 256, [c, g] = cv(W, H), col = new THREE.Color(hex);
    g.fillStyle = "rgb(" + ((col.r * 255) | 0) + "," + ((col.g * 255) | 0) + "," + ((col.b * 255) | 0) + ")"; g.fillRect(0, 0, W, H);
    const vg = g.createLinearGradient(0, 0, W, 0);
    vg.addColorStop(0, "rgba(0,0,0,0.35)"); vg.addColorStop(0.35, "rgba(255,255,255,0.12)"); vg.addColorStop(1, "rgba(0,0,0,0.35)");
    g.fillStyle = vg; g.fillRect(0, 0, W, H);
    [0.1, 0.5, 0.9].forEach(f => {
      g.fillStyle = "rgba(0,0,0,0.55)"; g.fillRect(0, f * H - 4, W, 4);
      g.fillStyle = "rgba(255,255,255,0.22)"; g.fillRect(0, f * H, W, 3);
    });
    for (let k = 0; k < 20; k++) {
      const x = rnd(0, W), y = rnd(0, H), r = rnd(6, 28), gr = g.createRadialGradient(x, y, 0, x, y, r);
      gr.addColorStop(0, "rgba(100,50,18,0.45)"); gr.addColorStop(1, "rgba(100,50,18,0)");
      g.fillStyle = gr; g.fillRect(x - r, y - r, r * 2, r * 2);
    }
    noiseify(g, W, H, 28);
    return c;
  }
  function buildingCanvas() {
    const W = 128, H = 256, [c, g] = cv(W, H);
    g.fillStyle = "#1b1f2b"; g.fillRect(0, 0, W, H);
    for (let y = 8; y < H - 8; y += 14) for (let x = 8; x < W - 8; x += 12) {
      const lit = Math.random() < 0.28;
      g.fillStyle = lit ? (Math.random() < 0.7 ? "#ffd27a" : "#9fd0ff") : "#0e1118";
      g.fillRect(x, y, 6, 8);
    }
    return c;
  }
  function camoCanvas() {
    const [c, g] = cv(256, 256);
    g.fillStyle = "#4b5538"; g.fillRect(0, 0, 256, 256);
    ["#3a432b", "#6b6a45", "#2e3322", "#5a5f40"].forEach(col => {
      g.fillStyle = col;
      for (let i = 0; i < 18; i++) { g.beginPath(); g.ellipse(rnd(0, 256), rnd(0, 256), rnd(12, 40), rnd(8, 26), rnd(0, 3), 0, 7); g.fill(); }
    });
    noiseify(g, 256, 256, 22);
    return c;
  }
  function softCanvas() {
    const [c, g] = cv(64, 64), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
    gr.addColorStop(0, "rgba(255,255,255,1)"); gr.addColorStop(0.4, "rgba(255,255,255,0.45)"); gr.addColorStop(1, "rgba(255,255,255,0)");
    g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
    return c;
  }
  function flashCanvas() {
    const [c, g] = cv(128, 128), gr = g.createRadialGradient(64, 64, 0, 64, 64, 60);
    gr.addColorStop(0, "rgba(255,255,230,1)"); gr.addColorStop(0.25, "rgba(255,200,110,0.9)"); gr.addColorStop(1, "rgba(255,120,30,0)");
    g.fillStyle = gr; g.fillRect(0, 0, 128, 128);
    g.strokeStyle = "rgba(255,220,150,0.85)"; g.lineWidth = 3;
    for (let k = 0; k < 9; k++) { const a = rnd(0, 6.28), l = rnd(36, 62); g.beginPath(); g.moveTo(64, 64); g.lineTo(64 + Math.cos(a) * l, 64 + Math.sin(a) * l); g.stroke(); }
    return c;
  }
  function holeCanvas() {
    const [c, g] = cv(64, 64), gr = g.createRadialGradient(32, 32, 0, 32, 32, 30);
    gr.addColorStop(0, "rgba(0,0,0,0.95)"); gr.addColorStop(0.3, "rgba(10,8,6,0.85)"); gr.addColorStop(1, "rgba(0,0,0,0)");
    g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
    g.strokeStyle = "rgba(0,0,0,0.5)"; g.lineWidth = 1;
    for (let k = 0; k < 6; k++) { const a = rnd(0, 6.28); g.beginPath(); g.moveTo(32, 32); g.lineTo(32 + Math.cos(a) * rnd(14, 30), 32 + Math.sin(a) * rnd(14, 30)); g.stroke(); }
    return c;
  }

  const softTex = tex(softCanvas()), flashTex = tex(flashCanvas()), holeTex = tex(holeCanvas());
  const concCanvas = concreteCanvas(512, [168, 166, 160]);
  const matCache = {};
  function concreteMat(rx, ry) {
    const k = rx.toFixed(1) + "x" + ry.toFixed(1);
    if (matCache[k]) return matCache[k];
    const m = tex(concCanvas); m.repeat.set(rx, ry);
    const b = tex(concCanvas, false); b.repeat.set(rx, ry);
    return (matCache[k] = new THREE.MeshStandardMaterial({ map: m, bumpMap: b, bumpScale: 1.5, roughness: 0.96, metalness: 0 }));
  }
  const crateC = crateCanvas();
  const crateMat = new THREE.MeshStandardMaterial({ map: tex(crateC), bumpMap: tex(crateC, false), bumpScale: 1.2, roughness: 0.85, metalness: 0 });
  const contCache = {};
  function containerMat(hex) {
    if (contCache[hex]) return contCache[hex];
    const c = containerCanvas(hex);
    return (contCache[hex] = new THREE.MeshStandardMaterial({ map: tex(c), bumpMap: tex(c, false), bumpScale: 2.0, roughness: 0.55, metalness: 0.55 }));
  }
  const metalDark = new THREE.MeshStandardMaterial({ color: 0x2b2d31, roughness: 0.5, metalness: 0.8 });
  const camoTexture = tex(camoCanvas());

  // ====================== WORLD ======================
  const blockers = [];  // meshes bullets can hit
  const solids = [];    // AABB colliders

  const floorTex = concreteMat(ARENA / 4, ARENA / 4);
  const floor = new THREE.Mesh(new THREE.PlaneGeometry(ARENA * 2, ARENA * 2), floorTex);
  floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; floor.userData.surface = "concrete";
  scene.add(floor); blockers.push(floor);
  const stainT = tex(stainCanvas()); stainT.repeat.set(2, 2);
  const stains = new THREE.Mesh(new THREE.PlaneGeometry(ARENA * 2, ARENA * 2),
    new THREE.MeshStandardMaterial({ map: stainT, transparent: true, depthWrite: false, roughness: 1, polygonOffset: true, polygonOffsetFactor: -1 }));
  stains.rotation.x = -Math.PI / 2; stains.position.y = 0.01; stains.receiveShadow = true; scene.add(stains);

  function registerSolid(mesh, x, z, w, d, top, surface) {
    mesh.castShadow = true; mesh.receiveShadow = true; mesh.userData.surface = surface;
    scene.add(mesh); blockers.push(mesh);
    solids.push({ minX: x - w / 2, maxX: x + w / 2, minZ: z - d / 2, maxZ: z + d / 2, h: top });
  }
  function addBox(x, z, w, d, h, mat, y0 = 0, surface = "concrete") {
    const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
    m.position.set(x, y0 + h / 2, z);
    registerSolid(m, x, z, w, d, y0 + h, surface);
    return m;
  }

  // perimeter walls
  const T = 2, WH = 7;
  addBox(0, -ARENA - T / 2, ARENA * 2 + T * 2, T, WH, concreteMat(22, 2));
  addBox(0, ARENA + T / 2, ARENA * 2 + T * 2, T, WH, concreteMat(22, 2));
  addBox(-ARENA - T / 2, 0, T, ARENA * 2, WH, concreteMat(20, 2));
  addBox(ARENA + T / 2, 0, T, ARENA * 2, WH, concreteMat(20, 2));

  // shipping containers
  [[-14, 10, 6.2, 2.5, 0xb8472f], [16, -12, 2.5, 6.2, 0x2f5f8f], [-20, -16, 6.2, 2.5, 0x3f7a4a],
   [8, 24, 6.2, 2.5, 0xc9a227], [28, 14, 2.5, 6.2, 0x8a8d91], [-30, 2, 2.5, 6.2, 0xb8472f], [4, -28, 6.2, 2.5, 0x2f5f8f]]
    .forEach(c => addBox(c[0], c[1], c[2], c[3], 2.6, containerMat(c[4]), 0, "metal"));
  addBox(-14, 10, 6.2, 2.5, 2.6, containerMat(0x2f5f8f), 2.6, "metal");
  // crates
  [[6, 6, 1.4, 0], [7.6, 6.4, 1.2, 0], [6.6, 6.2, 1.1, 1.4], [-6, -8, 1.5, 0], [-6, -9.6, 1.2, 0], [22, -4, 1.4, 0],
   [22, -5.6, 1.4, 0], [22.7, -4.8, 1.2, 1.4], [-26, 18, 1.5, 0], [-10, 26, 1.3, 0], [12, -22, 1.4, 0], [0, 8, 1.3, 0], [-3, -3, 1.0, 0]]
    .forEach(c => addBox(c[0], c[1], c[2], c[2], c[2], crateMat, c[3], "wood"));
  // concrete barriers
  [[0, -14, 6, 1, 1.1], [-18, 18, 1, 5, 1.1], [18, 18, 5, 1, 1.1], [-4, 22, 5, 1, 1.1], [30, -18, 1, 5, 1.1], [-30, -14, 5, 1, 1.1], [12, 12, 1, 4, 1.1]]
    .forEach(c => addBox(c[0], c[1], c[2], c[3], c[4], concreteMat(c[2] / 2 + 0.5, c[4] / 2 + 0.5)));
  // barrels
  const barrelTop = new THREE.MeshStandardMaterial({ color: 0x33353a, roughness: 0.5, metalness: 0.8 });
  [[2, 14, 0xa33a2a], [3, 15, 0x2d5d86], [-8, 16, 0x3b6b3d], [14, 2, 0xa33a2a], [-16, -4, 0x2d5d86], [-12, -24, 0xa33a2a],
   [24, 28, 0x3b6b3d], [30, -6, 0xa33a2a], [-24, -28, 0x2d5d86], [10, -8, 0xc9a227]].forEach(b => {
    const bc = barrelCanvas(b[2]);
    const side = new THREE.MeshStandardMaterial({ map: tex(bc), bumpMap: tex(bc, false), bumpScale: 1.5, roughness: 0.5, metalness: 0.6 });
    const m = new THREE.Mesh(new THREE.CylinderGeometry(0.45, 0.45, 1.1, 24), [side, barrelTop, barrelTop]);
    m.position.set(b[0], 0.55, b[1]);
    registerSolid(m, b[0], b[1], 0.9, 0.9, 1.1, "metal");
  });
  // street lamps
  const lampGlow = new THREE.MeshBasicMaterial({ color: 0xffe2b0 });
  [[-22, -22], [22, -22], [-22, 22], [22, 22]].forEach(p => {
    const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.14, 7, 10), metalDark);
    pole.position.set(p[0], 3.5, p[1]);
    registerSolid(pole, p[0], p[1], 0.4, 0.4, 7, "metal");
    const head = new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.15, 0.4), metalDark); head.position.set(p[0], 7.1, p[1]); scene.add(head);
    const panel = new THREE.Mesh(new THREE.BoxGeometry(0.8, 0.05, 0.35), lampGlow); panel.position.set(p[0], 7.0, p[1]); scene.add(panel);
    const pl = new THREE.PointLight(0xffd9a0, 2.2, 32, 2); pl.position.set(p[0], 6.5, p[1]); scene.add(pl);
  });
  // distant city skyline
  for (let i = 0; i < 28; i++) {
    const a = (i / 28) * Math.PI * 2 + rnd(-0.08, 0.08), r = rnd(78, 105), bh = [24, 36, 50, 62][i % 4], bw = rnd(12, 20);
    const bt = tex(buildingCanvas()); bt.repeat.set(bw / 12, bh / 24);
    const b = new THREE.Mesh(new THREE.BoxGeometry(bw, bh, bw), new THREE.MeshBasicMaterial({ map: bt }));
    b.position.set(Math.cos(a) * r, bh / 2 - 2, Math.sin(a) * r); b.rotation.y = rnd(0, 3);
    scene.add(b);
  }
  // floating dust
  const dustN = 260, dpos = new Float32Array(dustN * 3);
  for (let i = 0; i < dustN; i++) { dpos[i * 3] = rnd(-ARENA, ARENA); dpos[i * 3 + 1] = rnd(0.3, 8); dpos[i * 3 + 2] = rnd(-ARENA, ARENA); }
  const dg = new THREE.BufferGeometry(); dg.setAttribute("position", new THREE.BufferAttribute(dpos, 3));
  const dust = new THREE.Points(dg, new THREE.PointsMaterial({ color: 0xffe0b0, size: 0.07, transparent: true, opacity: 0.5, depthWrite: false, blending: THREE.AdditiveBlending }));
  scene.add(dust);

  function hitsSolid(x, z, r, feetY = 0) {
    if (Math.abs(x) > ARENA - r || Math.abs(z) > ARENA - r) return true;
    for (const s of solids) {
      if (feetY >= s.h) continue;
      if (x > s.minX - r && x < s.maxX + r && z > s.minZ - r && z < s.maxZ + r) return true;
    }
    return false;
  }
  function pointInSolid(x, y, z) {
    if (Math.abs(x) > ARENA || Math.abs(z) > ARENA || y < 0) return true;
    for (const s of solids) if (y < s.h && x > s.minX && x < s.maxX && z > s.minZ && z < s.maxZ) return true;
    return false;
  }
  function hasLOS(ax, az, bx, bz) {
    const dx = bx - ax, dz = bz - az, d = Math.hypot(dx, dz), n = Math.ceil(d / 0.8);
    for (let i = 1; i < n; i++) { const t = i / n; if (pointInSolid(ax + dx * t, 1.2, az + dz * t)) return false; }
    return true;
  }

  // ====================== PLAYER WEAPON ======================
  const gun = new THREE.Group();
  camera.add(gun);
  const mMetal = new THREE.MeshStandardMaterial({ color: 0x2b2e33, metalness: 0.95, roughness: 0.32 });
  const mDark = new THREE.MeshStandardMaterial({ color: 0x17181a, metalness: 0.4, roughness: 0.6 });
  const mPoly = new THREE.MeshStandardMaterial({ color: 0x232427, metalness: 0.1, roughness: 0.75 });
  const mGlove = new THREE.MeshStandardMaterial({ color: 0x2a2a28, roughness: 0.9 });
  const mSleeve = new THREE.MeshStandardMaterial({ color: 0x4a5238, roughness: 0.95 });
  const BX = (w, h, d) => new THREE.BoxGeometry(w, h, d);
  const CY = (r1, r2, l, s = 14) => new THREE.CylinderGeometry(r1, r2, l, s);
  function gpart(geo, mat, x, y, z, rx = 0, ry = 0, rz = 0) {
    const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.rotation.set(rx, ry, rz); gun.add(m); return m;
  }
  function limb(from, to, r, mat) {
    const a = new THREE.Vector3(...from), b = new THREE.Vector3(...to), dir = b.clone().sub(a), len = dir.length();
    const m = new THREE.Mesh(CY(r, r * 1.15, len, 12), mat);
    m.position.copy(a.clone().add(b).multiplyScalar(0.5));
    m.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir.normalize());
    gun.add(m);
  }
  gpart(BX(0.07, 0.095, 0.34), mMetal, 0, 0, -0.05);
  gpart(BX(0.045, 0.018, 0.36), mMetal, 0, 0.057, -0.05);
  gpart(BX(0.07, 0.075, 0.28), mPoly, 0, -0.005, -0.34);
  gpart(CY(0.011, 0.011, 0.34), mMetal, 0, 0.012, -0.66, Math.PI / 2);
  gpart(CY(0.019, 0.019, 0.07), mDark, 0, 0.012, -0.82, Math.PI / 2);
  gpart(BX(0.005, 0.05, 0.005), mMetal, 0, 0.07, -0.72);
  gpart(BX(0.008, 0.03, 0.015), mMetal, -0.014, 0.08, 0.12);
  gpart(BX(0.008, 0.03, 0.015), mMetal, 0.014, 0.08, 0.12);
  gpart(BX(0.05, 0.1, 0.22), mPoly, 0, -0.025, 0.3, 0.12);
  gpart(BX(0.052, 0.11, 0.03), mDark, 0, -0.04, 0.42, 0.12);
  gpart(BX(0.04, 0.11, 0.05), mPoly, 0, -0.1, 0.07, 0.4);
  const magMesh = gpart(BX(0.042, 0.17, 0.07), mDark, 0, -0.14, -0.12, -0.12);
  gpart(BX(0.03, 0.04, 0.06), mMetal, 0.04, 0.02, -0.02);
  gpart(BX(0.07, 0.06, 0.1), mGlove, -0.012, -0.06, -0.32);
  gpart(BX(0.06, 0.07, 0.08), mGlove, 0, -0.15, 0.09);
  limb([-0.012, -0.07, -0.32], [-0.26, -0.32, 0.18], 0.035, mSleeve);
  limb([0, -0.16, 0.1], [0.2, -0.4, 0.5], 0.035, mSleeve);
  const muzzle = new THREE.Object3D(); muzzle.position.set(0, 0.012, -0.87); gun.add(muzzle);
  const flashMat = new THREE.SpriteMaterial({ map: flashTex, blending: THREE.AdditiveBlending, transparent: true, depthWrite: false, fog: false });
  const flashSprite = new THREE.Sprite(flashMat); flashSprite.scale.set(0.5, 0.5, 1); flashSprite.visible = false; muzzle.add(flashSprite);
  const flashLight = new THREE.PointLight(0xffaa55, 0, 9); flashLight.position.set(0, 0.05, -0.2); muzzle.add(flashLight);

  // ====================== STATE ======================
  const player = { x: 0, z: 0, y: 0, vy: 0, yaw: 0, pitch: 0, hp: 100, onGround: true, bob: 0, lastStep: 0, moving: false };
  const keys = {};
  const MAG_SIZE = 30;
  let mag = 30, reserve = 120, reloading = 0, fireCd = 0, recoil = 0, shotCount = 0;
  let score = 0, wave = 0, running = false, gameOver = false, waveTimer = 0, waveActive = false;
  let ads = false, adsV = 0, kickP = 0, kickY = 0, roll = 0, lookDX = 0, lookDY = 0;
  const sway = { x: 0, y: 0 };
  const enemies = [], corpses = [], bullets = [], particles = [], shells = [], decals = [], tracers = [];

  // ====================== AUDIO ======================
  let actx, master, noiseBuffer, windOn = false;
  function A() {
    if (!actx) {
      try {
        actx = new (window.AudioContext || window.webkitAudioContext)();
        master = actx.createGain(); master.gain.value = 0.8; master.connect(actx.destination);
        noiseBuffer = actx.createBuffer(1, actx.sampleRate * 2, actx.sampleRate);
        const d = noiseBuffer.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
      } catch (e) {}
    }
    return actx;
  }
  function noiseHit(vol, dur, f0, f1, type = "lowpass", q = 0.7) {
    const c = A(); if (!c) return;
    const s = c.createBufferSource(); s.buffer = noiseBuffer;
    const f = c.createBiquadFilter(); f.type = type; f.Q.value = q;
    f.frequency.setValueAtTime(f0, c.currentTime); f.frequency.exponentialRampToValueAtTime(Math.max(40, f1), c.currentTime + dur);
    const g = c.createGain(); g.gain.setValueAtTime(vol, c.currentTime); g.gain.exponentialRampToValueAtTime(0.0001, c.currentTime + dur);
    s.connect(f); f.connect(g); g.connect(master); s.start(c.currentTime, Math.random()); s.stop(c.currentTime + dur + 0.05);
  }
  function tone(freq, dur, type, vol, end) {
    const c = A(); if (!c) return;
    const o = c.createOscillator(), g = c.createGain(); o.type = type;
    o.frequency.setValueAtTime(freq, c.currentTime);
    if (end) o.frequency.exponentialRampToValueAtTime(Math.max(20, end), c.currentTime + dur);
    g.gain.setValueAtTime(vol, c.currentTime); g.gain.exponentialRampToValueAtTime(0.0001, c.currentTime + dur);
    o.connect(g); g.connect(master); o.start(); o.stop(c.currentTime + dur);
  }
  function sndRifle(v = 1) { noiseHit(0.9 * v, 0.22, 6000, 300); noiseHit(0.5 * v, 0.5, 900, 60, "lowpass", 0.5); tone(120, 0.18, "sine", 0.7 * v, 45); }
  function sndStep() { noiseHit(0.12, 0.09, 500, 150); }
  function sndTick(head) { tone(head ? 2400 : 1700, 0.05, "square", 0.04); }
  function sndHurt() { noiseHit(0.5, 0.25, 700, 100); tone(70, 0.25, "sine", 0.5, 40); }
  function sndDie() { noiseHit(0.4, 0.45, 600, 80); }
  function sndReload() {
    setTimeout(() => noiseHit(0.25, 0.06, 3000, 900, "bandpass", 2), 150);
    setTimeout(() => { noiseHit(0.35, 0.08, 1500, 300, "bandpass", 2); tone(160, 0.07, "square", 0.05, 90); }, 700);
    setTimeout(() => noiseHit(0.3, 0.06, 4000, 1500, "bandpass", 3), 1050);
  }
  function startWind() {
    const c = A(); if (!c || windOn) return; windOn = true;
    const s = c.createBufferSource(); s.buffer = noiseBuffer; s.loop = true;
    const f = c.createBiquadFilter(); f.type = "lowpass"; f.frequency.value = 320;
    const g = c.createGain(); g.gain.value = 0.045;
    s.connect(f); f.connect(g); g.connect(master); s.start();
  }

  // ====================== PARTICLES / EFFECTS ======================
  const debrisGeo = new THREE.BoxGeometry(0.05, 0.05, 0.05);
  const debrisMats = { concrete: new THREE.MeshStandardMaterial({ color: 0x8a8780, roughness: 1 }), wood: new THREE.MeshStandardMaterial({ color: 0x8a6035, roughness: 1 }), metal: new THREE.MeshStandardMaterial({ color: 0x555a60, roughness: 0.5, metalness: 0.8 }), blood: new THREE.MeshBasicMaterial({ color: 0x7a0a0a }) };
  function addParticle(p) {
    scene.add(p.obj); p.t = 0; particles.push(p);
    if (particles.length > 450) removeParticle(0);
  }
  function removeParticle(i) { const p = particles[i]; scene.remove(p.obj); if (p.mat) p.mat.dispose(); particles.splice(i, 1); }
  function puff(pos, color, size, grow, life, vel, op = 0.6, grav = 0, additive = false) {
    const mat = new THREE.SpriteMaterial({ map: softTex, color, transparent: true, depthWrite: false, opacity: op, blending: additive ? THREE.AdditiveBlending : THREE.NormalBlending });
    const sp = new THREE.Sprite(mat); sp.position.copy(pos); sp.scale.set(size, size, 1);
    addParticle({ obj: sp, mat, vel: vel.clone(), life, grav, grow, baseOp: op });
  }
  function debris(pos, matKey, n, speed, normal) {
    for (let i = 0; i < n; i++) {
      const m = new THREE.Mesh(debrisGeo, debrisMats[matKey]); m.position.copy(pos);
      m.scale.setScalar(rnd(0.4, 1.2));
      const v = new THREE.Vector3(rnd(-1, 1), rnd(0, 1), rnd(-1, 1)).multiplyScalar(speed).addScaledVector(normal, speed * 0.6);
      addParticle({ obj: m, vel: v, life: rnd(0.6, 1.4), grav: 12, grow: 0, floor: true });
    }
  }
  function hitEffect(point, normal, surface) {
    const dustCol = surface === "wood" ? 0x9a7348 : 0xb9aea0;
    for (let i = 0; i < 3; i++) puff(point.clone().addScaledVector(normal, 0.05), dustCol, 0.18, 0.7, rnd(0.5, 0.9), new THREE.Vector3(rnd(-0.3, 0.3), rnd(0.1, 0.5), rnd(-0.3, 0.3)).addScaledVector(normal, 0.5), 0.5);
    debris(point, surface === "metal" ? "metal" : surface, 5, 2.2, normal);
    if (surface === "metal") for (let i = 0; i < 7; i++) puff(point.clone(), 0xffaa44, 0.07, 0, rnd(0.15, 0.3), new THREE.Vector3(rnd(-1, 1), rnd(0, 1), rnd(-1, 1)).multiplyScalar(3).addScaledVector(normal, 2.5), 1, 9, true);
    if (decals.length >= 80) { const d = decals.shift(); scene.remove(d); d.material.dispose(); }
    const d = new THREE.Mesh(new THREE.PlaneGeometry(0.13, 0.13), new THREE.MeshBasicMaterial({ map: holeTex, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4 }));
    d.position.copy(point).addScaledVector(normal, 0.012); d.lookAt(point.clone().add(normal)); d.rotation.z = rnd(0, 6);
    scene.add(d); decals.push(d);
  }
  function bloodEffect(point, dirOut) {
    puff(point, 0x7a0c0c, 0.28, 1.1, 0.5, dirOut.clone().multiplyScalar(0.8), 0.75);
    debris(point, "blood", 7, 3, dirOut);
  }
  function addTracer(from, to, life = 0.05) {
    const l = new THREE.Line(new THREE.BufferGeometry().setFromPoints([from, to]), new THREE.LineBasicMaterial({ color: 0xffd9a0, transparent: true, opacity: 0.55 }));
    scene.add(l); tracers.push({ l, life });
  }
  function ejectShell() {
    const m = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, 0.04, 8), new THREE.MeshStandardMaterial({ color: 0xc9a043, metalness: 1, roughness: 0.3 }));
    const pos = new THREE.Vector3(0.05, 0.03, -0.05); gun.localToWorld(pos); m.position.copy(pos);
    const right = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion), up = new THREE.Vector3(0, 1, 0);
    const v = right.multiplyScalar(rnd(1.5, 2.6)).addScaledVector(up, rnd(1.2, 2.2));
    m.rotation.set(rnd(0, 3), rnd(0, 3), rnd(0, 3)); scene.add(m);
    shells.push({ m, v, life: 3, spin: new THREE.Vector3(rnd(-12, 12), rnd(-12, 12), rnd(-12, 12)) });
    if (shells.length > 30) { const s = shells.shift(); scene.remove(s.m); }
  }

  // ====================== ENEMIES ======================
  function makeGLBVisual(heavy) {
    const model = THREE.SkeletonUtils.clone(soldierGLTF.scene);
    model.updateMatrixWorld(true);
    const box = new THREE.Box3().setFromObject(model);
    let h = box.max.y - box.min.y, s = 1.85 / h;
    if (!isFinite(s) || h < 0.2 || h > 30) s = 1;
    model.scale.multiplyScalar(s);
    model.position.y = isFinite(box.min.y) ? -box.min.y * s : 0;
    const mats = [], tint = heavy ? new THREE.Color(0xc07060) : new THREE.Color(rnd(0.8, 1), rnd(0.75, 1), rnd(0.75, 1));
    model.traverse(o => {
      if (o.isMesh) {
        o.castShadow = true; o.frustumCulled = false;
        const arr = Array.isArray(o.material), ms = arr ? o.material : [o.material];
        const nm = ms.map(m => { const c = m.clone(); if (c.color) c.color.multiply(tint); mats.push(c); return c; });
        o.material = arr ? nm : nm[0];
      }
    });
    const mixer = new THREE.AnimationMixer(model), acts = {};
    (soldierGLTF.animations || []).forEach(cl => { acts[cl.name.toLowerCase()] = mixer.clipAction(cl); });
    let cur = null;
    const play = n => {
      const a = acts[n] || acts.walk || acts.run || acts.idle || Object.values(acts)[0];
      if (!a || a === cur) return;
      a.reset(); a.fadeIn(0.18); a.play(); if (cur) cur.fadeOut(0.18); cur = a;
    };
    play("walk"); mixer.update(rnd(0, 1.5));
    return { root: model, mats, update(dt, state) { play(state); mixer.update(dt); }, die() { mixer.timeScale = 0; } };
  }
  function makeFallbackVisual(heavy) {
    const root = new THREE.Group(), mats = [];
    const M = (c, r, m, map) => { const x = new THREE.MeshStandardMaterial({ color: c, roughness: r, metalness: m, map: map || null }); mats.push(x); return x; };
    const camoM = M(heavy ? 0xb08070 : 0xffffff, 0.95, 0, camoTexture), vestM = M(0x2a2e28, 0.9, 0.05), skinM = M(0xc99a7c, 0.8, 0), helmM = M(0x3d4530, 0.7, 0.1), bootM = M(0x15130f, 0.8, 0.05), gunM = M(0x1b1c1e, 0.5, 0.7);
    const mk = (geo, mat, x, y, z) => { const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.castShadow = true; return m; };
    root.add(mk(BX(0.46, 0.6, 0.26), camoM, 0, 1.25, 0), mk(BX(0.5, 0.46, 0.3), vestM, 0, 1.28, 0), mk(BX(0.44, 0.2, 0.25), camoM, 0, 0.93, 0),
      mk(CY(0.05, 0.055, 0.08, 8), skinM, 0, 1.6, 0), mk(new THREE.SphereGeometry(0.11, 16, 12), skinM, 0, 1.7, 0),
      mk(new THREE.SphereGeometry(0.135, 16, 10, 0, Math.PI * 2, 0, Math.PI * 0.55), helmM, 0, 1.725, 0),
      mk(BX(0.05, 0.07, 0.75), gunM, 0.08, 1.3, 0.42));
    const legs = [-0.11, 0.11].map(x => {
      const p = new THREE.Group(); p.position.set(x, 0.92, 0);
      p.add(mk(CY(0.095, 0.08, 0.46, 10), camoM, 0, -0.23, 0), mk(CY(0.075, 0.065, 0.44, 10), camoM, 0, -0.66, 0), mk(BX(0.11, 0.09, 0.25), bootM, 0, -0.87, 0.05));
      root.add(p); return p;
    });
    [-0.3, 0.3].forEach(x => { const p = new THREE.Group(); p.position.set(x, 1.5, 0); p.rotation.x = -1.25; p.add(mk(CY(0.055, 0.05, 0.5, 8), camoM, 0, -0.25, 0)); root.add(p); });
    let ph = rnd(0, 6);
    return { root, mats, update(dt, state) {
      if (state !== "idle") ph += dt * (state === "run" ? 11 : 7);
      const a = state === "idle" ? 0 : Math.sin(ph) * (state === "run" ? 0.9 : 0.6);
      legs[0].rotation.x = a; legs[1].rotation.x = -a;
      root.position.y = state === "idle" ? 0 : Math.abs(Math.sin(ph)) * 0.04;
    }, die() {} };
  }

  const hbMat = new THREE.MeshBasicMaterial({ visible: false });
  function makeEnemy(x, z, heavy) {
    const group = new THREE.Group(); group.position.set(x, 0, z);
    const vis = soldierGLTF ? makeGLBVisual(heavy) : makeFallbackVisual(heavy);
    const fall = new THREE.Group(), holder = new THREE.Group();
    holder.rotation.y = MODEL_FACING; holder.add(vis.root); fall.add(holder); group.add(fall);
    const hbBody = new THREE.Mesh(new THREE.BoxGeometry(0.75, 0.75, 0.45), hbMat); hbBody.position.y = 1.2;
    const hbLegs = new THREE.Mesh(new THREE.BoxGeometry(0.5, 0.85, 0.32), hbMat); hbLegs.position.y = 0.43;
    const hbHead = new THREE.Mesh(new THREE.SphereGeometry(0.2, 10, 8), hbMat); hbHead.position.y = 1.68;
    group.add(hbBody, hbLegs, hbHead);
    const mk = new THREE.Sprite(new THREE.SpriteMaterial({ map: softTex, color: heavy ? 0xff9a00 : 0xff2a2a, transparent: true, depthTest: false, depthWrite: false, opacity: 0.95, fog: false }));
    mk.scale.set(0.35, 0.35, 1); mk.position.y = 2.25; mk.renderOrder = 10; group.add(mk);
    if (heavy) group.scale.setScalar(1.18);
    scene.add(group);
    const e = {
      group, fall, vis, heavy, hitboxes: [hbBody, hbLegs, hbHead], dead: false, yaw: 0, flashT: 0, pause: 0, avoidT: 0, avoidDir: 1,
      hp: (heavy ? 12 : 5) + Math.floor(wave / 3), speed: (heavy ? 2.0 : 2.4) + rnd(0, 1.4) + wave * 0.06,
      shootCd: rnd(1, 2.5), strafe: Math.random() < 0.5 ? 1 : -1, strafeT: rnd(1, 3)
    };
    hbBody.userData = { enemy: e, mult: 1 }; hbLegs.userData = { enemy: e, mult: 0.7 }; hbHead.userData = { enemy: e, mult: 3, head: true };
    return e;
  }
  function spawnWave() {
    wave++;
    const n = Math.min(24, 3 + wave * 2);
    for (let i = 0; i < n; i++) {
      let x, z, tries = 0;
      do { x = rnd(-ARENA + 3, ARENA - 3); z = rnd(-ARENA + 3, ARENA - 3); tries++; }
      while ((hitsSolid(x, z, 0.8) || Math.hypot(x - player.x, z - player.z) < 24) && tries < 100);
      enemies.push(makeEnemy(x, z, wave >= 3 && Math.random() < 0.2));
    }
    waveActive = true; showMsg("WAVE " + wave); updateHUD();
  }
  function showMsg(t) { const m = $("msg"); m.textContent = t; m.style.opacity = 1; clearTimeout(showMsg.t); showMsg.t = setTimeout(() => m.style.opacity = 0, 1800); }
  function killEnemy(e, head) {
    e.dead = true; e.vis.die();
    corpses.push({ e, t: 0 });
    score += 100 + wave * 10 + (head ? 50 : 0);
    if (head) showMsg("HEADSHOT");
    sndDie();
  }

  // ====================== SHOOTING ======================
  const ray = new THREE.Raycaster();
  function hitMarker(kill, head) {
    const h = $("hitmarker"); h.className = head ? "head" : ""; h.style.opacity = 1;
    h.style.transform = kill ? "scale(1.4)" : "scale(1)";
    clearTimeout(hitMarker.t); hitMarker.t = setTimeout(() => h.style.opacity = 0, 130);
  }
  function shoot() {
    if (reloading > 0 || fireCd > 0) return;
    if (mag <= 0) { reload(); return; }
    mag--; fireCd = 0.095; recoil = 1; shotCount++;
    sndRifle(1);
    flashSprite.visible = true; flashSprite.scale.setScalar(rnd(0.35, 0.65)); flashMat.rotation = rnd(0, 6.28); flashLight.intensity = 3.5;
    setTimeout(() => { flashSprite.visible = false; flashLight.intensity = 0; }, 45);
    kickP += ads ? 0.0055 : 0.011; kickY += rnd(-0.004, 0.004);
    ejectShell();
    camera.updateMatrixWorld(true);

    const spread = (ads ? 0.0015 : 0.006) + (player.moving ? 0.006 : 0) + (player.onGround ? 0 : 0.01);
    ray.setFromCamera({ x: rnd(-spread, spread), y: rnd(-spread, spread) }, camera);
    const targets = blockers.slice();
    for (const e of enemies) if (!e.dead) for (const hb of e.hitboxes) targets.push(hb);
    const hits = ray.intersectObjects(targets, false);
    const from = new THREE.Vector3(); muzzle.getWorldPosition(from);
    let end = ray.ray.at(120, new THREE.Vector3());
    if (hits.length) {
      const h = hits[0]; end = h.point.clone();
      const ud = h.object.userData;
      if (ud.enemy) {
        const e = ud.enemy;
        e.hp -= ud.mult; e.flashT = 0.08;
        bloodEffect(h.point, ray.ray.direction.clone().multiplyScalar(0.6).add(new THREE.Vector3(0, 0.3, 0)));
        sndTick(ud.head);
        if (e.hp <= 0) { killEnemy(e, ud.head); hitMarker(true, ud.head); } else hitMarker(false, ud.head);
        updateHUD();
      } else if (h.face) {
        const n = h.face.normal.clone().transformDirection(h.object.matrixWorld);
        hitEffect(h.point, n, ud.surface || "concrete");
      }
    }
    if (shotCount % 3 === 0) addTracer(from, end);
    updateHUD();
    if (mag <= 0 && reserve > 0) reload();
  }
  function reload() {
    if (reloading > 0 || mag === MAG_SIZE || reserve <= 0) return;
    reloading = 1.4; $("reloadtxt").textContent = "RELOADING"; sndReload();
  }

  // ====================== ENEMY FIRE ======================
  const enemyBulletMat = new THREE.MeshBasicMaterial({ color: 0xffb060, toneMapped: false });
  const enemyBulletGeo = new THREE.BoxGeometry(0.04, 0.04, 0.8);
  function enemyShoot(e) {
    const p = e.group.position, fwd = new THREE.Vector3(Math.sin(e.yaw), 0, Math.cos(e.yaw));
    const from = new THREE.Vector3(p.x, 1.35, p.z).addScaledVector(fwd, 0.7);
    const dist = Math.hypot(player.x - p.x, player.z - p.z);
    const err = (0.7 + dist * 0.03) * Math.max(0.35, 1 - wave * 0.04);
    const to = new THREE.Vector3(player.x + rnd(-err, err), player.y + 1.2 + rnd(-err, err) * 0.5, player.z + rnd(-err, err));
    const dir = to.sub(from).normalize();
    const m = new THREE.Mesh(enemyBulletGeo, enemyBulletMat); m.position.copy(from); m.lookAt(from.clone().add(dir)); scene.add(m);
    bullets.push({ m, v: dir.multiplyScalar(36), life: 3.5 });
    puff(from, 0xffc070, 0.55, 0, 0.07, new THREE.Vector3(), 1, 0, true);
    e.pause = 0.45;
    const vol = clamp(1 - dist / 70, 0.06, 1) * 0.45; sndRifle(vol);
  }
  function hurt(d) {
    if (gameOver) return;
    player.hp = Math.max(0, player.hp - d);
    $("damage").style.opacity = 1; setTimeout(() => $("damage").style.opacity = 0, 200);
    roll = rnd(-0.04, 0.04); kickP += 0.01;
    sndHurt(); updateHUD();
    if (player.hp <= 0) endGame();
  }

  // ====================== HUD / FLOW ======================
  function updateHUD() {
    $("wave").textContent = wave; $("score").textContent = score;
    $("enemies").textContent = enemies.filter(e => !e.dead).length;
    $("mag").textContent = mag; $("reserve").textContent = reserve;
    $("healthfill").style.width = player.hp + "%";
    $("lowhp").style.opacity = player.hp < 35 ? (1 - player.hp / 35) * 0.9 : 0;
  }
  function resetGame() {
    enemies.forEach(e => scene.remove(e.group)); enemies.length = 0;
    corpses.forEach(c => scene.remove(c.e.group)); corpses.length = 0;
    bullets.forEach(b => scene.remove(b.m)); bullets.length = 0;
    while (particles.length) removeParticle(0);
    Object.assign(player, { x: 0, z: 0, y: 0, vy: 0, yaw: 0, pitch: 0, hp: 100 });
    mag = MAG_SIZE; reserve = 120; reloading = 0; score = 0; wave = 0; waveActive = false; waveTimer = 0.8; gameOver = false;
    $("reloadtxt").textContent = ""; updateHUD();
  }
  function endGame() {
    gameOver = true; running = false; mouseDown = false; ads = false;
    document.exitPointerLock(); document.body.style.cursor = "";
    $("title").textContent = "YOU DIED";
    $("sub").textContent = "You reached wave " + wave + " with a score of " + score + ".";
    $("btn").textContent = "CLICK TO PLAY AGAIN";
    overlay.style.display = "flex";
  }

  const overlay = $("overlay");
  $("sub").textContent = "Survive endless waves of hostile soldiers.";
  function beginUnlocked() {
    if (running) return;
    running = true; overlay.style.display = "none";
    try { A().resume(); startWind(); } catch (e) {}
    document.body.style.cursor = "none";
    showMsg("Mouse capture blocked: move the mouse to look. Click to retry capture");
  }
  overlay.addEventListener("click", () => {
    if (gameOver) resetGame();
    try { A().resume(); } catch (e) {}
    let p;
    try { p = renderer.domElement.requestPointerLock(); } catch (e) { beginUnlocked(); return; }
    if (p && p.catch) p.catch(beginUnlocked);
  });
  document.addEventListener("pointerlockerror", beginUnlocked);
  document.addEventListener("contextmenu", e => e.preventDefault());
  document.addEventListener("pointerlockchange", () => {
    if (document.pointerLockElement === renderer.domElement) {
      running = true; overlay.style.display = "none";
      try { A().resume(); startWind(); } catch (e) {}
    } else if (!gameOver) {
      running = false; mouseDown = false; ads = false;
      $("title").textContent = "PAUSED"; $("sub").textContent = "Click to resume.";
      $("btn").textContent = "CLICK TO RESUME";
      overlay.style.display = "flex";
    }
  });

  // ====================== INPUT ======================
  let mouseDown = false, mouseX = innerWidth / 2;
  document.addEventListener("mousemove", e => {
    mouseX = e.clientX;
    if (!running) return;
    player.yaw -= e.movementX * 0.0022;
    player.pitch = clamp(player.pitch - e.movementY * 0.0022, -1.5, 1.5);
    lookDX += e.movementX; lookDY += e.movementY;
  });
  document.addEventListener("mousedown", e => {
    if (!running) return;
    if (e.button === 0) mouseDown = true;
    if (e.button === 2) ads = true;
    if (document.pointerLockElement !== renderer.domElement) {
      try { const p = renderer.domElement.requestPointerLock(); if (p && p.catch) p.catch(() => {}); } catch (err) {}
    }
  });
  document.addEventListener("mouseup", e => { if (e.button === 0) mouseDown = false; if (e.button === 2) ads = false; });
  document.addEventListener("keydown", e => {
    keys[e.code] = true;
    if (e.code === "KeyR" && running) reload();
    if (e.code === "Space") e.preventDefault();
  });
  document.addEventListener("keyup", e => keys[e.code] = false);
  addEventListener("blur", () => { for (const k in keys) keys[k] = false; mouseDown = false; ads = false; });
  addEventListener("resize", () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); });

  // ====================== UPDATE ======================
  function movePlayer(dt) {
    if (document.pointerLockElement !== renderer.domElement) {
      if (mouseX < innerWidth * 0.03) player.yaw += 2.2 * dt;
      else if (mouseX > innerWidth * 0.97) player.yaw -= 2.2 * dt;
    }
    const sprint = (keys.ShiftLeft || keys.ShiftRight) && keys.KeyW && !ads;
    const speed = ads ? 3.2 : (sprint ? 9 : 6);
    let fx = 0, fz = 0;
    if (keys.KeyW) fz -= 1; if (keys.KeyS) fz += 1;
    if (keys.KeyA) fx -= 1; if (keys.KeyD) fx += 1;
    const len = Math.hypot(fx, fz) || 1; fx /= len; fz /= len;
    const s = Math.sin(player.yaw), c = Math.cos(player.yaw);
    const dx = (fx * c + fz * s) * speed * dt, dz = (-fx * s + fz * c) * speed * dt, r = 0.4;
    if (!hitsSolid(player.x + dx, player.z, r, player.y)) player.x += dx;
    if (!hitsSolid(player.x, player.z + dz, r, player.y)) player.z += dz;

    if (keys.Space && player.onGround) { player.vy = 7.5; player.onGround = false; }
    player.vy -= 20 * dt; player.y += player.vy * dt;
    let ground = 0;
    for (const sd of solids) {
      if (player.x > sd.minX - r && player.x < sd.maxX + r && player.z > sd.minZ - r && player.z < sd.maxZ + r && sd.h <= player.y + 0.3 && sd.h < 5) ground = Math.max(ground, sd.h);
    }
    if (player.y <= ground) { player.y = ground; player.vy = 0; player.onGround = true; } else player.onGround = false;

    player.moving = !!(fx || fz) && player.onGround;
    player.bob += player.moving ? dt * (sprint ? 13 : (ads ? 6 : 9)) : 0;
    const stepIdx = Math.floor(player.bob / Math.PI);
    if (player.moving && stepIdx !== player.lastStep) { player.lastStep = stepIdx; sndStep(); }
    const bobAmp = player.moving ? (sprint ? 0.06 : 0.035) * (ads ? 0.3 : 1) : 0;

    kickP *= Math.exp(-dt * 9); kickY *= Math.exp(-dt * 9); roll *= Math.exp(-dt * 8);
    camera.position.set(player.x, player.y + 1.7 + Math.sin(player.bob) * bobAmp, player.z);
    camera.rotation.set(player.pitch + kickP, player.yaw + kickY, roll + Math.cos(player.bob * 0.5) * bobAmp * 0.2);
    const targetFov = ads ? 48 : (sprint ? 80 : 74);
    camera.fov = lerp(camera.fov, targetFov, Math.min(1, dt * 10)); camera.updateProjectionMatrix();
    camera.updateMatrixWorld(true);
    return sprint;
  }

  function updateEnemies(dt, t) {
    for (const e of enemies) {
      const p = e.group.position;
      const dx = player.x - p.x, dz = player.z - p.z, dist = Math.hypot(dx, dz) || 1, nx = dx / dist, nz = dz / dist;
      const target = Math.atan2(dx, dz);
      let diff = target - e.yaw; while (diff > Math.PI) diff -= 6.2832; while (diff < -Math.PI) diff += 6.2832;
      e.yaw += diff * Math.min(1, dt * 8); e.group.rotation.y = e.yaw;
      const los = hasLOS(p.x, p.z, player.x, player.z);
      e.strafeT -= dt; if (e.strafeT <= 0) { e.strafe *= -1; e.strafeT = rnd(1, 3); }
      e.pause -= dt;
      let mx = 0, mz = 0, spd = e.speed, state = "idle";
      if (e.pause <= 0) {
        if (e.avoidT > 0) { e.avoidT -= dt; mx = -nz * e.avoidDir + nx * 0.3; mz = nx * e.avoidDir + nz * 0.3; }
        else if (!los || dist > 13) { mx = nx; mz = nz; }
        else if (dist < 6) { mx = -nx; mz = -nz; spd *= 0.8; }
        else { mx = -nz * e.strafe; mz = nx * e.strafe; spd *= 0.6; }
        const nxp = p.x + mx * spd * dt, nzp = p.z + mz * spd * dt;
        let moved = false;
        if (!hitsSolid(nxp, p.z, 0.5)) { p.x = nxp; moved = true; }
        if (!hitsSolid(p.x, nzp, 0.5)) { p.z = nzp; moved = true; }
        if (!moved) { e.avoidT = rnd(0.6, 1.2); e.avoidDir = Math.random() < 0.5 ? 1 : -1; }
        state = spd > 3.0 ? "run" : "walk";
      }
      for (const o of enemies) {
        if (o === e) continue;
        const ox = p.x - o.group.position.x, oz = p.z - o.group.position.z, od = Math.hypot(ox, oz);
        if (od < 0.9 && od > 0.001) { const push = (0.9 - od) * 0.5; const ax = p.x + ox / od * push, az = p.z + oz / od * push; if (!hitsSolid(ax, az, 0.5)) { p.x = ax; p.z = az; } }
      }
      e.shootCd -= dt;
      if (e.shootCd <= 0 && los && dist < 40) { enemyShoot(e); e.shootCd = Math.max(0.8, 2.2 - wave * 0.08) + rnd(0, 1); }
      e.vis.update(dt, state, t);
      if (e.flashT > 0) { e.flashT -= dt; e.vis.mats.forEach(m => m.emissive && m.emissive.setHex(0x772211)); }
      else e.vis.mats.forEach(m => m.emissive && m.emissive.setHex(0x2e2218));
    }
    for (let i = enemies.length - 1; i >= 0; i--) if (enemies[i].dead) enemies.splice(i, 1);
  }
  function updateCorpses(dt) {
    for (let i = corpses.length - 1; i >= 0; i--) {
      const c = corpses[i]; c.t += dt;
      const k = Math.min(1, c.t / 0.7), ease = 1 - Math.pow(1 - k, 3);
      c.e.fall.rotation.x = -Math.PI / 2 * ease; c.e.fall.position.y = 0.12 * ease;
      c.e.vis.mats.forEach(m => m.emissive && m.emissive.setHex(0x000000));
      if (c.t > 8) { scene.remove(c.e.group); corpses.splice(i, 1); }
    }
  }
  function updateBullets(dt) {
    for (let i = bullets.length - 1; i >= 0; i--) {
      const b = bullets[i]; b.life -= dt;
      const steps = Math.ceil(36 * dt / 0.4); let remove = b.life <= 0;
      for (let s = 0; s < steps && !remove; s++) {
        b.m.position.addScaledVector(b.v, dt / steps);
        const p = b.m.position;
        if (pointInSolid(p.x, p.y, p.z)) { remove = true; puff(p, 0xb9aea0, 0.15, 0.5, 0.4, new THREE.Vector3(0, 0.3, 0), 0.4); break; }
        if (Math.hypot(p.x - player.x, p.z - player.z) < 0.6 && p.y > player.y && p.y < player.y + 1.9) { hurt(6); remove = true; }
      }
      if (remove) { scene.remove(b.m); bullets.splice(i, 1); }
    }
  }
  function updateFX(dt) {
    for (let i = tracers.length - 1; i >= 0; i--) { const t = tracers[i]; t.life -= dt; if (t.life <= 0) { scene.remove(t.l); t.l.geometry.dispose(); tracers.splice(i, 1); } }
    for (let i = particles.length - 1; i >= 0; i--) {
      const p = particles[i]; p.t += dt;
      if (p.t >= p.life) { removeParticle(i); continue; }
      p.obj.position.addScaledVector(p.vel, dt); p.vel.y -= p.grav * dt;
      if (p.grow) { p.obj.scale.x += p.grow * dt; p.obj.scale.y += p.grow * dt; }
      if (p.mat) p.mat.opacity = p.baseOp * (1 - p.t / p.life);
      if (p.floor && p.obj.position.y < 0.03) { p.obj.position.y = 0.03; p.vel.set(0, 0, 0); }
    }
    for (let i = shells.length - 1; i >= 0; i--) {
      const s = shells[i]; s.life -= dt;
      s.v.y -= 9.8 * dt; s.m.position.addScaledVector(s.v, dt);
      s.m.rotation.x += s.spin.x * dt; s.m.rotation.y += s.spin.y * dt;
      if (s.m.position.y < 0.02) { s.m.position.y = 0.02; s.v.y *= -0.3; s.v.x *= 0.5; s.v.z *= 0.5; s.spin.multiplyScalar(0.4); }
      if (s.life <= 0) { scene.remove(s.m); shells.splice(i, 1); }
    }
  }

  // ====================== MAIN LOOP ======================
  let last = performance.now(), tAcc = 0;
  function loop(now) {
    requestAnimationFrame(loop);
    const dt = Math.min(0.05, (now - last) / 1000); last = now; tAcc += dt;
    let sprint = false;
    if (running) {
      sprint = movePlayer(dt);
      fireCd -= dt;
      if (mouseDown) shoot();
      if (reloading > 0) {
        reloading -= dt;
        if (reloading <= 0) {
          const take = Math.min(MAG_SIZE - mag, reserve); mag += take; reserve -= take; reloading = 0;
          $("reloadtxt").textContent = ""; updateHUD();
        }
      }
      updateEnemies(dt, tAcc); updateBullets(dt);
      if (waveActive && enemies.length === 0) {
        waveActive = false; waveTimer = 3.5;
        player.hp = Math.min(100, player.hp + 25); reserve += 60;
        showMsg("WAVE CLEARED"); updateHUD();
      }
      if (!waveActive) { waveTimer -= dt; if (waveTimer <= 0) spawnWave(); }
    }
    updateCorpses(dt); updateFX(dt);

    // weapon animation
    recoil = Math.max(0, recoil - dt * 10);
    adsV += ((ads && running ? 1 : 0) - adsV) * Math.min(1, dt * 12);
    $("crosshair").style.opacity = 1 - adsV;
    const tx = clamp(-lookDX * 0.0009, -0.04, 0.04), ty = clamp(lookDY * 0.0009, -0.04, 0.04);
    sway.x += (tx - sway.x) * Math.min(1, dt * 8); sway.y += (ty - sway.y) * Math.min(1, dt * 8);
    lookDX = 0; lookDY = 0;
    const rl = reloading > 0 ? Math.sin(Math.PI * (1 - reloading / 1.4)) : 0;
    const bobX = player.moving ? Math.sin(player.bob * 0.5) * 0.012 * (1 - adsV * 0.8) : 0;
    const bobY = player.moving ? Math.abs(Math.sin(player.bob * 0.5)) * 0.012 * (1 - adsV * 0.8) : 0;
    const sprintPose = sprint ? 1 : 0;
    gun.position.set(lerp(0.2, 0, adsV) + sway.x + bobX - sprintPose * 0.05, lerp(-0.2, -0.1, adsV) + sway.y + bobY - rl * 0.12 + Math.sin(tAcc * 1.6) * 0.002, lerp(-0.38, -0.3, adsV) + recoil * 0.05);
    gun.rotation.set(recoil * 0.05 + rl * 0.6 + sprintPose * 0.15, sway.x * 2 + sprintPose * 0.5, sway.x * 1.5 + rl * 0.2);
    magMesh.position.y = -0.14 - (reloading > 0 && rl > 0.3 ? 0.12 : 0);

    sky.position.copy(camera.position);
    dust.rotation.y += dt * 0.01; dust.position.x = Math.sin(tAcc * 0.1) * 2;
    renderer.render(scene, camera);
  }

  camera.position.set(0, 1.7, 0);
  resetGame(); waveTimer = 0.8;
  $("btn").style.display = "";
  requestAnimationFrame(loop);
}

// ====================== BOOT ======================
(async function boot() {
  const sub = document.getElementById("sub"), btn = document.getElementById("btn");
  btn.style.display = "none";
  sub.textContent = "Loading engine...";
  const ok = await loadScript(LIBS.three, () => !!window.THREE);
  if (!ok) { sub.textContent = "Could not load three.js. Check your internet connection or ad blocker, then reload."; return; }
  sub.textContent = "Loading soldier model...";
  let gltf = null;
  try {
    const a = await loadScript(LIBS.gltf, () => !!THREE.GLTFLoader);
    const b = await loadScript(LIBS.skel, () => !!THREE.SkeletonUtils);
    if (a && b) gltf = await loadSoldier(LIBS.model);
  } catch (e) {}
  sub.textContent = "Building arena...";
  setTimeout(() => startGame(gltf), 30);
})();
</script>
</body>
</html>

Game Source: Arena Shooter HD

Creator: UltraNinja96

Libraries: three

Complexity: complex (1029 lines, 58.7 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: arena-shooter-hd-ultraninja96" to link back to the original. Then publish at arcadelab.ai/publish.