webgpu_compute_birds.html 16 KB

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