webgpu_compute_birds.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute birds</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>
  14. <span>Compute Birds</span>
  15. </div>
  16. <small>
  17. Move mouse to disturb birds.
  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 { uniform, varying, vec4, add, sub, max, dot, sin, mat3, uint, negate, instancedArray, cameraProjectionMatrix, cameraViewMatrix, positionLocal, modelWorldMatrix, sqrt, float, Fn, If, cos, Loop, Continue, normalize, instanceIndex, length, vertexIndex } from 'three/tsl';
  33. import { Inspector } from 'three/addons/inspector/Inspector.js';
  34. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  35. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  36. let container;
  37. let camera, scene, renderer;
  38. let last = performance.now();
  39. let pointer, raycaster;
  40. let computeVelocity, computePosition, effectController;
  41. const BIRDS = 16384;
  42. const SPEED_LIMIT = 9.0;
  43. const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  44. // Custom Geometry - using 3 triangles each. No normals currently.
  45. class BirdGeometry extends THREE.BufferGeometry {
  46. constructor() {
  47. super();
  48. const points = 3 * 3;
  49. const vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  50. this.setAttribute( 'position', vertices );
  51. let v = 0;
  52. function verts_push() {
  53. for ( let i = 0; i < arguments.length; i ++ ) {
  54. vertices.array[ v ++ ] = arguments[ i ];
  55. }
  56. }
  57. const wingsSpan = 20;
  58. // Body
  59. verts_push(
  60. 0, 0, - 20,
  61. 0, - 8, 10,
  62. 0, 0, 30
  63. );
  64. // Left Wing
  65. verts_push(
  66. 0, 0, - 15,
  67. - wingsSpan, 0, 5,
  68. 0, 0, 15
  69. );
  70. // Right Wing
  71. verts_push(
  72. 0, 0, 15,
  73. wingsSpan, 0, 5,
  74. 0, 0, - 15
  75. );
  76. this.scale( 0.2, 0.2, 0.2 );
  77. }
  78. }
  79. // TODO: Fix example with WebGL backend
  80. if ( WebGPU.isAvailable() === false ) {
  81. document.body.appendChild( WebGPU.getErrorMessage() );
  82. throw new Error( 'No WebGPU support' );
  83. }
  84. function init() {
  85. container = document.createElement( 'div' );
  86. document.body.appendChild( container );
  87. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 5000 );
  88. camera.position.z = 1000;
  89. scene = new THREE.Scene();
  90. scene.fog = new THREE.Fog( 0xffffff, 700, 3000 );
  91. // Pointer
  92. pointer = new THREE.Vector2();
  93. raycaster = new THREE.Raycaster();
  94. // Sky
  95. const geometry = new THREE.IcosahedronGeometry( 1, 6 );
  96. const material = new THREE.MeshBasicNodeMaterial( {
  97. // Use vertex positions to create atmosphere colors
  98. colorNode: varying(
  99. vec4(
  100. sub( 0.25, positionLocal.y ),
  101. sub( - 0.25, positionLocal.y ),
  102. add( 1.5, positionLocal.y ),
  103. 1.0
  104. )
  105. ),
  106. side: THREE.BackSide
  107. } );
  108. const mesh = new THREE.Mesh( geometry, material );
  109. mesh.rotation.z = 0.75;
  110. mesh.scale.setScalar( 1200 );
  111. scene.add( mesh );
  112. //
  113. renderer = new THREE.WebGPURenderer( { antialias: true, forceWebGL: false } );
  114. renderer.setPixelRatio( window.devicePixelRatio );
  115. renderer.setSize( window.innerWidth, window.innerHeight );
  116. renderer.setAnimationLoop( render );
  117. renderer.toneMapping = THREE.NeutralToneMapping;
  118. renderer.inspector = new Inspector();
  119. container.appendChild( renderer.domElement );
  120. const controls = new OrbitControls( camera );
  121. controls.connect( renderer.domElement );
  122. // Initialize position, velocity, and phase values
  123. const positionArray = new Float32Array( BIRDS * 3 );
  124. const velocityArray = new Float32Array( BIRDS * 3 );
  125. const phaseArray = new Float32Array( BIRDS );
  126. for ( let i = 0; i < BIRDS; i ++ ) {
  127. const posX = Math.random() * BOUNDS - BOUNDS_HALF;
  128. const posY = Math.random() * BOUNDS - BOUNDS_HALF;
  129. const posZ = Math.random() * BOUNDS - BOUNDS_HALF;
  130. positionArray[ i * 3 + 0 ] = posX;
  131. positionArray[ i * 3 + 1 ] = posY;
  132. positionArray[ i * 3 + 2 ] = posZ;
  133. const velX = Math.random() - 0.5;
  134. const velY = Math.random() - 0.5;
  135. const velZ = Math.random() - 0.5;
  136. velocityArray[ i * 3 + 0 ] = velX * 10;
  137. velocityArray[ i * 3 + 1 ] = velY * 10;
  138. velocityArray[ i * 3 + 2 ] = velZ * 10;
  139. phaseArray[ i ] = 1;
  140. }
  141. // Labels applied to storage nodes and uniform nodes are reflected within the shader output,
  142. // and are useful for debugging purposes.
  143. const positionStorage = instancedArray( positionArray, 'vec3' ).setName( 'positionStorage' );
  144. const velocityStorage = instancedArray( velocityArray, 'vec3' ).setName( 'velocityStorage' );
  145. const phaseStorage = instancedArray( phaseArray, 'float' ).setName( 'phaseStorage' );
  146. // The Pixel Buffer Object (PBO) is required to get the GPU computed data in the WebGL2 fallback.
  147. positionStorage.setPBO( true );
  148. velocityStorage.setPBO( true );
  149. phaseStorage.setPBO( true );
  150. // Define Uniforms. Uniforms only need to be defined once rather than per shader.
  151. effectController = {
  152. separation: uniform( 15.0 ).setName( 'separation' ),
  153. alignment: uniform( 20.0 ).setName( 'alignment' ),
  154. cohesion: uniform( 20.0 ).setName( 'cohesion' ),
  155. freedom: uniform( 0.75 ).setName( 'freedom' ),
  156. now: uniform( 0.0 ),
  157. deltaTime: uniform( 0.0 ).setName( 'deltaTime' ),
  158. rayOrigin: uniform( new THREE.Vector3() ).setName( 'rayOrigin' ),
  159. rayDirection: uniform( new THREE.Vector3() ).setName( 'rayDirection' )
  160. };
  161. // Create geometry
  162. const birdGeometry = new BirdGeometry();
  163. const birdMaterial = new THREE.NodeMaterial();
  164. // Animate bird mesh within vertex shader, then apply position offset to vertices.
  165. const birdVertexTSL = Fn( () => {
  166. const position = positionLocal.toVar();
  167. const newPhase = phaseStorage.element( instanceIndex ).toVar();
  168. const newVelocity = normalize( velocityStorage.element( instanceIndex ) ).toVar();
  169. If( vertexIndex.equal( 4 ).or( vertexIndex.equal( 7 ) ), () => {
  170. // flap wings
  171. position.y = sin( newPhase ).mul( 5.0 );
  172. } );
  173. const newPosition = modelWorldMatrix.mul( position );
  174. newVelocity.z.mulAssign( - 1.0 );
  175. const xz = length( newVelocity.xz );
  176. const xyz = float( 1.0 );
  177. const x = sqrt( ( newVelocity.y.mul( newVelocity.y ) ).oneMinus() );
  178. const cosry = newVelocity.x.div( xz ).toVar();
  179. const sinry = newVelocity.z.div( xz ).toVar();
  180. const cosrz = x.div( xyz );
  181. const sinrz = newVelocity.y.div( xyz ).toVar();
  182. // Nodes must be negated with negate(). Using '-', their values will resolve to NaN.
  183. const maty = mat3(
  184. cosry, 0, negate( sinry ),
  185. 0, 1, 0,
  186. sinry, 0, cosry
  187. );
  188. const matz = mat3(
  189. cosrz, sinrz, 0,
  190. negate( sinrz ), cosrz, 0,
  191. 0, 0, 1
  192. );
  193. const finalVert = maty.mul( matz ).mul( newPosition );
  194. finalVert.addAssign( positionStorage.element( instanceIndex ) );
  195. return cameraProjectionMatrix.mul( cameraViewMatrix ).mul( finalVert );
  196. } );
  197. birdMaterial.vertexNode = birdVertexTSL();
  198. birdMaterial.side = THREE.DoubleSide;
  199. const birdMesh = new THREE.InstancedMesh( birdGeometry, birdMaterial, BIRDS );
  200. birdMesh.rotation.y = Math.PI / 2;
  201. birdMesh.matrixAutoUpdate = false;
  202. birdMesh.frustumCulled = false;
  203. birdMesh.updateMatrix();
  204. // Define GPU Compute shaders.
  205. // Shaders are computationally identical to their GLSL counterparts outside of texture destructuring.
  206. computeVelocity = Fn( () => {
  207. // Define consts
  208. const PI = float( 3.141592653589793 );
  209. const PI_2 = PI.mul( 2.0 );
  210. const limit = float( SPEED_LIMIT ).toVar( 'limit' );
  211. // Destructure uniforms
  212. const { alignment, separation, cohesion, deltaTime, rayOrigin, rayDirection } = effectController;
  213. const zoneRadius = separation.add( alignment ).add( cohesion ).toConst();
  214. const separationThresh = separation.div( zoneRadius ).toConst();
  215. const alignmentThresh = ( separation.add( alignment ) ).div( zoneRadius ).toConst();
  216. const zoneRadiusSq = zoneRadius.mul( zoneRadius ).toConst();
  217. // Cache current bird's position and velocity outside the loop
  218. const birdIndex = instanceIndex.toConst( 'birdIndex' );
  219. const position = positionStorage.element( birdIndex ).toVar();
  220. const velocity = velocityStorage.element( birdIndex ).toVar();
  221. // Add influence of pointer position to velocity using cached position
  222. const directionToRay = rayOrigin.sub( position ).toConst();
  223. const projectionLength = dot( directionToRay, rayDirection ).toConst();
  224. const closestPoint = rayOrigin.sub( rayDirection.mul( projectionLength ) ).toConst();
  225. const directionToClosestPoint = closestPoint.sub( position ).toConst();
  226. const distanceToClosestPoint = length( directionToClosestPoint ).toConst();
  227. const distanceToClosestPointSq = distanceToClosestPoint.mul( distanceToClosestPoint ).toConst();
  228. const rayRadius = float( 150.0 ).toConst();
  229. const rayRadiusSq = rayRadius.mul( rayRadius ).toConst();
  230. If( distanceToClosestPointSq.lessThan( rayRadiusSq ), () => {
  231. const velocityAdjust = ( distanceToClosestPointSq.div( rayRadiusSq ).sub( 1.0 ) ).mul( deltaTime ).mul( 100.0 );
  232. velocity.addAssign( normalize( directionToClosestPoint ).mul( velocityAdjust ) );
  233. limit.addAssign( 5.0 );
  234. } );
  235. // Attract flocks to center
  236. const dirToCenter = position.toVar();
  237. dirToCenter.y.mulAssign( 2.5 );
  238. velocity.subAssign( normalize( dirToCenter ).mul( deltaTime ).mul( 5.0 ) );
  239. Loop( { start: uint( 0 ), end: uint( BIRDS ), type: 'uint', condition: '<' }, ( { i } ) => {
  240. If( i.equal( birdIndex ), () => {
  241. Continue();
  242. } );
  243. // Cache bird's position and velocity
  244. const birdPosition = positionStorage.element( i );
  245. const dirToBird = birdPosition.sub( position );
  246. const distToBird = length( dirToBird );
  247. If( distToBird.lessThan( 0.0001 ), () => {
  248. Continue();
  249. } );
  250. const distToBirdSq = distToBird.mul( distToBird );
  251. // Don't apply any changes to velocity if changes if the bird is outsize the zone's radius.
  252. If( distToBirdSq.greaterThan( zoneRadiusSq ), () => {
  253. Continue();
  254. } );
  255. // Determine which threshold the bird is flying within and adjust its velocity accordingly
  256. const percent = distToBirdSq.div( zoneRadiusSq );
  257. If( percent.lessThan( separationThresh ), () => {
  258. // Separation - Move apart for comfort
  259. const velocityAdjust = ( separationThresh.div( percent ).sub( 1.0 ) ).mul( deltaTime );
  260. velocity.subAssign( normalize( dirToBird ).mul( velocityAdjust ) );
  261. } ).ElseIf( percent.lessThan( alignmentThresh ), () => {
  262. // Alignment - fly the same direction
  263. const threshDelta = alignmentThresh.sub( separationThresh );
  264. const adjustedPercent = ( percent.sub( separationThresh ) ).div( threshDelta );
  265. const birdVelocity = velocityStorage.element( i );
  266. const cosRange = cos( adjustedPercent.mul( PI_2 ) );
  267. const cosRangeAdjust = float( 0.5 ).sub( cosRange.mul( 0.5 ) ).add( 0.5 );
  268. const velocityAdjust = cosRangeAdjust.mul( deltaTime );
  269. velocity.addAssign( normalize( birdVelocity ).mul( velocityAdjust ) );
  270. } ).Else( () => {
  271. // Attraction / Cohesion - move closer
  272. const threshDelta = alignmentThresh.oneMinus();
  273. const adjustedPercent = threshDelta.equal( 0.0 ).select( 1.0, ( percent.sub( alignmentThresh ) ).div( threshDelta ) );
  274. const cosRange = cos( adjustedPercent.mul( PI_2 ) );
  275. const adj1 = cosRange.mul( - 0.5 );
  276. const adj2 = adj1.add( 0.5 );
  277. const adj3 = float( 0.5 ).sub( adj2 );
  278. const velocityAdjust = adj3.mul( deltaTime );
  279. velocity.addAssign( normalize( dirToBird ).mul( velocityAdjust ) );
  280. } );
  281. } );
  282. If( length( velocity ).greaterThan( limit ), () => {
  283. velocity.assign( normalize( velocity ).mul( limit ) );
  284. } );
  285. // Write back the final velocity to storage
  286. velocityStorage.element( birdIndex ).assign( velocity );
  287. } )().compute( BIRDS ).setName( 'Birds Velocity' );
  288. computePosition = Fn( () => {
  289. const { deltaTime } = effectController;
  290. positionStorage.element( instanceIndex ).addAssign( velocityStorage.element( instanceIndex ).mul( deltaTime ).mul( 15.0 ) );
  291. const velocity = velocityStorage.element( instanceIndex );
  292. const phase = phaseStorage.element( instanceIndex );
  293. const modValue = phase.add( deltaTime ).add( length( velocity.xz ).mul( deltaTime ).mul( 3.0 ) ).add( max( velocity.y, 0.0 ).mul( deltaTime ).mul( 6.0 ) );
  294. phaseStorage.element( instanceIndex ).assign( modValue.mod( 62.83 ) );
  295. } )().compute( BIRDS ).setName( 'Birds Position' );
  296. scene.add( birdMesh );
  297. container.style.touchAction = 'none';
  298. container.addEventListener( 'pointermove', onPointerMove );
  299. window.addEventListener( 'resize', onWindowResize );
  300. const gui = renderer.inspector.createParameters( 'Birds settings' );
  301. gui.add( effectController.separation, 'value', 0.0, 100.0, 1.0 ).name( 'Separation' );
  302. gui.add( effectController.alignment, 'value', 0.0, 100, 0.001 ).name( 'Alignment ' );
  303. gui.add( effectController.cohesion, 'value', 0.0, 100, 0.025 ).name( 'Cohesion' );
  304. }
  305. function onWindowResize() {
  306. camera.aspect = window.innerWidth / window.innerHeight;
  307. camera.updateProjectionMatrix();
  308. renderer.setSize( window.innerWidth, window.innerHeight );
  309. }
  310. function onPointerMove( event ) {
  311. if ( event.isPrimary === false ) return;
  312. pointer.x = ( event.clientX / window.innerWidth ) * 2.0 - 1.0;
  313. pointer.y = 1.0 - ( event.clientY / window.innerHeight ) * 2.0;
  314. }
  315. function render() {
  316. const now = performance.now();
  317. let deltaTime = ( now - last ) / 1000;
  318. if ( deltaTime > 1 ) deltaTime = 1; // safety cap on large deltas
  319. last = now;
  320. raycaster.setFromCamera( pointer, camera );
  321. effectController.now.value = now;
  322. effectController.deltaTime.value = deltaTime;
  323. effectController.rayOrigin.value.copy( raycaster.ray.origin );
  324. effectController.rayDirection.value.copy( raycaster.ray.direction );
  325. renderer.compute( computeVelocity );
  326. renderer.compute( computePosition );
  327. renderer.render( scene, camera );
  328. // Move pointer away so we only affect birds when moving the mouse
  329. pointer.y = 10;
  330. }
  331. init();
  332. </script>
  333. </body>
  334. </html>
粤ICP备19079148号