particleSystem.ts 109 KB

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