SSRShader.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import {
  2. Matrix4,
  3. Vector2
  4. } from 'three';
  5. /**
  6. * A collection of shaders used for SSR.
  7. *
  8. * References:
  9. * - [3D Game Shaders For Beginners, Screen Space Reflection (SSR)]{@link https://lettier.github.io/3d-game-shaders-for-beginners/screen-space-reflection.html}.
  10. *
  11. * @module SSRShader
  12. * @three_import import * as SSRShader from 'three/addons/shaders/SSRShader.js';
  13. */
  14. /**
  15. * SSR shader.
  16. *
  17. * @constant
  18. * @type {ShaderMaterial~Shader}
  19. */
  20. const SSRShader = {
  21. name: 'SSRShader',
  22. defines: {
  23. MAX_STEP: 0,
  24. PERSPECTIVE_CAMERA: true,
  25. DISTANCE_ATTENUATION: true,
  26. FRESNEL: true,
  27. INFINITE_THICK: false,
  28. SELECTIVE: false,
  29. },
  30. uniforms: {
  31. 'tDiffuse': { value: null },
  32. 'tNormal': { value: null },
  33. 'tMetalness': { value: null },
  34. 'tDepth': { value: null },
  35. 'cameraNear': { value: null },
  36. 'cameraFar': { value: null },
  37. 'resolution': { value: new Vector2() },
  38. 'cameraProjectionMatrix': { value: new Matrix4() },
  39. 'cameraInverseProjectionMatrix': { value: new Matrix4() },
  40. 'opacity': { value: .5 },
  41. 'maxDistance': { value: 180 },
  42. 'cameraRange': { value: 0 },
  43. 'thickness': { value: .018 }
  44. },
  45. vertexShader: /* glsl */`
  46. varying vec2 vUv;
  47. void main() {
  48. vUv = uv;
  49. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  50. }
  51. `,
  52. fragmentShader: /* glsl */`
  53. // precision highp float;
  54. precision highp sampler2D;
  55. varying vec2 vUv;
  56. uniform sampler2D tDepth;
  57. uniform sampler2D tNormal;
  58. uniform sampler2D tMetalness;
  59. uniform sampler2D tDiffuse;
  60. uniform float cameraRange;
  61. uniform vec2 resolution;
  62. uniform float opacity;
  63. uniform float cameraNear;
  64. uniform float cameraFar;
  65. uniform float maxDistance;
  66. uniform float thickness;
  67. uniform mat4 cameraProjectionMatrix;
  68. uniform mat4 cameraInverseProjectionMatrix;
  69. #include <packing>
  70. float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) {
  71. //x0: point, x1: linePointA, x2: linePointB
  72. //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
  73. return length(cross(x0-x1,x0-x2))/length(x2-x1);
  74. }
  75. float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){
  76. // https://mathworld.wolfram.com/Point-PlaneDistance.html
  77. //// https://en.wikipedia.org/wiki/Plane_(geometry)
  78. //// http://paulbourke.net/geometry/pointlineplane/
  79. float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z;
  80. float x0=point.x,y0=point.y,z0=point.z;
  81. float x=planePoint.x,y=planePoint.y,z=planePoint.z;
  82. float d=-(a*x+b*y+c*z);
  83. float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c);
  84. return distance;
  85. }
  86. float getDepth( const in vec2 uv ) {
  87. return texture2D( tDepth, uv ).x;
  88. }
  89. float getViewZ( const in float depth ) {
  90. #ifdef PERSPECTIVE_CAMERA
  91. return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
  92. #else
  93. return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
  94. #endif
  95. }
  96. vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
  97. vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
  98. clipPosition *= clipW; //clip
  99. return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view
  100. }
  101. vec3 getViewNormal( const in vec2 uv ) {
  102. return unpackRGBToNormal( texture2D( tNormal, uv ).xyz );
  103. }
  104. vec2 viewPositionToXY(vec3 viewPosition){
  105. vec2 xy;
  106. vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1);
  107. xy=clip.xy;//clip
  108. float clipW=clip.w;
  109. xy/=clipW;//NDC
  110. xy=(xy+1.)/2.;//uv
  111. xy*=resolution;//screen
  112. return xy;
  113. }
  114. void main(){
  115. #ifdef SELECTIVE
  116. float metalness=texture2D(tMetalness,vUv).r;
  117. if(metalness==0.) return;
  118. #endif
  119. float depth = getDepth( vUv );
  120. float viewZ = getViewZ( depth );
  121. if(-viewZ>=cameraFar) return;
  122. float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3];
  123. vec3 viewPosition=getViewPosition( vUv, depth, clipW );
  124. vec2 d0=gl_FragCoord.xy;
  125. vec2 d1;
  126. vec3 viewNormal=getViewNormal( vUv );
  127. #ifdef PERSPECTIVE_CAMERA
  128. vec3 viewIncidentDir=normalize(viewPosition);
  129. vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
  130. #else
  131. vec3 viewIncidentDir=vec3(0,0,-1);
  132. vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
  133. #endif
  134. float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal);
  135. // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html
  136. // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta)
  137. // maxDistance/maxReflectRayLen=cos(theta)
  138. // maxDistance/maxReflectRayLen==dot(a,b)
  139. // maxReflectRayLen==maxDistance/dot(a,b)
  140. vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen;
  141. #ifdef PERSPECTIVE_CAMERA
  142. if(d1viewPosition.z>-cameraNear){
  143. //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx
  144. float t=(-cameraNear-viewPosition.z)/viewReflectDir.z;
  145. d1viewPosition=viewPosition+viewReflectDir*t;
  146. }
  147. #endif
  148. d1=viewPositionToXY(d1viewPosition);
  149. float totalLen=length(d1-d0);
  150. float xLen=d1.x-d0.x;
  151. float yLen=d1.y-d0.y;
  152. float totalStep=max(abs(xLen),abs(yLen));
  153. float xSpan=xLen/totalStep;
  154. float ySpan=yLen/totalStep;
  155. for(float i=0.;i<float(MAX_STEP);i++){
  156. if(i>=totalStep) break;
  157. vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan);
  158. if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break;
  159. float s=length(xy-d0)/totalLen;
  160. vec2 uv=xy/resolution;
  161. float d = getDepth(uv);
  162. float vZ = getViewZ( d );
  163. if(-vZ>=cameraFar) continue;
  164. float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3];
  165. vec3 vP=getViewPosition( uv, d, cW );
  166. #ifdef PERSPECTIVE_CAMERA
  167. // https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf
  168. float recipVPZ=1./viewPosition.z;
  169. float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ));
  170. #else
  171. float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z);
  172. #endif
  173. // if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang.
  174. // https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164
  175. if(viewReflectRayZ<=vZ){
  176. bool hit;
  177. #ifdef INFINITE_THICK
  178. hit=true;
  179. #else
  180. float away=pointToLineDistance(vP,viewPosition,d1viewPosition);
  181. float minThickness;
  182. vec2 xyNeighbor=xy;
  183. xyNeighbor.x+=1.;
  184. vec2 uvNeighbor=xyNeighbor/resolution;
  185. vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW);
  186. minThickness=vPNeighbor.x-vP.x;
  187. minThickness*=3.;
  188. float tk=max(minThickness,thickness);
  189. hit=away<=tk;
  190. #endif
  191. if(hit){
  192. vec3 vN=getViewNormal( uv );
  193. if(dot(viewReflectDir,vN)>=0.) continue;
  194. float distance=pointPlaneDistance(vP,viewPosition,viewNormal);
  195. if(distance>maxDistance) break;
  196. float op=opacity;
  197. #ifdef DISTANCE_ATTENUATION
  198. float ratio=1.-(distance/maxDistance);
  199. float attenuation=ratio*ratio;
  200. op=opacity*attenuation;
  201. #endif
  202. #ifdef FRESNEL
  203. float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.;
  204. op*=fresnelCoe;
  205. #endif
  206. vec4 reflectColor=texture2D(tDiffuse,uv);
  207. gl_FragColor.xyz=reflectColor.xyz;
  208. gl_FragColor.a=op;
  209. break;
  210. }
  211. }
  212. }
  213. }
  214. `
  215. };
  216. /**
  217. * SSR Depth shader.
  218. *
  219. * @constant
  220. * @type {ShaderMaterial~Shader}
  221. */
  222. const SSRDepthShader = {
  223. name: 'SSRDepthShader',
  224. defines: {
  225. 'PERSPECTIVE_CAMERA': 1
  226. },
  227. uniforms: {
  228. 'tDepth': { value: null },
  229. 'cameraNear': { value: null },
  230. 'cameraFar': { value: null },
  231. },
  232. vertexShader: /* glsl */`
  233. varying vec2 vUv;
  234. void main() {
  235. vUv = uv;
  236. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  237. }
  238. `,
  239. fragmentShader: /* glsl */`
  240. uniform sampler2D tDepth;
  241. uniform float cameraNear;
  242. uniform float cameraFar;
  243. varying vec2 vUv;
  244. #include <packing>
  245. float getLinearDepth( const in vec2 uv ) {
  246. #if PERSPECTIVE_CAMERA == 1
  247. float fragCoordZ = texture2D( tDepth, uv ).x;
  248. float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
  249. return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  250. #else
  251. return texture2D( tDepth, uv ).x;
  252. #endif
  253. }
  254. void main() {
  255. float depth = getLinearDepth( vUv );
  256. float d = 1.0 - depth;
  257. // d=(d-.999)*1000.;
  258. gl_FragColor = vec4( vec3( d ), 1.0 );
  259. }
  260. `
  261. };
  262. /**
  263. * SSR Blur shader.
  264. *
  265. * @constant
  266. * @type {ShaderMaterial~Shader}
  267. */
  268. const SSRBlurShader = {
  269. name: 'SSRBlurShader',
  270. uniforms: {
  271. 'tDiffuse': { value: null },
  272. 'resolution': { value: new Vector2() },
  273. 'opacity': { value: .5 },
  274. },
  275. vertexShader: /* glsl */`
  276. varying vec2 vUv;
  277. void main() {
  278. vUv = uv;
  279. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  280. }
  281. `,
  282. fragmentShader: /* glsl */`
  283. uniform sampler2D tDiffuse;
  284. uniform vec2 resolution;
  285. varying vec2 vUv;
  286. void main() {
  287. //reverse engineering from PhotoShop blur filter, then change coefficient
  288. vec2 texelSize = ( 1.0 / resolution );
  289. vec4 c=texture2D(tDiffuse,vUv);
  290. vec2 offset;
  291. offset=(vec2(-1,0))*texelSize;
  292. vec4 cl=texture2D(tDiffuse,vUv+offset);
  293. offset=(vec2(1,0))*texelSize;
  294. vec4 cr=texture2D(tDiffuse,vUv+offset);
  295. offset=(vec2(0,-1))*texelSize;
  296. vec4 cb=texture2D(tDiffuse,vUv+offset);
  297. offset=(vec2(0,1))*texelSize;
  298. vec4 ct=texture2D(tDiffuse,vUv+offset);
  299. // float coeCenter=.5;
  300. // float coeSide=.125;
  301. float coeCenter=.2;
  302. float coeSide=.2;
  303. float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide;
  304. vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a;
  305. gl_FragColor=vec4(rgb,a);
  306. }
  307. `
  308. };
  309. export { SSRShader, SSRDepthShader, SSRBlurShader };