webgl_shadowmap_pcss.html 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - percent closer soft-shadows</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #cce0ff;
  11. color: #000;
  12. }
  13. a {
  14. color: #08f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">Percent Closer Soft-Shadows (PCSS) by <a href="http://eduperiment.com">spidersharma03</a></div>
  20. <script type="x-shader/x-fragment" id="PCSS">
  21. #define LIGHT_WORLD_SIZE 0.005
  22. #define LIGHT_FRUSTUM_WIDTH 3.75
  23. #define LIGHT_SIZE_UV (LIGHT_WORLD_SIZE / LIGHT_FRUSTUM_WIDTH)
  24. #define NEAR_PLANE 9.5
  25. #define NUM_SAMPLES 17
  26. #define NUM_RINGS 11
  27. #define BLOCKER_SEARCH_NUM_SAMPLES NUM_SAMPLES
  28. vec2 poissonDisk[NUM_SAMPLES];
  29. void initPoissonSamples( const in vec2 randomSeed ) {
  30. float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );
  31. float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );
  32. // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/
  33. float angle = rand( randomSeed ) * PI2;
  34. float radius = INV_NUM_SAMPLES;
  35. float radiusStep = radius;
  36. for( int i = 0; i < NUM_SAMPLES; i ++ ) {
  37. poissonDisk[i] = vec2( cos( angle ), sin( angle ) ) * pow( radius, 0.75 );
  38. radius += radiusStep;
  39. angle += ANGLE_STEP;
  40. }
  41. }
  42. float penumbraSize( const in float zReceiver, const in float zBlocker ) { // Parallel plane estimation
  43. return (zReceiver - zBlocker) / zBlocker;
  44. }
  45. float findBlocker( sampler2D shadowMap, const in vec2 uv, const in float zReceiver ) {
  46. // This uses similar triangles to compute what
  47. // area of the shadow map we should search
  48. float searchRadius = LIGHT_SIZE_UV * ( zReceiver - NEAR_PLANE ) / zReceiver;
  49. float blockerDepthSum = 0.0;
  50. int numBlockers = 0;
  51. for( int i = 0; i < BLOCKER_SEARCH_NUM_SAMPLES; i++ ) {
  52. float shadowMapDepth = unpackRGBAToDepth(texture2D(shadowMap, uv + poissonDisk[i] * searchRadius));
  53. if ( shadowMapDepth < zReceiver ) {
  54. blockerDepthSum += shadowMapDepth;
  55. numBlockers ++;
  56. }
  57. }
  58. if( numBlockers == 0 ) return -1.0;
  59. return blockerDepthSum / float( numBlockers );
  60. }
  61. float PCF_Filter(sampler2D shadowMap, vec2 uv, float zReceiver, float filterRadius ) {
  62. float sum = 0.0;
  63. float depth;
  64. #pragma unroll_loop_start
  65. for( int i = 0; i < 17; i ++ ) {
  66. depth = unpackRGBAToDepth( texture2D( shadowMap, uv + poissonDisk[ i ] * filterRadius ) );
  67. if( zReceiver <= depth ) sum += 1.0;
  68. }
  69. #pragma unroll_loop_end
  70. #pragma unroll_loop_start
  71. for( int i = 0; i < 17; i ++ ) {
  72. depth = unpackRGBAToDepth( texture2D( shadowMap, uv + -poissonDisk[ i ].yx * filterRadius ) );
  73. if( zReceiver <= depth ) sum += 1.0;
  74. }
  75. #pragma unroll_loop_end
  76. return sum / ( 2.0 * float( 17 ) );
  77. }
  78. float PCSS ( sampler2D shadowMap, vec4 coords ) {
  79. vec2 uv = coords.xy;
  80. float zReceiver = coords.z; // Assumed to be eye-space z in this code
  81. initPoissonSamples( uv );
  82. // STEP 1: blocker search
  83. float avgBlockerDepth = findBlocker( shadowMap, uv, zReceiver );
  84. //There are no occluders so early out (this saves filtering)
  85. if( avgBlockerDepth == -1.0 ) return 1.0;
  86. // STEP 2: penumbra size
  87. float penumbraRatio = penumbraSize( zReceiver, avgBlockerDepth );
  88. float filterRadius = penumbraRatio * LIGHT_SIZE_UV * NEAR_PLANE / zReceiver;
  89. // STEP 3: filtering
  90. //return avgBlockerDepth;
  91. return PCF_Filter( shadowMap, uv, zReceiver, filterRadius );
  92. }
  93. </script>
  94. <script type="x-shader/x-fragment" id="PCSSGetShadow">
  95. return PCSS( shadowMap, shadowCoord );
  96. </script>
  97. <script type="importmap">
  98. {
  99. "imports": {
  100. "three": "../build/three.module.js",
  101. "three/addons/": "./jsm/"
  102. }
  103. }
  104. </script>
  105. <script type="module">
  106. import * as THREE from 'three';
  107. import Stats from 'three/addons/libs/stats.module.js';
  108. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  109. let stats;
  110. let camera, scene, renderer;
  111. let group;
  112. init();
  113. function init() {
  114. const container = document.createElement( 'div' );
  115. document.body.appendChild( container );
  116. // scene
  117. scene = new THREE.Scene();
  118. scene.fog = new THREE.Fog( 0xcce0ff, 5, 100 );
  119. // camera
  120. camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 );
  121. // We use this particular camera position in order to expose a bug that can sometimes happen presumably
  122. // due to lack of precision when interpolating values over really large triangles.
  123. // It reproduced on at least NVIDIA GTX 1080 and GTX 1050 Ti GPUs when the ground plane was not
  124. // subdivided into segments.
  125. camera.position.x = 7;
  126. camera.position.y = 13;
  127. camera.position.z = 7;
  128. scene.add( camera );
  129. // lights
  130. scene.add( new THREE.AmbientLight( 0xaaaaaa, 3 ) );
  131. const light = new THREE.DirectionalLight( 0xf0f6ff, 4.5 );
  132. light.position.set( 2, 8, 4 );
  133. light.castShadow = true;
  134. light.shadow.mapSize.width = 1024;
  135. light.shadow.mapSize.height = 1024;
  136. light.shadow.camera.far = 20;
  137. scene.add( light );
  138. // scene.add( new DirectionalLightHelper( light ) );
  139. scene.add( new THREE.CameraHelper( light.shadow.camera ) );
  140. // group
  141. group = new THREE.Group();
  142. scene.add( group );
  143. const geometry = new THREE.SphereGeometry( 0.3, 20, 20 );
  144. for ( let i = 0; i < 20; i ++ ) {
  145. const material = new THREE.MeshPhongMaterial( { color: Math.random() * 0xffffff } );
  146. const sphere = new THREE.Mesh( geometry, material );
  147. sphere.position.x = Math.random() - 0.5;
  148. sphere.position.z = Math.random() - 0.5;
  149. sphere.position.normalize();
  150. sphere.position.multiplyScalar( Math.random() * 2 + 1 );
  151. sphere.castShadow = true;
  152. sphere.receiveShadow = true;
  153. sphere.userData.phase = Math.random() * Math.PI;
  154. group.add( sphere );
  155. }
  156. // ground
  157. const groundMaterial = new THREE.MeshPhongMaterial( { color: 0x898989 } );
  158. const ground = new THREE.Mesh( new THREE.PlaneGeometry( 20000, 20000, 8, 8 ), groundMaterial );
  159. ground.rotation.x = - Math.PI / 2;
  160. ground.receiveShadow = true;
  161. scene.add( ground );
  162. // column
  163. const column = new THREE.Mesh( new THREE.BoxGeometry( 1, 4, 1 ), groundMaterial );
  164. column.position.y = 2;
  165. column.castShadow = true;
  166. column.receiveShadow = true;
  167. scene.add( column );
  168. // overwrite shadowmap code
  169. let shader = THREE.ShaderChunk.shadowmap_pars_fragment;
  170. shader = shader.replace(
  171. '#ifdef USE_SHADOWMAP',
  172. '#ifdef USE_SHADOWMAP' +
  173. document.getElementById( 'PCSS' ).textContent
  174. );
  175. shader = shader.replace(
  176. '#if defined( SHADOWMAP_TYPE_PCF )',
  177. document.getElementById( 'PCSSGetShadow' ).textContent +
  178. '#if defined( SHADOWMAP_TYPE_PCF )'
  179. );
  180. THREE.ShaderChunk.shadowmap_pars_fragment = shader;
  181. // renderer
  182. renderer = new THREE.WebGLRenderer( { antialias: true } );
  183. renderer.setPixelRatio( window.devicePixelRatio );
  184. renderer.setSize( window.innerWidth, window.innerHeight );
  185. renderer.setAnimationLoop( animate );
  186. renderer.setClearColor( scene.fog.color );
  187. container.appendChild( renderer.domElement );
  188. renderer.shadowMap.enabled = true;
  189. // controls
  190. const controls = new OrbitControls( camera, renderer.domElement );
  191. controls.maxPolarAngle = Math.PI * 0.5;
  192. controls.minDistance = 10;
  193. controls.maxDistance = 75;
  194. controls.target.set( 0, 2.5, 0 );
  195. controls.update();
  196. // performance monitor
  197. stats = new Stats();
  198. container.appendChild( stats.dom );
  199. //
  200. window.addEventListener( 'resize', onWindowResize );
  201. }
  202. //
  203. function onWindowResize() {
  204. camera.aspect = window.innerWidth / window.innerHeight;
  205. camera.updateProjectionMatrix();
  206. renderer.setSize( window.innerWidth, window.innerHeight );
  207. }
  208. //
  209. function animate() {
  210. const time = performance.now() / 1000;
  211. group.traverse( function ( child ) {
  212. if ( 'phase' in child.userData ) {
  213. child.position.y = Math.abs( Math.sin( time + child.userData.phase ) ) * 4 + 0.3;
  214. }
  215. } );
  216. renderer.render( scene, camera );
  217. stats.update();
  218. }
  219. </script>
  220. </body>
  221. </html>