| 1 |
// Adapted from: |
| 2 |
// http://callumhay.blogspot.com/2010/09/gaussian-blur-shader-glsl.html |
| 3 |
/* |
| 4 |
https://github.com/genekogan/Processing-Shader-Examples |
| 5 |
TextureShaders/data/blur.glsl |
| 6 |
*/ |
| 7 |
|
| 8 |
#ifdef GL_ES |
| 9 |
precision mediump float; |
| 10 |
precision mediump int; |
| 11 |
#endif |
| 12 |
|
| 13 |
#define PROCESSING_TEXTURE_SHADER |
| 14 |
|
| 15 |
varying vec4 vertTexCoord; |
| 16 |
uniform sampler2D texture; |
| 17 |
uniform int blurSize; |
| 18 |
uniform int horizontalPass; // 0 or 1 to indicate vertical or horizontal pass |
| 19 |
uniform float sigma; // The sigma value for the gaussian function: higher value means more blur |
| 20 |
// A good value for 9x9 is around 3 to 5 |
| 21 |
// A good value for 7x7 is around 2.5 to 4 |
| 22 |
// A good value for 5x5 is around 2 to 3.5 |
| 23 |
// ... play around with this based on what you need :) |
| 24 |
|
| 25 |
//const vec2 texOffset = vec2(1.0, 1.0); |
| 26 |
uniform vec2 texOffset; |
| 27 |
const float PI = 3.14159265; |
| 28 |
|
| 29 |
void main() { |
| 30 |
vec2 p = vertTexCoord.st; |
| 31 |
float numBlurPixelsPerSide = float(blurSize / 2); |
| 32 |
|
| 33 |
// Incremental Gaussian Coefficent Calculation (See GPU Gems 3 pp. 877 - 889) |
| 34 |
vec3 incrementalGaussian; |
| 35 |
incrementalGaussian.x = 1.0 / (sqrt(2.0 * PI) * sigma); |
| 36 |
incrementalGaussian.y = exp(-0.5 / (sigma * sigma)); |
| 37 |
incrementalGaussian.z = incrementalGaussian.y * incrementalGaussian.y; |
| 38 |
|
| 39 |
vec4 avgValue = vec4(0.0, 0.0, 0.0, 0.0); |
| 40 |
float coefficientSum = 0.0; |
| 41 |
|
| 42 |
// Take the central sample first... |
| 43 |
avgValue += texture2D(texture, p) * incrementalGaussian.x; |
| 44 |
coefficientSum += incrementalGaussian.x; |
| 45 |
incrementalGaussian.xy *= incrementalGaussian.yz; |
| 46 |
|
| 47 |
// Go through the remaining 8 vertical samples (4 on each side of the center) |
| 48 |
for (float i = 1.0; i <= numBlurPixelsPerSide; i++) { |
| 49 |
avgValue += texture2D(texture, p - i * texOffset) * incrementalGaussian.x; |
| 50 |
avgValue += texture2D(texture, p + i * texOffset) * incrementalGaussian.x; |
| 51 |
coefficientSum += 2.0 * incrementalGaussian.x; |
| 52 |
incrementalGaussian.xy *= incrementalGaussian.yz; |
| 53 |
} |
| 54 |
|
| 55 |
gl_FragColor = avgValue / coefficientSum; |
| 56 |
} |