SobelOperatorShader.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import {
  2. Vector2
  3. } from '../../../build/three.module.js';
  4. /**
  5. * Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  6. *
  7. * As mentioned in the video the Sobel operator expects a grayscale image as input.
  8. *
  9. */
  10. const SobelOperatorShader = {
  11. uniforms: {
  12. 'tDiffuse': { value: null },
  13. 'resolution': { value: new Vector2() }
  14. },
  15. vertexShader: /* glsl */`
  16. varying vec2 vUv;
  17. void main() {
  18. vUv = uv;
  19. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  20. }`,
  21. fragmentShader: /* glsl */`
  22. uniform sampler2D tDiffuse;
  23. uniform vec2 resolution;
  24. varying vec2 vUv;
  25. void main() {
  26. vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y );
  27. // kernel definition (in glsl matrices are filled in column-major order)
  28. const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  29. const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel
  30. // fetch the 3x3 neighbourhood of a fragment
  31. // first column
  32. float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r;
  33. float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r;
  34. float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r;
  35. // second column
  36. float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r;
  37. float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r;
  38. float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r;
  39. // third column
  40. float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r;
  41. float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r;
  42. float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r;
  43. // gradient value in x direction
  44. float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 +
  45. Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 +
  46. Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2;
  47. // gradient value in y direction
  48. float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 +
  49. Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 +
  50. Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2;
  51. // magnitute of the total gradient
  52. float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) );
  53. gl_FragColor = vec4( vec3( G ), 1 );
  54. }`
  55. };
  56. export { SobelOperatorShader };