webgpu_reflection.html 12 KB

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