ReflectorForSSRPass.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import {
  2. Color,
  3. Matrix4,
  4. Mesh,
  5. PerspectiveCamera,
  6. ShaderMaterial,
  7. UniformsUtils,
  8. Vector2,
  9. Vector3,
  10. WebGLRenderTarget,
  11. DepthTexture,
  12. UnsignedShortType,
  13. NearestFilter,
  14. Plane,
  15. HalfFloatType
  16. } from 'three';
  17. /**
  18. * A special version of {@link Reflector} for usage with {@link SSRPass}.
  19. *
  20. * @augments Mesh
  21. * @three_import import { ReflectorForSSRPass } from 'three/addons/objects/ReflectorForSSRPass.js';
  22. */
  23. class ReflectorForSSRPass extends Mesh {
  24. /**
  25. * Constructs a new reflector.
  26. *
  27. * @param {BufferGeometry} geometry - The reflector's geometry.
  28. * @param {ReflectorForSSRPass~Options} [options] - The configuration options.
  29. */
  30. constructor( geometry, options = {} ) {
  31. super( geometry );
  32. this.isReflectorForSSRPass = true;
  33. this.type = 'ReflectorForSSRPass';
  34. const scope = this;
  35. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  36. const textureWidth = options.textureWidth || 512;
  37. const textureHeight = options.textureHeight || 512;
  38. const clipBias = options.clipBias || 0;
  39. const shader = options.shader || ReflectorForSSRPass.ReflectorShader;
  40. const useDepthTexture = options.useDepthTexture === true;
  41. const yAxis = new Vector3( 0, 1, 0 );
  42. const vecTemp0 = new Vector3();
  43. const vecTemp1 = new Vector3();
  44. //
  45. scope.needsUpdate = false;
  46. scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value;
  47. scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value;
  48. scope.color = color;
  49. scope.resolution = options.resolution || new Vector2( window.innerWidth, window.innerHeight );
  50. scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION;
  51. Object.defineProperty( scope, 'distanceAttenuation', {
  52. get() {
  53. return scope._distanceAttenuation;
  54. },
  55. set( val ) {
  56. if ( scope._distanceAttenuation === val ) return;
  57. scope._distanceAttenuation = val;
  58. scope.material.defines.DISTANCE_ATTENUATION = val;
  59. scope.material.needsUpdate = true;
  60. }
  61. } );
  62. scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL;
  63. Object.defineProperty( scope, 'fresnel', {
  64. get() {
  65. return scope._fresnel;
  66. },
  67. set( val ) {
  68. if ( scope._fresnel === val ) return;
  69. scope._fresnel = val;
  70. scope.material.defines.FRESNEL = val;
  71. scope.material.needsUpdate = true;
  72. }
  73. } );
  74. const normal = new Vector3();
  75. const reflectorWorldPosition = new Vector3();
  76. const cameraWorldPosition = new Vector3();
  77. const rotationMatrix = new Matrix4();
  78. const lookAtPosition = new Vector3( 0, 0, - 1 );
  79. const view = new Vector3();
  80. const target = new Vector3();
  81. const textureMatrix = new Matrix4();
  82. const virtualCamera = new PerspectiveCamera();
  83. let depthTexture;
  84. if ( useDepthTexture ) {
  85. depthTexture = new DepthTexture();
  86. depthTexture.type = UnsignedShortType;
  87. depthTexture.minFilter = NearestFilter;
  88. depthTexture.magFilter = NearestFilter;
  89. }
  90. const parameters = {
  91. depthTexture: useDepthTexture ? depthTexture : null,
  92. type: HalfFloatType
  93. };
  94. const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
  95. const material = new ShaderMaterial( {
  96. name: ( shader.name !== undefined ) ? shader.name : 'unspecified',
  97. transparent: useDepthTexture,
  98. defines: Object.assign( {}, ReflectorForSSRPass.ReflectorShader.defines, {
  99. useDepthTexture
  100. } ),
  101. uniforms: UniformsUtils.clone( shader.uniforms ),
  102. fragmentShader: shader.fragmentShader,
  103. vertexShader: shader.vertexShader
  104. } );
  105. material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
  106. material.uniforms[ 'color' ].value = scope.color;
  107. material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  108. if ( useDepthTexture ) {
  109. material.uniforms[ 'tDepth' ].value = renderTarget.depthTexture;
  110. }
  111. this.material = material;
  112. const globalPlane = new Plane( new Vector3( 0, 1, 0 ), clipBias );
  113. const globalPlanes = [ globalPlane ];
  114. this.doRender = function ( renderer, scene, camera ) {
  115. material.uniforms[ 'maxDistance' ].value = scope.maxDistance;
  116. material.uniforms[ 'color' ].value = scope.color;
  117. material.uniforms[ 'opacity' ].value = scope.opacity;
  118. vecTemp0.copy( camera.position ).normalize();
  119. vecTemp1.copy( vecTemp0 ).reflect( yAxis );
  120. material.uniforms[ 'fresnelCoe' ].value = ( vecTemp0.dot( vecTemp1 ) + 1. ) / 2.; // TODO: Also need to use glsl viewPosition and viewNormal per pixel.
  121. reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  122. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  123. rotationMatrix.extractRotation( scope.matrixWorld );
  124. normal.set( 0, 0, 1 );
  125. normal.applyMatrix4( rotationMatrix );
  126. view.subVectors( reflectorWorldPosition, cameraWorldPosition );
  127. // Avoid rendering when reflector is facing away
  128. if ( view.dot( normal ) > 0 ) return;
  129. view.reflect( normal ).negate();
  130. view.add( reflectorWorldPosition );
  131. rotationMatrix.extractRotation( camera.matrixWorld );
  132. lookAtPosition.set( 0, 0, - 1 );
  133. lookAtPosition.applyMatrix4( rotationMatrix );
  134. lookAtPosition.add( cameraWorldPosition );
  135. target.subVectors( reflectorWorldPosition, lookAtPosition );
  136. target.reflect( normal ).negate();
  137. target.add( reflectorWorldPosition );
  138. virtualCamera.position.copy( view );
  139. virtualCamera.up.set( 0, 1, 0 );
  140. virtualCamera.up.applyMatrix4( rotationMatrix );
  141. virtualCamera.up.reflect( normal );
  142. virtualCamera.lookAt( target );
  143. virtualCamera.far = camera.far; // Used in WebGLBackground
  144. virtualCamera.updateMatrixWorld();
  145. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  146. material.uniforms[ 'virtualCameraNear' ].value = camera.near;
  147. material.uniforms[ 'virtualCameraFar' ].value = camera.far;
  148. material.uniforms[ 'virtualCameraMatrixWorld' ].value = virtualCamera.matrixWorld;
  149. material.uniforms[ 'virtualCameraProjectionMatrix' ].value = camera.projectionMatrix;
  150. material.uniforms[ 'virtualCameraProjectionMatrixInverse' ].value = camera.projectionMatrixInverse;
  151. material.uniforms[ 'resolution' ].value = scope.resolution;
  152. // Update the texture matrix
  153. textureMatrix.set(
  154. 0.5, 0.0, 0.0, 0.5,
  155. 0.0, 0.5, 0.0, 0.5,
  156. 0.0, 0.0, 0.5, 0.5,
  157. 0.0, 0.0, 0.0, 1.0
  158. );
  159. textureMatrix.multiply( virtualCamera.projectionMatrix );
  160. textureMatrix.multiply( virtualCamera.matrixWorldInverse );
  161. textureMatrix.multiply( scope.matrixWorld );
  162. // scope.visible = false;
  163. const currentRenderTarget = renderer.getRenderTarget();
  164. const currentXrEnabled = renderer.xr.enabled;
  165. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  166. const currentClippingPlanes = renderer.clippingPlanes;
  167. renderer.xr.enabled = false; // Avoid camera modification
  168. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  169. renderer.clippingPlanes = globalPlanes;
  170. renderer.setRenderTarget( renderTarget );
  171. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  172. if ( renderer.autoClear === false ) renderer.clear();
  173. renderer.render( scene, virtualCamera );
  174. renderer.xr.enabled = currentXrEnabled;
  175. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  176. renderer.clippingPlanes = currentClippingPlanes;
  177. renderer.setRenderTarget( currentRenderTarget );
  178. // Restore viewport
  179. const viewport = camera.viewport;
  180. if ( viewport !== undefined ) {
  181. renderer.state.viewport( viewport );
  182. }
  183. // scope.visible = true;
  184. };
  185. /**
  186. * Returns the reflector's internal render target.
  187. *
  188. * @return {WebGLRenderTarget} The internal render target
  189. */
  190. this.getRenderTarget = function () {
  191. return renderTarget;
  192. };
  193. /**
  194. * Frees the GPU-related resources allocated by this instance. Call this
  195. * method whenever this instance is no longer used in your app.
  196. */
  197. this.dispose = function () {
  198. renderTarget.dispose();
  199. scope.material.dispose();
  200. };
  201. }
  202. }
  203. ReflectorForSSRPass.ReflectorShader = {
  204. name: 'ReflectorShader',
  205. defines: {
  206. DISTANCE_ATTENUATION: true,
  207. FRESNEL: true,
  208. },
  209. uniforms: {
  210. color: { value: null },
  211. tDiffuse: { value: null },
  212. tDepth: { value: null },
  213. textureMatrix: { value: new Matrix4() },
  214. maxDistance: { value: 180 },
  215. opacity: { value: 0.5 },
  216. fresnelCoe: { value: null },
  217. virtualCameraNear: { value: null },
  218. virtualCameraFar: { value: null },
  219. virtualCameraProjectionMatrix: { value: new Matrix4() },
  220. virtualCameraMatrixWorld: { value: new Matrix4() },
  221. virtualCameraProjectionMatrixInverse: { value: new Matrix4() },
  222. resolution: { value: new Vector2() },
  223. },
  224. vertexShader: /* glsl */`
  225. uniform mat4 textureMatrix;
  226. varying vec4 vUv;
  227. void main() {
  228. vUv = textureMatrix * vec4( position, 1.0 );
  229. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  230. }`,
  231. fragmentShader: /* glsl */`
  232. uniform vec3 color;
  233. uniform sampler2D tDiffuse;
  234. uniform sampler2D tDepth;
  235. uniform float maxDistance;
  236. uniform float opacity;
  237. uniform float fresnelCoe;
  238. uniform float virtualCameraNear;
  239. uniform float virtualCameraFar;
  240. uniform mat4 virtualCameraProjectionMatrix;
  241. uniform mat4 virtualCameraProjectionMatrixInverse;
  242. uniform mat4 virtualCameraMatrixWorld;
  243. uniform vec2 resolution;
  244. varying vec4 vUv;
  245. #include <packing>
  246. float blendOverlay( float base, float blend ) {
  247. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  248. }
  249. vec3 blendOverlay( vec3 base, vec3 blend ) {
  250. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  251. }
  252. float getDepth( const in vec2 uv ) {
  253. return texture2D( tDepth, uv ).x;
  254. }
  255. float getViewZ( const in float depth ) {
  256. return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar );
  257. }
  258. vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
  259. vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
  260. clipPosition *= clipW; //clip
  261. return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view
  262. }
  263. void main() {
  264. vec4 base = texture2DProj( tDiffuse, vUv );
  265. #ifdef useDepthTexture
  266. vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy;
  267. uv.x=1.-uv.x;
  268. float depth = texture2DProj( tDepth, vUv ).r;
  269. float viewZ = getViewZ( depth );
  270. float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3];
  271. vec3 viewPosition=getViewPosition( uv, depth, clipW );
  272. vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz;
  273. if(worldPosition.y>maxDistance) discard;
  274. float op=opacity;
  275. #ifdef DISTANCE_ATTENUATION
  276. float ratio=1.-(worldPosition.y/maxDistance);
  277. float attenuation=ratio*ratio;
  278. op=opacity*attenuation;
  279. #endif
  280. #ifdef FRESNEL
  281. op*=fresnelCoe;
  282. #endif
  283. gl_FragColor = vec4( blendOverlay( base.rgb, color ), op );
  284. #else
  285. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  286. #endif
  287. }
  288. `,
  289. };
  290. /**
  291. * Constructor options of `ReflectorForSSRPass`.
  292. *
  293. * @typedef {Object} ReflectorForSSRPass~Options
  294. * @property {number|Color|string} [color=0x7F7F7F] - The reflector's color.
  295. * @property {number} [textureWidth=512] - The texture width. A higher value results in more clear reflections but is also more expensive.
  296. * @property {number} [textureHeight=512] - The texture height. A higher value results in more clear reflections but is also more expensive.
  297. * @property {number} [clipBias=0] - The clip bias.
  298. * @property {Object} [shader] - Can be used to pass in a custom shader that defines how the reflective view is projected onto the reflector's geometry.
  299. * @property {boolean} [useDepthTexture=true] - Whether to store depth values in a texture or not.
  300. **/
  301. export { ReflectorForSSRPass };