ConvolutionShader.js 1.8 KB

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