import * as THREE from 'three'; import { tallyCommit } from './tally'; import { EventBus } from './events'; import { Input } from './input'; import { GameState } from './state'; import { Entity } from './entity'; import { Physics, overlaps } from '../physics/world'; import { nullAudio, nullQuests, nullUi, nullVfx } from './nullServices'; import type { AABB, AudioService, EntityFactory, GameEvents, HeroApi, Hit, Props, QuestService, RenderService, System, Team, UiService, VfxService, ZoneContext, ZoneDef, } from './types'; /** Paso fijo de simulación. */ export const STEP = 1 / 60; export type HeroEntity = Entity & HeroApi; export type ZoneContextFactory = (game: Game, def: ZoneDef, group: THREE.Group) => ZoneContext & { finish?(): void }; /** * Núcleo del juego: bucle de paso fijo, entidades, zonas y servicios. * Los módulos se conectan con `install(game)` (ver main.ts) y sustituyen * los servicios nulos (ui, audio, vfx, quests) por los reales. */ export class Game { readonly events = new EventBus(); readonly input = new Input(); readonly physics = new Physics(); readonly state = new GameState(this.events); ui: UiService = nullUi; audio: AudioService = nullAudio; vfx: VfxService = nullVfx; quests: QuestService = nullQuests; hero: HeroEntity | null = null; readonly entities: Entity[] = []; /** Raíz de las vistas de entidades. */ readonly entityRoot = new THREE.Group(); /** Segundos de simulación transcurridos (no avanza en pausa). */ time = 0; paused = false; loading = false; zone: ZoneDef | null = null; zoneGroup: THREE.Group | null = null; /** La instala src/world. */ zoneContextFactory: ZoneContextFactory | null = null; private factories = new Map(); private zones = new Map(); private systems: System[] = []; private timers: Array<{ t: number; fn: () => void }> = []; private acc = 0; private last = 0; private hitstopLeft = 0; private running = false; constructor(readonly gfx: RenderService) { this.entityRoot.name = 'entities'; gfx.scene.add(this.entityRoot); } // ───────────── Registro ───────────── /** Registra un tipo de entidad instanciable con spawn(). */ register(type: string, factory: EntityFactory): void { this.factories.set(type, factory); } hasType(type: string): boolean { return this.factories.has(type); } registerZone(def: ZoneDef): void { this.zones.set(def.id, def); } hasZone(id: string): boolean { return this.zones.has(id); } getZone(id: string): ZoneDef | undefined { return this.zones.get(id); } zoneIds(): string[] { return [...this.zones.keys()]; } addSystem(s: System): void { this.systems.push(s); } // ───────────── Entidades ───────────── add(e: T): T { e.game = this; e.dead = false; this.entities.push(e); this.entityRoot.add(e.view); e.onAdded(); return e; } /** Crea una entidad registrada. Si el tipo no existe, avisa y devuelve un marcador inerte. */ spawn(type: string, x: number, y: number, props: Props = {}): Entity { const f = this.factories.get(type); let e: Entity; if (f) { e = f(this, x, y, props); } else { console.warn(`[game] tipo de entidad no registrado: ${type}`); e = new Placeholder(); } e.type = type; e.game = this; e.setPos(x, y); return this.add(e); } /** Entidades vivas cuya caja solapa `box`. */ entitiesIn(box: AABB, filter?: (e: Entity) => boolean): Entity[] { const out: Entity[] = []; for (const e of this.entities) { if (e.dead || !overlaps(box, e.bounds(), 0)) continue; if (!filter || filter(e)) out.push(e); } return out; } /** Primera entidad viva con la etiqueta. */ findByTag(tag: string): Entity | null { for (const e of this.entities) if (!e.dead && e.tags.has(tag)) return e; return null; } allByTag(tag: string): Entity[] { return this.entities.filter((e) => !e.dead && e.tags.has(tag)); } /** * Aplica un golpe a todo lo que solape `box` y no sea del equipo atacante. * Devuelve las entidades que acusaron el golpe (takeHit → true). */ hitArea(box: AABB, hit: Hit, from: Team, exclude?: Entity): Entity[] { const out: Entity[] = []; for (const e of this.entities) { if (e.dead || e === exclude || e.team === from) continue; if (!overlaps(box, e.bounds(), 0)) continue; if (e.takeHit(hit)) out.push(e); } return out; } // ───────────── Tiempo ───────────── /** Congela la simulación unos instantes para dar peso a los impactos. */ hitstop(seconds: number): void { this.hitstopLeft = Math.max(this.hitstopLeft, seconds); } /** Ejecuta `fn` tras `seconds` de tiempo de simulación. Se cancela al cambiar de zona si zoneBound. */ after(seconds: number, fn: () => void): void { this.timers.push({ t: this.time + seconds, fn }); } // ───────────── Zonas ───────────── async loadZone(id: string, spawn = 'default', fade = true): Promise { const def = this.zones.get(id); if (!def) { console.error(`[game] zona desconocida: ${id}`); return; } if (this.loading) return; this.loading = true; try { if (fade) await this.ui.fade(true, 0.22); if (this.zone) { this.zone.onExit?.(this); this.events.emit('zone:unload', { id: this.zone.id }); } for (const e of this.entities) if (!e.persistent) e.dead = true; this.sweep(); this.timers.length = 0; this.physics.clear(); if (this.zoneGroup) { this.gfx.scene.remove(this.zoneGroup); disposeTree(this.zoneGroup); } this.zone = def; const group = new THREE.Group(); group.name = `zone:${id}`; this.zoneGroup = group; this.gfx.scene.add(group); if (!this.zoneContextFactory) throw new Error('falta zoneContextFactory (src/world)'); const ctx = this.zoneContextFactory(this, def, group); def.build(ctx); ctx.finish?.(); const sp = def.spawns[spawn] ?? def.spawns.default; this.hero?.teleport(sp.x, sp.y); this.gfx.cam.setBounds(def.bounds); this.gfx.cam.snap(sp.x, sp.y); this.gfx.setEnv(def.env, 0); this.audio.music(def.music ?? null); tallyCommit(this); this.events.emit('zone:loaded', { id, spawn }); def.onEnter?.(this); // Compila en paralelo (sin congelar la pantalla) los shaders nuevos de la zona mientras la transición // la tapa: así el primer fotograma no se queda «colgado» varios segundos en el móvil. if (fade) await this.precompile(); } finally { this.loading = false; } if (fade) await this.ui.fade(false, 0.3); } private async precompile(): Promise { const r = (this.gfx as unknown as { three?: THREE.WebGLRenderer }).three; if (!r?.compileAsync) return; try { // Se compila contra el mismo destino que usa el juego (búfer HDR del composer): los parámetros del // programa dependen del destino y, si no coinciden, se recompilaría igualmente al dibujar. const rt = (this.gfx as unknown as { composer?: { renderTarget1?: THREE.WebGLRenderTarget } }).composer?.renderTarget1 ?? null; const prev = r.getRenderTarget(); r.setRenderTarget(rt); const job = r.compileAsync(this.gfx.scene, this.gfx.camera); r.setRenderTarget(prev); await Promise.race([ job, new Promise((res) => setTimeout(res, 1800)), ]); } catch { /* si falla, se compila al dibujar como antes */ } } /** Guarda el punto de control actual. */ checkpoint(zone: string, spawn: string): void { this.state.data.zone = zone; this.state.data.spawn = spawn; this.state.save(); this.events.emit('checkpoint', { zone, spawn }); } // ───────────── Bucle ───────────── start(): void { if (this.running) return; this.running = true; this.last = performance.now(); const loop = (now: number) => { if (!this.running) return; requestAnimationFrame(loop); const dt = Math.min(0.1, (now - this.last) / 1000); this.last = now; this.frame(dt); }; requestAnimationFrame(loop); } stop(): void { this.running = false; } /** Avanza un frame de `dt` segundos reales. Público para pruebas (window.__eh.frame). */ frame(dt: number): void { this.input.poll(); if (this.hitstopLeft > 0) { this.hitstopLeft -= dt; } else { this.acc += dt; } let steps = 0; while (this.acc >= STEP && steps < 5) { this.step(STEP); this.acc -= STEP; steps++; } if (steps === 5) this.acc = 0; const alpha = this.acc / STEP; for (const e of this.entities) if (!e.dead) e.render(alpha, dt); for (const s of this.systems) s.render?.(alpha, dt); this.gfx.update(dt); this.gfx.draw(); } get frozen(): boolean { return this.paused || this.loading || this.ui.modalOpen; } private step(dt: number): void { const frozen = this.frozen; for (const s of this.systems) if (s.update && (!frozen || s.always)) s.update(dt, frozen); if (!frozen) { this.time += dt; this.state.data.playTime += dt; if (this.timers.length) { const due = this.timers.filter((t) => t.t <= this.time); if (due.length) { this.timers = this.timers.filter((t) => t.t > this.time); for (const t of due) t.fn(); } } const list = this.entities; for (let i = 0; i < list.length; i++) { const e = list[i]; if (e.dead) continue; e.px = e.x; e.py = e.y; e.update(dt); if (e.body) { e.x = e.body.x; e.y = e.body.y; } } this.zone?.update?.(this, dt); this.sweep(); } this.input.endStep(); } private sweep(): void { const list = this.entities; for (let i = list.length - 1; i >= 0; i--) { const e = list[i]; if (!e.dead) continue; list.splice(i, 1); try { e.onRemoved(); } catch (err) { console.error('[game] error en onRemoved', err); } this.entityRoot.remove(e.view); disposeTree(e.view); } } } class Placeholder extends Entity {} /** * Libera geometrías y materiales de un árbol. Los recursos compartidos/cacheados * deben marcarse con `userData.shared = true` para no destruirlos. */ export function disposeTree(root: THREE.Object3D): void { root.traverse((o) => { const m = o as THREE.Mesh; if (m.geometry && !m.geometry.userData.shared) m.geometry.dispose(); const mat = m.material as THREE.Material | THREE.Material[] | undefined; if (!mat) return; for (const one of Array.isArray(mat) ? mat : [mat]) { if (!one.userData.shared) one.dispose(); } }); }