Capítulo 822 de 859
A technique for picking and highlighting regions (like countries on a globe) using small id/palette textures instead of heavy per-region 3D geometry, borrowing the idea of "paletted graphics" from older 8-bit systems.
Material.onBeforeCompile: used to inject custom GLSL into three.js's default shader (via string replacement of internal chunks like <color_fragment>) so the material can sample the index texture, look up a palette color, and blend it with diffuseColor.DataTexture: used to build the palette itself from raw RGBA byte data, sized to hold one color per region plus a background entry.material.onBeforeCompile = function (shader) {
shader.fragmentShader = shader.fragmentShader
.replace("#include <common>", `
#include <common>
uniform sampler2D indexTexture;
uniform sampler2D paletteTexture;
uniform float paletteTextureWidth;
`)
.replace("#include <color_fragment>", `
#include <color_fragment>
{
vec4 indexColor = texture2D(indexTexture, vUv);
float index = indexColor.r * 255.0 + indexColor.g * 255.0 * 256.0;
vec2 paletteUV = vec2((index + 0.5) / paletteTextureWidth, 0.5);
vec4 paletteColor = texture2D(paletteTexture, paletteUV);
diffuseColor.rgb = paletteColor.rgb - diffuseColor.rgb;
}
`);
};
Material.onBeforeCompile is the mechanism for injecting custom shader logic into three.js's built-in materials while keeping their standard lighting/shading pipeline.