webgpu_reflection.html 12 KB

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