particleSystem.ts 106 KB

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