webgpu_reflection.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - reflection</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 - reflection">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_reflection.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_reflection.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>Reflection + Recursive Tree Cubes</span>
  18. </div>
  19. <small>
  20. Based on <a href="https://oosmoxiecode.com/archive/js_webgl/recursive_tree_cubes/" target="_blank" rel="noopener">Recursive Tree Cubes</a>
  21. by <a href="https://github.com/oosmoxiecode" target="_blank" rel="noopener">oosmoxiecode</a>
  22. </small>
  23. </div>
  24. <script type="importmap">
  25. {
  26. "imports": {
  27. "three": "../build/three.webgpu.js",
  28. "three/webgpu": "../build/three.webgpu.js",
  29. "three/tsl": "../build/three.tsl.js",
  30. "three/addons/": "./jsm/"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three/webgpu';
  36. import { abs, blendOverlay, color, float, Fn, instancedBufferAttribute, max, normalWorldGeometry, pass, positionGeometry, positionLocal, pow2, reflector, screenUV, sin, sub, texture, time, uniform, uv, vec2, vec3 } from 'three/tsl';
  37. import { gaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
  38. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  39. import { Inspector } from 'three/addons/inspector/Inspector.js';
  40. import TWEEN from 'three/addons/libs/tween.module.js';
  41. let camera, scene, renderer;
  42. let renderPipeline;
  43. let controls;
  44. // below uniforms will be animated via TWEEN.js
  45. const uniformEffector1 = uniform( - 0.2 );
  46. const uniformEffector2 = uniform( - 0.2 );
  47. init();
  48. async function init() {
  49. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.25, 30 );
  50. camera.position.set( 4, 2, 4 );
  51. scene = new THREE.Scene();
  52. scene.fog = new THREE.Fog( 0x4195a4, 1, 20 );
  53. scene.backgroundNode = normalWorldGeometry.y.mix( color( 0x4195a4 ), color( 0x0066ff ) );
  54. camera.lookAt( 0, 1, 0 );
  55. const sunLight = new THREE.DirectionalLight( 0xFFE499, 2 );
  56. sunLight.position.set( 7, 5, 7 );
  57. sunLight.castShadow = true;
  58. sunLight.shadow.camera.zoom = 1.5;
  59. sunLight.shadow.mapSize.set( 1024, 1024 );
  60. sunLight.shadow.bias = - 0.0001; // remove self-shadowing artifacts
  61. scene.add( sunLight );
  62. const backLight = new THREE.DirectionalLight( 0x0487e2, 0.5 );
  63. backLight.position.set( 7, - 5, 7 );
  64. scene.add( backLight );
  65. // textures
  66. const textureLoader = new THREE.TextureLoader();
  67. const floorColor = await textureLoader.loadAsync( 'textures/floors/FloorsCheckerboard_S_Diffuse.jpg' );
  68. floorColor.wrapS = THREE.RepeatWrapping;
  69. floorColor.wrapT = THREE.RepeatWrapping;
  70. floorColor.colorSpace = THREE.SRGBColorSpace;
  71. floorColor.repeat.set( 15, 15 );
  72. const floorNormal = await textureLoader.loadAsync( 'textures/floors/FloorsCheckerboard_S_Normal.jpg' );
  73. floorNormal.wrapS = THREE.RepeatWrapping;
  74. floorNormal.wrapT = THREE.RepeatWrapping;
  75. floorNormal.repeat.set( 15, 15 );
  76. // tree
  77. const treeMesh = createTreeMesh();
  78. treeMesh.castShadow = true;
  79. treeMesh.receiveShadow = true;
  80. scene.add( treeMesh );
  81. // floor
  82. const floorUV = uv().mul( 15 );
  83. const floorNormalOffset = texture( floorNormal, floorUV ).xy.mul( 2 ).sub( 1 ).mul( .02 );
  84. const reflection = reflector( { resolutionScale: 0.2 } );
  85. reflection.target.rotateX( - Math.PI / 2 );
  86. reflection.uvNode = reflection.uvNode.add( floorNormalOffset );
  87. scene.add( reflection.target );
  88. const floorMaterial = new THREE.MeshPhongNodeMaterial();
  89. floorMaterial.colorNode = texture( floorColor, floorUV );
  90. floorMaterial.emissiveNode = reflection.mul( 0.25 );
  91. floorMaterial.normalMap = floorNormal;
  92. floorMaterial.normalScale.set( 0.2, - 0.2 );
  93. const floor = new THREE.Mesh( new THREE.BoxGeometry( 50, .001, 50 ), floorMaterial );
  94. floor.receiveShadow = true;
  95. scene.add( floor );
  96. // renderer
  97. renderer = new THREE.WebGPURenderer( { antialias: true } );
  98. renderer.setPixelRatio( window.devicePixelRatio );
  99. renderer.setSize( window.innerWidth, window.innerHeight );
  100. renderer.setAnimationLoop( animate );
  101. renderer.shadowMap.enabled = true;
  102. renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  103. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  104. renderer.inspector = new Inspector();
  105. document.body.appendChild( renderer.domElement );
  106. // controls
  107. controls = new OrbitControls( camera, renderer.domElement );
  108. controls.minDistance = 1;
  109. controls.maxDistance = 10;
  110. controls.maxPolarAngle = Math.PI / 2;
  111. controls.enableDamping = true;
  112. controls.autoRotate = true;
  113. controls.autoRotateSpeed = 1;
  114. controls.target.set( 0, 1, 0 );
  115. controls.update();
  116. // post-processing
  117. const scenePass = pass( scene, camera );
  118. const scenePassColor = scenePass.getTextureNode();
  119. const scenePassDepth = scenePass.getLinearDepthNode().remapClamp( .3, .7 );
  120. const scenePassColorBlurred = gaussianBlur( scenePassColor );
  121. scenePassColorBlurred.directionNode = scenePassDepth;
  122. const vignette = screenUV.distance( .5 ).mul( 1.25 ).clamp().oneMinus().sub( 0.2 );
  123. renderPipeline = new THREE.RenderPipeline( renderer );
  124. renderPipeline.outputNode = blendOverlay( scenePassColorBlurred, vignette );
  125. // tweens
  126. new TWEEN.Tween( uniformEffector1 )
  127. .to( { value: 1.2 }, 3000 )
  128. .delay( 800 )
  129. .repeat( Infinity )
  130. .easing( TWEEN.Easing.Sinusoidal.InOut )
  131. .start();
  132. new TWEEN.Tween( uniformEffector2 )
  133. .to( { value: 1.2 }, 3000 )
  134. .repeat( Infinity )
  135. .easing( TWEEN.Easing.Sinusoidal.InOut )
  136. .start();
  137. //
  138. window.addEventListener( 'resize', onWindowResize );
  139. }
  140. function onWindowResize() {
  141. camera.aspect = window.innerWidth / window.innerHeight;
  142. camera.updateProjectionMatrix();
  143. renderer.setSize( window.innerWidth, window.innerHeight );
  144. }
  145. function animate() {
  146. controls.update();
  147. TWEEN.update();
  148. renderPipeline.render();
  149. }
  150. function random() {
  151. return ( Math.random() - 0.5 ) * 2.0;
  152. }
  153. function createTreeMesh() {
  154. const maxSteps = 5;
  155. const lengthMult = 0.8;
  156. const positions = [];
  157. const normals = [];
  158. const colors = [];
  159. const data = []; // will save seed, size and time
  160. let instanceCount = 0;
  161. const newPosition = new THREE.Vector3();
  162. const position = new THREE.Vector3();
  163. const normal = new THREE.Vector3();
  164. const color = new THREE.Color();
  165. function createTreePart( angle, x, y, z, length, count ) {
  166. if ( Math.random() > ( maxSteps / count ) * 0.25 ) return;
  167. if ( count < maxSteps ) {
  168. const newLength = length * lengthMult;
  169. const newX = x + Math.cos( angle ) * length;
  170. const newY = y + Math.sin( angle ) * length;
  171. const countSq = Math.min( 3.2, count * count );
  172. const newZ = z + ( Math.random() * countSq - countSq / 2 ) * length;
  173. let size = 30 - ( count * 8 );
  174. if ( size > 25 ) size = 25;
  175. if ( size < 10 ) size = 10;
  176. size = size / 100;
  177. const subSteps = 50;
  178. // below loop generates the instanced data for a tree part
  179. for ( let i = 0; i < subSteps; i ++ ) {
  180. instanceCount ++;
  181. const percent = i / subSteps;
  182. const extra = 1 / maxSteps;
  183. // position
  184. newPosition.set( x, y, z ).lerp( new THREE.Vector3( newX, newY, newZ ), percent );
  185. position.copy( newPosition );
  186. position.x += random() * size * 3;
  187. position.y += random() * size * 3;
  188. position.z += random() * size * 3;
  189. positions.push( position.x, position.y, position.z );
  190. const scale = Math.random() + 5;
  191. // normal
  192. normal.copy( position ).sub( newPosition ).normalize();
  193. normals.push( normal.x, normal.y, normal.z );
  194. // color
  195. color.setHSL( ( count / maxSteps ) * 0.5 + Math.random() * 0.05, 0.75, 0.6 + Math.random() * 0.1 );
  196. colors.push( color.r, color.g, color.b );
  197. // to save vertex buffers, we store the size, time and seed in a single attribute
  198. const instanceSize = size * scale;
  199. const instanceTime = ( count / maxSteps ) + percent * extra;
  200. const instanceSeed = Math.random();
  201. data.push( instanceSize, instanceTime, instanceSeed );
  202. }
  203. createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
  204. createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
  205. createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
  206. createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
  207. createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
  208. createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
  209. }
  210. }
  211. const angle = Math.PI * 0.5;
  212. // the tree is represented as a collection of instances boxes generated with below recursive function
  213. createTreePart( angle, 0, 0, 0, 16, 0 );
  214. const geometry = new THREE.BoxGeometry();
  215. const material = new THREE.MeshStandardNodeMaterial();
  216. const mesh = new THREE.Mesh( geometry, material );
  217. mesh.scale.setScalar( 0.05 );
  218. mesh.count = instanceCount;
  219. mesh.frustumCulled = false;
  220. // instanced data
  221. const attributePosition = new THREE.InstancedBufferAttribute( new Float32Array( positions ), 3 );
  222. const attributeNormal = new THREE.InstancedBufferAttribute( new Float32Array( normals ), 3 );
  223. const attributeColor = new THREE.InstancedBufferAttribute( new Float32Array( colors ), 3 );
  224. const attributeData = new THREE.InstancedBufferAttribute( new Float32Array( data ), 3 );
  225. // TSL
  226. const instancePosition = instancedBufferAttribute( attributePosition );
  227. const instanceNormal = instancedBufferAttribute( attributeNormal );
  228. const instanceColor = instancedBufferAttribute( attributeColor );
  229. const instanceData = instancedBufferAttribute( attributeData );
  230. material.positionNode = Fn( () => {
  231. const instanceSize = instanceData.x;
  232. const instanceTime = instanceData.y;
  233. const instanceSeed = instanceData.z;
  234. // effectors (these are responsible for the blob-like scale effects)
  235. const dif1 = abs( instanceTime.sub( uniformEffector1 ) ).toConst();
  236. let effect = dif1.lessThanEqual( 0.15 ).select( sub( 0.15, dif1 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), float( 0 ) );
  237. const dif2 = abs( instanceTime.sub( uniformEffector2 ) ).toConst();
  238. effect = dif2.lessThanEqual( 0.15 ).select( sub( 0.15, dif2 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), effect );
  239. // accumulate different vertex animations
  240. let animated = positionLocal.add( instancePosition ).toVar();
  241. const direction = positionGeometry.normalize().toConst();
  242. animated = animated.add( direction.mul( effect.add( instanceSize ) ) );
  243. animated = animated.sub( direction.mul( effect ) );
  244. animated = animated.add( instanceNormal.mul( effect.mul( 1 ) ) );
  245. animated = animated.add( instanceNormal.mul( abs( sin( time.add( instanceSeed.mul( 2 ) ) ).mul( 1.5 ) ) ) );
  246. return animated;
  247. } )();
  248. const squareEdge = Fn( () => {
  249. const pos = uv().sub( vec2( 0.5, 0.5 ) );
  250. const squareDistance = max( abs( pos.x ), abs( pos.y ) );
  251. return squareDistance.div( 0.5 ).clamp( 0.85, 1 ).sub( 0.5 ).mul( 2.0 );
  252. } )();
  253. material.colorNode = Fn( () => {
  254. return squareEdge.sub( instanceColor );
  255. } )();
  256. material.emissiveNode = Fn( () => {
  257. const instanceTime = instanceData.y;
  258. const dif1 = abs( instanceTime.sub( uniformEffector1 ) ).toConst();
  259. const effect1 = dif1.lessThanEqual( 0.15 ).select( sub( 0.15, dif1 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), float( 0 ) );
  260. const dif2 = abs( instanceTime.sub( uniformEffector2 ) ).toConst();
  261. const effect2 = dif2.lessThanEqual( 0.15 ).select( sub( 0.15, dif2 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), effect1 );
  262. return pow2( vec3( effect1, 0, effect2 ) ).mul( instanceColor );
  263. } )();
  264. return mesh;
  265. }
  266. </script>
  267. </body>
  268. </html>
粤ICP备19079148号