webgpu_compute_birds.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute - flocking</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. <style>
  9. body {
  10. background-color: #fff;
  11. color: #444;
  12. }
  13. a {
  14. color:#08f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgpu compute birds<br/>
  21. Move mouse to disturb birds.
  22. </div>
  23. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../build/three.webgpu.js",
  27. "three/tsl": "../build/three.webgpu.js",
  28. "three/addons/": "./jsm/"
  29. }
  30. }
  31. </script>
  32. <script type="module">
  33. import * as THREE from 'three';
  34. import { uniform, varyingProperty, vec4, max, sin, mat3, uint, negate, cameraProjectionMatrix, cameraViewMatrix, positionLocal, modelWorldMatrix, sqrt, attribute, property, float, storage, storageObject, Fn, If, cos, Loop, Continue, normalize, instanceIndex, length } from 'three/tsl';
  35. import Stats from 'three/addons/libs/stats.module.js';
  36. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  37. let container, stats;
  38. let camera, scene, renderer;
  39. let mouseX = 0, mouseY = 0;
  40. let windowHalfX = window.innerWidth / 2, windowHalfY = window.innerHeight / 2;
  41. let last = performance.now();
  42. let computeVelocity, computePosition, effectController;
  43. const BIRDS = 1024;
  44. const SPEED_LIMIT = 9.0;
  45. const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  46. const UPPER_BOUNDS = BOUNDS;
  47. // Custom Geometry - using 3 triangles each. No UVs, no normals currently.
  48. class BirdGeometry extends THREE.BufferGeometry {
  49. constructor() {
  50. super();
  51. const trianglesPerBird = 3;
  52. const triangles = BIRDS * trianglesPerBird;
  53. const points = triangles * 3;
  54. const vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  55. const birdColors = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  56. const references = new THREE.BufferAttribute( new Uint32Array( points ), 1 );
  57. const birdVertex = new THREE.BufferAttribute( new Uint32Array( points ), 1 );
  58. this.setAttribute( 'position', vertices );
  59. this.setAttribute( 'birdColor', birdColors );
  60. this.setAttribute( 'reference', references );
  61. this.setAttribute( 'birdVertex', birdVertex );
  62. let v = 0;
  63. function verts_push() {
  64. for ( let i = 0; i < arguments.length; i ++ ) {
  65. vertices.array[ v ++ ] = arguments[ i ];
  66. }
  67. }
  68. const wingsSpan = 20;
  69. for ( let f = 0; f < BIRDS; f ++ ) {
  70. // Body
  71. verts_push(
  72. 0, - 0, - 20,
  73. 0, 4, - 20,
  74. 0, 0, 30
  75. );
  76. // Wings
  77. verts_push(
  78. 0, 0, - 15,
  79. - wingsSpan, 0, 0,
  80. 0, 0, 15
  81. );
  82. verts_push(
  83. 0, 0, 15,
  84. wingsSpan, 0, 0,
  85. 0, 0, - 15
  86. );
  87. }
  88. for ( let v = 0; v < triangles * 3; v ++ ) {
  89. const triangleIndex = ~ ~ ( v / 3 );
  90. const birdIndex = ~ ~ ( triangleIndex / trianglesPerBird );
  91. const c = new THREE.Color(
  92. 0x666666 +
  93. ~ ~ ( v / 9 ) / BIRDS * 0x666666
  94. );
  95. birdColors.array[ v * 3 + 0 ] = c.r;
  96. birdColors.array[ v * 3 + 1 ] = c.g;
  97. birdColors.array[ v * 3 + 2 ] = c.b;
  98. references.array[ v ] = birdIndex;
  99. birdVertex.array[ v ] = v % 9;
  100. }
  101. this.scale( 0.2, 0.2, 0.2 );
  102. }
  103. }
  104. function init() {
  105. container = document.createElement( 'div' );
  106. document.body.appendChild( container );
  107. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  108. camera.position.z = 350;
  109. scene = new THREE.Scene();
  110. scene.background = new THREE.Color( 0xffffff );
  111. scene.fog = new THREE.Fog( 0xffffff, 100, 1000 );
  112. renderer = new THREE.WebGPURenderer();
  113. renderer.setPixelRatio( window.devicePixelRatio );
  114. renderer.setSize( window.innerWidth, window.innerHeight );
  115. renderer.setAnimationLoop( animate );
  116. container.appendChild( renderer.domElement );
  117. // Initialize position, velocity, and phase values
  118. const positionArray = new Float32Array( BIRDS * 3 );
  119. const velocityArray = new Float32Array( BIRDS * 3 );
  120. const phaseArray = new Float32Array( BIRDS );
  121. for ( let i = 0; i < BIRDS; i ++ ) {
  122. const posX = Math.random() * BOUNDS - BOUNDS_HALF;
  123. const posY = Math.random() * BOUNDS - BOUNDS_HALF;
  124. const posZ = Math.random() * BOUNDS - BOUNDS_HALF;
  125. positionArray[ i * 3 + 0 ] = posX;
  126. positionArray[ i * 3 + 1 ] = posY;
  127. positionArray[ i * 3 + 2 ] = posZ;
  128. const velX = Math.random() - 0.5;
  129. const velY = Math.random() - 0.5;
  130. const velZ = Math.random() - 0.5;
  131. velocityArray[ i * 3 + 0 ] = velX * 10;
  132. velocityArray[ i * 3 + 1 ] = velY * 10;
  133. velocityArray[ i * 3 + 2 ] = velZ * 10;
  134. phaseArray[ i ] = 1;
  135. }
  136. // Create storage buffer attributes.
  137. const positionBufferAttribute = new THREE.StorageBufferAttribute( positionArray, 3 );
  138. const velocityBufferAttribute = new THREE.StorageBufferAttribute( velocityArray, 3 );
  139. const phaseBufferAttribute = new THREE.StorageBufferAttribute( phaseArray, 1 );
  140. // Labels applied to storage nodes and uniform nodes are reflected within the shader output,
  141. // and are useful for debugging purposes.
  142. // Access storage buffer attribute data from within shaders with a StorageNode.
  143. const positionStorage = storage( positionBufferAttribute, 'vec3', positionBufferAttribute.count ).label( 'positionStorage' );
  144. const velocityStorage = storage( velocityBufferAttribute, 'vec3', velocityBufferAttribute.count ).label( 'velocityStorage' );
  145. const phaseStorage = storage( phaseBufferAttribute, 'float', phaseBufferAttribute.count ).label( 'phaseStorage' );
  146. // Create read-only storage nodes. Storage nodes can only be accessed outside of compute shaders in a read-only state.
  147. const positionRead = storageObject( positionBufferAttribute, 'vec3', positionBufferAttribute.count ).toReadOnly();
  148. const velocityRead = storageObject( velocityBufferAttribute, 'vec3', velocityBufferAttribute.count ).toReadOnly();
  149. const phaseRead = storageObject( phaseBufferAttribute, 'float', phaseBufferAttribute.count ).toReadOnly();
  150. // Define Uniforms. Uniforms only need to be defined once rather than per shader.
  151. effectController = {
  152. separation: uniform( 20.0 ).label( 'separation' ),
  153. alignment: uniform( 20.0 ).label( 'alignment' ),
  154. cohesion: uniform( 20.0 ).label( 'cohesion' ),
  155. freedom: uniform( 0.75 ).label( 'freedom' ),
  156. now: uniform( 0.0 ),
  157. deltaTime: uniform( 0.0 ).label( 'deltaTime' ),
  158. predator: uniform( new THREE.Vector3() ).label( 'predator' ),
  159. };
  160. // Create geometry
  161. const birdGeometry = new BirdGeometry();
  162. const birdMaterial = new THREE.NodeMaterial();
  163. // Declare varyings
  164. const vColor = varyingProperty( 'vec4', 'vColor' );
  165. // Animate bird mesh within vertex shader, then apply position offset to vertices.
  166. const birdVertexTSL = Fn( () => {
  167. const reference = attribute( 'reference' );
  168. const birdVertex = attribute( 'birdVertex' );
  169. const birdColor = attribute( 'birdColor' );
  170. const position = positionLocal.toVar();
  171. const newPhase = phaseRead.element( reference ).toVar();
  172. const newVelocity = normalize( velocityRead.element( reference ) ).toVar();
  173. If( birdVertex.equal( 4 ).or( birdVertex.equal( 7 ) ), () => {
  174. // flap wings
  175. position.y = sin( newPhase ).mul( 5.0 );
  176. } );
  177. const newPosition = modelWorldMatrix.mul( position );
  178. newVelocity.z.mulAssign( - 1.0 );
  179. const xz = length( newVelocity.xz );
  180. const xyz = float( 1.0 );
  181. const x = sqrt( ( newVelocity.y.mul( newVelocity.y ) ).oneMinus() );
  182. const cosry = newVelocity.x.div( xz ).toVar();
  183. const sinry = newVelocity.z.div( xz ).toVar();
  184. const cosrz = x.div( xyz );
  185. const sinrz = newVelocity.y.div( xyz ).toVar();
  186. // Nodes must be negated with negate(). Using '-', their values will resolve to NaN.
  187. const maty = mat3(
  188. cosry, 0, negate( sinry ),
  189. 0, 1, 0,
  190. sinry, 0, cosry
  191. );
  192. const matz = mat3(
  193. cosrz, sinrz, 0,
  194. negate( sinrz ), cosrz, 0,
  195. 0, 0, 1
  196. );
  197. const finalVert = maty.mul( matz ).mul( newPosition );
  198. finalVert.addAssign( positionRead.element( reference ) );
  199. vColor.assign( vec4( birdColor, 1.0 ) );
  200. return cameraProjectionMatrix.mul( cameraViewMatrix ).mul( finalVert );
  201. } );
  202. birdMaterial.vertexNode = birdVertexTSL();
  203. birdMaterial.colorNode = vColor;
  204. birdMaterial.side = THREE.DoubleSide;
  205. const birdMesh = new THREE.Mesh( birdGeometry, birdMaterial );
  206. birdMesh.rotation.y = Math.PI / 2;
  207. birdMesh.matrixAutoUpdate = false;
  208. birdMesh.updateMatrix();
  209. // Define GPU Compute shaders.
  210. // Shaders are computationally identical to their GLSL counterparts outside of texture destructuring.
  211. computeVelocity = Fn( () => {
  212. // Define consts
  213. const PI = float( 3.141592653589793 );
  214. const PI_2 = PI.mul( 2.0 );
  215. const limit = property( 'float', 'limit' ).assign( SPEED_LIMIT );
  216. // Destructure uniforms
  217. const { alignment, separation, cohesion, predator, deltaTime } = effectController;
  218. const zoneRadius = separation.add( alignment ).add( cohesion );
  219. const separationThresh = separation.div( zoneRadius );
  220. const alignmentThresh = ( separation.add( alignment ) ).div( zoneRadius );
  221. const zoneRadiusSq = zoneRadius.mul( zoneRadius );
  222. const position = positionStorage.element( instanceIndex );
  223. const velocity = velocityStorage.element( instanceIndex );
  224. // Add influence of mouse position to velocity.
  225. const dirToPredator = predator.mul( UPPER_BOUNDS ).sub( position );
  226. dirToPredator.z.assign( 0.0 );
  227. const distToPredator = length( dirToPredator );
  228. const distToPreadatorSq = distToPredator.mul( distToPredator );
  229. const preyRadius = float( 150.0 );
  230. const preyRadiusSq = preyRadius.mul( preyRadius );
  231. // Move birds away from predator if they are within the predator's area.
  232. If( distToPredator.lessThan( preyRadius ), () => {
  233. // Scale bird velocity inversely with distance from prey radius center.
  234. const velocityAdjust = ( distToPreadatorSq.div( preyRadiusSq ).sub( 1.0 ) ).mul( deltaTime ).mul( 100.0 );
  235. velocity.addAssign( normalize( dirToPredator ).mul( velocityAdjust ) );
  236. limit.addAssign( 5.0 );
  237. } );
  238. // Attract flocks to center
  239. const dirToCenter = position.toVar();
  240. dirToCenter.y.mulAssign( 2.5 );
  241. velocity.subAssign( normalize( dirToCenter ).mul( deltaTime ).mul( 5.0 ) );
  242. Loop( { start: uint( 0 ), end: uint( BIRDS ), type: 'uint', condition: '<' }, ( { i } ) => {
  243. const birdPosition = positionStorage.element( i );
  244. const dirToBird = birdPosition.sub( position );
  245. const distToBird = length( dirToBird );
  246. // Don't apply any changes to velocity if the distance to this bird is negligable.
  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. } )().compute( BIRDS );
  286. computePosition = Fn( () => {
  287. const { deltaTime } = effectController;
  288. positionStorage.element( instanceIndex ).addAssign( velocityStorage.element( instanceIndex ).mul( deltaTime ).mul( 15.0 ) );
  289. const velocity = velocityStorage.element( instanceIndex );
  290. const phase = phaseStorage.element( instanceIndex );
  291. 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 ) );
  292. phaseStorage.element( instanceIndex ).assign( modValue.mod( 62.83 ) );
  293. } )().compute( BIRDS );
  294. scene.add( birdMesh );
  295. stats = new Stats();
  296. container.appendChild( stats.dom );
  297. container.style.touchAction = 'none';
  298. container.addEventListener( 'pointermove', onPointerMove );
  299. window.addEventListener( 'resize', onWindowResize );
  300. const gui = new GUI();
  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. gui.close();
  305. }
  306. function onWindowResize() {
  307. windowHalfX = window.innerWidth / 2;
  308. windowHalfY = window.innerHeight / 2;
  309. camera.aspect = window.innerWidth / window.innerHeight;
  310. camera.updateProjectionMatrix();
  311. renderer.setSize( window.innerWidth, window.innerHeight );
  312. }
  313. function onPointerMove( event ) {
  314. if ( event.isPrimary === false ) return;
  315. mouseX = event.clientX - windowHalfX;
  316. mouseY = event.clientY - windowHalfY;
  317. }
  318. function animate() {
  319. render();
  320. stats.update();
  321. }
  322. function render() {
  323. const now = performance.now();
  324. let deltaTime = ( now - last ) / 1000;
  325. if ( deltaTime > 1 ) deltaTime = 1; // safety cap on large deltas
  326. last = now;
  327. effectController.now.value = now;
  328. effectController.deltaTime.value = deltaTime;
  329. effectController.predator.value.set( 0.5 * mouseX / windowHalfX, - 0.5 * mouseY / windowHalfY, 0 );
  330. mouseX = 10000;
  331. mouseY = 10000;
  332. renderer.compute( computeVelocity );
  333. renderer.compute( computePosition );
  334. renderer.render( scene, camera );
  335. }
  336. init();
  337. </script>
  338. </body>
  339. </html>