Skip to content

Instantly share code, notes, and snippets.

@RaheelYawar
Created June 22, 2018 08:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaheelYawar/05e4f23a5ff930227f62d88963041668 to your computer and use it in GitHub Desktop.
Save RaheelYawar/05e4f23a5ff930227f62d88963041668 to your computer and use it in GitHub Desktop.
Three.js (GLSL) basic bloom shader
// THREEjs build-in uniforms and attributes (Fragment)
// uniform mat4 viewMatrix - camera.matrixWorldInverse
// uniform vec3 cameraPosition - camera position in world space
varying vec2 vUv;
uniform sampler2D albedo;
void main() {
vec4 col = vec4(0);
// Current texture coordinate
vec2 texel = vUv;
vec4 pixel = vec4(texture2D(albedo, texel));
// Mean spread value
float pixelWidth = 0.1;
float pixelHeight = 0.1;
// Dim factor
float dim = 0.75;
if (pixel.a < 1.0) {
// Glow is based on the alpha value
float glow = pixel.a * ((pixelWidth + pixelHeight) / 2.0);
vec4 bloom = vec4(0); // The vector to contain the new, "bloomed" colour values
// Apply a horrible version of "mean filter"
// Horrible because GLSL needs constants for loop initializations
bloom += (texture2D(albedo, vec2(texel.x, texel.y)) - dim);
bloom += (texture2D(albedo, vec2(texel.x - glow, texel.y - glow)) - dim);
bloom += (texture2D(albedo, vec2(texel.x + glow, texel.y + glow)) - dim);
bloom += (texture2D(albedo, vec2(texel.x + glow, texel.y - glow)) - dim);
bloom += (texture2D(albedo, vec2(texel.x - glow, texel.y + glow)) - dim);
bloom += (texture2D(albedo, vec2(texel.x + glow, texel.y)) - dim);
bloom += (texture2D(albedo, vec2(texel.x - glow, texel.y)) - dim);
bloom += (texture2D(albedo, vec2(texel.x, texel.y + glow)) - dim);
bloom += (texture2D(albedo, vec2(texel.x, texel.y - glow)) - dim);
// Clamp the value between a 0.0 to 1.0 range
bloom = clamp(bloom / 9.0, 0.0, 1.0);
col = pixel + bloom;
} else {
col = vec4(pixel.rgb, 1.0);
}
gl_FragColor = col;
}
// THREEjs build-in uniforms and attributes (Vertex)
// uniform mat4 modelMatrix - object.matrixWorld
// uniform mat4 modelViewMatrix - camera.matrixWorldInverse * object.matrixWorld
// uniform mat4 projectionMatrix - camera.projectionMatrix
// uniform mat4 viewMatrix - camera.matrixWorldInverse
// uniform mat3 normalMatrix - inverse transpose of modelViewMatrix
// uniform vec3 cameraPosition - camera position in world space
// attribute vec3 position - vertex position
// attribute vec3 normal - vertex normal
// attribute vec2 uv - uv
// attribute vec2 uv2 - uv2
varying vec2 vUv;
void main()
{
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment