瀏覽代碼

WebGPU: Compute Particles (#26655)

* StorageBuffer: Fix shared material

* StackNode: Use ShaderNode instead of shader

* TSL: storage().toAttribute() and attribute argument for bufferAttribute()

* add `webgpu_compute_particles` example

* add floor friction

* add size option

* precompute colors

* update native hash
sunag 1 年之前
父節點
當前提交
7050247031

+ 1 - 0
examples/files.json

@@ -312,6 +312,7 @@
 		"webgpu_backdrop_area",
 		"webgpu_clearcoat",
 		"webgpu_compute",
+		"webgpu_compute_particles",
 		"webgpu_compute_texture",
 		"webgpu_cubemap_adjustments",
 		"webgpu_cubemap_dynamic",

+ 28 - 2
examples/jsm/nodes/accessors/BufferAttributeNode.js

@@ -1,12 +1,12 @@
 import InputNode from '../core/InputNode.js';
 import { addNodeClass } from '../core/Node.js';
 import { varying } from '../core/VaryingNode.js';
-import { nodeObject } from '../shadernode/ShaderNode.js';
+import { nodeObject, addNodeElement } from '../shadernode/ShaderNode.js';
 import { InterleavedBufferAttribute, InterleavedBuffer, StaticDrawUsage, DynamicDrawUsage } from 'three';
 
 class BufferAttributeNode extends InputNode {
 
-	constructor( value, bufferType, bufferStride = 0, bufferOffset = 0 ) {
+	constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
 
 		super( value, bufferType );
 
@@ -19,10 +19,34 @@ class BufferAttributeNode extends InputNode {
 		this.usage = StaticDrawUsage;
 		this.instanced = false;
 
+		this.attribute = null;
+
+		if ( value && value.isBufferAttribute === true ) {
+
+			this.attribute = value;
+			this.usage = value.usage;
+			this.instanced = value.isInstancedBufferAttribute;
+
+		}
+
+	}
+
+	getNodeType( builder ) {
+
+		if ( this.bufferType === null ) {
+
+			this.bufferType = builder.getTypeFromAttribute( this.attribute );
+
+		}
+
+		return this.bufferType;
+
 	}
 
 	construct( builder ) {
 
+		if ( this.attribute !== null ) return;
+
 		const type = this.getNodeType( builder );
 		const array = this.value;
 		const itemSize = builder.getTypeLength( type );
@@ -96,4 +120,6 @@ export const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferA
 export const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
 export const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
 
+addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
+
 addNodeClass( BufferAttributeNode );

+ 4 - 4
examples/jsm/nodes/core/StackNode.js

@@ -4,7 +4,7 @@ import { bypass } from '../core/BypassNode.js';
 import { expression } from '../code/ExpressionNode.js';
 import { cond } from '../math/CondNode.js';
 import { loop } from '../utils/LoopNode.js';
-import { nodeProxy, shader } from '../shadernode/ShaderNode.js';
+import { ShaderNode, nodeProxy } from '../shadernode/ShaderNode.js';
 
 class StackNode extends Node {
 
@@ -39,7 +39,7 @@ class StackNode extends Node {
 
 	if( boolNode, method ) {
 
-		const methodNode = shader( method );
+		const methodNode = new ShaderNode( method );
 		this._currentCond = cond( boolNode, methodNode );
 
 		return this.add( this._currentCond );
@@ -48,7 +48,7 @@ class StackNode extends Node {
 
 	elseif( boolNode, method ) {
 
-		const methodNode = shader( method );
+		const methodNode = new ShaderNode( method );
 		const ifNode = cond( boolNode, methodNode );
 
 		this._currentCond.elseNode = ifNode;
@@ -60,7 +60,7 @@ class StackNode extends Node {
 
 	else( method ) {
 
-		this._currentCond.elseNode = shader( method );
+		this._currentCond.elseNode = new ShaderNode( method );
 
 		return this;
 

+ 1 - 1
examples/jsm/renderers/common/StorageBuffer.js

@@ -4,7 +4,7 @@ class StorageBuffer extends Buffer {
 
 	constructor( name, attribute ) {
 
-		super( name, attribute.array );
+		super( name, attribute ? attribute.array : null );
 
 		this.attribute = attribute;
 

二進制
examples/screenshots/webgpu_compute_particles.jpg


+ 269 - 0
examples/webgpu_compute_particles.html

@@ -0,0 +1,269 @@
+<html lang="en">
+	<head>
+		<title>three.js - WebGPU - Compute Particles</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="main.css">
+	</head>
+	<body>
+
+		<div id="info">
+			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - GPU Compute Particles / 100000 Particles
+		</div>
+
+		<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
+
+		<script type="importmap">
+			{
+				"imports": {
+					"three": "../build/three.module.js",
+					"three/addons/": "./jsm/",
+					"three/nodes": "./jsm/nodes/Nodes.js"
+				}
+			}
+		</script>
+
+		<script type="module">
+
+			import * as THREE from 'three';
+			import { ShaderNode, uniform, texture, instanceIndex, float, vec3, storage, SpriteNodeMaterial } from 'three/nodes';
+
+			import WebGPU from 'three/addons/capabilities/WebGPU.js';
+			import WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';
+
+			import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+
+			import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
+
+			const particleCount = 100000;
+
+			const gravity = uniform( - .0098 );
+			const bounce = uniform( .8 );
+			const friction = uniform( .99 );
+			const size = uniform( .12 );
+
+			const clickPosition = uniform( new THREE.Vector3() );
+
+			let camera, scene, renderer;
+			let controls;
+			let computeParticles;
+
+			init();
+
+			function init() {
+
+				if ( WebGPU.isAvailable() === false ) {
+
+					document.body.appendChild( WebGPU.getErrorMessage() );
+
+					throw new Error( 'No WebGPU support' );
+
+				}
+
+				const { innerWidth, innerHeight } = window;
+
+				camera = new THREE.PerspectiveCamera( 50, innerWidth / innerHeight, .1, 1000 );
+				camera.position.set( 40, 15, 40 );
+
+				scene = new THREE.Scene();
+
+				// textures
+
+				const textureLoader = new THREE.TextureLoader();
+				const map = textureLoader.load( 'textures/sprite1.png' );
+
+				//
+
+				const createBuffer = () => storage( new THREE.InstancedBufferAttribute( new Float32Array( particleCount * 4 ), 4 ), 'vec3', particleCount );
+
+				const positionBuffer = createBuffer();
+				const velocityBuffer = createBuffer();
+				const colorBuffer = createBuffer();
+
+				// compute
+
+				const computeInit = new ShaderNode( ( stack ) => {
+
+					const position = positionBuffer.element( instanceIndex );
+					const color = colorBuffer.element( instanceIndex );
+
+					const randX = instanceIndex.hash();
+					const randY = instanceIndex.add( 2 ).hash();
+					const randZ = instanceIndex.add( 3 ).hash();
+
+					stack.assign( position.x, randX.mul( 60 ).add( - 30 ) );
+					stack.assign( position.y, randY.mul( 10 ) );
+					stack.assign( position.z, randZ.mul( 60 ).add( - 30 ) );
+
+					stack.assign( color, vec3( randX, randY, randZ ) );
+
+				} ).compute( particleCount );
+
+				//
+
+				const computeUpdate = new ShaderNode( ( stack ) => {
+
+					const position = positionBuffer.element( instanceIndex );
+					const velocity = velocityBuffer.element( instanceIndex );
+
+					stack.assign( velocity, velocity.add( vec3( 0.00, gravity, 0.00 ) ) );
+					stack.assign( position, position.add( velocity ) );
+
+					stack.assign( velocity, velocity.mul( friction ) );
+
+					// floor
+
+					stack.if( position.y.lessThan( 0 ), ( stack ) => {
+
+						stack.assign( position.y, 0 );
+						stack.assign( velocity.y, velocity.y.negate().mul( bounce ) );
+
+						// floor friction
+
+						stack.assign( velocity.x, velocity.x.mul( .9 ) );
+						stack.assign( velocity.z, velocity.z.mul( .9 ) );
+
+					} );
+
+				} );
+
+				computeParticles = computeUpdate.compute( particleCount );
+
+				// create nodes
+
+				const textureNode = texture( map );
+
+				// create particles
+
+				const particleMaterial = new SpriteNodeMaterial();
+				particleMaterial.colorNode = textureNode.mul( colorBuffer.element( instanceIndex ) );
+				particleMaterial.positionNode = positionBuffer.toAttribute();
+				particleMaterial.scaleNode = size;
+				particleMaterial.depthWrite = false;
+				particleMaterial.depthTest = true;
+				particleMaterial.transparent = true;
+
+				const particles = new THREE.Mesh( new THREE.PlaneGeometry( 1, 1 ), particleMaterial );
+				particles.isInstancedMesh = true;
+				particles.count = particleCount;
+				scene.add( particles );
+
+				//
+
+				const helper = new THREE.GridHelper( 60, 40, 0x303030, 0x303030 );
+				scene.add( helper );
+
+				const geometry = new THREE.PlaneGeometry( 1000, 1000 );
+				geometry.rotateX( - Math.PI / 2 );
+
+				const plane = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { visible: false } ) );
+				scene.add( plane );
+
+				const raycaster = new THREE.Raycaster();
+				const pointer = new THREE.Vector2();
+
+				//
+
+				renderer = new WebGPURenderer( { antialias: true } );
+				renderer.setPixelRatio( window.devicePixelRatio );
+				renderer.setSize( window.innerWidth, window.innerHeight );
+				renderer.setAnimationLoop( render );
+				document.body.appendChild( renderer.domElement );
+
+				//
+
+				renderer.compute( computeInit );
+
+				// click event
+
+				const computeHit = new ShaderNode( ( stack ) => {
+
+					const position = positionBuffer.element( instanceIndex );
+					const velocity = velocityBuffer.element( instanceIndex );
+
+					const dist = position.distance( clickPosition );
+					const direction = position.sub( clickPosition ).normalize();
+					const distArea = float( 7 ).sub( dist ).max( 0 );
+
+					const power = distArea.mul( .1 );
+					const relativePower = power.mul( instanceIndex.hash().mul( .5 ).add( .5 ) );
+
+					stack.assign( velocity, velocity.add( direction.mul( relativePower ) ) );
+
+				} ).compute( particleCount );
+
+				//
+
+				function onHit( event ) {
+
+					pointer.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
+
+					raycaster.setFromCamera( pointer, camera );
+
+					const intersects = raycaster.intersectObjects( [ plane ], false );
+
+					if ( intersects.length > 0 ) {
+
+						const { point } = intersects[ 0 ];
+
+						// move to uniform
+
+						clickPosition.value.copy( point );
+						clickPosition.value.y = - 1;
+
+						// compute
+
+						renderer.compute( computeHit );
+
+					}
+
+				}
+
+				// events
+
+				renderer.domElement.addEventListener( 'pointerdown', onHit );
+
+				//
+
+				controls = new OrbitControls( camera, renderer.domElement );
+				controls.minDistance = 5;
+				controls.maxDistance = 70;
+				controls.target.set( 0, - 1, 0 );
+				controls.update();
+
+				//
+
+				window.addEventListener( 'resize', onWindowResize );
+
+				// gui
+
+				const gui = new GUI();
+
+				gui.add( gravity, 'value', - .0098, 0, 0.0001 ).name( 'gravity' );
+				gui.add( bounce, 'value', .1, 1, 0.01 ).name( 'bounce' );
+				gui.add( friction, 'value', .96, .99, 0.01 ).name( 'friction' );
+				gui.add( size, 'value', .12, .5, 0.01 ).name( 'size' );
+
+			}
+
+			function onWindowResize() {
+
+				const { innerWidth, innerHeight } = window;
+
+				camera.aspect = innerWidth / innerHeight;
+				camera.updateProjectionMatrix();
+
+				renderer.setSize( innerWidth, innerHeight );
+
+			}
+
+			function render() {
+
+				renderer.compute( computeParticles );
+				renderer.render( scene, camera );
+
+			}
+
+		</script>
+	</body>
+</html>

+ 1 - 0
test/e2e/puppeteer.js

@@ -111,6 +111,7 @@ const exceptionList = [
 	'webgpu_backdrop_area',
 	'webgpu_clearcoat',
 	'webgpu_compute',
+	'webgpu_compute_particles',
 	'webgpu_compute_texture',
 	'webgpu_cubemap_adjustments',
 	'webgpu_cubemap_dynamic',