webgl_gpgpu_birds_gltf.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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 + GLTF mesh<br/>
  21. Flamingo by <a href="http://mirada.com/">mirada</a> from <a href="http://ro.me">rome</a><br/>
  22. Move mouse to disturb birds.
  23. </div>
  24. <!-- shader for bird's position -->
  25. <script id="fragmentShaderPosition" type="x-shader/x-fragment">
  26. uniform float time;
  27. uniform float delta;
  28. void main() {
  29. vec2 uv = gl_FragCoord.xy / resolution.xy;
  30. vec4 tmpPos = texture2D( texturePosition, uv );
  31. vec3 position = tmpPos.xyz;
  32. vec3 velocity = texture2D( textureVelocity, uv ).xyz;
  33. float phase = tmpPos.w;
  34. phase = mod( ( phase + delta +
  35. length( velocity.xz ) * delta * 3. +
  36. max( velocity.y, 0.0 ) * delta * 6. ), 62.83 );
  37. gl_FragColor = vec4( position + velocity * delta * 15. , phase );
  38. }
  39. </script>
  40. <!-- shader for bird's velocity -->
  41. <script id="fragmentShaderVelocity" type="x-shader/x-fragment">
  42. uniform float time;
  43. uniform float testing;
  44. uniform float delta; // about 0.016
  45. uniform float separationDistance; // 20
  46. uniform float alignmentDistance; // 40
  47. uniform float cohesionDistance; //
  48. uniform float freedomFactor;
  49. uniform vec3 predator;
  50. const float width = resolution.x;
  51. const float height = resolution.y;
  52. const float PI = 3.141592653589793;
  53. const float PI_2 = PI * 2.0;
  54. // const float VISION = PI * 0.55;
  55. float zoneRadius = 40.0;
  56. float zoneRadiusSquared = 1600.0;
  57. float separationThresh = 0.45;
  58. float alignmentThresh = 0.65;
  59. const float UPPER_BOUNDS = BOUNDS;
  60. const float LOWER_BOUNDS = -UPPER_BOUNDS;
  61. const float SPEED_LIMIT = 9.0;
  62. float rand( vec2 co ){
  63. return fract( sin( dot( co.xy, vec2(12.9898,78.233) ) ) * 43758.5453 );
  64. }
  65. void main() {
  66. zoneRadius = separationDistance + alignmentDistance + cohesionDistance;
  67. separationThresh = separationDistance / zoneRadius;
  68. alignmentThresh = ( separationDistance + alignmentDistance ) / zoneRadius;
  69. zoneRadiusSquared = zoneRadius * zoneRadius;
  70. vec2 uv = gl_FragCoord.xy / resolution.xy;
  71. vec3 birdPosition, birdVelocity;
  72. vec3 selfPosition = texture2D( texturePosition, uv ).xyz;
  73. vec3 selfVelocity = texture2D( textureVelocity, uv ).xyz;
  74. float dist;
  75. vec3 dir; // direction
  76. float distSquared;
  77. float separationSquared = separationDistance * separationDistance;
  78. float cohesionSquared = cohesionDistance * cohesionDistance;
  79. float f;
  80. float percent;
  81. vec3 velocity = selfVelocity;
  82. float limit = SPEED_LIMIT;
  83. dir = predator * UPPER_BOUNDS - selfPosition;
  84. dir.z = 0.;
  85. // dir.z *= 0.6;
  86. dist = length( dir );
  87. distSquared = dist * dist;
  88. float preyRadius = 150.0;
  89. float preyRadiusSq = preyRadius * preyRadius;
  90. // move birds away from predator
  91. if ( dist < preyRadius ) {
  92. f = ( distSquared / preyRadiusSq - 1.0 ) * delta * 100.;
  93. velocity += normalize( dir ) * f;
  94. limit += 5.0;
  95. }
  96. // if (testing == 0.0) {}
  97. // if ( rand( uv + time ) < freedomFactor ) {}
  98. // Attract flocks to the center
  99. vec3 central = vec3( 0., 0., 0. );
  100. dir = selfPosition - central;
  101. dist = length( dir );
  102. dir.y *= 2.5;
  103. velocity -= normalize( dir ) * delta * 5.;
  104. for ( float y = 0.0; y < height; y++ ) {
  105. for ( float x = 0.0; x < width; x++ ) {
  106. vec2 ref = vec2( x + 0.5, y + 0.5 ) / resolution.xy;
  107. birdPosition = texture2D( texturePosition, ref ).xyz;
  108. dir = birdPosition - selfPosition;
  109. dist = length( dir );
  110. if ( dist < 0.0001 ) continue;
  111. distSquared = dist * dist;
  112. if ( distSquared > zoneRadiusSquared ) continue;
  113. percent = distSquared / zoneRadiusSquared;
  114. if ( percent < separationThresh ) { // low
  115. // Separation - Move apart for comfort
  116. f = ( separationThresh / percent - 1.0 ) * delta;
  117. velocity -= normalize( dir ) * f;
  118. } else if ( percent < alignmentThresh ) { // high
  119. // Alignment - fly the same direction
  120. float threshDelta = alignmentThresh - separationThresh;
  121. float adjustedPercent = ( percent - separationThresh ) / threshDelta;
  122. birdVelocity = texture2D( textureVelocity, ref ).xyz;
  123. f = ( 0.5 - cos( adjustedPercent * PI_2 ) * 0.5 + 0.5 ) * delta;
  124. velocity += normalize( birdVelocity ) * f;
  125. } else {
  126. // Attraction / Cohesion - move closer
  127. float threshDelta = 1.0 - alignmentThresh;
  128. float adjustedPercent = ( percent - alignmentThresh ) / threshDelta;
  129. f = ( 0.5 - ( cos( adjustedPercent * PI_2 ) * -0.5 + 0.5 ) ) * delta;
  130. velocity += normalize( dir ) * f;
  131. }
  132. }
  133. }
  134. // this make tends to fly around than down or up
  135. // if (velocity.y > 0.) velocity.y *= (1. - 0.2 * delta);
  136. // Speed Limits
  137. if ( length( velocity ) > limit ) {
  138. velocity = normalize( velocity ) * limit;
  139. }
  140. gl_FragColor = vec4( velocity, 1.0 );
  141. }
  142. </script>
  143. <script type="module">
  144. import * as THREE from '../build/three.module.js';
  145. import Stats from './jsm/libs/stats.module.js';
  146. import { GUI } from './jsm/libs/dat.gui.module.js';
  147. import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
  148. import { GPUComputationRenderer } from './jsm/misc/GPUComputationRenderer.js';
  149. /* TEXTURE WIDTH FOR SIMULATION */
  150. var WIDTH = 64;
  151. var BIRDS = WIDTH * WIDTH;
  152. /* BAKE ANIMATION INTO TEXTURE and CREATE GEOMETRY FROM BASE MODEL */
  153. var BirdGeometry = new THREE.BufferGeometry();
  154. var textureAnimation, durationAnimation, birdMesh, materialShader, vertexPerBird;
  155. function nextPowerOf2( n ) {
  156. return Math.pow( 2, Math.ceil( Math.log( n ) / Math.log( 2 ) ) );
  157. }
  158. Math.lerp = function ( value1, value2, amount ) {
  159. amount = Math.max( Math.min( amount, 1 ), 0 );
  160. return value1 + ( value2 - value1 ) * amount;
  161. };
  162. var gltfs = [ 'models/gltf/Parrot.glb', 'models/gltf/Flamingo.glb' ];
  163. var colors = [ 0xccFFFF, 0xffdeff ];
  164. var sizes = [ 0.2, 0.1 ];
  165. var selectModel = Math.floor( Math.random() * gltfs.length );
  166. new GLTFLoader().load( gltfs[ selectModel ], function ( gltf ) {
  167. var animations = gltf.animations;
  168. durationAnimation = Math.round( animations[ 0 ].duration * 60 );
  169. var birdGeo = gltf.scene.children[ 0 ].geometry;
  170. var morphAttributes = birdGeo.morphAttributes.position;
  171. var tHeight = nextPowerOf2( durationAnimation );
  172. var tWidth = nextPowerOf2( birdGeo.getAttribute( 'position' ).count );
  173. vertexPerBird = birdGeo.getAttribute( 'position' ).count;
  174. var tData = new Float32Array( 3 * tWidth * tHeight );
  175. for ( var i = 0; i < tWidth; i ++ ) {
  176. for ( var j = 0; j < tHeight; j ++ ) {
  177. var offset = j * tWidth * 3;
  178. var curMorph = Math.floor( j / durationAnimation * morphAttributes.length );
  179. var nextMorph = ( Math.floor( j / durationAnimation * morphAttributes.length ) + 1 ) % morphAttributes.length;
  180. var lerpAmount = j / durationAnimation * morphAttributes.length % 1;
  181. if ( j < durationAnimation ) {
  182. tData[ offset + i * 3 ] = Math.lerp( morphAttributes[ curMorph ].array[ i * 3 ], morphAttributes[ nextMorph ].array[ i * 3 ], lerpAmount );
  183. tData[ offset + i * 3 + 1 ] = Math.lerp( morphAttributes[ curMorph ].array[ i * 3 + 1 ], morphAttributes[ nextMorph ].array[ i * 3 + 1 ], lerpAmount );
  184. tData[ offset + i * 3 + 2 ] = Math.lerp( morphAttributes[ curMorph ].array[ i * 3 + 2 ], morphAttributes[ nextMorph ].array[ i * 3 + 2 ], lerpAmount );
  185. }
  186. }
  187. }
  188. textureAnimation = new THREE.DataTexture( tData, tWidth, tHeight, THREE.RGBFormat, THREE.FloatType );
  189. textureAnimation.needsUpdate = true;
  190. var vertices = [], color = [], reference = [], seeds = [], indices = [];
  191. var totalVertices = birdGeo.getAttribute( 'position' ).count * 3 * BIRDS;
  192. for ( var i = 0; i < totalVertices; i ++ ) {
  193. var bIndex = i % ( birdGeo.getAttribute( 'position' ).count * 3 );
  194. vertices.push( birdGeo.getAttribute( 'position' ).array[ bIndex ] );
  195. color.push( birdGeo.getAttribute( 'color' ).array[ bIndex ] );
  196. }
  197. var r = Math.random();
  198. for ( var i = 0; i < birdGeo.getAttribute( 'position' ).count * BIRDS; i ++ ) {
  199. var bIndex = i % ( birdGeo.getAttribute( 'position' ).count );
  200. var bird = Math.floor( i / birdGeo.getAttribute( 'position' ).count );
  201. if ( bIndex == 0 ) r = Math.random();
  202. var j = ~ ~ bird;
  203. var x = ( j % WIDTH ) / WIDTH;
  204. var y = ~ ~ ( j / WIDTH ) / WIDTH;
  205. reference.push( x, y, bIndex / tWidth, durationAnimation / tHeight );
  206. seeds.push( bird, r, Math.random(), Math.random() );
  207. }
  208. for ( var i = 0; i < birdGeo.index.array.length * BIRDS; i ++ ) {
  209. var offset = Math.floor( i / birdGeo.index.array.length ) * ( birdGeo.getAttribute( 'position' ).count );
  210. indices.push( birdGeo.index.array[ i % birdGeo.index.array.length ] + offset );
  211. }
  212. BirdGeometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
  213. BirdGeometry.setAttribute( 'birdColor', new THREE.BufferAttribute( new Float32Array( color ), 3 ) );
  214. BirdGeometry.setAttribute( 'color', new THREE.BufferAttribute( new Float32Array( color ), 3 ) );
  215. BirdGeometry.setAttribute( 'reference', new THREE.BufferAttribute( new Float32Array( reference ), 4 ) );
  216. BirdGeometry.setAttribute( 'seeds', new THREE.BufferAttribute( new Float32Array( seeds ), 4 ) );
  217. BirdGeometry.setIndex( indices );
  218. init();
  219. animate();
  220. } );
  221. var container, stats;
  222. var camera, scene, renderer;
  223. var mouseX = 0, mouseY = 0;
  224. var windowHalfX = window.innerWidth / 2;
  225. var windowHalfY = window.innerHeight / 2;
  226. var BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  227. var last = performance.now();
  228. var gpuCompute;
  229. var velocityVariable;
  230. var positionVariable;
  231. var positionUniforms;
  232. var velocityUniforms;
  233. function init() {
  234. container = document.createElement( 'div' );
  235. document.body.appendChild( container );
  236. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  237. camera.position.z = 350;
  238. scene = new THREE.Scene();
  239. scene.background = new THREE.Color( colors[ selectModel ] );
  240. scene.fog = new THREE.Fog( colors[ selectModel ], 100, 1000 );
  241. // LIGHTS
  242. var hemiLight = new THREE.HemisphereLight( colors[ selectModel ], 0xffffff, 1.6 );
  243. hemiLight.color.setHSL( 0.6, 1, 0.6 );
  244. hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
  245. hemiLight.position.set( 0, 50, 0 );
  246. scene.add( hemiLight );
  247. var dirLight = new THREE.DirectionalLight( 0x00CED1, 0.6 );
  248. dirLight.color.setHSL( 0.1, 1, 0.95 );
  249. dirLight.position.set( - 1, 1.75, 1 );
  250. dirLight.position.multiplyScalar( 30 );
  251. scene.add( dirLight );
  252. renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
  253. renderer.setPixelRatio( window.devicePixelRatio );
  254. renderer.setSize( window.innerWidth, window.innerHeight );
  255. container.appendChild( renderer.domElement );
  256. initComputeRenderer();
  257. stats = new Stats();
  258. container.appendChild( stats.dom );
  259. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  260. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  261. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  262. window.addEventListener( 'resize', onWindowResize, false );
  263. var gui = new GUI();
  264. var effectController = {
  265. separation: 20.0,
  266. alignment: 20.0,
  267. cohesion: 20.0,
  268. freedom: 0.75,
  269. size: sizes[ selectModel ],
  270. count: BIRDS
  271. };
  272. var valuesChanger = function () {
  273. velocityUniforms[ "separationDistance" ].value = effectController.separation;
  274. velocityUniforms[ "alignmentDistance" ].value = effectController.alignment;
  275. velocityUniforms[ "cohesionDistance" ].value = effectController.cohesion;
  276. velocityUniforms[ "freedomFactor" ].value = effectController.freedom;
  277. if ( materialShader ) materialShader.uniforms[ "size" ].value = effectController.size;
  278. BirdGeometry.setDrawRange( 0, vertexPerBird * effectController.count );
  279. };
  280. valuesChanger();
  281. gui.add( effectController, "separation", 0.0, 100.0, 1.0 ).onChange( valuesChanger );
  282. gui.add( effectController, "alignment", 0.0, 100, 0.001 ).onChange( valuesChanger );
  283. gui.add( effectController, "cohesion", 0.0, 100, 0.025 ).onChange( valuesChanger );
  284. gui.add( effectController, "size", 0, 1, 0.01 ).onChange( valuesChanger );
  285. gui.add( effectController, "count", 0, BIRDS, 1 ).onChange( valuesChanger );
  286. gui.close();
  287. initBirds();
  288. }
  289. function initComputeRenderer() {
  290. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  291. var dtPosition = gpuCompute.createTexture();
  292. var dtVelocity = gpuCompute.createTexture();
  293. fillPositionTexture( dtPosition );
  294. fillVelocityTexture( dtVelocity );
  295. velocityVariable = gpuCompute.addVariable( "textureVelocity", document.getElementById( 'fragmentShaderVelocity' ).textContent, dtVelocity );
  296. positionVariable = gpuCompute.addVariable( "texturePosition", document.getElementById( 'fragmentShaderPosition' ).textContent, dtPosition );
  297. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  298. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  299. positionUniforms = positionVariable.material.uniforms;
  300. velocityUniforms = velocityVariable.material.uniforms;
  301. positionUniforms[ "time" ] = { value: 0.0 };
  302. positionUniforms[ "delta" ] = { value: 0.0 };
  303. velocityUniforms[ "time" ] = { value: 1.0 };
  304. velocityUniforms[ "delta" ] = { value: 0.0 };
  305. velocityUniforms[ "testing" ] = { value: 1.0 };
  306. velocityUniforms[ "separationDistance" ] = { value: 1.0 };
  307. velocityUniforms[ "alignmentDistance" ] = { value: 1.0 };
  308. velocityUniforms[ "cohesionDistance" ] = { value: 1.0 };
  309. velocityUniforms[ "freedomFactor" ] = { value: 1.0 };
  310. velocityUniforms[ "predator" ] = { value: new THREE.Vector3() };
  311. velocityVariable.material.defines.BOUNDS = BOUNDS.toFixed( 2 );
  312. velocityVariable.wrapS = THREE.RepeatWrapping;
  313. velocityVariable.wrapT = THREE.RepeatWrapping;
  314. positionVariable.wrapS = THREE.RepeatWrapping;
  315. positionVariable.wrapT = THREE.RepeatWrapping;
  316. var error = gpuCompute.init();
  317. if ( error !== null ) {
  318. console.error( error );
  319. }
  320. }
  321. function initBirds() {
  322. var geometry = BirdGeometry;
  323. var m = new THREE.MeshStandardMaterial( {
  324. vertexColors: true,
  325. flatShading: true,
  326. roughness: 1,
  327. metalness: 0
  328. } );
  329. m.onBeforeCompile = ( shader ) => {
  330. shader.uniforms.texturePosition = { value: null };
  331. shader.uniforms.textureVelocity = { value: null };
  332. shader.uniforms.textureAnimation = { value: textureAnimation };
  333. shader.uniforms.time = { value: 1.0 };
  334. shader.uniforms.size = { value: 0.1 };
  335. shader.uniforms.delta = { value: 0.0 };
  336. var token = '#define STANDARD';
  337. var insert = /* glsl */`
  338. attribute vec4 reference;
  339. attribute vec4 seeds;
  340. attribute vec3 birdColor;
  341. uniform sampler2D texturePosition;
  342. uniform sampler2D textureVelocity;
  343. uniform sampler2D textureAnimation;
  344. uniform float size;
  345. uniform float time;
  346. `;
  347. shader.vertexShader = shader.vertexShader.replace( token, token + insert );
  348. var token = '#include <begin_vertex>';
  349. var insert = /* glsl */`
  350. vec4 tmpPos = texture2D( texturePosition, reference.xy );
  351. vec3 pos = tmpPos.xyz;
  352. vec3 velocity = normalize(texture2D( textureVelocity, reference.xy ).xyz);
  353. vec3 aniPos = texture2D( textureAnimation, vec2( reference.z, mod( ( time + seeds.x ) * ( ( 0.0004 + seeds.y / 10000.0) + normalize( velocity ) / 20000.0 ), reference.w ) ) ).xyz;
  354. vec3 newPosition = position;
  355. newPosition = mat3( modelMatrix ) * ( newPosition + aniPos );
  356. newPosition *= size + seeds.y * size * 0.2;
  357. velocity.z *= -1.;
  358. float xz = length( velocity.xz );
  359. float xyz = 1.;
  360. float x = sqrt( 1. - velocity.y * velocity.y );
  361. float cosry = velocity.x / xz;
  362. float sinry = velocity.z / xz;
  363. float cosrz = x / xyz;
  364. float sinrz = velocity.y / xyz;
  365. mat3 maty = mat3( cosry, 0, -sinry, 0 , 1, 0 , sinry, 0, cosry );
  366. mat3 matz = mat3( cosrz , sinrz, 0, -sinrz, cosrz, 0, 0 , 0 , 1 );
  367. newPosition = maty * matz * newPosition;
  368. newPosition += pos;
  369. vec3 transformed = vec3( newPosition );
  370. `;
  371. shader.vertexShader = shader.vertexShader.replace( token, insert );
  372. materialShader = shader;
  373. };
  374. birdMesh = new THREE.Mesh( geometry, m );
  375. birdMesh.rotation.y = Math.PI / 2;
  376. birdMesh.castShadow = true;
  377. birdMesh.receiveShadow = true;
  378. scene.add( birdMesh );
  379. }
  380. function fillPositionTexture( texture ) {
  381. var theArray = texture.image.data;
  382. for ( var k = 0, kl = theArray.length; k < kl; k += 4 ) {
  383. var x = Math.random() * BOUNDS - BOUNDS_HALF;
  384. var y = Math.random() * BOUNDS - BOUNDS_HALF;
  385. var z = Math.random() * BOUNDS - BOUNDS_HALF;
  386. theArray[ k + 0 ] = x;
  387. theArray[ k + 1 ] = y;
  388. theArray[ k + 2 ] = z;
  389. theArray[ k + 3 ] = 1;
  390. }
  391. }
  392. function fillVelocityTexture( texture ) {
  393. var theArray = texture.image.data;
  394. for ( var k = 0, kl = theArray.length; k < kl; k += 4 ) {
  395. var x = Math.random() - 0.5;
  396. var y = Math.random() - 0.5;
  397. var z = Math.random() - 0.5;
  398. theArray[ k + 0 ] = x * 10;
  399. theArray[ k + 1 ] = y * 10;
  400. theArray[ k + 2 ] = z * 10;
  401. theArray[ k + 3 ] = 1;
  402. }
  403. }
  404. function onWindowResize() {
  405. windowHalfX = window.innerWidth / 2;
  406. windowHalfY = window.innerHeight / 2;
  407. camera.aspect = window.innerWidth / window.innerHeight;
  408. camera.updateProjectionMatrix();
  409. renderer.setSize( window.innerWidth, window.innerHeight );
  410. }
  411. function onDocumentMouseMove( event ) {
  412. mouseX = event.clientX - windowHalfX;
  413. mouseY = event.clientY - windowHalfY;
  414. }
  415. function onDocumentTouchStart( event ) {
  416. if ( event.touches.length === 1 ) {
  417. event.preventDefault();
  418. mouseX = event.touches[ 0 ].pageX - windowHalfX;
  419. mouseY = event.touches[ 0 ].pageY - windowHalfY;
  420. }
  421. }
  422. function onDocumentTouchMove( event ) {
  423. if ( event.touches.length === 1 ) {
  424. event.preventDefault();
  425. mouseX = event.touches[ 0 ].pageX - windowHalfX;
  426. mouseY = event.touches[ 0 ].pageY - windowHalfY;
  427. }
  428. }
  429. //
  430. function animate() {
  431. requestAnimationFrame( animate );
  432. render();
  433. stats.update();
  434. }
  435. function render() {
  436. var now = performance.now();
  437. var delta = ( now - last ) / 1000;
  438. if ( delta > 1 ) delta = 1; // safety cap on large deltas
  439. last = now;
  440. positionUniforms[ "time" ].value = now;
  441. positionUniforms[ "delta" ].value = delta;
  442. velocityUniforms[ "time" ].value = now;
  443. velocityUniforms[ "delta" ].value = delta;
  444. if ( materialShader ) materialShader.uniforms[ "time" ].value = now;
  445. if ( materialShader ) materialShader.uniforms[ "delta" ].value = delta;
  446. velocityUniforms[ "predator" ].value.set( 0.5 * mouseX / windowHalfX, - 0.5 * mouseY / windowHalfY, 0 );
  447. mouseX = 10000;
  448. mouseY = 10000;
  449. gpuCompute.compute();
  450. if ( materialShader ) materialShader.uniforms[ "texturePosition" ].value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  451. if ( materialShader ) materialShader.uniforms[ "textureVelocity" ].value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  452. renderer.render( scene, camera );
  453. }
  454. </script>
  455. </body>
  456. </html>