webgpu_lights_clustered.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 { pass, uniform, vec3, float, mix, step, uv, instancedBufferAttribute } from 'three/tsl';
  36. import { ClusteredLighting } from 'three/addons/lighting/ClusteredLighting.js';
  37. import { Inspector } from 'three/addons/inspector/Inspector.js';
  38. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  39. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  40. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  41. const MODEL_INDEX_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/model-index.json';
  42. const SAMPLE_ASSETS_BASE_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/';
  43. let camera, scene, renderer,
  44. lights, lightDummy,
  45. lightPositionAttribute,
  46. controls,
  47. scenePass, clusterInfluence, debugZSliceNode,
  48. lighting,
  49. maxCount,
  50. count,
  51. renderPipeline;
  52. init();
  53. async function init() {
  54. if ( WebGPU.isAvailable() === false ) {
  55. document.body.appendChild( WebGPU.getErrorMessage() );
  56. throw new Error( 'No WebGPU support' );
  57. }
  58. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 70 );
  59. camera.position.set( - 10, 5, 0 );
  60. scene = new THREE.Scene();
  61. scene.fog = new THREE.Fog( 0x111111, 30, 80 );
  62. scene.background = new THREE.Color( 0x111111 );
  63. maxCount = 1000;
  64. count = 700;
  65. // sponza
  66. const loader = new GLTFLoader();
  67. const modelURL = await getSponzaModelURL();
  68. const gltf = await loader.loadAsync( modelURL );
  69. const model = gltf.scene;
  70. model.traverse( ( child ) => {
  71. if ( child.isLight && child.parent ) child.parent.remove( child );
  72. } );
  73. scene.add( model );
  74. const box = new THREE.Box3().setFromObject( model );
  75. const modelSize = box.getSize( new THREE.Vector3() );
  76. const modelCenter = box.getCenter( new THREE.Vector3() );
  77. const lightPositions = new Float32Array( maxCount * 3 );
  78. const lightColors = new Float32Array( maxCount * 3 );
  79. lightPositionAttribute = new THREE.InstancedBufferAttribute( lightPositions, 3 );
  80. lightPositionAttribute.setUsage( THREE.DynamicDrawUsage );
  81. const lightColorAttribute = new THREE.InstancedBufferAttribute( lightColors, 3 );
  82. // Physical 1/r² point-source falloff (Plummer profile): I = peak * r0² / ( r² + r0² )
  83. // Subtract the value at r = 0.5 so the soft tail reaches exactly 0 at the sprite edge.
  84. const coreRadius = 0.02;
  85. const peak = 16;
  86. const r0sq = coreRadius * coreRadius;
  87. const edgeBias = r0sq / ( 0.25 + r0sq );
  88. const offset = uv().sub( 0.5 );
  89. const r2 = offset.dot( offset );
  90. const glow = float( r0sq ).div( r2.add( r0sq ) ).sub( edgeBias ).max( 0 ).mul( peak );
  91. const spriteMaterial = new THREE.SpriteNodeMaterial( {
  92. transparent: true,
  93. depthWrite: false,
  94. blending: THREE.AdditiveBlending
  95. } );
  96. spriteMaterial.positionNode = instancedBufferAttribute( lightPositionAttribute );
  97. spriteMaterial.colorNode = glow.mul( instancedBufferAttribute( lightColorAttribute ) );
  98. spriteMaterial.scaleNode = uniform( 0.2 );
  99. lightDummy = new THREE.Sprite( spriteMaterial );
  100. lightDummy.count = count;
  101. lightDummy.frustumCulled = false;
  102. scene.add( lightDummy );
  103. // lights
  104. lights = new THREE.Group();
  105. scene.add( lights );
  106. const addLight = ( hexColor, power = 10, distance = 1 ) => {
  107. const light = new THREE.PointLight( hexColor, 1, distance );
  108. light.position.set(
  109. modelCenter.x + ( Math.random() - 0.5 ) * modelSize.x * 0.7,
  110. ( box.min.y + Math.random() * modelSize.y * 0.7 ) + 0.4,
  111. modelCenter.z + ( Math.random() - 0.5 ) * modelSize.z * 0.5
  112. );
  113. light.power = power;
  114. light.userData.fixedPosition = light.position.clone();
  115. light.visible = ( lights.children.length < count );
  116. const i = lights.children.length;
  117. lightPositions[ i * 3 + 0 ] = light.position.x;
  118. lightPositions[ i * 3 + 1 ] = light.position.y;
  119. lightPositions[ i * 3 + 2 ] = light.position.z;
  120. lights.add( light );
  121. return light;
  122. };
  123. const color = new THREE.Color();
  124. for ( let i = 0; i < maxCount; i ++ ) {
  125. const hex = ( Math.random() * 0x888888 ) + 0x888888;
  126. color.setHex( hex );
  127. lightColors[ i * 3 + 0 ] = color.r;
  128. lightColors[ i * 3 + 1 ] = color.g;
  129. lightColors[ i * 3 + 2 ] = color.b;
  130. addLight( hex );
  131. }
  132. //
  133. const lightAmbient = new THREE.AmbientLight( 0xffffff, .1 );
  134. scene.add( lightAmbient );
  135. // renderer
  136. lighting = new ClusteredLighting(); // ( maxLights = 1024, tileSize = 32, zSlices = 24, maxLightsPerCluster = 64 )
  137. renderer = new THREE.WebGPURenderer( { antialias: true } );
  138. renderer.setPixelRatio( window.devicePixelRatio );
  139. renderer.setSize( window.innerWidth, window.innerHeight );
  140. renderer.setAnimationLoop( animate );
  141. renderer.lighting = lighting; // set lighting system
  142. renderer.toneMapping = THREE.NeutralToneMapping;
  143. renderer.toneMappingExposure = 1.5;
  144. renderer.inspector = new Inspector();
  145. document.body.appendChild( renderer.domElement );
  146. // controls
  147. controls = new OrbitControls( camera, renderer.domElement );
  148. controls.target.set( 0, 5, 0 );
  149. controls.maxDistance = 60;
  150. controls.update();
  151. // events
  152. window.addEventListener( 'resize', onWindowResize );
  153. // post processing
  154. scenePass = pass( scene, camera );
  155. clusterInfluence = uniform( 0 );
  156. renderPipeline = new THREE.RenderPipeline( renderer );
  157. debugZSliceNode = uniform( 15, 'int' );
  158. updatePostProcessing();
  159. // gui
  160. const gui = renderer.inspector.createParameters( 'Settings' );
  161. const params = {
  162. count
  163. };
  164. gui.add( params, 'count', 0, maxCount, 1 ).name( 'light count' ).onChange( ( value ) => {
  165. lightDummy.count = value;
  166. for ( let i = 0; i < lights.children.length; i ++ ) {
  167. lights.children[ i ].visible = ( i < value );
  168. }
  169. } );
  170. gui.add( clusterInfluence, 'value', 0, .7 ).name( 'lights per tile' );
  171. gui.add( debugZSliceNode, 'value', 0, lighting.zSlices - 1, 1 ).name( 'z-slice' );
  172. }
  173. function updatePostProcessing() {
  174. // cluster light count debug overlay; needs to be updated every time the renderer size changes
  175. const lightingNode = lighting.getNode( scene ).setSize( window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio );
  176. // Calculate a color mapping based on the actual number of lights directly affecting the cluster.
  177. // We map between 0 and maxLightsPerCluster to a gradient
  178. const lightCount = lightingNode.getClusterLightCount( debugZSliceNode );
  179. const heatmap = float( lightCount ).div( float( lighting.maxLightsPerCluster ) );
  180. // Gradient mapping: Blue (0.0) -> Green (0.5) -> Red (1.0)
  181. let heatColor = mix( vec3( 0.0, 0.0, 1.0 ), vec3( 0.0, 1.0, 0.0 ), heatmap.mul( 2.0 ).saturate() );
  182. heatColor = mix( heatColor, vec3( 1.0, 0.0, 0.0 ), heatmap.sub( 0.5 ).mul( 2.0 ).saturate() );
  183. // Blend the heatmap over the original scene based on the slider value
  184. // The `step` drops opacity to 0.0 if there are strictly no lights in the cluster
  185. const finalInfluence = clusterInfluence.mul( step( 0.0001, heatmap ) );
  186. renderPipeline.outputNode = mix( scenePass, heatColor, finalInfluence );
  187. renderPipeline.needsUpdate = true;
  188. }
  189. async function getSponzaModelURL() {
  190. const response = await fetch( MODEL_INDEX_URL );
  191. const models = await response.json();
  192. const sponzaInfo = models.find( ( model ) => model.name === 'Sponza' );
  193. if ( ! sponzaInfo ) {
  194. throw new Error( 'Sponza entry was not found in the glTF sample model index.' );
  195. }
  196. const variants = sponzaInfo.variants || {};
  197. const variantName = variants[ 'glTF-Binary' ] || variants[ 'glTF' ] || variants[ 'glTF-Embedded' ] || Object.values( variants )[ 0 ];
  198. if ( ! variantName ) {
  199. throw new Error( 'Sponza has no supported glTF variant in the model index.' );
  200. }
  201. const variantFolder = variantName.endsWith( '.glb' ) ? 'glTF-Binary' : 'glTF';
  202. return `${ SAMPLE_ASSETS_BASE_URL }${ sponzaInfo.name }/${ variantFolder }/${ variantName }`;
  203. }
  204. function onWindowResize() {
  205. camera.aspect = window.innerWidth / window.innerHeight;
  206. camera.updateProjectionMatrix();
  207. renderer.setSize( window.innerWidth, window.innerHeight );
  208. updatePostProcessing();
  209. }
  210. function animate() {
  211. const time = performance.now() / 1000;
  212. const positions = lightPositionAttribute.array;
  213. for ( let i = 0; i < lights.children.length; i ++ ) {
  214. const light = lights.children[ i ];
  215. const lightTime = ( time * 0.5 ) + light.id;
  216. light.position.copy( light.userData.fixedPosition );
  217. light.position.x += Math.sin( lightTime * 0.7 ) * 1.5;
  218. light.position.y += Math.cos( lightTime * 0.5 ) * .3;
  219. light.position.z += Math.cos( lightTime * 0.3 ) * 1.5;
  220. positions[ i * 3 + 0 ] = light.position.x;
  221. positions[ i * 3 + 1 ] = light.position.y;
  222. positions[ i * 3 + 2 ] = light.position.z;
  223. }
  224. lightPositionAttribute.needsUpdate = true;
  225. renderPipeline.render();
  226. }
  227. </script>
  228. </body>
  229. </html>
粤ICP备19079148号