particleSystem.ts 112 KB

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