babylon.particleSystem.ts 103 KB

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