/** * Motor de partículas: un único Mesh instanciado (1 draw call) con atlas y shader propio. * - Pool preasignado en un Float32Array (STRIDE floats por partícula), asignación en anillo: * cuando se llena, se recicla la más vieja. Sin asignaciones por frame. * - Mezcla premultiplicada: cada instancia elige entre aditivo (add = 1) y alfa normal (add = 0) * o cualquier punto intermedio, todo en la misma draw call. * - Anillos de onda de impacto procedurales (grosor animado) en el mismo shader. */ import * as THREE from 'three'; import { GRID, SpriteAtlas } from './sprites'; export const MAX_PARTICLES = 1536; /** Flags por partícula. */ export const F = { /** Rota según la velocidad (+x del sprite = dirección). */ ALIGN: 1, /** Sigue animándose con el juego en pausa (efectos de UI). */ UI: 2, /** Aparece creciendo desde 0. */ POP: 4, /** Encoge hasta 0 al final de la vida. */ SHRINK: 8, /** Voltereta sobre su eje (confeti, hojas). */ FLIP: 16, /** Rebota en `floor`. */ BOUNCE: 32, } as const; /** Curvas de tamaño (s0 → s1). */ export const SC = { LIN: 0, OUT: 1, IN: 2, SIN: 3 } as const; /** Curvas de alfa. */ export const AC = { HOLD: 0, LIN: 1, QUAD: 2, SIN: 3, LATE: 4, INOUT: 5 } as const; /** Modos de movimiento. */ export const MODE = { FREE: 0, HOME: 1, ORBIT: 2 } as const; const STRIDE = 40; const X = 0, Y = 1, Z = 2, VX = 3, VY = 4, GRAV = 5, DRAG = 6, AGE = 7, LIFE = 8, S0 = 9, S1 = 10, ASP = 11, ROT = 12, RV = 13, R = 14, G = 15, B = 16, R2 = 17, G2 = 18, B2 = 19, A = 20, ADD = 21, CELL = 22, FLAGS = 23, FLOOR = 24, OX = 25, OY = 26, TX = 27, TY = 28, ANG = 29, ANGV = 30, RAD0 = 31, RAD1 = 32, SWA = 33, SWF = 34, TH0 = 35, TH1 = 36, CURVES = 37, MODE_ = 38, PHASE = 39; const tmpColor = new THREE.Color(); /** Descripción reutilizable de una partícula a emitir (se copia al pool en `emit`). */ export class Spec { x = 0; y = 0; z = 0; vx = 0; vy = 0; /** Aceleración vertical (negativa = cae). */ grav = 0; /** Rozamiento (1/s). */ drag = 0; life = 0.5; /** Segundos antes de aparecer. */ delay = 0; /** Tamaño (alto del quad en unidades) inicial y final. */ s0 = 0.3; s1 = 0.3; sc: number = SC.LIN; /** Ancho = tamaño × asp. */ asp = 1; rot = 0; rv = 0; r = 1; g = 1; b = 1; r2 = 1; g2 = 1; b2 = 1; a = 1; ac: number = AC.HOLD; /** 1 = aditivo (luminoso), 0 = alfa normal. */ add = 0; cell = 0; flags = 0; floor = -1e9; mode: number = MODE.FREE; /** HOME: destino. */ tx = 0; ty = 0; /** ORBIT: ángulo, velocidad angular, radio inicial/final (centro = x,y; sube con vy). */ ang = 0; angV = 0; rad0 = 0; rad1 = 0; /** Vaivén horizontal: amplitud (u/s) y frecuencia (rad/s). */ swA = 0; swF = 0; /** Anillo procedural: grosor relativo inicial/final (0 = sprite normal). */ th0 = 0; th1 = 0; reset(): this { this.x = this.y = this.z = 0; this.vx = this.vy = this.grav = this.drag = 0; this.life = 0.5; this.delay = 0; this.s0 = this.s1 = 0.3; this.sc = SC.LIN; this.asp = 1; this.rot = this.rv = 0; this.r = this.g = this.b = this.r2 = this.g2 = this.b2 = 1; this.a = 1; this.ac = AC.HOLD; this.add = 0; this.cell = 0; this.flags = 0; this.floor = -1e9; this.mode = MODE.FREE; this.tx = this.ty = this.ang = this.angV = this.rad0 = this.rad1 = 0; this.swA = this.swF = this.th0 = this.th1 = 0; return this; } /** Color (hex sRGB) con multiplicador de brillo (> 1 activa el bloom). Fija inicio y fin. */ col(hex: number, boost = 1): this { tmpColor.setHex(hex); this.r = this.r2 = tmpColor.r * boost; this.g = this.g2 = tmpColor.g * boost; this.b = this.b2 = tmpColor.b * boost; return this; } /** Color al final de la vida. */ col2(hex: number, boost = 1): this { tmpColor.setHex(hex); this.r2 = tmpColor.r * boost; this.g2 = tmpColor.g * boost; this.b2 = tmpColor.b * boost; return this; } } const VERT = /* glsl */ ` attribute vec3 iPos; attribute vec4 iXform; // ancho, alto, rotación, celda attribute vec4 iColor; attribute vec2 iMisc; // aditivo, grosor de anillo uniform float uGrid; varying vec2 vUv; varying vec2 vQuad; varying vec4 vColor; varying vec2 vMisc; void main() { float c = cos(iXform.z); float s = sin(iXform.z); vec2 q = position.xy * iXform.xy; q = vec2(q.x * c - q.y * s, q.x * s + q.y * c); vec4 mv = viewMatrix * vec4(iPos, 1.0); mv.xy += q; gl_Position = projectionMatrix * mv; float cx = mod(iXform.w, uGrid); float cy = floor(iXform.w / uGrid + 0.001); vUv = vec2((cx + uv.x) / uGrid, 1.0 - (cy + 1.0 - uv.y) / uGrid); vQuad = position.xy; vColor = iColor; vMisc = iMisc; } `; const FRAG = /* glsl */ ` uniform sampler2D map; varying vec2 vUv; varying vec2 vQuad; varying vec4 vColor; varying vec2 vMisc; void main() { vec4 t = texture2D(map, vUv); float a = t.a; vec3 rgb = t.rgb; if (vMisc.y > 0.0) { float d = length(vQuad) * 2.0; float th = vMisc.y; float soft = 0.05 + th * 0.25; a = smoothstep(1.0, 1.0 - soft, d) * smoothstep(1.0 - th - soft, 1.0 - th, d); rgb = vec3(1.0); } a *= vColor.a; if (a < 0.003) discard; gl_FragColor = vec4(rgb * vColor.rgb, 1.0); #include #include gl_FragColor = vec4(gl_FragColor.rgb * a, a * (1.0 - vMisc.x)); } `; export class ParticleEngine { readonly mesh: THREE.Mesh; readonly atlas: SpriteAtlas; /** Partículas vivas en el último frame. */ alive = 0; private d = new Float32Array(MAX_PARTICLES * STRIDE); private cursor = 0; private geo: THREE.InstancedBufferGeometry; private aPos: THREE.InstancedBufferAttribute; private aXform: THREE.InstancedBufferAttribute; private aColor: THREE.InstancedBufferAttribute; private aMisc: THREE.InstancedBufferAttribute; constructor() { this.atlas = new SpriteAtlas(); const quad = new THREE.PlaneGeometry(1, 1); const geo = new THREE.InstancedBufferGeometry(); geo.index = quad.index; geo.setAttribute('position', quad.getAttribute('position')); geo.setAttribute('uv', quad.getAttribute('uv')); const mk = (size: number): THREE.InstancedBufferAttribute => { const at = new THREE.InstancedBufferAttribute(new Float32Array(MAX_PARTICLES * size), size); at.setUsage(THREE.DynamicDrawUsage); return at; }; geo.setAttribute('iPos', (this.aPos = mk(3))); geo.setAttribute('iXform', (this.aXform = mk(4))); geo.setAttribute('iColor', (this.aColor = mk(4))); geo.setAttribute('iMisc', (this.aMisc = mk(2))); geo.instanceCount = 0; geo.userData.shared = true; this.geo = geo; const mat = new THREE.ShaderMaterial({ uniforms: { map: { value: this.atlas.texture }, uGrid: { value: GRID } }, vertexShader: VERT, fragmentShader: FRAG, transparent: true, depthWrite: false, depthTest: true, side: THREE.DoubleSide, blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, blendSrc: THREE.OneFactor, blendDst: THREE.OneMinusSrcAlphaFactor, blendSrcAlpha: THREE.OneFactor, blendDstAlpha: THREE.OneMinusSrcAlphaFactor, premultipliedAlpha: true, }); mat.userData.shared = true; this.mesh = new THREE.Mesh(geo, mat); this.mesh.name = 'vfx:particles'; this.mesh.frustumCulled = false; this.mesh.renderOrder = 900; this.mesh.castShadow = false; this.mesh.receiveShadow = false; // Pases con overrideMaterial (GTAO/normales/profundidad del post) dibujarían cada instancia como un // quad opaco sin textura: en esos pases no se dibuja ninguna instancia. let saved = 0; this.mesh.onBeforeRender = (_r, _s, _c, g, m) => { saved = -1; if (m !== mat) { saved = (g as THREE.InstancedBufferGeometry).instanceCount; (g as THREE.InstancedBufferGeometry).instanceCount = 0; } }; this.mesh.onAfterRender = (_r, _s, _c, g) => { if (saved >= 0) (g as THREE.InstancedBufferGeometry).instanceCount = saved; }; } /** Copia la especificación al pool (recicla la partícula más vieja si está lleno). */ emit(s: Spec): void { // Nada inválido llega al GPU: sprite fuera del atlas → círculo suave; NaN → se descarta. let cell = Math.floor(s.cell); if (!(cell >= 0 && cell < GRID * GRID)) cell = 0; if (!Number.isFinite(s.x + s.y + s.z + s.vx + s.vy + s.s0 + s.s1 + s.life + s.asp)) return; const d = this.d; const o = this.cursor * STRIDE; this.cursor = (this.cursor + 1) % MAX_PARTICLES; d[o + X] = d[o + OX] = s.x; d[o + Y] = d[o + OY] = s.y; d[o + Z] = s.z; d[o + VX] = s.vx; d[o + VY] = s.vy; d[o + GRAV] = s.grav; d[o + DRAG] = s.drag; d[o + AGE] = -s.delay; d[o + LIFE] = s.life > 0 ? s.life : 0.01; d[o + S0] = s.s0; d[o + S1] = s.s1; d[o + ASP] = s.asp; d[o + ROT] = s.rot; d[o + RV] = s.rv; d[o + R] = s.r; d[o + G] = s.g; d[o + B] = s.b; d[o + R2] = s.r2; d[o + G2] = s.g2; d[o + B2] = s.b2; d[o + A] = s.a; d[o + ADD] = s.add; d[o + CELL] = cell; d[o + FLAGS] = s.flags; d[o + FLOOR] = s.floor; d[o + TX] = s.tx; d[o + TY] = s.ty; d[o + ANG] = s.ang; d[o + ANGV] = s.angV; d[o + RAD0] = s.rad0; d[o + RAD1] = s.rad1; d[o + SWA] = s.swA; d[o + SWF] = s.swF; d[o + TH0] = s.th0; d[o + TH1] = s.th1; d[o + CURVES] = s.sc + s.ac * 8; d[o + MODE_] = s.mode; d[o + PHASE] = Math.random() * 6.2832; } clear(): void { const d = this.d; for (let i = 0; i < MAX_PARTICLES; i++) d[i * STRIDE + LIFE] = 0; this.geo.instanceCount = 0; this.alive = 0; } /** Simula y vuelca a los buffers de instancia. `frozen` detiene todo salvo las partículas UI. */ update(dt: number, frozen: boolean): void { const d = this.d; const pos = this.aPos.array as Float32Array; const xf = this.aXform.array as Float32Array; const col = this.aColor.array as Float32Array; const misc = this.aMisc.array as Float32Array; let n = 0; for (let i = 0; i < MAX_PARTICLES; i++) { const o = i * STRIDE; const life = d[o + LIFE]; if (life <= 0) continue; const flags = d[o + FLAGS] | 0; const step = frozen && !(flags & F.UI) ? 0 : dt; const age = d[o + AGE] + step; d[o + AGE] = age; if (age >= life) { d[o + LIFE] = 0; continue; } if (age < 0) continue; const t = age / life; const mode = d[o + MODE_]; if (step > 0) { if (mode === MODE.FREE) { let k = 1 - d[o + DRAG] * step; if (k < 0) k = 0; let vx = d[o + VX] * k; let vy = d[o + VY] * k + d[o + GRAV] * step; let x = d[o + X] + vx * step; let y = d[o + Y] + vy * step; const swA = d[o + SWA]; if (swA !== 0) x += Math.sin(age * d[o + SWF] + d[o + PHASE]) * swA * step; if (flags & F.BOUNCE && y < d[o + FLOOR] && vy < 0) { y = d[o + FLOOR]; vy *= -0.45; vx *= 0.6; d[o + RV] *= 0.5; } d[o + VX] = vx; d[o + VY] = vy; d[o + X] = x; d[o + Y] = y; } else if (mode === MODE.HOME) { const k = t * t * (3 - 2 * t); const arc = t * (1 - t); d[o + X] = d[o + OX] + (d[o + TX] - d[o + OX]) * k + d[o + VX] * arc; d[o + Y] = d[o + OY] + (d[o + TY] - d[o + OY]) * k + d[o + VY] * arc; } else { const ang = d[o + ANG] + d[o + ANGV] * step; d[o + ANG] = ang; d[o + OY] += d[o + VY] * step; const rad = d[o + RAD0] + (d[o + RAD1] - d[o + RAD0]) * t; d[o + X] = d[o + OX] + Math.cos(ang) * rad; d[o + Y] = d[o + OY] + Math.sin(ang) * rad * 0.38; } if (flags & F.ALIGN) { if (mode === MODE.FREE) d[o + ROT] = Math.atan2(d[o + VY], d[o + VX]); } else { d[o + ROT] += d[o + RV] * step; } } // Curvas const curves = d[o + CURVES] | 0; const sc = curves & 7; const ac = curves >> 3; let f = t; if (sc === SC.OUT) { const u = 1 - t; f = 1 - u * u * u; } else if (sc === SC.IN) f = t * t; let size = sc === SC.SIN ? d[o + S0] * Math.sin(Math.PI * t) : d[o + S0] + (d[o + S1] - d[o + S0]) * f; if (flags & F.POP) { const u = age < 0.09 ? age / 0.09 : 1; size *= u * (2 - u); } if (flags & F.SHRINK && t > 0.5) { const v = (t - 0.5) * 2; size *= 1 - v * v; } let a = d[o + A]; if (ac === AC.LIN) a *= 1 - t; else if (ac === AC.QUAD) a *= (1 - t) * (1 - t); else if (ac === AC.SIN) a *= Math.sin(Math.PI * t); else if (ac === AC.LATE) { if (t > 0.6) { const v = (t - 0.6) / 0.4; a *= 1 - v * v * (3 - 2 * v); } } else if (ac === AC.INOUT) a *= Math.min(1, t / 0.15) * Math.min(1, (1 - t) / 0.3); let sx = size * d[o + ASP]; if (flags & F.FLIP) sx *= Math.cos(age * 9 + d[o + PHASE]); const p3 = n * 3; const p4 = n * 4; const p2 = n * 2; pos[p3] = d[o + X]; pos[p3 + 1] = d[o + Y]; pos[p3 + 2] = d[o + Z]; xf[p4] = sx; xf[p4 + 1] = size; xf[p4 + 2] = d[o + ROT]; xf[p4 + 3] = d[o + CELL]; col[p4] = d[o + R] + (d[o + R2] - d[o + R]) * t; col[p4 + 1] = d[o + G] + (d[o + G2] - d[o + G]) * t; col[p4 + 2] = d[o + B] + (d[o + B2] - d[o + B]) * t; col[p4 + 3] = a; misc[p2] = d[o + ADD]; const th0 = d[o + TH0]; misc[p2 + 1] = th0 > 0 ? Math.max(0.004, th0 + (d[o + TH1] - th0) * f) : 0; n++; } this.alive = n; this.geo.instanceCount = n; if (n > 0) { this.touch(this.aPos, n * 3); this.touch(this.aXform, n * 4); this.touch(this.aColor, n * 4); this.touch(this.aMisc, n * 2); } } private touch(at: THREE.InstancedBufferAttribute, count: number): void { at.clearUpdateRanges(); at.addUpdateRange(0, count); at.needsUpdate = true; } }