webgl_shadow_contact.html 9.2 KB

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