Reflector.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import {
  2. Color,
  3. Matrix4,
  4. Mesh,
  5. Plane,
  6. ShaderMaterial,
  7. UniformsUtils,
  8. Vector3,
  9. Vector4,
  10. WebGLRenderTarget,
  11. HalfFloatType
  12. } from 'three';
  13. /**
  14. * Can be used to create a flat, reflective surface like a mirror.
  15. *
  16. * Note that this class can only be used with {@link WebGLRenderer}.
  17. * When using {@link WebGPURenderer}, use {@link ReflectorNode}.
  18. *
  19. * ```js
  20. * const geometry = new THREE.PlaneGeometry( 100, 100 );
  21. *
  22. * const reflector = new Reflector( geometry, {
  23. * clipBias: 0.003,
  24. * textureWidth: window.innerWidth * window.devicePixelRatio,
  25. * textureHeight: window.innerHeight * window.devicePixelRatio,
  26. * color: 0xc1cbcb
  27. * } );
  28. *
  29. * scene.add( reflector );
  30. * ```
  31. *
  32. * @augments Mesh
  33. * @three_import import { Reflector } from 'three/addons/objects/Reflector.js';
  34. */
  35. class Reflector extends Mesh {
  36. /**
  37. * Constructs a new reflector.
  38. *
  39. * @param {BufferGeometry} geometry - The reflector's geometry.
  40. * @param {Reflector~Options} [options] - The configuration options.
  41. */
  42. constructor( geometry, options = {} ) {
  43. super( geometry );
  44. /**
  45. * This flag can be used for type testing.
  46. *
  47. * @type {boolean}
  48. * @readonly
  49. * @default true
  50. */
  51. this.isReflector = true;
  52. this.type = 'Reflector';
  53. /**
  54. * Whether to force an update, no matter if the reflector
  55. * is in view or not.
  56. *
  57. * @type {boolean}
  58. * @default false
  59. */
  60. this.forceUpdate = false;
  61. /**
  62. * Weak map for managing reflection cameras.
  63. *
  64. * @private
  65. * @type {WeakMap<Camera, Camera>}
  66. */
  67. this._reflectionCameras = new WeakMap();
  68. const scope = this;
  69. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
  70. const textureWidth = options.textureWidth || 512;
  71. const textureHeight = options.textureHeight || 512;
  72. const clipBias = options.clipBias || 0;
  73. const shader = options.shader || Reflector.ReflectorShader;
  74. const multisample = ( options.multisample !== undefined ) ? options.multisample : 4;
  75. //
  76. const reflectorPlane = new Plane();
  77. const normal = new Vector3();
  78. const reflectorWorldPosition = new Vector3();
  79. const cameraWorldPosition = new Vector3();
  80. const rotationMatrix = new Matrix4();
  81. const lookAtPosition = new Vector3( 0, 0, - 1 );
  82. const clipPlane = new Vector4();
  83. const view = new Vector3();
  84. const target = new Vector3();
  85. const q = new Vector4();
  86. const textureMatrix = new Matrix4();
  87. const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, { samples: multisample, type: HalfFloatType } );
  88. const material = new ShaderMaterial( {
  89. name: ( shader.name !== undefined ) ? shader.name : 'unspecified',
  90. uniforms: UniformsUtils.clone( shader.uniforms ),
  91. fragmentShader: shader.fragmentShader,
  92. vertexShader: shader.vertexShader
  93. } );
  94. material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
  95. material.uniforms[ 'color' ].value = color;
  96. material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  97. this.material = material;
  98. this.onBeforeRender = function ( renderer, scene, camera ) {
  99. const reflectionCamera = this._getReflectionCamera( camera );
  100. reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  101. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  102. rotationMatrix.extractRotation( scope.matrixWorld );
  103. normal.set( 0, 0, 1 );
  104. normal.applyMatrix4( rotationMatrix );
  105. view.subVectors( reflectorWorldPosition, cameraWorldPosition );
  106. // Avoid rendering when reflector is facing away unless forcing an update
  107. const isFacingAway = view.dot( normal ) > 0;
  108. if ( isFacingAway === true && this.forceUpdate === false ) return;
  109. view.reflect( normal ).negate();
  110. view.add( reflectorWorldPosition );
  111. rotationMatrix.extractRotation( camera.matrixWorld );
  112. lookAtPosition.set( 0, 0, - 1 );
  113. lookAtPosition.applyMatrix4( rotationMatrix );
  114. lookAtPosition.add( cameraWorldPosition );
  115. target.subVectors( reflectorWorldPosition, lookAtPosition );
  116. target.reflect( normal ).negate();
  117. target.add( reflectorWorldPosition );
  118. reflectionCamera.position.copy( view );
  119. reflectionCamera.up.set( 0, 1, 0 );
  120. reflectionCamera.up.applyMatrix4( rotationMatrix );
  121. reflectionCamera.up.reflect( normal );
  122. reflectionCamera.lookAt( target );
  123. reflectionCamera.far = camera.far; // Used in WebGLBackground
  124. reflectionCamera.updateMatrixWorld();
  125. reflectionCamera.projectionMatrix.copy( camera.projectionMatrix );
  126. // Update the texture matrix
  127. textureMatrix.set(
  128. 0.5, 0.0, 0.0, 0.5,
  129. 0.0, 0.5, 0.0, 0.5,
  130. 0.0, 0.0, 0.5, 0.5,
  131. 0.0, 0.0, 0.0, 1.0
  132. );
  133. textureMatrix.multiply( reflectionCamera.projectionMatrix );
  134. textureMatrix.multiply( reflectionCamera.matrixWorldInverse );
  135. textureMatrix.multiply( scope.matrixWorld );
  136. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  137. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  138. reflectorPlane.setFromNormalAndCoplanarPoint( normal, reflectorWorldPosition );
  139. reflectorPlane.applyMatrix4( reflectionCamera.matrixWorldInverse );
  140. clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant );
  141. const projectionMatrix = reflectionCamera.projectionMatrix;
  142. if ( reflectionCamera.isOrthographicCamera ) {
  143. q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  144. q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  145. q.z = - camera.far; // actual view-space z at the far plane, no normalization needed
  146. q.w = 1.0; // w_clip = 1 in orthographic (no perspective division)
  147. } else {
  148. q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  149. q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  150. q.z = - 1.0;
  151. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  152. }
  153. // Calculate the scaled plane vector
  154. clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );
  155. // Replacing the third row of the projection matrix
  156. projectionMatrix.elements[ 2 ] = clipPlane.x;
  157. projectionMatrix.elements[ 6 ] = clipPlane.y;
  158. if ( reflectionCamera.isOrthographicCamera ) {
  159. // For orthographic cameras, w_clip = 1 always (no perspective division),
  160. // so the -1 near-plane offset must go into the constant term (elements[14])
  161. // rather than the z coefficient (elements[10]).
  162. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  163. projectionMatrix.elements[ 14 ] = clipPlane.w - 1.0;
  164. } else {
  165. projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
  166. projectionMatrix.elements[ 14 ] = clipPlane.w;
  167. }
  168. // Render
  169. scope.visible = false;
  170. const currentRenderTarget = renderer.getRenderTarget();
  171. const currentXrEnabled = renderer.xr.enabled;
  172. const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  173. renderer.xr.enabled = false; // Avoid camera modification
  174. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  175. renderer.setRenderTarget( renderTarget );
  176. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  177. if ( renderer.autoClear === false ) renderer.clear();
  178. renderer.render( scene, reflectionCamera );
  179. renderer.xr.enabled = currentXrEnabled;
  180. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  181. renderer.setRenderTarget( currentRenderTarget );
  182. // Restore viewport
  183. const viewport = camera.viewport;
  184. if ( viewport !== undefined ) {
  185. renderer.state.viewport( viewport );
  186. }
  187. scope.visible = true;
  188. this.forceUpdate = false;
  189. };
  190. /**
  191. * Returns the reflector's internal render target.
  192. *
  193. * @return {WebGLRenderTarget} The internal render target
  194. */
  195. this.getRenderTarget = function () {
  196. return renderTarget;
  197. };
  198. /**
  199. * Frees the GPU-related resources allocated by this instance. Call this
  200. * method whenever this instance is no longer used in your app.
  201. */
  202. this.dispose = function () {
  203. renderTarget.dispose();
  204. scope.material.dispose();
  205. };
  206. /**
  207. * Returns a reflection camera for the given camera. The reflection camera is used to
  208. * render the scene from the reflector's view so correct reflections can be produced.
  209. *
  210. * @private
  211. * @param {Camera} camera - The scene's camera.
  212. * @return {Camera} The corresponding reflection camera.
  213. */
  214. this._getReflectionCamera = function ( camera ) {
  215. let reflectionCamera = this._reflectionCameras.get( camera );
  216. if ( reflectionCamera === undefined ) {
  217. reflectionCamera = camera.clone();
  218. this._reflectionCameras.set( camera, reflectionCamera );
  219. }
  220. return reflectionCamera;
  221. };
  222. }
  223. }
  224. Reflector.ReflectorShader = {
  225. name: 'ReflectorShader',
  226. uniforms: {
  227. 'color': {
  228. value: null
  229. },
  230. 'tDiffuse': {
  231. value: null
  232. },
  233. 'textureMatrix': {
  234. value: null
  235. }
  236. },
  237. vertexShader: /* glsl */`
  238. uniform mat4 textureMatrix;
  239. varying vec4 vUv;
  240. #include <common>
  241. #include <logdepthbuf_pars_vertex>
  242. void main() {
  243. vUv = textureMatrix * vec4( position, 1.0 );
  244. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  245. #include <logdepthbuf_vertex>
  246. }`,
  247. fragmentShader: /* glsl */`
  248. uniform vec3 color;
  249. uniform sampler2D tDiffuse;
  250. varying vec4 vUv;
  251. #include <logdepthbuf_pars_fragment>
  252. float blendOverlay( float base, float blend ) {
  253. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  254. }
  255. vec3 blendOverlay( vec3 base, vec3 blend ) {
  256. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
  257. }
  258. void main() {
  259. #include <logdepthbuf_fragment>
  260. vec4 base = texture2DProj( tDiffuse, vUv );
  261. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  262. #include <tonemapping_fragment>
  263. #include <colorspace_fragment>
  264. }`
  265. };
  266. /**
  267. * Constructor options of `Reflector`.
  268. *
  269. * @typedef {Object} Reflector~Options
  270. * @property {number|Color|string} [color=0x7F7F7F] - The reflector's color.
  271. * @property {number} [textureWidth=512] - The texture width. A higher value results in more clear reflections but is also more expensive.
  272. * @property {number} [textureHeight=512] - The texture height. A higher value results in more clear reflections but is also more expensive.
  273. * @property {number} [clipBias=0] - The clip bias.
  274. * @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.
  275. * @property {number} [multisample=4] - How many samples to use for MSAA. `0` disables MSAA.
  276. **/
  277. export { Reflector };
粤ICP备19079148号