webgl_gpgpu_birds.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - gpgpu - 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> - webgl gpgpu birds<br/>
  21. Move mouse to disturb birds.
  22. </div>
  23. <!--
  24. TODO: If you're reading this, you may wish to improve this example by
  25. - Create a better shading for the birds?
  26. -->
  27. <!-- shader for bird's position -->
  28. <script id="fragmentShaderPosition" type="x-shader/x-fragment">
  29. uniform float time;
  30. uniform float delta;
  31. void main() {
  32. vec2 uv = gl_FragCoord.xy / resolution.xy;
  33. vec4 tmpPos = texture2D( texturePosition, uv );
  34. vec3 position = tmpPos.xyz;
  35. vec3 velocity = texture2D( textureVelocity, uv ).xyz;
  36. float phase = tmpPos.w;
  37. phase = mod( ( phase + delta +
  38. length( velocity.xz ) * delta * 3. +
  39. max( velocity.y, 0.0 ) * delta * 6. ), 62.83 );
  40. gl_FragColor = vec4( position + velocity * delta * 15. , phase );
  41. }
  42. </script>
  43. <!-- shader for bird's velocity -->
  44. <script id="fragmentShaderVelocity" type="x-shader/x-fragment">
  45. uniform float time;
  46. uniform float testing;
  47. uniform float delta; // about 0.016
  48. uniform float separationDistance; // 20
  49. uniform float alignmentDistance; // 40
  50. uniform float cohesionDistance; //
  51. uniform float freedomFactor;
  52. uniform vec3 predator;
  53. const float width = resolution.x;
  54. const float height = resolution.y;
  55. const float PI = 3.141592653589793;
  56. const float PI_2 = PI * 2.0;
  57. // const float VISION = PI * 0.55;
  58. float zoneRadius = 40.0;
  59. float zoneRadiusSquared = 1600.0;
  60. float separationThresh = 0.45;
  61. float alignmentThresh = 0.65;
  62. const float UPPER_BOUNDS = BOUNDS;
  63. const float LOWER_BOUNDS = -UPPER_BOUNDS;
  64. const float SPEED_LIMIT = 9.0;
  65. float rand( vec2 co ){
  66. return fract( sin( dot( co.xy, vec2(12.9898,78.233) ) ) * 43758.5453 );
  67. }
  68. void main() {
  69. zoneRadius = separationDistance + alignmentDistance + cohesionDistance;
  70. separationThresh = separationDistance / zoneRadius;
  71. alignmentThresh = ( separationDistance + alignmentDistance ) / zoneRadius;
  72. zoneRadiusSquared = zoneRadius * zoneRadius;
  73. vec2 uv = gl_FragCoord.xy / resolution.xy;
  74. vec3 birdPosition, birdVelocity;
  75. vec3 selfPosition = texture2D( texturePosition, uv ).xyz;
  76. vec3 selfVelocity = texture2D( textureVelocity, uv ).xyz;
  77. float dist;
  78. vec3 dir; // direction
  79. float distSquared;
  80. float separationSquared = separationDistance * separationDistance;
  81. float cohesionSquared = cohesionDistance * cohesionDistance;
  82. float f;
  83. float percent;
  84. vec3 velocity = selfVelocity;
  85. float limit = SPEED_LIMIT;
  86. dir = predator * UPPER_BOUNDS - selfPosition;
  87. dir.z = 0.;
  88. // dir.z *= 0.6;
  89. dist = length( dir );
  90. distSquared = dist * dist;
  91. float preyRadius = 150.0;
  92. float preyRadiusSq = preyRadius * preyRadius;
  93. // move birds away from predator
  94. if ( dist < preyRadius ) {
  95. f = ( distSquared / preyRadiusSq - 1.0 ) * delta * 100.;
  96. velocity += normalize( dir ) * f;
  97. limit += 5.0;
  98. }
  99. // if (testing == 0.0) {}
  100. // if ( rand( uv + time ) < freedomFactor ) {}
  101. // Attract flocks to the center
  102. vec3 central = vec3( 0., 0., 0. );
  103. dir = selfPosition - central;
  104. dist = length( dir );
  105. dir.y *= 2.5;
  106. velocity -= normalize( dir ) * delta * 5.;
  107. for ( float y = 0.0; y < height; y++ ) {
  108. for ( float x = 0.0; x < width; x++ ) {
  109. vec2 ref = vec2( x + 0.5, y + 0.5 ) / resolution.xy;
  110. birdPosition = texture2D( texturePosition, ref ).xyz;
  111. dir = birdPosition - selfPosition;
  112. dist = length( dir );
  113. if ( dist < 0.0001 ) continue;
  114. distSquared = dist * dist;
  115. if ( distSquared > zoneRadiusSquared ) continue;
  116. percent = distSquared / zoneRadiusSquared;
  117. if ( percent < separationThresh ) { // low
  118. // Separation - Move apart for comfort
  119. f = ( separationThresh / percent - 1.0 ) * delta;
  120. velocity -= normalize( dir ) * f;
  121. } else if ( percent < alignmentThresh ) { // high
  122. // Alignment - fly the same direction
  123. float threshDelta = alignmentThresh - separationThresh;
  124. float adjustedPercent = ( percent - separationThresh ) / threshDelta;
  125. birdVelocity = texture2D( textureVelocity, ref ).xyz;
  126. f = ( 0.5 - cos( adjustedPercent * PI_2 ) * 0.5 + 0.5 ) * delta;
  127. velocity += normalize( birdVelocity ) * f;
  128. } else {
  129. // Attraction / Cohesion - move closer
  130. float threshDelta = 1.0 - alignmentThresh;
  131. float adjustedPercent;
  132. if( threshDelta == 0. ) adjustedPercent = 1.;
  133. else adjustedPercent = ( percent - alignmentThresh ) / threshDelta;
  134. f = ( 0.5 - ( cos( adjustedPercent * PI_2 ) * -0.5 + 0.5 ) ) * delta;
  135. velocity += normalize( dir ) * f;
  136. }
  137. }
  138. }
  139. // this make tends to fly around than down or up
  140. // if (velocity.y > 0.) velocity.y *= (1. - 0.2 * delta);
  141. // Speed Limits
  142. if ( length( velocity ) > limit ) {
  143. velocity = normalize( velocity ) * limit;
  144. }
  145. gl_FragColor = vec4( velocity, 1.0 );
  146. }
  147. </script>
  148. <script type="x-shader/x-vertex" id="birdVS">
  149. attribute vec2 reference;
  150. attribute float birdVertex;
  151. attribute vec3 birdColor;
  152. uniform sampler2D texturePosition;
  153. uniform sampler2D textureVelocity;
  154. varying vec4 vColor;
  155. varying float z;
  156. uniform float time;
  157. void main() {
  158. vec4 tmpPos = texture2D( texturePosition, reference );
  159. vec3 pos = tmpPos.xyz;
  160. vec3 velocity = normalize(texture2D( textureVelocity, reference ).xyz);
  161. vec3 newPosition = position;
  162. if ( birdVertex == 4.0 || birdVertex == 7.0 ) {
  163. // flap wings
  164. newPosition.y = sin( tmpPos.w ) * 5.;
  165. }
  166. newPosition = mat3( modelMatrix ) * newPosition;
  167. velocity.z *= -1.;
  168. float xz = length( velocity.xz );
  169. float xyz = 1.;
  170. float x = sqrt( 1. - velocity.y * velocity.y );
  171. float cosry = velocity.x / xz;
  172. float sinry = velocity.z / xz;
  173. float cosrz = x / xyz;
  174. float sinrz = velocity.y / xyz;
  175. mat3 maty = mat3(
  176. cosry, 0, -sinry,
  177. 0 , 1, 0 ,
  178. sinry, 0, cosry
  179. );
  180. mat3 matz = mat3(
  181. cosrz , sinrz, 0,
  182. -sinrz, cosrz, 0,
  183. 0 , 0 , 1
  184. );
  185. newPosition = maty * matz * newPosition;
  186. newPosition += pos;
  187. z = newPosition.z;
  188. vColor = vec4( birdColor, 1.0 );
  189. gl_Position = projectionMatrix * viewMatrix * vec4( newPosition, 1.0 );
  190. }
  191. </script>
  192. <!-- bird geometry shader -->
  193. <script type="x-shader/x-fragment" id="birdFS">
  194. varying vec4 vColor;
  195. varying float z;
  196. uniform vec3 color;
  197. void main() {
  198. // Fake colors for now
  199. float z2 = 0.2 + ( 1000. - z ) / 1000. * vColor.x;
  200. gl_FragColor = vec4( z2, z2, z2, 1. );
  201. }
  202. </script>
  203. <script type="importmap">
  204. {
  205. "imports": {
  206. "three": "../build/three.module.js",
  207. "three/addons/": "./jsm/"
  208. }
  209. }
  210. </script>
  211. <script type="module">
  212. import * as THREE from 'three';
  213. import Stats from 'three/addons/libs/stats.module.js';
  214. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  215. import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';
  216. /* TEXTURE WIDTH FOR SIMULATION */
  217. const WIDTH = 32;
  218. const BIRDS = WIDTH * WIDTH;
  219. // Custom Geometry - using 3 triangles each. No UVs, no normals currently.
  220. class BirdGeometry extends THREE.BufferGeometry {
  221. constructor() {
  222. super();
  223. const trianglesPerBird = 3;
  224. const triangles = BIRDS * trianglesPerBird;
  225. const points = triangles * 3;
  226. const vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  227. const birdColors = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  228. const references = new THREE.BufferAttribute( new Float32Array( points * 2 ), 2 );
  229. const birdVertex = new THREE.BufferAttribute( new Float32Array( points ), 1 );
  230. this.setAttribute( 'position', vertices );
  231. this.setAttribute( 'birdColor', birdColors );
  232. this.setAttribute( 'reference', references );
  233. this.setAttribute( 'birdVertex', birdVertex );
  234. // this.setAttribute( 'normal', new Float32Array( points * 3 ), 3 );
  235. let v = 0;
  236. function verts_push() {
  237. for ( let i = 0; i < arguments.length; i ++ ) {
  238. vertices.array[ v ++ ] = arguments[ i ];
  239. }
  240. }
  241. const wingsSpan = 20;
  242. for ( let f = 0; f < BIRDS; f ++ ) {
  243. // Body
  244. verts_push(
  245. 0, - 0, - 20,
  246. 0, 4, - 20,
  247. 0, 0, 30
  248. );
  249. // Wings
  250. verts_push(
  251. 0, 0, - 15,
  252. - wingsSpan, 0, 0,
  253. 0, 0, 15
  254. );
  255. verts_push(
  256. 0, 0, 15,
  257. wingsSpan, 0, 0,
  258. 0, 0, - 15
  259. );
  260. }
  261. for ( let v = 0; v < triangles * 3; v ++ ) {
  262. const triangleIndex = ~ ~ ( v / 3 );
  263. const birdIndex = ~ ~ ( triangleIndex / trianglesPerBird );
  264. const x = ( birdIndex % WIDTH ) / WIDTH;
  265. const y = ~ ~ ( birdIndex / WIDTH ) / WIDTH;
  266. const c = new THREE.Color(
  267. 0x666666 +
  268. ~ ~ ( v / 9 ) / BIRDS * 0x666666
  269. );
  270. birdColors.array[ v * 3 + 0 ] = c.r;
  271. birdColors.array[ v * 3 + 1 ] = c.g;
  272. birdColors.array[ v * 3 + 2 ] = c.b;
  273. references.array[ v * 2 ] = x;
  274. references.array[ v * 2 + 1 ] = y;
  275. birdVertex.array[ v ] = v % 9;
  276. }
  277. this.scale( 0.2, 0.2, 0.2 );
  278. }
  279. }
  280. //
  281. let container, stats;
  282. let camera, scene, renderer;
  283. let mouseX = 0, mouseY = 0;
  284. let windowHalfX = window.innerWidth / 2;
  285. let windowHalfY = window.innerHeight / 2;
  286. const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  287. let last = performance.now();
  288. let gpuCompute;
  289. let velocityVariable;
  290. let positionVariable;
  291. let positionUniforms;
  292. let velocityUniforms;
  293. let birdUniforms;
  294. init();
  295. function init() {
  296. container = document.createElement( 'div' );
  297. document.body.appendChild( container );
  298. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  299. camera.position.z = 350;
  300. scene = new THREE.Scene();
  301. scene.background = new THREE.Color( 0xffffff );
  302. scene.fog = new THREE.Fog( 0xffffff, 100, 1000 );
  303. renderer = new THREE.WebGLRenderer();
  304. renderer.setPixelRatio( window.devicePixelRatio );
  305. renderer.setSize( window.innerWidth, window.innerHeight );
  306. renderer.setAnimationLoop( animate );
  307. container.appendChild( renderer.domElement );
  308. initComputeRenderer();
  309. stats = new Stats();
  310. container.appendChild( stats.dom );
  311. container.style.touchAction = 'none';
  312. container.addEventListener( 'pointermove', onPointerMove );
  313. //
  314. window.addEventListener( 'resize', onWindowResize );
  315. const gui = new GUI();
  316. const effectController = {
  317. separation: 20.0,
  318. alignment: 20.0,
  319. cohesion: 20.0,
  320. freedom: 0.75
  321. };
  322. const valuesChanger = function () {
  323. velocityUniforms[ 'separationDistance' ].value = effectController.separation;
  324. velocityUniforms[ 'alignmentDistance' ].value = effectController.alignment;
  325. velocityUniforms[ 'cohesionDistance' ].value = effectController.cohesion;
  326. velocityUniforms[ 'freedomFactor' ].value = effectController.freedom;
  327. };
  328. valuesChanger();
  329. gui.add( effectController, 'separation', 0.0, 100.0, 1.0 ).onChange( valuesChanger );
  330. gui.add( effectController, 'alignment', 0.0, 100, 0.001 ).onChange( valuesChanger );
  331. gui.add( effectController, 'cohesion', 0.0, 100, 0.025 ).onChange( valuesChanger );
  332. gui.close();
  333. initBirds();
  334. }
  335. function initComputeRenderer() {
  336. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  337. const dtPosition = gpuCompute.createTexture();
  338. const dtVelocity = gpuCompute.createTexture();
  339. fillPositionTexture( dtPosition );
  340. fillVelocityTexture( dtVelocity );
  341. velocityVariable = gpuCompute.addVariable( 'textureVelocity', document.getElementById( 'fragmentShaderVelocity' ).textContent, dtVelocity );
  342. positionVariable = gpuCompute.addVariable( 'texturePosition', document.getElementById( 'fragmentShaderPosition' ).textContent, dtPosition );
  343. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  344. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  345. positionUniforms = positionVariable.material.uniforms;
  346. velocityUniforms = velocityVariable.material.uniforms;
  347. positionUniforms[ 'time' ] = { value: 0.0 };
  348. positionUniforms[ 'delta' ] = { value: 0.0 };
  349. velocityUniforms[ 'time' ] = { value: 1.0 };
  350. velocityUniforms[ 'delta' ] = { value: 0.0 };
  351. velocityUniforms[ 'testing' ] = { value: 1.0 };
  352. velocityUniforms[ 'separationDistance' ] = { value: 1.0 };
  353. velocityUniforms[ 'alignmentDistance' ] = { value: 1.0 };
  354. velocityUniforms[ 'cohesionDistance' ] = { value: 1.0 };
  355. velocityUniforms[ 'freedomFactor' ] = { value: 1.0 };
  356. velocityUniforms[ 'predator' ] = { value: new THREE.Vector3() };
  357. velocityVariable.material.defines.BOUNDS = BOUNDS.toFixed( 2 );
  358. velocityVariable.wrapS = THREE.RepeatWrapping;
  359. velocityVariable.wrapT = THREE.RepeatWrapping;
  360. positionVariable.wrapS = THREE.RepeatWrapping;
  361. positionVariable.wrapT = THREE.RepeatWrapping;
  362. const error = gpuCompute.init();
  363. if ( error !== null ) {
  364. console.error( error );
  365. }
  366. }
  367. function initBirds() {
  368. const geometry = new BirdGeometry();
  369. // For Vertex and Fragment
  370. birdUniforms = {
  371. 'color': { value: new THREE.Color( 0xff2200 ) },
  372. 'texturePosition': { value: null },
  373. 'textureVelocity': { value: null },
  374. 'time': { value: 1.0 },
  375. 'delta': { value: 0.0 }
  376. };
  377. // THREE.ShaderMaterial
  378. const material = new THREE.ShaderMaterial( {
  379. uniforms: birdUniforms,
  380. vertexShader: document.getElementById( 'birdVS' ).textContent,
  381. fragmentShader: document.getElementById( 'birdFS' ).textContent,
  382. side: THREE.DoubleSide
  383. } );
  384. const birdMesh = new THREE.Mesh( geometry, material );
  385. birdMesh.rotation.y = Math.PI / 2;
  386. birdMesh.matrixAutoUpdate = false;
  387. birdMesh.updateMatrix();
  388. scene.add( birdMesh );
  389. }
  390. function fillPositionTexture( texture ) {
  391. const theArray = texture.image.data;
  392. for ( let k = 0, kl = theArray.length; k < kl; k += 4 ) {
  393. const x = Math.random() * BOUNDS - BOUNDS_HALF;
  394. const y = Math.random() * BOUNDS - BOUNDS_HALF;
  395. const z = Math.random() * BOUNDS - BOUNDS_HALF;
  396. theArray[ k + 0 ] = x;
  397. theArray[ k + 1 ] = y;
  398. theArray[ k + 2 ] = z;
  399. theArray[ k + 3 ] = 1;
  400. }
  401. }
  402. function fillVelocityTexture( texture ) {
  403. const theArray = texture.image.data;
  404. for ( let k = 0, kl = theArray.length; k < kl; k += 4 ) {
  405. const x = Math.random() - 0.5;
  406. const y = Math.random() - 0.5;
  407. const z = Math.random() - 0.5;
  408. theArray[ k + 0 ] = x * 10;
  409. theArray[ k + 1 ] = y * 10;
  410. theArray[ k + 2 ] = z * 10;
  411. theArray[ k + 3 ] = 1;
  412. }
  413. }
  414. function onWindowResize() {
  415. windowHalfX = window.innerWidth / 2;
  416. windowHalfY = window.innerHeight / 2;
  417. camera.aspect = window.innerWidth / window.innerHeight;
  418. camera.updateProjectionMatrix();
  419. renderer.setSize( window.innerWidth, window.innerHeight );
  420. }
  421. function onPointerMove( event ) {
  422. if ( event.isPrimary === false ) return;
  423. mouseX = event.clientX - windowHalfX;
  424. mouseY = event.clientY - windowHalfY;
  425. }
  426. //
  427. function animate() {
  428. render();
  429. stats.update();
  430. }
  431. function render() {
  432. const now = performance.now();
  433. let delta = ( now - last ) / 1000;
  434. if ( delta > 1 ) delta = 1; // safety cap on large deltas
  435. last = now;
  436. positionUniforms[ 'time' ].value = now;
  437. positionUniforms[ 'delta' ].value = delta;
  438. velocityUniforms[ 'time' ].value = now;
  439. velocityUniforms[ 'delta' ].value = delta;
  440. birdUniforms[ 'time' ].value = now;
  441. birdUniforms[ 'delta' ].value = delta;
  442. velocityUniforms[ 'predator' ].value.set( 0.5 * mouseX / windowHalfX, - 0.5 * mouseY / windowHalfY, 0 );
  443. mouseX = 10000;
  444. mouseY = 10000;
  445. gpuCompute.compute();
  446. birdUniforms[ 'texturePosition' ].value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  447. birdUniforms[ 'textureVelocity' ].value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  448. renderer.render( scene, camera );
  449. }
  450. </script>
  451. </body>
  452. </html>