import * as THREE from 'three';
import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';
import { buildWorld } from './world.js';
import { buildWall } from './wall.js';
import { createFx } from './fx.js';
import { createHud } from './hud.js';
import { createAudio } from './audio.js';
import { Game } from './game.js';
import { connectServer } from './net.js';
const DESIGN_W = 1080;
const DESIGN_H = 1920;
const params = new URLSearchParams(location.search);
async function loadRules() {
try {
const r = await fetch('/api/rules');
if (r.ok) return await r.json();
} catch { /* sunucu yoksa varsayılanlar */ }
return {};
}
const rules = await loadRules();
// ---------- Sahne ----------
const stage = document.getElementById('stage');
const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: params.has('shot') });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
stage.appendChild(renderer.domElement);
const labels = new CSS2DRenderer();
labels.domElement.className = 'labels';
stage.appendChild(labels.domElement);
const scene = new THREE.Scene();
// ?cam=yükseklik,uzaklık,bakılanY,bakılanZ,fov
const [camY, camZ, lookY, lookZ, fov] = (params.get('cam') || '9,17,2.5,-6,55').split(',').map(Number);
const camera = new THREE.PerspectiveCamera(fov, DESIGN_W / DESIGN_H, 0.5, 400);
const camBase = new THREE.Vector3(0, camY, camZ);
const look = new THREE.Vector3(0, lookY, lookZ);
const audio = createAudio({ volume: rules.music?.volume ?? 0.6, bpm: rules.music?.bpm ?? 100, youtube: rules.youtube });
const fx = createFx(scene, audio.fx);
const world = buildWorld(scene);
const wall = buildWall(scene, { fx, onFall: () => {} });
const hudEl = document.getElementById('hud');
const hud = createHud(hudEl, rules.texts);
audio.onTrack((n) => hud.setSong(n));
const game = new Game({ scene, rules, audio, hud, world, wall, fx });
// dünya konumu -> HUD (1080x1920) pikseli
const pv = new THREE.Vector3();
hud.project = (pos) => {
pv.copy(pos).project(camera);
if (pv.z > 1) return null;
return { x: (pv.x * 0.5 + 0.5) * DESIGN_W, y: (-pv.y * 0.5 + 0.5) * DESIGN_H };
};
function resize() {
const s = Math.min(window.innerWidth / DESIGN_W, window.innerHeight / DESIGN_H);
const w = Math.round(DESIGN_W * s);
const h = Math.round(DESIGN_H * s);
stage.style.width = w + 'px';
stage.style.height = h + 'px';
stage.style.setProperty('--s', s);
hudEl.style.transform = `scale(${s})`;
renderer.setSize(w, h);
labels.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
window.addEventListener('resize', resize);
resize();
// ---------- Ses ----------
const inObs = !!window.obsstudio || params.has('obs');
const soundBtn = document.getElementById('sound');
try { if (navigator.audioSession) navigator.audioSession.type = 'playback'; } catch { /* yok */ }
function refreshSoundBtn() {
soundBtn.hidden = inObs || audio.playing || !audio.needsGesture;
}
async function startAudio() {
await audio.start();
refreshSoundBtn();
}
startAudio();
setInterval(() => {
refreshSoundBtn();
if (audio.needsGesture) audio.start().catch(() => {});
}, 1000);
soundBtn.addEventListener('click', startAudio);
let triedFs = false;
const kick = () => {
if (!triedFs && !inObs && !params.has('nofs') && /Android/i.test(navigator.userAgent)) {
triedFs = true;
const el = document.documentElement;
try { (el.requestFullscreen || el.webkitRequestFullscreen)?.call(el, { navigationUI: 'hide' })?.catch?.(() => {}); } catch { /* yok */ }
}
if (audio.needsGesture) startAudio();
};
window.addEventListener('pointerdown', kick);
window.addEventListener('touchstart', kick, { passive: true });
window.addEventListener('keydown', kick);
document.addEventListener('visibilitychange', () => { if (!document.hidden) kick(); });
// ---------- Sunucu ----------
const netDot = document.getElementById('net');
const net = connectServer((msg) => {
if (msg.kind === 'event') game.handle(msg.event);
else if (msg.kind === 'reset') game.reset();
else if (msg.kind === 'restore') game.restore(msg.state);
else if (msg.kind === 'youtube') audio.setYoutube(msg.url);
else if (msg.kind === 'music-next') audio.next();
else if (msg.kind === 'win') game.hit(null, 1e9, wall.targetPoint(), true);
else if (msg.kind === 'reload') location.reload();
}, (ok) => { netDot.className = ok ? 'ok' : 'bad'; });
setInterval(() => {
if (params.has('demo')) return;
net.send({ kind: 'snapshot', state: game.snapshot() });
}, 3000);
window.addEventListener('pagehide', () => net.send({ kind: 'snapshot', state: game.snapshot() }));
// ---------- Demo (?demo=30): sunucusuz önizleme ----------
if (params.has('demo')) {
const NAMES = ['aysu', 'mert', 'zeynep', 'emre', 'elif', 'burak', 'selin', 'can', 'deniz', 'ece', 'kaan', 'irem', 'onur', 'melis', 'umut'];
const CMD = ['top', 'hücum', 'ok', 'selam', 'ileri', 'gemi'];
const user = (i) => { const id = NAMES[i % NAMES.length] + (i >= NAMES.length ? i : ''); return { id, name: id }; };
const n = Number(params.get('demo')) || 30;
for (let i = 0; i < n; i++) game.handle({ type: 'join', user: user(i) });
setInterval(() => {
const u = user(Math.floor(Math.random() * n));
if (Math.random() < 0.3) game.handle({ type: 'like', user: u, count: 10 });
else game.handle({ type: 'chat', user: u, text: CMD[Math.floor(Math.random() * CMD.length)] });
}, 800);
}
// ---------- Döngü ----------
const clock = new THREE.Clock();
let t = 0;
function step(dt) {
t += dt;
const beat = audio.update(dt);
game.update(dt, beat);
world.update(dt, t);
wall.update(dt, t, beat);
fx.update(dt);
}
function frame() {
step(Math.min(clock.getDelta(), 0.05));
const sh = fx.shakeAmount;
camera.position.copy(camBase);
if (sh > 0) camera.position.add(new THREE.Vector3((Math.random() - 0.5) * sh, (Math.random() - 0.5) * sh, 0));
camera.lookAt(look);
renderer.render(scene, camera);
labels.render(scene, camera);
requestAnimationFrame(frame);
}
camera.position.copy(camBase);
camera.lookAt(look);
if (params.has('warp')) {
const secs = Number(params.get('warp')) || 5;
for (let i = 0; i < secs * 30; i++) step(1 / 30);
}
frame();
window.__game = game;
Lisans bilgisi projenin LICENSE dosyasında.