webgl_shadowmap_pcss.html 8.8 KB

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