ConvolutionShader.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. console.warn( "THREE.ConvolutionShader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  2. /**
  3. * Convolution shader
  4. * ported from o3d sample to WebGL / GLSL
  5. * http://o3d.googlecode.com/svn/trunk/samples/convolution.html
  6. */
  7. THREE.ConvolutionShader = {
  8. defines: {
  9. "KERNEL_SIZE_FLOAT": "25.0",
  10. "KERNEL_SIZE_INT": "25"
  11. },
  12. uniforms: {
  13. "tDiffuse": { value: null },
  14. "uImageIncrement": { value: new THREE.Vector2( 0.001953125, 0.0 ) },
  15. "cKernel": { value: [] }
  16. },
  17. vertexShader: [
  18. "uniform vec2 uImageIncrement;",
  19. "varying vec2 vUv;",
  20. "void main() {",
  21. " vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;",
  22. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  23. "}"
  24. ].join( "\n" ),
  25. fragmentShader: [
  26. "uniform float cKernel[ KERNEL_SIZE_INT ];",
  27. "uniform sampler2D tDiffuse;",
  28. "uniform vec2 uImageIncrement;",
  29. "varying vec2 vUv;",
  30. "void main() {",
  31. " vec2 imageCoord = vUv;",
  32. " vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );",
  33. " for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {",
  34. " sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];",
  35. " imageCoord += uImageIncrement;",
  36. " }",
  37. " gl_FragColor = sum;",
  38. "}"
  39. ].join( "\n" ),
  40. buildKernel: function ( sigma ) {
  41. // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
  42. function gauss( x, sigma ) {
  43. return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
  44. }
  45. var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
  46. if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
  47. halfWidth = ( kernelSize - 1 ) * 0.5;
  48. values = new Array( kernelSize );
  49. sum = 0.0;
  50. for ( i = 0; i < kernelSize; ++ i ) {
  51. values[ i ] = gauss( i - halfWidth, sigma );
  52. sum += values[ i ];
  53. }
  54. // normalize the kernel
  55. for ( i = 0; i < kernelSize; ++ i ) values[ i ] /= sum;
  56. return values;
  57. }
  58. };