/** * Materiales — "plástico suave" de Emoji Heroes. * * `toonMaterial(opts)` devuelve un `ToonMaterial` (subclase de MeshStandardMaterial), así que admite * sombras, niebla, luces puntuales, `map`, `emissive`, transparencia… y además: * - rampa de luz suavizada (toon suave: meseta de luz amplia y terminador blando, no cel duro), * - luz de borde fresnel (`rim`, `rimPower`) teñida por el ambiente (`toonGlobals.uRimColor`), * - especular amplio y suave controlado por `gloss`, * - refuerzo de lo emisivo para que supere el umbral del bloom. */ import * as THREE from 'three'; export interface ToonOpts { color: THREE.ColorRepresentation; /** Color y fuerza del brillo propio (poderes, ojos de robot…). */ emissive?: THREE.ColorRepresentation; emissiveIntensity?: number; /** 0 mate … 1 plástico muy brillante. Por defecto 0.6. */ gloss?: number; /** Luz de borde 0..1. Por defecto 0.5. */ rim?: number; map?: THREE.Texture | null; transparent?: boolean; opacity?: number; side?: THREE.Side; /** Exponente del fresnel del borde (más alto = borde más fino). Por defecto 2.6. */ rimPower?: number; normalMap?: THREE.Texture | null; emissiveMap?: THREE.Texture | null; alphaTest?: number; /** false: no le afecta la niebla. */ fog?: boolean; depthWrite?: boolean; /** El `map` viene con alfa premultiplicado (texture.premultiplyAlpha): se des-premultiplica en el shader. */ premultipliedMap?: boolean; } /** Uniformes globales compartidos por todos los ToonMaterial; los actualiza el renderer según el ambiente. */ export const toonGlobals = { /** Color (lineal, ya con intensidad) de la luz de borde. */ uRimColor: { value: new THREE.Color(1, 1, 1) }, }; const PARS = /* glsl */ ` uniform vec3 uRimColor; uniform float uRim; uniform float uRimPower; float ehToonRamp( float ndl ) { // meseta de luz amplia + terminador blando; mezcla con lambert para conservar el volumen float s = smoothstep( -0.08, 0.58, ndl ); return mix( saturate( ndl ), s, 0.8 ); } ` + THREE.ShaderChunk.lights_physical_pars_fragment // La rampa toon solo va en el difuso. El especular conserva dotNL: el término de visibilidad del GGX se dispara // en bordes rasantes y solo dotNL lo anula; con la rampa salían píxeles sueltos x100 que el bloom volvía flashes. // Además se limita el especular directo para que ningún brillo puntual parpadee. .replace( 'reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );', 'reflectedLight.directSpecular += min( irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ), vec3( 0.9 ) );', ) .replace( 'reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}', 'reflectedLight.directDiffuse += ehToonRamp( dot( geometryNormal, directLight.direction ) ) * directLight.color * BRDF_Lambert( material.diffuseColor );\n}', ); if (!PARS.includes('vec3( 0.9 )') || !PARS.includes('ehToonRamp( dot( geometryNormal')) console.warn('[materials] parche toon no aplicado'); const MAP_PM = /* glsl */ ` #ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); // textura RGBA8 premultiplicada en sRGB (ver emojiTexturePM): color recto y luego a lineal sampledDiffuseColor.rgb = min( sampledDiffuseColor.rgb / max( sampledDiffuseColor.a, 1e-4 ), vec3( 1.0 ) ); sampledDiffuseColor.rgb = pow( sampledDiffuseColor.rgb, vec3( 2.2 ) ); diffuseColor *= sampledDiffuseColor; #endif `; const EMISSIVE_PM = /* glsl */ ` #ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); emissiveColor.rgb = pow( min( emissiveColor.rgb / max( emissiveColor.a, 1e-4 ), vec3( 1.0 ) ), vec3( 2.2 ) ) * emissiveColor.a; totalEmissiveRadiance *= emissiveColor.rgb; #endif `; const RIM = /* glsl */ ` { float ehNV = saturate( dot( normal, geometryViewDir ) ); float ehF = pow( 1.0 - ehNV, uRimPower ); // el borde pesa más por arriba (luz de cielo) y casi nada por abajo float ehUp = 0.3 + 0.7 * saturate( normal.y * 0.6 + 0.55 ); // las caras que miran hacia arriba (suelos) se ven casi rasantes desde la cámara 2.5D: // sin esto todo el suelo se convertía en una franja de borde que el bloom difuminaba. ehUp *= 1.0 - 0.85 * smoothstep( 0.55, 0.9, normal.y ); outgoingLight += uRimColor * ( uRim * ehF * ehUp ) * ( 0.3 + 0.7 * diffuseColor.rgb ); outgoingLight += totalEmissiveRadiance * 0.6; } `; export class ToonMaterial extends THREE.MeshStandardMaterial { readonly isToonMaterial = true; private ehUniforms = { uRim: { value: 0.5 }, uRimPower: { value: 2.6 } }; /** El map viene premultiplicado (ver ToonOpts.premultipliedMap). Cambiarlo exige needsUpdate. */ premultipliedMap = false; /** Luz de borde 0..1 (se puede animar). */ get rim(): number { return this.ehUniforms.uRim.value; } set rim(v: number) { this.ehUniforms.uRim.value = v; } get rimPower(): number { return this.ehUniforms.uRimPower.value; } set rimPower(v: number) { this.ehUniforms.uRimPower.value = v; } /** 0 mate … 1 muy brillante. */ set gloss(g: number) { this.roughness = glossToRoughness(g); } get gloss(): number { return (0.92 - this.roughness) / 0.64; } onBeforeCompile(shader: THREE.WebGLProgramParametersWithUniforms): void { shader.uniforms.uRim = this.ehUniforms.uRim; shader.uniforms.uRimPower = this.ehUniforms.uRimPower; shader.uniforms.uRimColor = toonGlobals.uRimColor; shader.fragmentShader = shader.fragmentShader .replace('#include ', PARS) .replace('#include ', RIM + '#include '); if (this.premultipliedMap) { shader.fragmentShader = shader.fragmentShader .replace('#include ', MAP_PM) .replace('#include ', EMISSIVE_PM); } } customProgramCacheKey(): string { return this.premultipliedMap ? 'eh-toon-3-pm' : 'eh-toon-3'; } copy(source: this): this { super.copy(source); if (source.ehUniforms && this.ehUniforms) { this.rim = source.rim; this.rimPower = source.rimPower; this.premultipliedMap = source.premultipliedMap; } return this; } } function glossToRoughness(g: number): number { return THREE.MathUtils.clamp(0.92 - g * 0.64, 0.06, 1); } /** Material estándar del juego: plástico suave con volumen. Crea uno nuevo en cada llamada. */ export function toonMaterial(opts: ToonOpts): ToonMaterial { const m = new ToonMaterial({ color: opts.color, emissive: opts.emissive ?? 0x000000, emissiveIntensity: opts.emissiveIntensity ?? 1, roughness: glossToRoughness(opts.gloss ?? 0.6), metalness: 0, map: opts.map ?? null, normalMap: opts.normalMap ?? null, emissiveMap: opts.emissiveMap ?? null, transparent: opts.transparent ?? false, opacity: opts.opacity ?? 1, side: opts.side ?? THREE.FrontSide, alphaTest: opts.alphaTest ?? 0, }); if (opts.fog === false) m.fog = false; if (opts.depthWrite !== undefined) m.depthWrite = opts.depthWrite; m.premultipliedMap = !!opts.premultipliedMap; m.rim = opts.rim ?? 0.5; m.rimPower = opts.rimPower ?? 2.6; return m; } // ───────────────────────────── Sombra de contacto ───────────────────────────── let blobTex: THREE.Texture | null = null; let blobGeo: THREE.PlaneGeometry | null = null; /** * Sombra de contacto barata: disco difuminado tumbado sobre el suelo (plano XZ), de radio `radius`. * Colócalo en la Y del suelo (+0.02) bajo el personaje; escala/opacidad según la altura del salto. */ export function blobShadow(radius = 0.5, opacity = 0.38): THREE.Mesh { if (!blobTex) { const n = 64; const data = new Uint8Array(n * n * 4); for (let y = 0; y < n; y++) { for (let x = 0; x < n; x++) { const d = Math.hypot((x + 0.5) / n - 0.5, (y + 0.5) / n - 0.5) * 2; const a = Math.max(0, 1 - d); const i = (y * n + x) * 4; data[i] = 20; data[i + 1] = 10; data[i + 2] = 50; data[i + 3] = Math.round(255 * a * a * (3 - 2 * a)); } } blobTex = new THREE.DataTexture(data, n, n, THREE.RGBAFormat); blobTex.colorSpace = THREE.SRGBColorSpace; blobTex.magFilter = blobTex.minFilter = THREE.LinearFilter; blobTex.needsUpdate = true; blobTex.userData.shared = true; blobGeo = new THREE.PlaneGeometry(2, 2); blobGeo.rotateX(-Math.PI / 2); blobGeo.userData.shared = true; } const mat = new THREE.MeshBasicMaterial({ map: blobTex, transparent: true, opacity, depthWrite: false, toneMapped: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, }); const mesh = new THREE.Mesh(blobGeo!, mat); mesh.scale.set(radius, 1, radius * 0.7); mesh.renderOrder = 1; return mesh; }