babylon.particleSystem.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  1. module BABYLON {
  2. /** @hidden */
  3. class ColorGradient {
  4. public gradient: number;
  5. public color: Color4;
  6. }
  7. /**
  8. * This represents a particle system in Babylon.
  9. * 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.
  10. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  11. * @example https://doc.babylonjs.com/babylon101/particles
  12. */
  13. export class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem {
  14. /**
  15. * Source color is added to the destination color without alpha affecting the result.
  16. */
  17. public static BLENDMODE_ONEONE = 0;
  18. /**
  19. * Blend current color and particle color using particle’s alpha.
  20. */
  21. public static BLENDMODE_STANDARD = 1;
  22. /**
  23. * Add current color and particle color multiplied by particle’s alpha.
  24. */
  25. public static BLENDMODE_ADD = 2;
  26. /**
  27. * List of animations used by the particle system.
  28. */
  29. public animations: Animation[] = [];
  30. /**
  31. * The id of the Particle system.
  32. */
  33. public id: string;
  34. /**
  35. * The friendly name of the Particle system.
  36. */
  37. public name: string;
  38. /**
  39. * The rendering group used by the Particle system to chose when to render.
  40. */
  41. public renderingGroupId = 0;
  42. /**
  43. * The emitter represents the Mesh or position we are attaching the particle system to.
  44. */
  45. public emitter: Nullable<AbstractMesh | Vector3> = null;
  46. /**
  47. * The maximum number of particles to emit per frame
  48. */
  49. public emitRate = 10;
  50. /**
  51. * If you want to launch only a few particles at once, that can be done, as well.
  52. */
  53. public manualEmitCount = -1;
  54. /**
  55. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56. */
  57. public updateSpeed = 0.01;
  58. /**
  59. * The amount of time the particle system is running (depends of the overall update speed).
  60. */
  61. public targetStopDuration = 0;
  62. /**
  63. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  64. */
  65. public disposeOnStop = false;
  66. /**
  67. * Minimum power of emitting particles.
  68. */
  69. public minEmitPower = 1;
  70. /**
  71. * Maximum power of emitting particles.
  72. */
  73. public maxEmitPower = 1;
  74. /**
  75. * Minimum life time of emitting particles.
  76. */
  77. public minLifeTime = 1;
  78. /**
  79. * Maximum life time of emitting particles.
  80. */
  81. public maxLifeTime = 1;
  82. /**
  83. * Minimum Size of emitting particles.
  84. */
  85. public minSize = 1;
  86. /**
  87. * Maximum Size of emitting particles.
  88. */
  89. public maxSize = 1;
  90. /**
  91. * Minimum scale of emitting particles on X axis.
  92. */
  93. public minScaleX = 1;
  94. /**
  95. * Maximum scale of emitting particles on X axis.
  96. */
  97. public maxScaleX = 1;
  98. /**
  99. * Minimum scale of emitting particles on Y axis.
  100. */
  101. public minScaleY = 1;
  102. /**
  103. * Maximum scale of emitting particles on Y axis.
  104. */
  105. public maxScaleY = 1;
  106. /**
  107. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  108. */
  109. public minAngularSpeed = 0;
  110. /**
  111. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  112. */
  113. public maxAngularSpeed = 0;
  114. /**
  115. * The texture used to render each particle. (this can be a spritesheet)
  116. */
  117. public particleTexture: Nullable<Texture>;
  118. /**
  119. * The layer mask we are rendering the particles through.
  120. */
  121. public layerMask: number = 0x0FFFFFFF;
  122. /**
  123. * This can help using your own shader to render the particle system.
  124. * The according effect will be created
  125. */
  126. public customShader: any = null;
  127. /**
  128. * By default particle system starts as soon as they are created. This prevents the
  129. * automatic start to happen and let you decide when to start emitting particles.
  130. */
  131. public preventAutoStart: boolean = false;
  132. /**
  133. * This function can be defined to provide custom update for active particles.
  134. * This function will be called instead of regular update (age, position, color, etc.).
  135. * Do not forget that this function will be called on every frame so try to keep it simple and fast :)
  136. */
  137. public updateFunction: (particles: Particle[]) => void;
  138. /**
  139. * Callback triggered when the particle animation is ending.
  140. */
  141. public onAnimationEnd: Nullable<() => void> = null;
  142. /**
  143. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  144. */
  145. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  146. /**
  147. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  148. * to override the particles.
  149. */
  150. public forceDepthWrite = false;
  151. /**
  152. * You can use gravity if you want to give an orientation to your particles.
  153. */
  154. public gravity = Vector3.Zero();
  155. private _colorGradients: Nullable<Array<ColorGradient>> = null;
  156. /**
  157. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  158. * This only works when particleEmitterTyps is a BoxParticleEmitter
  159. */
  160. public get direction1(): Vector3 {
  161. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  162. return (<BoxParticleEmitter>this.particleEmitterType).direction1;
  163. }
  164. return Vector3.Zero();
  165. }
  166. public set direction1(value: Vector3) {
  167. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  168. (<BoxParticleEmitter>this.particleEmitterType).direction1 = value;
  169. }
  170. }
  171. /**
  172. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  173. * This only works when particleEmitterTyps is a BoxParticleEmitter
  174. */
  175. public get direction2(): Vector3 {
  176. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  177. return (<BoxParticleEmitter>this.particleEmitterType).direction2;
  178. }
  179. return Vector3.Zero();
  180. }
  181. public set direction2(value: Vector3) {
  182. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  183. (<BoxParticleEmitter>this.particleEmitterType).direction2 = value;
  184. }
  185. }
  186. /**
  187. * 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.
  188. * This only works when particleEmitterTyps is a BoxParticleEmitter
  189. */
  190. public get minEmitBox(): Vector3 {
  191. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  192. return (<BoxParticleEmitter>this.particleEmitterType).minEmitBox;
  193. }
  194. return Vector3.Zero();
  195. }
  196. public set minEmitBox(value: Vector3) {
  197. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  198. (<BoxParticleEmitter>this.particleEmitterType).minEmitBox = value;
  199. }
  200. }
  201. /**
  202. * 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.
  203. * This only works when particleEmitterTyps is a BoxParticleEmitter
  204. */
  205. public get maxEmitBox(): Vector3 {
  206. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  207. return (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox;
  208. }
  209. return Vector3.Zero();
  210. }
  211. public set maxEmitBox(value: Vector3) {
  212. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  213. (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox = value;
  214. }
  215. }
  216. /**
  217. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  218. */
  219. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  220. /**
  221. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  222. */
  223. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  224. /**
  225. * Color the particle will have at the end of its lifetime
  226. */
  227. public colorDead = new Color4(0, 0, 0, 1.0);
  228. /**
  229. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  230. */
  231. public textureMask = new Color4(1.0, 1.0, 1.0, 1.0);
  232. /**
  233. * The particle emitter type defines the emitter used by the particle system.
  234. * It can be for example box, sphere, or cone...
  235. */
  236. public particleEmitterType: IParticleEmitterType;
  237. /**
  238. * This function can be defined to specify initial direction for every new particle.
  239. * It by default use the emitterType defined function
  240. */
  241. public startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void;
  242. /**
  243. * This function can be defined to specify initial position for every new particle.
  244. * It by default use the emitterType defined function
  245. */
  246. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void;
  247. /**
  248. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  249. */
  250. public spriteCellLoop = true;
  251. /**
  252. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  253. */
  254. public spriteCellChangeSpeed = 0;
  255. /**
  256. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  257. */
  258. public startSpriteCellID = 0;
  259. /**
  260. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  261. */
  262. public endSpriteCellID = 0;
  263. /**
  264. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  265. */
  266. public spriteCellWidth = 0;
  267. /**
  268. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  269. */
  270. public spriteCellHeight = 0;
  271. /**
  272. * An event triggered when the system is disposed
  273. */
  274. public onDisposeObservable = new Observable<ParticleSystem>();
  275. private _onDisposeObserver: Nullable<Observer<ParticleSystem>>;
  276. /**
  277. * Sets a callback that will be triggered when the system is disposed
  278. */
  279. public set onDispose(callback: () => void) {
  280. if (this._onDisposeObserver) {
  281. this.onDisposeObservable.remove(this._onDisposeObserver);
  282. }
  283. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  284. }
  285. /**
  286. * Gets whether an animation sprite sheet is enabled or not on the particle system
  287. */
  288. public get isAnimationSheetEnabled(): boolean {
  289. return this._isAnimationSheetEnabled;
  290. }
  291. /**
  292. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  293. */
  294. public get isBillboardBased(): boolean {
  295. return this._isBillboardBased;
  296. }
  297. public set isBillboardBased(value: boolean) {
  298. if (this._isBillboardBased === value) {
  299. return;
  300. }
  301. this._isBillboardBased = value;
  302. this._resetEffect();
  303. }
  304. private _particles = new Array<Particle>();
  305. private _epsilon: number;
  306. private _capacity: number;
  307. private _scene: Scene;
  308. private _stockParticles = new Array<Particle>();
  309. private _newPartsExcess = 0;
  310. private _vertexData: Float32Array;
  311. private _vertexBuffer: Nullable<Buffer>;
  312. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  313. private _spriteBuffer: Nullable<Buffer>;
  314. private _indexBuffer: Nullable<WebGLBuffer>;
  315. private _effect: Effect;
  316. private _customEffect: Nullable<Effect>;
  317. private _cachedDefines: string;
  318. private _scaledColorStep = new Color4(0, 0, 0, 0);
  319. private _colorDiff = new Color4(0, 0, 0, 0);
  320. private _scaledDirection = Vector3.Zero();
  321. private _scaledGravity = Vector3.Zero();
  322. private _currentRenderId = -1;
  323. private _alive: boolean;
  324. private _useInstancing = false;
  325. private _started = false;
  326. private _stopped = false;
  327. private _actualFrame = 0;
  328. private _scaledUpdateSpeed: number;
  329. private _vertexBufferSize: number;
  330. private _isAnimationSheetEnabled: boolean;
  331. private _isBillboardBased = true;
  332. // end of sheet animation
  333. // Sub-emitters
  334. /**
  335. * this is the Sub-emitters templates that will be used to generate particle system when the particle dies, this property is used by the root particle system only.
  336. */
  337. public subEmitters: ParticleSystem[];
  338. /**
  339. * The current active Sub-systems, this property is used by the root particle system only.
  340. */
  341. public activeSubSystems: Array<ParticleSystem>;
  342. private _rootParticleSystem: ParticleSystem;
  343. //end of Sub-emitter
  344. /**
  345. * Gets the current list of active particles
  346. */
  347. public get particles(): Particle[] {
  348. return this._particles;
  349. }
  350. /**
  351. * Returns the string "ParticleSystem"
  352. * @returns a string containing the class name
  353. */
  354. public getClassName(): string {
  355. return "ParticleSystem";
  356. }
  357. /**
  358. * Instantiates a particle system.
  359. * 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.
  360. * @param name The name of the particle system
  361. * @param capacity The max number of particles alive at the same time
  362. * @param scene The scene the particle system belongs to
  363. * @param customEffect a custom effect used to change the way particles are rendered by default
  364. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  365. * @param epsilon Offset used to render the particles
  366. */
  367. constructor(name: string, capacity: number, scene: Scene, customEffect: Nullable<Effect> = null, isAnimationSheetEnabled: boolean = false, epsilon: number = 0.01) {
  368. this.id = name;
  369. this.name = name;
  370. this._capacity = capacity;
  371. this._epsilon = epsilon;
  372. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  373. this._scene = scene || Engine.LastCreatedScene;
  374. this._customEffect = customEffect;
  375. scene.particleSystems.push(this);
  376. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  377. this._createIndexBuffer();
  378. this._createVertexBuffers();
  379. // Default emitter type
  380. this.particleEmitterType = new BoxParticleEmitter();
  381. this.updateFunction = (particles: Particle[]): void => {
  382. for (var index = 0; index < particles.length; index++) {
  383. var particle = particles[index];
  384. particle.age += this._scaledUpdateSpeed;
  385. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  386. this._emitFromParticle(particle);
  387. this.recycleParticle(particle);
  388. index--;
  389. continue;
  390. }
  391. else {
  392. if (this._colorGradients && this._colorGradients.length > 0) {
  393. let ratio = particle.age / particle.lifeTime;
  394. for (var gradientIndex = 0; gradientIndex < this._colorGradients.length - 1; gradientIndex++) {
  395. let currentGradient = this._colorGradients[gradientIndex];
  396. let nextGradient = this._colorGradients[gradientIndex + 1];
  397. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  398. let scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  399. Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, particle.color);
  400. break;
  401. }
  402. }
  403. }
  404. else {
  405. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  406. particle.color.addInPlace(this._scaledColorStep);
  407. if (particle.color.a < 0) {
  408. particle.color.a = 0;
  409. }
  410. }
  411. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  412. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  413. particle.position.addInPlace(this._scaledDirection);
  414. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  415. particle.direction.addInPlace(this._scaledGravity);
  416. if (this._isAnimationSheetEnabled) {
  417. particle.updateCellIndex(this._scaledUpdateSpeed);
  418. }
  419. }
  420. }
  421. }
  422. }
  423. /**
  424. * Adds a new color gradient
  425. * @param gradient defines the gradient to use (between 0 and 1)
  426. * @param color defines the color to affect to the specified gradient
  427. */
  428. public addColorGradient(gradient: number, color: Color4): ParticleSystem {
  429. if (!this._colorGradients) {
  430. this._colorGradients = [];
  431. }
  432. let colorGradient = new ColorGradient();
  433. colorGradient.gradient = gradient;
  434. colorGradient.color = color;
  435. this._colorGradients.push(colorGradient);
  436. this._colorGradients.sort((a, b) => {
  437. if (a.gradient < b.gradient) {
  438. return -1;
  439. } else if (a.gradient > b.gradient) {
  440. return 1;
  441. }
  442. return 0;
  443. })
  444. return this;
  445. }
  446. /**
  447. * Remove a specific color gradient
  448. * @param gradient defines the gradient to remove
  449. */
  450. public removeColorGradient(gradient: number): ParticleSystem {
  451. if (!this._colorGradients) {
  452. return this;
  453. }
  454. let index = 0;
  455. for (var colorGradient of this._colorGradients) {
  456. if (colorGradient.gradient === gradient) {
  457. this._colorGradients.splice(index, 1);
  458. break;
  459. }
  460. index++;
  461. }
  462. return this;
  463. }
  464. private _resetEffect() {
  465. if (this._vertexBuffer) {
  466. this._vertexBuffer.dispose();
  467. this._vertexBuffer = null;
  468. }
  469. if (this._spriteBuffer) {
  470. this._spriteBuffer.dispose();
  471. this._spriteBuffer = null;
  472. }
  473. this._createVertexBuffers();
  474. }
  475. private _createVertexBuffers() {
  476. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  477. if (this._isAnimationSheetEnabled) {
  478. this._vertexBufferSize += 1;
  479. }
  480. if (!this._isBillboardBased) {
  481. this._vertexBufferSize += 3;
  482. }
  483. let engine = this._scene.getEngine();
  484. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  485. this._vertexBuffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  486. let dataOffset = 0;
  487. var positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  488. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  489. dataOffset += 3;
  490. var colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  491. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  492. dataOffset += 4;
  493. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  494. this._vertexBuffers["angle"] = options;
  495. dataOffset += 1;
  496. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  497. this._vertexBuffers["size"] = size;
  498. dataOffset += 2;
  499. if (this._isAnimationSheetEnabled) {
  500. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  501. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  502. dataOffset += 1;
  503. }
  504. if (!this._isBillboardBased) {
  505. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  506. this._vertexBuffers["direction"] = directionBuffer;
  507. dataOffset += 3;
  508. }
  509. var offsets: VertexBuffer;
  510. if (this._useInstancing) {
  511. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  512. this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
  513. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  514. } else {
  515. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  516. dataOffset += 2;
  517. }
  518. this._vertexBuffers["offset"] = offsets;
  519. }
  520. private _createIndexBuffer() {
  521. if (this._useInstancing) {
  522. return;
  523. }
  524. var indices = [];
  525. var index = 0;
  526. for (var count = 0; count < this._capacity; count++) {
  527. indices.push(index);
  528. indices.push(index + 1);
  529. indices.push(index + 2);
  530. indices.push(index);
  531. indices.push(index + 2);
  532. indices.push(index + 3);
  533. index += 4;
  534. }
  535. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  536. }
  537. /**
  538. * Gets the maximum number of particles active at the same time.
  539. * @returns The max number of active particles.
  540. */
  541. public getCapacity(): number {
  542. return this._capacity;
  543. }
  544. /**
  545. * Gets Wether there are still active particles in the system.
  546. * @returns True if it is alive, otherwise false.
  547. */
  548. public isAlive(): boolean {
  549. return this._alive;
  550. }
  551. /**
  552. * Gets Wether the system has been started.
  553. * @returns True if it has been started, otherwise false.
  554. */
  555. public isStarted(): boolean {
  556. return this._started;
  557. }
  558. /**
  559. * Starts the particle system and begins to emit.
  560. */
  561. public start(): void {
  562. this._started = true;
  563. this._stopped = false;
  564. this._actualFrame = 0;
  565. if (this.subEmitters && this.subEmitters.length != 0) {
  566. this.activeSubSystems = new Array<ParticleSystem>();
  567. }
  568. }
  569. /**
  570. * Stops the particle system.
  571. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  572. */
  573. public stop(stopSubEmitters = true): void {
  574. this._stopped = true;
  575. if (stopSubEmitters) {
  576. this._stopSubEmitters();
  577. }
  578. }
  579. // animation sheet
  580. /**
  581. * Remove all active particles
  582. */
  583. public reset(): void {
  584. this._stockParticles = [];
  585. this._particles = [];
  586. }
  587. /**
  588. * @hidden (for internal use only)
  589. */
  590. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  591. var offset = index * this._vertexBufferSize;
  592. this._vertexData[offset++] = particle.position.x;
  593. this._vertexData[offset++] = particle.position.y;
  594. this._vertexData[offset++] = particle.position.z;
  595. this._vertexData[offset++] = particle.color.r;
  596. this._vertexData[offset++] = particle.color.g;
  597. this._vertexData[offset++] = particle.color.b;
  598. this._vertexData[offset++] = particle.color.a;
  599. this._vertexData[offset++] = particle.angle;
  600. this._vertexData[offset++] = particle.scale.x * particle.size;
  601. this._vertexData[offset++] = particle.scale.y * particle.size;
  602. if (this._isAnimationSheetEnabled) {
  603. this._vertexData[offset++] = particle.cellIndex;
  604. }
  605. if (!this._isBillboardBased) {
  606. if (particle._initialDirection) {
  607. this._vertexData[offset++] = particle._initialDirection.x;
  608. this._vertexData[offset++] = particle._initialDirection.y;
  609. this._vertexData[offset++] = particle._initialDirection.z;
  610. } else {
  611. this._vertexData[offset++] = particle.direction.x;
  612. this._vertexData[offset++] = particle.direction.y;
  613. this._vertexData[offset++] = particle.direction.z;
  614. }
  615. }
  616. if (!this._useInstancing) {
  617. if (this._isAnimationSheetEnabled) {
  618. if (offsetX === 0)
  619. offsetX = this._epsilon;
  620. else if (offsetX === 1)
  621. offsetX = 1 - this._epsilon;
  622. if (offsetY === 0)
  623. offsetY = this._epsilon;
  624. else if (offsetY === 1)
  625. offsetY = 1 - this._epsilon;
  626. }
  627. this._vertexData[offset++] = offsetX;
  628. this._vertexData[offset++] = offsetY;
  629. }
  630. }
  631. // start of sub system methods
  632. /**
  633. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  634. * Its lifetime will start back at 0.
  635. */
  636. public recycleParticle: (particle: Particle) => void = (particle) => {
  637. var lastParticle = <Particle>this._particles.pop();
  638. if (lastParticle !== particle) {
  639. lastParticle.copyTo(particle);
  640. }
  641. this._stockParticles.push(lastParticle);
  642. };
  643. private _stopSubEmitters(): void {
  644. if (!this.activeSubSystems) {
  645. return;
  646. }
  647. this.activeSubSystems.forEach(subSystem => {
  648. subSystem.stop(true);
  649. });
  650. this.activeSubSystems = new Array<ParticleSystem>();
  651. }
  652. private _createParticle: () => Particle = () => {
  653. var particle: Particle;
  654. if (this._stockParticles.length !== 0) {
  655. particle = <Particle>this._stockParticles.pop();
  656. particle.age = 0;
  657. particle.cellIndex = this.startSpriteCellID;
  658. } else {
  659. particle = new Particle(this);
  660. }
  661. return particle;
  662. }
  663. private _removeFromRoot(): void {
  664. if (!this._rootParticleSystem){
  665. return;
  666. }
  667. let index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  668. if (index !== -1) {
  669. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  670. }
  671. }
  672. private _emitFromParticle: (particle: Particle) => void = (particle) => {
  673. if (!this.subEmitters || this.subEmitters.length === 0) {
  674. return;
  675. }
  676. var templateIndex = Math.floor(Math.random() * this.subEmitters.length);
  677. var subSystem = this.subEmitters[templateIndex].clone(this.name + "_sub", particle.position.clone());
  678. subSystem._rootParticleSystem = this;
  679. this.activeSubSystems.push(subSystem);
  680. subSystem.start();
  681. }
  682. // end of sub system methods
  683. private _update(newParticles: number): void {
  684. // Update current
  685. this._alive = this._particles.length > 0;
  686. this.updateFunction(this._particles);
  687. // Add new ones
  688. var worldMatrix;
  689. if ((<AbstractMesh>this.emitter).position) {
  690. var emitterMesh = (<AbstractMesh>this.emitter);
  691. worldMatrix = emitterMesh.getWorldMatrix();
  692. } else {
  693. var emitterPosition = (<Vector3>this.emitter);
  694. worldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  695. }
  696. var particle: Particle;
  697. for (var index = 0; index < newParticles; index++) {
  698. if (this._particles.length === this._capacity) {
  699. break;
  700. }
  701. particle = this._createParticle();
  702. this._particles.push(particle);
  703. let emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  704. if (this.startPositionFunction) {
  705. this.startPositionFunction(worldMatrix, particle.position, particle);
  706. }
  707. else {
  708. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  709. }
  710. if (this.startDirectionFunction) {
  711. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  712. }
  713. else {
  714. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  715. }
  716. if (emitPower === 0) {
  717. if (!particle._initialDirection) {
  718. particle._initialDirection = particle.direction.clone();
  719. } else {
  720. particle._initialDirection.copyFrom(particle.direction);
  721. }
  722. } else {
  723. particle._initialDirection = null;
  724. }
  725. particle.direction.scaleInPlace(emitPower);
  726. particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  727. particle.size = Scalar.RandomRange(this.minSize, this.maxSize);
  728. particle.scale.copyFromFloats(Scalar.RandomRange(this.minScaleX, this.maxScaleX), Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  729. particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  730. if (!this._colorGradients || this._colorGradients.length === 0) {
  731. var step = Scalar.RandomRange(0, 1.0);
  732. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  733. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  734. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  735. } else {
  736. particle.color.copyFrom(this._colorGradients[0].color);
  737. }
  738. }
  739. }
  740. private _getEffect(): Effect {
  741. if (this._customEffect) {
  742. return this._customEffect;
  743. };
  744. var defines = [];
  745. if (this._scene.clipPlane) {
  746. defines.push("#define CLIPPLANE");
  747. }
  748. if (this._isAnimationSheetEnabled) {
  749. defines.push("#define ANIMATESHEET");
  750. }
  751. if (this._isBillboardBased) {
  752. defines.push("#define BILLBOARD");
  753. }
  754. // Effect
  755. var join = defines.join("\n");
  756. if (this._cachedDefines !== join) {
  757. this._cachedDefines = join;
  758. var attributesNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
  759. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  760. if (this._isAnimationSheetEnabled) {
  761. attributesNamesOrOptions.push("cellIndex");
  762. effectCreationOption.push("particlesInfos")
  763. }
  764. if (!this._isBillboardBased) {
  765. attributesNamesOrOptions.push("direction");
  766. }
  767. this._effect = this._scene.getEngine().createEffect(
  768. "particles",
  769. attributesNamesOrOptions,
  770. effectCreationOption,
  771. ["diffuseSampler"], join);
  772. }
  773. return this._effect;
  774. }
  775. /**
  776. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  777. */
  778. public animate(): void {
  779. if (!this._started)
  780. return;
  781. var effect = this._getEffect();
  782. // Check
  783. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  784. return;
  785. if (this._currentRenderId === this._scene.getRenderId()) {
  786. return;
  787. }
  788. this._currentRenderId = this._scene.getRenderId();
  789. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  790. // determine the number of particles we need to create
  791. var newParticles;
  792. if (this.manualEmitCount > -1) {
  793. newParticles = this.manualEmitCount;
  794. this._newPartsExcess = 0;
  795. this.manualEmitCount = 0;
  796. } else {
  797. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  798. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  799. }
  800. if (this._newPartsExcess > 1.0) {
  801. newParticles += this._newPartsExcess >> 0;
  802. this._newPartsExcess -= this._newPartsExcess >> 0;
  803. }
  804. this._alive = false;
  805. if (!this._stopped) {
  806. this._actualFrame += this._scaledUpdateSpeed;
  807. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  808. this.stop();
  809. } else {
  810. newParticles = 0;
  811. }
  812. this._update(newParticles);
  813. // Stopped?
  814. if (this._stopped) {
  815. if (!this._alive) {
  816. this._started = false;
  817. if (this.onAnimationEnd) {
  818. this.onAnimationEnd();
  819. }
  820. if (this.disposeOnStop) {
  821. this._scene._toBeDisposed.push(this);
  822. }
  823. }
  824. }
  825. // Update VBO
  826. var offset = 0;
  827. for (var index = 0; index < this._particles.length; index++) {
  828. var particle = this._particles[index];
  829. this._appendParticleVertices(offset, particle);
  830. offset += this._useInstancing ? 1 : 4;
  831. }
  832. if (this._vertexBuffer) {
  833. this._vertexBuffer.update(this._vertexData);
  834. }
  835. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  836. this.stop();
  837. }
  838. }
  839. private _appendParticleVertices(offset: number, particle: Particle) {
  840. this._appendParticleVertex(offset++, particle, 0, 0);
  841. if (!this._useInstancing) {
  842. this._appendParticleVertex(offset++, particle, 1, 0);
  843. this._appendParticleVertex(offset++, particle, 1, 1);
  844. this._appendParticleVertex(offset++, particle, 0, 1);
  845. }
  846. }
  847. /**
  848. * Rebuilds the particle system.
  849. */
  850. public rebuild(): void {
  851. this._createIndexBuffer();
  852. if (this._vertexBuffer) {
  853. this._vertexBuffer._rebuild();
  854. }
  855. }
  856. /**
  857. * Is this system ready to be used/rendered
  858. * @return true if the system is ready
  859. */
  860. public isReady(): boolean {
  861. var effect = this._getEffect();
  862. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  863. return false;
  864. }
  865. return true;
  866. }
  867. /**
  868. * Renders the particle system in its current state.
  869. * @returns the current number of particles
  870. */
  871. public render(): number {
  872. var effect = this._getEffect();
  873. // Check
  874. if (!this.isReady() || !this._particles.length) {
  875. return 0;
  876. }
  877. var engine = this._scene.getEngine();
  878. // Render
  879. engine.enableEffect(effect);
  880. engine.setState(false);
  881. var viewMatrix = this._scene.getViewMatrix();
  882. effect.setTexture("diffuseSampler", this.particleTexture);
  883. effect.setMatrix("view", viewMatrix);
  884. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  885. if (this._isAnimationSheetEnabled && this.particleTexture) {
  886. var baseSize = this.particleTexture.getBaseSize();
  887. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  888. }
  889. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  890. if (this._scene.clipPlane) {
  891. var clipPlane = this._scene.clipPlane;
  892. var invView = viewMatrix.clone();
  893. invView.invert();
  894. effect.setMatrix("invView", invView);
  895. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  896. }
  897. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  898. // Draw order
  899. switch(this.blendMode)
  900. {
  901. case ParticleSystem.BLENDMODE_ADD:
  902. engine.setAlphaMode(Engine.ALPHA_ADD);
  903. break;
  904. case ParticleSystem.BLENDMODE_ONEONE:
  905. engine.setAlphaMode(Engine.ALPHA_ONEONE);
  906. break;
  907. case ParticleSystem.BLENDMODE_STANDARD:
  908. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  909. break;
  910. }
  911. if (this.forceDepthWrite) {
  912. engine.setDepthWrite(true);
  913. }
  914. if (this._useInstancing) {
  915. engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  916. engine.unbindInstanceAttributes();
  917. } else {
  918. engine.drawElementsType(Material.TriangleFillMode, 0, this._particles.length * 6);
  919. }
  920. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  921. return this._particles.length;
  922. }
  923. /**
  924. * Disposes the particle system and free the associated resources
  925. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  926. */
  927. public dispose(disposeTexture = true): void {
  928. if (this._vertexBuffer) {
  929. this._vertexBuffer.dispose();
  930. this._vertexBuffer = null;
  931. }
  932. if (this._spriteBuffer) {
  933. this._spriteBuffer.dispose();
  934. this._spriteBuffer = null;
  935. }
  936. if (this._indexBuffer) {
  937. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  938. this._indexBuffer = null;
  939. }
  940. if (disposeTexture && this.particleTexture) {
  941. this.particleTexture.dispose();
  942. this.particleTexture = null;
  943. }
  944. this._removeFromRoot();
  945. // Remove from scene
  946. var index = this._scene.particleSystems.indexOf(this);
  947. if (index > -1) {
  948. this._scene.particleSystems.splice(index, 1);
  949. }
  950. // Callback
  951. this.onDisposeObservable.notifyObservers(this);
  952. this.onDisposeObservable.clear();
  953. }
  954. /**
  955. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  956. * @param radius The radius of the sphere to emit from
  957. * @returns the emitter
  958. */
  959. public createSphereEmitter(radius = 1): SphereParticleEmitter {
  960. var particleEmitter = new SphereParticleEmitter(radius);
  961. this.particleEmitterType = particleEmitter;
  962. return particleEmitter;
  963. }
  964. /**
  965. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  966. * @param radius The radius of the sphere to emit from
  967. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  968. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  969. * @returns the emitter
  970. */
  971. public createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)): SphereDirectedParticleEmitter {
  972. var particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2)
  973. this.particleEmitterType = particleEmitter;
  974. return particleEmitter;
  975. }
  976. /**
  977. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  978. * @param radius The radius of the cone to emit from
  979. * @param angle The base angle of the cone
  980. * @returns the emitter
  981. */
  982. public createConeEmitter(radius = 1, angle = Math.PI / 4): ConeParticleEmitter {
  983. var particleEmitter = new ConeParticleEmitter(radius, angle);
  984. this.particleEmitterType = particleEmitter;
  985. return particleEmitter;
  986. }
  987. // 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.
  988. /**
  989. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  990. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  991. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  992. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  993. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  994. * @returns the emitter
  995. */
  996. public createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter {
  997. var particleEmitter = new BoxParticleEmitter();
  998. this.particleEmitterType = particleEmitter;
  999. this.direction1 = direction1;
  1000. this.direction2 = direction2;
  1001. this.minEmitBox = minEmitBox;
  1002. this.maxEmitBox = maxEmitBox;
  1003. return particleEmitter;
  1004. }
  1005. // Clone
  1006. /**
  1007. * Clones the particle system.
  1008. * @param name The name of the cloned object
  1009. * @param newEmitter The new emitter to use
  1010. * @returns the cloned particle system
  1011. */
  1012. public clone(name: string, newEmitter: any): ParticleSystem {
  1013. var custom: Nullable<Effect> = null;
  1014. var program: any = null;
  1015. if (this.customShader != null) {
  1016. program = this.customShader;
  1017. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1018. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1019. }
  1020. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  1021. result.customShader = program;
  1022. Tools.DeepCopy(this, result, ["particles", "customShader"]);
  1023. if (newEmitter === undefined) {
  1024. newEmitter = this.emitter;
  1025. }
  1026. result.emitter = newEmitter;
  1027. if (this.particleTexture) {
  1028. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1029. }
  1030. if (!this.preventAutoStart) {
  1031. result.start();
  1032. }
  1033. return result;
  1034. }
  1035. /**
  1036. * Serializes the particle system to a JSON object.
  1037. * @returns the JSON object
  1038. */
  1039. public serialize(): any {
  1040. var serializationObject: any = {};
  1041. serializationObject.name = this.name;
  1042. serializationObject.id = this.id;
  1043. // Emitter
  1044. if ((<AbstractMesh>this.emitter).position) {
  1045. var emitterMesh = (<AbstractMesh>this.emitter);
  1046. serializationObject.emitterId = emitterMesh.id;
  1047. } else {
  1048. var emitterPosition = (<Vector3>this.emitter);
  1049. serializationObject.emitter = emitterPosition.asArray();
  1050. }
  1051. serializationObject.capacity = this.getCapacity();
  1052. if (this.particleTexture) {
  1053. serializationObject.textureName = this.particleTexture.name;
  1054. }
  1055. // Animations
  1056. Animation.AppendSerializedAnimations(this, serializationObject);
  1057. // Particle system
  1058. serializationObject.minAngularSpeed = this.minAngularSpeed;
  1059. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  1060. serializationObject.minSize = this.minSize;
  1061. serializationObject.maxSize = this.maxSize;
  1062. serializationObject.minScaleX = this.minScaleX;
  1063. serializationObject.maxScaleX = this.maxScaleX;
  1064. serializationObject.minScaleY = this.minScaleY;
  1065. serializationObject.maxScaleY = this.maxScaleY;
  1066. serializationObject.minEmitPower = this.minEmitPower;
  1067. serializationObject.maxEmitPower = this.maxEmitPower;
  1068. serializationObject.minLifeTime = this.minLifeTime;
  1069. serializationObject.maxLifeTime = this.maxLifeTime;
  1070. serializationObject.emitRate = this.emitRate;
  1071. serializationObject.minEmitBox = this.minEmitBox.asArray();
  1072. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  1073. serializationObject.gravity = this.gravity.asArray();
  1074. serializationObject.direction1 = this.direction1.asArray();
  1075. serializationObject.direction2 = this.direction2.asArray();
  1076. serializationObject.color1 = this.color1.asArray();
  1077. serializationObject.color2 = this.color2.asArray();
  1078. serializationObject.colorDead = this.colorDead.asArray();
  1079. serializationObject.updateSpeed = this.updateSpeed;
  1080. serializationObject.targetStopDuration = this.targetStopDuration;
  1081. serializationObject.textureMask = this.textureMask.asArray();
  1082. serializationObject.blendMode = this.blendMode;
  1083. serializationObject.customShader = this.customShader;
  1084. serializationObject.preventAutoStart = this.preventAutoStart;
  1085. serializationObject.startSpriteCellID = this.startSpriteCellID;
  1086. serializationObject.endSpriteCellID = this.endSpriteCellID;
  1087. serializationObject.spriteCellLoop = this.spriteCellLoop;
  1088. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  1089. serializationObject.spriteCellWidth = this.spriteCellWidth;
  1090. serializationObject.spriteCellHeight = this.spriteCellHeight;
  1091. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  1092. // Emitter
  1093. if (this.particleEmitterType) {
  1094. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  1095. }
  1096. return serializationObject;
  1097. }
  1098. /**
  1099. * Parses a JSON object to create a particle system.
  1100. * @param parsedParticleSystem The JSON object to parse
  1101. * @param scene The scene to create the particle system in
  1102. * @param rootUrl The root url to use to load external dependencies like texture
  1103. * @returns the Parsed particle system
  1104. */
  1105. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem {
  1106. var name = parsedParticleSystem.name;
  1107. var custom: Nullable<Effect> = null;
  1108. var program: any = null;
  1109. if (parsedParticleSystem.customShader) {
  1110. program = parsedParticleSystem.customShader;
  1111. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1112. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1113. }
  1114. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  1115. particleSystem.customShader = program;
  1116. if (parsedParticleSystem.id) {
  1117. particleSystem.id = parsedParticleSystem.id;
  1118. }
  1119. // Auto start
  1120. if (parsedParticleSystem.preventAutoStart) {
  1121. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  1122. }
  1123. // Texture
  1124. if (parsedParticleSystem.textureName) {
  1125. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  1126. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  1127. }
  1128. // Emitter
  1129. if (parsedParticleSystem.emitterId) {
  1130. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  1131. } else {
  1132. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  1133. }
  1134. // Animations
  1135. if (parsedParticleSystem.animations) {
  1136. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  1137. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  1138. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  1139. }
  1140. }
  1141. if (parsedParticleSystem.autoAnimate) {
  1142. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  1143. }
  1144. // Particle system
  1145. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  1146. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  1147. particleSystem.minSize = parsedParticleSystem.minSize;
  1148. particleSystem.maxSize = parsedParticleSystem.maxSize;
  1149. if (parsedParticleSystem.minScaleX) {
  1150. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  1151. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  1152. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  1153. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  1154. }
  1155. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  1156. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  1157. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  1158. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  1159. particleSystem.emitRate = parsedParticleSystem.emitRate;
  1160. particleSystem.minEmitBox = Vector3.FromArray(parsedParticleSystem.minEmitBox);
  1161. particleSystem.maxEmitBox = Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  1162. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  1163. particleSystem.direction1 = Vector3.FromArray(parsedParticleSystem.direction1);
  1164. particleSystem.direction2 = Vector3.FromArray(parsedParticleSystem.direction2);
  1165. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  1166. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  1167. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  1168. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  1169. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  1170. particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
  1171. particleSystem.blendMode = parsedParticleSystem.blendMode;
  1172. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  1173. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  1174. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  1175. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  1176. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  1177. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  1178. if (!particleSystem.preventAutoStart) {
  1179. particleSystem.start();
  1180. }
  1181. return particleSystem;
  1182. }
  1183. }
  1184. }