/* OmniNPC HTML Game — Three.js + Nemotron Nano/Super * 3 AI NPCs, 60s timer, voice, recording, latency chart, dialogue, reasoning panel. * Talks to api_server.py via fetch() against API_URL. */ import * as THREE from 'three'; // ──────────────────────────────────────────────────────────────────────────── // Config // ──────────────────────────────────────────────────────────────────────────── const ROUND_SECONDS = 60; const NUM_COINS = 16; const ARENA_HALF = 18; // 36×36 arena const COIN_RADIUS = 0.5; const PICKUP_DIST = 1.4; const PERCEPTION_INTERVAL_MS = 700; // round-robin: each NPC every ~2.1s const SUPER_INTERVAL_MS = 10_000; const DIALOGUE_DIST = 4.0; const DIALOGUE_COOLDOWN_MS = 8_000; const PLAYER_SPEED = 6.0; const NPC_SPEED = 4.0; let API_URL = window.location.origin; // ──────────────────────────────────────────────────────────────────────────── // State // ──────────────────────────────────────────────────────────────────────────── const state = { running: false, startTime: 0, timeLeft: ROUND_SECONDS, scores: { player: 0, hostile: 0, ally: 0, wanderer: 0 }, directive: 'Compete to collect coins.', npcs: [], coins: [], player: null, keys: {}, pointerLocked: false, yaw: 0, pitch: 0, velocityY: 0, onGround: true, // metrics latencies: [], totalCalls: 0, // perception scheduling rrIndex: 0, lastSuperTime: 0, // recording recorder: null, recordChunks: [], recording: false, // voice recognition: null, voiceActive: false, lastVoiceText: '', // dialogue lastDialogueTime: 0, }; // ──────────────────────────────────────────────────────────────────────────── // Sound effects — Web Audio synth (no asset files; everything procedural) // ──────────────────────────────────────────────────────────────────────────── const sfx = { ctx: null, enabled: true, ensure() { if (!this.ctx) { const AC = window.AudioContext || window.webkitAudioContext; if (AC) this.ctx = new AC(); } return this.ctx; }, blip(freq, dur = 0.08, type = 'sine', vol = 0.18) { const ctx = this.ensure(); if (!ctx || !this.enabled) return; const osc = ctx.createOscillator(), g = ctx.createGain(); osc.type = type; osc.frequency.value = freq; g.gain.setValueAtTime(vol, ctx.currentTime); g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + dur); osc.connect(g).connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + dur); }, sweep(f0, f1, dur = 0.25, type = 'square', vol = 0.15) { const ctx = this.ensure(); if (!ctx || !this.enabled) return; const osc = ctx.createOscillator(), g = ctx.createGain(); osc.type = type; osc.frequency.setValueAtTime(f0, ctx.currentTime); osc.frequency.exponentialRampToValueAtTime(Math.max(20, f1), ctx.currentTime + dur); g.gain.setValueAtTime(vol, ctx.currentTime); g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + dur); osc.connect(g).connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + dur); }, // ── Game-specific cues ── coinPlayer() { this.sweep(900, 1700, 0.12, 'triangle', 0.18); }, coinNPC() { this.blip(700, 0.06, 'square', 0.10); }, voiceAck() { this.blip(520, 0.07, 'sine', 0.12); setTimeout(()=>this.blip(780,0.07,'sine',0.12),60); }, evade() { this.sweep(1200, 200, 0.15, 'sawtooth', 0.10); }, dialogue() { this.blip(440, 0.06, 'triangle', 0.08); setTimeout(()=>this.blip(660,0.06,'triangle',0.08),80); }, win() { [523, 659, 784, 1047].forEach((f, i) => setTimeout(() => this.blip(f, 0.18, 'triangle', 0.16), i * 130)); }, loss() { [392, 330, 262].forEach((f, i) => setTimeout(() => this.blip(f, 0.22, 'sine', 0.16), i * 180)); }, countdown() { this.blip(880, 0.08, 'sine', 0.12); }, }; // ──────────────────────────────────────────────────────────────────────────── // Three.js scene // ──────────────────────────────────────────────────────────────────────────── const canvas = document.getElementById('game-canvas'); const renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); renderer.setSize(innerWidth, innerHeight); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; const scene = new THREE.Scene(); // Sky gradient const skyGeom = new THREE.SphereGeometry(200, 32, 16); const skyMat = new THREE.ShaderMaterial({ side: THREE.BackSide, uniforms: { topColor: { value: new THREE.Color(0x4a7eda) }, bottomColor: { value: new THREE.Color(0xc8e2ff) }, }, vertexShader: `varying vec3 vWorld; void main() { vWorld = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`, fragmentShader: `uniform vec3 topColor; uniform vec3 bottomColor; varying vec3 vWorld; void main() { float h = normalize(vWorld).y * 0.5 + 0.5; gl_FragColor = vec4(mix(bottomColor, topColor, smoothstep(0.0, 1.0, h)), 1.0); }` }); scene.add(new THREE.Mesh(skyGeom, skyMat)); // Sun (directional light + visible disc) const sunLight = new THREE.DirectionalLight(0xfff5d1, 1.05); sunLight.position.set(30, 50, 20); sunLight.castShadow = true; sunLight.shadow.mapSize.set(2048, 2048); sunLight.shadow.camera.left = -25; sunLight.shadow.camera.right = 25; sunLight.shadow.camera.top = 25; sunLight.shadow.camera.bottom = -25; scene.add(sunLight); scene.add(new THREE.AmbientLight(0xa3c4f3, 0.45)); const sunDisc = new THREE.Mesh( new THREE.SphereGeometry(3, 16, 16), new THREE.MeshBasicMaterial({ color: 0xfff088 }) ); sunDisc.position.copy(sunLight.position); scene.add(sunDisc); // Ground — procedural Minecraft-style grass const groundCanvas = document.createElement('canvas'); groundCanvas.width = groundCanvas.height = 256; const gctx = groundCanvas.getContext('2d'); gctx.fillStyle = '#3a7a2c'; gctx.fillRect(0, 0, 256, 256); for (let i = 0; i < 4000; i++) { const x = Math.random() * 256, y = Math.random() * 256; const v = Math.floor(Math.random() * 50); gctx.fillStyle = `rgb(${50 + v}, ${110 + v}, ${40 + v})`; gctx.fillRect(x, y, 2, 2); } const groundTex = new THREE.CanvasTexture(groundCanvas); groundTex.wrapS = groundTex.wrapT = THREE.RepeatWrapping; groundTex.repeat.set(12, 12); groundTex.colorSpace = THREE.SRGBColorSpace; const ground = new THREE.Mesh( new THREE.PlaneGeometry(ARENA_HALF * 2, ARENA_HALF * 2), new THREE.MeshLambertMaterial({ map: groundTex }) ); ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground); // Stone wall around arena const stoneCanvas = document.createElement('canvas'); stoneCanvas.width = stoneCanvas.height = 64; const sctx = stoneCanvas.getContext('2d'); sctx.fillStyle = '#6b7280'; sctx.fillRect(0, 0, 64, 64); for (let i = 0; i < 200; i++) { const v = Math.floor(Math.random() * 60); sctx.fillStyle = `rgb(${90 + v}, ${95 + v}, ${100 + v})`; sctx.fillRect(Math.random() * 64, Math.random() * 64, 2, 2); } const stoneTex = new THREE.CanvasTexture(stoneCanvas); stoneTex.wrapS = stoneTex.wrapT = THREE.RepeatWrapping; stoneTex.repeat.set(8, 1); stoneTex.colorSpace = THREE.SRGBColorSpace; const wallMat = new THREE.MeshLambertMaterial({ map: stoneTex }); const wallSpecs = [ [0, 1.5, ARENA_HALF, ARENA_HALF * 2, 3, 0.5], [0, 1.5, -ARENA_HALF, ARENA_HALF * 2, 3, 0.5], [ARENA_HALF, 1.5, 0, 0.5, 3, ARENA_HALF * 2], [-ARENA_HALF, 1.5, 0, 0.5, 3, ARENA_HALF * 2], ]; for (const [x, y, z, sx, sy, sz] of wallSpecs) { const w = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), wallMat); w.position.set(x, y, z); w.castShadow = w.receiveShadow = true; scene.add(w); } // Trees scattered around function makeTree(x, z) { const g = new THREE.Group(); const trunk = new THREE.Mesh( new THREE.BoxGeometry(0.5, 2, 0.5), new THREE.MeshLambertMaterial({ color: 0x6b3f1c }) ); trunk.position.y = 1; trunk.castShadow = true; const leaves = new THREE.Mesh( new THREE.BoxGeometry(2, 2, 2), new THREE.MeshLambertMaterial({ color: 0x2d5e1e }) ); leaves.position.y = 3; leaves.castShadow = true; g.add(trunk); g.add(leaves); g.position.set(x, 0, z); return g; } for (let i = 0; i < 8; i++) { const x = (Math.random() - 0.5) * (ARENA_HALF - 2) * 2; const z = (Math.random() - 0.5) * (ARENA_HALF - 2) * 2; if (Math.abs(x) > 3 || Math.abs(z) > 3) { scene.add(makeTree(x, z)); } } // Coloured zone tiles (for navigate_to_objective) const ZONES = { red: { pos: new THREE.Vector3(-10, 0.05, 0), color: 0xc83232 }, blue: { pos: new THREE.Vector3(0, 0.05, 10), color: 0x3264e6 }, green: { pos: new THREE.Vector3(10, 0.05, 0), color: 0x32c846 }, }; for (const k in ZONES) { const z = ZONES[k]; const tile = new THREE.Mesh( new THREE.PlaneGeometry(4, 4), new THREE.MeshLambertMaterial({ color: z.color }) ); tile.rotation.x = -Math.PI / 2; tile.position.copy(z.pos); tile.receiveShadow = true; scene.add(tile); } // ──────────────────────────────────────────────────────────────────────────── // Coin spawning // ──────────────────────────────────────────────────────────────────────────── function spawnCoins() { for (const c of state.coins) scene.remove(c.mesh); state.coins = []; for (let i = 0; i < NUM_COINS; i++) { const x = (Math.random() - 0.5) * (ARENA_HALF - 2) * 2; const z = (Math.random() - 0.5) * (ARENA_HALF - 2) * 2; const m = new THREE.Mesh( new THREE.CylinderGeometry(COIN_RADIUS, COIN_RADIUS, 0.15, 16), new THREE.MeshStandardMaterial({ color: 0xffcc00, emissive: 0x664400, metalness: 0.7, roughness: 0.3 }) ); m.position.set(x, 0.7, z); m.castShadow = true; scene.add(m); state.coins.push({ mesh: m, alive: true, spin: Math.random() }); } } // ──────────────────────────────────────────────────────────────────────────── // NPC builder — Minecraft-style "Steve" with limb pivots // ──────────────────────────────────────────────────────────────────────────── function makeNPC(role, color) { const g = new THREE.Group(); g.userData = { role, speed: NPC_SPEED, vy: 0, target: null, action: 'idle', say: '', lastInferTime: 0, latency: 0, speakUntil: 0, sayBubble: null, walkTime: 0, moving: false, }; const skin = 0xe0bb95; const pants = 0x2563eb; // Head const head = new THREE.Mesh(new THREE.BoxGeometry(0.7, 0.7, 0.7), new THREE.MeshLambertMaterial({ color: skin })); head.position.y = 1.7; head.castShadow = true; g.add(head); // Eyes const eyeMat = new THREE.MeshLambertMaterial({ color: 0x1a1a1a }); for (const sx of [-0.15, 0.15]) { const eye = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.05), eyeMat); eye.position.set(sx, 1.75, 0.36); g.add(eye); } // Mouth const mouth = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.05, 0.05), new THREE.MeshLambertMaterial({ color: 0x6b3f1c })); mouth.position.set(0, 1.55, 0.36); g.add(mouth); // Torso (role-coloured) const torso = new THREE.Mesh(new THREE.BoxGeometry(0.75, 0.95, 0.4), new THREE.MeshLambertMaterial({ color: color })); torso.position.y = 0.95; torso.castShadow = true; g.add(torso); // Arms (pivot at shoulder) const armMat = new THREE.MeshLambertMaterial({ color: skin }); function arm(side) { const piv = new THREE.Group(); piv.position.set(side * 0.5, 1.4, 0); const limb = new THREE.Mesh(new THREE.BoxGeometry(0.25, 0.85, 0.25), armMat); limb.position.y = -0.42; limb.castShadow = true; piv.add(limb); g.add(piv); return piv; } g.userData.larm = arm(-1); g.userData.rarm = arm(1); // Legs (pivot at hip) const legMat = new THREE.MeshLambertMaterial({ color: pants }); function leg(side) { const piv = new THREE.Group(); piv.position.set(side * 0.18, 0.5, 0); const limb = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.85, 0.3), legMat); limb.position.y = -0.42; limb.castShadow = true; piv.add(limb); g.add(piv); return piv; } g.userData.lleg = leg(-1); g.userData.rleg = leg(1); // Role label (sprite) const lblCanvas = document.createElement('canvas'); lblCanvas.width = 256; lblCanvas.height = 64; const lctx = lblCanvas.getContext('2d'); lctx.fillStyle = 'rgba(0,0,0,0.6)'; lctx.fillRect(0, 0, 256, 64); lctx.font = 'bold 28px monospace'; lctx.fillStyle = '#fff'; lctx.textAlign = 'center'; lctx.textBaseline = 'middle'; lctx.fillText(role.toUpperCase(), 128, 32); const lblTex = new THREE.CanvasTexture(lblCanvas); const lbl = new THREE.Sprite(new THREE.SpriteMaterial({ map: lblTex, depthTest: false })); lbl.position.y = 2.4; lbl.scale.set(1.5, 0.4, 1); g.add(lbl); g.userData.label = lbl; return g; } // Spawn NPCs const hostile = makeNPC('hostile', 0xdc2626); hostile.position.set(8, 0, 8); state.npcs.push(hostile); scene.add(hostile); const ally = makeNPC('ally', 0x38bdf8); ally.position.set(-6, 0, -2); state.npcs.push(ally); scene.add(ally); const wanderer = makeNPC('wanderer', 0xfbbf24); wanderer.position.set(-8, 0, 8); state.npcs.push(wanderer); scene.add(wanderer); // ──────────────────────────────────────────────────────────────────────────── // Player // ──────────────────────────────────────────────────────────────────────────── state.player = new THREE.Group(); state.player.position.set(0, 0, -8); scene.add(state.player); const camPivot = new THREE.Group(); camPivot.position.y = 1.7; state.player.add(camPivot); const camera = new THREE.PerspectiveCamera(75, innerWidth / innerHeight, 0.1, 500); camPivot.add(camera); // ──────────────────────────────────────────────────────────────────────────── // Particles for coin pickup // ──────────────────────────────────────────────────────────────────────────── const particles = []; function emitParticles(pos, color) { for (let i = 0; i < 12; i++) { const m = new THREE.Mesh( new THREE.BoxGeometry(0.1, 0.1, 0.1), new THREE.MeshBasicMaterial({ color }) ); m.position.copy(pos); m.userData = { vx: (Math.random() - 0.5) * 4, vy: Math.random() * 4 + 1, vz: (Math.random() - 0.5) * 4, life: 0.7, }; scene.add(m); particles.push(m); } } // ──────────────────────────────────────────────────────────────────────────── // Input // ──────────────────────────────────────────────────────────────────────────── addEventListener('keydown', e => { state.keys[e.code] = true; if (e.code === 'KeyR' && state.running) toggleRecording(); if (e.code === 'KeyV' && state.running) toggleVoice(); if (e.code === 'KeyE' && state.running) tryPlayerPickup(); if (e.code === 'KeyM') { sfx.enabled = !sfx.enabled; const m = document.getElementById('mic-text'); if (m) m.textContent = `sound ${sfx.enabled ? 'ON' : 'OFF'}`; if (sfx.enabled) sfx.blip(660, 0.07); } }); addEventListener('keyup', e => { state.keys[e.code] = false; }); canvas.addEventListener('click', () => { if (state.running && !state.pointerLocked) canvas.requestPointerLock(); }); document.addEventListener('pointerlockchange', () => { state.pointerLocked = document.pointerLockElement === canvas; }); addEventListener('mousemove', e => { if (!state.pointerLocked) return; state.yaw -= e.movementX * 0.0025; state.pitch -= e.movementY * 0.0025; state.pitch = Math.max(-Math.PI / 2 + 0.1, Math.min(Math.PI / 2 - 0.1, state.pitch)); }); addEventListener('resize', () => { renderer.setSize(innerWidth, innerHeight); camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); }); // ──────────────────────────────────────────────────────────────────────────── // AI plumbing // ──────────────────────────────────────────────────────────────────────────── async function captureFrameB64() { // Render the current frame, then copy to a smaller canvas for upload renderer.render(scene, camera); const w = 480, h = 270; const tmp = document.createElement('canvas'); tmp.width = w; tmp.height = h; tmp.getContext('2d').drawImage(canvas, 0, 0, w, h); return tmp.toDataURL('image/jpeg', 0.7).split(',')[1]; } async function callInfer(npc, voiceText = '') { const img = await captureFrameB64(); const t0 = performance.now(); try { const res = await fetch(`${API_URL}/infer`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image_b64: img, audio_text: voiceText, npc_role: npc.userData.role, directive: state.directive, }), }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = await res.json(); const latency = performance.now() - t0; handleInferResult(npc, data, latency); } catch (err) { console.warn(`[${npc.userData.role}] infer failed:`, err.message); npc.userData.lastInferTime = performance.now(); } } function handleInferResult(npc, data, latency) { npc.userData.action = data.action || 'idle'; npc.userData.latency = latency; npc.userData.lastInferTime = performance.now(); npc.userData.lastSceneDesc = data.scene_description || ''; // ── Error surfaced from server (e.g. NIM 429 rate-limit) ── if (data.error) { state.nimError = data.error; state.nimErrorAt = performance.now(); state.errorCount = (state.errorCount || 0) + 1; // Back off the request rate when errors are happening state.errorBackoffUntil = performance.now() + 4000; // Update directive line so the user immediately sees the cause document.getElementById('directive').textContent = `⚠ NIM: ${data.error}`; } else { state.nimError = ''; } if (data.say) { npc.userData.say = data.say; npc.userData.speakUntil = performance.now() + 4000; showSayBubble(npc, data.say); } // Update HUD card — show action + Nemotron's own scene description (proves it's not hardcoded) const card = document.getElementById(`card-${npc.userData.role}`); if (card) { card.querySelector('.action').textContent = data.error ? `⚠ error: ${data.error}` : `${data.action} → ${data.target || '—'} (conf=${(data.confidence||0).toFixed(2)})`; card.querySelector('.say').textContent = data.say ? `"${data.say}"` : (data.scene_description ? `[sees] ${data.scene_description}` : '"…"'); card.querySelector('.lat').textContent = `${Math.round(latency)}ms`; } // Reasoning trace — prefer if present, else scene_description (always Nemotron-generated text) const traceText = data.thinking || data.scene_description || ''; if (traceText) { addThink(npc.userData.role, traceText); } // Latency chart state.latencies.push(latency); if (state.latencies.length > 30) state.latencies.shift(); state.totalCalls++; drawLatencyChart(); // Apply Nano action applyAction(npc, data); } function applyAction(npc, data) { const a = data.action; const role = npc.userData.role; // Each role has its own twist on actions if (a === 'navigate_to_objective' || a === 'pick_up') { npc.userData.target = pickNearestCoin(npc.position); } else if (a === 'follow_threat') { npc.userData.target = state.player.position.clone(); } else if (a === 'evade_threat') { if (role === 'hostile') { // hostile evades the player const away = npc.position.clone().sub(state.player.position).normalize().multiplyScalar(8); npc.userData.target = npc.position.clone().add(away); } else { npc.userData.target = pickNearestCoin(npc.position); } } else if (a === 'wave' || a === 'dance' || a === 'idle' || a === 'stop') { npc.userData.target = null; } // Role bias overrides — keeps NPCs behaving in-character if (role === 'hostile' && state.player) { const dp = npc.position.distanceTo(state.player.position); if (dp < 4 && Math.random() < 0.3) { const away = npc.position.clone().sub(state.player.position).normalize().multiplyScalar(8); npc.userData.target = npc.position.clone().add(away); } } if (role === 'ally' && !npc.userData.target) { if (npc.position.distanceTo(state.player.position) > 5) { npc.userData.target = state.player.position.clone(); } else { npc.userData.target = pickNearestCoin(npc.position); } } if (role === 'wanderer' && !npc.userData.target) { npc.userData.target = pickNearestCoin(npc.position); } } function pickNearestCoin(pos) { let best = null, bd = Infinity; for (const c of state.coins) { if (!c.alive) continue; const d = pos.distanceTo(c.mesh.position); if (d < bd) { bd = d; best = c.mesh.position.clone(); } } return best; } async function callSuper() { try { const summary = `Player score=${state.scores.player}, hostile=${state.scores.hostile}, ally=${state.scores.ally}, wanderer=${state.scores.wanderer}. Coins remaining=${state.coins.filter(c => c.alive).length}. Time left=${Math.round(state.timeLeft)}s.`; const recent = state.npcs.map(n => `${n.userData.role}:${n.userData.action}`); const res = await fetch(`${API_URL}/super`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ scene_summary: summary, mission_context: 'Each NPC competes with others and the player to collect coins in a 60-second round.', recent_actions: recent, }), }); if (!res.ok) return; const data = await res.json(); if (data.directive) { state.directive = data.directive; document.getElementById('directive').textContent = data.directive; } // Show Super 49B chain-of-thought in reasoning panel const superThink = data.thinking || data.reasoning || ''; if (superThink) { addThink('super·49b', superThink); } } catch (err) { /* server might be down — ignore */ } } async function maybeRunDialogue(now) { if (now - state.lastDialogueTime < DIALOGUE_COOLDOWN_MS) return; for (let i = 0; i < state.npcs.length; i++) { for (let j = i + 1; j < state.npcs.length; j++) { if (state.npcs[i].position.distanceTo(state.npcs[j].position) < DIALOGUE_DIST) { state.lastDialogueTime = now; const a = state.npcs[i], b = state.npcs[j]; try { const res = await fetch(`${API_URL}/dialogue`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ npc_a: a.userData.role, npc_b: b.userData.role, scene_summary: state.directive, last_event: `Scores: P=${state.scores.player} H=${state.scores.hostile} A=${state.scores.ally} W=${state.scores.wanderer}`, }), }); if (!res.ok) return; const data = await res.json(); const target = data.speaker === 'b' ? b : a; target.userData.say = data.text; target.userData.speakUntil = performance.now() + 4500; showSayBubble(target, data.text); sfx.dialogue(); } catch {} return; } } } } // ──────────────────────────────────────────────────────────────────────────── // Speech bubbles (sprite text above NPC heads) // ──────────────────────────────────────────────────────────────────────────── function showSayBubble(npc, text) { if (npc.userData.sayBubble) { npc.remove(npc.userData.sayBubble); npc.userData.sayBubble.material.map.dispose(); npc.userData.sayBubble.material.dispose(); } const c = document.createElement('canvas'); c.width = 512; c.height = 80; const ctx = c.getContext('2d'); ctx.fillStyle = 'rgba(0,0,0,0.7)'; ctx.roundRect(0, 0, 512, 80, 12); ctx.fill(); ctx.font = 'bold 22px monospace'; ctx.fillStyle = '#a3e635'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; const t = text.length > 40 ? text.slice(0, 38) + '…' : text; ctx.fillText(t, 256, 40); const tex = new THREE.CanvasTexture(c); const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: false })); sprite.position.y = 3.0; sprite.scale.set(3.5, 0.55, 1); npc.add(sprite); npc.userData.sayBubble = sprite; } // ──────────────────────────────────────────────────────────────────────────── // Voice (Web Speech API — browser-side, no PyAudio needed) // ──────────────────────────────────────────────────────────────────────────── // Format the user can speak: // " " // e.g. "hostile go to blue zone" // "ally come here" // "wanderer dance" // "everyone stop" // No NPC name → defaults to ally (your team helper). // // Commands are PARSED IN-BROWSER and applied INSTANTLY. The parsed command // also gets a 6-second voice-override window during which the AI doesn't // re-target that NPC — so the player's intent isn't immediately overwritten. // ──────────────────────────────────────────────────────────────────────────── function setupVoice() { const SR = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SR) { document.getElementById('mic-text').textContent = 'speech API unsupported — use Chrome/Edge'; return false; } const r = new SR(); r.continuous = true; r.interimResults = true; r.lang = 'en-US'; r.maxAlternatives = 1; r.onresult = e => { let interim = '', final = ''; for (let i = e.resultIndex; i < e.results.length; i++) { const t = e.results[i][0].transcript; if (e.results[i].isFinal) final += t; else interim += t; } const heardEl = document.getElementById('voice-heard'); if (interim && !final) { heardEl.textContent = `"${interim.trim()}…"`; heardEl.style.opacity = '0.55'; } if (final) { const cleaned = final.trim().toLowerCase(); heardEl.textContent = `"${cleaned}"`; heardEl.style.opacity = '1'; state.lastVoiceText = cleaned; handleVoiceCommand(cleaned); } }; r.onerror = ev => { const m = document.getElementById('mic-text'); if (ev.error === 'not-allowed' || ev.error === 'service-not-allowed') { m.textContent = 'mic blocked — allow mic in browser settings'; } else if (ev.error === 'no-speech') { // expected when silent; ignore } else { m.textContent = `mic: ${ev.error}`; } }; r.onend = () => { if (state.voiceActive) { try { r.start(); } catch {} } }; state.recognition = r; return true; } async function requestMicPermission() { // Trigger the browser's explicit mic permission prompt by opening a // throwaway audio stream. SpeechRecognition alone often fails silently // when the page hasn't yet asked for mic access. if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { return { ok: false, reason: 'no-mediadevices' }; } try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); // Immediately stop — we just needed the permission, SpeechRecognition // opens its own audio pipeline. stream.getTracks().forEach(t => t.stop()); return { ok: true }; } catch (err) { return { ok: false, reason: err.name || err.message }; } } async function toggleVoice() { if (!state.recognition && !setupVoice()) return; const m = document.getElementById('mic-text'); if (state.voiceActive) { state.recognition.stop(); state.voiceActive = false; document.getElementById('mic-dot').classList.remove('live'); m.textContent = 'voice OFF (V to enable)'; return; } // Step 1: get mic permission via the standard prompt. m.textContent = 'requesting mic permission…'; const perm = await requestMicPermission(); if (!perm.ok) { if (perm.reason === 'NotAllowedError') { m.textContent = '❌ mic blocked — click 🔒 in URL bar → Microphone → Allow → reload'; } else if (perm.reason === 'NotFoundError') { m.textContent = '❌ no microphone detected on this device'; } else if (perm.reason === 'no-mediadevices') { m.textContent = '❌ getUserMedia unsupported — open page over http://localhost or https'; } else { m.textContent = `❌ mic error: ${perm.reason}`; } return; } // Step 2: start SpeechRecognition (now that the page has mic permission). try { state.recognition.start(); state.voiceActive = true; document.getElementById('mic-dot').classList.add('live'); m.textContent = 'listening… try "hostile go to blue zone" or "ally come here"'; } catch (err) { m.textContent = 'mic error: ' + (err.message || err.name); } } // ── Voice command parser ─────────────────────────────────────────────────── function handleVoiceCommand(text) { // 1. Pick target NPC(s) let targetRole = null; if (/\b(everyone|everybody|all of you|all)\b/.test(text)) targetRole = 'all'; else if (/\bhostile\b/.test(text)) targetRole = 'hostile'; else if (/\bally\b/.test(text)) targetRole = 'ally'; else if (/\b(wanderer|wonderer|wonder|wander)\b/.test(text)) targetRole = 'wanderer'; else targetRole = 'ally'; // default const targets = targetRole === 'all' ? state.npcs : state.npcs.filter(n => n.userData.role === targetRole); if (!targets.length) return; // 2. Pick action + destination let action = null, destination = null, sayLine = null, color = null; if (/\bred\b/.test(text)) { action = 'navigate'; destination = ZONES.red.pos.clone(); sayLine = 'Heading to the red zone!'; color = 'red'; } else if (/\bblue\b/.test(text)) { action = 'navigate'; destination = ZONES.blue.pos.clone(); sayLine = 'Heading to the blue zone!'; color = 'blue'; } else if (/\bgreen\b/.test(text)) { action = 'navigate'; destination = ZONES.green.pos.clone(); sayLine = 'Heading to the green zone!'; color = 'green'; } else if (/\b(come|follow|here)\b/.test(text)) { action = 'follow'; sayLine = 'On my way!'; } else if (/\bdance\b/.test(text)) { action = 'dance'; sayLine = "Let's dance!"; } else if (/\b(stop|wait|halt|freeze|stay)\b/.test(text)) { action = 'stop'; sayLine = 'Standing by.'; } else if (/\b(coin|coins|collect|grab|pick)\b/.test(text)) { action = 'coin'; sayLine = 'Going for the coins!'; } else if (/\b(run|flee|escape|away)\b/.test(text)) { action = 'flee'; sayLine = 'Getting out of here!'; } else { // No match — show what we heard but do nothing document.getElementById('mic-text').textContent = `heard but no command match — try a zone, "follow", "dance", or "stop"`; setTimeout(() => { if (state.voiceActive) document.getElementById('mic-text').textContent = 'listening…'; }, 2500); return; } // 3. Apply the parsed command directly to each target NPC const now = performance.now(); for (const npc of targets) { if (action === 'navigate') { npc.userData.target = destination.clone(); } else if (action === 'follow') { npc.userData.target = state.player.position.clone(); } else if (action === 'coin') { npc.userData.target = pickNearestCoin(npc.position); } else if (action === 'flee') { const away = npc.position.clone() .sub(state.player.position).normalize().multiplyScalar(10); npc.userData.target = npc.position.clone().add(away); } else if (action === 'stop' || action === 'dance') { npc.userData.target = null; } // 6-second voice-override window: AI inference for this NPC is paused npc.userData.voiceOverrideUntil = now + 6000; npc.userData.say = sayLine; npc.userData.speakUntil = now + 4000; showSayBubble(npc, sayLine); // Update bottom HUD card so the user sees it took effect const card = document.getElementById(`card-${npc.userData.role}`); if (card) { card.querySelector('.action').textContent = `voice: ${action}${color ? ' ' + color : ''}`; card.querySelector('.say').textContent = `"${sayLine}"`; } } // 4. Echo back the parsed command above the mic const label = targetRole === 'all' ? 'EVERYONE' : targetRole.toUpperCase(); document.getElementById('mic-text').textContent = `→ ${label}: ${action}${color ? ' ' + color + ' zone' : ''}`; sfx.voiceAck(); setTimeout(() => { if (state.voiceActive) document.getElementById('mic-text').textContent = 'listening…'; }, 2500); } // ──────────────────────────────────────────────────────────────────────────── // Recording (MediaRecorder on the canvas stream) // ──────────────────────────────────────────────────────────────────────────── function toggleRecording() { if (state.recording) { state.recorder.stop(); state.recording = false; document.getElementById('recording-badge').classList.remove('live'); return; } const stream = canvas.captureStream(30); state.recordChunks = []; state.recorder = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp9' }); state.recorder.ondataavailable = e => state.recordChunks.push(e.data); state.recorder.onstop = () => { const blob = new Blob(state.recordChunks, { type: 'video/webm' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `omninpc-${Date.now()}.webm`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); }; state.recorder.start(); state.recording = true; document.getElementById('recording-badge').classList.add('live'); } // ──────────────────────────────────────────────────────────────────────────── // Latency chart // ──────────────────────────────────────────────────────────────────────────── const latCanvas = document.getElementById('lat-canvas'); const latCtx = latCanvas.getContext('2d'); function drawLatencyChart() { const w = latCanvas.width = latCanvas.clientWidth * devicePixelRatio; const h = latCanvas.height = latCanvas.clientHeight * devicePixelRatio; latCtx.clearRect(0, 0, w, h); const lats = state.latencies; if (!lats.length) return; const maxLat = Math.max(2000, ...lats); const bw = w / Math.max(30, lats.length); for (let i = 0; i < lats.length; i++) { const v = lats[i]; const bh = (v / maxLat) * h; const color = v < 1000 ? '#76b900' : v < 2500 ? '#facc15' : '#f87171'; latCtx.fillStyle = color; latCtx.fillRect(i * bw, h - bh, bw - 1, bh); } // Stats const avg = lats.reduce((a,b)=>a+b,0) / lats.length; const sorted = [...lats].sort((a,b)=>a-b); const p95 = sorted[Math.floor(sorted.length * 0.95)] || 0; document.getElementById('lat-avg').textContent = `${Math.round(avg)}ms`; document.getElementById('lat-p95').textContent = `${Math.round(p95)}ms`; document.getElementById('lat-calls').textContent = state.totalCalls; document.getElementById('lat-errors').textContent = state.errorCount || 0; } // ──────────────────────────────────────────────────────────────────────────── // Reasoning panel // ──────────────────────────────────────────────────────────────────────────── function addThink(role, text) { const list = document.getElementById('think-list'); const div = document.createElement('div'); const isSuper = role.includes('super'); div.className = 'think-entry' + (isSuper ? ' super-entry' : ''); div.innerHTML = `${role.toUpperCase()} ${escapeHtml(text.slice(0, 400))}${text.length > 400 ? '…' : ''}`; list.insertBefore(div, list.firstChild); while (list.childNodes.length > 10) list.removeChild(list.lastChild); } function escapeHtml(s) { return s.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } // ──────────────────────────────────────────────────────────────────────────── // Player + NPC update loop // ──────────────────────────────────────────────────────────────────────────── const clock = new THREE.Clock(); function tick() { const dt = Math.min(0.05, clock.getDelta()); if (state.running) { updatePlayer(dt); updateNPCs(dt); updateCoins(dt); updateParticles(dt); updateTimer(dt); schedulePerception(); maybeRunDialogue(performance.now()); } renderer.render(scene, camera); requestAnimationFrame(tick); } function updatePlayer(dt) { // Three.js camera looks toward -Z by default. With player.rotation.y = yaw: // yaw=0 → forward = (0, 0, -1) // yaw=π/2 → forward = (-1, 0, 0) // So forward = (-sin yaw, 0, -cos yaw); right = (cos yaw, 0, -sin yaw). const fwd = new THREE.Vector3(-Math.sin(state.yaw), 0, -Math.cos(state.yaw)); const right = new THREE.Vector3(Math.cos(state.yaw), 0, -Math.sin(state.yaw)); const v = new THREE.Vector3(); if (state.keys.KeyW) v.add(fwd); if (state.keys.KeyS) v.sub(fwd); if (state.keys.KeyA) v.sub(right); if (state.keys.KeyD) v.add(right); if (v.lengthSq() > 0) v.normalize(); const sp = state.keys.ShiftLeft || state.keys.ShiftRight ? PLAYER_SPEED * 1.6 : PLAYER_SPEED; state.player.position.x += v.x * sp * dt; state.player.position.z += v.z * sp * dt; // Jump if (state.keys.Space && state.onGround) { state.velocityY = 6.5; state.onGround = false; } state.velocityY -= 18 * dt; state.player.position.y += state.velocityY * dt; if (state.player.position.y <= 0) { state.player.position.y = 0; state.velocityY = 0; state.onGround = true; } // Clamp to arena state.player.position.x = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, state.player.position.x)); state.player.position.z = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, state.player.position.z)); // Camera state.player.rotation.y = state.yaw; camPivot.rotation.x = state.pitch; // Auto-pickup on touch for (const c of state.coins) { if (!c.alive) continue; if (state.player.position.distanceTo(c.mesh.position) < PICKUP_DIST) { c.alive = false; scene.remove(c.mesh); state.scores.player++; document.getElementById('score-player').textContent = state.scores.player; emitParticles(c.mesh.position, 0xa3e635); sfx.coinPlayer(); } } } function tryPlayerPickup() { for (const c of state.coins) { if (!c.alive) continue; if (state.player.position.distanceTo(c.mesh.position) < PICKUP_DIST + 0.3) { c.alive = false; scene.remove(c.mesh); state.scores.player++; document.getElementById('score-player').textContent = state.scores.player; emitParticles(c.mesh.position, 0xa3e635); sfx.coinPlayer(); return; } } } function updateNPCs(dt) { const now = performance.now(); for (const npc of state.npcs) { const u = npc.userData; let moved = false; // ── Per-frame proximity reaction (no AI call needed) ── // Runs every frame so the NPC reacts the instant the player is in range, // not on the next inference (~2s away). The Nemotron action is still // applied separately — this is just reflex. const distP = state.player ? npc.position.distanceTo(state.player.position) : 999; if (u.role === 'hostile' && distP < 4 && (u.voiceOverrideUntil || 0) < now) { // Hostile sprints AWAY from player const away = npc.position.clone().sub(state.player.position).setY(0).normalize().multiplyScalar(8); u.target = npc.position.clone().add(away); u.speed = NPC_SPEED * 1.6; // sprint if (now > (u.proxSpokeUntil || 0) + 3500) { const lines = ['Stay back!', 'Get away from me!', "I'm out!"]; const line = lines[Math.floor(Math.random() * lines.length)]; u.say = line; u.speakUntil = now + 2500; showSayBubble(npc, line); u.proxSpokeUntil = now; sfx.evade(); } } else if (u.role === 'ally' && distP > 6 && (u.voiceOverrideUntil || 0) < now && !u.target) { // Ally drifts toward you when too far u.target = state.player.position.clone(); u.speed = NPC_SPEED; } else { u.speed = NPC_SPEED; } if (u.target) { const dx = u.target.x - npc.position.x; const dz = u.target.z - npc.position.z; const d = Math.sqrt(dx*dx + dz*dz); if (d > 0.3) { const nx = dx / d, nz = dz / d; npc.position.x += nx * u.speed * dt; npc.position.z += nz * u.speed * dt; npc.rotation.y = Math.atan2(nx, nz); moved = true; } else { u.target = null; } } // Clamp npc.position.x = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, npc.position.x)); npc.position.z = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, npc.position.z)); // NPC coin pickup for (const c of state.coins) { if (!c.alive) continue; if (npc.position.distanceTo(c.mesh.position) < PICKUP_DIST) { c.alive = false; scene.remove(c.mesh); state.scores[u.role]++; document.getElementById(`score-${u.role}`).textContent = state.scores[u.role]; emitParticles(c.mesh.position, 0xfff088); sfx.coinNPC(); } } // Limb animation if (moved) { u.walkTime += dt * 8; const swing = Math.sin(u.walkTime) * 0.5; u.larm.rotation.x = swing; u.rarm.rotation.x = -swing; u.lleg.rotation.x = -swing; u.rleg.rotation.x = swing; } else { u.larm.rotation.x *= 0.9; u.rarm.rotation.x *= 0.9; u.lleg.rotation.x *= 0.9; u.rleg.rotation.x *= 0.9; } // Speech bubble fade if (u.sayBubble && performance.now() > u.speakUntil) { npc.remove(u.sayBubble); u.sayBubble.material.map.dispose(); u.sayBubble.material.dispose(); u.sayBubble = null; } } } function updateCoins(dt) { for (const c of state.coins) { if (!c.alive) continue; c.spin += dt * 3; c.mesh.rotation.y = c.spin; c.mesh.position.y = 0.7 + Math.sin(c.spin) * 0.1; } } function updateParticles(dt) { for (let i = particles.length - 1; i >= 0; i--) { const p = particles[i]; p.position.x += p.userData.vx * dt; p.position.y += p.userData.vy * dt; p.position.z += p.userData.vz * dt; p.userData.vy -= 9 * dt; p.userData.life -= dt; if (p.userData.life <= 0) { scene.remove(p); p.geometry.dispose(); p.material.dispose(); particles.splice(i, 1); } } } function updateTimer(dt) { const before = state.timeLeft; state.timeLeft -= dt; // Per-second countdown beep in the last 5 seconds const flBefore = Math.floor(before); const flNow = Math.floor(state.timeLeft); if (flNow !== flBefore && state.timeLeft > 0 && state.timeLeft < 5.5) { sfx.countdown(); } if (state.timeLeft <= 0) endGame(); const t = Math.max(0, state.timeLeft); const el = document.getElementById('timer'); el.textContent = t.toFixed(1); el.classList.toggle('urgent', t < 10); } function schedulePerception() { const now = performance.now(); if (state.npcs.length === 0) return; // Back off when NIM errors are happening (rate limit, 5xx). Once the // window passes, the next call retries. This keeps the UI responsive. if ((state.errorBackoffUntil || 0) > now) return; const slotInterval = PERCEPTION_INTERVAL_MS; for (let attempt = 0; attempt < state.npcs.length; attempt++) { const npc = state.npcs[state.rrIndex % state.npcs.length]; state.rrIndex = (state.rrIndex + 1) % state.npcs.length; if ((npc.userData.voiceOverrideUntil || 0) > now) continue; if (now - (npc.userData.lastInferTime || 0) > slotInterval) { npc.userData.lastInferTime = now; callInfer(npc, ''); break; } } if (now - state.lastSuperTime > SUPER_INTERVAL_MS) { state.lastSuperTime = now; callSuper(); } } // ──────────────────────────────────────────────────────────────────────────── // Game flow // ──────────────────────────────────────────────────────────────────────────── function startGame() { // Web Audio requires a user-gesture before playing — kick it now. const ctx = sfx.ensure(); if (ctx && ctx.state === 'suspended') ctx.resume(); API_URL = document.getElementById('api-input').value.trim() || window.location.origin; // probe health to give early feedback fetch(`${API_URL}/health`).then(r => r.json()).then(h => { if (!h.api_key_set) { document.getElementById('directive').textContent = '⚠ API key not set on server — set NVIDIA_NIM_API_KEY before /infer works.'; } else { document.getElementById('directive').textContent = `connected · Nano=${h.nano_model.split('/').pop()}`; } }).catch(() => { document.getElementById('directive').textContent = `❌ cannot reach ${API_URL} — start api_server.py first.`; }); document.getElementById('start-screen').style.display = 'none'; state.running = true; state.startTime = performance.now(); state.timeLeft = ROUND_SECONDS; state.scores = { player: 0, hostile: 0, ally: 0, wanderer: 0 }; for (const k of ['player','hostile','ally','wanderer']) { document.getElementById(`score-${k}`).textContent = 0; } spawnCoins(); canvas.requestPointerLock(); state.lastSuperTime = performance.now() - SUPER_INTERVAL_MS + 2000; // first super in ~2s } function endGame() { state.running = false; if (state.recording) toggleRecording(); document.exitPointerLock(); const winner = Object.entries(state.scores).sort((a,b)=>b[1]-a[1])[0]; if (winner[0] === 'player') sfx.win(); else sfx.loss(); document.getElementById('end-title').textContent = winner[0] === 'player' ? 'YOU WIN!' : `${winner[0].toUpperCase()} WINS`; document.getElementById('end-stats').innerHTML = `
YOU: ${state.scores.player} coins
ALLY: ${state.scores.ally} coins
HOSTILE: ${state.scores.hostile} coins
WANDERER: ${state.scores.wanderer} coins
${state.totalCalls} Nano inference calls · avg ${Math.round(state.latencies.reduce((a,b)=>a+b,0)/Math.max(1,state.latencies.length))}ms
`; document.getElementById('end-screen').classList.add('show'); } document.getElementById('start-btn').onclick = startGame; document.getElementById('end-restart').onclick = () => { document.getElementById('end-screen').classList.remove('show'); document.getElementById('start-screen').style.display = 'flex'; // reset NPC positions state.npcs[0].position.set(8, 0, 8); state.npcs[1].position.set(-6, 0, -2); state.npcs[2].position.set(-8, 0, 8); state.player.position.set(0, 0, -8); state.yaw = 0; state.pitch = 0; }; tick();