webgl_gpgpu_birds.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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 = ( percent - alignmentThresh ) / threshDelta;
  132. f = ( 0.5 - ( cos( adjustedPercent * PI_2 ) * -0.5 + 0.5 ) ) * delta;
  133. velocity += normalize( dir ) * f;
  134. }
  135. }
  136. }
  137. // this make tends to fly around than down or up
  138. // if (velocity.y > 0.) velocity.y *= (1. - 0.2 * delta);
  139. // Speed Limits
  140. if ( length( velocity ) > limit ) {
  141. velocity = normalize( velocity ) * limit;
  142. }
  143. gl_FragColor = vec4( velocity, 1.0 );
  144. }
  145. </script>
  146. <script type="x-shader/x-vertex" id="birdVS">
  147. attribute vec2 reference;
  148. attribute float birdVertex;
  149. attribute vec3 birdColor;
  150. uniform sampler2D texturePosition;
  151. uniform sampler2D textureVelocity;
  152. varying vec4 vColor;
  153. varying float z;
  154. uniform float time;
  155. void main() {
  156. vec4 tmpPos = texture2D( texturePosition, reference );
  157. vec3 pos = tmpPos.xyz;
  158. vec3 velocity = normalize(texture2D( textureVelocity, reference ).xyz);
  159. vec3 newPosition = position;
  160. if ( birdVertex == 4.0 || birdVertex == 7.0 ) {
  161. // flap wings
  162. newPosition.y = sin( tmpPos.w ) * 5.;
  163. }
  164. newPosition = mat3( modelMatrix ) * newPosition;
  165. velocity.z *= -1.;
  166. float xz = length( velocity.xz );
  167. float xyz = 1.;
  168. float x = sqrt( 1. - velocity.y * velocity.y );
  169. float cosry = velocity.x / xz;
  170. float sinry = velocity.z / xz;
  171. float cosrz = x / xyz;
  172. float sinrz = velocity.y / xyz;
  173. mat3 maty = mat3(
  174. cosry, 0, -sinry,
  175. 0 , 1, 0 ,
  176. sinry, 0, cosry
  177. );
  178. mat3 matz = mat3(
  179. cosrz , sinrz, 0,
  180. -sinrz, cosrz, 0,
  181. 0 , 0 , 1
  182. );
  183. newPosition = maty * matz * newPosition;
  184. newPosition += pos;
  185. z = newPosition.z;
  186. vColor = vec4( birdColor, 1.0 );
  187. gl_Position = projectionMatrix * viewMatrix * vec4( newPosition, 1.0 );
  188. }
  189. </script>
  190. <!-- bird geometry shader -->
  191. <script type="x-shader/x-fragment" id="birdFS">
  192. varying vec4 vColor;
  193. varying float z;
  194. uniform vec3 color;
  195. void main() {
  196. // Fake colors for now
  197. float z2 = 0.2 + ( 1000. - z ) / 1000. * vColor.x;
  198. gl_FragColor = vec4( z2, z2, z2, 1. );
  199. }
  200. </script>
  201. <script type="module">
  202. import * as THREE from '../build/three.module.js';
  203. import Stats from './jsm/libs/stats.module.js';
  204. import { GUI } from './jsm/libs/dat.gui.module.js';
  205. import { GPUComputationRenderer } from './jsm/misc/GPUComputationRenderer.js';
  206. /* TEXTURE WIDTH FOR SIMULATION */
  207. var WIDTH = 32;
  208. var BIRDS = WIDTH * WIDTH;
  209. // Custom Geometry - using 3 triangles each. No UVs, no normals currently.
  210. var BirdGeometry = function () {
  211. var triangles = BIRDS * 3;
  212. var points = triangles * 3;
  213. THREE.BufferGeometry.call( this );
  214. var vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  215. var birdColors = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  216. var references = new THREE.BufferAttribute( new Float32Array( points * 2 ), 2 );
  217. var birdVertex = new THREE.BufferAttribute( new Float32Array( points ), 1 );
  218. this.setAttribute( 'position', vertices );
  219. this.setAttribute( 'birdColor', birdColors );
  220. this.setAttribute( 'reference', references );
  221. this.setAttribute( 'birdVertex', birdVertex );
  222. // this.setAttribute( 'normal', new Float32Array( points * 3 ), 3 );
  223. var v = 0;
  224. function verts_push() {
  225. for ( var i = 0; i < arguments.length; i ++ ) {
  226. vertices.array[ v ++ ] = arguments[ i ];
  227. }
  228. }
  229. var wingsSpan = 20;
  230. for ( var f = 0; f < BIRDS; f ++ ) {
  231. // Body
  232. verts_push(
  233. 0, - 0, - 20,
  234. 0, 4, - 20,
  235. 0, 0, 30
  236. );
  237. // Left Wing
  238. verts_push(
  239. 0, 0, - 15,
  240. - wingsSpan, 0, 0,
  241. 0, 0, 15
  242. );
  243. // Right Wing
  244. verts_push(
  245. 0, 0, 15,
  246. wingsSpan, 0, 0,
  247. 0, 0, - 15
  248. );
  249. }
  250. for ( var v = 0; v < triangles * 3; v ++ ) {
  251. var i = ~ ~ ( v / 3 );
  252. var x = ( i % WIDTH ) / WIDTH;
  253. var y = ~ ~ ( i / WIDTH ) / WIDTH;
  254. var c = new THREE.Color(
  255. 0x444444 +
  256. ~ ~ ( v / 9 ) / BIRDS * 0x666666
  257. );
  258. birdColors.array[ v * 3 + 0 ] = c.r;
  259. birdColors.array[ v * 3 + 1 ] = c.g;
  260. birdColors.array[ v * 3 + 2 ] = c.b;
  261. references.array[ v * 2 ] = x;
  262. references.array[ v * 2 + 1 ] = y;
  263. birdVertex.array[ v ] = v % 9;
  264. }
  265. this.scale( 0.2, 0.2, 0.2 );
  266. };
  267. BirdGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  268. var container, stats;
  269. var camera, scene, renderer;
  270. var mouseX = 0, mouseY = 0;
  271. var windowHalfX = window.innerWidth / 2;
  272. var windowHalfY = window.innerHeight / 2;
  273. var BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  274. var last = performance.now();
  275. var gpuCompute;
  276. var velocityVariable;
  277. var positionVariable;
  278. var positionUniforms;
  279. var velocityUniforms;
  280. var birdUniforms;
  281. init();
  282. animate();
  283. function init() {
  284. container = document.createElement( 'div' );
  285. document.body.appendChild( container );
  286. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  287. camera.position.z = 350;
  288. scene = new THREE.Scene();
  289. scene.background = new THREE.Color( 0xffffff );
  290. scene.fog = new THREE.Fog( 0xffffff, 100, 1000 );
  291. renderer = new THREE.WebGLRenderer();
  292. renderer.setPixelRatio( window.devicePixelRatio );
  293. renderer.setSize( window.innerWidth, window.innerHeight );
  294. container.appendChild( renderer.domElement );
  295. initComputeRenderer();
  296. stats = new Stats();
  297. container.appendChild( stats.dom );
  298. container.style.touchAction = 'none';
  299. container.addEventListener( 'pointermove', onPointerMove, false );
  300. //
  301. window.addEventListener( 'resize', onWindowResize, false );
  302. var gui = new GUI();
  303. var effectController = {
  304. separation: 20.0,
  305. alignment: 20.0,
  306. cohesion: 20.0,
  307. freedom: 0.75
  308. };
  309. var valuesChanger = function () {
  310. velocityUniforms[ "separationDistance" ].value = effectController.separation;
  311. velocityUniforms[ "alignmentDistance" ].value = effectController.alignment;
  312. velocityUniforms[ "cohesionDistance" ].value = effectController.cohesion;
  313. velocityUniforms[ "freedomFactor" ].value = effectController.freedom;
  314. };
  315. valuesChanger();
  316. gui.add( effectController, "separation", 0.0, 100.0, 1.0 ).onChange( valuesChanger );
  317. gui.add( effectController, "alignment", 0.0, 100, 0.001 ).onChange( valuesChanger );
  318. gui.add( effectController, "cohesion", 0.0, 100, 0.025 ).onChange( valuesChanger );
  319. gui.close();
  320. initBirds();
  321. }
  322. function initComputeRenderer() {
  323. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  324. if ( isSafari() ) {
  325. gpuCompute.setDataType( THREE.HalfFloatType );
  326. }
  327. var dtPosition = gpuCompute.createTexture();
  328. var dtVelocity = gpuCompute.createTexture();
  329. fillPositionTexture( dtPosition );
  330. fillVelocityTexture( dtVelocity );
  331. velocityVariable = gpuCompute.addVariable( "textureVelocity", document.getElementById( 'fragmentShaderVelocity' ).textContent, dtVelocity );
  332. positionVariable = gpuCompute.addVariable( "texturePosition", document.getElementById( 'fragmentShaderPosition' ).textContent, dtPosition );
  333. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  334. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  335. positionUniforms = positionVariable.material.uniforms;
  336. velocityUniforms = velocityVariable.material.uniforms;
  337. positionUniforms[ "time" ] = { value: 0.0 };
  338. positionUniforms[ "delta" ] = { value: 0.0 };
  339. velocityUniforms[ "time" ] = { value: 1.0 };
  340. velocityUniforms[ "delta" ] = { value: 0.0 };
  341. velocityUniforms[ "testing" ] = { value: 1.0 };
  342. velocityUniforms[ "separationDistance" ] = { value: 1.0 };
  343. velocityUniforms[ "alignmentDistance" ] = { value: 1.0 };
  344. velocityUniforms[ "cohesionDistance" ] = { value: 1.0 };
  345. velocityUniforms[ "freedomFactor" ] = { value: 1.0 };
  346. velocityUniforms[ "predator" ] = { value: new THREE.Vector3() };
  347. velocityVariable.material.defines.BOUNDS = BOUNDS.toFixed( 2 );
  348. velocityVariable.wrapS = THREE.RepeatWrapping;
  349. velocityVariable.wrapT = THREE.RepeatWrapping;
  350. positionVariable.wrapS = THREE.RepeatWrapping;
  351. positionVariable.wrapT = THREE.RepeatWrapping;
  352. var error = gpuCompute.init();
  353. if ( error !== null ) {
  354. console.error( error );
  355. }
  356. }
  357. function isSafari() {
  358. return !! navigator.userAgent.match( /Safari/i ) && ! navigator.userAgent.match( /Chrome/i );
  359. }
  360. function initBirds() {
  361. var geometry = new BirdGeometry();
  362. // For Vertex and Fragment
  363. birdUniforms = {
  364. "color": { value: new THREE.Color( 0xff2200 ) },
  365. "texturePosition": { value: null },
  366. "textureVelocity": { value: null },
  367. "time": { value: 1.0 },
  368. "delta": { value: 0.0 }
  369. };
  370. // THREE.ShaderMaterial
  371. var material = new THREE.ShaderMaterial( {
  372. uniforms: birdUniforms,
  373. vertexShader: document.getElementById( 'birdVS' ).textContent,
  374. fragmentShader: document.getElementById( 'birdFS' ).textContent,
  375. side: THREE.DoubleSide
  376. } );
  377. var birdMesh = new THREE.Mesh( geometry, material );
  378. birdMesh.rotation.y = Math.PI / 2;
  379. birdMesh.matrixAutoUpdate = false;
  380. birdMesh.updateMatrix();
  381. scene.add( birdMesh );
  382. }
  383. function fillPositionTexture( texture ) {
  384. var theArray = texture.image.data;
  385. for ( var k = 0, kl = theArray.length; k < kl; k += 4 ) {
  386. var x = Math.random() * BOUNDS - BOUNDS_HALF;
  387. var y = Math.random() * BOUNDS - BOUNDS_HALF;
  388. var z = Math.random() * BOUNDS - BOUNDS_HALF;
  389. theArray[ k + 0 ] = x;
  390. theArray[ k + 1 ] = y;
  391. theArray[ k + 2 ] = z;
  392. theArray[ k + 3 ] = 1;
  393. }
  394. }
  395. function fillVelocityTexture( texture ) {
  396. var theArray = texture.image.data;
  397. for ( var k = 0, kl = theArray.length; k < kl; k += 4 ) {
  398. var x = Math.random() - 0.5;
  399. var y = Math.random() - 0.5;
  400. var z = Math.random() - 0.5;
  401. theArray[ k + 0 ] = x * 10;
  402. theArray[ k + 1 ] = y * 10;
  403. theArray[ k + 2 ] = z * 10;
  404. theArray[ k + 3 ] = 1;
  405. }
  406. }
  407. function onWindowResize() {
  408. windowHalfX = window.innerWidth / 2;
  409. windowHalfY = window.innerHeight / 2;
  410. camera.aspect = window.innerWidth / window.innerHeight;
  411. camera.updateProjectionMatrix();
  412. renderer.setSize( window.innerWidth, window.innerHeight );
  413. }
  414. function onPointerMove( event ) {
  415. if ( event.isPrimary === false ) return;
  416. mouseX = event.clientX - windowHalfX;
  417. mouseY = event.clientY - windowHalfY;
  418. }
  419. //
  420. function animate() {
  421. requestAnimationFrame( animate );
  422. render();
  423. stats.update();
  424. }
  425. function render() {
  426. var now = performance.now();
  427. var delta = ( now - last ) / 1000;
  428. if ( delta > 1 ) delta = 1; // safety cap on large deltas
  429. last = now;
  430. positionUniforms[ "time" ].value = now;
  431. positionUniforms[ "delta" ].value = delta;
  432. velocityUniforms[ "time" ].value = now;
  433. velocityUniforms[ "delta" ].value = delta;
  434. birdUniforms[ "time" ].value = now;
  435. birdUniforms[ "delta" ].value = delta;
  436. velocityUniforms[ "predator" ].value.set( 0.5 * mouseX / windowHalfX, - 0.5 * mouseY / windowHalfY, 0 );
  437. mouseX = 10000;
  438. mouseY = 10000;
  439. gpuCompute.compute();
  440. birdUniforms[ "texturePosition" ].value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  441. birdUniforms[ "textureVelocity" ].value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  442. renderer.render( scene, camera );
  443. }
  444. </script>
  445. </body>
  446. </html>