babylon.particleSystem.ts 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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 implements IDisposable, IAnimatable, IParticleSystem {
  9. /**
  10. * Source color is added to the destination color without alpha affecting the result.
  11. */
  12. public static BLENDMODE_ONEONE = 0;
  13. /**
  14. * Blend current color and particle color using particle’s alpha.
  15. */
  16. public static BLENDMODE_STANDARD = 1;
  17. /**
  18. * Add current color and particle color multiplied by particle’s alpha.
  19. */
  20. public static BLENDMODE_ADD = 2;
  21. /**
  22. * List of animations used by the particle system.
  23. */
  24. public animations: Animation[] = [];
  25. /**
  26. * The id of the Particle system.
  27. */
  28. public id: string;
  29. /**
  30. * The friendly name of the Particle system.
  31. */
  32. public name: string;
  33. /**
  34. * The rendering group used by the Particle system to chose when to render.
  35. */
  36. public renderingGroupId = 0;
  37. /**
  38. * The emitter represents the Mesh or position we are attaching the particle system to.
  39. */
  40. public emitter: Nullable<AbstractMesh | Vector3> = null;
  41. /**
  42. * The maximum number of particles to emit per frame
  43. */
  44. public emitRate = 10;
  45. /**
  46. * If you want to launch only a few particles at once, that can be done, as well.
  47. */
  48. public manualEmitCount = -1;
  49. /**
  50. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51. */
  52. public updateSpeed = 0.01;
  53. /**
  54. * The amount of time the particle system is running (depends of the overall update speed).
  55. */
  56. public targetStopDuration = 0;
  57. /**
  58. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  59. */
  60. public disposeOnStop = false;
  61. /**
  62. * Minimum power of emitting particles.
  63. */
  64. public minEmitPower = 1;
  65. /**
  66. * Maximum power of emitting particles.
  67. */
  68. public maxEmitPower = 1;
  69. /**
  70. * Minimum life time of emitting particles.
  71. */
  72. public minLifeTime = 1;
  73. /**
  74. * Maximum life time of emitting particles.
  75. */
  76. public maxLifeTime = 1;
  77. /**
  78. * Minimum Size of emitting particles.
  79. */
  80. public minSize = 1;
  81. /**
  82. * Maximum Size of emitting particles.
  83. */
  84. public maxSize = 1;
  85. /**
  86. * Minimum scale of emitting particles on X axis.
  87. */
  88. public minScaleX = 1;
  89. /**
  90. * Maximum scale of emitting particles on X axis.
  91. */
  92. public maxScaleX = 1;
  93. /**
  94. * Minimum scale of emitting particles on Y axis.
  95. */
  96. public minScaleY = 1;
  97. /**
  98. * Maximum scale of emitting particles on Y axis.
  99. */
  100. public maxScaleY = 1;
  101. /**
  102. * Gets or sets the minimal initial rotation in radians.
  103. */
  104. public minInitialRotation = 0;
  105. /**
  106. * Gets or sets the maximal initial rotation in radians.
  107. */
  108. public maxInitialRotation = 0;
  109. /**
  110. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  111. */
  112. public minAngularSpeed = 0;
  113. /**
  114. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  115. */
  116. public maxAngularSpeed = 0;
  117. /**
  118. * The texture used to render each particle. (this can be a spritesheet)
  119. */
  120. public particleTexture: Nullable<Texture>;
  121. /**
  122. * The layer mask we are rendering the particles through.
  123. */
  124. public layerMask: number = 0x0FFFFFFF;
  125. /**
  126. * This can help using your own shader to render the particle system.
  127. * The according effect will be created
  128. */
  129. public customShader: any = null;
  130. /**
  131. * By default particle system starts as soon as they are created. This prevents the
  132. * automatic start to happen and let you decide when to start emitting particles.
  133. */
  134. public preventAutoStart: boolean = false;
  135. /**
  136. * This function can be defined to provide custom update for active particles.
  137. * This function will be called instead of regular update (age, position, color, etc.).
  138. * Do not forget that this function will be called on every frame so try to keep it simple and fast :)
  139. */
  140. public updateFunction: (particles: Particle[]) => void;
  141. /**
  142. * Callback triggered when the particle animation is ending.
  143. */
  144. public onAnimationEnd: Nullable<() => void> = null;
  145. /**
  146. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  147. */
  148. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  149. /**
  150. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  151. * to override the particles.
  152. */
  153. public forceDepthWrite = false;
  154. /**
  155. * You can use gravity if you want to give an orientation to your particles.
  156. */
  157. public gravity = Vector3.Zero();
  158. private _colorGradients: Nullable<Array<ColorGradient>> = null;
  159. private _sizeGradients: Nullable<Array<FactorGradient>> = null;
  160. private _lifeTimeGradients: Nullable<Array<FactorGradient>> = null;
  161. /**
  162. * Gets the current list of color gradients.
  163. * You must use addColorGradient and removeColorGradient to udpate this list
  164. * @returns the list of color gradients
  165. */
  166. public getColorGradients(): Nullable<Array<ColorGradient>> {
  167. return this._colorGradients;
  168. }
  169. /**
  170. * Gets the current list of size gradients.
  171. * You must use addSizeGradient and removeSizeGradient to udpate this list
  172. * @returns the list of size gradients
  173. */
  174. public getSizeGradients(): Nullable<Array<FactorGradient>> {
  175. return this._sizeGradients;
  176. }
  177. /**
  178. * Gets the current list of life time gradients.
  179. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  180. * @returns the list of life time gradients
  181. */
  182. public getLifeTimeGradients(): Nullable<Array<FactorGradient>> {
  183. return this._lifeTimeGradients;
  184. }
  185. /**
  186. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  187. * This only works when particleEmitterTyps is a BoxParticleEmitter
  188. */
  189. public get direction1(): Vector3 {
  190. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  191. return (<BoxParticleEmitter>this.particleEmitterType).direction1;
  192. }
  193. return Vector3.Zero();
  194. }
  195. public set direction1(value: Vector3) {
  196. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  197. (<BoxParticleEmitter>this.particleEmitterType).direction1 = value;
  198. }
  199. }
  200. /**
  201. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  202. * This only works when particleEmitterTyps is a BoxParticleEmitter
  203. */
  204. public get direction2(): Vector3 {
  205. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  206. return (<BoxParticleEmitter>this.particleEmitterType).direction2;
  207. }
  208. return Vector3.Zero();
  209. }
  210. public set direction2(value: Vector3) {
  211. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  212. (<BoxParticleEmitter>this.particleEmitterType).direction2 = value;
  213. }
  214. }
  215. /**
  216. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  217. * This only works when particleEmitterTyps is a BoxParticleEmitter
  218. */
  219. public get minEmitBox(): Vector3 {
  220. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  221. return (<BoxParticleEmitter>this.particleEmitterType).minEmitBox;
  222. }
  223. return Vector3.Zero();
  224. }
  225. public set minEmitBox(value: Vector3) {
  226. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  227. (<BoxParticleEmitter>this.particleEmitterType).minEmitBox = value;
  228. }
  229. }
  230. /**
  231. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  232. * This only works when particleEmitterTyps is a BoxParticleEmitter
  233. */
  234. public get maxEmitBox(): Vector3 {
  235. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  236. return (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox;
  237. }
  238. return Vector3.Zero();
  239. }
  240. public set maxEmitBox(value: Vector3) {
  241. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  242. (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox = value;
  243. }
  244. }
  245. /**
  246. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  247. */
  248. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  249. /**
  250. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  251. */
  252. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  253. /**
  254. * Color the particle will have at the end of its lifetime
  255. */
  256. public colorDead = new Color4(0, 0, 0, 1.0);
  257. /**
  258. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  259. */
  260. public textureMask = new Color4(1.0, 1.0, 1.0, 1.0);
  261. /**
  262. * The particle emitter type defines the emitter used by the particle system.
  263. * It can be for example box, sphere, or cone...
  264. */
  265. public particleEmitterType: IParticleEmitterType;
  266. /**
  267. * This function can be defined to specify initial direction for every new particle.
  268. * It by default use the emitterType defined function
  269. */
  270. public startDirectionFunction: (worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void;
  271. /**
  272. * This function can be defined to specify initial position for every new particle.
  273. * It by default use the emitterType defined function
  274. */
  275. public startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void;
  276. /**
  277. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  278. */
  279. public spriteCellChangeSpeed = 1;
  280. /**
  281. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  282. */
  283. public startSpriteCellID = 0;
  284. /**
  285. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  286. */
  287. public endSpriteCellID = 0;
  288. /**
  289. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  290. */
  291. public spriteCellWidth = 0;
  292. /**
  293. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  294. */
  295. public spriteCellHeight = 0;
  296. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  297. public preWarmCycles = 0;
  298. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  299. public preWarmStepOffset = 1;
  300. /**
  301. * An event triggered when the system is disposed
  302. */
  303. public onDisposeObservable = new Observable<ParticleSystem>();
  304. private _onDisposeObserver: Nullable<Observer<ParticleSystem>>;
  305. /**
  306. * Sets a callback that will be triggered when the system is disposed
  307. */
  308. public set onDispose(callback: () => void) {
  309. if (this._onDisposeObserver) {
  310. this.onDisposeObservable.remove(this._onDisposeObserver);
  311. }
  312. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  313. }
  314. /**
  315. * Gets whether an animation sprite sheet is enabled or not on the particle system
  316. */
  317. public get isAnimationSheetEnabled(): boolean {
  318. return this._isAnimationSheetEnabled;
  319. }
  320. /**
  321. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  322. */
  323. public get isBillboardBased(): boolean {
  324. return this._isBillboardBased;
  325. }
  326. public set isBillboardBased(value: boolean) {
  327. if (this._isBillboardBased === value) {
  328. return;
  329. }
  330. this._isBillboardBased = value;
  331. this._resetEffect();
  332. }
  333. private _particles = new Array<Particle>();
  334. private _epsilon: number;
  335. private _capacity: number;
  336. private _scene: Scene;
  337. private _stockParticles = new Array<Particle>();
  338. private _newPartsExcess = 0;
  339. private _vertexData: Float32Array;
  340. private _vertexBuffer: Nullable<Buffer>;
  341. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  342. private _spriteBuffer: Nullable<Buffer>;
  343. private _indexBuffer: Nullable<WebGLBuffer>;
  344. private _effect: Effect;
  345. private _customEffect: Nullable<Effect>;
  346. private _cachedDefines: string;
  347. private _scaledColorStep = new Color4(0, 0, 0, 0);
  348. private _colorDiff = new Color4(0, 0, 0, 0);
  349. private _scaledDirection = Vector3.Zero();
  350. private _scaledGravity = Vector3.Zero();
  351. private _currentRenderId = -1;
  352. private _alive: boolean;
  353. private _useInstancing = false;
  354. private _started = false;
  355. private _stopped = false;
  356. private _actualFrame = 0;
  357. private _scaledUpdateSpeed: number;
  358. private _vertexBufferSize: number;
  359. private _isAnimationSheetEnabled: boolean;
  360. private _isBillboardBased = true;
  361. // end of sheet animation
  362. // Sub-emitters
  363. /**
  364. * this is the Sub-emitters templates that will be used to generate particle system when the particle dies, this property is used by the root particle system only.
  365. */
  366. public subEmitters: ParticleSystem[];
  367. /**
  368. * The current active Sub-systems, this property is used by the root particle system only.
  369. */
  370. public activeSubSystems: Array<ParticleSystem>;
  371. private _rootParticleSystem: ParticleSystem;
  372. //end of Sub-emitter
  373. /**
  374. * Gets the current list of active particles
  375. */
  376. public get particles(): Particle[] {
  377. return this._particles;
  378. }
  379. /**
  380. * Returns the string "ParticleSystem"
  381. * @returns a string containing the class name
  382. */
  383. public getClassName(): string {
  384. return "ParticleSystem";
  385. }
  386. /**
  387. * Instantiates a particle system.
  388. * 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.
  389. * @param name The name of the particle system
  390. * @param capacity The max number of particles alive at the same time
  391. * @param scene The scene the particle system belongs to
  392. * @param customEffect a custom effect used to change the way particles are rendered by default
  393. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  394. * @param epsilon Offset used to render the particles
  395. */
  396. constructor(name: string, capacity: number, scene: Scene, customEffect: Nullable<Effect> = null, isAnimationSheetEnabled: boolean = false, epsilon: number = 0.01) {
  397. this.id = name;
  398. this.name = name;
  399. this._capacity = capacity;
  400. this._epsilon = epsilon;
  401. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  402. this._scene = scene || Engine.LastCreatedScene;
  403. this._customEffect = customEffect;
  404. scene.particleSystems.push(this);
  405. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  406. this._createIndexBuffer();
  407. this._createVertexBuffers();
  408. // Default emitter type
  409. this.particleEmitterType = new BoxParticleEmitter();
  410. this.updateFunction = (particles: Particle[]): void => {
  411. for (var index = 0; index < particles.length; index++) {
  412. var particle = particles[index];
  413. particle.age += this._scaledUpdateSpeed;
  414. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  415. this._emitFromParticle(particle);
  416. this.recycleParticle(particle);
  417. index--;
  418. continue;
  419. }
  420. else {
  421. let ratio = particle.age / particle.lifeTime;
  422. // Color
  423. if (this._colorGradients && this._colorGradients.length > 0) {
  424. Tools.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  425. if (currentGradient !== particle._currentColorGradient) {
  426. particle._currentColor1.copyFrom(particle._currentColor2);
  427. (<ColorGradient>nextGradient).getColorToRef(particle._currentColor2);
  428. particle._currentColorGradient = (<ColorGradient>currentGradient);
  429. }
  430. Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  431. });
  432. }
  433. else {
  434. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  435. particle.color.addInPlace(this._scaledColorStep);
  436. if (particle.color.a < 0) {
  437. particle.color.a = 0;
  438. }
  439. }
  440. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  441. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  442. particle.position.addInPlace(this._scaledDirection);
  443. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  444. particle.direction.addInPlace(this._scaledGravity);
  445. // Gradient
  446. if (this._sizeGradients && this._sizeGradients.length > 0) {
  447. Tools.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {
  448. if (currentGradient !== particle._currentSizeGradient) {
  449. particle._currentSize1 = particle._currentSize2;
  450. particle._currentSize2 = (<FactorGradient>nextGradient).getFactor();
  451. particle._currentSizeGradient = (<FactorGradient>currentGradient);
  452. }
  453. particle.size = Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  454. });
  455. }
  456. if (this._isAnimationSheetEnabled) {
  457. particle.updateCellIndex();
  458. }
  459. }
  460. }
  461. }
  462. }
  463. private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number, factor2?: number) {
  464. let newGradient = new FactorGradient();
  465. newGradient.gradient = gradient;
  466. newGradient.factor1 = factor;
  467. newGradient.factor2 = factor2;
  468. factorGradients.push(newGradient);
  469. factorGradients.sort((a, b) => {
  470. if (a.gradient < b.gradient) {
  471. return -1;
  472. } else if (a.gradient > b.gradient) {
  473. return 1;
  474. }
  475. return 0;
  476. });
  477. }
  478. private _removeFactorGradient(factorGradients: Nullable<FactorGradient[]>, gradient: number) {
  479. if (!factorGradients) {
  480. return;
  481. }
  482. let index = 0;
  483. for (var factorGradient of factorGradients) {
  484. if (factorGradient.gradient === gradient) {
  485. factorGradients.splice(index, 1);
  486. break;
  487. }
  488. index++;
  489. }
  490. }
  491. /**
  492. * Adds a new life time gradient
  493. * @param gradient defines the gradient to use (between 0 and 1)
  494. * @param factor defines the life time factor to affect to the specified gradient
  495. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  496. */
  497. public addLifeTimeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem {
  498. if (!this._lifeTimeGradients) {
  499. this._lifeTimeGradients = [];
  500. }
  501. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  502. return this;
  503. }
  504. /**
  505. * Remove a specific life time gradient
  506. * @param gradient defines the gradient to remove
  507. */
  508. public removeLifeTimeGradient(gradient: number): ParticleSystem {
  509. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  510. return this;
  511. }
  512. /**
  513. * Adds a new size gradient
  514. * @param gradient defines the gradient to use (between 0 and 1)
  515. * @param factor defines the size factor to affect to the specified gradient
  516. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  517. */
  518. public addSizeGradient(gradient: number, factor: number, factor2?: number): ParticleSystem {
  519. if (!this._sizeGradients) {
  520. this._sizeGradients = [];
  521. }
  522. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  523. return this;
  524. }
  525. /**
  526. * Remove a specific size gradient
  527. * @param gradient defines the gradient to remove
  528. */
  529. public removeSizeGradient(gradient: number): ParticleSystem {
  530. this._removeFactorGradient(this._sizeGradients, gradient);
  531. return this;
  532. }
  533. /**
  534. * Adds a new color gradient
  535. * @param gradient defines the gradient to use (between 0 and 1)
  536. * @param color defines the color to affect to the specified gradient
  537. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  538. */
  539. public addColorGradient(gradient: number, color: Color4, color2?: Color4): ParticleSystem {
  540. if (!this._colorGradients) {
  541. this._colorGradients = [];
  542. }
  543. let colorGradient = new ColorGradient();
  544. colorGradient.gradient = gradient;
  545. colorGradient.color1 = color;
  546. colorGradient.color2 = color2;
  547. this._colorGradients.push(colorGradient);
  548. this._colorGradients.sort((a, b) => {
  549. if (a.gradient < b.gradient) {
  550. return -1;
  551. } else if (a.gradient > b.gradient) {
  552. return 1;
  553. }
  554. return 0;
  555. });
  556. return this;
  557. }
  558. /**
  559. * Remove a specific color gradient
  560. * @param gradient defines the gradient to remove
  561. */
  562. public removeColorGradient(gradient: number): ParticleSystem {
  563. if (!this._colorGradients) {
  564. return this;
  565. }
  566. let index = 0;
  567. for (var colorGradient of this._colorGradients) {
  568. if (colorGradient.gradient === gradient) {
  569. this._colorGradients.splice(index, 1);
  570. break;
  571. }
  572. index++;
  573. }
  574. return this;
  575. }
  576. private _resetEffect() {
  577. if (this._vertexBuffer) {
  578. this._vertexBuffer.dispose();
  579. this._vertexBuffer = null;
  580. }
  581. if (this._spriteBuffer) {
  582. this._spriteBuffer.dispose();
  583. this._spriteBuffer = null;
  584. }
  585. this._createVertexBuffers();
  586. }
  587. private _createVertexBuffers() {
  588. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  589. if (this._isAnimationSheetEnabled) {
  590. this._vertexBufferSize += 1;
  591. }
  592. if (!this._isBillboardBased) {
  593. this._vertexBufferSize += 3;
  594. }
  595. let engine = this._scene.getEngine();
  596. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  597. this._vertexBuffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  598. let dataOffset = 0;
  599. var positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  600. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  601. dataOffset += 3;
  602. var colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  603. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  604. dataOffset += 4;
  605. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  606. this._vertexBuffers["angle"] = options;
  607. dataOffset += 1;
  608. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  609. this._vertexBuffers["size"] = size;
  610. dataOffset += 2;
  611. if (this._isAnimationSheetEnabled) {
  612. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  613. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  614. dataOffset += 1;
  615. }
  616. if (!this._isBillboardBased) {
  617. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  618. this._vertexBuffers["direction"] = directionBuffer;
  619. dataOffset += 3;
  620. }
  621. var offsets: VertexBuffer;
  622. if (this._useInstancing) {
  623. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  624. this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
  625. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  626. } else {
  627. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  628. dataOffset += 2;
  629. }
  630. this._vertexBuffers["offset"] = offsets;
  631. }
  632. private _createIndexBuffer() {
  633. if (this._useInstancing) {
  634. return;
  635. }
  636. var indices = [];
  637. var index = 0;
  638. for (var count = 0; count < this._capacity; count++) {
  639. indices.push(index);
  640. indices.push(index + 1);
  641. indices.push(index + 2);
  642. indices.push(index);
  643. indices.push(index + 2);
  644. indices.push(index + 3);
  645. index += 4;
  646. }
  647. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  648. }
  649. /**
  650. * Gets the maximum number of particles active at the same time.
  651. * @returns The max number of active particles.
  652. */
  653. public getCapacity(): number {
  654. return this._capacity;
  655. }
  656. /**
  657. * Gets Wether there are still active particles in the system.
  658. * @returns True if it is alive, otherwise false.
  659. */
  660. public isAlive(): boolean {
  661. return this._alive;
  662. }
  663. /**
  664. * Gets Wether the system has been started.
  665. * @returns True if it has been started, otherwise false.
  666. */
  667. public isStarted(): boolean {
  668. return this._started;
  669. }
  670. /**
  671. * Starts the particle system and begins to emit.
  672. */
  673. public start(): void {
  674. this._started = true;
  675. this._stopped = false;
  676. this._actualFrame = 0;
  677. if (this.subEmitters && this.subEmitters.length != 0) {
  678. this.activeSubSystems = new Array<ParticleSystem>();
  679. }
  680. if (this.preWarmCycles) {
  681. for (var index = 0; index < this.preWarmCycles; index++) {
  682. this.animate(true);
  683. }
  684. }
  685. }
  686. /**
  687. * Stops the particle system.
  688. * @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.
  689. */
  690. public stop(stopSubEmitters = true): void {
  691. this._stopped = true;
  692. if (stopSubEmitters) {
  693. this._stopSubEmitters();
  694. }
  695. }
  696. // animation sheet
  697. /**
  698. * Remove all active particles
  699. */
  700. public reset(): void {
  701. this._stockParticles = [];
  702. this._particles = [];
  703. }
  704. /**
  705. * @hidden (for internal use only)
  706. */
  707. public _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void {
  708. var offset = index * this._vertexBufferSize;
  709. this._vertexData[offset++] = particle.position.x;
  710. this._vertexData[offset++] = particle.position.y;
  711. this._vertexData[offset++] = particle.position.z;
  712. this._vertexData[offset++] = particle.color.r;
  713. this._vertexData[offset++] = particle.color.g;
  714. this._vertexData[offset++] = particle.color.b;
  715. this._vertexData[offset++] = particle.color.a;
  716. this._vertexData[offset++] = particle.angle;
  717. this._vertexData[offset++] = particle.scale.x * particle.size;
  718. this._vertexData[offset++] = particle.scale.y * particle.size;
  719. if (this._isAnimationSheetEnabled) {
  720. this._vertexData[offset++] = particle.cellIndex;
  721. }
  722. if (!this._isBillboardBased) {
  723. if (particle._initialDirection) {
  724. this._vertexData[offset++] = particle._initialDirection.x;
  725. this._vertexData[offset++] = particle._initialDirection.y;
  726. this._vertexData[offset++] = particle._initialDirection.z;
  727. } else {
  728. this._vertexData[offset++] = particle.direction.x;
  729. this._vertexData[offset++] = particle.direction.y;
  730. this._vertexData[offset++] = particle.direction.z;
  731. }
  732. }
  733. if (!this._useInstancing) {
  734. if (this._isAnimationSheetEnabled) {
  735. if (offsetX === 0)
  736. offsetX = this._epsilon;
  737. else if (offsetX === 1)
  738. offsetX = 1 - this._epsilon;
  739. if (offsetY === 0)
  740. offsetY = this._epsilon;
  741. else if (offsetY === 1)
  742. offsetY = 1 - this._epsilon;
  743. }
  744. this._vertexData[offset++] = offsetX;
  745. this._vertexData[offset++] = offsetY;
  746. }
  747. }
  748. // start of sub system methods
  749. /**
  750. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  751. * Its lifetime will start back at 0.
  752. */
  753. public recycleParticle: (particle: Particle) => void = (particle) => {
  754. var lastParticle = <Particle>this._particles.pop();
  755. if (lastParticle !== particle) {
  756. lastParticle.copyTo(particle);
  757. }
  758. this._stockParticles.push(lastParticle);
  759. };
  760. private _stopSubEmitters(): void {
  761. if (!this.activeSubSystems) {
  762. return;
  763. }
  764. this.activeSubSystems.forEach(subSystem => {
  765. subSystem.stop(true);
  766. });
  767. this.activeSubSystems = new Array<ParticleSystem>();
  768. }
  769. private _createParticle: () => Particle = () => {
  770. var particle: Particle;
  771. if (this._stockParticles.length !== 0) {
  772. particle = <Particle>this._stockParticles.pop();
  773. particle.age = 0;
  774. particle._currentColorGradient = null;
  775. particle.cellIndex = this.startSpriteCellID;
  776. } else {
  777. particle = new Particle(this);
  778. }
  779. return particle;
  780. }
  781. private _removeFromRoot(): void {
  782. if (!this._rootParticleSystem){
  783. return;
  784. }
  785. let index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  786. if (index !== -1) {
  787. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  788. }
  789. }
  790. private _emitFromParticle: (particle: Particle) => void = (particle) => {
  791. if (!this.subEmitters || this.subEmitters.length === 0) {
  792. return;
  793. }
  794. var templateIndex = Math.floor(Math.random() * this.subEmitters.length);
  795. var subSystem = this.subEmitters[templateIndex].clone(this.name + "_sub", particle.position.clone());
  796. subSystem._rootParticleSystem = this;
  797. this.activeSubSystems.push(subSystem);
  798. subSystem.start();
  799. }
  800. // End of sub system methods
  801. private _update(newParticles: number): void {
  802. // Update current
  803. this._alive = this._particles.length > 0;
  804. this.updateFunction(this._particles);
  805. // Add new ones
  806. var worldMatrix;
  807. if ((<AbstractMesh>this.emitter).position) {
  808. var emitterMesh = (<AbstractMesh>this.emitter);
  809. worldMatrix = emitterMesh.getWorldMatrix();
  810. } else {
  811. var emitterPosition = (<Vector3>this.emitter);
  812. worldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  813. }
  814. var particle: Particle;
  815. for (var index = 0; index < newParticles; index++) {
  816. if (this._particles.length === this._capacity) {
  817. break;
  818. }
  819. particle = this._createParticle();
  820. this._particles.push(particle);
  821. // Emitter
  822. let emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  823. if (this.startPositionFunction) {
  824. this.startPositionFunction(worldMatrix, particle.position, particle);
  825. }
  826. else {
  827. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  828. }
  829. if (this.startDirectionFunction) {
  830. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  831. }
  832. else {
  833. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  834. }
  835. if (emitPower === 0) {
  836. if (!particle._initialDirection) {
  837. particle._initialDirection = particle.direction.clone();
  838. } else {
  839. particle._initialDirection.copyFrom(particle.direction);
  840. }
  841. } else {
  842. particle._initialDirection = null;
  843. }
  844. particle.direction.scaleInPlace(emitPower);
  845. // Life time
  846. if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {
  847. let ratio = Scalar.Clamp(this._actualFrame / this.targetStopDuration);
  848. Tools.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient, scale) => {
  849. let factorGradient1 = (<FactorGradient>currentGradient);
  850. let factorGradient2 = (<FactorGradient>nextGradient);
  851. let lifeTime1 = factorGradient1.getFactor();
  852. let lifeTime2 = factorGradient2.getFactor();
  853. let gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  854. particle.lifeTime = Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  855. });
  856. } else {
  857. particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  858. }
  859. // Size
  860. if (!this._sizeGradients || this._sizeGradients.length === 0) {
  861. particle.size = Scalar.RandomRange(this.minSize, this.maxSize);
  862. } else {
  863. particle._currentSizeGradient = this._sizeGradients[0];
  864. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  865. particle.size = particle._currentSize1;
  866. if (this._sizeGradients.length > 1) {
  867. particle._currentSize2 = this._sizeGradients[1].getFactor();
  868. } else {
  869. particle._currentSize2 = particle._currentSize1;
  870. }
  871. }
  872. // Size and scale
  873. particle.scale.copyFromFloats(Scalar.RandomRange(this.minScaleX, this.maxScaleX), Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  874. // Angle
  875. particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  876. particle.angle = Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  877. // Color
  878. if (!this._colorGradients || this._colorGradients.length === 0) {
  879. var step = Scalar.RandomRange(0, 1.0);
  880. Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  881. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  882. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  883. } else {
  884. particle._currentColorGradient = this._colorGradients[0];
  885. particle._currentColorGradient.getColorToRef(particle.color);
  886. particle._currentColor1.copyFrom(particle.color);
  887. if (this._colorGradients.length > 1) {
  888. this._colorGradients[1].getColorToRef(particle._currentColor2);
  889. } else {
  890. particle._currentColor2.copyFrom(particle.color);
  891. }
  892. }
  893. // Sheet
  894. if (this._isAnimationSheetEnabled) {
  895. particle._initialStartSpriteCellID = this.startSpriteCellID;
  896. particle._initialEndSpriteCellID = this.endSpriteCellID;
  897. }
  898. }
  899. }
  900. /** @hidden */
  901. public static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false): string[] {
  902. var attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
  903. if (isAnimationSheetEnabled) {
  904. attributeNamesOrOptions.push("cellIndex");
  905. }
  906. if (!isBillboardBased) {
  907. attributeNamesOrOptions.push("direction");
  908. }
  909. return attributeNamesOrOptions;
  910. }
  911. public static _GetEffectCreationOptions(isAnimationSheetEnabled = false): string[] {
  912. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  913. if (isAnimationSheetEnabled) {
  914. effectCreationOption.push("particlesInfos")
  915. }
  916. return effectCreationOption;
  917. }
  918. private _getEffect(): Effect {
  919. if (this._customEffect) {
  920. return this._customEffect;
  921. };
  922. var defines = [];
  923. if (this._scene.clipPlane) {
  924. defines.push("#define CLIPPLANE");
  925. }
  926. if (this._isAnimationSheetEnabled) {
  927. defines.push("#define ANIMATESHEET");
  928. }
  929. if (this._isBillboardBased) {
  930. defines.push("#define BILLBOARD");
  931. }
  932. // Effect
  933. var join = defines.join("\n");
  934. if (this._cachedDefines !== join) {
  935. this._cachedDefines = join;
  936. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  937. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  938. this._effect = this._scene.getEngine().createEffect(
  939. "particles",
  940. attributesNamesOrOptions,
  941. effectCreationOption,
  942. ["diffuseSampler"], join);
  943. }
  944. return this._effect;
  945. }
  946. /**
  947. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  948. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  949. */
  950. public animate(preWarmOnly = false): void {
  951. if (!this._started)
  952. return;
  953. if (!preWarmOnly) {
  954. var effect = this._getEffect();
  955. // Check
  956. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  957. return;
  958. if (this._currentRenderId === this._scene.getRenderId()) {
  959. return;
  960. }
  961. this._currentRenderId = this._scene.getRenderId();
  962. }
  963. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  964. // determine the number of particles we need to create
  965. var newParticles;
  966. if (this.manualEmitCount > -1) {
  967. newParticles = this.manualEmitCount;
  968. this._newPartsExcess = 0;
  969. this.manualEmitCount = 0;
  970. } else {
  971. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  972. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  973. }
  974. if (this._newPartsExcess > 1.0) {
  975. newParticles += this._newPartsExcess >> 0;
  976. this._newPartsExcess -= this._newPartsExcess >> 0;
  977. }
  978. this._alive = false;
  979. if (!this._stopped) {
  980. this._actualFrame += this._scaledUpdateSpeed;
  981. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  982. this.stop();
  983. } else {
  984. newParticles = 0;
  985. }
  986. this._update(newParticles);
  987. // Stopped?
  988. if (this._stopped) {
  989. if (!this._alive) {
  990. this._started = false;
  991. if (this.onAnimationEnd) {
  992. this.onAnimationEnd();
  993. }
  994. if (this.disposeOnStop) {
  995. this._scene._toBeDisposed.push(this);
  996. }
  997. }
  998. }
  999. if (!preWarmOnly) {
  1000. // Update VBO
  1001. var offset = 0;
  1002. for (var index = 0; index < this._particles.length; index++) {
  1003. var particle = this._particles[index];
  1004. this._appendParticleVertices(offset, particle);
  1005. offset += this._useInstancing ? 1 : 4;
  1006. }
  1007. if (this._vertexBuffer) {
  1008. this._vertexBuffer.update(this._vertexData);
  1009. }
  1010. }
  1011. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  1012. this.stop();
  1013. }
  1014. }
  1015. private _appendParticleVertices(offset: number, particle: Particle) {
  1016. this._appendParticleVertex(offset++, particle, 0, 0);
  1017. if (!this._useInstancing) {
  1018. this._appendParticleVertex(offset++, particle, 1, 0);
  1019. this._appendParticleVertex(offset++, particle, 1, 1);
  1020. this._appendParticleVertex(offset++, particle, 0, 1);
  1021. }
  1022. }
  1023. /**
  1024. * Rebuilds the particle system.
  1025. */
  1026. public rebuild(): void {
  1027. this._createIndexBuffer();
  1028. if (this._vertexBuffer) {
  1029. this._vertexBuffer._rebuild();
  1030. }
  1031. }
  1032. /**
  1033. * Is this system ready to be used/rendered
  1034. * @return true if the system is ready
  1035. */
  1036. public isReady(): boolean {
  1037. var effect = this._getEffect();
  1038. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  1039. return false;
  1040. }
  1041. return true;
  1042. }
  1043. /**
  1044. * Renders the particle system in its current state.
  1045. * @returns the current number of particles
  1046. */
  1047. public render(): number {
  1048. var effect = this._getEffect();
  1049. // Check
  1050. if (!this.isReady() || !this._particles.length) {
  1051. return 0;
  1052. }
  1053. var engine = this._scene.getEngine();
  1054. // Render
  1055. engine.enableEffect(effect);
  1056. engine.setState(false);
  1057. var viewMatrix = this._scene.getViewMatrix();
  1058. effect.setTexture("diffuseSampler", this.particleTexture);
  1059. effect.setMatrix("view", viewMatrix);
  1060. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  1061. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1062. var baseSize = this.particleTexture.getBaseSize();
  1063. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  1064. }
  1065. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  1066. if (this._scene.clipPlane) {
  1067. var clipPlane = this._scene.clipPlane;
  1068. var invView = viewMatrix.clone();
  1069. invView.invert();
  1070. effect.setMatrix("invView", invView);
  1071. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  1072. }
  1073. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  1074. // Draw order
  1075. switch(this.blendMode)
  1076. {
  1077. case ParticleSystem.BLENDMODE_ADD:
  1078. engine.setAlphaMode(Engine.ALPHA_ADD);
  1079. break;
  1080. case ParticleSystem.BLENDMODE_ONEONE:
  1081. engine.setAlphaMode(Engine.ALPHA_ONEONE);
  1082. break;
  1083. case ParticleSystem.BLENDMODE_STANDARD:
  1084. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  1085. break;
  1086. }
  1087. if (this.forceDepthWrite) {
  1088. engine.setDepthWrite(true);
  1089. }
  1090. if (this._useInstancing) {
  1091. engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  1092. engine.unbindInstanceAttributes();
  1093. } else {
  1094. engine.drawElementsType(Material.TriangleFillMode, 0, this._particles.length * 6);
  1095. }
  1096. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  1097. return this._particles.length;
  1098. }
  1099. /**
  1100. * Disposes the particle system and free the associated resources
  1101. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1102. */
  1103. public dispose(disposeTexture = true): void {
  1104. if (this._vertexBuffer) {
  1105. this._vertexBuffer.dispose();
  1106. this._vertexBuffer = null;
  1107. }
  1108. if (this._spriteBuffer) {
  1109. this._spriteBuffer.dispose();
  1110. this._spriteBuffer = null;
  1111. }
  1112. if (this._indexBuffer) {
  1113. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  1114. this._indexBuffer = null;
  1115. }
  1116. if (disposeTexture && this.particleTexture) {
  1117. this.particleTexture.dispose();
  1118. this.particleTexture = null;
  1119. }
  1120. this._removeFromRoot();
  1121. // Remove from scene
  1122. var index = this._scene.particleSystems.indexOf(this);
  1123. if (index > -1) {
  1124. this._scene.particleSystems.splice(index, 1);
  1125. }
  1126. // Callback
  1127. this.onDisposeObservable.notifyObservers(this);
  1128. this.onDisposeObservable.clear();
  1129. }
  1130. /**
  1131. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  1132. * @param radius The radius of the sphere to emit from
  1133. * @returns the emitter
  1134. */
  1135. public createSphereEmitter(radius = 1): SphereParticleEmitter {
  1136. var particleEmitter = new SphereParticleEmitter(radius);
  1137. this.particleEmitterType = particleEmitter;
  1138. return particleEmitter;
  1139. }
  1140. /**
  1141. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  1142. * @param radius The radius of the sphere to emit from
  1143. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  1144. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  1145. * @returns the emitter
  1146. */
  1147. public createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)): SphereDirectedParticleEmitter {
  1148. var particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2)
  1149. this.particleEmitterType = particleEmitter;
  1150. return particleEmitter;
  1151. }
  1152. /**
  1153. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  1154. * @param radius The radius of the cone to emit from
  1155. * @param angle The base angle of the cone
  1156. * @returns the emitter
  1157. */
  1158. public createConeEmitter(radius = 1, angle = Math.PI / 4): ConeParticleEmitter {
  1159. var particleEmitter = new ConeParticleEmitter(radius, angle);
  1160. this.particleEmitterType = particleEmitter;
  1161. return particleEmitter;
  1162. }
  1163. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  1164. /**
  1165. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  1166. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  1167. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  1168. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  1169. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  1170. * @returns the emitter
  1171. */
  1172. public createBoxEmitter(direction1: Vector3, direction2: Vector3, minEmitBox: Vector3, maxEmitBox: Vector3): BoxParticleEmitter {
  1173. var particleEmitter = new BoxParticleEmitter();
  1174. this.particleEmitterType = particleEmitter;
  1175. this.direction1 = direction1;
  1176. this.direction2 = direction2;
  1177. this.minEmitBox = minEmitBox;
  1178. this.maxEmitBox = maxEmitBox;
  1179. return particleEmitter;
  1180. }
  1181. // Clone
  1182. /**
  1183. * Clones the particle system.
  1184. * @param name The name of the cloned object
  1185. * @param newEmitter The new emitter to use
  1186. * @returns the cloned particle system
  1187. */
  1188. public clone(name: string, newEmitter: any): ParticleSystem {
  1189. var custom: Nullable<Effect> = null;
  1190. var program: any = null;
  1191. if (this.customShader != null) {
  1192. program = this.customShader;
  1193. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1194. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1195. } else if (this._customEffect) {
  1196. custom = this._customEffect;
  1197. }
  1198. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  1199. result.customShader = program;
  1200. Tools.DeepCopy(this, result, ["particles", "customShader"]);
  1201. if (newEmitter === undefined) {
  1202. newEmitter = this.emitter;
  1203. }
  1204. result.emitter = newEmitter;
  1205. if (this.particleTexture) {
  1206. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1207. }
  1208. if (!this.preventAutoStart) {
  1209. result.start();
  1210. }
  1211. return result;
  1212. }
  1213. /**
  1214. * Serializes the particle system to a JSON object.
  1215. * @returns the JSON object
  1216. */
  1217. public serialize(): any {
  1218. var serializationObject: any = {};
  1219. ParticleSystem._Serialize(serializationObject, this);
  1220. serializationObject.textureMask = this.textureMask.asArray();
  1221. serializationObject.customShader = this.customShader;
  1222. serializationObject.preventAutoStart = this.preventAutoStart;
  1223. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  1224. return serializationObject;
  1225. }
  1226. /** @hidden */
  1227. public static _Serialize(serializationObject: any, particleSystem: IParticleSystem) {
  1228. serializationObject.name = particleSystem.name;
  1229. serializationObject.id = particleSystem.id;
  1230. serializationObject.capacity = particleSystem.getCapacity();
  1231. // Emitter
  1232. if ((<AbstractMesh>particleSystem.emitter).position) {
  1233. var emitterMesh = (<AbstractMesh>particleSystem.emitter);
  1234. serializationObject.emitterId = emitterMesh.id;
  1235. } else {
  1236. var emitterPosition = (<Vector3>particleSystem.emitter);
  1237. serializationObject.emitter = emitterPosition.asArray();
  1238. }
  1239. // Emitter
  1240. if (particleSystem.particleEmitterType) {
  1241. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  1242. }
  1243. if (particleSystem.particleTexture) {
  1244. serializationObject.textureName = particleSystem.particleTexture.name;
  1245. }
  1246. // Animations
  1247. Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  1248. // Particle system
  1249. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  1250. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  1251. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  1252. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  1253. serializationObject.minSize = particleSystem.minSize;
  1254. serializationObject.maxSize = particleSystem.maxSize;
  1255. serializationObject.minScaleX = particleSystem.minScaleX;
  1256. serializationObject.maxScaleX = particleSystem.maxScaleX;
  1257. serializationObject.minScaleY = particleSystem.minScaleY;
  1258. serializationObject.maxScaleY = particleSystem.maxScaleY;
  1259. serializationObject.minEmitPower = particleSystem.minEmitPower;
  1260. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  1261. serializationObject.minLifeTime = particleSystem.minLifeTime;
  1262. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  1263. serializationObject.emitRate = particleSystem.emitRate;
  1264. serializationObject.gravity = particleSystem.gravity.asArray();
  1265. serializationObject.color1 = particleSystem.color1.asArray();
  1266. serializationObject.color2 = particleSystem.color2.asArray();
  1267. serializationObject.colorDead = particleSystem.colorDead.asArray();
  1268. serializationObject.updateSpeed = particleSystem.updateSpeed;
  1269. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  1270. serializationObject.blendMode = particleSystem.blendMode;
  1271. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  1272. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  1273. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  1274. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  1275. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  1276. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  1277. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  1278. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  1279. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  1280. let colorGradients = particleSystem.getColorGradients();
  1281. if (colorGradients) {
  1282. serializationObject.colorGradients = [];
  1283. for (var colorGradient of colorGradients) {
  1284. var serializedGradient: any = {
  1285. gradient: colorGradient.gradient,
  1286. color1: colorGradient.color1.asArray()
  1287. };
  1288. if (colorGradient.color2) {
  1289. serializedGradient.color2 = colorGradient.color2.asArray();
  1290. }
  1291. serializationObject.colorGradients.push(serializedGradient);
  1292. }
  1293. }
  1294. let sizeGradients = particleSystem.getSizeGradients();
  1295. if (sizeGradients) {
  1296. serializationObject.sizeGradients = [];
  1297. for (var sizeGradient of sizeGradients) {
  1298. var serializedGradient: any = {
  1299. gradient: sizeGradient.gradient,
  1300. factor1: sizeGradient.factor1
  1301. };
  1302. if (sizeGradient.factor2 !== undefined) {
  1303. serializedGradient.factor2 = sizeGradient.factor2;
  1304. }
  1305. serializationObject.sizeGradients.push(serializedGradient);
  1306. }
  1307. }
  1308. }
  1309. /** @hidden */
  1310. public static _Parse(parsedParticleSystem: any, particleSystem: IParticleSystem, scene: Scene, rootUrl: string) {
  1311. // Texture
  1312. if (parsedParticleSystem.textureName) {
  1313. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  1314. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  1315. }
  1316. // Emitter
  1317. if (parsedParticleSystem.emitterId === undefined) {
  1318. particleSystem.emitter = Vector3.Zero();
  1319. }
  1320. else if (parsedParticleSystem.emitterId) {
  1321. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  1322. } else {
  1323. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  1324. }
  1325. // Misc.
  1326. if (parsedParticleSystem.renderingGroupId !== undefined) {
  1327. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  1328. }
  1329. if (parsedParticleSystem.isBillboardBased !== undefined) {
  1330. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  1331. }
  1332. // Animations
  1333. if (parsedParticleSystem.animations) {
  1334. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  1335. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  1336. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  1337. }
  1338. }
  1339. if (parsedParticleSystem.autoAnimate) {
  1340. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  1341. }
  1342. // Particle system
  1343. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  1344. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  1345. particleSystem.minSize = parsedParticleSystem.minSize;
  1346. particleSystem.maxSize = parsedParticleSystem.maxSize;
  1347. if (parsedParticleSystem.minScaleX) {
  1348. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  1349. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  1350. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  1351. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  1352. }
  1353. if (parsedParticleSystem.preWarmCycles !== undefined) {
  1354. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  1355. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  1356. }
  1357. if (parsedParticleSystem.minInitialRotation !== undefined) {
  1358. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  1359. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  1360. }
  1361. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  1362. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  1363. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  1364. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  1365. particleSystem.emitRate = parsedParticleSystem.emitRate;
  1366. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  1367. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  1368. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  1369. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  1370. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  1371. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  1372. particleSystem.blendMode = parsedParticleSystem.blendMode;
  1373. if (parsedParticleSystem.colorGradients) {
  1374. for (var colorGradient of parsedParticleSystem.colorGradients) {
  1375. particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined);
  1376. }
  1377. }
  1378. if (parsedParticleSystem.sizeGradients) {
  1379. for (var sizeGradient of parsedParticleSystem.sizeGradients) {
  1380. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  1381. }
  1382. }
  1383. // Emitter
  1384. let emitterType: IParticleEmitterType;
  1385. if (parsedParticleSystem.particleEmitterType) {
  1386. switch (parsedParticleSystem.particleEmitterType.type) {
  1387. case "SphereParticleEmitter":
  1388. emitterType = new SphereParticleEmitter();
  1389. break;
  1390. case "SphereDirectedParticleEmitter":
  1391. emitterType = new SphereDirectedParticleEmitter();
  1392. break;
  1393. case "ConeEmitter":
  1394. case "ConeParticleEmitter":
  1395. emitterType = new ConeParticleEmitter();
  1396. break;
  1397. case "BoxEmitter":
  1398. case "BoxParticleEmitter":
  1399. default:
  1400. emitterType = new BoxParticleEmitter();
  1401. break;
  1402. }
  1403. emitterType.parse(parsedParticleSystem.particleEmitterType);
  1404. } else {
  1405. emitterType = new BoxParticleEmitter();
  1406. emitterType.parse(parsedParticleSystem);
  1407. }
  1408. particleSystem.particleEmitterType = emitterType;
  1409. // Animation sheet
  1410. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  1411. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  1412. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  1413. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  1414. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  1415. }
  1416. /**
  1417. * Parses a JSON object to create a particle system.
  1418. * @param parsedParticleSystem The JSON object to parse
  1419. * @param scene The scene to create the particle system in
  1420. * @param rootUrl The root url to use to load external dependencies like texture
  1421. * @returns the Parsed particle system
  1422. */
  1423. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem {
  1424. var name = parsedParticleSystem.name;
  1425. var custom: Nullable<Effect> = null;
  1426. var program: any = null;
  1427. if (parsedParticleSystem.customShader) {
  1428. program = parsedParticleSystem.customShader;
  1429. var defines: string = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  1430. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  1431. }
  1432. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  1433. particleSystem.customShader = program;
  1434. if (parsedParticleSystem.id) {
  1435. particleSystem.id = parsedParticleSystem.id;
  1436. }
  1437. // Auto start
  1438. if (parsedParticleSystem.preventAutoStart) {
  1439. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  1440. }
  1441. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  1442. particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
  1443. if (!particleSystem.preventAutoStart) {
  1444. particleSystem.start();
  1445. }
  1446. return particleSystem;
  1447. }
  1448. }
  1449. }