/** * Módulo de render de Emoji Heroes. * * createRenderer(canvas): RenderService & RendererExtras * * Cadena: SkyPass (cielo) → RenderPass (escena, MSAA 4×) → GTAO (opcional) → Bloom por umbral → * Grade (tone mapping Neutral + sRGB + gradación cálida + viñeta). * Luces: hemisférica (cielo/suelo) + sol direccional con sombras PCFSoft que sigue a la cámara. * Calidad automática: baja pixel ratio / AO / sombras si el frame time sube (ver `quality`). */ import * as THREE from 'three'; import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js'; import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js'; import { updateDomEmoji } from './emojiDom'; import { installLightPool, syncLightPool } from './lightPool'; import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js'; import type { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js'; import type { DayPhase, EnvParams, RenderService } from '../core/types'; import { Camera, CAM_FOV } from './camera'; import { BASE_ENV, COLOR_KEYS, ENV_PRESETS, lerpEnv, resolveEnv, type EnvFull } from './env'; import { SkyPass } from './sky'; import { createGradePass, SoftGTAOPass } from './post'; import { toonGlobals } from './materials'; export { toonMaterial, ToonMaterial, toonGlobals, blobShadow } from './materials'; export type { ToonOpts } from './materials'; export { emojiTexture, emojiMesh, emojiMaterial, emojiSprite, emojiReady, emojiNormalMap, EMOJI_FONT } from './emoji'; export type { EmojiMeshOpts } from './emoji'; export { ENV_PRESETS, BASE_ENV, COLOR_KEYS } from './env'; export type { EnvFull } from './env'; export { Camera, CAM_DIST, CAM_FOV } from './camera'; // ───────────────────────────── Calidad ───────────────────────────── export type QualityLevel = 0 | 1 | 2 | 3; /** * Ajustes de calidad. `level`: 3 alto (AO, sombras 2048, DPR≤2), 2 medio (sin AO, DPR≤1.5), * 1 bajo (sombras 1024, DPR 1, bloom a media), 0 mínimo (DPR 0.75, sin sombras). * Con `auto` el renderer baja de nivel si la media de frame supera ~22 ms, y sube con cautela. * Tras cambiar campos a mano llama a `gfx.applyQuality()`. */ export const quality = { level: 2 as QualityLevel, auto: true, /** null = lo decide el nivel. */ ao: null as boolean | null, bloom: true, shadows: true, maxPixelRatio: 2, }; const LEVELS = [ // MSAA 2 en TODOS los niveles: a MSAA 0 los contornos de los edificios 3D // salen dentados (escalera) y al moverse la cámara en vertical (saltos, // plataformas) los escalones arrastran de cuadro en cuadro: el contorno // parpadea. En móvil a 30fps la autoQuality baja a nivel 1/0, así que sin // MSAA ahí el parpadeo volvía siempre. El nivel 0 no puede bajar más, así // que no hay riesgo de oscilación por el coste del MSAA 2. { pr: 0.75, ao: false, shadow: 0, bloomScale: 0.5, msaa: 2 }, { pr: 1, ao: false, shadow: 1024, bloomScale: 0.5, msaa: 2 }, { pr: 1.5, ao: false, shadow: 2048, bloomScale: 0.5, msaa: 2 }, { pr: 2, ao: false, shadow: 2048, bloomScale: 0.5, msaa: 4 }, ]; function isMobile(): boolean { return typeof matchMedia !== 'undefined' && matchMedia('(pointer: coarse)').matches; } /** Extras públicos del renderer (además de RenderService). */ export interface RendererExtras { /** Llamado al cambiar la fase del día. Conéctalo: `gfx.onPhase = (phase) => game.events.emit('env:phase', { phase })`. */ onPhase?: (phase: DayPhase) => void; readonly env: EnvFull; readonly sun: THREE.DirectionalLight; readonly hemi: THREE.HemisphereLight; /** Reaplica `quality` (pixel ratio, AO, sombras). */ applyQuality(): void; /** Muestras MSAA del render principal (0 = sin MSAA). */ setMsaa(samples: number): void; readonly msaa: number; /** Frame time medio (s). */ readonly frameTime: number; } // ───────────────────────────── Renderer ───────────────────────────── class Renderer implements RenderService, RendererExtras { readonly three: THREE.WebGLRenderer; readonly scene = new THREE.Scene(); readonly camera: THREE.PerspectiveCamera; readonly cam: Camera; onPhase?: (phase: DayPhase) => void; readonly sun: THREE.DirectionalLight; readonly hemi: THREE.HemisphereLight; /** Relleno frontal suave (sin sombra) para que las caras de cara a cámara nunca queden planas. */ private fill: THREE.DirectionalLight; private current: EnvFull = { ...BASE_ENV }; private from: EnvFull = { ...BASE_ENV }; private to: EnvFull = { ...BASE_ENV }; private tEnv = 1; private durEnv = 0; private phase: DayPhase = 'day'; private composer: EffectComposer; private skyPass: SkyPass; private renderPass: RenderPass; private aoPass: SoftGTAOPass | null = null; private bloomPass: UnrealBloomPass; private gradePass: ShaderPass; private fog: THREE.Fog; private avgDt = 1 / 60; private slowFor = 0; private fastFor = 0; private lastDowngrade = -999; private clock = 0; private width = 1; private height = 1; private appliedLevel = -1; constructor(private canvas: HTMLCanvasElement) { this.three = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', stencil: false, alpha: false, }); const r = this.three; r.outputColorSpace = THREE.SRGBColorSpace; // El tone mapping lo hace el pase final (Neutral). Para render directo sin composer, Neutral también. r.toneMapping = THREE.NeutralToneMapping; r.shadowMap.enabled = true; r.shadowMap.type = THREE.PCFSoftShadowMap; r.shadowMap.autoUpdate = false; // una vez por frame (GTAO renderiza la escena otra vez) this.camera = new THREE.PerspectiveCamera(CAM_FOV, 16 / 9, 0.5, 400); this.cam = new Camera(this.camera); this.fog = new THREE.Fog(0xffffff, 40, 150); this.scene.fog = this.fog; this.hemi = new THREE.HemisphereLight(0xffffff, 0x8a7a66, 1); this.sun = new THREE.DirectionalLight(0xffffff, 2); this.sun.castShadow = true; const sc = this.sun.shadow.camera; sc.left = -26; sc.right = 26; sc.top = 18; sc.bottom = -18; sc.near = 1; sc.far = 100; this.sun.shadow.bias = -0.0004; this.sun.shadow.normalBias = 0.035; this.sun.shadow.radius = 5; this.sun.shadow.blurSamples = 12; this.fill = new THREE.DirectionalLight(0xffffff, 0.35); this.scene.add(this.hemi, this.sun, this.sun.target, this.fill, this.fill.target); installLightPool(this.scene); // Composer con MSAA en el target (WebGL2) y HDR half-float const size = r.getDrawingBufferSize(new THREE.Vector2()); const rt = new THREE.WebGLRenderTarget(Math.max(1, size.x), Math.max(1, size.y), { type: THREE.HalfFloatType, samples: 4, }); this.composer = new EffectComposer(r, rt); this.skyPass = new SkyPass(); this.renderPass = new RenderPass(this.scene, this.camera); this.renderPass.clear = false; this.bloomPass = new UnrealBloomPass(new THREE.Vector2(256, 256), 0.5, 0.45, 1.0); // Píxeles sueltos muy brillantes (especular en bordes finos) se convertían en cuadraditos al // difuminarse: se limita lo que entra al bloom. const hp = this.bloomPass.materialHighPassFilter; hp.fragmentShader = hp.fragmentShader.replace( 'vec4 texel = texture2D( tDiffuse, vUv );', 'vec4 texel = texture2D( tDiffuse, vUv ); texel.rgb = min( max( texel.rgb, vec3( 0.0 ) ), vec3( 2.5 ) );', ); hp.needsUpdate = true; this.gradePass = createGradePass(); this.composer.addPass(this.skyPass); this.composer.addPass(this.renderPass); this.composer.addPass(this.bloomPass); this.composer.addPass(this.gradePass); quality.level = isMobile() ? 2 : 3; this.applyEnv(this.current); this.resize(); window.addEventListener('resize', () => this.resize()); window.visualViewport?.addEventListener('resize', () => this.resize()); if (typeof ResizeObserver !== 'undefined') new ResizeObserver(() => this.resize()).observe(canvas); } get env(): EnvFull { return this.current; } get frameTime(): number { return this.avgDt; } // ───────────── Ambiente ───────────── setEnv(env: string | Partial, seconds = 0): void { const target = resolveEnv(env, this.to); this.from = { ...this.current }; this.to = target; this.durEnv = Math.max(0, seconds); this.tEnv = this.durEnv > 0 ? 0 : 1; if (this.durEnv === 0) { this.current = { ...target }; this.applyEnv(this.current); } if (target.phase !== this.phase) { this.phase = target.phase; try { this.onPhase?.(this.phase); } catch (e) { console.error('[render] onPhase', e); } } } private applyEnv(e: EnvFull): void { const dark = THREE.MathUtils.clamp(e.darkness ?? 0, 0, 1); const lit = 1 - dark * 0.92; this.fog.color.setHex(e.fogColor); this.fog.near = e.fogNear; this.fog.far = e.fogFar; this.sun.color.setHex(e.sunColor); this.sun.intensity = e.sunIntensity * lit; this.hemi.color.setHex(e.ambientColor); this.hemi.groundColor.setHex(e.groundColor); this.hemi.intensity = e.ambientIntensity * (1 - dark * 0.75); this.fill.color.setHex(e.ambientColor); this.fill.intensity = 0.3 * e.ambientIntensity * lit; toonGlobals.uRimColor.value.setHex(e.rimColor).multiplyScalar(e.rimIntensity * (1 - dark * 0.5)); this.skyPass.setEnv(e); this.bloomPass.strength = quality.bloom ? (e.bloom ?? 0.4) * 0.75 : 0; this.bloomPass.enabled = quality.bloom && (e.bloom ?? 0) > 0.01; // Búfer HDR: solo lo emisivo debe pasar de ~1.2. Un umbral más bajo velaba superficies iluminadas // (fachadas, suelos con luz de borde) con una neblina rectangular. this.bloomPass.radius = 0.35; this.bloomPass.threshold = 1.2 - Math.min(0.2, dark * 0.25); const u = this.gradePass.uniforms; u.uExposure.value = e.exposure ?? 1; u.uWarmth.value = e.warmth ?? 0.2; u.uSaturation.value = e.saturation ?? 1.1; u.uVignette.value = Math.min(1, (e.vignette ?? 0.3) + dark * 0.35); } // ───────────── Frame ───────────── update(dt: number): void { this.clock += dt; if (this.tEnv < 1) { this.tEnv = Math.min(1, this.tEnv + dt / this.durEnv); const k = this.tEnv * this.tEnv * (3 - 2 * this.tEnv); lerpEnv(this.current, this.from, this.to, k); this.current.phase = this.to.phase; this.applyEnv(this.current); } this.cam.update(dt); this.skyPass.update(dt, this.cam.x, this.cam.y, this.camera.aspect); // Sol: acompaña a la cámara para cubrir lo visible; posición en texels para que la sombra no tiemble const ext = this.cam.halfExtents(); const sc = this.sun.shadow.camera; const hw = ext.hw + 6, hh = ext.hh + 5; if (sc.right !== hw || sc.top !== hh) { sc.left = -hw; sc.right = hw; sc.top = hh; sc.bottom = -hh; sc.updateProjectionMatrix(); } const texel = (hw * 2) / Math.max(1, this.sun.shadow.mapSize.x); const cx = Math.round(this.cam.x / texel) * texel; const cy = Math.round(this.cam.y / texel) * texel; this.sun.target.position.set(cx, cy, 0); this.sun.position.set(cx - 10, cy + 22, 18); this.fill.target.position.set(cx, cy, 0); this.fill.position.set(cx + 6, cy + 4, 30); this.autoQuality(dt); } draw(): void { this.three.shadowMap.needsUpdate = true; syncLightPool(this.camera); this.composer.render(); updateDomEmoji(this.camera, this.canvas); } // ───────────── Tamaño y calidad ───────────── resize(): void { const w = Math.max(1, this.canvas.clientWidth || window.innerWidth); const h = Math.max(1, this.canvas.clientHeight || window.innerHeight); const lvl = LEVELS[quality.level]; const pr = Math.min(window.devicePixelRatio || 1, lvl.pr, quality.maxPixelRatio); const changed = w !== this.width || h !== this.height || this.three.getPixelRatio() !== pr; this.width = w; this.height = h; this.camera.aspect = w / h; this.camera.updateProjectionMatrix(); (this.gradePass.uniforms.uAspect as { value: number }).value = w / h; if (!changed && this.appliedLevel === quality.level) return; this.three.setPixelRatio(pr); this.three.setSize(w, h, false); this.composer.setPixelRatio(pr); this.composer.setSize(w, h); // bloom a resolución reducida (más barato y más suave) this.bloomPass.setSize(Math.ceil(w * pr * lvl.bloomScale), Math.ceil(h * pr * lvl.bloomScale)); this.aoPass?.setSize(Math.ceil(w * pr * 0.5), Math.ceil(h * pr * 0.5)); } setMsaa(samples: number): void { for (const t of [this.composer.renderTarget1, this.composer.renderTarget2]) { if (t.samples === samples) continue; t.samples = samples; t.dispose(); } } get msaa(): number { return this.composer.renderTarget1.samples; } applyQuality(): void { const lvl = LEVELS[quality.level]; const wantAO = quality.ao ?? lvl.ao; if (wantAO && !this.aoPass) { const pr = this.three.getPixelRatio(); this.aoPass = new SoftGTAOPass(this.scene, this.camera, Math.ceil(this.width * pr * 0.5), Math.ceil(this.height * pr * 0.5)); this.aoPass.updateGtaoMaterial({ radius: 0.9, distanceExponent: 1.5, thickness: 1.5, scale: 1, samples: 12, distanceFallOff: 1 }); this.aoPass.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, rings: 2, samples: 12 }); this.aoPass.blendIntensity = 0.65; this.composer.insertPass(this.aoPass, 2); } else if (!wantAO && this.aoPass) { this.composer.removePass(this.aoPass); this.aoPass.dispose(); this.aoPass = null; } const shadowOn = quality.shadows && lvl.shadow > 0; this.sun.castShadow = shadowOn; if (shadowOn && this.sun.shadow.mapSize.x !== lvl.shadow) { this.sun.shadow.mapSize.set(lvl.shadow, lvl.shadow); this.sun.shadow.map?.dispose(); this.sun.shadow.map = null; } // El MSAA 4x es el coste fijo más alto en GPU móvil y autoQuality nunca // lo tocaba: en niveles bajos se quita (el arte es plano y en pantalla // pequeña apenas se nota) para que el juego pueda llegar a 60fps y el // fondo deje de avanzar a saltos. this.setMsaa(lvl.msaa); this.appliedLevel = -1; this.resize(); this.appliedLevel = quality.level; this.applyEnv(this.current); } private autoQuality(dt: number): void { if (this.appliedLevel !== quality.level) this.applyQuality(); if (!quality.auto || dt <= 0 || dt > 0.25) return; this.avgDt += (dt - this.avgDt) * 0.05; if (this.clock < 3) return; // arranque: compilación de shaders, carga… if (this.avgDt > 1 / 45) { this.slowFor += dt; this.fastFor = 0; } else if (this.avgDt < 1 / 58) { this.fastFor += dt; this.slowFor = 0; } else { this.slowFor = Math.max(0, this.slowFor - dt); } if (this.slowFor > 2 && quality.level > 0) { quality.level = (quality.level - 1) as QualityLevel; this.lastDowngrade = this.clock; this.slowFor = 0; this.avgDt = 1 / 60; } else if (this.fastFor > 20 && quality.level < 3 && this.clock - this.lastDowngrade > 60) { // solo sube si lleva mucho tiempo holgado y no se bajó hace poco (evita oscilar) const cap = isMobile() ? 2 : 3; if (quality.level < cap) quality.level = (quality.level + 1) as QualityLevel; this.fastFor = 0; } } } export function createRenderer(canvas: HTMLCanvasElement): RenderService & RendererExtras { return new Renderer(canvas); } export { ENV_PRESETS as envPresets };