GLSL shader example
3×3 Gaussian Blur Shader
The 3×3 kernel uses products of 1,2,1 weights summing to 16. The three columns show source, mean blur and Gaussian blur; the slider changes tap spacing.
Live example
Edit the code and the preview updates as you type.
What to observe
3×3 Gaussian Blur Shader.
Mechanism
The 3×3 kernel uses products of 1,2,1 weights summing to 16. The left, middle and right show original, mean blur and Gaussian blur; the slider changes tap spacing.
The controlling code
vec2 px=vec2(1.+u_parameter*5.)/256.;vec3 sum=vec3(0.),mean=vec3(0.);for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++){float w=(x==0?2.:1.)*(y==0?2.:1.);vec3 sampleColor=texture2D(u_texture,uv+vec2(float(x),float(y))*px).rgb;sum+=sampleColor*w;mean+=sampleColor;}c=uv.x<.3333?texture2D(u_texture,uv).rgb:uv.x<.6667?mean/9.:sum/16.;
Experiment
Move u_parameter from 0 to 1 to increase tap spacing (1.+u_parameter*5.)/256.. Compare the unchanged left third, equal-weight middle third and center-weighted Gaussian right third, especially around the GLSL letters.
Debugging and cost
The loop shares nine texture reads between the mean and weighted sums; their divisors are 9 and 16. Replace only sum/16. with sum/9. to make the Gaussian third too bright, demonstrating why weights need their own normalization.