webgl_shadow_contact.html 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - contact shadows</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #fff;
  11. color: #000;
  12. }
  13. a {
  14. color: #08f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - contact shadows
  21. </div>
  22. <!-- Import maps polyfill -->
  23. <!-- Remove this when import maps will be widely supported -->
  24. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  25. <script type="importmap">
  26. {
  27. "imports": {
  28. "three": "../build/three.module.js",
  29. "three/addons/": "./jsm/"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  36. import Stats from 'three/addons/libs/stats.module.js';
  37. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  38. import { HorizontalBlurShader } from 'three/addons/shaders/HorizontalBlurShader.js';
  39. import { VerticalBlurShader } from 'three/addons/shaders/VerticalBlurShader.js';
  40. let camera, scene, renderer, stats, gui;
  41. const meshes = [];
  42. const PLANE_WIDTH = 2.5;
  43. const PLANE_HEIGHT = 2.5;
  44. const CAMERA_HEIGHT = 0.3;
  45. const state = {
  46. shadow: {
  47. blur: 3.5,
  48. darkness: 1,
  49. opacity: 1,
  50. },
  51. plane: {
  52. color: '#ffffff',
  53. opacity: 1,
  54. },
  55. showWireframe: false,
  56. };
  57. let shadowGroup, renderTarget, renderTargetBlur, shadowCamera, cameraHelper, depthMaterial, horizontalBlurMaterial, verticalBlurMaterial;
  58. let plane, blurPlane, fillPlane;
  59. init();
  60. animate();
  61. function init() {
  62. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 100 );
  63. camera.position.set( 0.5, 1, 2 );
  64. scene = new THREE.Scene();
  65. scene.background = new THREE.Color( 0xffffff );
  66. stats = new Stats();
  67. document.body.appendChild( stats.dom );
  68. window.addEventListener( 'resize', onWindowResize );
  69. // add the example meshes
  70. const geometries = [
  71. new THREE.BoxGeometry( 0.4, 0.4, 0.4 ),
  72. new THREE.IcosahedronGeometry( 0.3 ),
  73. new THREE.TorusKnotGeometry( 0.4, 0.05, 256, 24, 1, 3 )
  74. ];
  75. const material = new THREE.MeshNormalMaterial();
  76. for ( let i = 0, l = geometries.length; i < l; i ++ ) {
  77. const angle = ( i / l ) * Math.PI * 2;
  78. const geometry = geometries[ i ];
  79. const mesh = new THREE.Mesh( geometry, material );
  80. mesh.position.y = 0.1;
  81. mesh.position.x = Math.cos( angle ) / 2.0;
  82. mesh.position.z = Math.sin( angle ) / 2.0;
  83. scene.add( mesh );
  84. meshes.push( mesh );
  85. }
  86. // the container, if you need to move the plane just move this
  87. shadowGroup = new THREE.Group();
  88. shadowGroup.position.y = - 0.3;
  89. scene.add( shadowGroup );
  90. // the render target that will show the shadows in the plane texture
  91. renderTarget = new THREE.WebGLRenderTarget( 512, 512 );
  92. renderTarget.texture.generateMipmaps = false;
  93. // the render target that we will use to blur the first render target
  94. renderTargetBlur = new THREE.WebGLRenderTarget( 512, 512 );
  95. renderTargetBlur.texture.generateMipmaps = false;
  96. // make a plane and make it face up
  97. const planeGeometry = new THREE.PlaneGeometry( PLANE_WIDTH, PLANE_HEIGHT ).rotateX( Math.PI / 2 );
  98. const planeMaterial = new THREE.MeshBasicMaterial( {
  99. map: renderTarget.texture,
  100. opacity: state.shadow.opacity,
  101. transparent: true,
  102. depthWrite: false,
  103. } );
  104. plane = new THREE.Mesh( planeGeometry, planeMaterial );
  105. // make sure it's rendered after the fillPlane
  106. plane.renderOrder = 1;
  107. shadowGroup.add( plane );
  108. // the y from the texture is flipped!
  109. plane.scale.y = - 1;
  110. // the plane onto which to blur the texture
  111. blurPlane = new THREE.Mesh( planeGeometry );
  112. blurPlane.visible = false;
  113. shadowGroup.add( blurPlane );
  114. // the plane with the color of the ground
  115. const fillPlaneMaterial = new THREE.MeshBasicMaterial( {
  116. color: state.plane.color,
  117. opacity: state.plane.opacity,
  118. transparent: true,
  119. depthWrite: false,
  120. } );
  121. fillPlane = new THREE.Mesh( planeGeometry, fillPlaneMaterial );
  122. fillPlane.rotateX( Math.PI );
  123. shadowGroup.add( fillPlane );
  124. // the camera to render the depth material from
  125. shadowCamera = new THREE.OrthographicCamera( - PLANE_WIDTH / 2, PLANE_WIDTH / 2, PLANE_HEIGHT / 2, - PLANE_HEIGHT / 2, 0, CAMERA_HEIGHT );
  126. shadowCamera.rotation.x = Math.PI / 2; // get the camera to look up
  127. shadowGroup.add( shadowCamera );
  128. cameraHelper = new THREE.CameraHelper( shadowCamera );
  129. // like MeshDepthMaterial, but goes from black to transparent
  130. depthMaterial = new THREE.MeshDepthMaterial();
  131. depthMaterial.userData.darkness = { value: state.shadow.darkness };
  132. depthMaterial.onBeforeCompile = function ( shader ) {
  133. shader.uniforms.darkness = depthMaterial.userData.darkness;
  134. shader.fragmentShader = /* glsl */`
  135. uniform float darkness;
  136. ${shader.fragmentShader.replace(
  137. 'gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );',
  138. 'gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * darkness );'
  139. )}
  140. `;
  141. };
  142. depthMaterial.depthTest = false;
  143. depthMaterial.depthWrite = false;
  144. horizontalBlurMaterial = new THREE.ShaderMaterial( HorizontalBlurShader );
  145. horizontalBlurMaterial.depthTest = false;
  146. verticalBlurMaterial = new THREE.ShaderMaterial( VerticalBlurShader );
  147. verticalBlurMaterial.depthTest = false;
  148. //
  149. gui = new GUI();
  150. const shadowFolder = gui.addFolder( 'shadow' );
  151. shadowFolder.open();
  152. const planeFolder = gui.addFolder( 'plane' );
  153. planeFolder.open();
  154. shadowFolder.add( state.shadow, 'blur', 0, 15, 0.1 );
  155. shadowFolder.add( state.shadow, 'darkness', 1, 5, 0.1 ).onChange( function () {
  156. depthMaterial.userData.darkness.value = state.shadow.darkness;
  157. } );
  158. shadowFolder.add( state.shadow, 'opacity', 0, 1, 0.01 ).onChange( function () {
  159. plane.material.opacity = state.shadow.opacity;
  160. } );
  161. planeFolder.addColor( state.plane, 'color' ).onChange( function () {
  162. fillPlane.material.color = new THREE.Color( state.plane.color );
  163. } );
  164. planeFolder.add( state.plane, 'opacity', 0, 1, 0.01 ).onChange( function () {
  165. fillPlane.material.opacity = state.plane.opacity;
  166. } );
  167. gui.add( state, 'showWireframe', true ).onChange( function () {
  168. if ( state.showWireframe ) {
  169. scene.add( cameraHelper );
  170. } else {
  171. scene.remove( cameraHelper );
  172. }
  173. } );
  174. //
  175. renderer = new THREE.WebGLRenderer( { antialias: true } );
  176. renderer.setPixelRatio( window.devicePixelRatio );
  177. renderer.setSize( window.innerWidth, window.innerHeight );
  178. document.body.appendChild( renderer.domElement );
  179. //
  180. new OrbitControls( camera, renderer.domElement );
  181. }
  182. function onWindowResize() {
  183. camera.aspect = window.innerWidth / window.innerHeight;
  184. camera.updateProjectionMatrix();
  185. renderer.setSize( window.innerWidth, window.innerHeight );
  186. }
  187. // renderTarget --> blurPlane (horizontalBlur) --> renderTargetBlur --> blurPlane (verticalBlur) --> renderTarget
  188. function blurShadow( amount ) {
  189. blurPlane.visible = true;
  190. // blur horizontally and draw in the renderTargetBlur
  191. blurPlane.material = horizontalBlurMaterial;
  192. blurPlane.material.uniforms.tDiffuse.value = renderTarget.texture;
  193. horizontalBlurMaterial.uniforms.h.value = amount * 1 / 256;
  194. renderer.setRenderTarget( renderTargetBlur );
  195. renderer.render( blurPlane, shadowCamera );
  196. // blur vertically and draw in the main renderTarget
  197. blurPlane.material = verticalBlurMaterial;
  198. blurPlane.material.uniforms.tDiffuse.value = renderTargetBlur.texture;
  199. verticalBlurMaterial.uniforms.v.value = amount * 1 / 256;
  200. renderer.setRenderTarget( renderTarget );
  201. renderer.render( blurPlane, shadowCamera );
  202. blurPlane.visible = false;
  203. }
  204. function animate( ) {
  205. requestAnimationFrame( animate );
  206. //
  207. meshes.forEach( mesh => {
  208. mesh.rotation.x += 0.01;
  209. mesh.rotation.y += 0.02;
  210. } );
  211. //
  212. // remove the background
  213. const initialBackground = scene.background;
  214. scene.background = null;
  215. // force the depthMaterial to everything
  216. cameraHelper.visible = false;
  217. scene.overrideMaterial = depthMaterial;
  218. // set renderer clear alpha
  219. const initialClearAlpha = renderer.getClearAlpha();
  220. renderer.setClearAlpha( 0 );
  221. // render to the render target to get the depths
  222. renderer.setRenderTarget( renderTarget );
  223. renderer.render( scene, shadowCamera );
  224. // and reset the override material
  225. scene.overrideMaterial = null;
  226. cameraHelper.visible = true;
  227. blurShadow( state.shadow.blur );
  228. // a second pass to reduce the artifacts
  229. // (0.4 is the minimum blur amout so that the artifacts are gone)
  230. blurShadow( state.shadow.blur * 0.4 );
  231. // reset and render the normal scene
  232. renderer.setRenderTarget( null );
  233. renderer.setClearAlpha( initialClearAlpha );
  234. scene.background = initialBackground;
  235. renderer.render( scene, camera );
  236. stats.update();
  237. }
  238. </script>
  239. </body>
  240. </html>