GPUParticleSystem.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. * GPU Particle System
  3. * @author flimshaw - Charlie Hoey - http://charliehoey.com
  4. *
  5. * A simple to use, general purpose GPU system. Particles are spawn-and-forget with
  6. * several options available, and do not require monitoring or cleanup after spawning.
  7. * Because the paths of all particles are completely deterministic once spawned, the scale
  8. * and direction of time is also variable.
  9. *
  10. * Currently uses a static wrapping perlin noise texture for turbulence, and a small png texture for
  11. * particles, but adding support for a particle texture atlas or changing to a different type of turbulence
  12. * would be a fairly light day's work.
  13. *
  14. * Shader and javascript packing code derrived from several Stack Overflow examples.
  15. *
  16. */
  17. THREE.GPUParticleSystem = function(options) {
  18. var self = this;
  19. var options = options || {};
  20. // parse options and use defaults
  21. self.PARTICLE_COUNT = options.maxParticles || 1000000;
  22. self.PARTICLE_CONTAINERS = options.containerCount || 1;
  23. self.PARTICLE_NOISE_TEXTURE = options.particleNoiseTex || null;
  24. self.PARTICLE_SPRITE_TEXTURE = options.particleSpriteTex || null;
  25. self.PARTICLES_PER_CONTAINER = Math.ceil(self.PARTICLE_COUNT / self.PARTICLE_CONTAINERS);
  26. self.PARTICLE_CURSOR = 0;
  27. self.time = 0;
  28. // Custom vertex and fragement shader
  29. var GPUParticleShader = {
  30. vertexShader: [
  31. 'precision highp float;',
  32. 'const vec4 bitSh = vec4(256. * 256. * 256., 256. * 256., 256., 1.);',
  33. 'const vec4 bitMsk = vec4(0.,vec3(1./256.0));',
  34. 'const vec4 bitShifts = vec4(1.) / bitSh;',
  35. '#define FLOAT_MAX 1.70141184e38',
  36. '#define FLOAT_MIN 1.17549435e-38',
  37. 'lowp vec4 encode_float(highp float v) {',
  38. 'highp float av = abs(v);',
  39. '//Handle special cases',
  40. 'if(av < FLOAT_MIN) {',
  41. 'return vec4(0.0, 0.0, 0.0, 0.0);',
  42. '} else if(v > FLOAT_MAX) {',
  43. 'return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;',
  44. '} else if(v < -FLOAT_MAX) {',
  45. 'return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;',
  46. '}',
  47. 'highp vec4 c = vec4(0,0,0,0);',
  48. '//Compute exponent and mantissa',
  49. 'highp float e = floor(log2(av));',
  50. 'highp float m = av * pow(2.0, -e) - 1.0;',
  51. //Unpack mantissa
  52. 'c[1] = floor(128.0 * m);',
  53. 'm -= c[1] / 128.0;',
  54. 'c[2] = floor(32768.0 * m);',
  55. 'm -= c[2] / 32768.0;',
  56. 'c[3] = floor(8388608.0 * m);',
  57. '//Unpack exponent',
  58. 'highp float ebias = e + 127.0;',
  59. 'c[0] = floor(ebias / 2.0);',
  60. 'ebias -= c[0] * 2.0;',
  61. 'c[1] += floor(ebias) * 128.0;',
  62. '//Unpack sign bit',
  63. 'c[0] += 128.0 * step(0.0, -v);',
  64. '//Scale back to range',
  65. 'return c / 255.0;',
  66. '}',
  67. 'vec4 pack(const in float depth)',
  68. '{',
  69. 'const vec4 bit_shift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);',
  70. 'const vec4 bit_mask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);',
  71. 'vec4 res = mod(depth*bit_shift*vec4(255), vec4(256))/vec4(255);',
  72. 'res -= res.xxyz * bit_mask;',
  73. 'return res;',
  74. '}',
  75. 'float unpack(const in vec4 rgba_depth)',
  76. '{',
  77. 'const vec4 bit_shift = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);',
  78. 'float depth = dot(rgba_depth, bit_shift);',
  79. 'return depth;',
  80. '}',
  81. 'uniform float uTime;',
  82. 'uniform float uScale;',
  83. 'uniform sampler2D tNoise;',
  84. 'attribute vec4 particlePositionsStartTime;',
  85. 'attribute vec4 particleVelColSizeLife;',
  86. 'varying vec4 vColor;',
  87. 'varying float lifeLeft;',
  88. 'void main() {',
  89. '// unpack things from our attributes',
  90. 'vColor = encode_float( particleVelColSizeLife.y );',
  91. '// convert our velocity back into a value we can use',
  92. 'vec4 velTurb = encode_float( particleVelColSizeLife.x );',
  93. 'vec3 velocity = vec3( velTurb.xyz );',
  94. 'float turbulence = velTurb.w;',
  95. 'vec3 newPosition;',
  96. 'float timeElapsed = uTime - particlePositionsStartTime.a;',
  97. 'lifeLeft = 1. - (timeElapsed / particleVelColSizeLife.w);',
  98. 'gl_PointSize = ( uScale * particleVelColSizeLife.z ) * lifeLeft;',
  99. 'velocity.x = ( velocity.x - .5 ) * 3.;',
  100. 'velocity.y = ( velocity.y - .5 ) * 3.;',
  101. 'velocity.z = ( velocity.z - .5 ) * 3.;',
  102. 'newPosition = particlePositionsStartTime.xyz + ( velocity * 10. ) * ( uTime - particlePositionsStartTime.a );',
  103. 'vec3 noise = texture2D( tNoise, vec2( newPosition.x * .015 + (uTime * .05), newPosition.y * .02 + (uTime * .015) )).rgb;',
  104. 'vec3 noiseVel = ( noise.rgb - .5 ) * 30.;',
  105. 'newPosition = mix(newPosition, newPosition + vec3(noiseVel * ( turbulence * 5. ) ), (timeElapsed / particleVelColSizeLife.a) );',
  106. 'if( velocity.y > 0. && velocity.y < .05 ) {',
  107. 'lifeLeft = 0.;',
  108. '}',
  109. 'if( velocity.x < -1.45 ) {',
  110. 'lifeLeft = 0.;',
  111. '}',
  112. 'if( timeElapsed > 0. ) {',
  113. 'gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );',
  114. '} else {',
  115. 'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  116. 'lifeLeft = 0.;',
  117. 'gl_PointSize = 0.;',
  118. '}',
  119. '}'
  120. ].join("\n"),
  121. fragmentShader: [
  122. 'float scaleLinear(float value, vec2 valueDomain) {',
  123. 'return (value - valueDomain.x) / (valueDomain.y - valueDomain.x);',
  124. '}',
  125. 'float scaleLinear(float value, vec2 valueDomain, vec2 valueRange) {',
  126. 'return mix(valueRange.x, valueRange.y, scaleLinear(value, valueDomain));',
  127. '}',
  128. 'varying vec4 vColor;',
  129. 'varying float lifeLeft;',
  130. 'uniform sampler2D tSprite;',
  131. 'void main() {',
  132. 'float alpha = 0.;',
  133. 'if( lifeLeft > .995 ) {',
  134. 'alpha = scaleLinear( lifeLeft, vec2(1., .995), vec2(0., 1.));//mix( 0., 1., ( lifeLeft - .95 ) * 100. ) * .75;',
  135. '} else {',
  136. 'alpha = lifeLeft * .75;',
  137. '}',
  138. 'vec4 tex = texture2D( tSprite, gl_PointCoord );',
  139. 'gl_FragColor = vec4( vColor.rgb * tex.a, alpha * tex.a );',
  140. '}'
  141. ].join("\n")
  142. };
  143. // preload a million random numbers
  144. self.rand = [];
  145. for (var i = 1e5; i > 0; i--) {
  146. self.rand.push(Math.random() - .5);
  147. }
  148. self.random = function() {
  149. return ++i >= self.rand.length ? self.rand[i = 1] : self.rand[i];
  150. };
  151. var textureLoader = new THREE.TextureLoader();
  152. self.particleNoiseTex = self.PARTICLE_NOISE_TEXTURE || textureLoader.load("textures/perlin-512.png");
  153. self.particleNoiseTex.wrapS = self.particleNoiseTex.wrapT = THREE.RepeatWrapping;
  154. self.particleSpriteTex = self.PARTICLE_SPRITE_TEXTURE || textureLoader.load("textures/particle2.png");
  155. self.particleSpriteTex.wrapS = self.particleSpriteTex.wrapT = THREE.RepeatWrapping;
  156. self.particleShaderMat = new THREE.ShaderMaterial({
  157. transparent: true,
  158. depthWrite: false,
  159. uniforms: {
  160. "uTime": {
  161. value: 0.0
  162. },
  163. "uScale": {
  164. value: 1.0
  165. },
  166. "tNoise": {
  167. value: self.particleNoiseTex
  168. },
  169. "tSprite": {
  170. value: self.particleSpriteTex
  171. }
  172. },
  173. blending: THREE.AdditiveBlending,
  174. vertexShader: GPUParticleShader.vertexShader,
  175. fragmentShader: GPUParticleShader.fragmentShader
  176. });
  177. // define defaults for all values
  178. self.particleShaderMat.defaultAttributeValues.particlePositionsStartTime = [0, 0, 0, 0];
  179. self.particleShaderMat.defaultAttributeValues.particleVelColSizeLife = [0, 0, 0, 0];
  180. self.particleContainers = [];
  181. // extend Object3D
  182. THREE.Object3D.apply(this, arguments);
  183. this.init = function() {
  184. for (var i = 0; i < self.PARTICLE_CONTAINERS; i++) {
  185. var c = new THREE.GPUParticleContainer(self.PARTICLES_PER_CONTAINER, self);
  186. self.particleContainers.push(c);
  187. self.add(c);
  188. }
  189. };
  190. this.spawnParticle = function(options) {
  191. self.PARTICLE_CURSOR++;
  192. if (self.PARTICLE_CURSOR >= self.PARTICLE_COUNT) {
  193. self.PARTICLE_CURSOR = 1;
  194. }
  195. var currentContainer = self.particleContainers[Math.floor(self.PARTICLE_CURSOR / self.PARTICLES_PER_CONTAINER)];
  196. currentContainer.spawnParticle(options);
  197. };
  198. this.update = function(time) {
  199. for (var i = 0; i < self.PARTICLE_CONTAINERS; i++) {
  200. self.particleContainers[i].update(time);
  201. }
  202. };
  203. this.init();
  204. };
  205. THREE.GPUParticleSystem.prototype = Object.create(THREE.Object3D.prototype);
  206. THREE.GPUParticleSystem.prototype.constructor = THREE.GPUParticleSystem;
  207. // Subclass for particle containers, allows for very large arrays to be spread out
  208. THREE.GPUParticleContainer = function(maxParticles, particleSystem) {
  209. var self = this;
  210. self.PARTICLE_COUNT = maxParticles || 100000;
  211. self.PARTICLE_CURSOR = 0;
  212. self.time = 0;
  213. self.DPR = window.devicePixelRatio;
  214. self.GPUParticleSystem = particleSystem;
  215. var particlesPerArray = Math.floor(self.PARTICLE_COUNT / self.MAX_ATTRIBUTES);
  216. // extend Object3D
  217. THREE.Object3D.apply(this, arguments);
  218. // construct a couple small arrays used for packing variables into floats etc
  219. var UINT8_VIEW = new Uint8Array(4);
  220. var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer);
  221. function decodeFloat(x, y, z, w) {
  222. UINT8_VIEW[0] = Math.floor(w);
  223. UINT8_VIEW[1] = Math.floor(z);
  224. UINT8_VIEW[2] = Math.floor(y);
  225. UINT8_VIEW[3] = Math.floor(x);
  226. return FLOAT_VIEW[0]
  227. }
  228. function componentToHex(c) {
  229. var hex = c.toString(16);
  230. return hex.length == 1 ? "0" + hex : hex;
  231. }
  232. function rgbToHex(r, g, b) {
  233. return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
  234. }
  235. function hexToRgb(hex) {
  236. var r = hex >> 16;
  237. var g = (hex & 0x00FF00) >> 8;
  238. var b = hex & 0x0000FF;
  239. if (r > 0) r--;
  240. if (g > 0) g--;
  241. if (b > 0) b--;
  242. return [r, g, b];
  243. }
  244. self.particles = [];
  245. self.deadParticles = [];
  246. self.particlesAvailableSlot = [];
  247. // create a container for particles
  248. self.particleUpdate = false;
  249. // Shader Based Particle System
  250. self.particleShaderGeo = new THREE.BufferGeometry();
  251. // new hyper compressed attributes
  252. self.particleVertices = new Float32Array(self.PARTICLE_COUNT * 3); // position
  253. self.particlePositionsStartTime = new Float32Array(self.PARTICLE_COUNT * 4); // position
  254. self.particleVelColSizeLife = new Float32Array(self.PARTICLE_COUNT * 4);
  255. for (var i = 0; i < self.PARTICLE_COUNT; i++) {
  256. self.particlePositionsStartTime[i * 4 + 0] = 100; //x
  257. self.particlePositionsStartTime[i * 4 + 1] = 0; //y
  258. self.particlePositionsStartTime[i * 4 + 2] = 0.0; //z
  259. self.particlePositionsStartTime[i * 4 + 3] = 0.0; //startTime
  260. self.particleVertices[i * 3 + 0] = 0; //x
  261. self.particleVertices[i * 3 + 1] = 0; //y
  262. self.particleVertices[i * 3 + 2] = 0.0; //z
  263. self.particleVelColSizeLife[i * 4 + 0] = decodeFloat(128, 128, 0, 0); //vel
  264. self.particleVelColSizeLife[i * 4 + 1] = decodeFloat(0, 254, 0, 254); //color
  265. self.particleVelColSizeLife[i * 4 + 2] = 1.0; //size
  266. self.particleVelColSizeLife[i * 4 + 3] = 0.0; //lifespan
  267. }
  268. self.particleShaderGeo.addAttribute('position', new THREE.BufferAttribute(self.particleVertices, 3));
  269. self.particleShaderGeo.addAttribute('particlePositionsStartTime', new THREE.BufferAttribute(self.particlePositionsStartTime, 4).setDynamic(true));
  270. self.particleShaderGeo.addAttribute('particleVelColSizeLife', new THREE.BufferAttribute(self.particleVelColSizeLife, 4).setDynamic(true));
  271. self.posStart = self.particleShaderGeo.getAttribute('particlePositionsStartTime');
  272. self.velCol = self.particleShaderGeo.getAttribute('particleVelColSizeLife');
  273. self.particleShaderMat = self.GPUParticleSystem.particleShaderMat;
  274. this.init = function() {
  275. self.particleSystem = new THREE.Points(self.particleShaderGeo, self.particleShaderMat);
  276. self.particleSystem.frustumCulled = false;
  277. this.add(self.particleSystem);
  278. };
  279. var options = {},
  280. position = new THREE.Vector3(),
  281. velocity = new THREE.Vector3(),
  282. positionRandomness = 0.,
  283. velocityRandomness = 0.,
  284. color = 0xffffff,
  285. colorRandomness = 0.,
  286. turbulence = 0.,
  287. lifetime = 0.,
  288. size = 0.,
  289. sizeRandomness = 0.,
  290. smoothPosition = false,
  291. i;
  292. var maxVel = 2;
  293. var maxSource = 250;
  294. this.offset = 0;
  295. this.count = 0;
  296. this.spawnParticle = function(options) {
  297. options = options || {};
  298. // setup reasonable default values for all arguments
  299. position = options.position !== undefined ? position.copy(options.position) : position.set(0., 0., 0.);
  300. velocity = options.velocity !== undefined ? velocity.copy(options.velocity) : velocity.set(0., 0., 0.);
  301. positionRandomness = options.positionRandomness !== undefined ? options.positionRandomness : 0.0;
  302. velocityRandomness = options.velocityRandomness !== undefined ? options.velocityRandomness : 0.0;
  303. color = options.color !== undefined ? options.color : 0xffffff;
  304. colorRandomness = options.colorRandomness !== undefined ? options.colorRandomness : 1.0;
  305. turbulence = options.turbulence !== undefined ? options.turbulence : 1.0;
  306. lifetime = options.lifetime !== undefined ? options.lifetime : 5.0;
  307. size = options.size !== undefined ? options.size : 10;
  308. sizeRandomness = options.sizeRandomness !== undefined ? options.sizeRandomness : 0.0;
  309. smoothPosition = options.smoothPosition !== undefined ? options.smoothPosition : false;
  310. if (self.DPR !== undefined) size *= self.DPR;
  311. i = self.PARTICLE_CURSOR;
  312. self.posStart.array[i * 4 + 0] = position.x + ((particleSystem.random()) * positionRandomness); // - ( velocity.x * particleSystem.random() ); //x
  313. self.posStart.array[i * 4 + 1] = position.y + ((particleSystem.random()) * positionRandomness); // - ( velocity.y * particleSystem.random() ); //y
  314. self.posStart.array[i * 4 + 2] = position.z + ((particleSystem.random()) * positionRandomness); // - ( velocity.z * particleSystem.random() ); //z
  315. self.posStart.array[i * 4 + 3] = self.time + (particleSystem.random() * 2e-2); //startTime
  316. if (smoothPosition === true) {
  317. self.posStart.array[i * 4 + 0] += -(velocity.x * particleSystem.random()); //x
  318. self.posStart.array[i * 4 + 1] += -(velocity.y * particleSystem.random()); //y
  319. self.posStart.array[i * 4 + 2] += -(velocity.z * particleSystem.random()); //z
  320. }
  321. var velX = velocity.x + (particleSystem.random()) * velocityRandomness;
  322. var velY = velocity.y + (particleSystem.random()) * velocityRandomness;
  323. var velZ = velocity.z + (particleSystem.random()) * velocityRandomness;
  324. // convert turbulence rating to something we can pack into a vec4
  325. var turbulence = Math.floor(turbulence * 254);
  326. // clamp our value to between 0. and 1.
  327. velX = Math.floor(maxSource * ((velX - -maxVel) / (maxVel - -maxVel)));
  328. velY = Math.floor(maxSource * ((velY - -maxVel) / (maxVel - -maxVel)));
  329. velZ = Math.floor(maxSource * ((velZ - -maxVel) / (maxVel - -maxVel)));
  330. self.velCol.array[i * 4 + 0] = decodeFloat(velX, velY, velZ, turbulence); //vel
  331. var rgb = hexToRgb(color);
  332. for (var c = 0; c < rgb.length; c++) {
  333. rgb[c] = Math.floor(rgb[c] + ((particleSystem.random()) * colorRandomness) * 254);
  334. if (rgb[c] > 254) rgb[c] = 254;
  335. if (rgb[c] < 0) rgb[c] = 0;
  336. }
  337. self.velCol.array[i * 4 + 1] = decodeFloat(rgb[0], rgb[1], rgb[2], 254); //color
  338. self.velCol.array[i * 4 + 2] = size + (particleSystem.random()) * sizeRandomness; //size
  339. self.velCol.array[i * 4 + 3] = lifetime; //lifespan
  340. if (this.offset == 0) {
  341. this.offset = self.PARTICLE_CURSOR;
  342. }
  343. self.count++;
  344. self.PARTICLE_CURSOR++;
  345. if (self.PARTICLE_CURSOR >= self.PARTICLE_COUNT) {
  346. self.PARTICLE_CURSOR = 0;
  347. }
  348. self.particleUpdate = true;
  349. };
  350. this.update = function(time) {
  351. self.time = time;
  352. self.particleShaderMat.uniforms['uTime'].value = time;
  353. this.geometryUpdate();
  354. };
  355. this.geometryUpdate = function() {
  356. if (self.particleUpdate == true) {
  357. self.particleUpdate = false;
  358. // if we can get away with a partial buffer update, do so
  359. if (self.offset + self.count < self.PARTICLE_COUNT) {
  360. self.posStart.updateRange.offset = self.velCol.updateRange.offset = self.offset * 4;
  361. self.posStart.updateRange.count = self.velCol.updateRange.count = self.count * 4;
  362. } else {
  363. self.posStart.updateRange.offset = 0;
  364. self.posStart.updateRange.count = self.velCol.updateRange.count = (self.PARTICLE_COUNT * 4);
  365. }
  366. self.posStart.needsUpdate = true;
  367. self.velCol.needsUpdate = true;
  368. self.offset = 0;
  369. self.count = 0;
  370. }
  371. };
  372. this.init();
  373. };
  374. THREE.GPUParticleContainer.prototype = Object.create(THREE.Object3D.prototype);
  375. THREE.GPUParticleContainer.prototype.constructor = THREE.GPUParticleContainer;