babylon.particleSystem.ts 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  1. module BABYLON {
  2. /**
  3. * This represents a particle system in Babylon.
  4. * 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.
  5. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  6. * @example https://doc.babylonjs.com/babylon101/particles
  7. */
  8. export class ParticleSystem implements IDisposable, IAnimatable, IParticleSystem {
  9. /**
  10. * Source color is added to the destination color without alpha affecting the result.
  11. */
  12. public static BLENDMODE_ONEONE = 0;
  13. /**
  14. * Blend current color and particle color using particle’s alpha.
  15. */
  16. public static BLENDMODE_STANDARD = 1;
  17. /**
  18. * Add current color and particle color multiplied by particle’s alpha.
  19. */
  20. public static BLENDMODE_ADD = 2;
  21. /**
  22. * List of animations used by the particle system.
  23. */
  24. public animations: Animation[] = [];
  25. /**
  26. * The id of the Particle system.
  27. */
  28. public id: string;
  29. /**
  30. * The friendly name of the Particle system.
  31. */
  32. public name: string;
  33. /**
  34. * The rendering group used by the Particle system to chose when to render.
  35. */
  36. public renderingGroupId = 0;
  37. /**
  38. * The emitter represents the Mesh or position we are attaching the particle system to.
  39. */
  40. public emitter: Nullable<AbstractMesh | Vector3> = null;
  41. /**
  42. * The maximum number of particles to emit per frame
  43. */
  44. public emitRate = 10;
  45. /**
  46. * If you want to launch only a few particles at once, that can be done, as well.
  47. */
  48. public manualEmitCount = -1;
  49. /**
  50. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51. */
  52. public updateSpeed = 0.01;
  53. /**
  54. * The amount of time the particle system is running (depends of the overall update speed).
  55. */
  56. public targetStopDuration = 0;
  57. /**
  58. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  59. */
  60. public disposeOnStop = false;
  61. /**
  62. * Minimum power of emitting particles.
  63. */
  64. public minEmitPower = 1;
  65. /**
  66. * Maximum power of emitting particles.
  67. */
  68. public maxEmitPower = 1;
  69. /**
  70. * Minimum life time of emitting particles.
  71. */
  72. public minLifeTime = 1;
  73. /**
  74. * Maximum life time of emitting particles.
  75. */
  76. public maxLifeTime = 1;
  77. /**
  78. * Minimum Size of emitting particles.
  79. */
  80. public minSize = 1;
  81. /**
  82. * Maximum Size of emitting particles.
  83. */
  84. public maxSize = 1;
  85. /**
  86. * Minimum scale of emitting particles on X axis.
  87. */
  88. public minScaleX = 1;
  89. /**
  90. * Maximum scale of emitting particles on X axis.
  91. */
  92. public maxScaleX = 1;
  93. /**
  94. * Minimum scale of emitting particles on Y axis.
  95. */
  96. public minScaleY = 1;
  97. /**
  98. * Maximum scale of emitting particles on Y axis.
  99. */
  100. public maxScaleY = 1;
  101. /**
  102. * Gets or sets the minimal initial rotation in radians.
  103. */
  104. public minInitialRotation = 0;
  105. /**
  106. * Gets or sets the maximal initial rotation in radians.
  107. */
  108. public maxInitialRotation = 0;
  109. /**
  110. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  111. */
  112. public minAngularSpeed = 0;
  113. /**
  114. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  115. */
  116. public maxAngularSpeed = 0;
  117. /**
  118. * The texture used to render each particle. (this can be a spritesheet)
  119. */
  120. public particleTexture: Nullable<Texture>;
  121. /**
  122. * The layer mask we are rendering the particles through.
  123. */
  124. public layerMask: number = 0x0FFFFFFF;
  125. /**
  126. * This can help using your own shader to render the particle system.
  127. * The according effect will be created
  128. */
  129. public customShader: any = null;
  130. /**
  131. * By default particle system starts as soon as they are created. This prevents the
  132. * automatic start to happen and let you decide when to start emitting particles.
  133. */
  134. public preventAutoStart: boolean = false;
  135. /**
  136. * Gets or sets a texture used to add random noise to particle positions
  137. */
  138. public noiseTexture: Texture;
  139. /** Gets or sets the estimated area used by the system. It will be used to normalize the projection onto the noise texture (default is (1, 1)) */
  140. public noiseGridSize = new Vector2(1, 1);
  141. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  142. public noiseStrength = new Vector3(10, 10, 10);
  143. /**
  144. * This function can be defined to provide custom update for active particles.
  145. * This function will be called instead of regular update (age, position, color, etc.).
  146. * Do not forget that this function will be called on every frame so try to keep it simple and fast :)
  147. */
  148. public updateFunction: (particles: Particle[]) => void;
  149. /**
  150. * Callback triggered when the particle animation is ending.
  151. */
  152. public onAnimationEnd: Nullable<() => void> = null;
  153. /**
  154. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  155. */
  156. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  157. /**
  158. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  159. * to override the particles.
  160. */
  161. public forceDepthWrite = false;
  162. /**
  163. * You can use gravity if you want to give an orientation to your particles.
  164. */
  165. public gravity = Vector3.Zero();
  166. private _colorGradients: Nullable<Array<ColorGradient>> = null;
  167. private _sizeGradients: Nullable<Array<FactorGradient>> = null;
  168. private _lifeTimeGradients: Nullable<Array<FactorGradient>> = null;
  169. private _angularSpeedGradients: Nullable<Array<FactorGradient>> = null;
  170. private _velocityGradients: Nullable<Array<FactorGradient>> = null;
  171. /**
  172. * Gets the current list of color gradients.
  173. * You must use addColorGradient and removeColorGradient to udpate this list
  174. * @returns the list of color gradients
  175. */
  176. public getColorGradients(): Nullable<Array<ColorGradient>> {
  177. return this._colorGradients;
  178. }
  179. /**
  180. * Gets the current list of size gradients.
  181. * You must use addSizeGradient and removeSizeGradient to udpate this list
  182. * @returns the list of size gradients
  183. */
  184. public getSizeGradients(): Nullable<Array<FactorGradient>> {
  185. return this._sizeGradients;
  186. }
  187. /**
  188. * Gets the current list of life time gradients.
  189. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  190. * @returns the list of life time gradients
  191. */
  192. public getLifeTimeGradients(): Nullable<Array<FactorGradient>> {
  193. return this._lifeTimeGradients;
  194. }
  195. /**
  196. * Gets the current list of angular speed gradients.
  197. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  198. * @returns the list of angular speed gradients
  199. */
  200. public getAngularSpeedGradients(): Nullable<Array<FactorGradient>> {
  201. return this._angularSpeedGradients;
  202. }
  203. /**
  204. * Gets the current list of velocity gradients.
  205. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  206. * @returns the list of velocity gradients
  207. */
  208. public getVelocityGradients(): Nullable<Array<FactorGradient>> {
  209. return this._velocityGradients;
  210. }
  211. /**
  212. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  213. * This only works when particleEmitterTyps is a BoxParticleEmitter
  214. */
  215. public get direction1(): Vector3 {
  216. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  217. return (<BoxParticleEmitter>this.particleEmitterType).direction1;
  218. }
  219. return Vector3.Zero();
  220. }
  221. public set direction1(value: Vector3) {
  222. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  223. (<BoxParticleEmitter>this.particleEmitterType).direction1 = value;
  224. }
  225. }
  226. /**
  227. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  228. * This only works when particleEmitterTyps is a BoxParticleEmitter
  229. */
  230. public get direction2(): Vector3 {
  231. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  232. return (<BoxParticleEmitter>this.particleEmitterType).direction2;
  233. }
  234. return Vector3.Zero();
  235. }
  236. public set direction2(value: Vector3) {
  237. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  238. (<BoxParticleEmitter>this.particleEmitterType).direction2 = value;
  239. }
  240. }
  241. /**
  242. * 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.
  243. * This only works when particleEmitterTyps is a BoxParticleEmitter
  244. */
  245. public get minEmitBox(): Vector3 {
  246. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  247. return (<BoxParticleEmitter>this.particleEmitterType).minEmitBox;
  248. }
  249. return Vector3.Zero();
  250. }
  251. public set minEmitBox(value: Vector3) {
  252. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  253. (<BoxParticleEmitter>this.particleEmitterType).minEmitBox = value;
  254. }
  255. }
  256. /**
  257. * 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.
  258. * This only works when particleEmitterTyps is a BoxParticleEmitter
  259. */
  260. public get maxEmitBox(): Vector3 {
  261. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  262. return (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox;
  263. }
  264. return Vector3.Zero();
  265. }
  266. public set maxEmitBox(value: Vector3) {
  267. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  268. (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox = value;
  269. }
  270. }
  271. /**
  272. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  273. */
  274. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  275. /**
  276. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  277. */
  278. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  279. /**
  280. * Color the particle will have at the end of its lifetime
  281. */
  282. public colorDead = new Color4(0, 0, 0, 1.0);
  283. /**
  284. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  285. */
  286. public textureMask = new Color4(1.0, 1.0, 1.0, 1.0);
  287. /**
  288. * The particle emitter type defines the emitter used by the particle system.
  289. * It can be for example box, sphere, or cone...
  290. */
  291. public particleEmitterType: IParticleEmitterType;
  292. /**
  293. * This function can be defined to specify initial direction for every new particle.
  294. * It by default use the emitterType defined function
  295. */
  296. public startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void;
  297. /**
  298. * This function can be defined to specify initial position for every new particle.
  299. * It by default use the emitterType defined function
  300. */
  301. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void;
  302. /**
  303. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  304. */
  305. public spriteCellChangeSpeed = 1;
  306. /**
  307. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  308. */
  309. public startSpriteCellID = 0;
  310. /**
  311. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  312. */
  313. public endSpriteCellID = 0;
  314. /**
  315. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  316. */
  317. public spriteCellWidth = 0;
  318. /**
  319. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  320. */
  321. public spriteCellHeight = 0;
  322. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  323. public preWarmCycles = 0;
  324. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  325. public preWarmStepOffset = 1;
  326. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  327. public translationPivot = new Vector2(0, 0);
  328. /**
  329. * An event triggered when the system is disposed
  330. */
  331. public onDisposeObservable = new Observable<ParticleSystem>();
  332. private _onDisposeObserver: Nullable<Observer<ParticleSystem>>;
  333. /**
  334. * Sets a callback that will be triggered when the system is disposed
  335. */
  336. public set onDispose(callback: () => void) {
  337. if (this._onDisposeObserver) {
  338. this.onDisposeObservable.remove(this._onDisposeObserver);
  339. }
  340. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  341. }
  342. /**
  343. * Gets whether an animation sprite sheet is enabled or not on the particle system
  344. */
  345. public get isAnimationSheetEnabled(): boolean {
  346. return this._isAnimationSheetEnabled;
  347. }
  348. /**
  349. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  350. */
  351. public get isBillboardBased(): boolean {
  352. return this._isBillboardBased;
  353. }
  354. public set isBillboardBased(value: boolean) {
  355. if (this._isBillboardBased === value) {
  356. return;
  357. }
  358. this._isBillboardBased = value;
  359. this._resetEffect();
  360. }
  361. /**
  362. * Gets or sets the billboard mode to use when isBillboardBased = true.
  363. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  364. */
  365. public billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  366. private _particles = new Array<Particle>();
  367. private _epsilon: number;
  368. private _capacity: number;
  369. private _scene: Scene;
  370. private _stockParticles = new Array<Particle>();
  371. private _newPartsExcess = 0;
  372. private _vertexData: Float32Array;
  373. private _vertexBuffer: Nullable<Buffer>;
  374. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  375. private _spriteBuffer: Nullable<Buffer>;
  376. private _indexBuffer: Nullable<WebGLBuffer>;
  377. private _effect: Effect;
  378. private _customEffect: Nullable<Effect>;
  379. private _cachedDefines: string;
  380. private _scaledColorStep = new Color4(0, 0, 0, 0);
  381. private _colorDiff = new Color4(0, 0, 0, 0);
  382. private _scaledDirection = Vector3.Zero();
  383. private _scaledGravity = Vector3.Zero();
  384. private _currentRenderId = -1;
  385. private _alive: boolean;
  386. private _useInstancing = false;
  387. private _started = false;
  388. private _stopped = false;
  389. private _actualFrame = 0;
  390. private _scaledUpdateSpeed: number;
  391. private _vertexBufferSize: number;
  392. private _isAnimationSheetEnabled: boolean;
  393. private _isBillboardBased = true;
  394. // end of sheet animation
  395. // Sub-emitters
  396. /**
  397. * 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.
  398. */
  399. public subEmitters: ParticleSystem[];
  400. /**
  401. * The current active Sub-systems, this property is used by the root particle system only.
  402. */
  403. public activeSubSystems: Array<ParticleSystem>;
  404. private _rootParticleSystem: ParticleSystem;
  405. //end of Sub-emitter
  406. /**
  407. * Gets the current list of active particles
  408. */
  409. public get particles(): Particle[] {
  410. return this._particles;
  411. }
  412. /**
  413. * Returns the string "ParticleSystem"
  414. * @returns a string containing the class name
  415. */
  416. public getClassName(): string {
  417. return "ParticleSystem";
  418. }
  419. /**
  420. * Instantiates a particle system.
  421. * 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.
  422. * @param name The name of the particle system
  423. * @param capacity The max number of particles alive at the same time
  424. * @param scene The scene the particle system belongs to
  425. * @param customEffect a custom effect used to change the way particles are rendered by default
  426. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  427. * @param epsilon Offset used to render the particles
  428. */
  429. constructor(name: string, capacity: number, scene: Scene, customEffect: Nullable<Effect> = null, isAnimationSheetEnabled: boolean = false, epsilon: number = 0.01) {
  430. this.id = name;
  431. this.name = name;
  432. this._capacity = capacity;
  433. this._epsilon = epsilon;
  434. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  435. this._scene = scene || Engine.LastCreatedScene;
  436. this._customEffect = customEffect;
  437. scene.particleSystems.push(this);
  438. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  439. this._createIndexBuffer();
  440. this._createVertexBuffers();
  441. // Default emitter type
  442. this.particleEmitterType = new BoxParticleEmitter();
  443. this.updateFunction = (particles: Particle[]): void => {
  444. let noiseTextureData: Nullable<Uint8Array> = null;
  445. let noiseTextureSize: Nullable<ISize> = null;
  446. if (this.noiseTexture) { // We need to get texture data back to CPU
  447. noiseTextureData = <Nullable<Uint8Array>>(this.noiseTexture.readPixels());
  448. noiseTextureSize = this.noiseTexture.getSize();
  449. }
  450. for (var index = 0; index < particles.length; index++) {
  451. var particle = particles[index];
  452. particle.age += this._scaledUpdateSpeed;
  453. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  454. this._emitFromParticle(particle);
  455. this.recycleParticle(particle);
  456. index--;
  457. continue;
  458. }
  459. else {
  460. let ratio = particle.age / particle.lifeTime;
  461. // Color
  462. if (this._colorGradients && this._colorGradients.length > 0) {
  463. Tools.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  464. if (currentGradient !== particle._currentColorGradient) {
  465. particle._currentColor1.copyFrom(particle._currentColor2);
  466. (<ColorGradient>nextGradient).getColorToRef(particle._currentColor2);
  467. particle._currentColorGradient = (<ColorGradient>currentGradient);
  468. }
  469. Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  470. });
  471. }
  472. else {
  473. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  474. particle.color.addInPlace(this._scaledColorStep);
  475. if (particle.color.a < 0) {
  476. particle.color.a = 0;
  477. }
  478. }
  479. if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) {
  480. Tools.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => {
  481. if (currentGradient !== particle._currentAngularSpeedGradient) {
  482. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  483. particle._currentAngularSpeed2 = (<FactorGradient>nextGradient).getFactor();
  484. particle._currentAngularSpeedGradient = (<FactorGradient>currentGradient);
  485. }
  486. particle.angularSpeed = Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  487. });
  488. }
  489. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  490. let directionScale = this._scaledUpdateSpeed;
  491. if (this._velocityGradients && this._velocityGradients.length > 0) {
  492. Tools.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => {
  493. if (currentGradient !== particle._currentVelocityGradient) {
  494. particle._currentVelocity1 = particle._currentVelocity2;
  495. particle._currentVelocity2 = (<FactorGradient>nextGradient).getFactor();
  496. particle._currentVelocityGradient = (<FactorGradient>currentGradient);
  497. }
  498. directionScale *= Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  499. });
  500. }
  501. particle.direction.scaleToRef(directionScale, this._scaledDirection);
  502. particle.position.addInPlace(this._scaledDirection);
  503. if (noiseTextureData && noiseTextureSize) {
  504. let fetchedColorR = Tools.FetchR(particle.position.x / this.noiseGridSize.x, particle.position.y / this.noiseGridSize.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  505. let fetchedColorG = Tools.FetchR(particle.position.x / this.noiseGridSize.x + 0.33, particle.position.y / this.noiseGridSize.y + 0.66, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  506. let fetchedColorB = Tools.FetchR(particle.position.x / this.noiseGridSize.x + 0.66, particle.position.y / this.noiseGridSize.y + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  507. let force = Tmp.Vector3[0];
  508. let scaledForce = Tmp.Vector3[1];
  509. force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.x, (2 * fetchedColorB - 1) * this.noiseStrength.x);
  510. force.scaleToRef(this._scaledUpdateSpeed, scaledForce);
  511. particle.direction.addInPlace(scaledForce);
  512. }
  513. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  514. particle.direction.addInPlace(this._scaledGravity);
  515. // Size
  516. if (this._sizeGradients && this._sizeGradients.length > 0) {
  517. Tools.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {
  518. if (currentGradient !== particle._currentSizeGradient) {
  519. particle._currentSize1 = particle._currentSize2;
  520. particle._currentSize2 = (<FactorGradient>nextGradient).getFactor();
  521. particle._currentSizeGradient = (<FactorGradient>currentGradient);
  522. }
  523. particle.size = Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  524. });
  525. }
  526. if (this._isAnimationSheetEnabled) {
  527. particle.updateCellIndex();
  528. }
  529. }
  530. }
  531. }
  532. }
  533. private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number, factor2?: number) {
  534. let newGradient = new FactorGradient();
  535. newGradient.gradient = gradient;
  536. newGradient.factor1 = factor;
  537. newGradient.factor2 = factor2;
  538. factorGradients.push(newGradient);
  539. factorGradients.sort((a, b) => {
  540. if (a.gradient < b.gradient) {
  541. return -1;
  542. } else if (a.gradient > b.gradient) {
  543. return 1;
  544. }
  545. return 0;
  546. });
  547. }
  548. private _removeFactorGradient(factorGradients: Nullable<FactorGradient[]>, gradient: number) {
  549. if (!factorGradients) {
  550. return;
  551. }
  552. let index = 0;
  553. for (var factorGradient of factorGradients) {
  554. if (factorGradient.gradient === gradient) {
  555. factorGradients.splice(index, 1);
  556. break;
  557. }
  558. index++;
  559. }
  560. }
  561. /**
  562. * Adds a new life time gradient
  563. * @param gradient defines the gradient to use (between 0 and 1)
  564. * @param factor defines the life time factor to affect to the specified gradient
  565. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  566. * @returns the current particle system
  567. */
  568. public addLifeTimeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem {
  569. if (!this._lifeTimeGradients) {
  570. this._lifeTimeGradients = [];
  571. }
  572. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  573. return this;
  574. }
  575. /**
  576. * Remove a specific life time gradient
  577. * @param gradient defines the gradient to remove
  578. * @returns the current particle system
  579. */
  580. public removeLifeTimeGradient(gradient: number): ParticleSystem {
  581. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  582. return this;
  583. }
  584. /**
  585. * Adds a new size gradient
  586. * @param gradient defines the gradient to use (between 0 and 1)
  587. * @param factor defines the size factor to affect to the specified gradient
  588. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  589. * @returns the current particle system
  590. */
  591. public addSizeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem {
  592. if (!this._sizeGradients) {
  593. this._sizeGradients = [];
  594. }
  595. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  596. return this;
  597. }
  598. /**
  599. * Remove a specific size gradient
  600. * @param gradient defines the gradient to remove
  601. * @returns the current particle system
  602. */
  603. public removeSizeGradient(gradient: number): ParticleSystem {
  604. this._removeFactorGradient(this._sizeGradients, gradient);
  605. return this;
  606. }
  607. /**
  608. * Adds a new angular speed gradient
  609. * @param gradient defines the gradient to use (between 0 and 1)
  610. * @param factor defines the size factor to affect to the specified gradient
  611. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  612. * @returns the current particle system
  613. */
  614. public addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): ParticleSystem {
  615. if (!this._angularSpeedGradients) {
  616. this._angularSpeedGradients = [];
  617. }
  618. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  619. return this;
  620. }
  621. /**
  622. * Remove a specific angular speed gradient
  623. * @param gradient defines the gradient to remove
  624. * @returns the current particle system
  625. */
  626. public removeAngularSpeedGradient(gradient: number): ParticleSystem {
  627. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  628. return this;
  629. }
  630. /**
  631. * Adds a new velocity gradient
  632. * @param gradient defines the gradient to use (between 0 and 1)
  633. * @param factor defines the size factor to affect to the specified gradient
  634. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  635. * @returns the current particle system
  636. */
  637. public addVelocityGradient(gradient: number, factor: number, factor2?: number): ParticleSystem {
  638. if (!this._velocityGradients) {
  639. this._velocityGradients = [];
  640. }
  641. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  642. return this;
  643. }
  644. /**
  645. * Remove a specific velocity gradient
  646. * @param gradient defines the gradient to remove
  647. * @returns the current particle system
  648. */
  649. public removeVelocityGradient(gradient: number): ParticleSystem {
  650. this._removeFactorGradient(this._velocityGradients, gradient);
  651. return this;
  652. }
  653. /**
  654. * Adds a new color gradient
  655. * @param gradient defines the gradient to use (between 0 and 1)
  656. * @param color defines the color to affect to the specified gradient
  657. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  658. */
  659. public addColorGradient(gradient: number, color: Color4, color2?: Color4): ParticleSystem {
  660. if (!this._colorGradients) {
  661. this._colorGradients = [];
  662. }
  663. let colorGradient = new ColorGradient();
  664. colorGradient.gradient = gradient;
  665. colorGradient.color1 = color;
  666. colorGradient.color2 = color2;
  667. this._colorGradients.push(colorGradient);
  668. this._colorGradients.sort((a, b) => {
  669. if (a.gradient < b.gradient) {
  670. return -1;
  671. } else if (a.gradient > b.gradient) {
  672. return 1;
  673. }
  674. return 0;
  675. });
  676. return this;
  677. }
  678. /**
  679. * Remove a specific color gradient
  680. * @param gradient defines the gradient to remove
  681. */
  682. public removeColorGradient(gradient: number): ParticleSystem {
  683. if (!this._colorGradients) {
  684. return this;
  685. }
  686. let index = 0;
  687. for (var colorGradient of this._colorGradients) {
  688. if (colorGradient.gradient === gradient) {
  689. this._colorGradients.splice(index, 1);
  690. break;
  691. }
  692. index++;
  693. }
  694. return this;
  695. }
  696. private _resetEffect() {
  697. if (this._vertexBuffer) {
  698. this._vertexBuffer.dispose();
  699. this._vertexBuffer = null;
  700. }
  701. if (this._spriteBuffer) {
  702. this._spriteBuffer.dispose();
  703. this._spriteBuffer = null;
  704. }
  705. this._createVertexBuffers();
  706. }
  707. private _createVertexBuffers() {
  708. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  709. if (this._isAnimationSheetEnabled) {
  710. this._vertexBufferSize += 1;
  711. }
  712. if (!this._isBillboardBased) {
  713. this._vertexBufferSize += 3;
  714. }
  715. let engine = this._scene.getEngine();
  716. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  717. this._vertexBuffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  718. let dataOffset = 0;
  719. var positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  720. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  721. dataOffset += 3;
  722. var colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  723. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  724. dataOffset += 4;
  725. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  726. this._vertexBuffers["angle"] = options;
  727. dataOffset += 1;
  728. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  729. this._vertexBuffers["size"] = size;
  730. dataOffset += 2;
  731. if (this._isAnimationSheetEnabled) {
  732. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  733. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  734. dataOffset += 1;
  735. }
  736. if (!this._isBillboardBased) {
  737. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  738. this._vertexBuffers["direction"] = directionBuffer;
  739. dataOffset += 3;
  740. }
  741. var offsets: VertexBuffer;
  742. if (this._useInstancing) {
  743. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  744. this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
  745. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  746. } else {
  747. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  748. dataOffset += 2;
  749. }
  750. this._vertexBuffers["offset"] = offsets;
  751. }
  752. private _createIndexBuffer() {
  753. if (this._useInstancing) {
  754. return;
  755. }
  756. var indices = [];
  757. var index = 0;
  758. for (var count = 0; count < this._capacity; count++) {
  759. indices.push(index);
  760. indices.push(index + 1);
  761. indices.push(index + 2);
  762. indices.push(index);
  763. indices.push(index + 2);
  764. indices.push(index + 3);
  765. index += 4;
  766. }
  767. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  768. }
  769. /**
  770. * Gets the maximum number of particles active at the same time.
  771. * @returns The max number of active particles.
  772. */
  773. public getCapacity(): number {
  774. return this._capacity;
  775. }
  776. /**
  777. * Gets Wether there are still active particles in the system.
  778. * @returns True if it is alive, otherwise false.
  779. */
  780. public isAlive(): boolean {
  781. return this._alive;
  782. }
  783. /**
  784. * Gets Wether the system has been started.
  785. * @returns True if it has been started, otherwise false.
  786. */
  787. public isStarted(): boolean {
  788. return this._started;
  789. }
  790. /**
  791. * Starts the particle system and begins to emit
  792. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  793. */
  794. public start(delay = 0): void {
  795. if (delay) {
  796. setTimeout(()=> {
  797. this.start(0);
  798. }, delay);
  799. return;
  800. }
  801. this._started = true;
  802. this._stopped = false;
  803. this._actualFrame = 0;
  804. if (this.subEmitters && this.subEmitters.length != 0) {
  805. this.activeSubSystems = new Array<ParticleSystem>();
  806. }
  807. if (this.preWarmCycles) {
  808. for (var index = 0; index < this.preWarmCycles; index++) {
  809. this.animate(true);
  810. }
  811. }
  812. }
  813. /**
  814. * Stops the particle system.
  815. * @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.
  816. */
  817. public stop(stopSubEmitters = true): void {
  818. this._stopped = true;
  819. if (stopSubEmitters) {
  820. this._stopSubEmitters();
  821. }
  822. }
  823. // animation sheet
  824. /**
  825. * Remove all active particles
  826. */
  827. public reset(): void {
  828. this._stockParticles = [];
  829. this._particles = [];
  830. }
  831. /**
  832. * @hidden (for internal use only)
  833. */
  834. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  835. var offset = index * this._vertexBufferSize;
  836. this._vertexData[offset++] = particle.position.x;
  837. this._vertexData[offset++] = particle.position.y;
  838. this._vertexData[offset++] = particle.position.z;
  839. this._vertexData[offset++] = particle.color.r;
  840. this._vertexData[offset++] = particle.color.g;
  841. this._vertexData[offset++] = particle.color.b;
  842. this._vertexData[offset++] = particle.color.a;
  843. this._vertexData[offset++] = particle.angle;
  844. this._vertexData[offset++] = particle.scale.x * particle.size;
  845. this._vertexData[offset++] = particle.scale.y * particle.size;
  846. if (this._isAnimationSheetEnabled) {
  847. this._vertexData[offset++] = particle.cellIndex;
  848. }
  849. if (!this._isBillboardBased) {
  850. if (particle._initialDirection) {
  851. this._vertexData[offset++] = particle._initialDirection.x;
  852. this._vertexData[offset++] = particle._initialDirection.y;
  853. this._vertexData[offset++] = particle._initialDirection.z;
  854. } else {
  855. this._vertexData[offset++] = particle.direction.x;
  856. this._vertexData[offset++] = particle.direction.y;
  857. this._vertexData[offset++] = particle.direction.z;
  858. }
  859. }
  860. if (!this._useInstancing) {
  861. if (this._isAnimationSheetEnabled) {
  862. if (offsetX === 0)
  863. offsetX = this._epsilon;
  864. else if (offsetX === 1)
  865. offsetX = 1 - this._epsilon;
  866. if (offsetY === 0)
  867. offsetY = this._epsilon;
  868. else if (offsetY === 1)
  869. offsetY = 1 - this._epsilon;
  870. }
  871. this._vertexData[offset++] = offsetX;
  872. this._vertexData[offset++] = offsetY;
  873. }
  874. }
  875. // start of sub system methods
  876. /**
  877. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  878. * Its lifetime will start back at 0.
  879. */
  880. public recycleParticle: (particle: Particle) => void = (particle) => {
  881. var lastParticle = <Particle>this._particles.pop();
  882. if (lastParticle !== particle) {
  883. lastParticle.copyTo(particle);
  884. }
  885. this._stockParticles.push(lastParticle);
  886. };
  887. private _stopSubEmitters(): void {
  888. if (!this.activeSubSystems) {
  889. return;
  890. }
  891. this.activeSubSystems.forEach(subSystem => {
  892. subSystem.stop(true);
  893. });
  894. this.activeSubSystems = new Array<ParticleSystem>();
  895. }
  896. private _createParticle: () => Particle = () => {
  897. var particle: Particle;
  898. if (this._stockParticles.length !== 0) {
  899. particle = <Particle>this._stockParticles.pop();
  900. particle.age = 0;
  901. particle._currentColorGradient = null;
  902. particle.cellIndex = this.startSpriteCellID;
  903. } else {
  904. particle = new Particle(this);
  905. }
  906. return particle;
  907. }
  908. private _removeFromRoot(): void {
  909. if (!this._rootParticleSystem){
  910. return;
  911. }
  912. let index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  913. if (index !== -1) {
  914. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  915. }
  916. }
  917. private _emitFromParticle: (particle: Particle) => void = (particle) => {
  918. if (!this.subEmitters || this.subEmitters.length === 0) {
  919. return;
  920. }
  921. var templateIndex = Math.floor(Math.random() * this.subEmitters.length);
  922. var subSystem = this.subEmitters[templateIndex].clone(this.name + "_sub", particle.position.clone());
  923. subSystem._rootParticleSystem = this;
  924. this.activeSubSystems.push(subSystem);
  925. subSystem.start();
  926. }
  927. // End of sub system methods
  928. private _update(newParticles: number): void {
  929. // Update current
  930. this._alive = this._particles.length > 0;
  931. this.updateFunction(this._particles);
  932. // Add new ones
  933. var worldMatrix;
  934. if ((<AbstractMesh>this.emitter).position) {
  935. var emitterMesh = (<AbstractMesh>this.emitter);
  936. worldMatrix = emitterMesh.getWorldMatrix();
  937. } else {
  938. var emitterPosition = (<Vector3>this.emitter);
  939. worldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  940. }
  941. var particle: Particle;
  942. for (var index = 0; index < newParticles; index++) {
  943. if (this._particles.length === this._capacity) {
  944. break;
  945. }
  946. particle = this._createParticle();
  947. this._particles.push(particle);
  948. // Emitter
  949. let emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  950. if (this.startPositionFunction) {
  951. this.startPositionFunction(worldMatrix, particle.position, particle);
  952. }
  953. else {
  954. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  955. }
  956. if (this.startDirectionFunction) {
  957. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  958. }
  959. else {
  960. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  961. }
  962. if (emitPower === 0) {
  963. if (!particle._initialDirection) {
  964. particle._initialDirection = particle.direction.clone();
  965. } else {
  966. particle._initialDirection.copyFrom(particle.direction);
  967. }
  968. } else {
  969. particle._initialDirection = null;
  970. }
  971. particle.direction.scaleInPlace(emitPower);
  972. // Life time
  973. if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {
  974. let ratio = Scalar.Clamp(this._actualFrame / this.targetStopDuration);
  975. Tools.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient, scale) => {
  976. let factorGradient1 = (<FactorGradient>currentGradient);
  977. let factorGradient2 = (<FactorGradient>nextGradient);
  978. let lifeTime1 = factorGradient1.getFactor();
  979. let lifeTime2 = factorGradient2.getFactor();
  980. let gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  981. particle.lifeTime = Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  982. });
  983. } else {
  984. particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  985. }
  986. // Size
  987. if (!this._sizeGradients || this._sizeGradients.length === 0) {
  988. particle.size = Scalar.RandomRange(this.minSize, this.maxSize);
  989. } else {
  990. particle._currentSizeGradient = this._sizeGradients[0];
  991. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  992. particle.size = particle._currentSize1;
  993. if (this._sizeGradients.length > 1) {
  994. particle._currentSize2 = this._sizeGradients[1].getFactor();
  995. } else {
  996. particle._currentSize2 = particle._currentSize1;
  997. }
  998. }
  999. // Size and scale
  1000. particle.scale.copyFromFloats(Scalar.RandomRange(this.minScaleX, this.maxScaleX), Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  1001. // Angle
  1002. if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) {
  1003. particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  1004. } else {
  1005. particle._currentAngularSpeedGradient = this._angularSpeedGradients[0];
  1006. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  1007. particle._currentAngularSpeed1 = particle.angularSpeed;
  1008. if (this._angularSpeedGradients.length > 1) {
  1009. particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor();
  1010. } else {
  1011. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  1012. }
  1013. }
  1014. particle.angle = Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  1015. // Velocity
  1016. if (this._velocityGradients && this._velocityGradients.length > 0) {
  1017. particle._currentVelocityGradient = this._velocityGradients[0];
  1018. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  1019. if (this._velocityGradients.length > 1) {
  1020. particle._currentVelocity2 = this._velocityGradients[1].getFactor();
  1021. } else {
  1022. particle._currentVelocity2 = particle._currentVelocity1;
  1023. }
  1024. }
  1025. // Color
  1026. if (!this._colorGradients || this._colorGradients.length === 0) {
  1027. var step = Scalar.RandomRange(0, 1.0);
  1028. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  1029. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  1030. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  1031. } else {
  1032. particle._currentColorGradient = this._colorGradients[0];
  1033. particle._currentColorGradient.getColorToRef(particle.color);
  1034. particle._currentColor1.copyFrom(particle.color);
  1035. if (this._colorGradients.length > 1) {
  1036. this._colorGradients[1].getColorToRef(particle._currentColor2);
  1037. } else {
  1038. particle._currentColor2.copyFrom(particle.color);
  1039. }
  1040. }
  1041. // Sheet
  1042. if (this._isAnimationSheetEnabled) {
  1043. particle._initialStartSpriteCellID = this.startSpriteCellID;
  1044. particle._initialEndSpriteCellID = this.endSpriteCellID;
  1045. }
  1046. }
  1047. }
  1048. /** @hidden */
  1049. public static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false): string[] {
  1050. var attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
  1051. if (isAnimationSheetEnabled) {
  1052. attributeNamesOrOptions.push("cellIndex");
  1053. }
  1054. if (!isBillboardBased) {
  1055. attributeNamesOrOptions.push("direction");
  1056. }
  1057. return attributeNamesOrOptions;
  1058. }
  1059. public static _GetEffectCreationOptions(isAnimationSheetEnabled = false): string[] {
  1060. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  1061. if (isAnimationSheetEnabled) {
  1062. effectCreationOption.push("particlesInfos")
  1063. }
  1064. return effectCreationOption;
  1065. }
  1066. private _getEffect(): Effect {
  1067. if (this._customEffect) {
  1068. return this._customEffect;
  1069. };
  1070. var defines = [];
  1071. if (this._scene.clipPlane) {
  1072. defines.push("#define CLIPPLANE");
  1073. }
  1074. if (this._isAnimationSheetEnabled) {
  1075. defines.push("#define ANIMATESHEET");
  1076. }
  1077. if (this._isBillboardBased) {
  1078. defines.push("#define BILLBOARD");
  1079. switch (this.billboardMode) {
  1080. case AbstractMesh.BILLBOARDMODE_Y:
  1081. defines.push("#define BILLBOARDY");
  1082. break;
  1083. case AbstractMesh.BILLBOARDMODE_ALL:
  1084. default:
  1085. break;
  1086. }
  1087. }
  1088. // Effect
  1089. var join = defines.join("\n");
  1090. if (this._cachedDefines !== join) {
  1091. this._cachedDefines = join;
  1092. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  1093. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  1094. this._effect = this._scene.getEngine().createEffect(
  1095. "particles",
  1096. attributesNamesOrOptions,
  1097. effectCreationOption,
  1098. ["diffuseSampler"], join);
  1099. }
  1100. return this._effect;
  1101. }
  1102. /**
  1103. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  1104. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  1105. */
  1106. public animate(preWarmOnly = false): void {
  1107. if (!this._started)
  1108. return;
  1109. if (!preWarmOnly) {
  1110. var effect = this._getEffect();
  1111. // Check
  1112. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  1113. return;
  1114. if (this._currentRenderId === this._scene.getRenderId()) {
  1115. return;
  1116. }
  1117. this._currentRenderId = this._scene.getRenderId();
  1118. }
  1119. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  1120. // determine the number of particles we need to create
  1121. var newParticles;
  1122. if (this.manualEmitCount > -1) {
  1123. newParticles = this.manualEmitCount;
  1124. this._newPartsExcess = 0;
  1125. this.manualEmitCount = 0;
  1126. } else {
  1127. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  1128. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  1129. }
  1130. if (this._newPartsExcess > 1.0) {
  1131. newParticles += this._newPartsExcess >> 0;
  1132. this._newPartsExcess -= this._newPartsExcess >> 0;
  1133. }
  1134. this._alive = false;
  1135. if (!this._stopped) {
  1136. this._actualFrame += this._scaledUpdateSpeed;
  1137. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  1138. this.stop();
  1139. } else {
  1140. newParticles = 0;
  1141. }
  1142. this._update(newParticles);
  1143. // Stopped?
  1144. if (this._stopped) {
  1145. if (!this._alive) {
  1146. this._started = false;
  1147. if (this.onAnimationEnd) {
  1148. this.onAnimationEnd();
  1149. }
  1150. if (this.disposeOnStop) {
  1151. this._scene._toBeDisposed.push(this);
  1152. }
  1153. }
  1154. }
  1155. if (!preWarmOnly) {
  1156. // Update VBO
  1157. var offset = 0;
  1158. for (var index = 0; index < this._particles.length; index++) {
  1159. var particle = this._particles[index];
  1160. this._appendParticleVertices(offset, particle);
  1161. offset += this._useInstancing ? 1 : 4;
  1162. }
  1163. if (this._vertexBuffer) {
  1164. this._vertexBuffer.update(this._vertexData);
  1165. }
  1166. }
  1167. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  1168. this.stop();
  1169. }
  1170. }
  1171. private _appendParticleVertices(offset: number, particle: Particle) {
  1172. this._appendParticleVertex(offset++, particle, 0, 0);
  1173. if (!this._useInstancing) {
  1174. this._appendParticleVertex(offset++, particle, 1, 0);
  1175. this._appendParticleVertex(offset++, particle, 1, 1);
  1176. this._appendParticleVertex(offset++, particle, 0, 1);
  1177. }
  1178. }
  1179. /**
  1180. * Rebuilds the particle system.
  1181. */
  1182. public rebuild(): void {
  1183. this._createIndexBuffer();
  1184. if (this._vertexBuffer) {
  1185. this._vertexBuffer._rebuild();
  1186. }
  1187. }
  1188. /**
  1189. * Is this system ready to be used/rendered
  1190. * @return true if the system is ready
  1191. */
  1192. public isReady(): boolean {
  1193. var effect = this._getEffect();
  1194. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  1195. return false;
  1196. }
  1197. return true;
  1198. }
  1199. /**
  1200. * Renders the particle system in its current state.
  1201. * @returns the current number of particles
  1202. */
  1203. public render(): number {
  1204. var effect = this._getEffect();
  1205. // Check
  1206. if (!this.isReady() || !this._particles.length) {
  1207. return 0;
  1208. }
  1209. var engine = this._scene.getEngine();
  1210. // Render
  1211. engine.enableEffect(effect);
  1212. engine.setState(false);
  1213. var viewMatrix = this._scene.getViewMatrix();
  1214. effect.setTexture("diffuseSampler", this.particleTexture);
  1215. effect.setMatrix("view", viewMatrix);
  1216. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  1217. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1218. var baseSize = this.particleTexture.getBaseSize();
  1219. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  1220. }
  1221. effect.setVector2("translationPivot", this.translationPivot);
  1222. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  1223. if (this._isBillboardBased) {
  1224. var camera = this._scene.activeCamera!;
  1225. effect.setVector3("eyePosition", camera.globalPosition);
  1226. }
  1227. if (this._scene.clipPlane) {
  1228. var clipPlane = this._scene.clipPlane;
  1229. var invView = viewMatrix.clone();
  1230. invView.invert();
  1231. effect.setMatrix("invView", invView);
  1232. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  1233. }
  1234. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  1235. // Draw order
  1236. switch(this.blendMode)
  1237. {
  1238. case ParticleSystem.BLENDMODE_ADD:
  1239. engine.setAlphaMode(Engine.ALPHA_ADD);
  1240. break;
  1241. case ParticleSystem.BLENDMODE_ONEONE:
  1242. engine.setAlphaMode(Engine.ALPHA_ONEONE);
  1243. break;
  1244. case ParticleSystem.BLENDMODE_STANDARD:
  1245. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  1246. break;
  1247. }
  1248. if (this.forceDepthWrite) {
  1249. engine.setDepthWrite(true);
  1250. }
  1251. if (this._useInstancing) {
  1252. engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  1253. engine.unbindInstanceAttributes();
  1254. } else {
  1255. engine.drawElementsType(Material.TriangleFillMode, 0, this._particles.length * 6);
  1256. }
  1257. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  1258. return this._particles.length;
  1259. }
  1260. /**
  1261. * Disposes the particle system and free the associated resources
  1262. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1263. */
  1264. public dispose(disposeTexture = true): void {
  1265. if (this._vertexBuffer) {
  1266. this._vertexBuffer.dispose();
  1267. this._vertexBuffer = null;
  1268. }
  1269. if (this._spriteBuffer) {
  1270. this._spriteBuffer.dispose();
  1271. this._spriteBuffer = null;
  1272. }
  1273. if (this._indexBuffer) {
  1274. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  1275. this._indexBuffer = null;
  1276. }
  1277. if (disposeTexture && this.particleTexture) {
  1278. this.particleTexture.dispose();
  1279. this.particleTexture = null;
  1280. }
  1281. this._removeFromRoot();
  1282. // Remove from scene
  1283. var index = this._scene.particleSystems.indexOf(this);
  1284. if (index > -1) {
  1285. this._scene.particleSystems.splice(index, 1);
  1286. }
  1287. // Callback
  1288. this.onDisposeObservable.notifyObservers(this);
  1289. this.onDisposeObservable.clear();
  1290. }
  1291. /**
  1292. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  1293. * @param radius The radius of the sphere to emit from
  1294. * @returns the emitter
  1295. */
  1296. public createSphereEmitter(radius = 1): SphereParticleEmitter {
  1297. var particleEmitter = new SphereParticleEmitter(radius);
  1298. this.particleEmitterType = particleEmitter;
  1299. return particleEmitter;
  1300. }
  1301. /**
  1302. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  1303. * @param radius The radius of the sphere to emit from
  1304. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  1305. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  1306. * @returns the emitter
  1307. */
  1308. public createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)): SphereDirectedParticleEmitter {
  1309. var particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2)
  1310. this.particleEmitterType = particleEmitter;
  1311. return particleEmitter;
  1312. }
  1313. /**
  1314. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  1315. * @param radius The radius of the cone to emit from
  1316. * @param angle The base angle of the cone
  1317. * @returns the emitter
  1318. */
  1319. public createConeEmitter(radius = 1, angle = Math.PI / 4): ConeParticleEmitter {
  1320. var particleEmitter = new ConeParticleEmitter(radius, angle);
  1321. this.particleEmitterType = particleEmitter;
  1322. return particleEmitter;
  1323. }
  1324. // 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.
  1325. /**
  1326. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  1327. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  1328. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  1329. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  1330. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  1331. * @returns the emitter
  1332. */
  1333. public createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter {
  1334. var particleEmitter = new BoxParticleEmitter();
  1335. this.particleEmitterType = particleEmitter;
  1336. this.direction1 = direction1;
  1337. this.direction2 = direction2;
  1338. this.minEmitBox = minEmitBox;
  1339. this.maxEmitBox = maxEmitBox;
  1340. return particleEmitter;
  1341. }
  1342. // Clone
  1343. /**
  1344. * Clones the particle system.
  1345. * @param name The name of the cloned object
  1346. * @param newEmitter The new emitter to use
  1347. * @returns the cloned particle system
  1348. */
  1349. public clone(name: string, newEmitter: any): ParticleSystem {
  1350. var custom: Nullable<Effect> = null;
  1351. var program: any = null;
  1352. if (this.customShader != null) {
  1353. program = this.customShader;
  1354. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1355. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1356. } else if (this._customEffect) {
  1357. custom = this._customEffect;
  1358. }
  1359. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  1360. result.customShader = program;
  1361. Tools.DeepCopy(this, result, ["particles", "customShader"]);
  1362. if (newEmitter === undefined) {
  1363. newEmitter = this.emitter;
  1364. }
  1365. result.emitter = newEmitter;
  1366. if (this.particleTexture) {
  1367. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1368. }
  1369. if (!this.preventAutoStart) {
  1370. result.start();
  1371. }
  1372. return result;
  1373. }
  1374. /**
  1375. * Serializes the particle system to a JSON object.
  1376. * @returns the JSON object
  1377. */
  1378. public serialize(): any {
  1379. var serializationObject: any = {};
  1380. ParticleSystem._Serialize(serializationObject, this);
  1381. serializationObject.textureMask = this.textureMask.asArray();
  1382. serializationObject.customShader = this.customShader;
  1383. serializationObject.preventAutoStart = this.preventAutoStart;
  1384. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  1385. return serializationObject;
  1386. }
  1387. /** @hidden */
  1388. public static _Serialize(serializationObject: any, particleSystem: IParticleSystem) {
  1389. serializationObject.name = particleSystem.name;
  1390. serializationObject.id = particleSystem.id;
  1391. serializationObject.capacity = particleSystem.getCapacity();
  1392. // Emitter
  1393. if ((<AbstractMesh>particleSystem.emitter).position) {
  1394. var emitterMesh = (<AbstractMesh>particleSystem.emitter);
  1395. serializationObject.emitterId = emitterMesh.id;
  1396. } else {
  1397. var emitterPosition = (<Vector3>particleSystem.emitter);
  1398. serializationObject.emitter = emitterPosition.asArray();
  1399. }
  1400. // Emitter
  1401. if (particleSystem.particleEmitterType) {
  1402. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  1403. }
  1404. if (particleSystem.particleTexture) {
  1405. serializationObject.textureName = particleSystem.particleTexture.name;
  1406. }
  1407. // Animations
  1408. Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  1409. // Particle system
  1410. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  1411. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  1412. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  1413. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  1414. serializationObject.minSize = particleSystem.minSize;
  1415. serializationObject.maxSize = particleSystem.maxSize;
  1416. serializationObject.minScaleX = particleSystem.minScaleX;
  1417. serializationObject.maxScaleX = particleSystem.maxScaleX;
  1418. serializationObject.minScaleY = particleSystem.minScaleY;
  1419. serializationObject.maxScaleY = particleSystem.maxScaleY;
  1420. serializationObject.minEmitPower = particleSystem.minEmitPower;
  1421. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  1422. serializationObject.minLifeTime = particleSystem.minLifeTime;
  1423. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  1424. serializationObject.emitRate = particleSystem.emitRate;
  1425. serializationObject.gravity = particleSystem.gravity.asArray();
  1426. serializationObject.color1 = particleSystem.color1.asArray();
  1427. serializationObject.color2 = particleSystem.color2.asArray();
  1428. serializationObject.colorDead = particleSystem.colorDead.asArray();
  1429. serializationObject.updateSpeed = particleSystem.updateSpeed;
  1430. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  1431. serializationObject.blendMode = particleSystem.blendMode;
  1432. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  1433. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  1434. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  1435. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  1436. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  1437. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  1438. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  1439. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  1440. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  1441. let colorGradients = particleSystem.getColorGradients();
  1442. if (colorGradients) {
  1443. serializationObject.colorGradients = [];
  1444. for (var colorGradient of colorGradients) {
  1445. var serializedGradient: any = {
  1446. gradient: colorGradient.gradient,
  1447. color1: colorGradient.color1.asArray()
  1448. };
  1449. if (colorGradient.color2) {
  1450. serializedGradient.color2 = colorGradient.color2.asArray();
  1451. }
  1452. serializationObject.colorGradients.push(serializedGradient);
  1453. }
  1454. }
  1455. let sizeGradients = particleSystem.getSizeGradients();
  1456. if (sizeGradients) {
  1457. serializationObject.sizeGradients = [];
  1458. for (var sizeGradient of sizeGradients) {
  1459. var serializedGradient: any = {
  1460. gradient: sizeGradient.gradient,
  1461. factor1: sizeGradient.factor1
  1462. };
  1463. if (sizeGradient.factor2 !== undefined) {
  1464. serializedGradient.factor2 = sizeGradient.factor2;
  1465. }
  1466. serializationObject.sizeGradients.push(serializedGradient);
  1467. }
  1468. }
  1469. let angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  1470. if (angularSpeedGradients) {
  1471. serializationObject.angularSpeedGradients = [];
  1472. for (var angularSpeedGradient of angularSpeedGradients) {
  1473. var serializedGradient: any = {
  1474. gradient: angularSpeedGradient.gradient,
  1475. factor1: angularSpeedGradient.factor1
  1476. };
  1477. if (angularSpeedGradient.factor2 !== undefined) {
  1478. serializedGradient.factor2 = angularSpeedGradient.factor2;
  1479. }
  1480. serializationObject.angularSpeedGradients.push(serializedGradient);
  1481. }
  1482. }
  1483. let velocityGradients = particleSystem.getVelocityGradients();
  1484. if (velocityGradients) {
  1485. serializationObject.velocityGradients = [];
  1486. for (var velocityGradient of velocityGradients) {
  1487. var serializedGradient: any = {
  1488. gradient: velocityGradient.gradient,
  1489. factor1: velocityGradient.factor1
  1490. };
  1491. if (velocityGradient.factor2 !== undefined) {
  1492. serializedGradient.factor2 = velocityGradient.factor2;
  1493. }
  1494. serializationObject.velocityGradients.push(serializedGradient);
  1495. }
  1496. }
  1497. }
  1498. /** @hidden */
  1499. public static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string) {
  1500. // Texture
  1501. if (parsedParticleSystem.textureName) {
  1502. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  1503. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  1504. }
  1505. // Emitter
  1506. if (parsedParticleSystem.emitterId === undefined) {
  1507. particleSystem.emitter = Vector3.Zero();
  1508. }
  1509. else if (parsedParticleSystem.emitterId) {
  1510. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  1511. } else {
  1512. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  1513. }
  1514. // Misc.
  1515. if (parsedParticleSystem.renderingGroupId !== undefined) {
  1516. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  1517. }
  1518. if (parsedParticleSystem.isBillboardBased !== undefined) {
  1519. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  1520. }
  1521. // Animations
  1522. if (parsedParticleSystem.animations) {
  1523. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  1524. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  1525. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  1526. }
  1527. }
  1528. if (parsedParticleSystem.autoAnimate) {
  1529. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  1530. }
  1531. // Particle system
  1532. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  1533. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  1534. particleSystem.minSize = parsedParticleSystem.minSize;
  1535. particleSystem.maxSize = parsedParticleSystem.maxSize;
  1536. if (parsedParticleSystem.minScaleX) {
  1537. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  1538. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  1539. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  1540. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  1541. }
  1542. if (parsedParticleSystem.preWarmCycles !== undefined) {
  1543. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  1544. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  1545. }
  1546. if (parsedParticleSystem.minInitialRotation !== undefined) {
  1547. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  1548. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  1549. }
  1550. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  1551. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  1552. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  1553. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  1554. particleSystem.emitRate = parsedParticleSystem.emitRate;
  1555. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  1556. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  1557. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  1558. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  1559. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  1560. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  1561. particleSystem.blendMode = parsedParticleSystem.blendMode;
  1562. if (parsedParticleSystem.colorGradients) {
  1563. for (var colorGradient of parsedParticleSystem.colorGradients) {
  1564. particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined);
  1565. }
  1566. }
  1567. if (parsedParticleSystem.sizeGradients) {
  1568. for (var sizeGradient of parsedParticleSystem.sizeGradients) {
  1569. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  1570. }
  1571. }
  1572. if (parsedParticleSystem.angularSpeedGradients) {
  1573. for (var angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) {
  1574. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  1575. }
  1576. }
  1577. if (parsedParticleSystem.velocityGradients) {
  1578. for (var velocityGradient of parsedParticleSystem.velocityGradients) {
  1579. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  1580. }
  1581. }
  1582. // Emitter
  1583. let emitterType: IParticleEmitterType;
  1584. if (parsedParticleSystem.particleEmitterType) {
  1585. switch (parsedParticleSystem.particleEmitterType.type) {
  1586. case "SphereParticleEmitter":
  1587. emitterType = new SphereParticleEmitter();
  1588. break;
  1589. case "SphereDirectedParticleEmitter":
  1590. emitterType = new SphereDirectedParticleEmitter();
  1591. break;
  1592. case "ConeEmitter":
  1593. case "ConeParticleEmitter":
  1594. emitterType = new ConeParticleEmitter();
  1595. break;
  1596. case "BoxEmitter":
  1597. case "BoxParticleEmitter":
  1598. default:
  1599. emitterType = new BoxParticleEmitter();
  1600. break;
  1601. }
  1602. emitterType.parse(parsedParticleSystem.particleEmitterType);
  1603. } else {
  1604. emitterType = new BoxParticleEmitter();
  1605. emitterType.parse(parsedParticleSystem);
  1606. }
  1607. particleSystem.particleEmitterType = emitterType;
  1608. // Animation sheet
  1609. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  1610. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  1611. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  1612. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  1613. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  1614. }
  1615. /**
  1616. * Parses a JSON object to create a particle system.
  1617. * @param parsedParticleSystem The JSON object to parse
  1618. * @param scene The scene to create the particle system in
  1619. * @param rootUrl The root url to use to load external dependencies like texture
  1620. * @returns the Parsed particle system
  1621. */
  1622. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem {
  1623. var name = parsedParticleSystem.name;
  1624. var custom: Nullable<Effect> = null;
  1625. var program: any = null;
  1626. if (parsedParticleSystem.customShader) {
  1627. program = parsedParticleSystem.customShader;
  1628. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1629. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1630. }
  1631. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  1632. particleSystem.customShader = program;
  1633. if (parsedParticleSystem.id) {
  1634. particleSystem.id = parsedParticleSystem.id;
  1635. }
  1636. // Auto start
  1637. if (parsedParticleSystem.preventAutoStart) {
  1638. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  1639. }
  1640. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  1641. particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
  1642. if (!particleSystem.preventAutoStart) {
  1643. particleSystem.start();
  1644. }
  1645. return particleSystem;
  1646. }
  1647. }
  1648. }