webgpu_lights_clustered.html 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - clustered lighting</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 webgpu - clustered lighting">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_lights_clustered.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_lights_clustered.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  16. <div class="title-wrapper">
  17. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Clustered Lighting</span>
  18. </div>
  19. <small>
  20. Forward+ clustered lighting.
  21. </small>
  22. </div>
  23. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../build/three.webgpu.js",
  27. "three/webgpu": "../build/three.webgpu.js",
  28. "three/tsl": "../build/three.tsl.js",
  29. "three/addons/": "./jsm/"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three/webgpu';
  35. import { instancedBufferAttribute, pass, uniform, vec3, float, mix, step, renderOutput } from 'three/tsl';
  36. import { fxaa } from 'three/addons/tsl/display/FXAANode.js';
  37. import { ClusteredLighting } from 'three/addons/lighting/ClusteredLighting.js';
  38. import { Inspector } from 'three/addons/inspector/Inspector.js';
  39. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  40. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  41. const GRID = 30; // GRID x GRID spheres
  42. const SPACING = 5;
  43. const RADIUS = 0.5;
  44. const WAVE_HEIGHT = 4;
  45. const BIG_RADIUS = 6;
  46. const BASE_POWER = 45;
  47. let camera, scene, renderer, controls, spheresMesh, lighting;
  48. let renderPipeline, scenePass, clusterInfluence, debugZSliceNode;
  49. const balls = [];
  50. const dummy = new THREE.Object3D();
  51. const params = {
  52. intensity: 1,
  53. animate: true
  54. };
  55. init();
  56. async function init() {
  57. if ( WebGPU.isAvailable() === false ) {
  58. document.body.appendChild( WebGPU.getErrorMessage() );
  59. throw new Error( 'No WebGPU support' );
  60. }
  61. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 200 );
  62. camera.position.set( 36, 18, 36 );
  63. scene = new THREE.Scene();
  64. renderer = new THREE.WebGPURenderer();
  65. renderer.setPixelRatio( window.devicePixelRatio );
  66. renderer.setSize( window.innerWidth, window.innerHeight );
  67. renderer.setAnimationLoop( animate );
  68. renderer.toneMapping = THREE.NeutralToneMapping;
  69. renderer.toneMappingExposure = 1;
  70. lighting = new ClusteredLighting();
  71. renderer.lighting = lighting; // set lighting system
  72. renderer.inspector = new Inspector();
  73. document.body.appendChild( renderer.domElement );
  74. await renderer.init();
  75. // ground
  76. const ground = new THREE.Mesh(
  77. new THREE.PlaneGeometry( 1000, 1000 ).rotateX( - Math.PI / 2 ),
  78. new THREE.MeshPhongNodeMaterial( { color: 0x2a2a2a, shininess: 80 } )
  79. );
  80. scene.add( ground );
  81. // four big spheres in the middle for the surrounding lights to play across
  82. const bigPositions = [
  83. new THREE.Vector3( - 9, BIG_RADIUS, - 9 ),
  84. new THREE.Vector3( 9, BIG_RADIUS, - 9 ),
  85. new THREE.Vector3( - 9, BIG_RADIUS, 9 ),
  86. new THREE.Vector3( 9, BIG_RADIUS, 9 )
  87. ];
  88. const bigGeometry = new THREE.SphereGeometry( BIG_RADIUS, 64, 32 );
  89. const bigMaterial = new THREE.MeshPhongNodeMaterial( { color: 0xdddddd, shininess: 80 } );
  90. for ( const position of bigPositions ) {
  91. const bigSphere = new THREE.Mesh( bigGeometry, bigMaterial );
  92. bigSphere.position.copy( position );
  93. scene.add( bigSphere );
  94. }
  95. // a grid of coloured spheres drawn as a single InstancedMesh; each is
  96. // unlit in its own colour and holds a matching point light at its centre
  97. const maxCount = GRID * GRID;
  98. const colorAttribute = new THREE.InstancedBufferAttribute( new Float32Array( maxCount * 3 ), 3 );
  99. const material = new THREE.MeshBasicNodeMaterial();
  100. material.colorNode = instancedBufferAttribute( colorAttribute );
  101. spheresMesh = new THREE.InstancedMesh( new THREE.SphereGeometry( RADIUS, 32, 16 ), material, maxCount );
  102. spheresMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  103. scene.add( spheresMesh );
  104. const color = new THREE.Color();
  105. const span = ( GRID - 1 ) * SPACING;
  106. let i = 0;
  107. for ( let ix = 0; ix < GRID; ix ++ ) {
  108. for ( let iz = 0; iz < GRID; iz ++ ) {
  109. const x = ix * SPACING - span / 2;
  110. const z = iz * SPACING - span / 2;
  111. // leave a clearing where a big sphere sits
  112. if ( bigPositions.some( ( position ) => Math.hypot( x - position.x, z - position.z ) < BIG_RADIUS + 1 ) ) continue;
  113. const phase = ( ix + iz ) * 0.5;
  114. dummy.position.set( x, RADIUS, z );
  115. dummy.updateMatrix();
  116. spheresMesh.setMatrixAt( i, dummy.matrix );
  117. color.setHSL( ( ix * GRID + iz ) / ( GRID * GRID ), 1.0, 0.5 );
  118. colorAttribute.setXYZ( i, color.r, color.g, color.b );
  119. const light = new THREE.PointLight( color, 1, 9 );
  120. light.power = BASE_POWER;
  121. light.position.set( x, RADIUS, z );
  122. scene.add( light );
  123. balls.push( { x, z, phase, light } );
  124. i ++;
  125. }
  126. }
  127. spheresMesh.count = i;
  128. // controls
  129. controls = new OrbitControls( camera, renderer.domElement );
  130. controls.enableDamping = true;
  131. controls.target.set( 0, 6, 0 );
  132. controls.maxPolarAngle = Math.PI * 0.49;
  133. controls.minDistance = 4;
  134. controls.maxDistance = 400;
  135. controls.update();
  136. // post-processing: a debug overlay that tints each screen tile by how many
  137. // lights its cluster holds, for the selected depth slice
  138. scenePass = pass( scene, camera );
  139. clusterInfluence = uniform( 0 );
  140. debugZSliceNode = uniform( 20, 'int' );
  141. renderPipeline = new THREE.RenderPipeline( renderer );
  142. renderPipeline.outputColorTransform = false;
  143. updatePostProcessing();
  144. // gui
  145. const gui = renderer.inspector.createParameters( 'Settings' );
  146. gui.add( params, 'intensity', 0, 3 ).name( 'light intensity' ).onChange( ( value ) => {
  147. for ( const ball of balls ) ball.light.power = BASE_POWER * value;
  148. } );
  149. gui.add( params, 'animate' );
  150. gui.add( clusterInfluence, 'value', 0, .7 ).name( 'lights per tile' );
  151. gui.add( debugZSliceNode, 'value', 0, lighting.zSlices - 1, 1 ).name( 'z-slice' );
  152. // events
  153. window.addEventListener( 'resize', onWindowResize );
  154. }
  155. function onWindowResize() {
  156. camera.aspect = window.innerWidth / window.innerHeight;
  157. camera.updateProjectionMatrix();
  158. renderer.setSize( window.innerWidth, window.innerHeight );
  159. updatePostProcessing();
  160. }
  161. function updatePostProcessing() {
  162. // the overlay samples the cluster grid at the current resolution, so it
  163. // is rebuilt whenever the renderer size changes
  164. const lightingNode = lighting.getNode( scene ).setSize( window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio );
  165. // map the light count of each cluster ( 0 … maxLightsPerCluster ) to a
  166. // blue → green → red gradient
  167. const lightCount = lightingNode.getClusterLightCount( debugZSliceNode );
  168. const heatmap = float( lightCount ).div( float( lighting.maxLightsPerCluster ) );
  169. let heatColor = mix( vec3( 0.0, 0.0, 1.0 ), vec3( 0.0, 1.0, 0.0 ), heatmap.mul( 2.0 ).saturate() );
  170. heatColor = mix( heatColor, vec3( 1.0, 0.0, 0.0 ), heatmap.sub( 0.5 ).mul( 2.0 ).saturate() );
  171. // blend the heatmap over the scene by the slider amount; step() keeps
  172. // empty clusters transparent
  173. const finalInfluence = clusterInfluence.mul( step( 0.0001, heatmap ) );
  174. const outputPass = renderOutput( mix( scenePass, heatColor, finalInfluence ) );
  175. renderPipeline.outputNode = fxaa( outputPass );
  176. renderPipeline.needsUpdate = true;
  177. }
  178. function animate() {
  179. if ( params.animate === true ) {
  180. const time = performance.now() / 1000;
  181. for ( let i = 0; i < balls.length; i ++ ) {
  182. const ball = balls[ i ];
  183. const y = RADIUS + ( 0.5 + 0.5 * Math.sin( time * 1.5 + ball.phase ) ) * WAVE_HEIGHT;
  184. dummy.position.set( ball.x, y, ball.z );
  185. dummy.updateMatrix();
  186. spheresMesh.setMatrixAt( i, dummy.matrix );
  187. ball.light.position.y = y;
  188. }
  189. spheresMesh.instanceMatrix.needsUpdate = true;
  190. }
  191. controls.update();
  192. renderPipeline.render();
  193. }
  194. </script>
  195. </body>
  196. </html>
粤ICP备19079148号