particleSystem.ts 109 KB

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