babylon.particleSystem.ts 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. module BABYLON {
  2. /**
  3. * Interface representing a particle system in Babylon.
  4. * This groups the common functionalities that needs to be implemented in order to create a particle system.
  5. * A particle system represents a way to manage particles (@see Particle) from their emission to their animation and rendering.
  6. */
  7. export interface IParticleSystem {
  8. /**
  9. * The id of the Particle system.
  10. */
  11. id: string;
  12. /**
  13. * The name of the Particle system.
  14. */
  15. name: string;
  16. /**
  17. * The emitter represents the Mesh or position we are attaching the particle system to.
  18. */
  19. emitter: Nullable<AbstractMesh | Vector3>;
  20. /**
  21. * The rendering group used by the Particle system to chose when to render.
  22. */
  23. renderingGroupId: number;
  24. /**
  25. * The layer mask we are rendering the particles through.
  26. */
  27. layerMask: number;
  28. /**
  29. * Gets if the particle system has been started.
  30. * @return true if the system has been started, otherwise false.
  31. */
  32. isStarted(): boolean;
  33. /**
  34. * Animates the particle system for this frame.
  35. */
  36. animate(): void;
  37. /**
  38. * Renders the particle system in its current state.
  39. * @returns the current number of particles.
  40. */
  41. render(): number;
  42. /**
  43. * Dispose the particle system and frees its associated resources.
  44. */
  45. dispose(): void;
  46. /**
  47. * Clones the particle system.
  48. * @param name The name of the cloned object
  49. * @param newEmitter The new emitter to use
  50. * @returns the cloned particle system
  51. */
  52. clone(name: string, newEmitter: any): Nullable<IParticleSystem>;
  53. /**
  54. * Serializes the particle system to a JSON object.
  55. * @returns the JSON object
  56. */
  57. serialize(): any;
  58. /**
  59. * Rebuild the particle system
  60. */
  61. rebuild(): void
  62. }
  63. /**
  64. * This represents a particle system in Babylon.
  65. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  66. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  67. * @example https://doc.babylonjs.com/babylon101/particles
  68. */
  69. export class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem {
  70. /**
  71. * Source color is added to the destination color without alpha affecting the result.
  72. */
  73. public static BLENDMODE_ONEONE = 0;
  74. /**
  75. * Blend current color and particle color using particle’s alpha.
  76. */
  77. public static BLENDMODE_STANDARD = 1;
  78. /**
  79. * List of animations used by the particle system.
  80. */
  81. public animations: Animation[] = [];
  82. /**
  83. * The id of the Particle system.
  84. */
  85. public id: string;
  86. /**
  87. * The friendly name of the Particle system.
  88. */
  89. public name: string;
  90. /**
  91. * The rendering group used by the Particle system to chose when to render.
  92. */
  93. public renderingGroupId = 0;
  94. /**
  95. * The emitter represents the Mesh or position we are attaching the particle system to.
  96. */
  97. public emitter: Nullable<AbstractMesh | Vector3> = null;
  98. /**
  99. * The maximum number of particles to emit per frame
  100. */
  101. public emitRate = 10;
  102. /**
  103. * If you want to launch only a few particles at once, that can be done, as well.
  104. */
  105. public manualEmitCount = -1;
  106. /**
  107. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  108. */
  109. public updateSpeed = 0.01;
  110. /**
  111. * The amount of time the particle system is running (depends of the overall speed above).
  112. */
  113. public targetStopDuration = 0;
  114. /**
  115. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  116. */
  117. public disposeOnStop = false;
  118. /**
  119. * Minimum power of emitting particles.
  120. */
  121. public minEmitPower = 1;
  122. /**
  123. * Maximum power of emitting particles.
  124. */
  125. public maxEmitPower = 1;
  126. /**
  127. * Minimum life time of emitting particles.
  128. */
  129. public minLifeTime = 1;
  130. /**
  131. * Maximum life time of emitting particles.
  132. */
  133. public maxLifeTime = 1;
  134. /**
  135. * Minimum Size of emitting particles.
  136. */
  137. public minSize = 1;
  138. /**
  139. * Maximum Size of emitting particles.
  140. */
  141. public maxSize = 1;
  142. /**
  143. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  144. */
  145. public minAngularSpeed = 0;
  146. /**
  147. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  148. */
  149. public maxAngularSpeed = 0;
  150. /**
  151. * The texture used to render each particle. (this can be a spritesheet)
  152. */
  153. public particleTexture: Nullable<Texture>;
  154. /**
  155. * The layer mask we are rendering the particles through.
  156. */
  157. public layerMask: number = 0x0FFFFFFF;
  158. /**
  159. * This can help using your own shader to render the particle system.
  160. * The according effect will be created
  161. */
  162. public customShader: any = null;
  163. /**
  164. * By default particle system starts as soon as they are created. This prevents the
  165. * automatic start to happen and let you decide when to start emitting particles.
  166. */
  167. public preventAutoStart: boolean = false;
  168. /**
  169. * This function can be defined to provide custom update for active particles.
  170. * This function will be called instead of regular update (age, position, color, etc.).
  171. * Do not forget that this function will be called on every frame so try to keep it simple and fast :)
  172. */
  173. public updateFunction: (particles: Particle[]) => void;
  174. /**
  175. * Callback triggered when the particle animation is ending.
  176. */
  177. public onAnimationEnd: Nullable<() => void> = null;
  178. /**
  179. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  180. */
  181. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  182. /**
  183. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  184. * to override the particles.
  185. */
  186. public forceDepthWrite = false;
  187. /**
  188. * You can use gravity if you want to give an orientation to your particles.
  189. */
  190. public gravity = Vector3.Zero();
  191. /**
  192. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  193. */
  194. public direction1 = new Vector3(0, 1.0, 0);
  195. /**
  196. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  197. */
  198. public direction2 = new Vector3(0, 1.0, 0);
  199. /**
  200. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  201. */
  202. public minEmitBox = new Vector3(-0.5, -0.5, -0.5);
  203. /**
  204. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  205. */
  206. public maxEmitBox = new Vector3(0.5, 0.5, 0.5);
  207. /**
  208. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  209. */
  210. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  211. /**
  212. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  213. */
  214. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  215. /**
  216. * Color the particle will have at the end of its lifetime.
  217. */
  218. public colorDead = new Color4(0, 0, 0, 1.0);
  219. /**
  220. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  221. */
  222. public textureMask = new Color4(1.0, 1.0, 1.0, 1.0);
  223. /**
  224. * The particle emitter type defines the emitter used by the particle system.
  225. * It can be for example box, sphere, or cone...
  226. */
  227. public particleEmitterType: IParticleEmitterType;
  228. /**
  229. * This function can be defined to specify initial direction for every new particle.
  230. * It by default use the emitterType defined function.
  231. */
  232. public startDirectionFunction: (emitPower: number, worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void;
  233. /**
  234. * This function can be defined to specify initial position for every new particle.
  235. * It by default use the emitterType defined function.
  236. */
  237. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void;
  238. /**
  239. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  240. */
  241. public spriteCellLoop = true;
  242. /**
  243. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  244. */
  245. public spriteCellChangeSpeed = 0;
  246. /**
  247. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  248. */
  249. public startSpriteCellID = 0;
  250. /**
  251. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  252. */
  253. public endSpriteCellID = 0;
  254. /**
  255. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  256. */
  257. public spriteCellWidth = 0;
  258. /**
  259. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  260. */
  261. public spriteCellHeight = 0;
  262. /**
  263. * An event triggered when the system is disposed.
  264. */
  265. public onDisposeObservable = new Observable<ParticleSystem>();
  266. private _onDisposeObserver: Nullable<Observer<ParticleSystem>>;
  267. /**
  268. * Sets a callback that will be triggered when the system is disposed.
  269. */
  270. public set onDispose(callback: () => void) {
  271. if (this._onDisposeObserver) {
  272. this.onDisposeObservable.remove(this._onDisposeObserver);
  273. }
  274. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  275. }
  276. /**
  277. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  278. */
  279. public get isAnimationSheetEnabled(): Boolean {
  280. return this._isAnimationSheetEnabled;
  281. }
  282. private _particles = new Array<Particle>();
  283. private _epsilon: number;
  284. private _capacity: number;
  285. private _scene: Scene;
  286. private _stockParticles = new Array<Particle>();
  287. private _newPartsExcess = 0;
  288. private _vertexData: Float32Array;
  289. private _vertexBuffer: Nullable<Buffer>;
  290. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  291. private _indexBuffer: Nullable<WebGLBuffer>;
  292. private _effect: Effect;
  293. private _customEffect: Nullable<Effect>;
  294. private _cachedDefines: string;
  295. private _scaledColorStep = new Color4(0, 0, 0, 0);
  296. private _colorDiff = new Color4(0, 0, 0, 0);
  297. private _scaledDirection = Vector3.Zero();
  298. private _scaledGravity = Vector3.Zero();
  299. private _currentRenderId = -1;
  300. private _alive: boolean;
  301. private _started = false;
  302. private _stopped = false;
  303. private _actualFrame = 0;
  304. private _scaledUpdateSpeed: number;
  305. private _vertexBufferSize = 11;
  306. private _isAnimationSheetEnabled: boolean;
  307. /**
  308. * Instantiates a particle system.
  309. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  310. * @param name The name of the particle system
  311. * @param capacity The max number of particles alive at the same time
  312. * @param scene The scene the particle system belongs to
  313. * @param customEffect a custom effect used to change the way particles are rendered by default
  314. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  315. * @param epsilon Offset used to render the particles
  316. */
  317. constructor(name: string, capacity: number, scene: Scene, customEffect: Nullable<Effect> = null, isAnimationSheetEnabled: boolean = false, epsilon: number = 0.01) {
  318. this.id = name;
  319. this.name = name;
  320. this._capacity = capacity;
  321. this._epsilon = epsilon;
  322. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  323. if (isAnimationSheetEnabled) {
  324. this._vertexBufferSize = 12;
  325. }
  326. this._scene = scene || Engine.LastCreatedScene;
  327. this._customEffect = customEffect;
  328. scene.particleSystems.push(this);
  329. this._createIndexBuffer();
  330. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  331. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  332. this._vertexBuffer = new Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  333. var positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 3);
  334. var colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, 3, 4);
  335. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  336. if (this._isAnimationSheetEnabled) {
  337. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  338. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  339. }
  340. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  341. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  342. this._vertexBuffers["options"] = options;
  343. // Default behaviors
  344. this.particleEmitterType = new BoxParticleEmitter(this);
  345. this.updateFunction = (particles: Particle[]): void => {
  346. for (var index = 0; index < particles.length; index++) {
  347. var particle = particles[index];
  348. particle.age += this._scaledUpdateSpeed;
  349. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  350. this.recycleParticle(particle);
  351. index--;
  352. continue;
  353. }
  354. else {
  355. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  356. particle.color.addInPlace(this._scaledColorStep);
  357. if (particle.color.a < 0)
  358. particle.color.a = 0;
  359. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  360. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  361. particle.position.addInPlace(this._scaledDirection);
  362. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  363. particle.direction.addInPlace(this._scaledGravity);
  364. if (this._isAnimationSheetEnabled) {
  365. particle.updateCellIndex(this._scaledUpdateSpeed);
  366. }
  367. }
  368. }
  369. }
  370. }
  371. private _createIndexBuffer() {
  372. var indices = [];
  373. var index = 0;
  374. for (var count = 0; count < this._capacity; count++) {
  375. indices.push(index);
  376. indices.push(index + 1);
  377. indices.push(index + 2);
  378. indices.push(index);
  379. indices.push(index + 2);
  380. indices.push(index + 3);
  381. index += 4;
  382. }
  383. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  384. }
  385. /**
  386. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  387. * Its lifetime will start back at 0.
  388. * @param particle The particle to recycle
  389. */
  390. public recycleParticle(particle: Particle): void {
  391. var lastParticle = <Particle>this._particles.pop();
  392. if (lastParticle !== particle) {
  393. lastParticle.copyTo(particle);
  394. this._stockParticles.push(lastParticle);
  395. }
  396. }
  397. /**
  398. * Gets the maximum number of particles active at the same time.
  399. * @returns The max number of active particles.
  400. */
  401. public getCapacity(): number {
  402. return this._capacity;
  403. }
  404. /**
  405. * Gets Wether there are still active particles in the system.
  406. * @returns True if it is alive, otherwise false.
  407. */
  408. public isAlive(): boolean {
  409. return this._alive;
  410. }
  411. /**
  412. * Gets Wether the system has been started.
  413. * @returns True if it has been started, otherwise false.
  414. */
  415. public isStarted(): boolean {
  416. return this._started;
  417. }
  418. /**
  419. * Starts the particle system and begins to emit.
  420. */
  421. public start(): void {
  422. this._started = true;
  423. this._stopped = false;
  424. this._actualFrame = 0;
  425. }
  426. /**
  427. * Stops the particle system.
  428. */
  429. public stop(): void {
  430. this._stopped = true;
  431. }
  432. /**
  433. * Remove all active particles
  434. */
  435. public reset(): void {
  436. this._stockParticles = [];
  437. this._particles = [];
  438. }
  439. /**
  440. * @ignore (for internal use only)
  441. */
  442. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  443. var offset = index * this._vertexBufferSize;
  444. this._vertexData[offset] = particle.position.x;
  445. this._vertexData[offset + 1] = particle.position.y;
  446. this._vertexData[offset + 2] = particle.position.z;
  447. this._vertexData[offset + 3] = particle.color.r;
  448. this._vertexData[offset + 4] = particle.color.g;
  449. this._vertexData[offset + 5] = particle.color.b;
  450. this._vertexData[offset + 6] = particle.color.a;
  451. this._vertexData[offset + 7] = particle.angle;
  452. this._vertexData[offset + 8] = particle.size;
  453. this._vertexData[offset + 9] = offsetX;
  454. this._vertexData[offset + 10] = offsetY;
  455. }
  456. /**
  457. * @ignore (for internal use only)
  458. */
  459. public _appendParticleVertexWithAnimation(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  460. if (offsetX === 0)
  461. offsetX = this._epsilon;
  462. else if (offsetX === 1)
  463. offsetX = 1 - this._epsilon;
  464. if (offsetY === 0)
  465. offsetY = this._epsilon;
  466. else if (offsetY === 1)
  467. offsetY = 1 - this._epsilon;
  468. var offset = index * this._vertexBufferSize;
  469. this._vertexData[offset] = particle.position.x;
  470. this._vertexData[offset + 1] = particle.position.y;
  471. this._vertexData[offset + 2] = particle.position.z;
  472. this._vertexData[offset + 3] = particle.color.r;
  473. this._vertexData[offset + 4] = particle.color.g;
  474. this._vertexData[offset + 5] = particle.color.b;
  475. this._vertexData[offset + 6] = particle.color.a;
  476. this._vertexData[offset + 7] = particle.angle;
  477. this._vertexData[offset + 8] = particle.size;
  478. this._vertexData[offset + 9] = offsetX;
  479. this._vertexData[offset + 10] = offsetY;
  480. this._vertexData[offset + 11] = particle.cellIndex;
  481. }
  482. private _update(newParticles: number): void {
  483. // Update current
  484. this._alive = this._particles.length > 0;
  485. this.updateFunction(this._particles);
  486. // Add new ones
  487. var worldMatrix;
  488. if ((<AbstractMesh>this.emitter).position) {
  489. var emitterMesh = (<AbstractMesh>this.emitter);
  490. worldMatrix = emitterMesh.getWorldMatrix();
  491. } else {
  492. var emitterPosition = (<Vector3>this.emitter);
  493. worldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  494. }
  495. var particle: Particle;
  496. for (var index = 0; index < newParticles; index++) {
  497. if (this._particles.length === this._capacity) {
  498. break;
  499. }
  500. if (this._stockParticles.length !== 0) {
  501. particle = <Particle>this._stockParticles.pop();
  502. particle.age = 0;
  503. particle.cellIndex = this.startSpriteCellID;
  504. } else {
  505. particle = new Particle(this);
  506. }
  507. this._particles.push(particle);
  508. var emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  509. if (this.startPositionFunction) {
  510. this.startPositionFunction(worldMatrix, particle.position, particle);
  511. }
  512. else {
  513. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  514. }
  515. if (this.startDirectionFunction) {
  516. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  517. }
  518. else {
  519. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  520. }
  521. particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  522. particle.size = Scalar.RandomRange(this.minSize, this.maxSize);
  523. particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  524. var step = Scalar.RandomRange(0, 1.0);
  525. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  526. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  527. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  528. }
  529. }
  530. private _getEffect(): Effect {
  531. if (this._customEffect) {
  532. return this._customEffect;
  533. };
  534. var defines = [];
  535. if (this._scene.clipPlane) {
  536. defines.push("#define CLIPPLANE");
  537. }
  538. if (this._isAnimationSheetEnabled) {
  539. defines.push("#define ANIMATESHEET");
  540. }
  541. // Effect
  542. var join = defines.join("\n");
  543. if (this._cachedDefines !== join) {
  544. this._cachedDefines = join;
  545. var attributesNamesOrOptions: any;
  546. var effectCreationOption: any;
  547. if (this._isAnimationSheetEnabled) {
  548. attributesNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "options", "cellIndex"];
  549. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  550. }
  551. else {
  552. attributesNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "options"];
  553. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"]
  554. }
  555. this._effect = this._scene.getEngine().createEffect(
  556. "particles",
  557. attributesNamesOrOptions,
  558. effectCreationOption,
  559. ["diffuseSampler"], join);
  560. }
  561. return this._effect;
  562. }
  563. /**
  564. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  565. */
  566. public animate(): void {
  567. if (!this._started)
  568. return;
  569. var effect = this._getEffect();
  570. // Check
  571. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  572. return;
  573. if (this._currentRenderId === this._scene.getRenderId()) {
  574. return;
  575. }
  576. this._currentRenderId = this._scene.getRenderId();
  577. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  578. // determine the number of particles we need to create
  579. var newParticles;
  580. if (this.manualEmitCount > -1) {
  581. newParticles = this.manualEmitCount;
  582. this._newPartsExcess = 0;
  583. this.manualEmitCount = 0;
  584. } else {
  585. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  586. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  587. }
  588. if (this._newPartsExcess > 1.0) {
  589. newParticles += this._newPartsExcess >> 0;
  590. this._newPartsExcess -= this._newPartsExcess >> 0;
  591. }
  592. this._alive = false;
  593. if (!this._stopped) {
  594. this._actualFrame += this._scaledUpdateSpeed;
  595. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  596. this.stop();
  597. } else {
  598. newParticles = 0;
  599. }
  600. this._update(newParticles);
  601. // Stopped?
  602. if (this._stopped) {
  603. if (!this._alive) {
  604. this._started = false;
  605. if (this.onAnimationEnd) {
  606. this.onAnimationEnd();
  607. }
  608. if (this.disposeOnStop) {
  609. this._scene._toBeDisposed.push(this);
  610. }
  611. }
  612. }
  613. // Animation sheet
  614. if (this._isAnimationSheetEnabled) {
  615. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  616. }
  617. else {
  618. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  619. }
  620. // Update VBO
  621. var offset = 0;
  622. for (var index = 0; index < this._particles.length; index++) {
  623. var particle = this._particles[index];
  624. this._appendParticleVertexes(offset, particle);
  625. offset += 4;
  626. }
  627. if (this._vertexBuffer) {
  628. this._vertexBuffer.update(this._vertexData);
  629. }
  630. }
  631. private _appendParticleVertexes: Nullable<(offset: number, particle: Particle) => void> = null;
  632. private _appenedParticleVertexesWithSheet(offset: number, particle: Particle) {
  633. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  634. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  635. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  636. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  637. }
  638. private _appenedParticleVertexesNoSheet(offset: number, particle: Particle) {
  639. this._appendParticleVertex(offset++, particle, 0, 0);
  640. this._appendParticleVertex(offset++, particle, 1, 0);
  641. this._appendParticleVertex(offset++, particle, 1, 1);
  642. this._appendParticleVertex(offset++, particle, 0, 1);
  643. }
  644. /**
  645. * Rebuilds the particle system.
  646. */
  647. public rebuild(): void {
  648. this._createIndexBuffer();
  649. if (this._vertexBuffer) {
  650. this._vertexBuffer._rebuild();
  651. }
  652. }
  653. /**
  654. * Renders the particle system in its current state.
  655. * @returns the current number of particles.
  656. */
  657. public render(): number {
  658. var effect = this._getEffect();
  659. // Check
  660. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  661. return 0;
  662. var engine = this._scene.getEngine();
  663. // Render
  664. engine.enableEffect(effect);
  665. engine.setState(false);
  666. var viewMatrix = this._scene.getViewMatrix();
  667. effect.setTexture("diffuseSampler", this.particleTexture);
  668. effect.setMatrix("view", viewMatrix);
  669. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  670. if (this._isAnimationSheetEnabled) {
  671. var baseSize = this.particleTexture.getBaseSize();
  672. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  673. }
  674. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  675. if (this._scene.clipPlane) {
  676. var clipPlane = this._scene.clipPlane;
  677. var invView = viewMatrix.clone();
  678. invView.invert();
  679. effect.setMatrix("invView", invView);
  680. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  681. }
  682. // VBOs
  683. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  684. // Draw order
  685. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  686. engine.setAlphaMode(Engine.ALPHA_ONEONE);
  687. } else {
  688. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  689. }
  690. if (this.forceDepthWrite) {
  691. engine.setDepthWrite(true);
  692. }
  693. engine.drawElementsType(Material.TriangleFillMode, 0, this._particles.length * 6);
  694. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  695. return this._particles.length;
  696. }
  697. /**
  698. * Disposes the particle system and free the associated resources.
  699. */
  700. public dispose(): void {
  701. if (this._vertexBuffer) {
  702. this._vertexBuffer.dispose();
  703. this._vertexBuffer = null;
  704. }
  705. if (this._indexBuffer) {
  706. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  707. this._indexBuffer = null;
  708. }
  709. if (this.particleTexture) {
  710. this.particleTexture.dispose();
  711. this.particleTexture = null;
  712. }
  713. // Remove from scene
  714. var index = this._scene.particleSystems.indexOf(this);
  715. if (index > -1) {
  716. this._scene.particleSystems.splice(index, 1);
  717. }
  718. // Callback
  719. this.onDisposeObservable.notifyObservers(this);
  720. this.onDisposeObservable.clear();
  721. }
  722. /**
  723. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  724. * @param radius The radius of the sphere to emit from
  725. * @returns the emitter
  726. */
  727. public createSphereEmitter(radius = 1): SphereParticleEmitter {
  728. var particleEmitter = new SphereParticleEmitter(radius);
  729. this.particleEmitterType = particleEmitter;
  730. return particleEmitter;
  731. }
  732. /**
  733. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  734. * @param radius The radius of the sphere to emit from
  735. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  736. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  737. * @returns the emitter
  738. */
  739. public createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)): SphereDirectedParticleEmitter {
  740. var particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2)
  741. this.particleEmitterType = particleEmitter;
  742. return particleEmitter;
  743. }
  744. /**
  745. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  746. * @param radius The radius of the cone to emit from
  747. * @param angle The base angle of the cone
  748. * @returns the emitter
  749. */
  750. public createConeEmitter(radius = 1, angle = Math.PI / 4): ConeParticleEmitter {
  751. var particleEmitter = new ConeParticleEmitter(radius, angle);
  752. this.particleEmitterType = particleEmitter;
  753. return particleEmitter;
  754. }
  755. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  756. /**
  757. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  758. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  759. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  760. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  761. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  762. * @returns the emitter
  763. */
  764. public createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter {
  765. var particleEmitter = new BoxParticleEmitter(this);
  766. this.direction1 = direction1;
  767. this.direction2 = direction2;
  768. this.minEmitBox = minEmitBox;
  769. this.maxEmitBox = maxEmitBox;
  770. this.particleEmitterType = particleEmitter;
  771. return particleEmitter;
  772. }
  773. /**
  774. * Clones the particle system.
  775. * @param name The name of the cloned object
  776. * @param newEmitter The new emitter to use
  777. * @returns the cloned particle system
  778. */
  779. public clone(name: string, newEmitter: any): ParticleSystem {
  780. var custom: Nullable<Effect> = null;
  781. var program: any = null;
  782. if (this.customShader != null) {
  783. program = this.customShader;
  784. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  785. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  786. }
  787. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  788. result.customShader = program;
  789. Tools.DeepCopy(this, result, ["particles", "customShader"]);
  790. if (newEmitter === undefined) {
  791. newEmitter = this.emitter;
  792. }
  793. result.emitter = newEmitter;
  794. if (this.particleTexture) {
  795. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  796. }
  797. if (!this.preventAutoStart) {
  798. result.start();
  799. }
  800. return result;
  801. }
  802. /**
  803. * Serializes the particle system to a JSON object.
  804. * @returns the JSON object
  805. */
  806. public serialize(): any {
  807. var serializationObject: any = {};
  808. serializationObject.name = this.name;
  809. serializationObject.id = this.id;
  810. // Emitter
  811. if ((<AbstractMesh>this.emitter).position) {
  812. var emitterMesh = (<AbstractMesh>this.emitter);
  813. serializationObject.emitterId = emitterMesh.id;
  814. } else {
  815. var emitterPosition = (<Vector3>this.emitter);
  816. serializationObject.emitter = emitterPosition.asArray();
  817. }
  818. serializationObject.capacity = this.getCapacity();
  819. if (this.particleTexture) {
  820. serializationObject.textureName = this.particleTexture.name;
  821. }
  822. // Animations
  823. Animation.AppendSerializedAnimations(this, serializationObject);
  824. // Particle system
  825. serializationObject.minAngularSpeed = this.minAngularSpeed;
  826. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  827. serializationObject.minSize = this.minSize;
  828. serializationObject.maxSize = this.maxSize;
  829. serializationObject.minEmitPower = this.minEmitPower;
  830. serializationObject.maxEmitPower = this.maxEmitPower;
  831. serializationObject.minLifeTime = this.minLifeTime;
  832. serializationObject.maxLifeTime = this.maxLifeTime;
  833. serializationObject.emitRate = this.emitRate;
  834. serializationObject.minEmitBox = this.minEmitBox.asArray();
  835. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  836. serializationObject.gravity = this.gravity.asArray();
  837. serializationObject.direction1 = this.direction1.asArray();
  838. serializationObject.direction2 = this.direction2.asArray();
  839. serializationObject.color1 = this.color1.asArray();
  840. serializationObject.color2 = this.color2.asArray();
  841. serializationObject.colorDead = this.colorDead.asArray();
  842. serializationObject.updateSpeed = this.updateSpeed;
  843. serializationObject.targetStopDuration = this.targetStopDuration;
  844. serializationObject.textureMask = this.textureMask.asArray();
  845. serializationObject.blendMode = this.blendMode;
  846. serializationObject.customShader = this.customShader;
  847. serializationObject.preventAutoStart = this.preventAutoStart;
  848. serializationObject.startSpriteCellID = this.startSpriteCellID;
  849. serializationObject.endSpriteCellID = this.endSpriteCellID;
  850. serializationObject.spriteCellLoop = this.spriteCellLoop;
  851. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  852. serializationObject.spriteCellWidth = this.spriteCellWidth;
  853. serializationObject.spriteCellHeight = this.spriteCellHeight;
  854. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  855. return serializationObject;
  856. }
  857. /**
  858. * Parses a JSON object to create a particle system.
  859. * @param parsedParticleSystem The JSON object to parse
  860. * @param scene The scene to create the particle system in
  861. * @param rootUrl The root url to use to load external dependencies like texture
  862. * @returns the Parsed particle system
  863. */
  864. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem {
  865. var name = parsedParticleSystem.name;
  866. var custom: Nullable<Effect> = null;
  867. var program: any = null;
  868. if (parsedParticleSystem.customShader) {
  869. program = parsedParticleSystem.customShader;
  870. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  871. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  872. }
  873. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  874. particleSystem.customShader = program;
  875. if (parsedParticleSystem.id) {
  876. particleSystem.id = parsedParticleSystem.id;
  877. }
  878. // Auto start
  879. if (parsedParticleSystem.preventAutoStart) {
  880. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  881. }
  882. // Texture
  883. if (parsedParticleSystem.textureName) {
  884. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  885. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  886. }
  887. // Emitter
  888. if (parsedParticleSystem.emitterId) {
  889. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  890. } else {
  891. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  892. }
  893. // Animations
  894. if (parsedParticleSystem.animations) {
  895. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  896. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  897. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  898. }
  899. }
  900. if (parsedParticleSystem.autoAnimate) {
  901. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  902. }
  903. // Particle system
  904. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  905. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  906. particleSystem.minSize = parsedParticleSystem.minSize;
  907. particleSystem.maxSize = parsedParticleSystem.maxSize;
  908. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  909. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  910. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  911. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  912. particleSystem.emitRate = parsedParticleSystem.emitRate;
  913. particleSystem.minEmitBox = Vector3.FromArray(parsedParticleSystem.minEmitBox);
  914. particleSystem.maxEmitBox = Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  915. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  916. particleSystem.direction1 = Vector3.FromArray(parsedParticleSystem.direction1);
  917. particleSystem.direction2 = Vector3.FromArray(parsedParticleSystem.direction2);
  918. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  919. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  920. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  921. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  922. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  923. particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
  924. particleSystem.blendMode = parsedParticleSystem.blendMode;
  925. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  926. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  927. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  928. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  929. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  930. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  931. if (!particleSystem.preventAutoStart) {
  932. particleSystem.start();
  933. }
  934. return particleSystem;
  935. }
  936. }
  937. }