babylon.particleSystem.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. module BABYLON {
  2. var randomNumber = (min: number, max: number): number => {
  3. if (min == max) {
  4. return (min);
  5. }
  6. var random = Math.random();
  7. return ((random * (max - min)) + min);
  8. }
  9. export class ParticleSystem {
  10. // Statics
  11. public static BLENDMODE_ONEONE = 0;
  12. public static BLENDMODE_STANDARD = 1;
  13. // Members
  14. public id: string;
  15. public renderingGroupId = 0;
  16. public emitter = null;
  17. public emitRate = 10;
  18. public manualEmitCount = -1;
  19. public updateSpeed = 0.01;
  20. public targetStopDuration = 0;
  21. public disposeOnStop = false;
  22. public minEmitPower = 1;
  23. public maxEmitPower = 1;
  24. public minLifeTime = 1;
  25. public maxLifeTime = 1;
  26. public minSize = 1;
  27. public maxSize = 1;
  28. public minAngularSpeed = 0;
  29. public maxAngularSpeed = 0;
  30. public particleTexture: Texture;
  31. public onDispose: () => void;
  32. public blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  33. public forceDepthWrite = false;
  34. public gravity = BABYLON.Vector3.Zero();
  35. public direction1 = new BABYLON.Vector3(0, 1.0, 0);
  36. public direction2 = new BABYLON.Vector3(0, 1.0, 0);
  37. public minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  38. public maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39. public color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40. public color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41. public colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  42. public textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43. private particles = new Array<Particle>();
  44. private _capacity: number;
  45. private _scene: Scene;
  46. private _vertexDeclaration = [3, 4, 4];
  47. private _vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  48. private _stockParticles = new Array<Particle>();
  49. private _newPartsExcess = 0;
  50. private _vertexBuffer: WebGLBuffer;
  51. private _indexBuffer: WebGLBuffer;
  52. private _vertices: Float32Array;
  53. private _effect: Effect;
  54. private _cachedDefines: string;
  55. private _scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56. private _colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57. private _scaledDirection = BABYLON.Vector3.Zero();
  58. private _scaledGravity = BABYLON.Vector3.Zero();
  59. private _currentRenderId = -1;
  60. private _alive: boolean;
  61. private _started = true;
  62. private _stopped = false;
  63. private _actualFrame = 0;
  64. private _scaledUpdateSpeed: number;
  65. constructor(public name: string, capacity: number, scene: Scene) {
  66. this.id = name;
  67. this._capacity = capacity;
  68. this._scene = scene;
  69. scene.particleSystems.push(this);
  70. // VBO
  71. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  72. var indices = [];
  73. var index = 0;
  74. for (var count = 0; count < capacity; count++) {
  75. indices.push(index);
  76. indices.push(index + 1);
  77. indices.push(index + 2);
  78. indices.push(index);
  79. indices.push(index + 2);
  80. indices.push(index + 3);
  81. index += 4;
  82. }
  83. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  84. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  85. }
  86. public getCapacity(): number {
  87. return this._capacity;
  88. }
  89. public isAlive(): boolean {
  90. return this._alive;
  91. }
  92. public start(): void {
  93. this._started = true;
  94. this._stopped = false;
  95. this._actualFrame = 0;
  96. }
  97. public stop(): void {
  98. this._stopped = true;
  99. }
  100. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  101. var offset = index * 11;
  102. this._vertices[offset] = particle.position.x;
  103. this._vertices[offset + 1] = particle.position.y;
  104. this._vertices[offset + 2] = particle.position.z;
  105. this._vertices[offset + 3] = particle.color.r;
  106. this._vertices[offset + 4] = particle.color.g;
  107. this._vertices[offset + 5] = particle.color.b;
  108. this._vertices[offset + 6] = particle.color.a;
  109. this._vertices[offset + 7] = particle.angle;
  110. this._vertices[offset + 8] = particle.size;
  111. this._vertices[offset + 9] = offsetX;
  112. this._vertices[offset + 10] = offsetY;
  113. }
  114. private _update(newParticles: number): void {
  115. // Update current
  116. this._alive = this.particles.length > 0;
  117. for (var index = 0; index < this.particles.length; index++) {
  118. var particle = this.particles[index];
  119. particle.age += this._scaledUpdateSpeed;
  120. if (particle.age >= particle.lifeTime) {
  121. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  122. index--;
  123. continue;
  124. }
  125. else {
  126. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  127. particle.color.addInPlace(this._scaledColorStep);
  128. if (particle.color.a < 0)
  129. particle.color.a = 0;
  130. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  131. particle.position.addInPlace(this._scaledDirection);
  132. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  133. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  134. particle.direction.addInPlace(this._scaledGravity);
  135. }
  136. }
  137. // Add new ones
  138. var worldMatrix;
  139. if (this.emitter.position) {
  140. worldMatrix = this.emitter.getWorldMatrix();
  141. } else {
  142. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  143. }
  144. for (index = 0; index < newParticles; index++) {
  145. if (this.particles.length == this._capacity) {
  146. break;
  147. }
  148. if (this._stockParticles.length !== 0) {
  149. particle = this._stockParticles.pop();
  150. particle.age = 0;
  151. } else {
  152. particle = new BABYLON.Particle();
  153. }
  154. this.particles.push(particle);
  155. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  156. var randX = randomNumber(this.direction1.x, this.direction2.x);
  157. var randY = randomNumber(this.direction1.y, this.direction2.y);
  158. var randZ = randomNumber(this.direction1.z, this.direction2.z);
  159. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, particle.direction);
  160. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  161. particle.size = randomNumber(this.minSize, this.maxSize);
  162. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  163. randX = randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  164. randY = randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  165. randZ = randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  166. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, particle.position);
  167. var step = randomNumber(0, 1.0);
  168. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  169. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  170. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  171. }
  172. }
  173. private _getEffect(): Effect {
  174. var defines = [];
  175. if (this._scene.clipPlane) {
  176. defines.push("#define CLIPPLANE");
  177. }
  178. // Effect
  179. var join = defines.join("\n");
  180. if (this._cachedDefines != join) {
  181. this._cachedDefines = join;
  182. this._effect = this._scene.getEngine().createEffect("particles",
  183. ["position", "color", "options"],
  184. ["invView", "view", "projection", "vClipPlane", "textureMask"],
  185. ["diffuseSampler"], join);
  186. }
  187. return this._effect;
  188. }
  189. public animate(): void {
  190. if (!this._started)
  191. return;
  192. var effect = this._getEffect();
  193. // Check
  194. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  195. return;
  196. if (this._currentRenderId === this._scene.getRenderId()) {
  197. return;
  198. }
  199. this._currentRenderId = this._scene.getRenderId();
  200. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  201. // determine the number of particles we need to create
  202. var emitCout;
  203. if (this.manualEmitCount > -1) {
  204. emitCout = this.manualEmitCount;
  205. this.manualEmitCount = 0;
  206. } else {
  207. emitCout = this.emitRate;
  208. }
  209. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  210. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  211. if (this._newPartsExcess > 1.0) {
  212. newParticles += this._newPartsExcess >> 0;
  213. this._newPartsExcess -= this._newPartsExcess >> 0;
  214. }
  215. this._alive = false;
  216. if (!this._stopped) {
  217. this._actualFrame += this._scaledUpdateSpeed;
  218. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  219. this.stop();
  220. } else {
  221. newParticles = 0;
  222. }
  223. this._update(newParticles);
  224. // Stopped?
  225. if (this._stopped) {
  226. if (!this._alive) {
  227. this._started = false;
  228. if (this.disposeOnStop) {
  229. this._scene._toBeDisposed.push(this);
  230. }
  231. }
  232. }
  233. // Update VBO
  234. var offset = 0;
  235. for (var index = 0; index < this.particles.length; index++) {
  236. var particle = this.particles[index];
  237. this._appendParticleVertex(offset++, particle, 0, 0);
  238. this._appendParticleVertex(offset++, particle, 1, 0);
  239. this._appendParticleVertex(offset++, particle, 1, 1);
  240. this._appendParticleVertex(offset++, particle, 0, 1);
  241. }
  242. var engine = this._scene.getEngine();
  243. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  244. }
  245. public render(): number {
  246. var effect = this._getEffect();
  247. // Check
  248. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  249. return 0;
  250. var engine = this._scene.getEngine();
  251. // Render
  252. engine.enableEffect(effect);
  253. var viewMatrix = this._scene.getViewMatrix();
  254. effect.setTexture("diffuseSampler", this.particleTexture);
  255. effect.setMatrix("view", viewMatrix);
  256. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  257. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  258. if (this._scene.clipPlane) {
  259. var clipPlane = this._scene.clipPlane;
  260. var invView = viewMatrix.clone();
  261. invView.invert();
  262. effect.setMatrix("invView", invView);
  263. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  264. }
  265. // VBOs
  266. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  267. // Draw order
  268. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  269. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  270. } else {
  271. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  272. }
  273. if (this.forceDepthWrite) {
  274. engine.setDepthWrite(true);
  275. }
  276. engine.draw(true, 0, this.particles.length * 6);
  277. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  278. return this.particles.length;
  279. }
  280. public dispose(): void {
  281. if (this._vertexBuffer) {
  282. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  283. this._vertexBuffer = null;
  284. }
  285. if (this._indexBuffer) {
  286. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  287. this._indexBuffer = null;
  288. }
  289. if (this.particleTexture) {
  290. this.particleTexture.dispose();
  291. this.particleTexture = null;
  292. }
  293. // Remove from scene
  294. var index = this._scene.particleSystems.indexOf(this);
  295. this._scene.particleSystems.splice(index, 1);
  296. // Callback
  297. if (this.onDispose) {
  298. this.onDispose();
  299. }
  300. }
  301. // Clone
  302. public clone(name: string, newEmitter: any): ParticleSystem {
  303. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  304. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  305. if (newEmitter === undefined) {
  306. newEmitter = this.emitter;
  307. }
  308. result.emitter = newEmitter;
  309. if (this.particleTexture) {
  310. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  311. }
  312. result.start();
  313. return result;
  314. }
  315. }
  316. }