webgpu_reflection.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgpu - reflection<br/>
  12. Based on <a href="https://web.archive.org/web/20210101053442/http://oos.moxiecode.com/js_webgl/recursive_tree_cubes/" target="_blank" rel="noopener">Recursive Tree Cubes</a>
  13. by <a href="https://github.com/oosmoxiecode" target="_blank" rel="noopener">oosmoxiecode</a>
  14. </div>
  15. <script type="importmap">
  16. {
  17. "imports": {
  18. "three": "../build/three.webgpu.js",
  19. "three/webgpu": "../build/three.webgpu.js",
  20. "three/tsl": "../build/three.tsl.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import { abs, color, div, float, Fn, instancedBufferAttribute, materialColor, min, normalWorldGeometry, pass, positionGeometry, positionLocal, reflector, screenUV, sin, sub, texture, time, uniform, uv, varyingProperty } from 'three/tsl';
  28. import { gaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
  29. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  30. import Stats from 'three/addons/libs/stats.module.js';
  31. import TWEEN from 'three/addons/libs/tween.module.js';
  32. let camera, scene, renderer;
  33. let postProcessing;
  34. let controls;
  35. let stats;
  36. // below uniforms will be animated via TWEEN.js
  37. const uniformLife = uniform( 0 );
  38. const uniformEffector1 = uniform( - 0.2 );
  39. const uniformEffector2 = uniform( - 0.2 );
  40. init();
  41. function init() {
  42. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.25, 30 );
  43. camera.position.set( 4, 2, 4 );
  44. scene = new THREE.Scene();
  45. scene.fog = new THREE.Fog( 0x0487e2, 7, 25 );
  46. scene.backgroundNode = normalWorldGeometry.y.mix( color( 0x0487e2 ), color( 0x0066ff ) );
  47. camera.lookAt( 0, 1, 0 );
  48. const sunLight = new THREE.DirectionalLight( 0xFFE499, 3 );
  49. sunLight.position.set( 7, 3, 7 );
  50. const waterAmbientLight = new THREE.HemisphereLight( 0x333366, 0x74ccf4, 3 );
  51. const skyAmbientLight = new THREE.HemisphereLight( 0x74ccf4, 0, 1 );
  52. scene.add( sunLight );
  53. scene.add( skyAmbientLight );
  54. scene.add( waterAmbientLight );
  55. // textures
  56. const textureLoader = new THREE.TextureLoader();
  57. const floorColor = textureLoader.load( 'textures/floors/FloorsCheckerboard_S_Diffuse.jpg' );
  58. floorColor.wrapS = THREE.RepeatWrapping;
  59. floorColor.wrapT = THREE.RepeatWrapping;
  60. floorColor.colorSpace = THREE.SRGBColorSpace;
  61. const floorNormal = textureLoader.load( 'textures/floors/FloorsCheckerboard_S_Normal.jpg' );
  62. floorNormal.wrapS = THREE.RepeatWrapping;
  63. floorNormal.wrapT = THREE.RepeatWrapping;
  64. // tree
  65. const treeMesh = createTreeMesh();
  66. scene.add( treeMesh );
  67. // floor
  68. const floorUV = uv().mul( 15 );
  69. const floorNormalOffset = texture( floorNormal, floorUV ).xy.mul( 2 ).sub( 1 ).mul( .02 );
  70. const reflection = reflector( { resolution: 0.5 } ); // 0.5 is half of the rendering view
  71. reflection.target.rotateX( - Math.PI / 2 );
  72. reflection.uvNode = reflection.uvNode.add( floorNormalOffset );
  73. scene.add( reflection.target );
  74. const floorMaterial = new THREE.MeshPhongNodeMaterial();
  75. floorMaterial.colorNode = texture( floorColor, floorUV ).add( reflection );
  76. const floor = new THREE.Mesh( new THREE.BoxGeometry( 50, .001, 50 ), floorMaterial );
  77. floor.position.set( 0, 0, 0 );
  78. scene.add( floor );
  79. // renderer
  80. renderer = new THREE.WebGPURenderer( { antialias: true } );
  81. renderer.setPixelRatio( window.devicePixelRatio );
  82. renderer.setSize( window.innerWidth, window.innerHeight );
  83. renderer.setAnimationLoop( animate );
  84. document.body.appendChild( renderer.domElement );
  85. stats = new Stats();
  86. document.body.appendChild( stats.dom );
  87. // controls
  88. controls = new OrbitControls( camera, renderer.domElement );
  89. controls.minDistance = 1;
  90. controls.maxDistance = 10;
  91. controls.maxPolarAngle = Math.PI / 2;
  92. controls.autoRotate = true;
  93. controls.autoRotateSpeed = 1;
  94. controls.target.set( 0, 1, 0 );
  95. controls.update();
  96. // post-processing
  97. const scenePass = pass( scene, camera );
  98. const scenePassColor = scenePass.getTextureNode();
  99. const scenePassDepth = scenePass.getLinearDepthNode().remapClamp( .3, .7 );
  100. const scenePassColorBlurred = gaussianBlur( scenePassColor );
  101. scenePassColorBlurred.directionNode = scenePassDepth;
  102. const vignette = screenUV.distance( .5 ).mul( 1.35 ).clamp().oneMinus();
  103. postProcessing = new THREE.PostProcessing( renderer );
  104. postProcessing.outputNode = scenePassColorBlurred.mul( vignette );
  105. //
  106. window.addEventListener( 'resize', onWindowResize );
  107. //
  108. startTweens();
  109. }
  110. function onWindowResize() {
  111. camera.aspect = window.innerWidth / window.innerHeight;
  112. camera.updateProjectionMatrix();
  113. renderer.setSize( window.innerWidth, window.innerHeight );
  114. }
  115. function animate() {
  116. stats.update();
  117. controls.update();
  118. TWEEN.update();
  119. postProcessing.render();
  120. }
  121. function startTweens() {
  122. const lifeTween = new TWEEN.Tween( uniformLife )
  123. .to( { value: 1 }, 5000 )
  124. .easing( TWEEN.Easing.Bounce.Out );
  125. lifeTween.start();
  126. const effectTween = new TWEEN.Tween( uniformEffector1 )
  127. .to( { value: 1.2 }, 2500 )
  128. .delay( 3000 )
  129. .easing( TWEEN.Easing.Sinusoidal.InOut )
  130. .onComplete( function () {
  131. secondaryTweens();
  132. } );
  133. effectTween.start();
  134. }
  135. function secondaryTweens() {
  136. uniformEffector1.value = - 0.2;
  137. uniformEffector2.value = - 0.2;
  138. const effect2Tween = new TWEEN.Tween( uniformEffector2 )
  139. .to( { value: 1.2 }, 3000 )
  140. .repeat( Infinity )
  141. .easing( TWEEN.Easing.Sinusoidal.InOut );
  142. effect2Tween.start();
  143. const effectTween = new TWEEN.Tween( uniformEffector1 )
  144. .to( { value: 1.2 }, 3000 )
  145. .delay( 800 )
  146. .repeat( Infinity )
  147. .easing( TWEEN.Easing.Sinusoidal.InOut );
  148. effectTween.start();
  149. }
  150. function createTreeMesh() {
  151. const maxSteps = 6;
  152. const angleLeft = Math.PI / 180 * 30;
  153. const angleRight = Math.PI / 180 * 40;
  154. const lengthMult = 0.88;
  155. const positions = [];
  156. const normals = [];
  157. const colors = [];
  158. const data = []; // will save seed, size and time
  159. let instanceCount = 0;
  160. const newPosition = new THREE.Vector3();
  161. const position = new THREE.Vector3();
  162. const normal = new THREE.Vector3();
  163. const color = new THREE.Color();
  164. function createTreePart( angle, x, y, z, length, count ) {
  165. if ( count < maxSteps ) {
  166. const newLength = length * lengthMult;
  167. const newX = x + Math.cos( angle ) * length;
  168. const newY = y + Math.sin( angle ) * length;
  169. const countSq = Math.min( 3.2, count * count );
  170. const newZ = z + ( Math.random() * countSq - countSq / 2 ) * length;
  171. let size = 30 - ( count * 8 );
  172. if ( size > 25 ) size = 25;
  173. if ( size < 10 ) size = 10;
  174. size = size / 10;
  175. const subSteps = 60;
  176. // below loop generates the instanced data for a tree part
  177. for ( let i = 0; i < subSteps; i ++ ) {
  178. instanceCount ++;
  179. const percent = i / subSteps;
  180. const extra = 1 / maxSteps;
  181. // position
  182. newPosition.set( x, y, z ).lerp( new THREE.Vector3( newX, newY, newZ ), percent );
  183. position.copy( newPosition );
  184. position.x += Math.random() * ( size * 3 ) - ( size * 1.5 );
  185. position.y += Math.random() * ( size * 3 ) - ( size * 1.5 );
  186. position.z += Math.random() * ( size * 3 ) - ( size * 1.5 );
  187. positions.push( position.x, position.y, position.z );
  188. const scale = 0.25 * Math.random();
  189. // normal
  190. normal.copy( position ).sub( newPosition ).normalize();
  191. normals.push( normal.x, normal.y, normal.z );
  192. // color
  193. color.setHSL( 0.55 + Math.random() * 0.05, 1.0, 0.7 + Math.random() * 0.3 );
  194. colors.push( color.r, color.g, color.b );
  195. // to save vertex buffers, we store the size, time and seed in a single attribute
  196. const instanceSize = size * scale;
  197. const instanceTime = ( count / maxSteps ) + percent * extra;
  198. const instanceSeed = Math.random();
  199. data.push( instanceSize, instanceTime, instanceSeed );
  200. }
  201. createTreePart( angle - angleRight, newX, newY, newZ, newLength, count + 1 );
  202. createTreePart( angle + angleLeft, newX, newY, newZ, newLength, count + 1 );
  203. }
  204. }
  205. const angle = Math.PI * 0.5;
  206. // the tree is represented as a collection of instances boxes generated with below recursive function
  207. createTreePart( angle, 0, 0, 0, 16, 0 );
  208. const geometry = new THREE.BoxGeometry();
  209. const material = new THREE.MeshStandardNodeMaterial();
  210. const mesh = new THREE.Mesh( geometry, material );
  211. mesh.scale.setScalar( 0.05 );
  212. mesh.count = instanceCount;
  213. mesh.frustumCulled = false;
  214. // instanced data
  215. const attributePosition = new THREE.InstancedBufferAttribute( new Float32Array( positions ), 3 );
  216. const attributeNormal = new THREE.InstancedBufferAttribute( new Float32Array( normals ), 3 );
  217. const attributeColor = new THREE.InstancedBufferAttribute( new Float32Array( colors ), 3 );
  218. const attributeData = new THREE.InstancedBufferAttribute( new Float32Array( data ), 3 );
  219. // TSL
  220. const vVisbility = varyingProperty( 'float' );
  221. const instancePosition = instancedBufferAttribute( attributePosition );
  222. const instanceNormal = instancedBufferAttribute( attributeNormal );
  223. const instanceColor = instancedBufferAttribute( attributeColor );
  224. const instanceData = instancedBufferAttribute( attributeData );
  225. material.positionNode = Fn( () => {
  226. const instanceSize = instanceData.x;
  227. const instanceTime = instanceData.y;
  228. const instanceSeed = instanceData.z;
  229. // effectors (these are responsible for the blob-like scale effects)
  230. const dif1 = abs( instanceTime.sub( uniformEffector1 ) ).toConst();
  231. let effect = dif1.lessThanEqual( 0.15 ).select( sub( 0.15, dif1 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), float( 0 ) );
  232. const dif2 = abs( instanceTime.sub( uniformEffector2 ) ).toConst();
  233. effect = dif2.lessThanEqual( 0.15 ).select( sub( 0.15, dif2 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), effect );
  234. // life (controls the visibility and initial scale of the cubes)
  235. const scale = uniformLife.greaterThan( instanceTime ).select( min( 1, div( uniformLife.sub( instanceTime ), 0 ) ) ).oneMinus();
  236. vVisbility.assign( uniformLife.greaterThan( instanceTime ).select( 1, 0 ) );
  237. // accumulate different vertex animations
  238. let animated = positionLocal.add( instancePosition ).toVar();
  239. const direction = positionGeometry.normalize().toConst();
  240. animated = animated.add( direction.mul( effect.add( instanceSize ) ) );
  241. animated = animated.sub( direction.mul( scale ) );
  242. animated = animated.add( instanceNormal.mul( effect.mul( 1 ) ) );
  243. animated = animated.add( instanceNormal.mul( abs( sin( time.add( instanceSeed.mul( 2 ) ) ).mul( 1.5 ) ) ) );
  244. return animated;
  245. } )();
  246. material.colorNode = Fn( () => {
  247. vVisbility.equal( 0 ).discard();
  248. return materialColor.mul( instanceColor );
  249. } )();
  250. return mesh;
  251. }
  252. </script>
  253. </body>
  254. </html>
粤ICP备19079148号