babylon.particleSystem.ts 104 KB

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