/** * Sistema único de animación del kit: viento (balanceo), flotación, tiempo de shaders, * parallax de fondos y materiales que reaccionan a la fase del día. Se limpia al cambiar de zona. */ import * as THREE from 'three'; import type { Game } from '../../core/game'; import type { DayPhase } from '../../core/types'; interface Sway { o: THREE.Object3D; amp: number; speed: number; ph: number; base: number } interface Bob { o: THREE.Object3D; amp: number; speed: number; ph: number; base: number; rot: number } export interface ParallaxLayer { group: THREE.Object3D; /** Escala (distancia relativa) del grupo. */ k: number; /** Velocidad aparente horizontal/vertical respecto al plano de juego (0 = pegado a pantalla). */ s: number; sy: number; /** Altura del horizonte en coordenadas de juego. */ h0: number; /** Recolorea según la fase y el color del cielo. */ retint?(night: number, sky: THREE.Color, fog: THREE.Color): void; /** Ancla vertical en bloque (ver frame): Y y cy del momento del anclaje. */ anchorY?: number; anchorCy?: number; /** cy del cuadro anterior (para detectar teletransportes). */ prevCy?: number; } /** * Hundimiento vertical del fondo EN PANTALLA por unidad que sube la cámara * (−0,16 = el de la capa media actual). Todas las capas comparten este valor, * así el skyline se mueve como una unidad en pantalla y la oclusión entre * capas no cambia nunca. La velocidad de grupo (R = 1 + S·k) compensa la * perspectiva: cada capa está a una profundidad k distinta, así que una R * común NO basta (las posiciones en pantalla seguirían separándose a ritmos * distintos y los bordes superiores barrerían las ventanas lejanas). */ const SCREEN_SINK = -0.16; export class KitAnim { /** Uniform de tiempo compartido por todos los shaders del kit. */ readonly time = { value: 0 }; private sways: Sway[] = []; private bobs: Bob[] = []; private layers: ParallaxLayer[] = []; private tickers: Array<(t: number, dt: number) => void> = []; /** Tickers globales (materiales compartidos entre zonas); no se limpian. */ private globals: Array<(t: number, phase: DayPhase) => void> = []; private envKey = ''; phase: DayPhase = 'day'; /** 0 día … 1 noche, suavizado. */ night = -1; reset(): void { this.sways.length = 0; this.bobs.length = 0; this.layers.length = 0; this.tickers.length = 0; this.envKey = ''; this.night = -1; } sway(o: THREE.Object3D, amp = 0.06, speed = 1.6): void { this.sways.push({ o, amp, speed, ph: o.position.x * 0.7 + o.position.z, base: o.rotation.z }); } bob(o: THREE.Object3D, amp = 0.05, speed = 1.2, rot = 0): void { this.bobs.push({ o, amp, speed, ph: o.position.x * 0.37, base: o.position.y, rot }); } layer(l: ParallaxLayer): void { this.layers.push(l); this.envKey = ''; } tick(fn: (t: number, dt: number) => void): void { this.tickers.push(fn); } global(fn: (t: number, phase: DayPhase) => void): void { this.globals.push(fn); } frame(game: Game, dt: number): void { const t = (this.time.value += dt); const env = game.gfx.env; this.phase = env?.phase ?? 'day'; const nt = this.phase === 'night' ? 1 : this.phase === 'dusk' ? 0.5 : 0; this.night = this.night < 0 ? nt : this.night + (nt - this.night) * Math.min(1, dt * 1.5); for (const s of this.sways) { s.o.rotation.z = s.base + Math.sin(t * s.speed + s.ph) * s.amp + Math.sin(t * s.speed * 2.3 + s.ph) * s.amp * 0.3; } for (const b of this.bobs) { b.o.position.y = b.base + Math.sin(t * b.speed + b.ph) * b.amp; if (b.rot) b.o.rotation.z = Math.sin(t * b.speed * 0.7 + b.ph) * b.rot; } for (const fn of this.tickers) fn(t, dt); for (const fn of this.globals) fn(t, this.phase); if (this.layers.length) { const cam = game.gfx.cam; const cx = cam.x; const cy = cam.y; for (const l of this.layers) { const tx = cx - l.k * l.s * cx; // Suavizado horizontal: a 30fps con hitches la cámara salta y las // capas teleportaban las ventanas del fondo (el ojo lo lee como // parpadeo). La capa recorre la mitad de la distancia a su objetivo // en cada cuadro: un salto se reparte en 3-4 cuadros y el lag en // régimen es ~1 cuadro de movimiento (imperceptible). Un salto mayor // de 1 u es un teletransporte: ahí se coloca directo. const dx = tx - l.group.position.x; if (Math.abs(dx) > 1) { l.group.position.x = tx; } else { l.group.position.x += dx * 0.5; } // Vertical bloqueada en pantalla: todas las capas se hunden en pantalla // a la misma velocidad (SCREEN_SINK), así el skyline se mueve como una // unidad EN PANTALLA y la oclusión entre capas no cambia nunca. Antes // cada capa seguía la Y de la cámara a su propio ritmo (k·sy distinto), // así que al subir/bajar por plataformas los bordes superiores de los // edificios cercanos barrían las ventanas lejanas y filas enteras se // encendían/apagaban en un solo cuadro: el parpadeo que solo se ve en // lo aéreo (en suelo firme la cámara casi no se mueve en Y y no pasa). // La velocidad de grupo R = 1 + S·k compensa la perspectiva (cada capa // está a una profundidad k distinta). El primer cuadro usa la fórmula // original (el encuadre diseñado) y la ancla; un salto de cámara >1 u // en un cuadro es un teletransporte: se re-ancla al encuadre diseñado // en la nueva altura. let ay = l.anchorY; let acy = l.anchorCy; if (ay === undefined || acy === undefined || Math.abs(cy - (l.prevCy ?? cy)) > 1) { ay = cy + l.k * l.sy * (l.h0 - cy); acy = cy; l.anchorY = ay; l.anchorCy = acy; } l.group.position.y = ay + (1 + SCREEN_SINK * l.k) * (cy - acy); l.prevCy = cy; } const key = `${Math.round(this.night * 40)}:${env?.skyBottom}:${env?.fogColor}`; if (key !== this.envKey) { this.envKey = key; const sky = new THREE.Color(env?.skyBottom ?? 0xbfe6ff); const fog = new THREE.Color(env?.fogColor ?? env?.skyBottom ?? 0xbfe6ff); for (const l of this.layers) l.retint?.(this.night, sky, fog); } } } } export const anim = new KitAnim();