webgl_gpgpu_birds.html 17 KB

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