| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>three.js webgpu - reflection</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
- <link type="text/css" rel="stylesheet" href="example.css">
- </head>
- <body>
- <div id="info">
- <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
- <div class="title-wrapper">
- <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Reflection + Recursive Tree Cubes</span>
- </div>
- <small>
- Based on <a href="https://oosmoxiecode.com/archive/js_webgl/recursive_tree_cubes/" target="_blank" rel="noopener">Recursive Tree Cubes</a>
- by <a href="https://github.com/oosmoxiecode" target="_blank" rel="noopener">oosmoxiecode</a>
- </small>
- </div>
- <script type="importmap">
- {
- "imports": {
- "three": "../build/three.webgpu.js",
- "three/webgpu": "../build/three.webgpu.js",
- "three/tsl": "../build/three.tsl.js",
- "three/addons/": "./jsm/"
- }
- }
- </script>
- <script type="module">
- import * as THREE from 'three/webgpu';
- 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';
- import { gaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
- import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
- import { Inspector } from 'three/addons/inspector/Inspector.js';
- import TWEEN from 'three/addons/libs/tween.module.js';
- let camera, scene, renderer;
- let postProcessing;
- let controls;
- // below uniforms will be animated via TWEEN.js
- const uniformEffector1 = uniform( - 0.2 );
- const uniformEffector2 = uniform( - 0.2 );
- init();
- async function init() {
- camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.25, 30 );
- camera.position.set( 4, 2, 4 );
- scene = new THREE.Scene();
- scene.fog = new THREE.Fog( 0x4195a4, 1, 20 );
- scene.backgroundNode = normalWorldGeometry.y.mix( color( 0x4195a4 ), color( 0x0066ff ) );
- camera.lookAt( 0, 1, 0 );
- const sunLight = new THREE.DirectionalLight( 0xFFE499, 2 );
- sunLight.position.set( 7, 5, 7 );
- sunLight.castShadow = true;
- sunLight.shadow.camera.zoom = 1.5;
- sunLight.shadow.mapSize.set( 1024, 1024 );
- sunLight.shadow.bias = - 0.0001;
- scene.add( sunLight );
- const backLight = new THREE.DirectionalLight( 0x0487e2, 0.5 );
- backLight.position.set( 7, - 5, 7 );
- scene.add( backLight );
- // textures
- const textureLoader = new THREE.TextureLoader();
- const floorColor = await textureLoader.loadAsync( 'textures/floors/FloorsCheckerboard_S_Diffuse.jpg' );
- floorColor.wrapS = THREE.RepeatWrapping;
- floorColor.wrapT = THREE.RepeatWrapping;
- floorColor.colorSpace = THREE.SRGBColorSpace;
- floorColor.repeat.set( 15, 15 );
- const floorNormal = await textureLoader.loadAsync( 'textures/floors/FloorsCheckerboard_S_Normal.jpg' );
- floorNormal.wrapS = THREE.RepeatWrapping;
- floorNormal.wrapT = THREE.RepeatWrapping;
- floorNormal.repeat.set( 15, 15 );
- // tree
- const treeMesh = createTreeMesh();
- treeMesh.castShadow = true;
- treeMesh.receiveShadow = true;
- scene.add( treeMesh );
- // floor
- const floorUV = uv().mul( 15 );
- const floorNormalOffset = texture( floorNormal, floorUV ).xy.mul( 2 ).sub( 1 ).mul( .02 );
- const reflection = reflector( { resolutionScale: 0.2 } );
- reflection.target.rotateX( - Math.PI / 2 );
- reflection.uvNode = reflection.uvNode.add( floorNormalOffset );
- scene.add( reflection.target );
- const floorMaterial = new THREE.MeshPhongNodeMaterial();
- floorMaterial.colorNode = texture( floorColor, floorUV );
- floorMaterial.emissiveNode = reflection.mul( 0.25 );
- floorMaterial.normalMap = floorNormal;
- floorMaterial.normalScale.set( 0.2, - 0.2 );
- const floor = new THREE.Mesh( new THREE.BoxGeometry( 50, .001, 50 ), floorMaterial );
- floor.receiveShadow = true;
- scene.add( floor );
- // renderer
- renderer = new THREE.WebGPURenderer( { antialias: true } );
- renderer.setPixelRatio( window.devicePixelRatio );
- renderer.setSize( window.innerWidth, window.innerHeight );
- renderer.setAnimationLoop( animate );
- renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.inspector = new Inspector();
- document.body.appendChild( renderer.domElement );
- // controls
- controls = new OrbitControls( camera, renderer.domElement );
- controls.minDistance = 1;
- controls.maxDistance = 10;
- controls.maxPolarAngle = Math.PI / 2;
- controls.enableDamping = true;
- controls.autoRotate = true;
- controls.autoRotateSpeed = 1;
- controls.target.set( 0, 1, 0 );
- controls.update();
- // post-processing
- const scenePass = pass( scene, camera );
- const scenePassColor = scenePass.getTextureNode();
- const scenePassDepth = scenePass.getLinearDepthNode().remapClamp( .3, .7 );
- const scenePassColorBlurred = gaussianBlur( scenePassColor );
- scenePassColorBlurred.directionNode = scenePassDepth;
- const vignette = screenUV.distance( .5 ).mul( 1.25 ).clamp().oneMinus().sub( 0.2 );
- postProcessing = new THREE.PostProcessing( renderer );
- postProcessing.outputNode = blendOverlay( scenePassColorBlurred, vignette );
- // tweens
- new TWEEN.Tween( uniformEffector1 )
- .to( { value: 1.2 }, 3000 )
- .delay( 800 )
- .repeat( Infinity )
- .easing( TWEEN.Easing.Sinusoidal.InOut )
- .start();
- new TWEEN.Tween( uniformEffector2 )
- .to( { value: 1.2 }, 3000 )
- .repeat( Infinity )
- .easing( TWEEN.Easing.Sinusoidal.InOut )
- .start();
- //
- window.addEventListener( 'resize', onWindowResize );
- }
- function onWindowResize() {
- camera.aspect = window.innerWidth / window.innerHeight;
- camera.updateProjectionMatrix();
- renderer.setSize( window.innerWidth, window.innerHeight );
- }
- function animate() {
- controls.update();
- TWEEN.update();
- postProcessing.render();
- }
- function random() {
- return ( Math.random() - 0.5 ) * 2.0;
- }
- function createTreeMesh() {
- const maxSteps = 5;
- const lengthMult = 0.8;
- const positions = [];
- const normals = [];
- const colors = [];
- const data = []; // will save seed, size and time
- let instanceCount = 0;
- const newPosition = new THREE.Vector3();
- const position = new THREE.Vector3();
- const normal = new THREE.Vector3();
- const color = new THREE.Color();
- function createTreePart( angle, x, y, z, length, count ) {
- if ( Math.random() > ( maxSteps / count ) * 0.25 ) return;
- if ( count < maxSteps ) {
- const newLength = length * lengthMult;
- const newX = x + Math.cos( angle ) * length;
- const newY = y + Math.sin( angle ) * length;
- const countSq = Math.min( 3.2, count * count );
- const newZ = z + ( Math.random() * countSq - countSq / 2 ) * length;
- let size = 30 - ( count * 8 );
- if ( size > 25 ) size = 25;
- if ( size < 10 ) size = 10;
- size = size / 100;
- const subSteps = 50;
- // below loop generates the instanced data for a tree part
- for ( let i = 0; i < subSteps; i ++ ) {
- instanceCount ++;
- const percent = i / subSteps;
- const extra = 1 / maxSteps;
- // position
- newPosition.set( x, y, z ).lerp( new THREE.Vector3( newX, newY, newZ ), percent );
- position.copy( newPosition );
- position.x += random() * size * 3;
- position.y += random() * size * 3;
- position.z += random() * size * 3;
- positions.push( position.x, position.y, position.z );
- const scale = Math.random() + 5;
- // normal
- normal.copy( position ).sub( newPosition ).normalize();
- normals.push( normal.x, normal.y, normal.z );
- // color
- color.setHSL( ( count / maxSteps ) * 0.5 + Math.random() * 0.05, 0.75, 0.6 + Math.random() * 0.1 );
- colors.push( color.r, color.g, color.b );
- // to save vertex buffers, we store the size, time and seed in a single attribute
- const instanceSize = size * scale;
- const instanceTime = ( count / maxSteps ) + percent * extra;
- const instanceSeed = Math.random();
- data.push( instanceSize, instanceTime, instanceSeed );
- }
- createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
- createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
- createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
- createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
- createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
- createTreePart( angle + random(), newX, newY, newZ, newLength + random(), count + 1 );
- }
- }
- const angle = Math.PI * 0.5;
- // the tree is represented as a collection of instances boxes generated with below recursive function
- createTreePart( angle, 0, 0, 0, 16, 0 );
- const geometry = new THREE.BoxGeometry();
- const material = new THREE.MeshStandardNodeMaterial();
- const mesh = new THREE.Mesh( geometry, material );
- mesh.scale.setScalar( 0.05 );
- mesh.count = instanceCount;
- mesh.frustumCulled = false;
- // instanced data
- const attributePosition = new THREE.InstancedBufferAttribute( new Float32Array( positions ), 3 );
- const attributeNormal = new THREE.InstancedBufferAttribute( new Float32Array( normals ), 3 );
- const attributeColor = new THREE.InstancedBufferAttribute( new Float32Array( colors ), 3 );
- const attributeData = new THREE.InstancedBufferAttribute( new Float32Array( data ), 3 );
- // TSL
- const instancePosition = instancedBufferAttribute( attributePosition );
- const instanceNormal = instancedBufferAttribute( attributeNormal );
- const instanceColor = instancedBufferAttribute( attributeColor );
- const instanceData = instancedBufferAttribute( attributeData );
- material.positionNode = Fn( () => {
- const instanceSize = instanceData.x;
- const instanceTime = instanceData.y;
- const instanceSeed = instanceData.z;
- // effectors (these are responsible for the blob-like scale effects)
- const dif1 = abs( instanceTime.sub( uniformEffector1 ) ).toConst();
- let effect = dif1.lessThanEqual( 0.15 ).select( sub( 0.15, dif1 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), float( 0 ) );
- const dif2 = abs( instanceTime.sub( uniformEffector2 ) ).toConst();
- effect = dif2.lessThanEqual( 0.15 ).select( sub( 0.15, dif2 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), effect );
- // accumulate different vertex animations
- let animated = positionLocal.add( instancePosition ).toVar();
- const direction = positionGeometry.normalize().toConst();
- animated = animated.add( direction.mul( effect.add( instanceSize ) ) );
- animated = animated.sub( direction.mul( effect ) );
- animated = animated.add( instanceNormal.mul( effect.mul( 1 ) ) );
- animated = animated.add( instanceNormal.mul( abs( sin( time.add( instanceSeed.mul( 2 ) ) ).mul( 1.5 ) ) ) );
- return animated;
- } )();
- const squareEdge = Fn( () => {
- const pos = uv().sub( vec2( 0.5, 0.5 ) );
- const squareDistance = max( abs( pos.x ), abs( pos.y ) );
- return squareDistance.div( 0.5 ).clamp( 0.85, 1 ).sub( 0.5 ).mul( 2.0 );
- } )();
- material.colorNode = Fn( () => {
- return squareEdge.sub( instanceColor );
- } )();
- material.emissiveNode = Fn( () => {
- const instanceTime = instanceData.y;
- const dif1 = abs( instanceTime.sub( uniformEffector1 ) ).toConst();
- const effect1 = dif1.lessThanEqual( 0.15 ).select( sub( 0.15, dif1 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), float( 0 ) );
- const dif2 = abs( instanceTime.sub( uniformEffector2 ) ).toConst();
- const effect2 = dif2.lessThanEqual( 0.15 ).select( sub( 0.15, dif2 ).mul( sub( 1.7, instanceTime ).mul( 10 ) ), effect1 );
- return pow2( vec3( effect1, 0, effect2 ) ).mul( instanceColor );
- } )();
- return mesh;
- }
- </script>
- </body>
- </html>
|