particleSystem.ts 110 KB

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