ConvolutionShader.js 1.8 KB

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