ConvolutionShader.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. ( function () {
  2. /**
  3. * Convolution shader
  4. * ported from o3d sample to WebGL / GLSL
  5. * http://o3d.googlecode.com/svn/trunk/samples/convolution.html
  6. */
  7. const ConvolutionShader = {
  8. defines: {
  9. 'KERNEL_SIZE_FLOAT': '25.0',
  10. 'KERNEL_SIZE_INT': '25'
  11. },
  12. uniforms: {
  13. 'tDiffuse': {
  14. value: null
  15. },
  16. 'uImageIncrement': {
  17. value: new THREE.Vector2( 0.001953125, 0.0 )
  18. },
  19. 'cKernel': {
  20. value: []
  21. }
  22. },
  23. vertexShader: `uniform vec2 uImageIncrement;
  24. varying vec2 vUv;
  25. void main() {
  26. vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;
  27. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  28. }`,
  29. fragmentShader: `uniform float cKernel[ KERNEL_SIZE_INT ];
  30. uniform sampler2D tDiffuse;
  31. uniform vec2 uImageIncrement;
  32. varying vec2 vUv;
  33. void main() {
  34. vec2 imageCoord = vUv;
  35. vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );
  36. for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {
  37. sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];
  38. imageCoord += uImageIncrement;
  39. }
  40. gl_FragColor = sum;
  41. }`,
  42. buildKernel: function ( sigma ) {
  43. // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
  44. const kMaxKernelSize = 25;
  45. let kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
  46. if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
  47. const halfWidth = ( kernelSize - 1 ) * 0.5;
  48. const values = new Array( kernelSize );
  49. let sum = 0.0;
  50. for ( let i = 0; i < kernelSize; ++ i ) {
  51. values[ i ] = gauss( i - halfWidth, sigma );
  52. sum += values[ i ];
  53. } // normalize the kernel
  54. for ( let i = 0; i < kernelSize; ++ i ) values[ i ] /= sum;
  55. return values;
  56. }
  57. };
  58. function gauss( x, sigma ) {
  59. return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
  60. }
  61. THREE.ConvolutionShader = ConvolutionShader;
  62. } )();