particleSystem.ts 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588
  1. import { Nullable } from "../types";
  2. import { IAnimatable } from "../Misc/tools";
  3. import { FactorGradient, ColorGradient, Color3Gradient, GradientHelper } from "../Misc/gradients";
  4. import { Observable, Observer } from "../Misc/observable";
  5. import { Color4, Color3, Vector3, Matrix, Tmp, ISize, Vector4 } from "../Maths/math";
  6. import { Scalar } from "../Maths/math.scalar";
  7. import { VertexBuffer } from "../Meshes/buffer";
  8. import { Buffer } from "../Meshes/buffer";
  9. import { AbstractMesh } from "../Meshes/abstractMesh";
  10. import { Material } from "../Materials/material";
  11. import { MaterialHelper } from "../Materials/materialHelper";
  12. import { Effect } from "../Materials/effect";
  13. import { ImageProcessingConfiguration } from "../Materials/imageProcessingConfiguration";
  14. import { Texture } from "../Materials/Textures/texture";
  15. import { RawTexture } from "../Materials/Textures/rawTexture";
  16. import { ProceduralTexture } from "../Materials/Textures/Procedurals/proceduralTexture";
  17. import { EngineStore } from "../Engines/engineStore";
  18. import { Scene, IDisposable } from "../scene";
  19. import { BoxParticleEmitter, IParticleEmitterType, HemisphericParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CylinderParticleEmitter, ConeParticleEmitter } from "../Particles/EmitterTypes/index";
  20. import { IParticleSystem } from "./IParticleSystem";
  21. import { BaseParticleSystem } from "./baseParticleSystem";
  22. import { Particle } from "./particle";
  23. import { SubEmitter, SubEmitterType } from "./subEmitter";
  24. import { Constants } from "../Engines/constants";
  25. import { SerializationHelper } from "../Misc/decorators";
  26. import { DeepCopier } from "../Misc/deepCopier";
  27. import { _TypeStore } from '../Misc/typeStore';
  28. import "../Shaders/particles.fragment";
  29. import "../Shaders/particles.vertex";
  30. import { DataBuffer } from '../Meshes/dataBuffer';
  31. /**
  32. * This represents a particle system in Babylon.
  33. * 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.
  34. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  35. * @example https://doc.babylonjs.com/babylon101/particles
  36. */
  37. export class ParticleSystem extends BaseParticleSystem implements IDisposable, IAnimatable, IParticleSystem {
  38. /**
  39. * Billboard mode will only apply to Y axis
  40. */
  41. public static readonly BILLBOARDMODE_Y = Constants.PARTICLES_BILLBOARDMODE_Y;
  42. /**
  43. * Billboard mode will apply to all axes
  44. */
  45. public static readonly BILLBOARDMODE_ALL = Constants.PARTICLES_BILLBOARDMODE_ALL;
  46. /**
  47. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  48. */
  49. public static readonly BILLBOARDMODE_STRETCHED = Constants.PARTICLES_BILLBOARDMODE_STRETCHED;
  50. /**
  51. * This function can be defined to provide custom update for active particles.
  52. * This function will be called instead of regular update (age, position, color, etc.).
  53. * Do not forget that this function will be called on every frame so try to keep it simple and fast :)
  54. */
  55. public updateFunction: (particles: Particle[]) => void;
  56. private _emitterWorldMatrix: Matrix;
  57. /**
  58. * This function can be defined to specify initial direction for every new particle.
  59. * It by default use the emitterType defined function
  60. */
  61. public startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void;
  62. /**
  63. * This function can be defined to specify initial position for every new particle.
  64. * It by default use the emitterType defined function
  65. */
  66. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void;
  67. /**
  68. * @hidden
  69. */
  70. public _inheritedVelocityOffset = new Vector3();
  71. /**
  72. * An event triggered when the system is disposed
  73. */
  74. public onDisposeObservable = new Observable<ParticleSystem>();
  75. private _onDisposeObserver: Nullable<Observer<ParticleSystem>>;
  76. /**
  77. * Sets a callback that will be triggered when the system is disposed
  78. */
  79. public set onDispose(callback: () => void) {
  80. if (this._onDisposeObserver) {
  81. this.onDisposeObservable.remove(this._onDisposeObserver);
  82. }
  83. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84. }
  85. private _particles = new Array<Particle>();
  86. private _epsilon: number;
  87. private _capacity: number;
  88. private _stockParticles = new Array<Particle>();
  89. private _newPartsExcess = 0;
  90. private _vertexData: Float32Array;
  91. private _vertexBuffer: Nullable<Buffer>;
  92. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  93. private _spriteBuffer: Nullable<Buffer>;
  94. private _indexBuffer: Nullable<DataBuffer>;
  95. private _effect: Effect;
  96. private _customEffect: Nullable<Effect>;
  97. private _cachedDefines: string;
  98. private _scaledColorStep = new Color4(0, 0, 0, 0);
  99. private _colorDiff = new Color4(0, 0, 0, 0);
  100. private _scaledDirection = Vector3.Zero();
  101. private _scaledGravity = Vector3.Zero();
  102. private _currentRenderId = -1;
  103. private _alive: boolean;
  104. private _useInstancing = false;
  105. private _started = false;
  106. private _stopped = false;
  107. private _actualFrame = 0;
  108. private _scaledUpdateSpeed: number;
  109. private _vertexBufferSize: number;
  110. /** @hidden */
  111. public _currentEmitRateGradient: Nullable<FactorGradient>;
  112. /** @hidden */
  113. public _currentEmitRate1 = 0;
  114. /** @hidden */
  115. public _currentEmitRate2 = 0;
  116. /** @hidden */
  117. public _currentStartSizeGradient: Nullable<FactorGradient>;
  118. /** @hidden */
  119. public _currentStartSize1 = 0;
  120. /** @hidden */
  121. public _currentStartSize2 = 0;
  122. private readonly _rawTextureWidth = 256;
  123. private _rampGradientsTexture: Nullable<RawTexture>;
  124. private _useRampGradients = false;
  125. /** Gets or sets a boolean indicating that ramp gradients must be used
  126. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  127. */
  128. public get useRampGradients(): boolean {
  129. return this._useRampGradients;
  130. }
  131. public set useRampGradients(value: boolean) {
  132. if (this._useRampGradients === value) {
  133. return;
  134. }
  135. this._useRampGradients = value;
  136. this._resetEffect();
  137. }
  138. // Sub-emitters
  139. /**
  140. * The Sub-emitters templates that will be used to generate the sub particle system to be associated with the system, this property is used by the root particle system only.
  141. * When a particle is spawned, an array will be chosen at random and all the emitters in that array will be attached to the particle. (Default: [])
  142. */
  143. public subEmitters: Array<ParticleSystem | SubEmitter | Array<SubEmitter>>;
  144. // the subEmitters field above converted to a constant type
  145. private _subEmitters: Array<Array<SubEmitter>>;
  146. /**
  147. * @hidden
  148. * If the particle systems emitter should be disposed when the particle system is disposed
  149. */
  150. public _disposeEmitterOnDispose = false;
  151. /**
  152. * The current active Sub-systems, this property is used by the root particle system only.
  153. */
  154. public activeSubSystems: Array<ParticleSystem>;
  155. private _rootParticleSystem: Nullable<ParticleSystem>;
  156. //end of Sub-emitter
  157. /**
  158. * Gets the current list of active particles
  159. */
  160. public get particles(): Particle[] {
  161. return this._particles;
  162. }
  163. /**
  164. * Returns the string "ParticleSystem"
  165. * @returns a string containing the class name
  166. */
  167. public getClassName(): string {
  168. return "ParticleSystem";
  169. }
  170. /**
  171. * Instantiates a particle system.
  172. * 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.
  173. * @param name The name of the particle system
  174. * @param capacity The max number of particles alive at the same time
  175. * @param scene The scene the particle system belongs to
  176. * @param customEffect a custom effect used to change the way particles are rendered by default
  177. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  178. * @param epsilon Offset used to render the particles
  179. */
  180. constructor(name: string, capacity: number, scene: Scene, customEffect: Nullable<Effect> = null, isAnimationSheetEnabled: boolean = false, epsilon: number = 0.01) {
  181. super(name);
  182. this._capacity = capacity;
  183. this._epsilon = epsilon;
  184. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  185. this._scene = scene || EngineStore.LastCreatedScene;
  186. // Setup the default processing configuration to the scene.
  187. this._attachImageProcessingConfiguration(null);
  188. this._customEffect = customEffect;
  189. this._scene.particleSystems.push(this);
  190. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  191. this._createIndexBuffer();
  192. this._createVertexBuffers();
  193. // Default emitter type
  194. this.particleEmitterType = new BoxParticleEmitter();
  195. // Update
  196. this.updateFunction = (particles: Particle[]): void => {
  197. let noiseTextureSize: Nullable<ISize> = null;
  198. let noiseTextureData: Nullable<Uint8Array> = null;
  199. if (this.noiseTexture) { // We need to get texture data back to CPU
  200. noiseTextureSize = this.noiseTexture.getSize();
  201. noiseTextureData = <Nullable<Uint8Array>>(this.noiseTexture.getContent());
  202. }
  203. for (var index = 0; index < particles.length; index++) {
  204. var particle = particles[index];
  205. let scaledUpdateSpeed = this._scaledUpdateSpeed;
  206. let previousAge = particle.age;
  207. particle.age += scaledUpdateSpeed;
  208. // Evaluate step to death
  209. if (particle.age > particle.lifeTime) {
  210. let diff = particle.age - previousAge;
  211. let oldDiff = particle.lifeTime - previousAge;
  212. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  213. particle.age = particle.lifeTime;
  214. }
  215. let ratio = particle.age / particle.lifeTime;
  216. // Color
  217. if (this._colorGradients && this._colorGradients.length > 0) {
  218. GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  219. if (currentGradient !== particle._currentColorGradient) {
  220. particle._currentColor1.copyFrom(particle._currentColor2);
  221. (<ColorGradient>nextGradient).getColorToRef(particle._currentColor2);
  222. particle._currentColorGradient = (<ColorGradient>currentGradient);
  223. }
  224. Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  225. });
  226. }
  227. else {
  228. particle.colorStep.scaleToRef(scaledUpdateSpeed, this._scaledColorStep);
  229. particle.color.addInPlace(this._scaledColorStep);
  230. if (particle.color.a < 0) {
  231. particle.color.a = 0;
  232. }
  233. }
  234. // Angular speed
  235. if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) {
  236. GradientHelper.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => {
  237. if (currentGradient !== particle._currentAngularSpeedGradient) {
  238. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  239. particle._currentAngularSpeed2 = (<FactorGradient>nextGradient).getFactor();
  240. particle._currentAngularSpeedGradient = (<FactorGradient>currentGradient);
  241. }
  242. particle.angularSpeed = Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  243. });
  244. }
  245. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  246. // Direction
  247. let directionScale = scaledUpdateSpeed;
  248. /// Velocity
  249. if (this._velocityGradients && this._velocityGradients.length > 0) {
  250. GradientHelper.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => {
  251. if (currentGradient !== particle._currentVelocityGradient) {
  252. particle._currentVelocity1 = particle._currentVelocity2;
  253. particle._currentVelocity2 = (<FactorGradient>nextGradient).getFactor();
  254. particle._currentVelocityGradient = (<FactorGradient>currentGradient);
  255. }
  256. directionScale *= Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  257. });
  258. }
  259. particle.direction.scaleToRef(directionScale, this._scaledDirection);
  260. /// Limit velocity
  261. if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
  262. GradientHelper.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => {
  263. if (currentGradient !== particle._currentLimitVelocityGradient) {
  264. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  265. particle._currentLimitVelocity2 = (<FactorGradient>nextGradient).getFactor();
  266. particle._currentLimitVelocityGradient = (<FactorGradient>currentGradient);
  267. }
  268. let limitVelocity = Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  269. let currentVelocity = particle.direction.length();
  270. if (currentVelocity > limitVelocity) {
  271. particle.direction.scaleInPlace(this.limitVelocityDamping);
  272. }
  273. });
  274. }
  275. /// Drag
  276. if (this._dragGradients && this._dragGradients.length > 0) {
  277. GradientHelper.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => {
  278. if (currentGradient !== particle._currentDragGradient) {
  279. particle._currentDrag1 = particle._currentDrag2;
  280. particle._currentDrag2 = (<FactorGradient>nextGradient).getFactor();
  281. particle._currentDragGradient = (<FactorGradient>currentGradient);
  282. }
  283. let drag = Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  284. this._scaledDirection.scaleInPlace(1.0 - drag);
  285. });
  286. }
  287. particle.position.addInPlace(this._scaledDirection);
  288. // Noise
  289. if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) {
  290. let fetchedColorR = this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  291. let fetchedColorG = this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  292. let fetchedColorB = this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  293. let force = Tmp.Vector3[0];
  294. let scaledForce = Tmp.Vector3[1];
  295. force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z);
  296. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  297. particle.direction.addInPlace(scaledForce);
  298. }
  299. // Gravity
  300. this.gravity.scaleToRef(scaledUpdateSpeed, this._scaledGravity);
  301. particle.direction.addInPlace(this._scaledGravity);
  302. // Size
  303. if (this._sizeGradients && this._sizeGradients.length > 0) {
  304. GradientHelper.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {
  305. if (currentGradient !== particle._currentSizeGradient) {
  306. particle._currentSize1 = particle._currentSize2;
  307. particle._currentSize2 = (<FactorGradient>nextGradient).getFactor();
  308. particle._currentSizeGradient = (<FactorGradient>currentGradient);
  309. }
  310. particle.size = Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  311. });
  312. }
  313. // Remap data
  314. if (this._useRampGradients) {
  315. if (this._colorRemapGradients && this._colorRemapGradients.length > 0) {
  316. GradientHelper.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => {
  317. let min = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  318. let max = Scalar.Lerp((<FactorGradient>currentGradient).factor2!, (<FactorGradient>nextGradient).factor2!, scale);
  319. particle.remapData.x = min;
  320. particle.remapData.y = max - min;
  321. });
  322. }
  323. if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) {
  324. GradientHelper.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => {
  325. let min = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  326. let max = Scalar.Lerp((<FactorGradient>currentGradient).factor2!, (<FactorGradient>nextGradient).factor2!, scale);
  327. particle.remapData.z = min;
  328. particle.remapData.w = max - min;
  329. });
  330. }
  331. }
  332. if (this._isAnimationSheetEnabled) {
  333. particle.updateCellIndex();
  334. }
  335. // Update the position of the attached sub-emitters to match their attached particle
  336. particle._inheritParticleInfoToSubEmitters();
  337. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  338. this._emitFromParticle(particle);
  339. if (particle._attachedSubEmitters) {
  340. particle._attachedSubEmitters.forEach((subEmitter) => {
  341. subEmitter.particleSystem.disposeOnStop = true;
  342. subEmitter.particleSystem.stop();
  343. });
  344. particle._attachedSubEmitters = null;
  345. }
  346. this.recycleParticle(particle);
  347. index--;
  348. continue;
  349. }
  350. }
  351. };
  352. }
  353. private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number, factor2?: number) {
  354. let newGradient = new FactorGradient();
  355. newGradient.gradient = gradient;
  356. newGradient.factor1 = factor;
  357. newGradient.factor2 = factor2;
  358. factorGradients.push(newGradient);
  359. factorGradients.sort((a, b) => {
  360. if (a.gradient < b.gradient) {
  361. return -1;
  362. } else if (a.gradient > b.gradient) {
  363. return 1;
  364. }
  365. return 0;
  366. });
  367. }
  368. private _removeFactorGradient(factorGradients: Nullable<FactorGradient[]>, gradient: number) {
  369. if (!factorGradients) {
  370. return;
  371. }
  372. let index = 0;
  373. for (var factorGradient of factorGradients) {
  374. if (factorGradient.gradient === gradient) {
  375. factorGradients.splice(index, 1);
  376. break;
  377. }
  378. index++;
  379. }
  380. }
  381. /**
  382. * Adds a new life time gradient
  383. * @param gradient defines the gradient to use (between 0 and 1)
  384. * @param factor defines the life time factor to affect to the specified gradient
  385. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  386. * @returns the current particle system
  387. */
  388. public addLifeTimeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  389. if (!this._lifeTimeGradients) {
  390. this._lifeTimeGradients = [];
  391. }
  392. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  393. return this;
  394. }
  395. /**
  396. * Remove a specific life time gradient
  397. * @param gradient defines the gradient to remove
  398. * @returns the current particle system
  399. */
  400. public removeLifeTimeGradient(gradient: number): IParticleSystem {
  401. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  402. return this;
  403. }
  404. /**
  405. * Adds a new size gradient
  406. * @param gradient defines the gradient to use (between 0 and 1)
  407. * @param factor defines the size factor to affect to the specified gradient
  408. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  409. * @returns the current particle system
  410. */
  411. public addSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  412. if (!this._sizeGradients) {
  413. this._sizeGradients = [];
  414. }
  415. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  416. return this;
  417. }
  418. /**
  419. * Remove a specific size gradient
  420. * @param gradient defines the gradient to remove
  421. * @returns the current particle system
  422. */
  423. public removeSizeGradient(gradient: number): IParticleSystem {
  424. this._removeFactorGradient(this._sizeGradients, gradient);
  425. return this;
  426. }
  427. /**
  428. * Adds a new color remap gradient
  429. * @param gradient defines the gradient to use (between 0 and 1)
  430. * @param min defines the color remap minimal range
  431. * @param max defines the color remap maximal range
  432. * @returns the current particle system
  433. */
  434. public addColorRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
  435. if (!this._colorRemapGradients) {
  436. this._colorRemapGradients = [];
  437. }
  438. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  439. return this;
  440. }
  441. /**
  442. * Remove a specific color remap gradient
  443. * @param gradient defines the gradient to remove
  444. * @returns the current particle system
  445. */
  446. public removeColorRemapGradient(gradient: number): IParticleSystem {
  447. this._removeFactorGradient(this._colorRemapGradients, gradient);
  448. return this;
  449. }
  450. /**
  451. * Adds a new alpha remap gradient
  452. * @param gradient defines the gradient to use (between 0 and 1)
  453. * @param min defines the alpha remap minimal range
  454. * @param max defines the alpha remap maximal range
  455. * @returns the current particle system
  456. */
  457. public addAlphaRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
  458. if (!this._alphaRemapGradients) {
  459. this._alphaRemapGradients = [];
  460. }
  461. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  462. return this;
  463. }
  464. /**
  465. * Remove a specific alpha remap gradient
  466. * @param gradient defines the gradient to remove
  467. * @returns the current particle system
  468. */
  469. public removeAlphaRemapGradient(gradient: number): IParticleSystem {
  470. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  471. return this;
  472. }
  473. /**
  474. * Adds a new angular speed gradient
  475. * @param gradient defines the gradient to use (between 0 and 1)
  476. * @param factor defines the angular speed to affect to the specified gradient
  477. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  478. * @returns the current particle system
  479. */
  480. public addAngularSpeedGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  481. if (!this._angularSpeedGradients) {
  482. this._angularSpeedGradients = [];
  483. }
  484. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  485. return this;
  486. }
  487. /**
  488. * Remove a specific angular speed gradient
  489. * @param gradient defines the gradient to remove
  490. * @returns the current particle system
  491. */
  492. public removeAngularSpeedGradient(gradient: number): IParticleSystem {
  493. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  494. return this;
  495. }
  496. /**
  497. * Adds a new velocity gradient
  498. * @param gradient defines the gradient to use (between 0 and 1)
  499. * @param factor defines the velocity to affect to the specified gradient
  500. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  501. * @returns the current particle system
  502. */
  503. public addVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  504. if (!this._velocityGradients) {
  505. this._velocityGradients = [];
  506. }
  507. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  508. return this;
  509. }
  510. /**
  511. * Remove a specific velocity gradient
  512. * @param gradient defines the gradient to remove
  513. * @returns the current particle system
  514. */
  515. public removeVelocityGradient(gradient: number): IParticleSystem {
  516. this._removeFactorGradient(this._velocityGradients, gradient);
  517. return this;
  518. }
  519. /**
  520. * Adds a new limit velocity gradient
  521. * @param gradient defines the gradient to use (between 0 and 1)
  522. * @param factor defines the limit velocity value to affect to the specified gradient
  523. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  524. * @returns the current particle system
  525. */
  526. public addLimitVelocityGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  527. if (!this._limitVelocityGradients) {
  528. this._limitVelocityGradients = [];
  529. }
  530. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  531. return this;
  532. }
  533. /**
  534. * Remove a specific limit velocity gradient
  535. * @param gradient defines the gradient to remove
  536. * @returns the current particle system
  537. */
  538. public removeLimitVelocityGradient(gradient: number): IParticleSystem {
  539. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  540. return this;
  541. }
  542. /**
  543. * Adds a new drag gradient
  544. * @param gradient defines the gradient to use (between 0 and 1)
  545. * @param factor defines the drag value to affect to the specified gradient
  546. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  547. * @returns the current particle system
  548. */
  549. public addDragGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  550. if (!this._dragGradients) {
  551. this._dragGradients = [];
  552. }
  553. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  554. return this;
  555. }
  556. /**
  557. * Remove a specific drag gradient
  558. * @param gradient defines the gradient to remove
  559. * @returns the current particle system
  560. */
  561. public removeDragGradient(gradient: number): IParticleSystem {
  562. this._removeFactorGradient(this._dragGradients, gradient);
  563. return this;
  564. }
  565. /**
  566. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  567. * @param gradient defines the gradient to use (between 0 and 1)
  568. * @param factor defines the emit rate value to affect to the specified gradient
  569. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  570. * @returns the current particle system
  571. */
  572. public addEmitRateGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  573. if (!this._emitRateGradients) {
  574. this._emitRateGradients = [];
  575. }
  576. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  577. return this;
  578. }
  579. /**
  580. * Remove a specific emit rate gradient
  581. * @param gradient defines the gradient to remove
  582. * @returns the current particle system
  583. */
  584. public removeEmitRateGradient(gradient: number): IParticleSystem {
  585. this._removeFactorGradient(this._emitRateGradients, gradient);
  586. return this;
  587. }
  588. /**
  589. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  590. * @param gradient defines the gradient to use (between 0 and 1)
  591. * @param factor defines the start size value to affect to the specified gradient
  592. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  593. * @returns the current particle system
  594. */
  595. public addStartSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  596. if (!this._startSizeGradients) {
  597. this._startSizeGradients = [];
  598. }
  599. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  600. return this;
  601. }
  602. /**
  603. * Remove a specific start size gradient
  604. * @param gradient defines the gradient to remove
  605. * @returns the current particle system
  606. */
  607. public removeStartSizeGradient(gradient: number): IParticleSystem {
  608. this._removeFactorGradient(this._emitRateGradients, gradient);
  609. return this;
  610. }
  611. private _createRampGradientTexture() {
  612. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  613. return;
  614. }
  615. let data = new Uint8Array(this._rawTextureWidth * 4);
  616. let tmpColor = Tmp.Color3[0];
  617. for (var x = 0; x < this._rawTextureWidth; x++) {
  618. var ratio = x / this._rawTextureWidth;
  619. GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => {
  620. Color3.LerpToRef((<Color3Gradient>currentGradient).color, (<Color3Gradient>nextGradient).color, scale, tmpColor);
  621. data[x * 4] = tmpColor.r * 255;
  622. data[x * 4 + 1] = tmpColor.g * 255;
  623. data[x * 4 + 2] = tmpColor.b * 255;
  624. data[x * 4 + 3] = 255;
  625. });
  626. }
  627. this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  628. }
  629. /**
  630. * Gets the current list of ramp gradients.
  631. * You must use addRampGradient and removeRampGradient to udpate this list
  632. * @returns the list of ramp gradients
  633. */
  634. public getRampGradients(): Nullable<Array<Color3Gradient>> {
  635. return this._rampGradients;
  636. }
  637. /**
  638. * Adds a new ramp gradient used to remap particle colors
  639. * @param gradient defines the gradient to use (between 0 and 1)
  640. * @param color defines the color to affect to the specified gradient
  641. * @returns the current particle system
  642. */
  643. public addRampGradient(gradient: number, color: Color3): ParticleSystem {
  644. if (!this._rampGradients) {
  645. this._rampGradients = [];
  646. }
  647. let rampGradient = new Color3Gradient();
  648. rampGradient.gradient = gradient;
  649. rampGradient.color = color;
  650. this._rampGradients.push(rampGradient);
  651. this._rampGradients.sort((a, b) => {
  652. if (a.gradient < b.gradient) {
  653. return -1;
  654. } else if (a.gradient > b.gradient) {
  655. return 1;
  656. }
  657. return 0;
  658. });
  659. if (this._rampGradientsTexture) {
  660. this._rampGradientsTexture.dispose();
  661. (<any>this._rampGradientsTexture) = null;
  662. }
  663. this._createRampGradientTexture();
  664. return this;
  665. }
  666. /**
  667. * Remove a specific ramp gradient
  668. * @param gradient defines the gradient to remove
  669. * @returns the current particle system
  670. */
  671. public removeRampGradient(gradient: number): ParticleSystem {
  672. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  673. (<any>this._rampGradientsTexture) = null;
  674. if (this._rampGradients && this._rampGradients.length > 0) {
  675. this._createRampGradientTexture();
  676. }
  677. return this;
  678. }
  679. /**
  680. * Adds a new color gradient
  681. * @param gradient defines the gradient to use (between 0 and 1)
  682. * @param color1 defines the color to affect to the specified gradient
  683. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  684. * @returns this particle system
  685. */
  686. public addColorGradient(gradient: number, color1: Color4, color2?: Color4): IParticleSystem {
  687. if (!this._colorGradients) {
  688. this._colorGradients = [];
  689. }
  690. let colorGradient = new ColorGradient();
  691. colorGradient.gradient = gradient;
  692. colorGradient.color1 = color1;
  693. colorGradient.color2 = color2;
  694. this._colorGradients.push(colorGradient);
  695. this._colorGradients.sort((a, b) => {
  696. if (a.gradient < b.gradient) {
  697. return -1;
  698. } else if (a.gradient > b.gradient) {
  699. return 1;
  700. }
  701. return 0;
  702. });
  703. return this;
  704. }
  705. /**
  706. * Remove a specific color gradient
  707. * @param gradient defines the gradient to remove
  708. * @returns this particle system
  709. */
  710. public removeColorGradient(gradient: number): IParticleSystem {
  711. if (!this._colorGradients) {
  712. return this;
  713. }
  714. let index = 0;
  715. for (var colorGradient of this._colorGradients) {
  716. if (colorGradient.gradient === gradient) {
  717. this._colorGradients.splice(index, 1);
  718. break;
  719. }
  720. index++;
  721. }
  722. return this;
  723. }
  724. private _fetchR(u: number, v: number, width: number, height: number, pixels: Uint8Array): number {
  725. u = Math.abs(u) * 0.5 + 0.5;
  726. v = Math.abs(v) * 0.5 + 0.5;
  727. let wrappedU = ((u * width) % width) | 0;
  728. let wrappedV = ((v * height) % height) | 0;
  729. let position = (wrappedU + wrappedV * width) * 4;
  730. return pixels[position] / 255;
  731. }
  732. protected _reset() {
  733. this._resetEffect();
  734. }
  735. private _resetEffect() {
  736. if (this._vertexBuffer) {
  737. this._vertexBuffer.dispose();
  738. this._vertexBuffer = null;
  739. }
  740. if (this._spriteBuffer) {
  741. this._spriteBuffer.dispose();
  742. this._spriteBuffer = null;
  743. }
  744. this._createVertexBuffers();
  745. }
  746. private _createVertexBuffers() {
  747. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  748. if (this._isAnimationSheetEnabled) {
  749. this._vertexBufferSize += 1;
  750. }
  751. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  752. this._vertexBufferSize += 3;
  753. }
  754. if (this._useRampGradients) {
  755. this._vertexBufferSize += 4;
  756. }
  757. let engine = this._scene.getEngine();
  758. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  759. this._vertexBuffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  760. let dataOffset = 0;
  761. var positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  762. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  763. dataOffset += 3;
  764. var colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  765. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  766. dataOffset += 4;
  767. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  768. this._vertexBuffers["angle"] = options;
  769. dataOffset += 1;
  770. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  771. this._vertexBuffers["size"] = size;
  772. dataOffset += 2;
  773. if (this._isAnimationSheetEnabled) {
  774. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  775. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  776. dataOffset += 1;
  777. }
  778. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  779. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  780. this._vertexBuffers["direction"] = directionBuffer;
  781. dataOffset += 3;
  782. }
  783. if (this._useRampGradients) {
  784. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  785. this._vertexBuffers["remapData"] = rampDataBuffer;
  786. dataOffset += 4;
  787. }
  788. var offsets: VertexBuffer;
  789. if (this._useInstancing) {
  790. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  791. this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
  792. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  793. } else {
  794. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  795. dataOffset += 2;
  796. }
  797. this._vertexBuffers["offset"] = offsets;
  798. }
  799. private _createIndexBuffer() {
  800. if (this._useInstancing) {
  801. return;
  802. }
  803. var indices = [];
  804. var index = 0;
  805. for (var count = 0; count < this._capacity; count++) {
  806. indices.push(index);
  807. indices.push(index + 1);
  808. indices.push(index + 2);
  809. indices.push(index);
  810. indices.push(index + 2);
  811. indices.push(index + 3);
  812. index += 4;
  813. }
  814. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  815. }
  816. /**
  817. * Gets the maximum number of particles active at the same time.
  818. * @returns The max number of active particles.
  819. */
  820. public getCapacity(): number {
  821. return this._capacity;
  822. }
  823. /**
  824. * Gets whether there are still active particles in the system.
  825. * @returns True if it is alive, otherwise false.
  826. */
  827. public isAlive(): boolean {
  828. return this._alive;
  829. }
  830. /**
  831. * Gets if the system has been started. (Note: this will still be true after stop is called)
  832. * @returns True if it has been started, otherwise false.
  833. */
  834. public isStarted(): boolean {
  835. return this._started;
  836. }
  837. private _prepareSubEmitterInternalArray() {
  838. this._subEmitters = new Array<Array<SubEmitter>>();
  839. if (this.subEmitters) {
  840. this.subEmitters.forEach((subEmitter) => {
  841. if (subEmitter instanceof ParticleSystem) {
  842. this._subEmitters.push([new SubEmitter(subEmitter)]);
  843. } else if (subEmitter instanceof SubEmitter) {
  844. this._subEmitters.push([subEmitter]);
  845. } else if (subEmitter instanceof Array) {
  846. this._subEmitters.push(subEmitter);
  847. }
  848. });
  849. }
  850. }
  851. /**
  852. * Starts the particle system and begins to emit
  853. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  854. */
  855. public start(delay = this.startDelay): void {
  856. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  857. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  858. }
  859. if (delay) {
  860. setTimeout(() => {
  861. this.start(0);
  862. }, delay);
  863. return;
  864. }
  865. // Convert the subEmitters field to the constant type field _subEmitters
  866. this._prepareSubEmitterInternalArray();
  867. this._started = true;
  868. this._stopped = false;
  869. this._actualFrame = 0;
  870. if (this._subEmitters && this._subEmitters.length != 0) {
  871. this.activeSubSystems = new Array<ParticleSystem>();
  872. }
  873. // Reset emit gradient so it acts the same on every start
  874. if (this._emitRateGradients) {
  875. if (this._emitRateGradients.length > 0) {
  876. this._currentEmitRateGradient = this._emitRateGradients[0];
  877. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  878. this._currentEmitRate2 = this._currentEmitRate1;
  879. }
  880. if (this._emitRateGradients.length > 1) {
  881. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  882. }
  883. }
  884. // Reset start size gradient so it acts the same on every start
  885. if (this._startSizeGradients) {
  886. if (this._startSizeGradients.length > 0) {
  887. this._currentStartSizeGradient = this._startSizeGradients[0];
  888. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  889. this._currentStartSize2 = this._currentStartSize1;
  890. }
  891. if (this._startSizeGradients.length > 1) {
  892. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  893. }
  894. }
  895. if (this.preWarmCycles) {
  896. if (this.emitter instanceof AbstractMesh) {
  897. this.emitter.computeWorldMatrix(true);
  898. }
  899. let noiseTextureAsProcedural = this.noiseTexture as ProceduralTexture;
  900. if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) {
  901. noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => {
  902. setTimeout(() => {
  903. for (var index = 0; index < this.preWarmCycles; index++) {
  904. this.animate(true);
  905. noiseTextureAsProcedural.render();
  906. }
  907. });
  908. });
  909. } else {
  910. for (var index = 0; index < this.preWarmCycles; index++) {
  911. this.animate(true);
  912. }
  913. }
  914. }
  915. // Animations
  916. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  917. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  918. }
  919. }
  920. /**
  921. * Stops the particle system.
  922. * @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.
  923. */
  924. public stop(stopSubEmitters = true): void {
  925. this._stopped = true;
  926. if (stopSubEmitters) {
  927. this._stopSubEmitters();
  928. }
  929. }
  930. // animation sheet
  931. /**
  932. * Remove all active particles
  933. */
  934. public reset(): void {
  935. this._stockParticles = [];
  936. this._particles = [];
  937. }
  938. /**
  939. * @hidden (for internal use only)
  940. */
  941. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  942. var offset = index * this._vertexBufferSize;
  943. this._vertexData[offset++] = particle.position.x + this.worldOffset.x;
  944. this._vertexData[offset++] = particle.position.y + this.worldOffset.y;
  945. this._vertexData[offset++] = particle.position.z + this.worldOffset.z;
  946. this._vertexData[offset++] = particle.color.r;
  947. this._vertexData[offset++] = particle.color.g;
  948. this._vertexData[offset++] = particle.color.b;
  949. this._vertexData[offset++] = particle.color.a;
  950. this._vertexData[offset++] = particle.angle;
  951. this._vertexData[offset++] = particle.scale.x * particle.size;
  952. this._vertexData[offset++] = particle.scale.y * particle.size;
  953. if (this._isAnimationSheetEnabled) {
  954. this._vertexData[offset++] = particle.cellIndex;
  955. }
  956. if (!this._isBillboardBased) {
  957. if (particle._initialDirection) {
  958. this._vertexData[offset++] = particle._initialDirection.x;
  959. this._vertexData[offset++] = particle._initialDirection.y;
  960. this._vertexData[offset++] = particle._initialDirection.z;
  961. } else {
  962. this._vertexData[offset++] = particle.direction.x;
  963. this._vertexData[offset++] = particle.direction.y;
  964. this._vertexData[offset++] = particle.direction.z;
  965. }
  966. } else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  967. this._vertexData[offset++] = particle.direction.x;
  968. this._vertexData[offset++] = particle.direction.y;
  969. this._vertexData[offset++] = particle.direction.z;
  970. }
  971. if (this._useRampGradients) {
  972. this._vertexData[offset++] = particle.remapData.x;
  973. this._vertexData[offset++] = particle.remapData.y;
  974. this._vertexData[offset++] = particle.remapData.z;
  975. this._vertexData[offset++] = particle.remapData.w;
  976. }
  977. if (!this._useInstancing) {
  978. if (this._isAnimationSheetEnabled) {
  979. if (offsetX === 0) {
  980. offsetX = this._epsilon;
  981. }
  982. else if (offsetX === 1) {
  983. offsetX = 1 - this._epsilon;
  984. }
  985. if (offsetY === 0) {
  986. offsetY = this._epsilon;
  987. }
  988. else if (offsetY === 1) {
  989. offsetY = 1 - this._epsilon;
  990. }
  991. }
  992. this._vertexData[offset++] = offsetX;
  993. this._vertexData[offset++] = offsetY;
  994. }
  995. }
  996. // start of sub system methods
  997. /**
  998. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  999. * Its lifetime will start back at 0.
  1000. */
  1001. public recycleParticle: (particle: Particle) => void = (particle) => {
  1002. // move particle from activeParticle list to stock particles
  1003. var lastParticle = <Particle>this._particles.pop();
  1004. if (lastParticle !== particle) {
  1005. lastParticle.copyTo(particle);
  1006. }
  1007. this._stockParticles.push(lastParticle);
  1008. }
  1009. private _stopSubEmitters(): void {
  1010. if (!this.activeSubSystems) {
  1011. return;
  1012. }
  1013. this.activeSubSystems.forEach((subSystem) => {
  1014. subSystem.stop(true);
  1015. });
  1016. this.activeSubSystems = new Array<ParticleSystem>();
  1017. }
  1018. private _createParticle: () => Particle = () => {
  1019. var particle: Particle;
  1020. if (this._stockParticles.length !== 0) {
  1021. particle = <Particle>this._stockParticles.pop();
  1022. particle._reset();
  1023. } else {
  1024. particle = new Particle(this);
  1025. }
  1026. // Attach emitters
  1027. if (this._subEmitters && this._subEmitters.length > 0) {
  1028. var subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)];
  1029. particle._attachedSubEmitters = [];
  1030. subEmitters.forEach((subEmitter) => {
  1031. if (subEmitter.type === SubEmitterType.ATTACHED) {
  1032. var newEmitter = subEmitter.clone();
  1033. (<Array<SubEmitter>>particle._attachedSubEmitters).push(newEmitter);
  1034. newEmitter.particleSystem.start();
  1035. }
  1036. });
  1037. }
  1038. return particle;
  1039. }
  1040. private _removeFromRoot(): void {
  1041. if (!this._rootParticleSystem) {
  1042. return;
  1043. }
  1044. let index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  1045. if (index !== -1) {
  1046. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  1047. }
  1048. this._rootParticleSystem = null;
  1049. }
  1050. private _emitFromParticle: (particle: Particle) => void = (particle) => {
  1051. if (!this._subEmitters || this._subEmitters.length === 0) {
  1052. return;
  1053. }
  1054. var templateIndex = Math.floor(Math.random() * this._subEmitters.length);
  1055. this._subEmitters[templateIndex].forEach((subEmitter) => {
  1056. if (subEmitter.type === SubEmitterType.END) {
  1057. var subSystem = subEmitter.clone();
  1058. particle._inheritParticleInfoToSubEmitter(subSystem);
  1059. subSystem.particleSystem._rootParticleSystem = this;
  1060. this.activeSubSystems.push(subSystem.particleSystem);
  1061. subSystem.particleSystem.start();
  1062. }
  1063. });
  1064. }
  1065. // End of sub system methods
  1066. private _update(newParticles: number): void {
  1067. // Update current
  1068. this._alive = this._particles.length > 0;
  1069. if ((<AbstractMesh>this.emitter).position) {
  1070. var emitterMesh = (<AbstractMesh>this.emitter);
  1071. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  1072. } else {
  1073. var emitterPosition = (<Vector3>this.emitter);
  1074. this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  1075. }
  1076. this.updateFunction(this._particles);
  1077. // Add new ones
  1078. var particle: Particle;
  1079. for (var index = 0; index < newParticles; index++) {
  1080. if (this._particles.length === this._capacity) {
  1081. break;
  1082. }
  1083. particle = this._createParticle();
  1084. this._particles.push(particle);
  1085. // Emitter
  1086. let emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  1087. if (this.startPositionFunction) {
  1088. this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle);
  1089. }
  1090. else {
  1091. this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle);
  1092. }
  1093. if (this.startDirectionFunction) {
  1094. this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle);
  1095. }
  1096. else {
  1097. this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle);
  1098. }
  1099. if (emitPower === 0) {
  1100. if (!particle._initialDirection) {
  1101. particle._initialDirection = particle.direction.clone();
  1102. } else {
  1103. particle._initialDirection.copyFrom(particle.direction);
  1104. }
  1105. } else {
  1106. particle._initialDirection = null;
  1107. }
  1108. particle.direction.scaleInPlace(emitPower);
  1109. // Life time
  1110. if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {
  1111. let ratio = Scalar.Clamp(this._actualFrame / this.targetStopDuration);
  1112. GradientHelper.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient) => {
  1113. let factorGradient1 = (<FactorGradient>currentGradient);
  1114. let factorGradient2 = (<FactorGradient>nextGradient);
  1115. let lifeTime1 = factorGradient1.getFactor();
  1116. let lifeTime2 = factorGradient2.getFactor();
  1117. let gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  1118. particle.lifeTime = Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  1119. });
  1120. } else {
  1121. particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  1122. }
  1123. // Size
  1124. if (!this._sizeGradients || this._sizeGradients.length === 0) {
  1125. particle.size = Scalar.RandomRange(this.minSize, this.maxSize);
  1126. } else {
  1127. particle._currentSizeGradient = this._sizeGradients[0];
  1128. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  1129. particle.size = particle._currentSize1;
  1130. if (this._sizeGradients.length > 1) {
  1131. particle._currentSize2 = this._sizeGradients[1].getFactor();
  1132. } else {
  1133. particle._currentSize2 = particle._currentSize1;
  1134. }
  1135. }
  1136. // Size and scale
  1137. particle.scale.copyFromFloats(Scalar.RandomRange(this.minScaleX, this.maxScaleX), Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  1138. // Adjust scale by start size
  1139. if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) {
  1140. const ratio = this._actualFrame / this.targetStopDuration;
  1141. GradientHelper.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => {
  1142. if (currentGradient !== this._currentStartSizeGradient) {
  1143. this._currentStartSize1 = this._currentStartSize2;
  1144. this._currentStartSize2 = (<FactorGradient>nextGradient).getFactor();
  1145. this._currentStartSizeGradient = (<FactorGradient>currentGradient);
  1146. }
  1147. var value = Scalar.Lerp(this._currentStartSize1, this._currentStartSize2, scale);
  1148. particle.scale.scaleInPlace(value);
  1149. });
  1150. }
  1151. // Angle
  1152. if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) {
  1153. particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  1154. } else {
  1155. particle._currentAngularSpeedGradient = this._angularSpeedGradients[0];
  1156. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  1157. particle._currentAngularSpeed1 = particle.angularSpeed;
  1158. if (this._angularSpeedGradients.length > 1) {
  1159. particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor();
  1160. } else {
  1161. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  1162. }
  1163. }
  1164. particle.angle = Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  1165. // Velocity
  1166. if (this._velocityGradients && this._velocityGradients.length > 0) {
  1167. particle._currentVelocityGradient = this._velocityGradients[0];
  1168. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  1169. if (this._velocityGradients.length > 1) {
  1170. particle._currentVelocity2 = this._velocityGradients[1].getFactor();
  1171. } else {
  1172. particle._currentVelocity2 = particle._currentVelocity1;
  1173. }
  1174. }
  1175. // Limit velocity
  1176. if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
  1177. particle._currentLimitVelocityGradient = this._limitVelocityGradients[0];
  1178. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  1179. if (this._limitVelocityGradients.length > 1) {
  1180. particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor();
  1181. } else {
  1182. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  1183. }
  1184. }
  1185. // Drag
  1186. if (this._dragGradients && this._dragGradients.length > 0) {
  1187. particle._currentDragGradient = this._dragGradients[0];
  1188. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  1189. if (this._dragGradients.length > 1) {
  1190. particle._currentDrag2 = this._dragGradients[1].getFactor();
  1191. } else {
  1192. particle._currentDrag2 = particle._currentDrag1;
  1193. }
  1194. }
  1195. // Color
  1196. if (!this._colorGradients || this._colorGradients.length === 0) {
  1197. var step = Scalar.RandomRange(0, 1.0);
  1198. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  1199. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  1200. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  1201. } else {
  1202. particle._currentColorGradient = this._colorGradients[0];
  1203. particle._currentColorGradient.getColorToRef(particle.color);
  1204. particle._currentColor1.copyFrom(particle.color);
  1205. if (this._colorGradients.length > 1) {
  1206. this._colorGradients[1].getColorToRef(particle._currentColor2);
  1207. } else {
  1208. particle._currentColor2.copyFrom(particle.color);
  1209. }
  1210. }
  1211. // Sheet
  1212. if (this._isAnimationSheetEnabled) {
  1213. particle._initialStartSpriteCellID = this.startSpriteCellID;
  1214. particle._initialEndSpriteCellID = this.endSpriteCellID;
  1215. }
  1216. // Inherited Velocity
  1217. particle.direction.addInPlace(this._inheritedVelocityOffset);
  1218. // Ramp
  1219. if (this._useRampGradients) {
  1220. particle.remapData = new Vector4(0, 1, 0, 1);
  1221. }
  1222. // Noise texture coordinates
  1223. if (this.noiseTexture) {
  1224. if (particle._randomNoiseCoordinates1) {
  1225. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  1226. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  1227. } else {
  1228. particle._randomNoiseCoordinates1 = new Vector3(Math.random(), Math.random(), Math.random());
  1229. particle._randomNoiseCoordinates2 = new Vector3(Math.random(), Math.random(), Math.random());
  1230. }
  1231. }
  1232. // Update the position of the attached sub-emitters to match their attached particle
  1233. particle._inheritParticleInfoToSubEmitters();
  1234. }
  1235. }
  1236. /** @hidden */
  1237. public static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false): string[] {
  1238. var attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
  1239. if (isAnimationSheetEnabled) {
  1240. attributeNamesOrOptions.push("cellIndex");
  1241. }
  1242. if (!isBillboardBased) {
  1243. attributeNamesOrOptions.push("direction");
  1244. }
  1245. if (useRampGradients) {
  1246. attributeNamesOrOptions.push("remapData");
  1247. }
  1248. return attributeNamesOrOptions;
  1249. }
  1250. /** @hidden */
  1251. public static _GetEffectCreationOptions(isAnimationSheetEnabled = false): string[] {
  1252. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  1253. if (isAnimationSheetEnabled) {
  1254. effectCreationOption.push("particlesInfos");
  1255. }
  1256. return effectCreationOption;
  1257. }
  1258. /** @hidden */
  1259. private _getEffect(blendMode: number): Effect {
  1260. if (this._customEffect) {
  1261. return this._customEffect;
  1262. }
  1263. var defines = [];
  1264. if (this._scene.clipPlane) {
  1265. defines.push("#define CLIPPLANE");
  1266. }
  1267. if (this._scene.clipPlane2) {
  1268. defines.push("#define CLIPPLANE2");
  1269. }
  1270. if (this._scene.clipPlane3) {
  1271. defines.push("#define CLIPPLANE3");
  1272. }
  1273. if (this._scene.clipPlane4) {
  1274. defines.push("#define CLIPPLANE4");
  1275. }
  1276. if (this._isAnimationSheetEnabled) {
  1277. defines.push("#define ANIMATESHEET");
  1278. }
  1279. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  1280. defines.push("#define BLENDMULTIPLYMODE");
  1281. }
  1282. if (this._useRampGradients) {
  1283. defines.push("#define RAMPGRADIENT");
  1284. }
  1285. if (this._isBillboardBased) {
  1286. defines.push("#define BILLBOARD");
  1287. switch (this.billboardMode) {
  1288. case ParticleSystem.BILLBOARDMODE_Y:
  1289. defines.push("#define BILLBOARDY");
  1290. break;
  1291. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  1292. defines.push("#define BILLBOARDSTRETCHED");
  1293. break;
  1294. case ParticleSystem.BILLBOARDMODE_ALL:
  1295. default:
  1296. break;
  1297. }
  1298. }
  1299. if (this._imageProcessingConfiguration) {
  1300. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  1301. defines.push(this._imageProcessingConfigurationDefines.toString());
  1302. }
  1303. // Effect
  1304. var join = defines.join("\n");
  1305. if (this._cachedDefines !== join) {
  1306. this._cachedDefines = join;
  1307. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  1308. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  1309. var samplers = ["diffuseSampler", "rampSampler"];
  1310. if (ImageProcessingConfiguration) {
  1311. ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  1312. ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  1313. }
  1314. this._effect = this._scene.getEngine().createEffect(
  1315. "particles",
  1316. attributesNamesOrOptions,
  1317. effectCreationOption,
  1318. samplers, join);
  1319. }
  1320. return this._effect;
  1321. }
  1322. /**
  1323. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  1324. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  1325. */
  1326. public animate(preWarmOnly = false): void {
  1327. if (!this._started) {
  1328. return;
  1329. }
  1330. if (!preWarmOnly) {
  1331. // Check
  1332. if (!this.isReady()) {
  1333. return;
  1334. }
  1335. if (this._currentRenderId === this._scene.getFrameId()) {
  1336. return;
  1337. }
  1338. this._currentRenderId = this._scene.getFrameId();
  1339. }
  1340. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  1341. // Determine the number of particles we need to create
  1342. var newParticles;
  1343. if (this.manualEmitCount > -1) {
  1344. newParticles = this.manualEmitCount;
  1345. this._newPartsExcess = 0;
  1346. this.manualEmitCount = 0;
  1347. } else {
  1348. let rate = this.emitRate;
  1349. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  1350. const ratio = this._actualFrame / this.targetStopDuration;
  1351. GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => {
  1352. if (currentGradient !== this._currentEmitRateGradient) {
  1353. this._currentEmitRate1 = this._currentEmitRate2;
  1354. this._currentEmitRate2 = (<FactorGradient>nextGradient).getFactor();
  1355. this._currentEmitRateGradient = (<FactorGradient>currentGradient);
  1356. }
  1357. rate = Scalar.Lerp(this._currentEmitRate1, this._currentEmitRate2, scale);
  1358. });
  1359. }
  1360. newParticles = ((rate * this._scaledUpdateSpeed) >> 0);
  1361. this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles;
  1362. }
  1363. if (this._newPartsExcess > 1.0) {
  1364. newParticles += this._newPartsExcess >> 0;
  1365. this._newPartsExcess -= this._newPartsExcess >> 0;
  1366. }
  1367. this._alive = false;
  1368. if (!this._stopped) {
  1369. this._actualFrame += this._scaledUpdateSpeed;
  1370. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  1371. this.stop();
  1372. }
  1373. } else {
  1374. newParticles = 0;
  1375. }
  1376. this._update(newParticles);
  1377. // Stopped?
  1378. if (this._stopped) {
  1379. if (!this._alive) {
  1380. this._started = false;
  1381. if (this.onAnimationEnd) {
  1382. this.onAnimationEnd();
  1383. }
  1384. if (this.disposeOnStop) {
  1385. this._scene._toBeDisposed.push(this);
  1386. }
  1387. }
  1388. }
  1389. if (!preWarmOnly) {
  1390. // Update VBO
  1391. var offset = 0;
  1392. for (var index = 0; index < this._particles.length; index++) {
  1393. var particle = this._particles[index];
  1394. this._appendParticleVertices(offset, particle);
  1395. offset += this._useInstancing ? 1 : 4;
  1396. }
  1397. if (this._vertexBuffer) {
  1398. this._vertexBuffer.update(this._vertexData);
  1399. }
  1400. }
  1401. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  1402. this.stop();
  1403. }
  1404. }
  1405. private _appendParticleVertices(offset: number, particle: Particle) {
  1406. this._appendParticleVertex(offset++, particle, 0, 0);
  1407. if (!this._useInstancing) {
  1408. this._appendParticleVertex(offset++, particle, 1, 0);
  1409. this._appendParticleVertex(offset++, particle, 1, 1);
  1410. this._appendParticleVertex(offset++, particle, 0, 1);
  1411. }
  1412. }
  1413. /**
  1414. * Rebuilds the particle system.
  1415. */
  1416. public rebuild(): void {
  1417. this._createIndexBuffer();
  1418. if (this._vertexBuffer) {
  1419. this._vertexBuffer._rebuild();
  1420. }
  1421. for (var key in this._vertexBuffers) {
  1422. this._vertexBuffers[key]._rebuild();
  1423. }
  1424. }
  1425. /**
  1426. * Is this system ready to be used/rendered
  1427. * @return true if the system is ready
  1428. */
  1429. public isReady(): boolean {
  1430. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  1431. return false;
  1432. }
  1433. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  1434. if (!this._getEffect(this.blendMode).isReady()) {
  1435. return false;
  1436. }
  1437. } else {
  1438. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  1439. return false;
  1440. }
  1441. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  1442. return false;
  1443. }
  1444. }
  1445. return true;
  1446. }
  1447. private _render(blendMode: number) {
  1448. var effect = this._getEffect(blendMode);
  1449. var engine = this._scene.getEngine();
  1450. // Render
  1451. engine.enableEffect(effect);
  1452. var viewMatrix = this._scene.getViewMatrix();
  1453. effect.setTexture("diffuseSampler", this.particleTexture);
  1454. effect.setMatrix("view", viewMatrix);
  1455. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  1456. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1457. var baseSize = this.particleTexture.getBaseSize();
  1458. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  1459. }
  1460. effect.setVector2("translationPivot", this.translationPivot);
  1461. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  1462. if (this._isBillboardBased) {
  1463. var camera = this._scene.activeCamera!;
  1464. effect.setVector3("eyePosition", camera.globalPosition);
  1465. }
  1466. if (this._rampGradientsTexture) {
  1467. effect.setTexture("rampSampler", this._rampGradientsTexture);
  1468. }
  1469. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  1470. var invView = viewMatrix.clone();
  1471. invView.invert();
  1472. effect.setMatrix("invView", invView);
  1473. MaterialHelper.BindClipPlane(effect, this._scene);
  1474. }
  1475. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  1476. // image processing
  1477. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  1478. this._imageProcessingConfiguration.bind(effect);
  1479. }
  1480. // Draw order
  1481. switch (blendMode) {
  1482. case ParticleSystem.BLENDMODE_ADD:
  1483. engine.setAlphaMode(Constants.ALPHA_ADD);
  1484. break;
  1485. case ParticleSystem.BLENDMODE_ONEONE:
  1486. engine.setAlphaMode(Constants.ALPHA_ONEONE);
  1487. break;
  1488. case ParticleSystem.BLENDMODE_STANDARD:
  1489. engine.setAlphaMode(Constants.ALPHA_COMBINE);
  1490. break;
  1491. case ParticleSystem.BLENDMODE_MULTIPLY:
  1492. engine.setAlphaMode(Constants.ALPHA_MULTIPLY);
  1493. break;
  1494. }
  1495. if (this._useInstancing) {
  1496. engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  1497. } else {
  1498. engine.drawElementsType(Material.TriangleFillMode, 0, this._particles.length * 6);
  1499. }
  1500. return this._particles.length;
  1501. }
  1502. /**
  1503. * Renders the particle system in its current state.
  1504. * @returns the current number of particles
  1505. */
  1506. public render(): number {
  1507. // Check
  1508. if (!this.isReady() || !this._particles.length) {
  1509. return 0;
  1510. }
  1511. var engine = this._scene.getEngine();
  1512. engine.setState(false);
  1513. if (this.forceDepthWrite) {
  1514. engine.setDepthWrite(true);
  1515. }
  1516. let outparticles = 0;
  1517. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  1518. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  1519. }
  1520. outparticles = this._render(this.blendMode);
  1521. engine.unbindInstanceAttributes();
  1522. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  1523. return outparticles;
  1524. }
  1525. /**
  1526. * Disposes the particle system and free the associated resources
  1527. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1528. */
  1529. public dispose(disposeTexture = true): void {
  1530. if (this._vertexBuffer) {
  1531. this._vertexBuffer.dispose();
  1532. this._vertexBuffer = null;
  1533. }
  1534. if (this._spriteBuffer) {
  1535. this._spriteBuffer.dispose();
  1536. this._spriteBuffer = null;
  1537. }
  1538. if (this._indexBuffer) {
  1539. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  1540. this._indexBuffer = null;
  1541. }
  1542. if (disposeTexture && this.particleTexture) {
  1543. this.particleTexture.dispose();
  1544. this.particleTexture = null;
  1545. }
  1546. if (disposeTexture && this.noiseTexture) {
  1547. this.noiseTexture.dispose();
  1548. this.noiseTexture = null;
  1549. }
  1550. if (this._rampGradientsTexture) {
  1551. this._rampGradientsTexture.dispose();
  1552. this._rampGradientsTexture = null;
  1553. }
  1554. this._removeFromRoot();
  1555. if (this._subEmitters && this._subEmitters.length) {
  1556. for (var index = 0; index < this._subEmitters.length; index++) {
  1557. for (var subEmitter of this._subEmitters[index]) {
  1558. subEmitter.dispose();
  1559. }
  1560. }
  1561. this._subEmitters = [];
  1562. this.subEmitters = [];
  1563. }
  1564. if (this._disposeEmitterOnDispose && this.emitter && (this.emitter as AbstractMesh).dispose) {
  1565. (<AbstractMesh>this.emitter).dispose(true);
  1566. }
  1567. // Remove from scene
  1568. var index = this._scene.particleSystems.indexOf(this);
  1569. if (index > -1) {
  1570. this._scene.particleSystems.splice(index, 1);
  1571. }
  1572. this._scene._activeParticleSystems.dispose();
  1573. // Callback
  1574. this.onDisposeObservable.notifyObservers(this);
  1575. this.onDisposeObservable.clear();
  1576. this.reset();
  1577. }
  1578. // Clone
  1579. /**
  1580. * Clones the particle system.
  1581. * @param name The name of the cloned object
  1582. * @param newEmitter The new emitter to use
  1583. * @returns the cloned particle system
  1584. */
  1585. public clone(name: string, newEmitter: any): ParticleSystem {
  1586. var custom: Nullable<Effect> = null;
  1587. var program: any = null;
  1588. if (this.customShader != null) {
  1589. program = this.customShader;
  1590. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1591. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1592. } else if (this._customEffect) {
  1593. custom = this._customEffect;
  1594. }
  1595. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  1596. result.customShader = program;
  1597. DeepCopier.DeepCopy(this, result, ["particles", "customShader", "noiseTexture", "particleTexture", "onDisposeObservable"]);
  1598. if (newEmitter === undefined) {
  1599. newEmitter = this.emitter;
  1600. }
  1601. result.noiseTexture = this.noiseTexture;
  1602. result.emitter = newEmitter;
  1603. if (this.particleTexture) {
  1604. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1605. }
  1606. // Clone gradients
  1607. if (this._colorGradients) {
  1608. this._colorGradients.forEach((v) => {
  1609. result.addColorGradient(v.gradient, v.color1, v.color2);
  1610. });
  1611. }
  1612. if (this._dragGradients) {
  1613. this._dragGradients.forEach((v) => {
  1614. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  1615. });
  1616. }
  1617. if (this._angularSpeedGradients) {
  1618. this._angularSpeedGradients.forEach((v) => {
  1619. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  1620. });
  1621. }
  1622. if (this._emitRateGradients) {
  1623. this._emitRateGradients.forEach((v) => {
  1624. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  1625. });
  1626. }
  1627. if (this._lifeTimeGradients) {
  1628. this._lifeTimeGradients.forEach((v) => {
  1629. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  1630. });
  1631. }
  1632. if (this._limitVelocityGradients) {
  1633. this._limitVelocityGradients.forEach((v) => {
  1634. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  1635. });
  1636. }
  1637. if (this._sizeGradients) {
  1638. this._sizeGradients.forEach((v) => {
  1639. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  1640. });
  1641. }
  1642. if (this._startSizeGradients) {
  1643. this._startSizeGradients.forEach((v) => {
  1644. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  1645. });
  1646. }
  1647. if (this._velocityGradients) {
  1648. this._velocityGradients.forEach((v) => {
  1649. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  1650. });
  1651. }
  1652. if (this._rampGradients) {
  1653. this._rampGradients.forEach((v) => {
  1654. result.addRampGradient(v.gradient, v.color);
  1655. });
  1656. }
  1657. if (this._colorRemapGradients) {
  1658. this._colorRemapGradients.forEach((v) => {
  1659. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2!);
  1660. });
  1661. }
  1662. if (this._alphaRemapGradients) {
  1663. this._alphaRemapGradients.forEach((v) => {
  1664. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2!);
  1665. });
  1666. }
  1667. if (!this.preventAutoStart) {
  1668. result.start();
  1669. }
  1670. return result;
  1671. }
  1672. /**
  1673. * Serializes the particle system to a JSON object.
  1674. * @returns the JSON object
  1675. */
  1676. public serialize(): any {
  1677. var serializationObject: any = {};
  1678. ParticleSystem._Serialize(serializationObject, this);
  1679. serializationObject.textureMask = this.textureMask.asArray();
  1680. serializationObject.customShader = this.customShader;
  1681. serializationObject.preventAutoStart = this.preventAutoStart;
  1682. // SubEmitters
  1683. if (this.subEmitters) {
  1684. serializationObject.subEmitters = [];
  1685. if (!this._subEmitters) {
  1686. this._prepareSubEmitterInternalArray();
  1687. }
  1688. for (var subs of this._subEmitters) {
  1689. let cell = [];
  1690. for (var sub of subs) {
  1691. cell.push(sub.serialize());
  1692. }
  1693. serializationObject.subEmitters.push(cell);
  1694. }
  1695. }
  1696. return serializationObject;
  1697. }
  1698. /** @hidden */
  1699. public static _Serialize(serializationObject: any, particleSystem: IParticleSystem) {
  1700. serializationObject.name = particleSystem.name;
  1701. serializationObject.id = particleSystem.id;
  1702. serializationObject.capacity = particleSystem.getCapacity();
  1703. // Emitter
  1704. if ((<AbstractMesh>particleSystem.emitter).position) {
  1705. var emitterMesh = (<AbstractMesh>particleSystem.emitter);
  1706. serializationObject.emitterId = emitterMesh.id;
  1707. } else {
  1708. var emitterPosition = (<Vector3>particleSystem.emitter);
  1709. serializationObject.emitter = emitterPosition.asArray();
  1710. }
  1711. // Emitter
  1712. if (particleSystem.particleEmitterType) {
  1713. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  1714. }
  1715. if (particleSystem.particleTexture) {
  1716. serializationObject.textureName = particleSystem.particleTexture.name;
  1717. serializationObject.invertY = particleSystem.particleTexture._invertY;
  1718. }
  1719. // Animations
  1720. SerializationHelper.AppendSerializedAnimations(particleSystem, serializationObject);
  1721. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  1722. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  1723. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  1724. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  1725. // Particle system
  1726. serializationObject.startDelay = particleSystem.startDelay;
  1727. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  1728. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  1729. serializationObject.billboardMode = particleSystem.billboardMode;
  1730. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  1731. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  1732. serializationObject.minSize = particleSystem.minSize;
  1733. serializationObject.maxSize = particleSystem.maxSize;
  1734. serializationObject.minScaleX = particleSystem.minScaleX;
  1735. serializationObject.maxScaleX = particleSystem.maxScaleX;
  1736. serializationObject.minScaleY = particleSystem.minScaleY;
  1737. serializationObject.maxScaleY = particleSystem.maxScaleY;
  1738. serializationObject.minEmitPower = particleSystem.minEmitPower;
  1739. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  1740. serializationObject.minLifeTime = particleSystem.minLifeTime;
  1741. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  1742. serializationObject.emitRate = particleSystem.emitRate;
  1743. serializationObject.gravity = particleSystem.gravity.asArray();
  1744. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  1745. serializationObject.color1 = particleSystem.color1.asArray();
  1746. serializationObject.color2 = particleSystem.color2.asArray();
  1747. serializationObject.colorDead = particleSystem.colorDead.asArray();
  1748. serializationObject.updateSpeed = particleSystem.updateSpeed;
  1749. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  1750. serializationObject.blendMode = particleSystem.blendMode;
  1751. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  1752. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  1753. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  1754. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  1755. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  1756. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  1757. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  1758. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  1759. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  1760. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  1761. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  1762. let colorGradients = particleSystem.getColorGradients();
  1763. if (colorGradients) {
  1764. serializationObject.colorGradients = [];
  1765. for (var colorGradient of colorGradients) {
  1766. var serializedGradient: any = {
  1767. gradient: colorGradient.gradient,
  1768. color1: colorGradient.color1.asArray()
  1769. };
  1770. if (colorGradient.color2) {
  1771. serializedGradient.color2 = colorGradient.color2.asArray();
  1772. }
  1773. serializationObject.colorGradients.push(serializedGradient);
  1774. }
  1775. }
  1776. let rampGradients = particleSystem.getRampGradients();
  1777. if (rampGradients) {
  1778. serializationObject.rampGradients = [];
  1779. for (var rampGradient of rampGradients) {
  1780. var serializedGradient: any = {
  1781. gradient: rampGradient.gradient,
  1782. color: rampGradient.color.asArray()
  1783. };
  1784. serializationObject.rampGradients.push(serializedGradient);
  1785. }
  1786. serializationObject.useRampGradients = particleSystem.useRampGradients;
  1787. }
  1788. let colorRemapGradients = particleSystem.getColorRemapGradients();
  1789. if (colorRemapGradients) {
  1790. serializationObject.colorRemapGradients = [];
  1791. for (var colorRemapGradient of colorRemapGradients) {
  1792. var serializedGradient: any = {
  1793. gradient: colorRemapGradient.gradient,
  1794. factor1: colorRemapGradient.factor1
  1795. };
  1796. if (colorRemapGradient.factor2 !== undefined) {
  1797. serializedGradient.factor2 = colorRemapGradient.factor2;
  1798. }
  1799. serializationObject.colorRemapGradients.push(serializedGradient);
  1800. }
  1801. }
  1802. let alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  1803. if (alphaRemapGradients) {
  1804. serializationObject.alphaRemapGradients = [];
  1805. for (var alphaRemapGradient of alphaRemapGradients) {
  1806. var serializedGradient: any = {
  1807. gradient: alphaRemapGradient.gradient,
  1808. factor1: alphaRemapGradient.factor1
  1809. };
  1810. if (alphaRemapGradient.factor2 !== undefined) {
  1811. serializedGradient.factor2 = alphaRemapGradient.factor2;
  1812. }
  1813. serializationObject.alphaRemapGradients.push(serializedGradient);
  1814. }
  1815. }
  1816. let sizeGradients = particleSystem.getSizeGradients();
  1817. if (sizeGradients) {
  1818. serializationObject.sizeGradients = [];
  1819. for (var sizeGradient of sizeGradients) {
  1820. var serializedGradient: any = {
  1821. gradient: sizeGradient.gradient,
  1822. factor1: sizeGradient.factor1
  1823. };
  1824. if (sizeGradient.factor2 !== undefined) {
  1825. serializedGradient.factor2 = sizeGradient.factor2;
  1826. }
  1827. serializationObject.sizeGradients.push(serializedGradient);
  1828. }
  1829. }
  1830. let angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  1831. if (angularSpeedGradients) {
  1832. serializationObject.angularSpeedGradients = [];
  1833. for (var angularSpeedGradient of angularSpeedGradients) {
  1834. var serializedGradient: any = {
  1835. gradient: angularSpeedGradient.gradient,
  1836. factor1: angularSpeedGradient.factor1
  1837. };
  1838. if (angularSpeedGradient.factor2 !== undefined) {
  1839. serializedGradient.factor2 = angularSpeedGradient.factor2;
  1840. }
  1841. serializationObject.angularSpeedGradients.push(serializedGradient);
  1842. }
  1843. }
  1844. let velocityGradients = particleSystem.getVelocityGradients();
  1845. if (velocityGradients) {
  1846. serializationObject.velocityGradients = [];
  1847. for (var velocityGradient of velocityGradients) {
  1848. var serializedGradient: any = {
  1849. gradient: velocityGradient.gradient,
  1850. factor1: velocityGradient.factor1
  1851. };
  1852. if (velocityGradient.factor2 !== undefined) {
  1853. serializedGradient.factor2 = velocityGradient.factor2;
  1854. }
  1855. serializationObject.velocityGradients.push(serializedGradient);
  1856. }
  1857. }
  1858. let dragGradients = particleSystem.getDragGradients();
  1859. if (dragGradients) {
  1860. serializationObject.dragGradients = [];
  1861. for (var dragGradient of dragGradients) {
  1862. var serializedGradient: any = {
  1863. gradient: dragGradient.gradient,
  1864. factor1: dragGradient.factor1
  1865. };
  1866. if (dragGradient.factor2 !== undefined) {
  1867. serializedGradient.factor2 = dragGradient.factor2;
  1868. }
  1869. serializationObject.dragGradients.push(serializedGradient);
  1870. }
  1871. }
  1872. let emitRateGradients = particleSystem.getEmitRateGradients();
  1873. if (emitRateGradients) {
  1874. serializationObject.emitRateGradients = [];
  1875. for (var emitRateGradient of emitRateGradients) {
  1876. var serializedGradient: any = {
  1877. gradient: emitRateGradient.gradient,
  1878. factor1: emitRateGradient.factor1
  1879. };
  1880. if (emitRateGradient.factor2 !== undefined) {
  1881. serializedGradient.factor2 = emitRateGradient.factor2;
  1882. }
  1883. serializationObject.emitRateGradients.push(serializedGradient);
  1884. }
  1885. }
  1886. let startSizeGradients = particleSystem.getStartSizeGradients();
  1887. if (startSizeGradients) {
  1888. serializationObject.startSizeGradients = [];
  1889. for (var startSizeGradient of startSizeGradients) {
  1890. var serializedGradient: any = {
  1891. gradient: startSizeGradient.gradient,
  1892. factor1: startSizeGradient.factor1
  1893. };
  1894. if (startSizeGradient.factor2 !== undefined) {
  1895. serializedGradient.factor2 = startSizeGradient.factor2;
  1896. }
  1897. serializationObject.startSizeGradients.push(serializedGradient);
  1898. }
  1899. }
  1900. let lifeTimeGradients = particleSystem.getLifeTimeGradients();
  1901. if (lifeTimeGradients) {
  1902. serializationObject.lifeTimeGradients = [];
  1903. for (var lifeTimeGradient of lifeTimeGradients) {
  1904. var serializedGradient: any = {
  1905. gradient: lifeTimeGradient.gradient,
  1906. factor1: lifeTimeGradient.factor1
  1907. };
  1908. if (lifeTimeGradient.factor2 !== undefined) {
  1909. serializedGradient.factor2 = lifeTimeGradient.factor2;
  1910. }
  1911. serializationObject.lifeTimeGradients.push(serializedGradient);
  1912. }
  1913. }
  1914. let limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  1915. if (limitVelocityGradients) {
  1916. serializationObject.limitVelocityGradients = [];
  1917. for (var limitVelocityGradient of limitVelocityGradients) {
  1918. var serializedGradient: any = {
  1919. gradient: limitVelocityGradient.gradient,
  1920. factor1: limitVelocityGradient.factor1
  1921. };
  1922. if (limitVelocityGradient.factor2 !== undefined) {
  1923. serializedGradient.factor2 = limitVelocityGradient.factor2;
  1924. }
  1925. serializationObject.limitVelocityGradients.push(serializedGradient);
  1926. }
  1927. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  1928. }
  1929. if (particleSystem.noiseTexture) {
  1930. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  1931. }
  1932. }
  1933. /** @hidden */
  1934. public static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string) {
  1935. // Texture
  1936. if (parsedParticleSystem.textureName) {
  1937. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  1938. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  1939. }
  1940. // Emitter
  1941. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  1942. particleSystem.emitter = Vector3.Zero();
  1943. }
  1944. else if (parsedParticleSystem.emitterId) {
  1945. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  1946. } else {
  1947. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  1948. }
  1949. // Misc.
  1950. if (parsedParticleSystem.renderingGroupId !== undefined) {
  1951. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  1952. }
  1953. if (parsedParticleSystem.isBillboardBased !== undefined) {
  1954. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  1955. }
  1956. if (parsedParticleSystem.billboardMode !== undefined) {
  1957. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  1958. }
  1959. // Animations
  1960. if (parsedParticleSystem.animations) {
  1961. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  1962. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  1963. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  1964. if (internalClass) {
  1965. particleSystem.animations.push(internalClass.Parse(parsedAnimation));
  1966. }
  1967. }
  1968. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  1969. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  1970. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  1971. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  1972. }
  1973. if (parsedParticleSystem.autoAnimate) {
  1974. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  1975. }
  1976. // Particle system
  1977. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  1978. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  1979. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  1980. particleSystem.minSize = parsedParticleSystem.minSize;
  1981. particleSystem.maxSize = parsedParticleSystem.maxSize;
  1982. if (parsedParticleSystem.minScaleX) {
  1983. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  1984. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  1985. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  1986. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  1987. }
  1988. if (parsedParticleSystem.preWarmCycles !== undefined) {
  1989. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  1990. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  1991. }
  1992. if (parsedParticleSystem.minInitialRotation !== undefined) {
  1993. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  1994. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  1995. }
  1996. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  1997. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  1998. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  1999. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  2000. particleSystem.emitRate = parsedParticleSystem.emitRate;
  2001. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  2002. if (parsedParticleSystem.noiseStrength) {
  2003. particleSystem.noiseStrength = Vector3.FromArray(parsedParticleSystem.noiseStrength);
  2004. }
  2005. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  2006. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  2007. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  2008. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  2009. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  2010. particleSystem.blendMode = parsedParticleSystem.blendMode;
  2011. if (parsedParticleSystem.colorGradients) {
  2012. for (var colorGradient of parsedParticleSystem.colorGradients) {
  2013. particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined);
  2014. }
  2015. }
  2016. if (parsedParticleSystem.rampGradients) {
  2017. for (var rampGradient of parsedParticleSystem.rampGradients) {
  2018. particleSystem.addRampGradient(rampGradient.gradient, Color3.FromArray(rampGradient.color));
  2019. }
  2020. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  2021. }
  2022. if (parsedParticleSystem.colorRemapGradients) {
  2023. for (var colorRemapGradient of parsedParticleSystem.colorRemapGradients) {
  2024. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  2025. }
  2026. }
  2027. if (parsedParticleSystem.alphaRemapGradients) {
  2028. for (var alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) {
  2029. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  2030. }
  2031. }
  2032. if (parsedParticleSystem.sizeGradients) {
  2033. for (var sizeGradient of parsedParticleSystem.sizeGradients) {
  2034. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  2035. }
  2036. }
  2037. if (parsedParticleSystem.angularSpeedGradients) {
  2038. for (var angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) {
  2039. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  2040. }
  2041. }
  2042. if (parsedParticleSystem.velocityGradients) {
  2043. for (var velocityGradient of parsedParticleSystem.velocityGradients) {
  2044. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  2045. }
  2046. }
  2047. if (parsedParticleSystem.dragGradients) {
  2048. for (var dragGradient of parsedParticleSystem.dragGradients) {
  2049. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  2050. }
  2051. }
  2052. if (parsedParticleSystem.emitRateGradients) {
  2053. for (var emitRateGradient of parsedParticleSystem.emitRateGradients) {
  2054. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  2055. }
  2056. }
  2057. if (parsedParticleSystem.startSizeGradients) {
  2058. for (var startSizeGradient of parsedParticleSystem.startSizeGradients) {
  2059. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  2060. }
  2061. }
  2062. if (parsedParticleSystem.lifeTimeGradients) {
  2063. for (var lifeTimeGradient of parsedParticleSystem.lifeTimeGradients) {
  2064. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  2065. }
  2066. }
  2067. if (parsedParticleSystem.limitVelocityGradients) {
  2068. for (var limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) {
  2069. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  2070. }
  2071. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  2072. }
  2073. if (parsedParticleSystem.noiseTexture) {
  2074. particleSystem.noiseTexture = ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  2075. }
  2076. // Emitter
  2077. let emitterType: IParticleEmitterType;
  2078. if (parsedParticleSystem.particleEmitterType) {
  2079. switch (parsedParticleSystem.particleEmitterType.type) {
  2080. case "SphereParticleEmitter":
  2081. emitterType = new SphereParticleEmitter();
  2082. break;
  2083. case "SphereDirectedParticleEmitter":
  2084. emitterType = new SphereDirectedParticleEmitter();
  2085. break;
  2086. case "ConeEmitter":
  2087. case "ConeParticleEmitter":
  2088. emitterType = new ConeParticleEmitter();
  2089. break;
  2090. case "CylinderParticleEmitter":
  2091. emitterType = new CylinderParticleEmitter();
  2092. break;
  2093. case "HemisphericParticleEmitter":
  2094. emitterType = new HemisphericParticleEmitter();
  2095. break;
  2096. case "BoxEmitter":
  2097. case "BoxParticleEmitter":
  2098. default:
  2099. emitterType = new BoxParticleEmitter();
  2100. break;
  2101. }
  2102. emitterType.parse(parsedParticleSystem.particleEmitterType);
  2103. } else {
  2104. emitterType = new BoxParticleEmitter();
  2105. emitterType.parse(parsedParticleSystem);
  2106. }
  2107. particleSystem.particleEmitterType = emitterType;
  2108. // Animation sheet
  2109. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  2110. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  2111. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  2112. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  2113. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  2114. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  2115. }
  2116. /**
  2117. * Parses a JSON object to create a particle system.
  2118. * @param parsedParticleSystem The JSON object to parse
  2119. * @param scene The scene to create the particle system in
  2120. * @param rootUrl The root url to use to load external dependencies like texture
  2121. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  2122. * @returns the Parsed particle system
  2123. */
  2124. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string, doNotStart = false): ParticleSystem {
  2125. var name = parsedParticleSystem.name;
  2126. var custom: Nullable<Effect> = null;
  2127. var program: any = null;
  2128. if (parsedParticleSystem.customShader) {
  2129. program = parsedParticleSystem.customShader;
  2130. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  2131. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  2132. }
  2133. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  2134. particleSystem.customShader = program;
  2135. if (parsedParticleSystem.id) {
  2136. particleSystem.id = parsedParticleSystem.id;
  2137. }
  2138. // SubEmitters
  2139. if (parsedParticleSystem.subEmitters) {
  2140. particleSystem.subEmitters = [];
  2141. for (var cell of parsedParticleSystem.subEmitters) {
  2142. let cellArray = [];
  2143. for (var sub of cell) {
  2144. cellArray.push(SubEmitter.Parse(sub, scene, rootUrl));
  2145. }
  2146. particleSystem.subEmitters.push(cellArray);
  2147. }
  2148. }
  2149. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  2150. particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
  2151. // Auto start
  2152. if (parsedParticleSystem.preventAutoStart) {
  2153. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  2154. }
  2155. if (!doNotStart && !particleSystem.preventAutoStart) {
  2156. particleSystem.start();
  2157. }
  2158. return particleSystem;
  2159. }
  2160. }
  2161. SubEmitter._ParseParticleSystem = ParticleSystem.Parse;