babylon.particleSystem.ts 66 KB

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