import * as THREE from 'three';
import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { buildVenue } from './scene/venue.js';
import { danceMode } from './scene/avatar.js';
import { costumeOn } from './scene/costume.js';
import { buildTables } from './scene/tables.js';
import { createConfetti } from './fx/confetti.js';
import { createHud } from './ui/hud.js';
import { createAudio } from './audio.js';
import { Game } from './game/rules.js';
import { connectServer } from './net.js';
import { randomDemoEvent } from './demo.js';
const DESIGN_W = 1080;
const DESIGN_H = 1920;
async function loadRules() {
try {
const r = await fetch('/api/rules');
if (r.ok) return await r.json();
} catch { /* sunucu yoksa varsayılanlar */ }
return {};
}
const params = new URLSearchParams(location.search);
const rules = await loadRules();
// ---------- Sahne ----------
const stage = document.getElementById('stage');
// Hafif mod: telefonda oyun + TikTok yayını aynı anda çalışınca telefon ısınıp donmasın.
// Telefonda otomatik açılır. ?hq ile kapatılır, ?lite ile bilgisayarda da açılır.
const LITE = params.has('lite') || (/Android|iPhone|iPad|Mobile/i.test(navigator.userAgent) && !params.has('hq'));
const renderer = new THREE.WebGLRenderer({ antialias: !LITE, preserveDrawingBuffer: params.has('shot'), powerPreference: LITE ? 'low-power' : 'high-performance' });
renderer.setPixelRatio(LITE ? Math.min(window.devicePixelRatio, 1.25) : Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
if (LITE) renderer.shadowMap.autoUpdate = false; // gölgeler her karede değil, aralıklı hesaplanır
stage.appendChild(renderer.domElement);
const labels = new CSS2DRenderer();
labels.domElement.className = 'labels';
stage.appendChild(labels.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0208);
scene.fog = new THREE.FogExp2(0x12040c, 0.016); // pavyon dumanı
// parlak yüzeyler (zemin, cam, pul) ortamı yansıtsın
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
scene.environmentIntensity = 0.35;
// Kamera ayarı: ?cam=yükseklik,uzaklık,bakılanZ,fov ile denenebilir
const [camY, camZ, lookZ, fov] = (params.get('cam') || '19,28.5,-2.5,46').split(',').map(Number);
const camera = new THREE.PerspectiveCamera(fov, DESIGN_W / DESIGN_H, 0.5, 200);
camera.position.set(0, camY, camZ);
camera.lookAt(0, 0, lookZ);
// Panelden kamera: genel görünüm / sahneye zoom / piste zoom (yumuşak geçiş)
const CAM_VIEWS = {
genel: { pos: new THREE.Vector3(0, camY, camZ), look: new THREE.Vector3(0, 0, lookZ) },
sahne: { pos: new THREE.Vector3(0.4, 3.4, -6.2), look: new THREE.Vector3(0.4, 1.6, -15.2) },
pist: { pos: new THREE.Vector3(0, 10.5, 2.5), look: new THREE.Vector3(0, 0, -9.5) },
};
const camNow = { pos: CAM_VIEWS.genel.pos.clone(), look: CAM_VIEWS.genel.look.clone() };
let camView = params.get('view') in CAM_VIEWS ? params.get('view') : 'genel';
if (params.has('view')) { camNow.pos.copy(CAM_VIEWS[camView].pos); camNow.look.copy(CAM_VIEWS[camView].look); }
function updateCamera(dt) {
const v = CAM_VIEWS[camView];
const k = 1 - Math.exp(-dt * 2.2);
camNow.pos.lerp(v.pos, k);
camNow.look.lerp(v.look, k);
camera.position.copy(camNow.pos);
camera.lookAt(camNow.look);
}
const venue = buildVenue(scene);
const layout = buildTables(scene);
// gölgeler: mekandaki her şey gölge alır/verir
scene.traverse((o) => {
if (!o.isMesh || o.isInstancedMesh || o.material?.transparent) return;
o.castShadow = o.geometry.type !== 'PlaneGeometry';
o.receiveShadow = true;
});
// neonlar, mumlar ve ışıklar parlasın
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
const bloom = new UnrealBloomPass(new THREE.Vector2(DESIGN_W, DESIGN_H), 0.6, 0.5, 0.88);
composer.addPass(bloom);
composer.addPass(new OutputPass());
const confetti = createConfetti(scene);
const hudEl = document.getElementById('hud');
const hud = createHud(hudEl, rules.texts);
const audio = createAudio({
volume: rules.music?.volume ?? 0.6,
crossfade: rules.music?.crossfadeSeconds ?? 3,
youtube: rules.youtube,
});
audio.onTrack((name) => hud.setSong(name));
const game = new Game({ scene, layout, rules, audio, hud, venue, confetti });
// ---------- Ekran boyutu: 9:16 alanı pencereye sığdır ----------
function resize() {
const ww = window.innerWidth;
const wh = window.innerHeight;
const s = Math.min(ww / DESIGN_W, wh / 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);
composer.setSize(w, h);
labels.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
window.addEventListener('resize', resize);
resize();
// ---------- Ses: tarayıcılar sesi ilk tıklamaya kadar engeller (OBS engellemez) ----------
// OBS içinde (window.obsstudio) ses kendiliğinden başlar; buton yayına asla çıkmasın.
const inObs = !!window.obsstudio || params.has('obs');
const soundBtn = document.getElementById('sound');
// iPhone: sessiz moddayken de çalsın (Safari 17+)
try { if (navigator.audioSession) navigator.audioSession.type = 'playback'; } catch { /* desteklenmiyor */ }
// Buton sadece ilk açılışta (ses hiç başlamadıysa) görünür; sonra ses kesilirse sessizce yeniden denenir.
let everStarted = false;
function refreshSoundBtn() {
if (audio.playing) everStarted = true;
// YouTube telefonda her kesintide bir dokunuş isteyebilir: çalmıyorsa buton görünsün
const hideAfterStart = everStarted && audio.mode !== 'youtube';
soundBtn.hidden = inObs || audio.playing || hideAfterStart || !audio.needsGesture;
}
async function startAudio() {
await audio.start();
refreshSoundBtn();
}
await audio.load();
startAudio();
setInterval(() => {
refreshSoundBtn();
// uygulama değişince (ör. TikTok'a geçip dönünce) askıya alınan sesi geri aç
if (everStarted && audio.needsGesture) audio.start().catch(() => {});
}, 1000);
soundBtn.addEventListener('click', startAudio);
// Android: ilk dokunuşta tam ekran (durum çubuğu da gizlenir). iPhone bunu desteklemez.
let triedFullscreen = false;
function goFullscreen() {
if (triedFullscreen || inObs || params.has('nofs')) return;
triedFullscreen = true;
const el = document.documentElement;
const req = el.requestFullscreen || el.webkitRequestFullscreen;
if (req && /Android/i.test(navigator.userAgent)) {
try { req.call(el, { navigationUI: 'hide' })?.catch?.(() => {}); } catch { /* desteklenmiyor */ }
}
}
const kick = () => { goFullscreen(); 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(); });
window.addEventListener('pageshow', kick);
// test: ?mode=halay ile dans modu sabitlenir (panel değiştiremez)
if (params.has('mode')) danceMode.value = params.get('mode');
// ---------- Müzik: dans moduna özel YouTube linki (halay / horon / oyun havası) ----------
let mainYt = rules.youtube?.url || '';
let modeYt = rules.youtube?.modes || {};
let playingYt = mainYt;
function syncMusic() {
const want = modeYt[danceMode.value] || mainYt;
if (want === playingYt) return;
playingYt = want;
audio.setYoutube(want);
}
// ---------- 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') mainYt = msg.url || '';
else if (msg.kind === 'music-next') audio.next();
if (msg.kind === 'costume' || msg.kind === 'status') {
const on = msg.kind === 'costume' ? msg.on : msg.costume;
if (typeof on === 'boolean' && on !== costumeOn.value) {
costumeOn.value = on;
if (msg.kind === 'costume') hud.banner(on ? '👗 Pistte kostüm partisi!' : '👕 Kostümler çıkarıldı', on ? 'party' : 'song');
}
}
if ((msg.kind === 'danceMode' || msg.kind === 'status') && !params.has('mode')) {
const mode = msg.kind === 'danceMode' ? msg.mode : msg.danceMode;
if (mode && mode !== danceMode.value) {
danceMode.value = mode;
const BANNERS = {
oyun: ['🎶 OYUN HAVASI! Herkes piste! 💃', 'party'],
halay: ['💃 HALAY BAŞLADI! El ele, omuz omuza! 🔴', 'party'],
horon: ['🌊 HORON! Karadeniz geldi! 🌊', 'party'],
normal: ['🪩 Normal dans modu', 'song'],
};
if (msg.kind === 'danceMode') hud.banner(...(BANNERS[mode] || BANNERS.normal));
}
}
else if (msg.kind === 'reload') location.reload();
if (msg.kind === 'status') {
mainYt = msg.youtubeUrl || '';
modeYt = msg.youtubeModes || {};
}
if (msg.kind === 'status' || msg.kind === 'youtube' || msg.kind === 'danceMode') syncMusic();
if (msg.kind === 'stage') {
if (msg.op === 'next') game.stageNext();
else if (msg.op === 'hold') game.setStageHold(msg.on);
else if (msg.op === 'up' && msg.user) game.stageUp(msg.user);
}
if (msg.kind === 'status' && typeof msg.stageHold === 'boolean') game.setStageHold(msg.stageHold);
if ((msg.kind === 'camera' || msg.kind === 'status') && !params.has('view')) {
const view = msg.kind === 'camera' ? msg.view : msg.camera;
if (view in CAM_VIEWS) camView = view;
}
}, (ok) => { netDot.className = ok ? 'ok' : 'bad'; });
// Sahne durumu panelde görünsün (şarkıcı, kalan süre, sıra)
setInterval(() => {
if (params.has('demo')) return;
net.send({ kind: 'stage-info', info: game.stageInfo() });
}, 1000);
// Mekanın durumunu birkaç saniyede bir sunucuya kaydet (yenileyince herkes yerinde kalsın)
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=40): sunucusuz hızlı önizleme ----------
if (params.has('demo')) {
const n = Number(params.get('demo')) || 30;
for (let i = 0; i < n; i++) game.handle(randomDemoEvent(i));
setInterval(() => game.handle(randomDemoEvent()), 700);
}
// ---------- Döngü ----------
const clock = new THREE.Clock();
let t = 0;
const FRAME_MIN = LITE ? 1 / 30 - 0.002 : 0; // hafif modda en fazla 30 kare/sn
let acc = 0;
let shadowTick = 0;
function frame() {
requestAnimationFrame(frame);
acc += clock.getDelta();
if (acc < FRAME_MIN) return;
const dt = Math.min(acc, 0.05);
acc = 0;
t += dt;
if (LITE && shadowTick++ % 3 === 0) renderer.shadowMap.needsUpdate = true;
const beat = audio.update(dt);
game.update(dt, beat);
updateCamera(dt);
venue.update(dt, beat, t);
confetti.update(dt, t);
composer.render();
labels.render(scene, camera);
}
frame();
// Hızlı ileri sarma (ekran görüntüsü testleri için): ?warp=5 -> 5 sn simülasyon
if (params.has('warp')) {
const secs = Number(params.get('warp')) || 5;
for (let i = 0; i < secs * 30; i++) {
const beat = audio.update(1 / 30);
game.update(1 / 30, beat);
venue.update(1 / 30, beat, (t += 1 / 30));
confetti.update(1 / 30, t);
}
}
window.__game = game;
Lisans bilgisi projenin LICENSE dosyasında.