babylon.particleSystem.ts 16 KB

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