webgpu_compute_birds.html 15 KB

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