webgpu_volume_caustics.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - volumetric caustics</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="example.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  12. <div class="title-wrapper">
  13. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Volumetric Caustics</span>
  14. </div>
  15. <small>Real-time volumetric caustics effects.</small>
  16. </div>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.webgpu.js",
  21. "three/webgpu": "../build/three.webgpu.js",
  22. "three/tsl": "../build/three.tsl.js",
  23. "three/addons/": "./jsm/"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three/webgpu';
  29. import { uniform, refract, div, frameId, lightViewPosition, float, positionView, positionViewDirection, screenUV, pass, texture3D, time, screenCoordinate, normalView, texture, Fn, vec2, vec3 } from 'three/tsl';
  30. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  31. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  32. import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
  33. import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
  34. import { Inspector } from 'three/addons/inspector/Inspector.js';
  35. import { bayer16 } from 'three/addons/tsl/math/Bayer.js';
  36. import { bloom } from 'three/addons/tsl/display/BloomNode.js';
  37. let camera, scene, renderer, controls;
  38. let postProcessing;
  39. let gltf;
  40. init();
  41. async function init() {
  42. const LAYER_VOLUMETRIC_LIGHTING = 10;
  43. camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 0.025, 5 );
  44. camera.position.set( - 0.7, 0.2, 0.2 );
  45. scene = new THREE.Scene();
  46. // Light
  47. const spotLight = new THREE.SpotLight( 0xffffff, 1 );
  48. spotLight.position.set( .2, .3, .2 );
  49. spotLight.castShadow = true;
  50. spotLight.angle = Math.PI / 6;
  51. spotLight.penumbra = 1;
  52. spotLight.decay = 2;
  53. spotLight.distance = 0;
  54. spotLight.shadow.mapType = THREE.HalfFloatType; // For HDR Caustics
  55. spotLight.shadow.mapSize.width = 1024;
  56. spotLight.shadow.mapSize.height = 1024;
  57. spotLight.shadow.camera.near = .1;
  58. spotLight.shadow.camera.far = 1;
  59. spotLight.shadow.bias = - .003;
  60. spotLight.shadow.intensity = .95;
  61. spotLight.layers.enable( LAYER_VOLUMETRIC_LIGHTING );
  62. scene.add( spotLight );
  63. // Model / Textures
  64. const dracoLoader = new DRACOLoader();
  65. dracoLoader.setDecoderPath( 'jsm/libs/draco/' );
  66. dracoLoader.setDecoderConfig( { type: 'js' } );
  67. gltf = ( await new GLTFLoader().setDRACOLoader( dracoLoader ).loadAsync( './models/gltf/duck.glb' ) ).scene;
  68. gltf.scale.setScalar( .5 );
  69. scene.add( gltf );
  70. const causticMap = new THREE.TextureLoader().load( './textures/opengameart/Caustic_Free.jpg' );
  71. causticMap.wrapS = causticMap.wrapT = THREE.RepeatWrapping;
  72. causticMap.colorSpace = THREE.SRGBColorSpace;
  73. // Material
  74. const duck = gltf.children[ 0 ];
  75. duck.material = new THREE.MeshPhysicalNodeMaterial();
  76. duck.material.side = THREE.DoubleSide;
  77. duck.material.transparent = true;
  78. duck.material.color = new THREE.Color( 0xFFD700 );
  79. duck.material.transmission = 1;
  80. duck.material.thickness = .25;
  81. duck.material.ior = 1.5;
  82. duck.material.metalness = 0;
  83. duck.material.roughness = .1;
  84. duck.castShadow = true;
  85. // TSL Shader
  86. const causticOcclusion = uniform( 1 );
  87. const causticEffect = Fn( () => {
  88. const refractionVector = refract( positionViewDirection.negate(), normalView, div( 1.0, duck.material.ior ) ).normalize();
  89. const viewZ = normalView.z.pow( causticOcclusion );
  90. const textureUV = refractionVector.xy.mul( .6 );
  91. const causticColor = uniform( duck.material.color );
  92. const chromaticAberrationOffset = normalView.z.pow( - .9 ).mul( .004 );
  93. const causticProjection = vec3(
  94. texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset.negate(), 0 ) ) ).r,
  95. texture( causticMap, textureUV.add( vec2( 0, chromaticAberrationOffset.negate() ) ) ).g,
  96. texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset, chromaticAberrationOffset ) ) ).b
  97. );
  98. return causticProjection.mul( viewZ.mul( 60 ) ).add( viewZ ).mul( causticColor );
  99. } )().toVar();
  100. duck.material.castShadowNode = causticEffect;
  101. duck.material.emissiveNode = Fn( () => {
  102. // Custom emissive for illuminating backside of the mesh based on the caustic effect and light direction
  103. const thicknessPowerNode = float( 3.0 );
  104. const scatteringHalf = lightViewPosition( spotLight ).sub( positionView ).normalize();
  105. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ) );
  106. return causticEffect.mul( scatteringDot.add( .1 ) ).mul( .02 );
  107. } )();
  108. // Ground
  109. const textureLoader = new THREE.TextureLoader();
  110. const map = textureLoader.load( 'textures/hardwood2_diffuse.jpg' );
  111. map.wrapS = map.wrapT = THREE.RepeatWrapping;
  112. map.repeat.set( 10, 10 );
  113. const geometry = new THREE.PlaneGeometry( 2, 2 );
  114. const material = new THREE.MeshStandardMaterial( { color: 0 } );
  115. const ground = new THREE.Mesh( geometry, material );
  116. ground.rotation.x = - Math.PI / 2;
  117. ground.receiveShadow = true;
  118. scene.add( ground );
  119. // Renderer
  120. renderer = new THREE.WebGPURenderer( { antialias: true } );
  121. renderer.shadowMap.enabled = true;
  122. renderer.shadowMap.transmitted = true;
  123. renderer.inspector = new Inspector();
  124. renderer.setPixelRatio( window.devicePixelRatio );
  125. renderer.setSize( window.innerWidth, window.innerHeight );
  126. renderer.setAnimationLoop( animate );
  127. document.body.appendChild( renderer.domElement );
  128. // GUI
  129. const gui = renderer.inspector.createParameters( 'Volumetric Caustics' );
  130. gui.add( causticOcclusion, 'value', 0, 20 ).name( 'caustic occlusion' );
  131. gui.addColor( duck.material, 'color' ).name( 'material color' );
  132. // Post-Processing
  133. postProcessing = new THREE.PostProcessing( renderer );
  134. // Layers
  135. const volumetricLightingIntensity = uniform( .7 );
  136. const volumetricLayer = new THREE.Layers();
  137. volumetricLayer.disableAll();
  138. volumetricLayer.enable( LAYER_VOLUMETRIC_LIGHTING );
  139. // Volumetric Fog Area
  140. function createTexture3D() {
  141. let i = 0;
  142. const size = 128;
  143. const data = new Uint8Array( size * size * size );
  144. const scale = 10;
  145. const perlin = new ImprovedNoise();
  146. const repeatFactor = 5.0;
  147. for ( let z = 0; z < size; z ++ ) {
  148. for ( let y = 0; y < size; y ++ ) {
  149. for ( let x = 0; x < size; x ++ ) {
  150. const nx = ( x / size ) * repeatFactor;
  151. const ny = ( y / size ) * repeatFactor;
  152. const nz = ( z / size ) * repeatFactor;
  153. const noiseValue = perlin.noise( nx * scale, ny * scale, nz * scale );
  154. data[ i ] = ( 128 + 128 * noiseValue );
  155. i ++;
  156. }
  157. }
  158. }
  159. const texture = new THREE.Data3DTexture( data, size, size, size );
  160. texture.format = THREE.RedFormat;
  161. texture.minFilter = THREE.LinearFilter;
  162. texture.magFilter = THREE.LinearFilter;
  163. texture.wrapS = THREE.RepeatWrapping;
  164. texture.wrapT = THREE.RepeatWrapping;
  165. texture.unpackAlignment = 1;
  166. texture.needsUpdate = true;
  167. return texture;
  168. }
  169. const noiseTexture3D = createTexture3D();
  170. const smokeAmount = uniform( 3 );
  171. const volumetricMaterial = new THREE.VolumeNodeMaterial();
  172. volumetricMaterial.steps = 20;
  173. volumetricMaterial.offsetNode = bayer16( screenCoordinate.add( frameId ) ); // Add dithering to reduce banding
  174. volumetricMaterial.scatteringNode = Fn( ( { positionRay } ) => {
  175. // Return the amount of fog based on the noise texture
  176. const timeScaled = vec3( time.mul( .01 ), 0, time.mul( .03 ) );
  177. const sampleGrain = ( scale, timeScale = 1 ) => texture3D( noiseTexture3D, positionRay.add( timeScaled.mul( timeScale ) ).mul( scale ).mod( 1 ), 0 ).r.add( .5 );
  178. let density = sampleGrain( 1 );
  179. density = density.mul( sampleGrain( .5, 1 ) );
  180. density = density.mul( sampleGrain( .2, 2 ) );
  181. return smokeAmount.mix( 1, density );
  182. } );
  183. const volumetricMesh = new THREE.Mesh( new THREE.BoxGeometry( 1.5, .5, 1.5 ), volumetricMaterial );
  184. volumetricMesh.receiveShadow = true;
  185. volumetricMesh.position.y = .25;
  186. volumetricMesh.layers.disableAll();
  187. volumetricMesh.layers.enable( LAYER_VOLUMETRIC_LIGHTING );
  188. scene.add( volumetricMesh );
  189. // Scene Pass
  190. const scenePass = pass( scene, camera ).toInspector();
  191. scenePass.name = 'Scene';
  192. const sceneDepth = scenePass.getTextureNode( 'depth' );
  193. sceneDepth.name = 'Scene Depth';
  194. // Material - Apply occlusion depth of volumetric lighting based on the scene depth
  195. volumetricMaterial.depthNode = sceneDepth.sample( screenUV );
  196. // Volumetric Lighting Pass
  197. const volumetricPass = pass( scene, camera, { depthBuffer: false, samples: 0 } ).toInspector( 'Volumetric Lighting / Raw' );
  198. volumetricPass.name = 'Volumetric Lighting';
  199. volumetricPass.setLayers( volumetricLayer );
  200. volumetricPass.setResolutionScale( .5 );
  201. // Compose and Denoise
  202. const bloomPass = bloom( volumetricPass, 1, 1, 0 ).toInspector( 'Volumetric Lighting / Mip-Chain Gaussian Blur' );
  203. bloomPass.name = 'Bloom';
  204. const scenePassColor = scenePass.add( bloomPass.mul( volumetricLightingIntensity ) );
  205. postProcessing.outputNode = scenePassColor;
  206. // Controls
  207. controls = new OrbitControls( camera, renderer.domElement );
  208. controls.target.z = - .05;
  209. controls.target.y = .02;
  210. controls.maxDistance = 1;
  211. window.addEventListener( 'resize', onWindowResize );
  212. }
  213. function onWindowResize() {
  214. camera.aspect = window.innerWidth / window.innerHeight;
  215. camera.updateProjectionMatrix();
  216. renderer.setSize( window.innerWidth, window.innerHeight );
  217. }
  218. function animate() {
  219. for ( const mesh of gltf.children ) {
  220. mesh.rotation.y -= .01;
  221. }
  222. controls.update();
  223. postProcessing.render();
  224. }
  225. </script>
  226. </body>
  227. </html>
粤ICP备19079148号